diff --git a/app/controlplane/pkg/data/ent/client.go b/app/controlplane/pkg/data/ent/client.go index a7d16ee51..002b8359a 100644 --- a/app/controlplane/pkg/data/ent/client.go +++ b/app/controlplane/pkg/data/ent/client.go @@ -31,6 +31,7 @@ import ( "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/project" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/projectversion" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/referrer" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/referrerreference" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/robotaccount" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/user" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflow" @@ -74,6 +75,8 @@ type Client struct { ProjectVersion *ProjectVersionClient // Referrer is the client for interacting with the Referrer builders. Referrer *ReferrerClient + // ReferrerReference is the client for interacting with the ReferrerReference builders. + ReferrerReference *ReferrerReferenceClient // RobotAccount is the client for interacting with the RobotAccount builders. RobotAccount *RobotAccountClient // User is the client for interacting with the User builders. @@ -112,6 +115,7 @@ func (c *Client) init() { c.Project = NewProjectClient(c.config) c.ProjectVersion = NewProjectVersionClient(c.config) c.Referrer = NewReferrerClient(c.config) + c.ReferrerReference = NewReferrerReferenceClient(c.config) c.RobotAccount = NewRobotAccountClient(c.config) c.User = NewUserClient(c.config) c.Workflow = NewWorkflowClient(c.config) @@ -225,6 +229,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { Project: NewProjectClient(cfg), ProjectVersion: NewProjectVersionClient(cfg), Referrer: NewReferrerClient(cfg), + ReferrerReference: NewReferrerReferenceClient(cfg), RobotAccount: NewRobotAccountClient(cfg), User: NewUserClient(cfg), Workflow: NewWorkflowClient(cfg), @@ -265,6 +270,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) Project: NewProjectClient(cfg), ProjectVersion: NewProjectVersionClient(cfg), Referrer: NewReferrerClient(cfg), + ReferrerReference: NewReferrerReferenceClient(cfg), RobotAccount: NewRobotAccountClient(cfg), User: NewUserClient(cfg), Workflow: NewWorkflowClient(cfg), @@ -303,8 +309,8 @@ func (c *Client) Use(hooks ...Hook) { c.APIToken, c.Attestation, c.CASBackend, c.CASMapping, c.Group, c.GroupMembership, c.Integration, c.IntegrationAttachment, c.LoginHandoff, c.Membership, c.OrgInvitation, c.Organization, c.Project, c.ProjectVersion, - c.Referrer, c.RobotAccount, c.User, c.Workflow, c.WorkflowContract, - c.WorkflowContractVersion, c.WorkflowRun, + c.Referrer, c.ReferrerReference, c.RobotAccount, c.User, c.Workflow, + c.WorkflowContract, c.WorkflowContractVersion, c.WorkflowRun, } { n.Use(hooks...) } @@ -317,8 +323,8 @@ func (c *Client) Intercept(interceptors ...Interceptor) { c.APIToken, c.Attestation, c.CASBackend, c.CASMapping, c.Group, c.GroupMembership, c.Integration, c.IntegrationAttachment, c.LoginHandoff, c.Membership, c.OrgInvitation, c.Organization, c.Project, c.ProjectVersion, - c.Referrer, c.RobotAccount, c.User, c.Workflow, c.WorkflowContract, - c.WorkflowContractVersion, c.WorkflowRun, + c.Referrer, c.ReferrerReference, c.RobotAccount, c.User, c.Workflow, + c.WorkflowContract, c.WorkflowContractVersion, c.WorkflowRun, } { n.Intercept(interceptors...) } @@ -357,6 +363,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.ProjectVersion.mutate(ctx, m) case *ReferrerMutation: return c.Referrer.mutate(ctx, m) + case *ReferrerReferenceMutation: + return c.ReferrerReference.mutate(ctx, m) case *RobotAccountMutation: return c.RobotAccount.mutate(ctx, m) case *UserMutation: @@ -3000,6 +3008,38 @@ func (c *ReferrerClient) QueryWorkflows(_m *Referrer) *WorkflowQuery { return query } +// QueryReferredByEdges queries the referred_by_edges edge of a Referrer. +func (c *ReferrerClient) QueryReferredByEdges(_m *Referrer) *ReferrerReferenceQuery { + query := (&ReferrerReferenceClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(referrer.Table, referrer.FieldID, id), + sqlgraph.To(referrerreference.Table, referrerreference.ReferredByColumn), + sqlgraph.Edge(sqlgraph.O2M, true, referrer.ReferredByEdgesTable, referrer.ReferredByEdgesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryReferenceEdges queries the reference_edges edge of a Referrer. +func (c *ReferrerClient) QueryReferenceEdges(_m *Referrer) *ReferrerReferenceQuery { + query := (&ReferrerReferenceClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(referrer.Table, referrer.FieldID, id), + sqlgraph.To(referrerreference.Table, referrerreference.ReferrerColumn), + sqlgraph.Edge(sqlgraph.O2M, true, referrer.ReferenceEdgesTable, referrer.ReferenceEdgesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + // Hooks returns the client hooks. func (c *ReferrerClient) Hooks() []Hook { return c.hooks.Referrer @@ -3025,6 +3065,122 @@ func (c *ReferrerClient) mutate(ctx context.Context, m *ReferrerMutation) (Value } } +// ReferrerReferenceClient is a client for the ReferrerReference schema. +type ReferrerReferenceClient struct { + config +} + +// NewReferrerReferenceClient returns a client for the ReferrerReference from the given config. +func NewReferrerReferenceClient(c config) *ReferrerReferenceClient { + return &ReferrerReferenceClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `referrerreference.Hooks(f(g(h())))`. +func (c *ReferrerReferenceClient) Use(hooks ...Hook) { + c.hooks.ReferrerReference = append(c.hooks.ReferrerReference, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `referrerreference.Intercept(f(g(h())))`. +func (c *ReferrerReferenceClient) Intercept(interceptors ...Interceptor) { + c.inters.ReferrerReference = append(c.inters.ReferrerReference, interceptors...) +} + +// Create returns a builder for creating a ReferrerReference entity. +func (c *ReferrerReferenceClient) Create() *ReferrerReferenceCreate { + mutation := newReferrerReferenceMutation(c.config, OpCreate) + return &ReferrerReferenceCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of ReferrerReference entities. +func (c *ReferrerReferenceClient) CreateBulk(builders ...*ReferrerReferenceCreate) *ReferrerReferenceCreateBulk { + return &ReferrerReferenceCreateBulk{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 *ReferrerReferenceClient) MapCreateBulk(slice any, setFunc func(*ReferrerReferenceCreate, int)) *ReferrerReferenceCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ReferrerReferenceCreateBulk{err: fmt.Errorf("calling to ReferrerReferenceClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ReferrerReferenceCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ReferrerReferenceCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for ReferrerReference. +func (c *ReferrerReferenceClient) Update() *ReferrerReferenceUpdate { + mutation := newReferrerReferenceMutation(c.config, OpUpdate) + return &ReferrerReferenceUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ReferrerReferenceClient) UpdateOne(_m *ReferrerReference) *ReferrerReferenceUpdateOne { + mutation := newReferrerReferenceMutation(c.config, OpUpdateOne) + mutation.referrer = &_m.ReferrerID + mutation.referred_by = &_m.ReferredByID + return &ReferrerReferenceUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for ReferrerReference. +func (c *ReferrerReferenceClient) Delete() *ReferrerReferenceDelete { + mutation := newReferrerReferenceMutation(c.config, OpDelete) + return &ReferrerReferenceDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Query returns a query builder for ReferrerReference. +func (c *ReferrerReferenceClient) Query() *ReferrerReferenceQuery { + return &ReferrerReferenceQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeReferrerReference}, + inters: c.Interceptors(), + } +} + +// QueryReferrer queries the referrer edge of a ReferrerReference. +func (c *ReferrerReferenceClient) QueryReferrer(_m *ReferrerReference) *ReferrerQuery { + return c.Query(). + Where(referrerreference.ReferrerID(_m.ReferrerID), referrerreference.ReferredByID(_m.ReferredByID)). + QueryReferrer() +} + +// QueryReferredBy queries the referred_by edge of a ReferrerReference. +func (c *ReferrerReferenceClient) QueryReferredBy(_m *ReferrerReference) *ReferrerQuery { + return c.Query(). + Where(referrerreference.ReferrerID(_m.ReferrerID), referrerreference.ReferredByID(_m.ReferredByID)). + QueryReferredBy() +} + +// Hooks returns the client hooks. +func (c *ReferrerReferenceClient) Hooks() []Hook { + return c.hooks.ReferrerReference +} + +// Interceptors returns the client interceptors. +func (c *ReferrerReferenceClient) Interceptors() []Interceptor { + return c.inters.ReferrerReference +} + +func (c *ReferrerReferenceClient) mutate(ctx context.Context, m *ReferrerReferenceMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ReferrerReferenceCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ReferrerReferenceUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ReferrerReferenceUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ReferrerReferenceDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown ReferrerReference mutation op: %q", m.Op()) + } +} + // RobotAccountClient is a client for the RobotAccount schema. type RobotAccountClient struct { config @@ -4164,13 +4320,15 @@ type ( hooks struct { APIToken, Attestation, CASBackend, CASMapping, Group, GroupMembership, Integration, IntegrationAttachment, LoginHandoff, Membership, OrgInvitation, - Organization, Project, ProjectVersion, Referrer, RobotAccount, User, Workflow, - WorkflowContract, WorkflowContractVersion, WorkflowRun []ent.Hook + Organization, Project, ProjectVersion, Referrer, ReferrerReference, + RobotAccount, User, Workflow, WorkflowContract, WorkflowContractVersion, + WorkflowRun []ent.Hook } inters struct { APIToken, Attestation, CASBackend, CASMapping, Group, GroupMembership, Integration, IntegrationAttachment, LoginHandoff, Membership, OrgInvitation, - Organization, Project, ProjectVersion, Referrer, RobotAccount, User, Workflow, - WorkflowContract, WorkflowContractVersion, WorkflowRun []ent.Interceptor + Organization, Project, ProjectVersion, Referrer, ReferrerReference, + RobotAccount, User, Workflow, WorkflowContract, WorkflowContractVersion, + WorkflowRun []ent.Interceptor } ) diff --git a/app/controlplane/pkg/data/ent/ent.go b/app/controlplane/pkg/data/ent/ent.go index 3422f6194..a77070a39 100644 --- a/app/controlplane/pkg/data/ent/ent.go +++ b/app/controlplane/pkg/data/ent/ent.go @@ -27,6 +27,7 @@ import ( "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/project" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/projectversion" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/referrer" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/referrerreference" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/robotaccount" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/user" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflow" @@ -108,6 +109,7 @@ func checkColumn(t, c string) error { project.Table: project.ValidColumn, projectversion.Table: projectversion.ValidColumn, referrer.Table: referrer.ValidColumn, + referrerreference.Table: referrerreference.ValidColumn, robotaccount.Table: robotaccount.ValidColumn, user.Table: user.ValidColumn, workflow.Table: workflow.ValidColumn, diff --git a/app/controlplane/pkg/data/ent/hook/hook.go b/app/controlplane/pkg/data/ent/hook/hook.go index 49d424b61..77a2a0580 100644 --- a/app/controlplane/pkg/data/ent/hook/hook.go +++ b/app/controlplane/pkg/data/ent/hook/hook.go @@ -189,6 +189,18 @@ func (f ReferrerFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, er return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.ReferrerMutation", m) } +// The ReferrerReferenceFunc type is an adapter to allow the use of ordinary +// function as ReferrerReference mutator. +type ReferrerReferenceFunc func(context.Context, *ent.ReferrerReferenceMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f ReferrerReferenceFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.ReferrerReferenceMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.ReferrerReferenceMutation", m) +} + // The RobotAccountFunc type is an adapter to allow the use of ordinary // function as RobotAccount mutator. type RobotAccountFunc func(context.Context, *ent.RobotAccountMutation) (ent.Value, error) diff --git a/app/controlplane/pkg/data/ent/migrate/migrations/20261116124542.sql b/app/controlplane/pkg/data/ent/migrate/migrations/20261116124542.sql new file mode 100644 index 000000000..ec0b75851 --- /dev/null +++ b/app/controlplane/pkg/data/ent/migrate/migrations/20261116124542.sql @@ -0,0 +1,9 @@ +-- Modify "referrer_references" table +-- The foreign keys get the names of the new edge schema. A rename keeps them valid without +-- checking every row again. +ALTER TABLE "referrer_references" RENAME CONSTRAINT "referrer_references_referred_by_id" TO "referrer_references_referrers_referred_by"; +ALTER TABLE "referrer_references" RENAME CONSTRAINT "referrer_references_referrer_id" TO "referrer_references_referrers_referrer"; +-- A non-volatile default does not rewrite the table, so the lock is held only briefly. +ALTER TABLE "referrer_references" ADD COLUMN "created_at" timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP; +-- A nullable column with no default only changes the catalog. +ALTER TABLE "referrer_references" ADD COLUMN "organization_id" uuid NULL; diff --git a/app/controlplane/pkg/data/ent/migrate/migrations/20261116124543.sql b/app/controlplane/pkg/data/ent/migrate/migrations/20261116124543.sql new file mode 100644 index 000000000..787be3f04 --- /dev/null +++ b/app/controlplane/pkg/data/ent/migrate/migrations/20261116124543.sql @@ -0,0 +1,36 @@ +-- atlas:txmode none + +-- Fill in the new columns of the existing references, in one pass over the table. Outside a +-- transaction with the schema change above, the update holds row locks only, until it ends. Reads +-- and new references are not blocked. Storing an existing reference again waits for the update. +-- +-- created_at is the creation time of the referrer the reference points to. +-- +-- organization_id is the organization of the attestation that stored the reference. Storing an +-- attestation links every referrer it touches, both ends of each reference included, to the +-- attestation's workflow, so that organization is one that both ends belong to. When the ends +-- share exactly one organization, it is that one. When they share more, the reference stays NULL, +-- which means that it is read in every organization. +WITH "referrer_orgs" AS ( + SELECT DISTINCT "rw"."referrer_id", "w"."organization_id" + FROM "referrer_workflows" AS "rw" + JOIN "workflows" AS "w" ON "w"."id" = "rw"."workflow_id" +), "backfill" AS ( + SELECT "rr"."referrer_id", "rr"."referred_by_id", "r"."created_at", + CASE WHEN count("b"."organization_id") = 1 THEN (array_agg("b"."organization_id") FILTER (WHERE "b"."organization_id" IS NOT NULL))[1] END AS "organization_id" + FROM "referrer_references" AS "rr" + JOIN "referrers" AS "r" ON "r"."id" = "rr"."referred_by_id" + LEFT JOIN "referrer_orgs" AS "a" ON "a"."referrer_id" = "rr"."referrer_id" + LEFT JOIN "referrer_orgs" AS "b" ON "b"."referrer_id" = "rr"."referred_by_id" AND "b"."organization_id" = "a"."organization_id" + GROUP BY "rr"."referrer_id", "rr"."referred_by_id", "r"."created_at" +) +UPDATE "referrer_references" AS "rr" +SET "created_at" = "b"."created_at", "organization_id" = "b"."organization_id" +FROM "backfill" AS "b" +WHERE "b"."referrer_id" = "rr"."referrer_id" AND "b"."referred_by_id" = "rr"."referred_by_id" + AND ("rr"."created_at" <> "b"."created_at" OR "rr"."organization_id" IS DISTINCT FROM "b"."organization_id"); +-- The update leaves a dead version of each row. Reclaim them before the index build reads the table. +VACUUM (ANALYZE) "referrer_references"; + +-- Create index "referrerreference_referrer_id_organization_id_created_at" to table: "referrer_references" +CREATE INDEX CONCURRENTLY "referrerreference_referrer_id_organization_id_created_at" ON "referrer_references" ("referrer_id", "organization_id", "created_at" DESC, "referred_by_id" DESC); diff --git a/app/controlplane/pkg/data/ent/migrate/migrations/atlas.sum b/app/controlplane/pkg/data/ent/migrate/migrations/atlas.sum index ad67be2ba..d66088c29 100644 --- a/app/controlplane/pkg/data/ent/migrate/migrations/atlas.sum +++ b/app/controlplane/pkg/data/ent/migrate/migrations/atlas.sum @@ -1,4 +1,4 @@ -h1:sz67a3W+tAr+VPRPPJ48+ancduf0og/7OrQnz+ECdyk= +h1:hWv3uPoEHIMT147AEfHNRFZ7uMnYVlKAVQACoFjPAoE= 20230706165452_init-schema.sql h1:VvqbNFEQnCvUVyj2iDYVQQxDM0+sSXqocpt/5H64k8M= 20230710111950-cas-backend.sql h1:A8iBuSzZIEbdsv9ipBtscZQuaBp3V5/VMw7eZH6GX+g= 20230712094107-cas-backends-workflow-runs.sql h1:a5rzxpVGyd56nLRSsKrmCFc9sebg65RWzLghKHh5xvI= @@ -144,3 +144,5 @@ h1:sz67a3W+tAr+VPRPPJ48+ancduf0og/7OrQnz+ECdyk= 20260929114227.sql h1:oulkhKH6cKhFva/5mYx6aSaFarM6YgeuTh0Plw8X38E= 20260930160057.sql h1:rKEj/76c/TiBjl/loP4Bld1BPMPTBlCWhaWvN/pJaRY= 20261015173225.sql h1:s5wTFJqcXx+cGUPpzyY93wP/IuizLaQ/9rP/VqtamRE= +20261116124542.sql h1:PNFvP+qcO1URsP9QsKGpAwaAL9m7yP7bzi/8SHk6yNs= +20261116124543.sql h1:r+8IOuLFQ3iMrQjYN8hPGxItVJu/bidc0/yeEUe6RFQ= diff --git a/app/controlplane/pkg/data/ent/migrate/schema.go b/app/controlplane/pkg/data/ent/migrate/schema.go index 2f9a38801..9fe082722 100644 --- a/app/controlplane/pkg/data/ent/migrate/schema.go +++ b/app/controlplane/pkg/data/ent/migrate/schema.go @@ -618,6 +618,47 @@ var ( }, }, } + // ReferrerReferencesColumns holds the columns for the "referrer_references" table. + ReferrerReferencesColumns = []*schema.Column{ + {Name: "created_at", Type: field.TypeTime, Default: "CURRENT_TIMESTAMP"}, + {Name: "organization_id", Type: field.TypeUUID, Nullable: true}, + {Name: "referrer_id", Type: field.TypeUUID}, + {Name: "referred_by_id", Type: field.TypeUUID}, + } + // ReferrerReferencesTable holds the schema information for the "referrer_references" table. + ReferrerReferencesTable = &schema.Table{ + Name: "referrer_references", + Columns: ReferrerReferencesColumns, + PrimaryKey: []*schema.Column{ReferrerReferencesColumns[2], ReferrerReferencesColumns[3]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "referrer_references_referrers_referrer", + Columns: []*schema.Column{ReferrerReferencesColumns[2]}, + RefColumns: []*schema.Column{ReferrersColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "referrer_references_referrers_referred_by", + Columns: []*schema.Column{ReferrerReferencesColumns[3]}, + RefColumns: []*schema.Column{ReferrersColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + Indexes: []*schema.Index{ + { + Name: "referrerreference_referrer_id_organization_id_created_at", + Unique: false, + Columns: []*schema.Column{ReferrerReferencesColumns[2], ReferrerReferencesColumns[1], ReferrerReferencesColumns[0], ReferrerReferencesColumns[3]}, + Annotation: &entsql.IndexAnnotation{ + DescColumns: map[string]bool{ + ReferrerReferencesColumns[0].Name: true, + + ReferrerReferencesColumns[3].Name: true, + }, + }, + }, + }, + } // RobotAccountsColumns holds the columns for the "robot_accounts" table. RobotAccountsColumns = []*schema.Column{ {Name: "id", Type: field.TypeUUID, Unique: true}, @@ -954,31 +995,6 @@ var ( }, }, } - // ReferrerReferencesColumns holds the columns for the "referrer_references" table. - ReferrerReferencesColumns = []*schema.Column{ - {Name: "referrer_id", Type: field.TypeUUID}, - {Name: "referred_by_id", Type: field.TypeUUID}, - } - // ReferrerReferencesTable holds the schema information for the "referrer_references" table. - ReferrerReferencesTable = &schema.Table{ - Name: "referrer_references", - Columns: ReferrerReferencesColumns, - PrimaryKey: []*schema.Column{ReferrerReferencesColumns[0], ReferrerReferencesColumns[1]}, - ForeignKeys: []*schema.ForeignKey{ - { - Symbol: "referrer_references_referrer_id", - Columns: []*schema.Column{ReferrerReferencesColumns[0]}, - RefColumns: []*schema.Column{ReferrersColumns[0]}, - OnDelete: schema.Cascade, - }, - { - Symbol: "referrer_references_referred_by_id", - Columns: []*schema.Column{ReferrerReferencesColumns[1]}, - RefColumns: []*schema.Column{ReferrersColumns[0]}, - OnDelete: schema.Cascade, - }, - }, - } // ReferrerWorkflowsColumns holds the columns for the "referrer_workflows" table. ReferrerWorkflowsColumns = []*schema.Column{ {Name: "referrer_id", Type: field.TypeUUID}, @@ -1046,13 +1062,13 @@ var ( ProjectsTable, ProjectVersionsTable, ReferrersTable, + ReferrerReferencesTable, RobotAccountsTable, UsersTable, WorkflowsTable, WorkflowContractsTable, WorkflowContractVersionsTable, WorkflowRunsTable, - ReferrerReferencesTable, ReferrerWorkflowsTable, WorkflowRunCasBackendsTable, } @@ -1081,6 +1097,11 @@ func init() { OrgInvitationsTable.ForeignKeys[1].RefTable = UsersTable ProjectsTable.ForeignKeys[0].RefTable = OrganizationsTable ProjectVersionsTable.ForeignKeys[0].RefTable = ProjectsTable + ReferrerReferencesTable.ForeignKeys[0].RefTable = ReferrersTable + ReferrerReferencesTable.ForeignKeys[1].RefTable = ReferrersTable + ReferrerReferencesTable.Annotation = &entsql.Annotation{ + Table: "referrer_references", + } RobotAccountsTable.ForeignKeys[0].RefTable = WorkflowsTable WorkflowsTable.ForeignKeys[0].RefTable = OrganizationsTable WorkflowsTable.ForeignKeys[1].RefTable = ProjectsTable @@ -1092,8 +1113,6 @@ func init() { WorkflowRunsTable.ForeignKeys[1].RefTable = ProjectVersionsTable WorkflowRunsTable.ForeignKeys[2].RefTable = WorkflowsTable WorkflowRunsTable.ForeignKeys[3].RefTable = WorkflowContractVersionsTable - ReferrerReferencesTable.ForeignKeys[0].RefTable = ReferrersTable - ReferrerReferencesTable.ForeignKeys[1].RefTable = ReferrersTable ReferrerWorkflowsTable.ForeignKeys[0].RefTable = ReferrersTable ReferrerWorkflowsTable.ForeignKeys[1].RefTable = WorkflowsTable WorkflowRunCasBackendsTable.ForeignKeys[0].RefTable = WorkflowRunsTable diff --git a/app/controlplane/pkg/data/ent/mutation.go b/app/controlplane/pkg/data/ent/mutation.go index 8a7ef8aed..494a7c000 100644 --- a/app/controlplane/pkg/data/ent/mutation.go +++ b/app/controlplane/pkg/data/ent/mutation.go @@ -29,6 +29,7 @@ import ( "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/project" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/projectversion" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/referrer" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/referrerreference" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/robotaccount" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/user" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflow" @@ -64,6 +65,7 @@ const ( TypeProject = "Project" TypeProjectVersion = "ProjectVersion" TypeReferrer = "Referrer" + TypeReferrerReference = "ReferrerReference" TypeRobotAccount = "RobotAccount" TypeUser = "User" TypeWorkflow = "Workflow" @@ -14762,6 +14764,477 @@ func (m *ReferrerMutation) ResetEdge(name string) error { return fmt.Errorf("unknown Referrer edge %s", name) } +// ReferrerReferenceMutation represents an operation that mutates the ReferrerReference nodes in the graph. +type ReferrerReferenceMutation struct { + config + op Op + typ string + created_at *time.Time + organization_id *uuid.UUID + clearedFields map[string]struct{} + referrer *uuid.UUID + clearedreferrer bool + referred_by *uuid.UUID + clearedreferred_by bool + done bool + oldValue func(context.Context) (*ReferrerReference, error) + predicates []predicate.ReferrerReference +} + +var _ ent.Mutation = (*ReferrerReferenceMutation)(nil) + +// referrerreferenceOption allows management of the mutation configuration using functional options. +type referrerreferenceOption func(*ReferrerReferenceMutation) + +// newReferrerReferenceMutation creates new mutation for the ReferrerReference entity. +func newReferrerReferenceMutation(c config, op Op, opts ...referrerreferenceOption) *ReferrerReferenceMutation { + m := &ReferrerReferenceMutation{ + config: c, + op: op, + typ: TypeReferrerReference, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// 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 ReferrerReferenceMutation) 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 ReferrerReferenceMutation) 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 +} + +// SetReferrerID sets the "referrer_id" field. +func (m *ReferrerReferenceMutation) SetReferrerID(u uuid.UUID) { + m.referrer = &u +} + +// ReferrerID returns the value of the "referrer_id" field in the mutation. +func (m *ReferrerReferenceMutation) ReferrerID() (r uuid.UUID, exists bool) { + v := m.referrer + if v == nil { + return + } + return *v, true +} + +// ResetReferrerID resets all changes to the "referrer_id" field. +func (m *ReferrerReferenceMutation) ResetReferrerID() { + m.referrer = nil +} + +// SetReferredByID sets the "referred_by_id" field. +func (m *ReferrerReferenceMutation) SetReferredByID(u uuid.UUID) { + m.referred_by = &u +} + +// ReferredByID returns the value of the "referred_by_id" field in the mutation. +func (m *ReferrerReferenceMutation) ReferredByID() (r uuid.UUID, exists bool) { + v := m.referred_by + if v == nil { + return + } + return *v, true +} + +// ResetReferredByID resets all changes to the "referred_by_id" field. +func (m *ReferrerReferenceMutation) ResetReferredByID() { + m.referred_by = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *ReferrerReferenceMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *ReferrerReferenceMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return + } + return *v, true +} + +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *ReferrerReferenceMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetOrganizationID sets the "organization_id" field. +func (m *ReferrerReferenceMutation) SetOrganizationID(u uuid.UUID) { + m.organization_id = &u +} + +// OrganizationID returns the value of the "organization_id" field in the mutation. +func (m *ReferrerReferenceMutation) OrganizationID() (r uuid.UUID, exists bool) { + v := m.organization_id + if v == nil { + return + } + return *v, true +} + +// ClearOrganizationID clears the value of the "organization_id" field. +func (m *ReferrerReferenceMutation) ClearOrganizationID() { + m.organization_id = nil + m.clearedFields[referrerreference.FieldOrganizationID] = struct{}{} +} + +// OrganizationIDCleared returns if the "organization_id" field was cleared in this mutation. +func (m *ReferrerReferenceMutation) OrganizationIDCleared() bool { + _, ok := m.clearedFields[referrerreference.FieldOrganizationID] + return ok +} + +// ResetOrganizationID resets all changes to the "organization_id" field. +func (m *ReferrerReferenceMutation) ResetOrganizationID() { + m.organization_id = nil + delete(m.clearedFields, referrerreference.FieldOrganizationID) +} + +// ClearReferrer clears the "referrer" edge to the Referrer entity. +func (m *ReferrerReferenceMutation) ClearReferrer() { + m.clearedreferrer = true + m.clearedFields[referrerreference.FieldReferrerID] = struct{}{} +} + +// ReferrerCleared reports if the "referrer" edge to the Referrer entity was cleared. +func (m *ReferrerReferenceMutation) ReferrerCleared() bool { + return m.clearedreferrer +} + +// ReferrerIDs returns the "referrer" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// ReferrerID instead. It exists only for internal usage by the builders. +func (m *ReferrerReferenceMutation) ReferrerIDs() (ids []uuid.UUID) { + if id := m.referrer; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetReferrer resets all changes to the "referrer" edge. +func (m *ReferrerReferenceMutation) ResetReferrer() { + m.referrer = nil + m.clearedreferrer = false +} + +// ClearReferredBy clears the "referred_by" edge to the Referrer entity. +func (m *ReferrerReferenceMutation) ClearReferredBy() { + m.clearedreferred_by = true + m.clearedFields[referrerreference.FieldReferredByID] = struct{}{} +} + +// ReferredByCleared reports if the "referred_by" edge to the Referrer entity was cleared. +func (m *ReferrerReferenceMutation) ReferredByCleared() bool { + return m.clearedreferred_by +} + +// ReferredByIDs returns the "referred_by" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// ReferredByID instead. It exists only for internal usage by the builders. +func (m *ReferrerReferenceMutation) ReferredByIDs() (ids []uuid.UUID) { + if id := m.referred_by; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetReferredBy resets all changes to the "referred_by" edge. +func (m *ReferrerReferenceMutation) ResetReferredBy() { + m.referred_by = nil + m.clearedreferred_by = false +} + +// Where appends a list predicates to the ReferrerReferenceMutation builder. +func (m *ReferrerReferenceMutation) Where(ps ...predicate.ReferrerReference) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ReferrerReferenceMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ReferrerReferenceMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.ReferrerReference, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ReferrerReferenceMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ReferrerReferenceMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (ReferrerReference). +func (m *ReferrerReferenceMutation) 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 *ReferrerReferenceMutation) Fields() []string { + fields := make([]string, 0, 4) + if m.referrer != nil { + fields = append(fields, referrerreference.FieldReferrerID) + } + if m.referred_by != nil { + fields = append(fields, referrerreference.FieldReferredByID) + } + if m.created_at != nil { + fields = append(fields, referrerreference.FieldCreatedAt) + } + if m.organization_id != nil { + fields = append(fields, referrerreference.FieldOrganizationID) + } + 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 *ReferrerReferenceMutation) Field(name string) (ent.Value, bool) { + switch name { + case referrerreference.FieldReferrerID: + return m.ReferrerID() + case referrerreference.FieldReferredByID: + return m.ReferredByID() + case referrerreference.FieldCreatedAt: + return m.CreatedAt() + case referrerreference.FieldOrganizationID: + return m.OrganizationID() + } + 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 *ReferrerReferenceMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + return nil, errors.New("edge schema ReferrerReference does not support getting old values") +} + +// 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 *ReferrerReferenceMutation) SetField(name string, value ent.Value) error { + switch name { + case referrerreference.FieldReferrerID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetReferrerID(v) + return nil + case referrerreference.FieldReferredByID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetReferredByID(v) + return nil + case referrerreference.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case referrerreference.FieldOrganizationID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOrganizationID(v) + return nil + } + return fmt.Errorf("unknown ReferrerReference field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ReferrerReferenceMutation) AddedFields() []string { + return nil +} + +// 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 *ReferrerReferenceMutation) AddedField(name string) (ent.Value, bool) { + 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 *ReferrerReferenceMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown ReferrerReference numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ReferrerReferenceMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(referrerreference.FieldOrganizationID) { + fields = append(fields, referrerreference.FieldOrganizationID) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ReferrerReferenceMutation) 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 *ReferrerReferenceMutation) ClearField(name string) error { + switch name { + case referrerreference.FieldOrganizationID: + m.ClearOrganizationID() + return nil + } + return fmt.Errorf("unknown ReferrerReference 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 *ReferrerReferenceMutation) ResetField(name string) error { + switch name { + case referrerreference.FieldReferrerID: + m.ResetReferrerID() + return nil + case referrerreference.FieldReferredByID: + m.ResetReferredByID() + return nil + case referrerreference.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case referrerreference.FieldOrganizationID: + m.ResetOrganizationID() + return nil + } + return fmt.Errorf("unknown ReferrerReference field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ReferrerReferenceMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.referrer != nil { + edges = append(edges, referrerreference.EdgeReferrer) + } + if m.referred_by != nil { + edges = append(edges, referrerreference.EdgeReferredBy) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ReferrerReferenceMutation) AddedIDs(name string) []ent.Value { + switch name { + case referrerreference.EdgeReferrer: + if id := m.referrer; id != nil { + return []ent.Value{*id} + } + case referrerreference.EdgeReferredBy: + if id := m.referred_by; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *ReferrerReferenceMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *ReferrerReferenceMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ReferrerReferenceMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedreferrer { + edges = append(edges, referrerreference.EdgeReferrer) + } + if m.clearedreferred_by { + edges = append(edges, referrerreference.EdgeReferredBy) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ReferrerReferenceMutation) EdgeCleared(name string) bool { + switch name { + case referrerreference.EdgeReferrer: + return m.clearedreferrer + case referrerreference.EdgeReferredBy: + return m.clearedreferred_by + } + 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 *ReferrerReferenceMutation) ClearEdge(name string) error { + switch name { + case referrerreference.EdgeReferrer: + m.ClearReferrer() + return nil + case referrerreference.EdgeReferredBy: + m.ClearReferredBy() + return nil + } + return fmt.Errorf("unknown ReferrerReference 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 *ReferrerReferenceMutation) ResetEdge(name string) error { + switch name { + case referrerreference.EdgeReferrer: + m.ResetReferrer() + return nil + case referrerreference.EdgeReferredBy: + m.ResetReferredBy() + return nil + } + return fmt.Errorf("unknown ReferrerReference edge %s", name) +} + // RobotAccountMutation represents an operation that mutates the RobotAccount nodes in the graph. type RobotAccountMutation struct { config diff --git a/app/controlplane/pkg/data/ent/predicate/predicate.go b/app/controlplane/pkg/data/ent/predicate/predicate.go index a4ba7fab4..c46a3dd0f 100644 --- a/app/controlplane/pkg/data/ent/predicate/predicate.go +++ b/app/controlplane/pkg/data/ent/predicate/predicate.go @@ -51,6 +51,9 @@ type ProjectVersion func(*sql.Selector) // Referrer is the predicate function for referrer builders. type Referrer func(*sql.Selector) +// ReferrerReference is the predicate function for referrerreference builders. +type ReferrerReference func(*sql.Selector) + // RobotAccount is the predicate function for robotaccount builders. type RobotAccount func(*sql.Selector) diff --git a/app/controlplane/pkg/data/ent/referrer.go b/app/controlplane/pkg/data/ent/referrer.go index c00a72aea..667567f2d 100644 --- a/app/controlplane/pkg/data/ent/referrer.go +++ b/app/controlplane/pkg/data/ent/referrer.go @@ -45,9 +45,13 @@ type ReferrerEdges struct { References []*Referrer `json:"references,omitempty"` // Workflows holds the value of the workflows edge. Workflows []*Workflow `json:"workflows,omitempty"` + // ReferredByEdges holds the value of the referred_by_edges edge. + ReferredByEdges []*ReferrerReference `json:"referred_by_edges,omitempty"` + // ReferenceEdges holds the value of the reference_edges edge. + ReferenceEdges []*ReferrerReference `json:"reference_edges,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [3]bool + loadedTypes [5]bool } // ReferredByOrErr returns the ReferredBy value or an error if the edge @@ -77,6 +81,24 @@ func (e ReferrerEdges) WorkflowsOrErr() ([]*Workflow, error) { return nil, &NotLoadedError{edge: "workflows"} } +// ReferredByEdgesOrErr returns the ReferredByEdges value or an error if the edge +// was not loaded in eager-loading. +func (e ReferrerEdges) ReferredByEdgesOrErr() ([]*ReferrerReference, error) { + if e.loadedTypes[3] { + return e.ReferredByEdges, nil + } + return nil, &NotLoadedError{edge: "referred_by_edges"} +} + +// ReferenceEdgesOrErr returns the ReferenceEdges value or an error if the edge +// was not loaded in eager-loading. +func (e ReferrerEdges) ReferenceEdgesOrErr() ([]*ReferrerReference, error) { + if e.loadedTypes[4] { + return e.ReferenceEdges, nil + } + return nil, &NotLoadedError{edge: "reference_edges"} +} + // scanValues returns the types for scanning values from sql.Rows. func (*Referrer) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) @@ -181,6 +203,16 @@ func (_m *Referrer) QueryWorkflows() *WorkflowQuery { return NewReferrerClient(_m.config).QueryWorkflows(_m) } +// QueryReferredByEdges queries the "referred_by_edges" edge of the Referrer entity. +func (_m *Referrer) QueryReferredByEdges() *ReferrerReferenceQuery { + return NewReferrerClient(_m.config).QueryReferredByEdges(_m) +} + +// QueryReferenceEdges queries the "reference_edges" edge of the Referrer entity. +func (_m *Referrer) QueryReferenceEdges() *ReferrerReferenceQuery { + return NewReferrerClient(_m.config).QueryReferenceEdges(_m) +} + // Update returns a builder for updating this Referrer. // Note that you need to call Referrer.Unwrap() before calling this method if this Referrer // was returned from a transaction, and the transaction was committed or rolled back. diff --git a/app/controlplane/pkg/data/ent/referrer/referrer.go b/app/controlplane/pkg/data/ent/referrer/referrer.go index e6be513ca..2d2d7342f 100644 --- a/app/controlplane/pkg/data/ent/referrer/referrer.go +++ b/app/controlplane/pkg/data/ent/referrer/referrer.go @@ -33,6 +33,10 @@ const ( EdgeReferences = "references" // EdgeWorkflows holds the string denoting the workflows edge name in mutations. EdgeWorkflows = "workflows" + // EdgeReferredByEdges holds the string denoting the referred_by_edges edge name in mutations. + EdgeReferredByEdges = "referred_by_edges" + // EdgeReferenceEdges holds the string denoting the reference_edges edge name in mutations. + EdgeReferenceEdges = "reference_edges" // Table holds the table name of the referrer in the database. Table = "referrers" // ReferredByTable is the table that holds the referred_by relation/edge. The primary key declared below. @@ -44,6 +48,20 @@ const ( // WorkflowsInverseTable is the table name for the Workflow entity. // It exists in this package in order to avoid circular dependency with the "workflow" package. WorkflowsInverseTable = "workflows" + // ReferredByEdgesTable is the table that holds the referred_by_edges relation/edge. + ReferredByEdgesTable = "referrer_references" + // ReferredByEdgesInverseTable is the table name for the ReferrerReference entity. + // It exists in this package in order to avoid circular dependency with the "referrerreference" package. + ReferredByEdgesInverseTable = "referrer_references" + // ReferredByEdgesColumn is the table column denoting the referred_by_edges relation/edge. + ReferredByEdgesColumn = "referred_by_id" + // ReferenceEdgesTable is the table that holds the reference_edges relation/edge. + ReferenceEdgesTable = "referrer_references" + // ReferenceEdgesInverseTable is the table name for the ReferrerReference entity. + // It exists in this package in order to avoid circular dependency with the "referrerreference" package. + ReferenceEdgesInverseTable = "referrer_references" + // ReferenceEdgesColumn is the table column denoting the reference_edges relation/edge. + ReferenceEdgesColumn = "referrer_id" ) // Columns holds all SQL columns for referrer fields. @@ -155,6 +173,34 @@ func ByWorkflows(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { sqlgraph.OrderByNeighborTerms(s, newWorkflowsStep(), append([]sql.OrderTerm{term}, terms...)...) } } + +// ByReferredByEdgesCount orders the results by referred_by_edges count. +func ByReferredByEdgesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newReferredByEdgesStep(), opts...) + } +} + +// ByReferredByEdges orders the results by referred_by_edges terms. +func ByReferredByEdges(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newReferredByEdgesStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByReferenceEdgesCount orders the results by reference_edges count. +func ByReferenceEdgesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newReferenceEdgesStep(), opts...) + } +} + +// ByReferenceEdges orders the results by reference_edges terms. +func ByReferenceEdges(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newReferenceEdgesStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} func newReferredByStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), @@ -176,3 +222,17 @@ func newWorkflowsStep() *sqlgraph.Step { sqlgraph.Edge(sqlgraph.M2M, false, WorkflowsTable, WorkflowsPrimaryKey...), ) } +func newReferredByEdgesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ReferredByEdgesInverseTable, ReferredByEdgesColumn), + sqlgraph.Edge(sqlgraph.O2M, true, ReferredByEdgesTable, ReferredByEdgesColumn), + ) +} +func newReferenceEdgesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ReferenceEdgesInverseTable, ReferenceEdgesColumn), + sqlgraph.Edge(sqlgraph.O2M, true, ReferenceEdgesTable, ReferenceEdgesColumn), + ) +} diff --git a/app/controlplane/pkg/data/ent/referrer/where.go b/app/controlplane/pkg/data/ent/referrer/where.go index d3be2a7c5..4b2bd46cb 100644 --- a/app/controlplane/pkg/data/ent/referrer/where.go +++ b/app/controlplane/pkg/data/ent/referrer/where.go @@ -345,6 +345,52 @@ func HasWorkflowsWith(preds ...predicate.Workflow) predicate.Referrer { }) } +// HasReferredByEdges applies the HasEdge predicate on the "referred_by_edges" edge. +func HasReferredByEdges() predicate.Referrer { + return predicate.Referrer(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, ReferredByEdgesTable, ReferredByEdgesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasReferredByEdgesWith applies the HasEdge predicate on the "referred_by_edges" edge with a given conditions (other predicates). +func HasReferredByEdgesWith(preds ...predicate.ReferrerReference) predicate.Referrer { + return predicate.Referrer(func(s *sql.Selector) { + step := newReferredByEdgesStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasReferenceEdges applies the HasEdge predicate on the "reference_edges" edge. +func HasReferenceEdges() predicate.Referrer { + return predicate.Referrer(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, ReferenceEdgesTable, ReferenceEdgesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasReferenceEdgesWith applies the HasEdge predicate on the "reference_edges" edge with a given conditions (other predicates). +func HasReferenceEdgesWith(preds ...predicate.ReferrerReference) predicate.Referrer { + return predicate.Referrer(func(s *sql.Selector) { + step := newReferenceEdgesStep() + 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.Referrer) predicate.Referrer { return predicate.Referrer(sql.AndPredicates(predicates...)) diff --git a/app/controlplane/pkg/data/ent/referrer_query.go b/app/controlplane/pkg/data/ent/referrer_query.go index e456bfb1e..fb18f75ef 100644 --- a/app/controlplane/pkg/data/ent/referrer_query.go +++ b/app/controlplane/pkg/data/ent/referrer_query.go @@ -15,6 +15,7 @@ import ( "entgo.io/ent/schema/field" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/predicate" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/referrer" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/referrerreference" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflow" "github.com/google/uuid" ) @@ -22,14 +23,16 @@ import ( // ReferrerQuery is the builder for querying Referrer entities. type ReferrerQuery struct { config - ctx *QueryContext - order []referrer.OrderOption - inters []Interceptor - predicates []predicate.Referrer - withReferredBy *ReferrerQuery - withReferences *ReferrerQuery - withWorkflows *WorkflowQuery - modifiers []func(*sql.Selector) + ctx *QueryContext + order []referrer.OrderOption + inters []Interceptor + predicates []predicate.Referrer + withReferredBy *ReferrerQuery + withReferences *ReferrerQuery + withWorkflows *WorkflowQuery + withReferredByEdges *ReferrerReferenceQuery + withReferenceEdges *ReferrerReferenceQuery + modifiers []func(*sql.Selector) // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -132,6 +135,50 @@ func (_q *ReferrerQuery) QueryWorkflows() *WorkflowQuery { return query } +// QueryReferredByEdges chains the current query on the "referred_by_edges" edge. +func (_q *ReferrerQuery) QueryReferredByEdges() *ReferrerReferenceQuery { + query := (&ReferrerReferenceClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(referrer.Table, referrer.FieldID, selector), + sqlgraph.To(referrerreference.Table, referrerreference.ReferredByColumn), + sqlgraph.Edge(sqlgraph.O2M, true, referrer.ReferredByEdgesTable, referrer.ReferredByEdgesColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryReferenceEdges chains the current query on the "reference_edges" edge. +func (_q *ReferrerQuery) QueryReferenceEdges() *ReferrerReferenceQuery { + query := (&ReferrerReferenceClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(referrer.Table, referrer.FieldID, selector), + sqlgraph.To(referrerreference.Table, referrerreference.ReferrerColumn), + sqlgraph.Edge(sqlgraph.O2M, true, referrer.ReferenceEdgesTable, referrer.ReferenceEdgesColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + // First returns the first Referrer entity from the query. // Returns a *NotFoundError when no Referrer was found. func (_q *ReferrerQuery) First(ctx context.Context) (*Referrer, error) { @@ -319,14 +366,16 @@ func (_q *ReferrerQuery) Clone() *ReferrerQuery { return nil } return &ReferrerQuery{ - config: _q.config, - ctx: _q.ctx.Clone(), - order: append([]referrer.OrderOption{}, _q.order...), - inters: append([]Interceptor{}, _q.inters...), - predicates: append([]predicate.Referrer{}, _q.predicates...), - withReferredBy: _q.withReferredBy.Clone(), - withReferences: _q.withReferences.Clone(), - withWorkflows: _q.withWorkflows.Clone(), + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]referrer.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Referrer{}, _q.predicates...), + withReferredBy: _q.withReferredBy.Clone(), + withReferences: _q.withReferences.Clone(), + withWorkflows: _q.withWorkflows.Clone(), + withReferredByEdges: _q.withReferredByEdges.Clone(), + withReferenceEdges: _q.withReferenceEdges.Clone(), // clone intermediate query. sql: _q.sql.Clone(), path: _q.path, @@ -367,6 +416,28 @@ func (_q *ReferrerQuery) WithWorkflows(opts ...func(*WorkflowQuery)) *ReferrerQu return _q } +// WithReferredByEdges tells the query-builder to eager-load the nodes that are connected to +// the "referred_by_edges" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ReferrerQuery) WithReferredByEdges(opts ...func(*ReferrerReferenceQuery)) *ReferrerQuery { + query := (&ReferrerReferenceClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withReferredByEdges = query + return _q +} + +// WithReferenceEdges tells the query-builder to eager-load the nodes that are connected to +// the "reference_edges" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ReferrerQuery) WithReferenceEdges(opts ...func(*ReferrerReferenceQuery)) *ReferrerQuery { + query := (&ReferrerReferenceClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withReferenceEdges = query + return _q +} + // 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. // @@ -445,10 +516,12 @@ func (_q *ReferrerQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Ref var ( nodes = []*Referrer{} _spec = _q.querySpec() - loadedTypes = [3]bool{ + loadedTypes = [5]bool{ _q.withReferredBy != nil, _q.withReferences != nil, _q.withWorkflows != nil, + _q.withReferredByEdges != nil, + _q.withReferenceEdges != nil, } ) _spec.ScanValues = func(columns []string) ([]any, error) { @@ -493,6 +566,20 @@ func (_q *ReferrerQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Ref return nil, err } } + if query := _q.withReferredByEdges; query != nil { + if err := _q.loadReferredByEdges(ctx, query, nodes, + func(n *Referrer) { n.Edges.ReferredByEdges = []*ReferrerReference{} }, + func(n *Referrer, e *ReferrerReference) { n.Edges.ReferredByEdges = append(n.Edges.ReferredByEdges, e) }); err != nil { + return nil, err + } + } + if query := _q.withReferenceEdges; query != nil { + if err := _q.loadReferenceEdges(ctx, query, nodes, + func(n *Referrer) { n.Edges.ReferenceEdges = []*ReferrerReference{} }, + func(n *Referrer, e *ReferrerReference) { n.Edges.ReferenceEdges = append(n.Edges.ReferenceEdges, e) }); err != nil { + return nil, err + } + } return nodes, nil } @@ -679,6 +766,66 @@ func (_q *ReferrerQuery) loadWorkflows(ctx context.Context, query *WorkflowQuery } return nil } +func (_q *ReferrerQuery) loadReferredByEdges(ctx context.Context, query *ReferrerReferenceQuery, nodes []*Referrer, init func(*Referrer), assign func(*Referrer, *ReferrerReference)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[uuid.UUID]*Referrer) + 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(referrerreference.FieldReferredByID) + } + query.Where(predicate.ReferrerReference(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(referrer.ReferredByEdgesColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.ReferredByID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "referred_by_id" returned %v for node %v`, fk, n) + } + assign(node, n) + } + return nil +} +func (_q *ReferrerQuery) loadReferenceEdges(ctx context.Context, query *ReferrerReferenceQuery, nodes []*Referrer, init func(*Referrer), assign func(*Referrer, *ReferrerReference)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[uuid.UUID]*Referrer) + 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(referrerreference.FieldReferrerID) + } + query.Where(predicate.ReferrerReference(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(referrer.ReferenceEdgesColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.ReferrerID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "referrer_id" returned %v for node %v`, fk, n) + } + assign(node, n) + } + return nil +} func (_q *ReferrerQuery) sqlCount(ctx context.Context) (int, error) { _spec := _q.querySpec() diff --git a/app/controlplane/pkg/data/ent/referrerreference.go b/app/controlplane/pkg/data/ent/referrerreference.go new file mode 100644 index 000000000..29e57b8c0 --- /dev/null +++ b/app/controlplane/pkg/data/ent/referrerreference.go @@ -0,0 +1,181 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/referrer" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/referrerreference" + "github.com/google/uuid" +) + +// ReferrerReference is the model entity for the ReferrerReference schema. +type ReferrerReference struct { + config `json:"-"` + // ReferrerID holds the value of the "referrer_id" field. + ReferrerID uuid.UUID `json:"referrer_id,omitempty"` + // ReferredByID holds the value of the "referred_by_id" field. + ReferredByID uuid.UUID `json:"referred_by_id,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // OrganizationID holds the value of the "organization_id" field. + OrganizationID *uuid.UUID `json:"organization_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the ReferrerReferenceQuery when eager-loading is set. + Edges ReferrerReferenceEdges `json:"edges"` + selectValues sql.SelectValues +} + +// ReferrerReferenceEdges holds the relations/edges for other nodes in the graph. +type ReferrerReferenceEdges struct { + // Referrer holds the value of the referrer edge. + Referrer *Referrer `json:"referrer,omitempty"` + // ReferredBy holds the value of the referred_by edge. + ReferredBy *Referrer `json:"referred_by,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// ReferrerOrErr returns the Referrer value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ReferrerReferenceEdges) ReferrerOrErr() (*Referrer, error) { + if e.Referrer != nil { + return e.Referrer, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: referrer.Label} + } + return nil, &NotLoadedError{edge: "referrer"} +} + +// ReferredByOrErr returns the ReferredBy value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e ReferrerReferenceEdges) ReferredByOrErr() (*Referrer, error) { + if e.ReferredBy != nil { + return e.ReferredBy, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: referrer.Label} + } + return nil, &NotLoadedError{edge: "referred_by"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*ReferrerReference) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case referrerreference.FieldOrganizationID: + values[i] = &sql.NullScanner{S: new(uuid.UUID)} + case referrerreference.FieldCreatedAt: + values[i] = new(sql.NullTime) + case referrerreference.FieldReferrerID, referrerreference.FieldReferredByID: + 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 ReferrerReference fields. +func (_m *ReferrerReference) 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 referrerreference.FieldReferrerID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field referrer_id", values[i]) + } else if value != nil { + _m.ReferrerID = *value + } + case referrerreference.FieldReferredByID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field referred_by_id", values[i]) + } else if value != nil { + _m.ReferredByID = *value + } + case referrerreference.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + case referrerreference.FieldOrganizationID: + if value, ok := values[i].(*sql.NullScanner); !ok { + return fmt.Errorf("unexpected type %T for field organization_id", values[i]) + } else if value.Valid { + _m.OrganizationID = new(uuid.UUID) + *_m.OrganizationID = *value.S.(*uuid.UUID) + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the ReferrerReference. +// This includes values selected through modifiers, order, etc. +func (_m *ReferrerReference) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryReferrer queries the "referrer" edge of the ReferrerReference entity. +func (_m *ReferrerReference) QueryReferrer() *ReferrerQuery { + return NewReferrerReferenceClient(_m.config).QueryReferrer(_m) +} + +// QueryReferredBy queries the "referred_by" edge of the ReferrerReference entity. +func (_m *ReferrerReference) QueryReferredBy() *ReferrerQuery { + return NewReferrerReferenceClient(_m.config).QueryReferredBy(_m) +} + +// Update returns a builder for updating this ReferrerReference. +// Note that you need to call ReferrerReference.Unwrap() before calling this method if this ReferrerReference +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *ReferrerReference) Update() *ReferrerReferenceUpdateOne { + return NewReferrerReferenceClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the ReferrerReference entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *ReferrerReference) Unwrap() *ReferrerReference { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: ReferrerReference is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *ReferrerReference) String() string { + var builder strings.Builder + builder.WriteString("ReferrerReference(") + builder.WriteString("referrer_id=") + builder.WriteString(fmt.Sprintf("%v", _m.ReferrerID)) + builder.WriteString(", ") + builder.WriteString("referred_by_id=") + builder.WriteString(fmt.Sprintf("%v", _m.ReferredByID)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + if v := _m.OrganizationID; v != nil { + builder.WriteString("organization_id=") + builder.WriteString(fmt.Sprintf("%v", *v)) + } + builder.WriteByte(')') + return builder.String() +} + +// ReferrerReferences is a parsable slice of ReferrerReference. +type ReferrerReferences []*ReferrerReference diff --git a/app/controlplane/pkg/data/ent/referrerreference/referrerreference.go b/app/controlplane/pkg/data/ent/referrerreference/referrerreference.go new file mode 100644 index 000000000..b28b11c4a --- /dev/null +++ b/app/controlplane/pkg/data/ent/referrerreference/referrerreference.go @@ -0,0 +1,112 @@ +// Code generated by ent, DO NOT EDIT. + +package referrerreference + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the referrerreference type in the database. + Label = "referrer_reference" + // FieldReferrerID holds the string denoting the referrer_id field in the database. + FieldReferrerID = "referrer_id" + // FieldReferredByID holds the string denoting the referred_by_id field in the database. + FieldReferredByID = "referred_by_id" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldOrganizationID holds the string denoting the organization_id field in the database. + FieldOrganizationID = "organization_id" + // EdgeReferrer holds the string denoting the referrer edge name in mutations. + EdgeReferrer = "referrer" + // EdgeReferredBy holds the string denoting the referred_by edge name in mutations. + EdgeReferredBy = "referred_by" + // ReferrerFieldID holds the string denoting the ID field of the Referrer. + ReferrerFieldID = "id" + // Table holds the table name of the referrerreference in the database. + Table = "referrer_references" + // ReferrerTable is the table that holds the referrer relation/edge. + ReferrerTable = "referrer_references" + // ReferrerInverseTable is the table name for the Referrer entity. + // It exists in this package in order to avoid circular dependency with the "referrer" package. + ReferrerInverseTable = "referrers" + // ReferrerColumn is the table column denoting the referrer relation/edge. + ReferrerColumn = "referrer_id" + // ReferredByTable is the table that holds the referred_by relation/edge. + ReferredByTable = "referrer_references" + // ReferredByInverseTable is the table name for the Referrer entity. + // It exists in this package in order to avoid circular dependency with the "referrer" package. + ReferredByInverseTable = "referrers" + // ReferredByColumn is the table column denoting the referred_by relation/edge. + ReferredByColumn = "referred_by_id" +) + +// Columns holds all SQL columns for referrerreference fields. +var Columns = []string{ + FieldReferrerID, + FieldReferredByID, + FieldCreatedAt, + FieldOrganizationID, +} + +// 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 +} + +// OrderOption defines the ordering options for the ReferrerReference queries. +type OrderOption func(*sql.Selector) + +// ByReferrerID orders the results by the referrer_id field. +func ByReferrerID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldReferrerID, opts...).ToFunc() +} + +// ByReferredByID orders the results by the referred_by_id field. +func ByReferredByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldReferredByID, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByOrganizationID orders the results by the organization_id field. +func ByOrganizationID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldOrganizationID, opts...).ToFunc() +} + +// ByReferrerField orders the results by referrer field. +func ByReferrerField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newReferrerStep(), sql.OrderByField(field, opts...)) + } +} + +// ByReferredByField orders the results by referred_by field. +func ByReferredByField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newReferredByStep(), sql.OrderByField(field, opts...)) + } +} +func newReferrerStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, ReferrerColumn), + sqlgraph.To(ReferrerInverseTable, ReferrerFieldID), + sqlgraph.Edge(sqlgraph.M2O, false, ReferrerTable, ReferrerColumn), + ) +} +func newReferredByStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, ReferredByColumn), + sqlgraph.To(ReferredByInverseTable, ReferrerFieldID), + sqlgraph.Edge(sqlgraph.M2O, false, ReferredByTable, ReferredByColumn), + ) +} diff --git a/app/controlplane/pkg/data/ent/referrerreference/where.go b/app/controlplane/pkg/data/ent/referrerreference/where.go new file mode 100644 index 000000000..8739d7b92 --- /dev/null +++ b/app/controlplane/pkg/data/ent/referrerreference/where.go @@ -0,0 +1,223 @@ +// Code generated by ent, DO NOT EDIT. + +package referrerreference + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/predicate" + "github.com/google/uuid" +) + +// ReferrerID applies equality check predicate on the "referrer_id" field. It's identical to ReferrerIDEQ. +func ReferrerID(v uuid.UUID) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldEQ(FieldReferrerID, v)) +} + +// ReferredByID applies equality check predicate on the "referred_by_id" field. It's identical to ReferredByIDEQ. +func ReferredByID(v uuid.UUID) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldEQ(FieldReferredByID, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldEQ(FieldCreatedAt, v)) +} + +// OrganizationID applies equality check predicate on the "organization_id" field. It's identical to OrganizationIDEQ. +func OrganizationID(v uuid.UUID) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldEQ(FieldOrganizationID, v)) +} + +// ReferrerIDEQ applies the EQ predicate on the "referrer_id" field. +func ReferrerIDEQ(v uuid.UUID) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldEQ(FieldReferrerID, v)) +} + +// ReferrerIDNEQ applies the NEQ predicate on the "referrer_id" field. +func ReferrerIDNEQ(v uuid.UUID) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldNEQ(FieldReferrerID, v)) +} + +// ReferrerIDIn applies the In predicate on the "referrer_id" field. +func ReferrerIDIn(vs ...uuid.UUID) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldIn(FieldReferrerID, vs...)) +} + +// ReferrerIDNotIn applies the NotIn predicate on the "referrer_id" field. +func ReferrerIDNotIn(vs ...uuid.UUID) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldNotIn(FieldReferrerID, vs...)) +} + +// ReferredByIDEQ applies the EQ predicate on the "referred_by_id" field. +func ReferredByIDEQ(v uuid.UUID) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldEQ(FieldReferredByID, v)) +} + +// ReferredByIDNEQ applies the NEQ predicate on the "referred_by_id" field. +func ReferredByIDNEQ(v uuid.UUID) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldNEQ(FieldReferredByID, v)) +} + +// ReferredByIDIn applies the In predicate on the "referred_by_id" field. +func ReferredByIDIn(vs ...uuid.UUID) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldIn(FieldReferredByID, vs...)) +} + +// ReferredByIDNotIn applies the NotIn predicate on the "referred_by_id" field. +func ReferredByIDNotIn(vs ...uuid.UUID) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldNotIn(FieldReferredByID, vs...)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldLTE(FieldCreatedAt, v)) +} + +// OrganizationIDEQ applies the EQ predicate on the "organization_id" field. +func OrganizationIDEQ(v uuid.UUID) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldEQ(FieldOrganizationID, v)) +} + +// OrganizationIDNEQ applies the NEQ predicate on the "organization_id" field. +func OrganizationIDNEQ(v uuid.UUID) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldNEQ(FieldOrganizationID, v)) +} + +// OrganizationIDIn applies the In predicate on the "organization_id" field. +func OrganizationIDIn(vs ...uuid.UUID) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldIn(FieldOrganizationID, vs...)) +} + +// OrganizationIDNotIn applies the NotIn predicate on the "organization_id" field. +func OrganizationIDNotIn(vs ...uuid.UUID) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldNotIn(FieldOrganizationID, vs...)) +} + +// OrganizationIDGT applies the GT predicate on the "organization_id" field. +func OrganizationIDGT(v uuid.UUID) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldGT(FieldOrganizationID, v)) +} + +// OrganizationIDGTE applies the GTE predicate on the "organization_id" field. +func OrganizationIDGTE(v uuid.UUID) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldGTE(FieldOrganizationID, v)) +} + +// OrganizationIDLT applies the LT predicate on the "organization_id" field. +func OrganizationIDLT(v uuid.UUID) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldLT(FieldOrganizationID, v)) +} + +// OrganizationIDLTE applies the LTE predicate on the "organization_id" field. +func OrganizationIDLTE(v uuid.UUID) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldLTE(FieldOrganizationID, v)) +} + +// OrganizationIDIsNil applies the IsNil predicate on the "organization_id" field. +func OrganizationIDIsNil() predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldIsNull(FieldOrganizationID)) +} + +// OrganizationIDNotNil applies the NotNil predicate on the "organization_id" field. +func OrganizationIDNotNil() predicate.ReferrerReference { + return predicate.ReferrerReference(sql.FieldNotNull(FieldOrganizationID)) +} + +// HasReferrer applies the HasEdge predicate on the "referrer" edge. +func HasReferrer() predicate.ReferrerReference { + return predicate.ReferrerReference(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, ReferrerColumn), + sqlgraph.Edge(sqlgraph.M2O, false, ReferrerTable, ReferrerColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasReferrerWith applies the HasEdge predicate on the "referrer" edge with a given conditions (other predicates). +func HasReferrerWith(preds ...predicate.Referrer) predicate.ReferrerReference { + return predicate.ReferrerReference(func(s *sql.Selector) { + step := newReferrerStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasReferredBy applies the HasEdge predicate on the "referred_by" edge. +func HasReferredBy() predicate.ReferrerReference { + return predicate.ReferrerReference(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, ReferredByColumn), + sqlgraph.Edge(sqlgraph.M2O, false, ReferredByTable, ReferredByColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasReferredByWith applies the HasEdge predicate on the "referred_by" edge with a given conditions (other predicates). +func HasReferredByWith(preds ...predicate.Referrer) predicate.ReferrerReference { + return predicate.ReferrerReference(func(s *sql.Selector) { + step := newReferredByStep() + 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.ReferrerReference) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.ReferrerReference) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.ReferrerReference) predicate.ReferrerReference { + return predicate.ReferrerReference(sql.NotPredicates(p)) +} diff --git a/app/controlplane/pkg/data/ent/referrerreference_create.go b/app/controlplane/pkg/data/ent/referrerreference_create.go new file mode 100644 index 000000000..15f6bbc4c --- /dev/null +++ b/app/controlplane/pkg/data/ent/referrerreference_create.go @@ -0,0 +1,560 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/referrer" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/referrerreference" + "github.com/google/uuid" +) + +// ReferrerReferenceCreate is the builder for creating a ReferrerReference entity. +type ReferrerReferenceCreate struct { + config + mutation *ReferrerReferenceMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetReferrerID sets the "referrer_id" field. +func (_c *ReferrerReferenceCreate) SetReferrerID(v uuid.UUID) *ReferrerReferenceCreate { + _c.mutation.SetReferrerID(v) + return _c +} + +// SetReferredByID sets the "referred_by_id" field. +func (_c *ReferrerReferenceCreate) SetReferredByID(v uuid.UUID) *ReferrerReferenceCreate { + _c.mutation.SetReferredByID(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *ReferrerReferenceCreate) SetCreatedAt(v time.Time) *ReferrerReferenceCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetOrganizationID sets the "organization_id" field. +func (_c *ReferrerReferenceCreate) SetOrganizationID(v uuid.UUID) *ReferrerReferenceCreate { + _c.mutation.SetOrganizationID(v) + return _c +} + +// SetNillableOrganizationID sets the "organization_id" field if the given value is not nil. +func (_c *ReferrerReferenceCreate) SetNillableOrganizationID(v *uuid.UUID) *ReferrerReferenceCreate { + if v != nil { + _c.SetOrganizationID(*v) + } + return _c +} + +// SetReferrer sets the "referrer" edge to the Referrer entity. +func (_c *ReferrerReferenceCreate) SetReferrer(v *Referrer) *ReferrerReferenceCreate { + return _c.SetReferrerID(v.ID) +} + +// SetReferredBy sets the "referred_by" edge to the Referrer entity. +func (_c *ReferrerReferenceCreate) SetReferredBy(v *Referrer) *ReferrerReferenceCreate { + return _c.SetReferredByID(v.ID) +} + +// Mutation returns the ReferrerReferenceMutation object of the builder. +func (_c *ReferrerReferenceCreate) Mutation() *ReferrerReferenceMutation { + return _c.mutation +} + +// Save creates the ReferrerReference in the database. +func (_c *ReferrerReferenceCreate) Save(ctx context.Context) (*ReferrerReference, error) { + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *ReferrerReferenceCreate) SaveX(ctx context.Context) *ReferrerReference { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ReferrerReferenceCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ReferrerReferenceCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *ReferrerReferenceCreate) check() error { + if _, ok := _c.mutation.ReferrerID(); !ok { + return &ValidationError{Name: "referrer_id", err: errors.New(`ent: missing required field "ReferrerReference.referrer_id"`)} + } + if _, ok := _c.mutation.ReferredByID(); !ok { + return &ValidationError{Name: "referred_by_id", err: errors.New(`ent: missing required field "ReferrerReference.referred_by_id"`)} + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "ReferrerReference.created_at"`)} + } + if len(_c.mutation.ReferrerIDs()) == 0 { + return &ValidationError{Name: "referrer", err: errors.New(`ent: missing required edge "ReferrerReference.referrer"`)} + } + if len(_c.mutation.ReferredByIDs()) == 0 { + return &ValidationError{Name: "referred_by", err: errors.New(`ent: missing required edge "ReferrerReference.referred_by"`)} + } + return nil +} + +func (_c *ReferrerReferenceCreate) sqlSave(ctx context.Context) (*ReferrerReference, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + return _node, nil +} + +func (_c *ReferrerReferenceCreate) createSpec() (*ReferrerReference, *sqlgraph.CreateSpec) { + var ( + _node = &ReferrerReference{config: _c.config} + _spec = sqlgraph.NewCreateSpec(referrerreference.Table, nil) + ) + _spec.OnConflict = _c.conflict + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(referrerreference.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.OrganizationID(); ok { + _spec.SetField(referrerreference.FieldOrganizationID, field.TypeUUID, value) + _node.OrganizationID = &value + } + if nodes := _c.mutation.ReferrerIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: referrerreference.ReferrerTable, + Columns: []string{referrerreference.ReferrerColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(referrer.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.ReferrerID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.ReferredByIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: referrerreference.ReferredByTable, + Columns: []string{referrerreference.ReferredByColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(referrer.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.ReferredByID = 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.ReferrerReference.Create(). +// SetReferrerID(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.ReferrerReferenceUpsert) { +// SetReferrerID(v+v). +// }). +// Exec(ctx) +func (_c *ReferrerReferenceCreate) OnConflict(opts ...sql.ConflictOption) *ReferrerReferenceUpsertOne { + _c.conflict = opts + return &ReferrerReferenceUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ReferrerReference.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ReferrerReferenceCreate) OnConflictColumns(columns ...string) *ReferrerReferenceUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ReferrerReferenceUpsertOne{ + create: _c, + } +} + +type ( + // ReferrerReferenceUpsertOne is the builder for "upsert"-ing + // one ReferrerReference node. + ReferrerReferenceUpsertOne struct { + create *ReferrerReferenceCreate + } + + // ReferrerReferenceUpsert is the "OnConflict" setter. + ReferrerReferenceUpsert struct { + *sql.UpdateSet + } +) + +// SetOrganizationID sets the "organization_id" field. +func (u *ReferrerReferenceUpsert) SetOrganizationID(v uuid.UUID) *ReferrerReferenceUpsert { + u.Set(referrerreference.FieldOrganizationID, v) + return u +} + +// UpdateOrganizationID sets the "organization_id" field to the value that was provided on create. +func (u *ReferrerReferenceUpsert) UpdateOrganizationID() *ReferrerReferenceUpsert { + u.SetExcluded(referrerreference.FieldOrganizationID) + return u +} + +// ClearOrganizationID clears the value of the "organization_id" field. +func (u *ReferrerReferenceUpsert) ClearOrganizationID() *ReferrerReferenceUpsert { + u.SetNull(referrerreference.FieldOrganizationID) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create. +// Using this option is equivalent to using: +// +// client.ReferrerReference.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// ). +// Exec(ctx) +func (u *ReferrerReferenceUpsertOne) UpdateNewValues() *ReferrerReferenceUpsertOne { + 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.ReferrerID(); exists { + s.SetIgnore(referrerreference.FieldReferrerID) + } + if _, exists := u.create.mutation.ReferredByID(); exists { + s.SetIgnore(referrerreference.FieldReferredByID) + } + if _, exists := u.create.mutation.CreatedAt(); exists { + s.SetIgnore(referrerreference.FieldCreatedAt) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ReferrerReference.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ReferrerReferenceUpsertOne) Ignore() *ReferrerReferenceUpsertOne { + 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 *ReferrerReferenceUpsertOne) DoNothing() *ReferrerReferenceUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ReferrerReferenceCreate.OnConflict +// documentation for more info. +func (u *ReferrerReferenceUpsertOne) Update(set func(*ReferrerReferenceUpsert)) *ReferrerReferenceUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ReferrerReferenceUpsert{UpdateSet: update}) + })) + return u +} + +// SetOrganizationID sets the "organization_id" field. +func (u *ReferrerReferenceUpsertOne) SetOrganizationID(v uuid.UUID) *ReferrerReferenceUpsertOne { + return u.Update(func(s *ReferrerReferenceUpsert) { + s.SetOrganizationID(v) + }) +} + +// UpdateOrganizationID sets the "organization_id" field to the value that was provided on create. +func (u *ReferrerReferenceUpsertOne) UpdateOrganizationID() *ReferrerReferenceUpsertOne { + return u.Update(func(s *ReferrerReferenceUpsert) { + s.UpdateOrganizationID() + }) +} + +// ClearOrganizationID clears the value of the "organization_id" field. +func (u *ReferrerReferenceUpsertOne) ClearOrganizationID() *ReferrerReferenceUpsertOne { + return u.Update(func(s *ReferrerReferenceUpsert) { + s.ClearOrganizationID() + }) +} + +// Exec executes the query. +func (u *ReferrerReferenceUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for ReferrerReferenceCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ReferrerReferenceUpsertOne) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} + +// ReferrerReferenceCreateBulk is the builder for creating many ReferrerReference entities in bulk. +type ReferrerReferenceCreateBulk struct { + config + err error + builders []*ReferrerReferenceCreate + conflict []sql.ConflictOption +} + +// Save creates the ReferrerReference entities in the database. +func (_c *ReferrerReferenceCreateBulk) Save(ctx context.Context) ([]*ReferrerReference, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*ReferrerReference, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*ReferrerReferenceMutation) + 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, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + 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, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *ReferrerReferenceCreateBulk) SaveX(ctx context.Context) []*ReferrerReference { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *ReferrerReferenceCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *ReferrerReferenceCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.ReferrerReference.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.ReferrerReferenceUpsert) { +// SetReferrerID(v+v). +// }). +// Exec(ctx) +func (_c *ReferrerReferenceCreateBulk) OnConflict(opts ...sql.ConflictOption) *ReferrerReferenceUpsertBulk { + _c.conflict = opts + return &ReferrerReferenceUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.ReferrerReference.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *ReferrerReferenceCreateBulk) OnConflictColumns(columns ...string) *ReferrerReferenceUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &ReferrerReferenceUpsertBulk{ + create: _c, + } +} + +// ReferrerReferenceUpsertBulk is the builder for "upsert"-ing +// a bulk of ReferrerReference nodes. +type ReferrerReferenceUpsertBulk struct { + create *ReferrerReferenceCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.ReferrerReference.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// ). +// Exec(ctx) +func (u *ReferrerReferenceUpsertBulk) UpdateNewValues() *ReferrerReferenceUpsertBulk { + 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.ReferrerID(); exists { + s.SetIgnore(referrerreference.FieldReferrerID) + } + if _, exists := b.mutation.ReferredByID(); exists { + s.SetIgnore(referrerreference.FieldReferredByID) + } + if _, exists := b.mutation.CreatedAt(); exists { + s.SetIgnore(referrerreference.FieldCreatedAt) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.ReferrerReference.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *ReferrerReferenceUpsertBulk) Ignore() *ReferrerReferenceUpsertBulk { + 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 *ReferrerReferenceUpsertBulk) DoNothing() *ReferrerReferenceUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the ReferrerReferenceCreateBulk.OnConflict +// documentation for more info. +func (u *ReferrerReferenceUpsertBulk) Update(set func(*ReferrerReferenceUpsert)) *ReferrerReferenceUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&ReferrerReferenceUpsert{UpdateSet: update}) + })) + return u +} + +// SetOrganizationID sets the "organization_id" field. +func (u *ReferrerReferenceUpsertBulk) SetOrganizationID(v uuid.UUID) *ReferrerReferenceUpsertBulk { + return u.Update(func(s *ReferrerReferenceUpsert) { + s.SetOrganizationID(v) + }) +} + +// UpdateOrganizationID sets the "organization_id" field to the value that was provided on create. +func (u *ReferrerReferenceUpsertBulk) UpdateOrganizationID() *ReferrerReferenceUpsertBulk { + return u.Update(func(s *ReferrerReferenceUpsert) { + s.UpdateOrganizationID() + }) +} + +// ClearOrganizationID clears the value of the "organization_id" field. +func (u *ReferrerReferenceUpsertBulk) ClearOrganizationID() *ReferrerReferenceUpsertBulk { + return u.Update(func(s *ReferrerReferenceUpsert) { + s.ClearOrganizationID() + }) +} + +// Exec executes the query. +func (u *ReferrerReferenceUpsertBulk) 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 ReferrerReferenceCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("ent: missing options for ReferrerReferenceCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *ReferrerReferenceUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/controlplane/pkg/data/ent/referrerreference_delete.go b/app/controlplane/pkg/data/ent/referrerreference_delete.go new file mode 100644 index 000000000..8a42f46b7 --- /dev/null +++ b/app/controlplane/pkg/data/ent/referrerreference_delete.go @@ -0,0 +1,87 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/predicate" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/referrerreference" +) + +// ReferrerReferenceDelete is the builder for deleting a ReferrerReference entity. +type ReferrerReferenceDelete struct { + config + hooks []Hook + mutation *ReferrerReferenceMutation +} + +// Where appends a list predicates to the ReferrerReferenceDelete builder. +func (_d *ReferrerReferenceDelete) Where(ps ...predicate.ReferrerReference) *ReferrerReferenceDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *ReferrerReferenceDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ReferrerReferenceDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *ReferrerReferenceDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(referrerreference.Table, nil) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// ReferrerReferenceDeleteOne is the builder for deleting a single ReferrerReference entity. +type ReferrerReferenceDeleteOne struct { + _d *ReferrerReferenceDelete +} + +// Where appends a list predicates to the ReferrerReferenceDelete builder. +func (_d *ReferrerReferenceDeleteOne) Where(ps ...predicate.ReferrerReference) *ReferrerReferenceDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *ReferrerReferenceDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{referrerreference.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *ReferrerReferenceDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/app/controlplane/pkg/data/ent/referrerreference_query.go b/app/controlplane/pkg/data/ent/referrerreference_query.go new file mode 100644 index 000000000..0fece74a3 --- /dev/null +++ b/app/controlplane/pkg/data/ent/referrerreference_query.go @@ -0,0 +1,653 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/predicate" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/referrer" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/referrerreference" + "github.com/google/uuid" +) + +// ReferrerReferenceQuery is the builder for querying ReferrerReference entities. +type ReferrerReferenceQuery struct { + config + ctx *QueryContext + order []referrerreference.OrderOption + inters []Interceptor + predicates []predicate.ReferrerReference + withReferrer *ReferrerQuery + withReferredBy *ReferrerQuery + 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 ReferrerReferenceQuery builder. +func (_q *ReferrerReferenceQuery) Where(ps ...predicate.ReferrerReference) *ReferrerReferenceQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *ReferrerReferenceQuery) Limit(limit int) *ReferrerReferenceQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *ReferrerReferenceQuery) Offset(offset int) *ReferrerReferenceQuery { + _q.ctx.Offset = &offset + return _q +} + +// 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 (_q *ReferrerReferenceQuery) Unique(unique bool) *ReferrerReferenceQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *ReferrerReferenceQuery) Order(o ...referrerreference.OrderOption) *ReferrerReferenceQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryReferrer chains the current query on the "referrer" edge. +func (_q *ReferrerReferenceQuery) QueryReferrer() *ReferrerQuery { + query := (&ReferrerClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(referrerreference.Table, referrerreference.ReferrerColumn, selector), + sqlgraph.To(referrer.Table, referrer.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, referrerreference.ReferrerTable, referrerreference.ReferrerColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryReferredBy chains the current query on the "referred_by" edge. +func (_q *ReferrerReferenceQuery) QueryReferredBy() *ReferrerQuery { + query := (&ReferrerClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(referrerreference.Table, referrerreference.ReferredByColumn, selector), + sqlgraph.To(referrer.Table, referrer.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, referrerreference.ReferredByTable, referrerreference.ReferredByColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first ReferrerReference entity from the query. +// Returns a *NotFoundError when no ReferrerReference was found. +func (_q *ReferrerReferenceQuery) First(ctx context.Context) (*ReferrerReference, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{referrerreference.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *ReferrerReferenceQuery) FirstX(ctx context.Context) *ReferrerReference { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// Only returns a single ReferrerReference entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one ReferrerReference entity is found. +// Returns a *NotFoundError when no ReferrerReference entities are found. +func (_q *ReferrerReferenceQuery) Only(ctx context.Context) (*ReferrerReference, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{referrerreference.Label} + default: + return nil, &NotSingularError{referrerreference.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *ReferrerReferenceQuery) OnlyX(ctx context.Context) *ReferrerReference { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// All executes the query and returns a list of ReferrerReferences. +func (_q *ReferrerReferenceQuery) All(ctx context.Context) ([]*ReferrerReference, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*ReferrerReference, *ReferrerReferenceQuery]() + return withInterceptors[[]*ReferrerReference](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *ReferrerReferenceQuery) AllX(ctx context.Context) []*ReferrerReference { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// Count returns the count of the given query. +func (_q *ReferrerReferenceQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*ReferrerReferenceQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *ReferrerReferenceQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *ReferrerReferenceQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.First(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 (_q *ReferrerReferenceQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ReferrerReferenceQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *ReferrerReferenceQuery) Clone() *ReferrerReferenceQuery { + if _q == nil { + return nil + } + return &ReferrerReferenceQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]referrerreference.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.ReferrerReference{}, _q.predicates...), + withReferrer: _q.withReferrer.Clone(), + withReferredBy: _q.withReferredBy.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + modifiers: append([]func(*sql.Selector){}, _q.modifiers...), + } +} + +// WithReferrer tells the query-builder to eager-load the nodes that are connected to +// the "referrer" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ReferrerReferenceQuery) WithReferrer(opts ...func(*ReferrerQuery)) *ReferrerReferenceQuery { + query := (&ReferrerClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withReferrer = query + return _q +} + +// WithReferredBy tells the query-builder to eager-load the nodes that are connected to +// the "referred_by" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ReferrerReferenceQuery) WithReferredBy(opts ...func(*ReferrerQuery)) *ReferrerReferenceQuery { + query := (&ReferrerClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withReferredBy = query + return _q +} + +// 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 { +// ReferrerID uuid.UUID `json:"referrer_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.ReferrerReference.Query(). +// GroupBy(referrerreference.FieldReferrerID). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *ReferrerReferenceQuery) GroupBy(field string, fields ...string) *ReferrerReferenceGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ReferrerReferenceGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = referrerreference.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 { +// ReferrerID uuid.UUID `json:"referrer_id,omitempty"` +// } +// +// client.ReferrerReference.Query(). +// Select(referrerreference.FieldReferrerID). +// Scan(ctx, &v) +func (_q *ReferrerReferenceQuery) Select(fields ...string) *ReferrerReferenceSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ReferrerReferenceSelect{ReferrerReferenceQuery: _q} + sbuild.label = referrerreference.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ReferrerReferenceSelect configured with the given aggregations. +func (_q *ReferrerReferenceQuery) Aggregate(fns ...AggregateFunc) *ReferrerReferenceSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *ReferrerReferenceQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.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, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !referrerreference.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *ReferrerReferenceQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ReferrerReference, error) { + var ( + nodes = []*ReferrerReference{} + _spec = _q.querySpec() + loadedTypes = [2]bool{ + _q.withReferrer != nil, + _q.withReferredBy != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*ReferrerReference).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &ReferrerReference{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withReferrer; query != nil { + if err := _q.loadReferrer(ctx, query, nodes, nil, + func(n *ReferrerReference, e *Referrer) { n.Edges.Referrer = e }); err != nil { + return nil, err + } + } + if query := _q.withReferredBy; query != nil { + if err := _q.loadReferredBy(ctx, query, nodes, nil, + func(n *ReferrerReference, e *Referrer) { n.Edges.ReferredBy = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *ReferrerReferenceQuery) loadReferrer(ctx context.Context, query *ReferrerQuery, nodes []*ReferrerReference, init func(*ReferrerReference), assign func(*ReferrerReference, *Referrer)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*ReferrerReference) + for i := range nodes { + fk := nodes[i].ReferrerID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(referrer.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 "referrer_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *ReferrerReferenceQuery) loadReferredBy(ctx context.Context, query *ReferrerQuery, nodes []*ReferrerReference, init func(*ReferrerReference), assign func(*ReferrerReference, *Referrer)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*ReferrerReference) + for i := range nodes { + fk := nodes[i].ReferredByID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(referrer.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 "referred_by_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *ReferrerReferenceQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + _spec.Unique = false + _spec.Node.Columns = nil + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *ReferrerReferenceQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(referrerreference.Table, referrerreference.Columns, nil) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + for i := range fields { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + if _q.withReferrer != nil { + _spec.Node.AddColumnOnce(referrerreference.FieldReferrerID) + } + if _q.withReferredBy != nil { + _spec.Node.AddColumnOnce(referrerreference.FieldReferredByID) + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *ReferrerReferenceQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(referrerreference.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = referrerreference.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, m := range _q.modifiers { + m(selector) + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.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 := _q.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 (_q *ReferrerReferenceQuery) ForUpdate(opts ...sql.LockOption) *ReferrerReferenceQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return _q +} + +// 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 (_q *ReferrerReferenceQuery) ForShare(opts ...sql.LockOption) *ReferrerReferenceQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (_q *ReferrerReferenceQuery) Modify(modifiers ...func(s *sql.Selector)) *ReferrerReferenceSelect { + _q.modifiers = append(_q.modifiers, modifiers...) + return _q.Select() +} + +// ReferrerReferenceGroupBy is the group-by builder for ReferrerReference entities. +type ReferrerReferenceGroupBy struct { + selector + build *ReferrerReferenceQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *ReferrerReferenceGroupBy) Aggregate(fns ...AggregateFunc) *ReferrerReferenceGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *ReferrerReferenceGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ReferrerReferenceQuery, *ReferrerReferenceGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *ReferrerReferenceGroupBy) sqlScan(ctx context.Context, root *ReferrerReferenceQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// ReferrerReferenceSelect is the builder for selecting fields of ReferrerReference entities. +type ReferrerReferenceSelect struct { + *ReferrerReferenceQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *ReferrerReferenceSelect) Aggregate(fns ...AggregateFunc) *ReferrerReferenceSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *ReferrerReferenceSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ReferrerReferenceQuery, *ReferrerReferenceSelect](ctx, _s.ReferrerReferenceQuery, _s, _s.inters, v) +} + +func (_s *ReferrerReferenceSelect) sqlScan(ctx context.Context, root *ReferrerReferenceQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.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 := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (_s *ReferrerReferenceSelect) Modify(modifiers ...func(s *sql.Selector)) *ReferrerReferenceSelect { + _s.modifiers = append(_s.modifiers, modifiers...) + return _s +} diff --git a/app/controlplane/pkg/data/ent/referrerreference_update.go b/app/controlplane/pkg/data/ent/referrerreference_update.go new file mode 100644 index 000000000..5493ad23e --- /dev/null +++ b/app/controlplane/pkg/data/ent/referrerreference_update.go @@ -0,0 +1,274 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/predicate" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/referrerreference" + "github.com/google/uuid" +) + +// ReferrerReferenceUpdate is the builder for updating ReferrerReference entities. +type ReferrerReferenceUpdate struct { + config + hooks []Hook + mutation *ReferrerReferenceMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the ReferrerReferenceUpdate builder. +func (_u *ReferrerReferenceUpdate) Where(ps ...predicate.ReferrerReference) *ReferrerReferenceUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetOrganizationID sets the "organization_id" field. +func (_u *ReferrerReferenceUpdate) SetOrganizationID(v uuid.UUID) *ReferrerReferenceUpdate { + _u.mutation.SetOrganizationID(v) + return _u +} + +// SetNillableOrganizationID sets the "organization_id" field if the given value is not nil. +func (_u *ReferrerReferenceUpdate) SetNillableOrganizationID(v *uuid.UUID) *ReferrerReferenceUpdate { + if v != nil { + _u.SetOrganizationID(*v) + } + return _u +} + +// ClearOrganizationID clears the value of the "organization_id" field. +func (_u *ReferrerReferenceUpdate) ClearOrganizationID() *ReferrerReferenceUpdate { + _u.mutation.ClearOrganizationID() + return _u +} + +// Mutation returns the ReferrerReferenceMutation object of the builder. +func (_u *ReferrerReferenceUpdate) Mutation() *ReferrerReferenceMutation { + return _u.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *ReferrerReferenceUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ReferrerReferenceUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *ReferrerReferenceUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ReferrerReferenceUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ReferrerReferenceUpdate) check() error { + if _u.mutation.ReferrerCleared() && len(_u.mutation.ReferrerIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "ReferrerReference.referrer"`) + } + if _u.mutation.ReferredByCleared() && len(_u.mutation.ReferredByIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "ReferrerReference.referred_by"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *ReferrerReferenceUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *ReferrerReferenceUpdate { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *ReferrerReferenceUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(referrerreference.Table, referrerreference.Columns, sqlgraph.NewFieldSpec(referrerreference.FieldReferrerID, field.TypeUUID), sqlgraph.NewFieldSpec(referrerreference.FieldReferredByID, field.TypeUUID)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.OrganizationID(); ok { + _spec.SetField(referrerreference.FieldOrganizationID, field.TypeUUID, value) + } + if _u.mutation.OrganizationIDCleared() { + _spec.ClearField(referrerreference.FieldOrganizationID, field.TypeUUID) + } + _spec.AddModifiers(_u.modifiers...) + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{referrerreference.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// ReferrerReferenceUpdateOne is the builder for updating a single ReferrerReference entity. +type ReferrerReferenceUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ReferrerReferenceMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetOrganizationID sets the "organization_id" field. +func (_u *ReferrerReferenceUpdateOne) SetOrganizationID(v uuid.UUID) *ReferrerReferenceUpdateOne { + _u.mutation.SetOrganizationID(v) + return _u +} + +// SetNillableOrganizationID sets the "organization_id" field if the given value is not nil. +func (_u *ReferrerReferenceUpdateOne) SetNillableOrganizationID(v *uuid.UUID) *ReferrerReferenceUpdateOne { + if v != nil { + _u.SetOrganizationID(*v) + } + return _u +} + +// ClearOrganizationID clears the value of the "organization_id" field. +func (_u *ReferrerReferenceUpdateOne) ClearOrganizationID() *ReferrerReferenceUpdateOne { + _u.mutation.ClearOrganizationID() + return _u +} + +// Mutation returns the ReferrerReferenceMutation object of the builder. +func (_u *ReferrerReferenceUpdateOne) Mutation() *ReferrerReferenceMutation { + return _u.mutation +} + +// Where appends a list predicates to the ReferrerReferenceUpdate builder. +func (_u *ReferrerReferenceUpdateOne) Where(ps ...predicate.ReferrerReference) *ReferrerReferenceUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *ReferrerReferenceUpdateOne) Select(field string, fields ...string) *ReferrerReferenceUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated ReferrerReference entity. +func (_u *ReferrerReferenceUpdateOne) Save(ctx context.Context) (*ReferrerReference, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *ReferrerReferenceUpdateOne) SaveX(ctx context.Context) *ReferrerReference { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *ReferrerReferenceUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *ReferrerReferenceUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *ReferrerReferenceUpdateOne) check() error { + if _u.mutation.ReferrerCleared() && len(_u.mutation.ReferrerIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "ReferrerReference.referrer"`) + } + if _u.mutation.ReferredByCleared() && len(_u.mutation.ReferredByIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "ReferrerReference.referred_by"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *ReferrerReferenceUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *ReferrerReferenceUpdateOne { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *ReferrerReferenceUpdateOne) sqlSave(ctx context.Context) (_node *ReferrerReference, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(referrerreference.Table, referrerreference.Columns, sqlgraph.NewFieldSpec(referrerreference.FieldReferrerID, field.TypeUUID), sqlgraph.NewFieldSpec(referrerreference.FieldReferredByID, field.TypeUUID)) + if id, ok := _u.mutation.ReferrerID(); !ok { + return nil, &ValidationError{Name: "referrer_id", err: errors.New(`ent: missing "ReferrerReference.referrer_id" for update`)} + } else { + _spec.Node.CompositeID[0].Value = id + } + if id, ok := _u.mutation.ReferredByID(); !ok { + return nil, &ValidationError{Name: "referred_by_id", err: errors.New(`ent: missing "ReferrerReference.referred_by_id" for update`)} + } else { + _spec.Node.CompositeID[1].Value = id + } + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, len(fields)) + for i, f := range fields { + if !referrerreference.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + _spec.Node.Columns[i] = f + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.OrganizationID(); ok { + _spec.SetField(referrerreference.FieldOrganizationID, field.TypeUUID, value) + } + if _u.mutation.OrganizationIDCleared() { + _spec.ClearField(referrerreference.FieldOrganizationID, field.TypeUUID) + } + _spec.AddModifiers(_u.modifiers...) + _node = &ReferrerReference{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{referrerreference.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/app/controlplane/pkg/data/ent/schema/referrer.go b/app/controlplane/pkg/data/ent/schema/referrer.go index 8b6906275..3ec9f8db8 100644 --- a/app/controlplane/pkg/data/ent/schema/referrer.go +++ b/app/controlplane/pkg/data/ent/schema/referrer.go @@ -1,5 +1,5 @@ // -// Copyright 2023 The Chainloop Authors. +// Copyright 2023-2026 The Chainloop Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -50,7 +50,8 @@ func (Referrer) Fields() []ent.Field { func (Referrer) Edges() []ent.Edge { return []ent.Edge{ // M2M referrer can refer to itself via references - edge.To("references", Referrer.Type).From("referred_by").Immutable(), + edge.To("references", Referrer.Type).Through("reference_edges", ReferrerReference.Type). + From("referred_by").Through("referred_by_edges", ReferrerReference.Type).Immutable(), // M2M. referrer can be part of multiple workflows edge.To("workflows", Workflow.Type).Annotations(entsql.Annotation{OnDelete: entsql.Cascade}), } diff --git a/app/controlplane/pkg/data/ent/schema/referrerreference.go b/app/controlplane/pkg/data/ent/schema/referrerreference.go new file mode 100644 index 000000000..bd7145b86 --- /dev/null +++ b/app/controlplane/pkg/data/ent/schema/referrerreference.go @@ -0,0 +1,93 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" + "github.com/google/uuid" +) + +// currentTimestamp is the SQL default for timestamp columns that the database fills in. +const currentTimestamp = "CURRENT_TIMESTAMP" + +// ReferrerReference is the edge schema of the references between referrers. A row says that +// referrer_id references referred_by_id. +type ReferrerReference struct { + ent.Schema +} + +func (ReferrerReference) Fields() []ent.Field { + return []ent.Field{ + field.UUID("referrer_id", uuid.UUID{}).Immutable(), + field.UUID("referred_by_id", uuid.UUID{}).Immutable(), + // The creation time of the referenced referrer (referred_by_id), copied so that the + // references of a referrer can be read newest first from an index. There is no Go default, + // so a create must set it. The database default covers writers outside Ent's create, such + // as the previous release during an upgrade, with the time the reference was stored. + field.Time("created_at"). + Immutable(). + Annotations(&entsql.Annotation{Default: currentTimestamp}), + // The organization of the attestation whose ingestion stored the reference, so that a + // caller can page over the references stored in its own organizations only. NULL means + // that the organization is not known, or that the reference was stored by attestations in + // more than one organization: such a reference is read in every organization, subject to + // the visibility check. A value is only ever replaced with NULL, never with another + // organization. + field.UUID("organization_id", uuid.UUID{}). + Optional(). + Nillable(), + } +} + +func (ReferrerReference) Annotations() []schema.Annotation { + return []schema.Annotation{ + field.ID("referrer_id", "referred_by_id"), + entsql.Annotation{Table: "referrer_references"}, + } +} + +func (ReferrerReference) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("referrer", Referrer.Type). + Required(). + Unique(). + Immutable(). + Field("referrer_id"). + Annotations(entsql.Annotation{OnDelete: entsql.Cascade}), + edge.To("referred_by", Referrer.Type). + Required(). + Unique(). + Immutable(). + Field("referred_by_id"). + Annotations(entsql.Annotation{OnDelete: entsql.Cascade}), + } +} + +func (ReferrerReference) Indexes() []ent.Index { + return []ent.Index{ + // A page of the references of a referrer in one organization (or with no known + // organization), newest first, in index order. + // The generated name is longer than the 63 characters PostgreSQL keeps, so it is set here. + index.Fields("referrer_id", "organization_id", "created_at", "referred_by_id"). + StorageKey("referrerreference_referrer_id_organization_id_created_at"). + Annotations(entsql.DescColumns("created_at", "referred_by_id")), + } +} diff --git a/app/controlplane/pkg/data/ent/tx.go b/app/controlplane/pkg/data/ent/tx.go index f6c16a2e4..2fca8d2a7 100644 --- a/app/controlplane/pkg/data/ent/tx.go +++ b/app/controlplane/pkg/data/ent/tx.go @@ -42,6 +42,8 @@ type Tx struct { ProjectVersion *ProjectVersionClient // Referrer is the client for interacting with the Referrer builders. Referrer *ReferrerClient + // ReferrerReference is the client for interacting with the ReferrerReference builders. + ReferrerReference *ReferrerReferenceClient // RobotAccount is the client for interacting with the RobotAccount builders. RobotAccount *RobotAccountClient // User is the client for interacting with the User builders. @@ -200,6 +202,7 @@ func (tx *Tx) init() { tx.Project = NewProjectClient(tx.config) tx.ProjectVersion = NewProjectVersionClient(tx.config) tx.Referrer = NewReferrerClient(tx.config) + tx.ReferrerReference = NewReferrerReferenceClient(tx.config) tx.RobotAccount = NewRobotAccountClient(tx.config) tx.User = NewUserClient(tx.config) tx.Workflow = NewWorkflowClient(tx.config) diff --git a/app/controlplane/pkg/data/referrer.go b/app/controlplane/pkg/data/referrer.go index 56e277ef8..080fcea11 100644 --- a/app/controlplane/pkg/data/referrer.go +++ b/app/controlplane/pkg/data/referrer.go @@ -16,6 +16,7 @@ package data import ( + "bytes" "context" "fmt" "slices" @@ -27,6 +28,7 @@ import ( "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/project" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/projectversion" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/referrer" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/referrerreference" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflow" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflowrun" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/pagination" @@ -52,7 +54,8 @@ func NewReferrerRepo(data *Data, wfRepo biz.WorkflowRepo, logger log.Logger) biz } } -type storedReferrerMap map[string]uuid.UUID +// storedReferrerMap holds the ID and creation time of each stored referrer, by MapID. +type storedReferrerMap map[string]*ent.Referrer func (r *ReferrerRepo) Save(ctx context.Context, referrers []*biz.Referrer, workflowID uuid.UUID) (err error) { ctx, span := otelx.Start(ctx, referrerRepoTracer, "ReferrerRepo.Save") @@ -81,39 +84,62 @@ func (r *ReferrerRepo) Save(ctx context.Context, referrers []*biz.Referrer, work return fmt.Errorf("failed to create referrer: %w", err) } - storedRef, err := r.data.DB.Referrer.Query().Select(referrer.FieldID).Where(referrer.ID(storedID)).First(ctx) + storedRef, err := r.data.DB.Referrer.Query().Select(referrer.FieldID, referrer.FieldCreatedAt).Where(referrer.ID(storedID)).First(ctx) if err != nil { return fmt.Errorf("failed to load referrer: %w", err) - } else if storedRef == nil { - return fmt.Errorf("failed to load referrer: %w", err) } // Store it in the map - storedMap[ref.MapID()] = storedRef.ID + storedMap[ref.MapID()] = storedRef } // 2 - define the relationship between referrers for _, parentRef := range referrers { // This is the current item stored in DB - storedReferrer := storedMap[parentRef.MapID()] + parent := storedMap[parentRef.MapID()] // Iterate on the items it refers to (references) - var references []uuid.UUID + references := make([]*ent.ReferrerReferenceCreate, 0, len(parentRef.References)) + seen := make(map[uuid.UUID]bool, len(parentRef.References)) for _, ref := range parentRef.References { // and find it in the DB - storedReference, ok := storedMap[ref.MapID()] + target, ok := storedMap[ref.MapID()] if !ok { return fmt.Errorf("referrer %v not found", ref) } - - references = append(references, storedReference) + // An upsert cannot touch the same row twice in one statement + if seen[target.ID] { + continue + } + seen[target.ID] = true + + // The reference carries the creation time of the referrer it points to and the + // organization of the attestation being stored, so that the references of a referrer + // can be paged newest first, per organization, from an index. + references = append(references, r.data.DB.ReferrerReference.Create(). + SetReferrerID(parent.ID). + SetReferredByID(target.ID). + SetCreatedAt(target.CreatedAt). + SetOrganizationID(wf.OrgID)) } if len(references) == 0 { continue } - // Create the relationship - if err := r.data.DB.Referrer.UpdateOneID(storedReferrer).AddReferenceIDs(references...).Exec(ctx); err != nil { + // Create the relationship. A reference that exists already keeps its organization if it + // was stored in the same one. If an attestation in another organization stores it again, + // for example the same attestation pushed to a run in another organization, the reference + // belongs to both: it loses its organization, so that it is read in every organization. + // A reference with no organization is left as it is, so storing it again writes nothing. + storedOrg := referrerreference.Table + "." + referrerreference.FieldOrganizationID + if err := r.data.DB.ReferrerReference.CreateBulk(references...). + OnConflict( + sql.ConflictColumns(referrerreference.FieldReferrerID, referrerreference.FieldReferredByID), + sql.UpdateWhere(sql.ExprP(fmt.Sprintf("%s IS NOT NULL AND %s IS DISTINCT FROM excluded.%s", + storedOrg, storedOrg, referrerreference.FieldOrganizationID))), + ). + Update(func(u *ent.ReferrerReferenceUpsert) { u.ClearOrganizationID() }). + Exec(ctx); err != nil { return fmt.Errorf("failed to create referrer relationship: %w", err) } } @@ -428,48 +454,27 @@ func (r *ReferrerRepo) doGet(ctx context.Context, root *ent.Referrer, allowedOrg p = &pagination.CursorOptions{Limit: pagination.DefaultCursorLimit} } - // Sort references by creation date and ID in descending order for deterministic pagination - q := root.QueryReferences().Where(predicateReferrer...).WithWorkflows(). - // Ent adds a DISTINCT to any traversal by default, because an edge query can multiply - // rows. This one cannot: the join table is keyed on (referrer_id, referred_by_id), so a - // fixed root matches each referrer at most once, and the selected columns include the - // primary key, so there is nothing to collapse. Every predicate above is a semi-join - // (EXISTS, IN) or a scalar comparison. - // - // Any predicate added here must stay join-free. A join would return a reference twice, - // which consumes a slot in the page and leaves the cursor on the wrong row, so references - // are skipped rather than repeated. sql.OrPredicates applies each predicate to this same - // selector, so a joining predicate inside an Or leaks its join here while its WHERE is - // OR-ed away. - Unique(false). - Order(referrer.ByCreatedAt(sql.OrderDesc())). - Order(referrer.ByID(sql.OrderDesc())). - Limit(p.Limit + 1) // fetch limit+1 to detect next page - - if p.Cursor != nil { - q = q.Where(func(s *sql.Selector) { - s.Where(sql.CompositeLT( - []string{s.C(referrer.FieldCreatedAt), s.C(referrer.FieldID)}, - p.Cursor.Timestamp, p.Cursor.ID, - )) - }) - } - - refs, err := q.All(ctx) + rows, err := r.referencesPage(ctx, root.ID, allowedOrgs, predicateReferrer, p) if err != nil { - return nil, "", fmt.Errorf("failed to query references: %w", err) + return nil, "", err } // Determine if there is a next page and encode the cursor var nextCursor string - if len(refs) > p.Limit { - lastVisible := refs[p.Limit-1] - nextCursor = pagination.EncodeCursor(lastVisible.CreatedAt, lastVisible.ID) - refs = refs[:p.Limit] + if len(rows) > p.Limit { + lastVisible := rows[p.Limit-1] + nextCursor = pagination.EncodeCursor(lastVisible.CreatedAt, lastVisible.ReferredByID) + rows = rows[:p.Limit] } // Add the references to the result - for _, reference := range refs { + for _, row := range rows { + reference := row.Edges.ReferredBy + // A referrer deleted since the page was read is left out. It still counts for the cursor + // above, so the next page starts after it. + if reference == nil { + continue + } // Call recursively the function — pagination only applies to the first level ref, _, err := r.doGet(ctx, reference, allowedOrgs, visibleProjectsMap, projectPred, nil, level+1) if err != nil && !biz.IsErrUnauthorized(err) { @@ -487,11 +492,17 @@ func (r *ReferrerRepo) doGet(ctx context.Context, root *ent.Referrer, allowedOrg // absence from the page alone (a later page can be empty simply because we paged past the // results), so we run a pagination-independent existence check before rejecting the root. if projectFilterActive && level == 0 && root.Kind != biz.ReferrerAttestationType && len(res.References) == 0 { - inProject, err := root.QueryReferences(). + // It reads the same references as the pages: those stored in the allowed organizations, + // or with no organization. + inProject, err := r.data.DB.ReferrerReference.Query(). Where( - referrer.KindEQ(biz.ReferrerAttestationType), - projectPred, - referrerVisibleToOrgs(allowedOrgs), + referrerreference.ReferrerID(root.ID), + referenceStoredInOrgs(allowedOrgs), + referrerreference.HasReferredByWith( + referrer.KindEQ(biz.ReferrerAttestationType), + projectPred, + referrerVisibleToOrgs(allowedOrgs), + ), ). Exist(ctx) if err != nil { @@ -505,6 +516,111 @@ func (r *ReferrerRepo) doGet(ctx context.Context, root *ent.Referrer, allowedOrg return res, nextCursor, nil } +// referencesPage returns up to p.Limit+1 references of the root, newest first, with the referenced +// referrer and its workflows loaded on the first p.Limit. The extra row tells the caller that there +// is a next page. A row whose referrer was deleted in between has no referrer loaded. +// +// The rows carry the creation time of the referrer they point to and the organization that stored +// them, and the index on (referrer_id, organization_id, created_at DESC, referred_by_id DESC) +// returns the references of one organization in page order. So the database reads one range per +// allowed organization, plus the range of references with no organization, and stops each range +// after the page, instead of sorting every reference of the root. A material shared by many +// attestations has tens of thousands, mostly stored in other organizations. The ranges are merged +// here, and each row is in one range only. +// +// Inside each range, the referenced referrer is checked against the predicates row by row: +// HasReferredByWith renders a correlated EXISTS, which keeps the query on the index. The check +// still applies to references with an organization, because a workflow can be deleted. +func (r *ReferrerRepo) referencesPage(ctx context.Context, rootID uuid.UUID, allowedOrgs []uuid.UUID, predicateReferrer []predicate.Referrer, p *pagination.CursorOptions) ([]*ent.ReferrerReference, error) { + limit := p.Limit + 1 // fetch limit+1 to detect next page + + ranges := make([]predicate.ReferrerReference, 0, len(allowedOrgs)+1) + ranges = append(ranges, referrerreference.OrganizationIDIsNil()) + // One range per distinct organization, or a reference would be returned twice + for _, orgID := range slices.Compact(slices.SortedFunc(slices.Values(allowedOrgs), func(a, b uuid.UUID) int { + return bytes.Compare(a[:], b[:]) + })) { + ranges = append(ranges, referrerreference.OrganizationID(orgID)) + } + + var rows []*ent.ReferrerReference + for _, inRange := range ranges { + q := r.data.DB.ReferrerReference.Query(). + Where( + referrerreference.ReferrerID(rootID), + inRange, + referrerreference.HasReferredByWith(predicateReferrer...), + ). + Order( + referrerreference.ByCreatedAt(sql.OrderDesc()), + referrerreference.ByReferredByID(sql.OrderDesc()), + ). + Limit(limit) + + if p.Cursor != nil { + q = q.Where(func(s *sql.Selector) { + s.Where(sql.CompositeLT( + []string{s.C(referrerreference.FieldCreatedAt), s.C(referrerreference.FieldReferredByID)}, + p.Cursor.Timestamp, p.Cursor.ID, + )) + }) + } + + page, err := q.All(ctx) + if err != nil { + return nil, fmt.Errorf("failed to query references: %w", err) + } + rows = append(rows, page...) + } + + // Merge the ranges in the order of the index: newest first, then by referenced ID, descending. + // Postgres compares UUIDs byte by byte, like bytes.Compare. + slices.SortFunc(rows, func(a, b *ent.ReferrerReference) int { + if c := b.CreatedAt.Compare(a.CreatedAt); c != 0 { + return c + } + return bytes.Compare(b.ReferredByID[:], a.ReferredByID[:]) + }) + if len(rows) > limit { + rows = rows[:limit] + } + if len(rows) == 0 { + return rows, nil + } + + // Load the referenced referrers of the page and their workflows in one query. The extra row + // only tells that there is a next page, so it is not loaded. + visible := rows[:min(len(rows), p.Limit)] + ids := make([]uuid.UUID, 0, len(visible)) + for _, row := range visible { + ids = append(ids, row.ReferredByID) + } + referenced, err := r.data.DB.Referrer.Query().Where(referrer.IDIn(ids...)).WithWorkflows().All(ctx) + if err != nil { + return nil, fmt.Errorf("failed to load references: %w", err) + } + byID := make(map[uuid.UUID]*ent.Referrer, len(referenced)) + for _, ref := range referenced { + byID[ref.ID] = ref + } + + // A referrer deleted since the first query is not found, and its row keeps no referrer + for _, row := range visible { + row.Edges.ReferredBy = byID[row.ReferredByID] + } + + return rows, nil +} + +// referenceStoredInOrgs matches a reference stored in one of the given organizations, or with no +// organization, which means that it can belong to any of them. +func referenceStoredInOrgs(orgIDs []uuid.UUID) predicate.ReferrerReference { + return referrerreference.Or( + referrerreference.OrganizationIDIsNil(), + referrerreference.OrganizationIDIn(orgIDs...), + ) +} + // isReferrerVisible reports whether the referrer, attached to the given projects of each organization, // is visible in at least one allowed organization. Project visibility is evaluated per organization, // like projectVisibilityPredicate: only the referrer's projects of an organization are compared with diff --git a/app/controlplane/pkg/data/referrer_references_integration_test.go b/app/controlplane/pkg/data/referrer_references_integration_test.go new file mode 100644 index 000000000..3fe97903e --- /dev/null +++ b/app/controlplane/pkg/data/referrer_references_integration_test.go @@ -0,0 +1,389 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package data_test + +import ( + "context" + "fmt" + "os" + "slices" + "strings" + "testing" + "time" + + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/biz" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/biz/testhelpers" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/referrer" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/referrerreference" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/pagination" + "github.com/google/uuid" + "github.com/stretchr/testify/suite" +) + +// A material shared by many attestations, such as an identical scanner report, collects one +// reference per attestation in every organization. Discovery pages over those references newest +// first, so each page must be read in order from the references of the root instead of sorting +// all of them. +func TestReferrerReferencesIntegration(t *testing.T) { + suite.Run(t, new(referrerReferencesIntegrationTestSuite)) +} + +type referrerReferencesIntegrationTestSuite struct { + testhelpers.UseCasesEachTestSuite + + orgA, orgB uuid.UUID + wfA, wfB uuid.UUID + // the material every attestation references + materialDigest string + // the attestations in storage order, oldest first + attestations []storedAttestation +} + +type storedAttestation struct { + digest string + org uuid.UUID +} + +// newestFirst returns the digests of the attestations stored in the given organizations, newest +// first. +func (s *referrerReferencesIntegrationTestSuite) newestFirst(orgs ...uuid.UUID) []string { + var digests []string + for _, att := range s.attestations { + if slices.Contains(orgs, att.org) { + digests = append(digests, att.digest) + } + } + slices.Reverse(digests) + return digests +} + +const sharedMaterialKind = "GITLEAKS_JSON" + +func (s *referrerReferencesIntegrationTestSuite) SetupTest() { + s.UseCasesEachTestSuite.SetupTest() + ctx := context.Background() + s.attestations = nil + + newWorkflow := func() (uuid.UUID, uuid.UUID) { + org, err := s.Organization.CreateWithRandomName(ctx) + s.Require().NoError(err) + wf, err := s.Workflow.Create(ctx, &biz.WorkflowCreateOpts{Name: "wf", OrgID: org.ID, Project: "project"}) + s.Require().NoError(err) + return uuid.MustParse(org.ID), wf.ID + } + + s.orgA, s.wfA = newWorkflow() + s.orgB, s.wfB = newWorkflow() + s.materialDigest = fmt.Sprintf("sha256:%064d", 0) + + store := func(orgID, wfID uuid.UUID) { + digest := fmt.Sprintf("sha256:%064d", len(s.attestations)+1) + s.saveAttestation(digest, wfID) + s.attestations = append(s.attestations, storedAttestation{digest: digest, org: orgID}) + } + + // Interleave the organizations so that the newest-first order mixes them. + for range 3 { + store(s.orgA, s.wfA) + store(s.orgB, s.wfB) + } + store(s.orgA, s.wfA) + store(s.orgA, s.wfA) +} + +// saveAttestation stores an attestation of the shared material in the given workflow, as the +// attestation extraction does, with any other attestations as materials. +func (s *referrerReferencesIntegrationTestSuite) saveAttestation(digest string, wfID uuid.UUID, attestationMaterials ...string) { + s.T().Helper() + att := &biz.Referrer{Digest: digest, Kind: biz.ReferrerAttestationType, Downloadable: true} + material := &biz.Referrer{Digest: s.materialDigest, Kind: sharedMaterialKind, Downloadable: true} + // both directions, as the attestation extraction stores them + att.References = []*biz.Referrer{{Digest: material.Digest, Kind: material.Kind}} + material.References = []*biz.Referrer{{Digest: att.Digest, Kind: att.Kind}} + referrers := make([]*biz.Referrer, 0, 2+len(attestationMaterials)) + referrers = append(referrers, att, material) + for _, d := range attestationMaterials { + att.References = append(att.References, &biz.Referrer{Digest: d, Kind: biz.ReferrerAttestationType}) + referrers = append(referrers, &biz.Referrer{ + Digest: d, Kind: biz.ReferrerAttestationType, Downloadable: true, + References: []*biz.Referrer{{Digest: att.Digest, Kind: att.Kind}}, + }) + } + s.Require().NoError(s.Repos.Referrer.Save(context.Background(), referrers, wfID)) +} + +// idOf returns the ID of the referrer with the given digest. +func (s *referrerReferencesIntegrationTestSuite) idOf(digest string) uuid.UUID { + s.T().Helper() + return s.Data.DB.Referrer.Query().Where(referrer.Digest(digest)).OnlyIDX(context.Background()) +} + +func (s *referrerReferencesIntegrationTestSuite) TestReferenceStoredColumns() { + ctx := context.Background() + client := s.Data.DB + + createdAt := make(map[uuid.UUID]int64) + for _, r := range client.Referrer.Query().AllX(ctx) { + createdAt[r.ID] = r.CreatedAt.UnixMicro() + } + orgOf := make(map[uuid.UUID]uuid.UUID) + for _, att := range s.attestations { + orgOf[s.idOf(att.digest)] = att.org + } + + refs := client.ReferrerReference.Query().AllX(ctx) + // each attestation has a reference to the material and one back + s.Require().Len(refs, 2*len(s.attestations)) + for _, ref := range refs { + // The material was stored with the first attestation. Every later reference to it must + // still carry the material's own creation time, not the time the reference was stored. + s.Equal(createdAt[ref.ReferredByID], ref.CreatedAt.UnixMicro(), + "reference %s -> %s", ref.ReferrerID, ref.ReferredByID) + + // one end of each reference is the attestation that stored it + org, ok := orgOf[ref.ReferrerID] + if !ok { + org = orgOf[ref.ReferredByID] + } + s.Require().NotNil(ref.OrganizationID, "reference %s -> %s", ref.ReferrerID, ref.ReferredByID) + s.Equal(org, *ref.OrganizationID, "reference %s -> %s", ref.ReferrerID, ref.ReferredByID) + } +} + +// The same attestation can be stored again in a run of another organization. Its references then +// belong to both organizations: they lose their organization and are read in both. +func (s *referrerReferencesIntegrationTestSuite) TestReferenceStoredFromTwoOrganizations() { + ctx := context.Background() + client := s.Data.DB + + first := s.attestations[0] + s.Require().Equal(s.orgA, first.org) + s.saveAttestation(first.digest, s.wfB) + + firstID := s.idOf(first.digest) + for _, ref := range client.ReferrerReference.Query().AllX(ctx) { + if ref.ReferrerID == firstID || ref.ReferredByID == firstID { + s.Nil(ref.OrganizationID, "reference %s -> %s", ref.ReferrerID, ref.ReferredByID) + } else { + s.NotNil(ref.OrganizationID, "reference %s -> %s", ref.ReferrerID, ref.ReferredByID) + } + } + + // Storing it again in the same organization leaves the references as they are + s.saveAttestation(s.attestations[1].digest, s.wfB) + secondID := s.idOf(s.attestations[1].digest) + for _, ref := range client.ReferrerReference.Query().AllX(ctx) { + if ref.ReferrerID == secondID || ref.ReferredByID == secondID { + s.Require().NotNil(ref.OrganizationID) + s.Equal(s.orgB, *ref.OrganizationID) + } + } + + // The first attestation is now read in both organizations, in its place in the order + got, _ := s.collectPages([]uuid.UUID{s.orgB}, 2) + s.Equal(append(s.newestFirst(s.orgB), first.digest), got) + got, _ = s.collectPages([]uuid.UUID{s.orgA}, 2) + s.Equal(s.newestFirst(s.orgA), got) + got, _ = s.collectPages([]uuid.UUID{s.orgA, s.orgB}, 3) + s.Equal(s.newestFirst(s.orgA, s.orgB), got) +} + +// An attestation can be a material of an attestation in another organization. That links it to +// the other organization too, but the references that its own organization stored stay there: +// the other organization reads it only through the references that its own attestation stored. +func (s *referrerReferencesIntegrationTestSuite) TestAttestationMaterialFromAnotherOrganization() { + fromA := s.attestations[0] + s.Require().Equal(s.orgA, fromA.org) + + inB := fmt.Sprintf("sha256:%064d", 100) + s.saveAttestation(inB, s.wfB, fromA.digest) + + // Through the shared material, organization B reads its own attestations only + got, _ := s.collectPages([]uuid.UUID{s.orgB}, 20) + s.Equal(append([]string{inB}, s.newestFirst(s.orgB)...), got) + + // Through its own attestation, organization B reads the attestation of organization A + got, _ = s.collectPagesFrom(inB, []uuid.UUID{s.orgB}, 20) + s.ElementsMatch([]string{s.materialDigest, fromA.digest}, got) +} + +// The migration fills in the organization of the existing references from the organizations both +// ends belong to, since nothing recorded which attestation stored them. It must give what storing +// them gives, or NULL where it cannot tell: NULL is read in every organization, so it never hides +// a reference. +func (s *referrerReferencesIntegrationTestSuite) TestBackfillMatchesTheStoredOrganization() { + ctx := context.Background() + client := s.Data.DB + + // Add the cases that link a referrer to more than one organization + repushed := s.attestations[0] + s.saveAttestation(repushed.digest, s.wfB) + fromA := s.attestations[2] + s.Require().Equal(s.orgA, fromA.org) + s.saveAttestation(fmt.Sprintf("sha256:%064d", 100), s.wfB, fromA.digest) + + type key struct{ from, to uuid.UUID } + type value struct { + org *uuid.UUID + createdAt int64 + } + snapshot := func() map[key]value { + out := make(map[key]value) + for _, ref := range client.ReferrerReference.Query().AllX(ctx) { + out[key{ref.ReferrerID, ref.ReferredByID}] = value{ref.OrganizationID, ref.CreatedAt.UnixMicro()} + } + return out + } + stored := snapshot() + + _, err := s.Data.SQLDB.ExecContext(ctx, `UPDATE referrer_references SET organization_id = NULL, created_at = $1`, time.Now()) + s.Require().NoError(err) + _, err = s.Data.SQLDB.ExecContext(ctx, s.backfillStatement()) + s.Require().NoError(err) + backfilled := snapshot() + + materialID := s.idOf(s.materialDigest) + fromAID := s.idOf(fromA.digest) + s.Require().Len(backfilled, len(stored)) + for k, want := range stored { + got := backfilled[k] + s.Equal(want.createdAt, got.createdAt, "reference %s -> %s", k.from, k.to) + if (k == key{materialID, fromAID}) || (k == key{fromAID, materialID}) { + // Organization A stored these, but both ends are now in both organizations, so the + // migration cannot tell which one did. + s.Require().NotNil(want.org) + s.Nil(got.org, "reference %s -> %s", k.from, k.to) + continue + } + s.Equal(want.org, got.org, "reference %s -> %s", k.from, k.to) + } +} + +// backfillStatement returns the UPDATE of the migration that fills in the reference columns. +func (s *referrerReferencesIntegrationTestSuite) backfillStatement() string { + s.T().Helper() + migration, err := os.ReadFile("ent/migrate/migrations/20261116124543.sql") + s.Require().NoError(err) + for _, statement := range strings.Split(string(migration), ";\n") { + if strings.Contains(statement, "UPDATE \"referrer_references\"") { + return statement + } + } + s.Require().Fail("the migration has no backfill statement") + return "" +} + +// The organization of a reference only narrows what a page reads. A reference with no +// organization, or with the caller's organization, is still returned only when the caller can see +// the referrer it points to. +func (s *referrerReferencesIntegrationTestSuite) TestOrganizationNeverGrantsVisibility() { + ctx := context.Background() + client := s.Data.DB + + // Two attestations visible in organization B only, referenced from the shared material + onlyInB := func(n int) *ent.Referrer { + return client.Referrer.Create().SetDigest(fmt.Sprintf("sha256:%064d", n)). + SetKind(biz.ReferrerAttestationType).SetDownloadable(true).AddWorkflowIDs(s.wfB).SaveX(ctx) + } + withNoOrg, withOrgA := onlyInB(200), onlyInB(201) + materialID := s.idOf(s.materialDigest) + client.Referrer.UpdateOneID(materialID).AddReferenceIDs(withNoOrg.ID, withOrgA.ID).ExecX(ctx) + // One reference has no organization, the other claims organization A + client.ReferrerReference.Update(). + Where(referrerreference.ReferrerID(materialID), referrerreference.ReferredByID(withOrgA.ID)). + SetOrganizationID(s.orgA).ExecX(ctx) + + got, _ := s.collectPages([]uuid.UUID{s.orgA}, 2) + s.Equal(s.newestFirst(s.orgA), got, "organization A must not see referrers of organization B") + + got, _ = s.collectPages([]uuid.UUID{s.orgB}, 2) + s.Contains(got, withNoOrg.Digest, "a reference with no organization is read in organization B") + s.NotContains(got, withOrgA.Digest, "a reference stored in organization A is not read in organization B") +} + +func (s *referrerReferencesIntegrationTestSuite) TestPagesNewestFirst() { + testCases := []struct { + name string + orgs []uuid.UUID + limit int + }{ + {name: "one organization, pages of two", orgs: []uuid.UUID{s.orgA}, limit: 2}, + {name: "one organization, one page", orgs: []uuid.UUID{s.orgA}, limit: 20}, + {name: "other organization, pages of one", orgs: []uuid.UUID{s.orgB}, limit: 1}, + {name: "both organizations, pages of three", orgs: []uuid.UUID{s.orgA, s.orgB}, limit: 3}, + } + + for _, tc := range testCases { + s.Run(tc.name, func() { + want := s.newestFirst(tc.orgs...) + got, pages := s.collectPages(tc.orgs, tc.limit) + s.Equal(want, got) + s.Equal((len(want)+tc.limit-1)/tc.limit, pages) + }) + } +} + +// A reference stored without an explicit creation time, for example by a control plane that runs +// the previous release during a rolling upgrade, still takes part in the pages. It sorts by the +// time it was stored. +func (s *referrerReferencesIntegrationTestSuite) TestReferenceWithoutExplicitCreationTime() { + ctx := context.Background() + client := s.Data.DB + + material := client.Referrer.Query().Where(referrer.Digest(s.materialDigest)).OnlyX(ctx) + wf := client.Workflow.Query().FirstIDX(ctx) + late := client.Referrer.Create().SetDigest(fmt.Sprintf("sha256:%064d", 99)). + SetKind(biz.ReferrerAttestationType).SetDownloadable(true).AddWorkflowIDs(wf).SaveX(ctx) + client.Referrer.UpdateOneID(material.ID).AddReferenceIDs(late.ID).ExecX(ctx) + + orgs := []uuid.UUID{s.orgA, s.orgB} + got, _ := s.collectPages(orgs, 2) + s.Require().Len(got, len(s.attestations)+1) + s.Equal(late.Digest, got[0], "the latest stored reference comes first") +} + +// collectPages follows the cursor from the shared material and returns the attestation digests +// in the order they were returned, and the number of pages read. +func (s *referrerReferencesIntegrationTestSuite) collectPages(orgs []uuid.UUID, limit int) ([]string, int) { + return s.collectPagesFrom(s.materialDigest, orgs, limit) +} + +// collectPagesFrom follows the cursor from the given root. +func (s *referrerReferencesIntegrationTestSuite) collectPagesFrom(root string, orgs []uuid.UUID, limit int) ([]string, int) { + s.T().Helper() + ctx := context.Background() + + var digests []string + cursor, pages := "", 0 + for pages < 20 { + p, err := pagination.NewCursor(cursor, limit) + s.Require().NoError(err) + got, next, err := s.Repos.Referrer.GetFromRoot(ctx, root, orgs, p) + s.Require().NoError(err) + s.Require().NotNil(got) + pages++ + for _, ref := range got.References { + digests = append(digests, ref.Digest) + } + if next == "" { + break + } + cursor = next + } + + return digests, pages +} diff --git a/app/controlplane/pkg/data/referrer_visibility_integration_test.go b/app/controlplane/pkg/data/referrer_visibility_integration_test.go index 64ee84b51..14fd682a8 100644 --- a/app/controlplane/pkg/data/referrer_visibility_integration_test.go +++ b/app/controlplane/pkg/data/referrer_visibility_integration_test.go @@ -27,6 +27,7 @@ import ( "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/organization" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/predicate" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/referrer" + "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/referrerreference" "github.com/chainloop-dev/chainloop/app/controlplane/pkg/data/ent/workflow" "github.com/google/uuid" "github.com/stretchr/testify/suite" @@ -206,18 +207,26 @@ func (s *referrerVisibilityIntegrationTestSuite) TestMatchesTheGeneratedPredicat s.NotEmpty(handWritten, "the fixture must exercise this, not pass by returning nothing") }) - // doGet applies the filter to root.QueryReferences(), a different query shape where the - // selector is already joined through the references table. - s.Run("behaves the same when traversing references", func() { + // doGet's pages and its project membership check read the reference rows of the root and apply + // the filter to the referenced referrer inside a correlated EXISTS. + s.Run("behaves the same inside the references page query", func() { orgs := []uuid.UUID{s.orgAllowed, s.orgOther} - root := s.Data.DB.Referrer.GetX(ctx, s.liveInAllowed) - - generated, err := root.QueryReferences().Where(generatedVisibilityPredicate(orgs)).IDs(ctx) - s.Require().NoError(err) - handWritten, err := root.QueryReferences().Where(data.ReferrerVisibleToOrgsForTest(orgs)).Unique(false).IDs(ctx) - s.Require().NoError(err) + referenced := func(p predicate.Referrer) []uuid.UUID { + rows := s.Data.DB.ReferrerReference.Query(). + Where( + referrerreference.ReferrerID(s.liveInAllowed), + referrerreference.HasReferredByWith(p), + ). + AllX(ctx) + ids := make([]uuid.UUID, 0, len(rows)) + for _, row := range rows { + ids = append(ids, row.ReferredByID) + } + return sortIDs(ids) + } - s.Equal(sortIDs(generated), sortIDs(handWritten)) + handWritten := referenced(data.ReferrerVisibleToOrgsForTest(orgs)) + s.Equal(referenced(generatedVisibilityPredicate(orgs)), handWritten) s.NotEmpty(handWritten, "the fixture must exercise this, not pass by returning nothing") }) }