Compare commits

...

7 Commits

Author SHA1 Message Date
Jeff McCune
ad70a6c4fe (#150) Add holos.v1alpha1.PlatformService.AddPlatform
This patch adds a basic AddPlatform method that adds a platform with a
name and a display name.

Next steps are to add fields for the Platform Config Form definition and
the Platform Config values submitted from the form.
2024-04-29 09:35:49 -07:00
Jeff McCune
22a04da6bb (#150) Add holos.v1alpha1.PlatformService.GetPlatforms
Next step: AddPlatform

Also consider extracting the queries to get the requested org_id to a
helper function.  This will likely eventually move to an interceptor
because every request is org scoped and needs authorization checks
against the org.

```
grpcurl -H "x-oidc-id-token: $(holos token)" -d '{"org_id":"018f27cd-e5ac-7f98-bfe1-2dbab208a48c"}' jeff.app.dev.k2.holos.run:443 holos.v1alpha1.PlatformService.GetPlatforms
```
2024-04-28 20:21:32 -07:00
Jeff McCune
dc97fe0ff0 (#150) Define a PlatformForm for platform design
Problem:
Platform engineers need the ability to define custom input fields for
their own platform level configuration values.  The holos web UI needs
to present the platform config values in a clean way.  The values
entered on the form need to make their way into the top level
Platform.spec field for use across all components and clusters in the
platform.

Solution:
Define a Platform Form in a forms cue package.  The output of this
definition is intended to be sent to the holos server to provide to the
web UI.

Result:
Platform engineers can define their platform config input values in
their infrastructure repository.  For example, the bare platform form
inputs are defined at `platforms/bare/forms/platform/platform-form.cue`.

This cue file produces [FormlyFieldConfig][1] output.

```console
cue export ./forms/platform/ --out yaml
```

```yaml
apiVersion: forms.holos.run/v1alpha1
kind: PlatformForm
metadata:
  name: bare
spec:
  sections:
    - name: org
      displayName: Organization
      description: Organization config values are used to derive more specific configuration values throughout the platform.
      fieldConfigs:
        - key: name
          type: input
          props:
            label: Name
            placeholder: example
            description: DNS label, e.g. 'example'
            required: true
        - key: domain
          type: input
          props:
            label: Domain
            placeholder: example.com
            description: DNS domain, e.g. 'example.com'
            required: true
        - key: displayName
          type: input
          props:
            label: Display Name
            placeholder: Example Organization
            description: Display name, e.g. 'Example Organization'
            required: true
        - key: contactEmail
          type: input
          props:
            label: Contact Email
            placeholder: platform-team@example.com
            description: Technical contact email address
            required: true
```

Next Steps:
Add a holos subcommand to produce the output and store it in the
backend.  Wire the front end to fetch the form config from the backend.

[1]: https://formly.dev/docs/api/core#formlyfieldconfig
2024-04-28 11:25:06 -07:00
Jeff McCune
9ca97c6e01 Merge pull request #148 from holos-run/jeff/147-cue-oom
(#147) Add holos render --print-instances flag
2024-04-26 16:31:14 -07:00
Jeff McCune
924653e240 (#150) Bare Platform
This patch adds a bare platform that does nothing but render a configmap
containing the platform config structure itself.

The definition of the platform structure is firming up.  The platform
designer, which may be a holos customer, is responsible for defining the
structure of the `platform.spec` output field.

Us holos developers have a reserved namespace to add configuration
fields and data in the `platform.holos` output file.

Beyond these two fields, the platform config structure has TypeMeta and
ObjectMeta fields similar to a kubernetes api object to support
versioning the platform config data, naming the platform, annotating the
platform, and labeling the platform.

The path forward from here is to:

 1. Eventually move the stable definitions into a CUE module that gets
    imported into the user's package.
 2. As a platform designer, add the organization field to the
    #PlatformSpec definition as a CUE definition.
 3. As a platform designer, add the organization field Form data
    structure as a JSON file.
 4. Add an API to upload the #PlatformSpec cue file and the
    #PlatformSpec form json file to the saas backend.
 5. Wire up Angular to pull the form json from the API and render the
    form.
 6. Wire up Angular to write the form data to a gRPC service method.
 7. Wire up the `holos cli` to read the form data from a gRPC service
    method.
 8. Tie it all together where the holos cli renders the configmap.
2024-04-26 16:14:30 -07:00
Jeff McCune
59d48f8599 (#146) Platform Config Mock Up
This patch adds a mock up of the platform config.  The goal is to use
this to connect to an anemic example platform built from `holos init`.
2024-04-26 11:29:58 -07:00
Jeff McCune
9ae45e260d (#147) Add holos render --print-instances flag
To enumerate all of the instances that could be run in separate
processes with xargs instead of run in the for loop in the Builder Run
method.
2024-04-25 13:59:10 -07:00
120 changed files with 16763 additions and 55 deletions

View File

@@ -9,8 +9,9 @@ import (
type BuildPlan struct {
TypeMeta `json:",inline" yaml:",inline"`
// Metadata represents the holos component name
Metadata ObjectMeta `json:"metadata,omitempty" yaml:"metadata,omitempty"`
Spec BuildPlanSpec `json:"spec,omitempty" yaml:"spec,omitempty"`
Metadata ObjectMeta `json:"metadata,omitempty" yaml:"metadata,omitempty"`
Spec BuildPlanSpec `json:"spec,omitempty" yaml:"spec,omitempty"`
Platform map[string]any `json:"platform,omitempty" yaml:"platform,omitempty"`
}
type BuildPlanSpec struct {

View File

@@ -1,6 +1,7 @@
package render
import (
"flag"
"fmt"
"github.com/holos-run/holos/internal/cli/command"
@@ -11,8 +12,21 @@ import (
"github.com/spf13/cobra"
)
func makeRenderRunFunc(cfg *holos.Config) command.RunFunc {
return func(cmd *cobra.Command, args []string) error {
// New returns the render subcommand for the root command
func New(cfg *holos.Config) *cobra.Command {
cmd := command.New("render [directory...]")
cmd.Args = cobra.MinimumNArgs(1)
cmd.Short = "write kubernetes api objects to the filesystem"
cmd.Flags().SortFlags = false
cmd.Flags().AddGoFlagSet(cfg.WriteFlagSet())
cmd.Flags().AddGoFlagSet(cfg.ClusterFlagSet())
var printInstances bool
flagSet := flag.NewFlagSet("", flag.ContinueOnError)
flagSet.BoolVar(&printInstances, "print-instances", false, "expand /... paths for xargs")
cmd.Flags().AddGoFlagSet(flagSet)
cmd.RunE = func(cmd *cobra.Command, args []string) error {
if cfg.ClusterName() == "" {
return errors.Wrap(fmt.Errorf("missing cluster name"))
}
@@ -20,6 +34,18 @@ func makeRenderRunFunc(cfg *holos.Config) command.RunFunc {
ctx := cmd.Context()
log := logger.FromContext(ctx).With("cluster", cfg.ClusterName())
build := builder.New(builder.Entrypoints(args), builder.Cluster(cfg.ClusterName()))
if printInstances {
instances, err := build.Instances(ctx)
if err != nil {
return errors.Wrap(err)
}
for _, instance := range instances {
fmt.Fprintln(cmd.OutOrStdout(), instance.Dir)
}
return nil
}
results, err := build.Run(cmd.Context())
if err != nil {
return errors.Wrap(err)
@@ -45,16 +71,5 @@ func makeRenderRunFunc(cfg *holos.Config) command.RunFunc {
}
return nil
}
}
// New returns the render subcommand for the root command
func New(cfg *holos.Config) *cobra.Command {
cmd := command.New("render [directory...]")
cmd.Args = cobra.MinimumNArgs(1)
cmd.Short = "write kubernetes api objects to the filesystem"
cmd.Flags().SortFlags = false
cmd.Flags().AddGoFlagSet(cfg.WriteFlagSet())
cmd.Flags().AddGoFlagSet(cfg.ClusterFlagSet())
cmd.RunE = makeRenderRunFunc(cfg)
return cmd
}

View File

@@ -17,6 +17,7 @@ import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/holos-run/holos/internal/ent/organization"
"github.com/holos-run/holos/internal/ent/platform"
"github.com/holos-run/holos/internal/ent/user"
)
@@ -27,6 +28,8 @@ type Client struct {
Schema *migrate.Schema
// Organization is the client for interacting with the Organization builders.
Organization *OrganizationClient
// Platform is the client for interacting with the Platform builders.
Platform *PlatformClient
// User is the client for interacting with the User builders.
User *UserClient
}
@@ -41,6 +44,7 @@ func NewClient(opts ...Option) *Client {
func (c *Client) init() {
c.Schema = migrate.NewSchema(c.driver)
c.Organization = NewOrganizationClient(c.config)
c.Platform = NewPlatformClient(c.config)
c.User = NewUserClient(c.config)
}
@@ -135,6 +139,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) {
ctx: ctx,
config: cfg,
Organization: NewOrganizationClient(cfg),
Platform: NewPlatformClient(cfg),
User: NewUserClient(cfg),
}, nil
}
@@ -156,6 +161,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
ctx: ctx,
config: cfg,
Organization: NewOrganizationClient(cfg),
Platform: NewPlatformClient(cfg),
User: NewUserClient(cfg),
}, nil
}
@@ -186,6 +192,7 @@ func (c *Client) Close() error {
// In order to add hooks to a specific client, call: `client.Node.Use(...)`.
func (c *Client) Use(hooks ...Hook) {
c.Organization.Use(hooks...)
c.Platform.Use(hooks...)
c.User.Use(hooks...)
}
@@ -193,6 +200,7 @@ func (c *Client) Use(hooks ...Hook) {
// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`.
func (c *Client) Intercept(interceptors ...Interceptor) {
c.Organization.Intercept(interceptors...)
c.Platform.Intercept(interceptors...)
c.User.Intercept(interceptors...)
}
@@ -201,6 +209,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
switch m := m.(type) {
case *OrganizationMutation:
return c.Organization.mutate(ctx, m)
case *PlatformMutation:
return c.Platform.mutate(ctx, m)
case *UserMutation:
return c.User.mutate(ctx, m)
default:
@@ -348,6 +358,22 @@ func (c *OrganizationClient) QueryUsers(o *Organization) *UserQuery {
return query
}
// QueryPlatforms queries the platforms edge of a Organization.
func (c *OrganizationClient) QueryPlatforms(o *Organization) *PlatformQuery {
query := (&PlatformClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := o.ID
step := sqlgraph.NewStep(
sqlgraph.From(organization.Table, organization.FieldID, id),
sqlgraph.To(platform.Table, platform.FieldID),
sqlgraph.Edge(sqlgraph.O2M, true, organization.PlatformsTable, organization.PlatformsColumn),
)
fromV = sqlgraph.Neighbors(o.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *OrganizationClient) Hooks() []Hook {
return c.hooks.Organization
@@ -373,6 +399,171 @@ func (c *OrganizationClient) mutate(ctx context.Context, m *OrganizationMutation
}
}
// PlatformClient is a client for the Platform schema.
type PlatformClient struct {
config
}
// NewPlatformClient returns a client for the Platform from the given config.
func NewPlatformClient(c config) *PlatformClient {
return &PlatformClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `platform.Hooks(f(g(h())))`.
func (c *PlatformClient) Use(hooks ...Hook) {
c.hooks.Platform = append(c.hooks.Platform, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `platform.Intercept(f(g(h())))`.
func (c *PlatformClient) Intercept(interceptors ...Interceptor) {
c.inters.Platform = append(c.inters.Platform, interceptors...)
}
// Create returns a builder for creating a Platform entity.
func (c *PlatformClient) Create() *PlatformCreate {
mutation := newPlatformMutation(c.config, OpCreate)
return &PlatformCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Platform entities.
func (c *PlatformClient) CreateBulk(builders ...*PlatformCreate) *PlatformCreateBulk {
return &PlatformCreateBulk{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 *PlatformClient) MapCreateBulk(slice any, setFunc func(*PlatformCreate, int)) *PlatformCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &PlatformCreateBulk{err: fmt.Errorf("calling to PlatformClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*PlatformCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &PlatformCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Platform.
func (c *PlatformClient) Update() *PlatformUpdate {
mutation := newPlatformMutation(c.config, OpUpdate)
return &PlatformUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *PlatformClient) UpdateOne(pl *Platform) *PlatformUpdateOne {
mutation := newPlatformMutation(c.config, OpUpdateOne, withPlatform(pl))
return &PlatformUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *PlatformClient) UpdateOneID(id uuid.UUID) *PlatformUpdateOne {
mutation := newPlatformMutation(c.config, OpUpdateOne, withPlatformID(id))
return &PlatformUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Platform.
func (c *PlatformClient) Delete() *PlatformDelete {
mutation := newPlatformMutation(c.config, OpDelete)
return &PlatformDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *PlatformClient) DeleteOne(pl *Platform) *PlatformDeleteOne {
return c.DeleteOneID(pl.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *PlatformClient) DeleteOneID(id uuid.UUID) *PlatformDeleteOne {
builder := c.Delete().Where(platform.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &PlatformDeleteOne{builder}
}
// Query returns a query builder for Platform.
func (c *PlatformClient) Query() *PlatformQuery {
return &PlatformQuery{
config: c.config,
ctx: &QueryContext{Type: TypePlatform},
inters: c.Interceptors(),
}
}
// Get returns a Platform entity by its id.
func (c *PlatformClient) Get(ctx context.Context, id uuid.UUID) (*Platform, error) {
return c.Query().Where(platform.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *PlatformClient) GetX(ctx context.Context, id uuid.UUID) *Platform {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryCreator queries the creator edge of a Platform.
func (c *PlatformClient) QueryCreator(pl *Platform) *UserQuery {
query := (&UserClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := pl.ID
step := sqlgraph.NewStep(
sqlgraph.From(platform.Table, platform.FieldID, id),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, platform.CreatorTable, platform.CreatorColumn),
)
fromV = sqlgraph.Neighbors(pl.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryOrganization queries the organization edge of a Platform.
func (c *PlatformClient) QueryOrganization(pl *Platform) *OrganizationQuery {
query := (&OrganizationClient{config: c.config}).Query()
query.path = func(context.Context) (fromV *sql.Selector, _ error) {
id := pl.ID
step := sqlgraph.NewStep(
sqlgraph.From(platform.Table, platform.FieldID, id),
sqlgraph.To(organization.Table, organization.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, platform.OrganizationTable, platform.OrganizationColumn),
)
fromV = sqlgraph.Neighbors(pl.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *PlatformClient) Hooks() []Hook {
return c.hooks.Platform
}
// Interceptors returns the client interceptors.
func (c *PlatformClient) Interceptors() []Interceptor {
return c.inters.Platform
}
func (c *PlatformClient) mutate(ctx context.Context, m *PlatformMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&PlatformCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&PlatformUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&PlatformUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&PlatformDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown Platform mutation op: %q", m.Op())
}
}
// UserClient is a client for the User schema.
type UserClient struct {
config
@@ -525,9 +716,9 @@ func (c *UserClient) mutate(ctx context.Context, m *UserMutation) (Value, error)
// hooks and interceptors per client, for fast access.
type (
hooks struct {
Organization, User []ent.Hook
Organization, Platform, User []ent.Hook
}
inters struct {
Organization, User []ent.Interceptor
Organization, Platform, User []ent.Interceptor
}
)

View File

@@ -13,6 +13,7 @@ import (
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/holos-run/holos/internal/ent/organization"
"github.com/holos-run/holos/internal/ent/platform"
"github.com/holos-run/holos/internal/ent/user"
)
@@ -75,6 +76,7 @@ func checkColumn(table, column string) error {
initCheck.Do(func() {
columnCheck = sql.NewColumnCheck(map[string]func(string) bool{
organization.Table: organization.ValidColumn,
platform.Table: platform.ValidColumn,
user.Table: user.ValidColumn,
})
})

View File

@@ -21,6 +21,18 @@ func (f OrganizationFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.OrganizationMutation", m)
}
// The PlatformFunc type is an adapter to allow the use of ordinary
// function as Platform mutator.
type PlatformFunc func(context.Context, *ent.PlatformMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f PlatformFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.PlatformMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.PlatformMutation", m)
}
// The UserFunc type is an adapter to allow the use of ordinary
// function as User mutator.
type UserFunc func(context.Context, *ent.UserMutation) (ent.Value, error)

View File

@@ -31,6 +31,36 @@ var (
},
},
}
// PlatformsColumns holds the columns for the "platforms" table.
PlatformsColumns = []*schema.Column{
{Name: "id", Type: field.TypeUUID},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
{Name: "name", Type: field.TypeString},
{Name: "display_name", Type: field.TypeString},
{Name: "creator_id", Type: field.TypeUUID},
{Name: "org_id", Type: field.TypeUUID},
}
// PlatformsTable holds the schema information for the "platforms" table.
PlatformsTable = &schema.Table{
Name: "platforms",
Columns: PlatformsColumns,
PrimaryKey: []*schema.Column{PlatformsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "platforms_users_creator",
Columns: []*schema.Column{PlatformsColumns[5]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.NoAction,
},
{
Symbol: "platforms_organizations_organization",
Columns: []*schema.Column{PlatformsColumns[6]},
RefColumns: []*schema.Column{OrganizationsColumns[0]},
OnDelete: schema.NoAction,
},
},
}
// UsersColumns holds the columns for the "users" table.
UsersColumns = []*schema.Column{
{Name: "id", Type: field.TypeUUID},
@@ -82,6 +112,7 @@ var (
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
OrganizationsTable,
PlatformsTable,
UsersTable,
OrganizationUsersTable,
}
@@ -89,6 +120,8 @@ var (
func init() {
OrganizationsTable.ForeignKeys[0].RefTable = UsersTable
PlatformsTable.ForeignKeys[0].RefTable = UsersTable
PlatformsTable.ForeignKeys[1].RefTable = OrganizationsTable
OrganizationUsersTable.ForeignKeys[0].RefTable = OrganizationsTable
OrganizationUsersTable.ForeignKeys[1].RefTable = UsersTable
}

View File

@@ -13,6 +13,7 @@ import (
"entgo.io/ent/dialect/sql"
"github.com/gofrs/uuid"
"github.com/holos-run/holos/internal/ent/organization"
"github.com/holos-run/holos/internal/ent/platform"
"github.com/holos-run/holos/internal/ent/predicate"
"github.com/holos-run/holos/internal/ent/user"
)
@@ -27,28 +28,32 @@ const (
// Node types.
TypeOrganization = "Organization"
TypePlatform = "Platform"
TypeUser = "User"
)
// OrganizationMutation represents an operation that mutates the Organization nodes in the graph.
type OrganizationMutation struct {
config
op Op
typ string
id *uuid.UUID
created_at *time.Time
updated_at *time.Time
name *string
display_name *string
clearedFields map[string]struct{}
creator *uuid.UUID
clearedcreator bool
users map[uuid.UUID]struct{}
removedusers map[uuid.UUID]struct{}
clearedusers bool
done bool
oldValue func(context.Context) (*Organization, error)
predicates []predicate.Organization
op Op
typ string
id *uuid.UUID
created_at *time.Time
updated_at *time.Time
name *string
display_name *string
clearedFields map[string]struct{}
creator *uuid.UUID
clearedcreator bool
users map[uuid.UUID]struct{}
removedusers map[uuid.UUID]struct{}
clearedusers bool
platforms map[uuid.UUID]struct{}
removedplatforms map[uuid.UUID]struct{}
clearedplatforms bool
done bool
oldValue func(context.Context) (*Organization, error)
predicates []predicate.Organization
}
var _ ent.Mutation = (*OrganizationMutation)(nil)
@@ -416,6 +421,60 @@ func (m *OrganizationMutation) ResetUsers() {
m.removedusers = nil
}
// AddPlatformIDs adds the "platforms" edge to the Platform entity by ids.
func (m *OrganizationMutation) AddPlatformIDs(ids ...uuid.UUID) {
if m.platforms == nil {
m.platforms = make(map[uuid.UUID]struct{})
}
for i := range ids {
m.platforms[ids[i]] = struct{}{}
}
}
// ClearPlatforms clears the "platforms" edge to the Platform entity.
func (m *OrganizationMutation) ClearPlatforms() {
m.clearedplatforms = true
}
// PlatformsCleared reports if the "platforms" edge to the Platform entity was cleared.
func (m *OrganizationMutation) PlatformsCleared() bool {
return m.clearedplatforms
}
// RemovePlatformIDs removes the "platforms" edge to the Platform entity by IDs.
func (m *OrganizationMutation) RemovePlatformIDs(ids ...uuid.UUID) {
if m.removedplatforms == nil {
m.removedplatforms = make(map[uuid.UUID]struct{})
}
for i := range ids {
delete(m.platforms, ids[i])
m.removedplatforms[ids[i]] = struct{}{}
}
}
// RemovedPlatforms returns the removed IDs of the "platforms" edge to the Platform entity.
func (m *OrganizationMutation) RemovedPlatformsIDs() (ids []uuid.UUID) {
for id := range m.removedplatforms {
ids = append(ids, id)
}
return
}
// PlatformsIDs returns the "platforms" edge IDs in the mutation.
func (m *OrganizationMutation) PlatformsIDs() (ids []uuid.UUID) {
for id := range m.platforms {
ids = append(ids, id)
}
return
}
// ResetPlatforms resets all changes to the "platforms" edge.
func (m *OrganizationMutation) ResetPlatforms() {
m.platforms = nil
m.clearedplatforms = false
m.removedplatforms = nil
}
// Where appends a list predicates to the OrganizationMutation builder.
func (m *OrganizationMutation) Where(ps ...predicate.Organization) {
m.predicates = append(m.predicates, ps...)
@@ -617,13 +676,16 @@ func (m *OrganizationMutation) ResetField(name string) error {
// AddedEdges returns all edge names that were set/added in this mutation.
func (m *OrganizationMutation) AddedEdges() []string {
edges := make([]string, 0, 2)
edges := make([]string, 0, 3)
if m.creator != nil {
edges = append(edges, organization.EdgeCreator)
}
if m.users != nil {
edges = append(edges, organization.EdgeUsers)
}
if m.platforms != nil {
edges = append(edges, organization.EdgePlatforms)
}
return edges
}
@@ -641,16 +703,25 @@ func (m *OrganizationMutation) AddedIDs(name string) []ent.Value {
ids = append(ids, id)
}
return ids
case organization.EdgePlatforms:
ids := make([]ent.Value, 0, len(m.platforms))
for id := range m.platforms {
ids = append(ids, id)
}
return ids
}
return nil
}
// RemovedEdges returns all edge names that were removed in this mutation.
func (m *OrganizationMutation) RemovedEdges() []string {
edges := make([]string, 0, 2)
edges := make([]string, 0, 3)
if m.removedusers != nil {
edges = append(edges, organization.EdgeUsers)
}
if m.removedplatforms != nil {
edges = append(edges, organization.EdgePlatforms)
}
return edges
}
@@ -664,19 +735,28 @@ func (m *OrganizationMutation) RemovedIDs(name string) []ent.Value {
ids = append(ids, id)
}
return ids
case organization.EdgePlatforms:
ids := make([]ent.Value, 0, len(m.removedplatforms))
for id := range m.removedplatforms {
ids = append(ids, id)
}
return ids
}
return nil
}
// ClearedEdges returns all edge names that were cleared in this mutation.
func (m *OrganizationMutation) ClearedEdges() []string {
edges := make([]string, 0, 2)
edges := make([]string, 0, 3)
if m.clearedcreator {
edges = append(edges, organization.EdgeCreator)
}
if m.clearedusers {
edges = append(edges, organization.EdgeUsers)
}
if m.clearedplatforms {
edges = append(edges, organization.EdgePlatforms)
}
return edges
}
@@ -688,6 +768,8 @@ func (m *OrganizationMutation) EdgeCleared(name string) bool {
return m.clearedcreator
case organization.EdgeUsers:
return m.clearedusers
case organization.EdgePlatforms:
return m.clearedplatforms
}
return false
}
@@ -713,10 +795,728 @@ func (m *OrganizationMutation) ResetEdge(name string) error {
case organization.EdgeUsers:
m.ResetUsers()
return nil
case organization.EdgePlatforms:
m.ResetPlatforms()
return nil
}
return fmt.Errorf("unknown Organization edge %s", name)
}
// PlatformMutation represents an operation that mutates the Platform nodes in the graph.
type PlatformMutation struct {
config
op Op
typ string
id *uuid.UUID
created_at *time.Time
updated_at *time.Time
name *string
display_name *string
clearedFields map[string]struct{}
creator *uuid.UUID
clearedcreator bool
organization *uuid.UUID
clearedorganization bool
done bool
oldValue func(context.Context) (*Platform, error)
predicates []predicate.Platform
}
var _ ent.Mutation = (*PlatformMutation)(nil)
// platformOption allows management of the mutation configuration using functional options.
type platformOption func(*PlatformMutation)
// newPlatformMutation creates new mutation for the Platform entity.
func newPlatformMutation(c config, op Op, opts ...platformOption) *PlatformMutation {
m := &PlatformMutation{
config: c,
op: op,
typ: TypePlatform,
clearedFields: make(map[string]struct{}),
}
for _, opt := range opts {
opt(m)
}
return m
}
// withPlatformID sets the ID field of the mutation.
func withPlatformID(id uuid.UUID) platformOption {
return func(m *PlatformMutation) {
var (
err error
once sync.Once
value *Platform
)
m.oldValue = func(ctx context.Context) (*Platform, error) {
once.Do(func() {
if m.done {
err = errors.New("querying old values post mutation is not allowed")
} else {
value, err = m.Client().Platform.Get(ctx, id)
}
})
return value, err
}
m.id = &id
}
}
// withPlatform sets the old Platform of the mutation.
func withPlatform(node *Platform) platformOption {
return func(m *PlatformMutation) {
m.oldValue = func(context.Context) (*Platform, error) {
return node, nil
}
m.id = &node.ID
}
}
// Client returns a new `ent.Client` from the mutation. If the mutation was
// executed in a transaction (ent.Tx), a transactional client is returned.
func (m PlatformMutation) 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 PlatformMutation) Tx() (*Tx, error) {
if _, ok := m.driver.(*txDriver); !ok {
return nil, errors.New("ent: mutation is not running in a transaction")
}
tx := &Tx{config: m.config}
tx.init()
return tx, nil
}
// SetID sets the value of the id field. Note that this
// operation is only accepted on creation of Platform entities.
func (m *PlatformMutation) SetID(id uuid.UUID) {
m.id = &id
}
// ID returns the ID value in the mutation. Note that the ID is only available
// if it was provided to the builder or after it was returned from the database.
func (m *PlatformMutation) ID() (id uuid.UUID, exists bool) {
if m.id == nil {
return
}
return *m.id, true
}
// IDs queries the database and returns the entity ids that match the mutation's predicate.
// That means, if the mutation is applied within a transaction with an isolation level such
// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated
// or updated by the mutation.
func (m *PlatformMutation) IDs(ctx context.Context) ([]uuid.UUID, error) {
switch {
case m.op.Is(OpUpdateOne | OpDeleteOne):
id, exists := m.ID()
if exists {
return []uuid.UUID{id}, nil
}
fallthrough
case m.op.Is(OpUpdate | OpDelete):
return m.Client().Platform.Query().Where(m.predicates...).IDs(ctx)
default:
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)
}
}
// SetCreatedAt sets the "created_at" field.
func (m *PlatformMutation) SetCreatedAt(t time.Time) {
m.created_at = &t
}
// CreatedAt returns the value of the "created_at" field in the mutation.
func (m *PlatformMutation) CreatedAt() (r time.Time, exists bool) {
v := m.created_at
if v == nil {
return
}
return *v, true
}
// OldCreatedAt returns the old "created_at" field's value of the Platform entity.
// If the Platform object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *PlatformMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldCreatedAt requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err)
}
return oldValue.CreatedAt, nil
}
// ResetCreatedAt resets all changes to the "created_at" field.
func (m *PlatformMutation) ResetCreatedAt() {
m.created_at = nil
}
// SetUpdatedAt sets the "updated_at" field.
func (m *PlatformMutation) SetUpdatedAt(t time.Time) {
m.updated_at = &t
}
// UpdatedAt returns the value of the "updated_at" field in the mutation.
func (m *PlatformMutation) UpdatedAt() (r time.Time, exists bool) {
v := m.updated_at
if v == nil {
return
}
return *v, true
}
// OldUpdatedAt returns the old "updated_at" field's value of the Platform entity.
// If the Platform object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *PlatformMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldUpdatedAt requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err)
}
return oldValue.UpdatedAt, nil
}
// ResetUpdatedAt resets all changes to the "updated_at" field.
func (m *PlatformMutation) ResetUpdatedAt() {
m.updated_at = nil
}
// SetOrgID sets the "org_id" field.
func (m *PlatformMutation) SetOrgID(u uuid.UUID) {
m.organization = &u
}
// OrgID returns the value of the "org_id" field in the mutation.
func (m *PlatformMutation) OrgID() (r uuid.UUID, exists bool) {
v := m.organization
if v == nil {
return
}
return *v, true
}
// OldOrgID returns the old "org_id" field's value of the Platform entity.
// If the Platform object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *PlatformMutation) OldOrgID(ctx context.Context) (v uuid.UUID, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldOrgID is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldOrgID requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldOrgID: %w", err)
}
return oldValue.OrgID, nil
}
// ResetOrgID resets all changes to the "org_id" field.
func (m *PlatformMutation) ResetOrgID() {
m.organization = nil
}
// SetName sets the "name" field.
func (m *PlatformMutation) SetName(s string) {
m.name = &s
}
// Name returns the value of the "name" field in the mutation.
func (m *PlatformMutation) Name() (r string, exists bool) {
v := m.name
if v == nil {
return
}
return *v, true
}
// OldName returns the old "name" field's value of the Platform entity.
// If the Platform object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *PlatformMutation) OldName(ctx context.Context) (v string, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldName is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldName requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldName: %w", err)
}
return oldValue.Name, nil
}
// ResetName resets all changes to the "name" field.
func (m *PlatformMutation) ResetName() {
m.name = nil
}
// SetDisplayName sets the "display_name" field.
func (m *PlatformMutation) SetDisplayName(s string) {
m.display_name = &s
}
// DisplayName returns the value of the "display_name" field in the mutation.
func (m *PlatformMutation) DisplayName() (r string, exists bool) {
v := m.display_name
if v == nil {
return
}
return *v, true
}
// OldDisplayName returns the old "display_name" field's value of the Platform entity.
// If the Platform object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *PlatformMutation) OldDisplayName(ctx context.Context) (v string, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldDisplayName is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldDisplayName requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldDisplayName: %w", err)
}
return oldValue.DisplayName, nil
}
// ResetDisplayName resets all changes to the "display_name" field.
func (m *PlatformMutation) ResetDisplayName() {
m.display_name = nil
}
// SetCreatorID sets the "creator_id" field.
func (m *PlatformMutation) SetCreatorID(u uuid.UUID) {
m.creator = &u
}
// CreatorID returns the value of the "creator_id" field in the mutation.
func (m *PlatformMutation) CreatorID() (r uuid.UUID, exists bool) {
v := m.creator
if v == nil {
return
}
return *v, true
}
// OldCreatorID returns the old "creator_id" field's value of the Platform entity.
// If the Platform object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *PlatformMutation) OldCreatorID(ctx context.Context) (v uuid.UUID, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldCreatorID is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldCreatorID requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldCreatorID: %w", err)
}
return oldValue.CreatorID, nil
}
// ResetCreatorID resets all changes to the "creator_id" field.
func (m *PlatformMutation) ResetCreatorID() {
m.creator = nil
}
// ClearCreator clears the "creator" edge to the User entity.
func (m *PlatformMutation) ClearCreator() {
m.clearedcreator = true
m.clearedFields[platform.FieldCreatorID] = struct{}{}
}
// CreatorCleared reports if the "creator" edge to the User entity was cleared.
func (m *PlatformMutation) CreatorCleared() bool {
return m.clearedcreator
}
// CreatorIDs returns the "creator" edge IDs in the mutation.
// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
// CreatorID instead. It exists only for internal usage by the builders.
func (m *PlatformMutation) CreatorIDs() (ids []uuid.UUID) {
if id := m.creator; id != nil {
ids = append(ids, *id)
}
return
}
// ResetCreator resets all changes to the "creator" edge.
func (m *PlatformMutation) ResetCreator() {
m.creator = nil
m.clearedcreator = false
}
// SetOrganizationID sets the "organization" edge to the Organization entity by id.
func (m *PlatformMutation) SetOrganizationID(id uuid.UUID) {
m.organization = &id
}
// ClearOrganization clears the "organization" edge to the Organization entity.
func (m *PlatformMutation) ClearOrganization() {
m.clearedorganization = true
m.clearedFields[platform.FieldOrgID] = struct{}{}
}
// OrganizationCleared reports if the "organization" edge to the Organization entity was cleared.
func (m *PlatformMutation) OrganizationCleared() bool {
return m.clearedorganization
}
// OrganizationID returns the "organization" edge ID in the mutation.
func (m *PlatformMutation) OrganizationID() (id uuid.UUID, exists bool) {
if m.organization != nil {
return *m.organization, true
}
return
}
// OrganizationIDs returns the "organization" edge IDs in the mutation.
// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
// OrganizationID instead. It exists only for internal usage by the builders.
func (m *PlatformMutation) OrganizationIDs() (ids []uuid.UUID) {
if id := m.organization; id != nil {
ids = append(ids, *id)
}
return
}
// ResetOrganization resets all changes to the "organization" edge.
func (m *PlatformMutation) ResetOrganization() {
m.organization = nil
m.clearedorganization = false
}
// Where appends a list predicates to the PlatformMutation builder.
func (m *PlatformMutation) Where(ps ...predicate.Platform) {
m.predicates = append(m.predicates, ps...)
}
// WhereP appends storage-level predicates to the PlatformMutation builder. Using this method,
// users can use type-assertion to append predicates that do not depend on any generated package.
func (m *PlatformMutation) WhereP(ps ...func(*sql.Selector)) {
p := make([]predicate.Platform, len(ps))
for i := range ps {
p[i] = ps[i]
}
m.Where(p...)
}
// Op returns the operation name.
func (m *PlatformMutation) Op() Op {
return m.op
}
// SetOp allows setting the mutation operation.
func (m *PlatformMutation) SetOp(op Op) {
m.op = op
}
// Type returns the node type of this mutation (Platform).
func (m *PlatformMutation) 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 *PlatformMutation) Fields() []string {
fields := make([]string, 0, 6)
if m.created_at != nil {
fields = append(fields, platform.FieldCreatedAt)
}
if m.updated_at != nil {
fields = append(fields, platform.FieldUpdatedAt)
}
if m.organization != nil {
fields = append(fields, platform.FieldOrgID)
}
if m.name != nil {
fields = append(fields, platform.FieldName)
}
if m.display_name != nil {
fields = append(fields, platform.FieldDisplayName)
}
if m.creator != nil {
fields = append(fields, platform.FieldCreatorID)
}
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 *PlatformMutation) Field(name string) (ent.Value, bool) {
switch name {
case platform.FieldCreatedAt:
return m.CreatedAt()
case platform.FieldUpdatedAt:
return m.UpdatedAt()
case platform.FieldOrgID:
return m.OrgID()
case platform.FieldName:
return m.Name()
case platform.FieldDisplayName:
return m.DisplayName()
case platform.FieldCreatorID:
return m.CreatorID()
}
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 *PlatformMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
switch name {
case platform.FieldCreatedAt:
return m.OldCreatedAt(ctx)
case platform.FieldUpdatedAt:
return m.OldUpdatedAt(ctx)
case platform.FieldOrgID:
return m.OldOrgID(ctx)
case platform.FieldName:
return m.OldName(ctx)
case platform.FieldDisplayName:
return m.OldDisplayName(ctx)
case platform.FieldCreatorID:
return m.OldCreatorID(ctx)
}
return nil, fmt.Errorf("unknown Platform field %s", name)
}
// SetField sets the value of a field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *PlatformMutation) SetField(name string, value ent.Value) error {
switch name {
case platform.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 platform.FieldUpdatedAt:
v, ok := value.(time.Time)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetUpdatedAt(v)
return nil
case platform.FieldOrgID:
v, ok := value.(uuid.UUID)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetOrgID(v)
return nil
case platform.FieldName:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetName(v)
return nil
case platform.FieldDisplayName:
v, ok := value.(string)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetDisplayName(v)
return nil
case platform.FieldCreatorID:
v, ok := value.(uuid.UUID)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetCreatorID(v)
return nil
}
return fmt.Errorf("unknown Platform field %s", name)
}
// AddedFields returns all numeric fields that were incremented/decremented during
// this mutation.
func (m *PlatformMutation) 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 *PlatformMutation) 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 *PlatformMutation) AddField(name string, value ent.Value) error {
switch name {
}
return fmt.Errorf("unknown Platform numeric field %s", name)
}
// ClearedFields returns all nullable fields that were cleared during this
// mutation.
func (m *PlatformMutation) ClearedFields() []string {
return nil
}
// FieldCleared returns a boolean indicating if a field with the given name was
// cleared in this mutation.
func (m *PlatformMutation) 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 *PlatformMutation) ClearField(name string) error {
return fmt.Errorf("unknown Platform 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 *PlatformMutation) ResetField(name string) error {
switch name {
case platform.FieldCreatedAt:
m.ResetCreatedAt()
return nil
case platform.FieldUpdatedAt:
m.ResetUpdatedAt()
return nil
case platform.FieldOrgID:
m.ResetOrgID()
return nil
case platform.FieldName:
m.ResetName()
return nil
case platform.FieldDisplayName:
m.ResetDisplayName()
return nil
case platform.FieldCreatorID:
m.ResetCreatorID()
return nil
}
return fmt.Errorf("unknown Platform field %s", name)
}
// AddedEdges returns all edge names that were set/added in this mutation.
func (m *PlatformMutation) AddedEdges() []string {
edges := make([]string, 0, 2)
if m.creator != nil {
edges = append(edges, platform.EdgeCreator)
}
if m.organization != nil {
edges = append(edges, platform.EdgeOrganization)
}
return edges
}
// AddedIDs returns all IDs (to other nodes) that were added for the given edge
// name in this mutation.
func (m *PlatformMutation) AddedIDs(name string) []ent.Value {
switch name {
case platform.EdgeCreator:
if id := m.creator; id != nil {
return []ent.Value{*id}
}
case platform.EdgeOrganization:
if id := m.organization; id != nil {
return []ent.Value{*id}
}
}
return nil
}
// RemovedEdges returns all edge names that were removed in this mutation.
func (m *PlatformMutation) 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 *PlatformMutation) RemovedIDs(name string) []ent.Value {
return nil
}
// ClearedEdges returns all edge names that were cleared in this mutation.
func (m *PlatformMutation) ClearedEdges() []string {
edges := make([]string, 0, 2)
if m.clearedcreator {
edges = append(edges, platform.EdgeCreator)
}
if m.clearedorganization {
edges = append(edges, platform.EdgeOrganization)
}
return edges
}
// EdgeCleared returns a boolean which indicates if the edge with the given name
// was cleared in this mutation.
func (m *PlatformMutation) EdgeCleared(name string) bool {
switch name {
case platform.EdgeCreator:
return m.clearedcreator
case platform.EdgeOrganization:
return m.clearedorganization
}
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 *PlatformMutation) ClearEdge(name string) error {
switch name {
case platform.EdgeCreator:
m.ClearCreator()
return nil
case platform.EdgeOrganization:
m.ClearOrganization()
return nil
}
return fmt.Errorf("unknown Platform 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 *PlatformMutation) ResetEdge(name string) error {
switch name {
case platform.EdgeCreator:
m.ResetCreator()
return nil
case platform.EdgeOrganization:
m.ResetOrganization()
return nil
}
return fmt.Errorf("unknown Platform edge %s", name)
}
// UserMutation represents an operation that mutates the User nodes in the graph.
type UserMutation struct {
config

View File

@@ -41,9 +41,11 @@ type OrganizationEdges struct {
Creator *User `json:"creator,omitempty"`
// Users holds the value of the users edge.
Users []*User `json:"users,omitempty"`
// Platforms holds the value of the platforms edge.
Platforms []*Platform `json:"platforms,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
loadedTypes [3]bool
}
// CreatorOrErr returns the Creator value or an error if the edge
@@ -66,6 +68,15 @@ func (e OrganizationEdges) UsersOrErr() ([]*User, error) {
return nil, &NotLoadedError{edge: "users"}
}
// PlatformsOrErr returns the Platforms value or an error if the edge
// was not loaded in eager-loading.
func (e OrganizationEdges) PlatformsOrErr() ([]*Platform, error) {
if e.loadedTypes[2] {
return e.Platforms, nil
}
return nil, &NotLoadedError{edge: "platforms"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Organization) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
@@ -151,6 +162,11 @@ func (o *Organization) QueryUsers() *UserQuery {
return NewOrganizationClient(o.config).QueryUsers(o)
}
// QueryPlatforms queries the "platforms" edge of the Organization entity.
func (o *Organization) QueryPlatforms() *PlatformQuery {
return NewOrganizationClient(o.config).QueryPlatforms(o)
}
// Update returns a builder for updating this Organization.
// Note that you need to call Organization.Unwrap() before calling this method if this Organization
// was returned from a transaction, and the transaction was committed or rolled back.

View File

@@ -29,6 +29,8 @@ const (
EdgeCreator = "creator"
// EdgeUsers holds the string denoting the users edge name in mutations.
EdgeUsers = "users"
// EdgePlatforms holds the string denoting the platforms edge name in mutations.
EdgePlatforms = "platforms"
// Table holds the table name of the organization in the database.
Table = "organizations"
// CreatorTable is the table that holds the creator relation/edge.
@@ -43,6 +45,13 @@ const (
// UsersInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
UsersInverseTable = "users"
// PlatformsTable is the table that holds the platforms relation/edge.
PlatformsTable = "platforms"
// PlatformsInverseTable is the table name for the Platform entity.
// It exists in this package in order to avoid circular dependency with the "platform" package.
PlatformsInverseTable = "platforms"
// PlatformsColumn is the table column denoting the platforms relation/edge.
PlatformsColumn = "org_id"
)
// Columns holds all SQL columns for organization fields.
@@ -137,6 +146,20 @@ func ByUsers(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
sqlgraph.OrderByNeighborTerms(s, newUsersStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
// ByPlatformsCount orders the results by platforms count.
func ByPlatformsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborsCount(s, newPlatformsStep(), opts...)
}
}
// ByPlatforms orders the results by platforms terms.
func ByPlatforms(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newPlatformsStep(), append([]sql.OrderTerm{term}, terms...)...)
}
}
func newCreatorStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
@@ -151,3 +174,10 @@ func newUsersStep() *sqlgraph.Step {
sqlgraph.Edge(sqlgraph.M2M, false, UsersTable, UsersPrimaryKey...),
)
}
func newPlatformsStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(PlatformsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, true, PlatformsTable, PlatformsColumn),
)
}

View File

@@ -357,6 +357,29 @@ func HasUsersWith(preds ...predicate.User) predicate.Organization {
})
}
// HasPlatforms applies the HasEdge predicate on the "platforms" edge.
func HasPlatforms() predicate.Organization {
return predicate.Organization(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, true, PlatformsTable, PlatformsColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasPlatformsWith applies the HasEdge predicate on the "platforms" edge with a given conditions (other predicates).
func HasPlatformsWith(preds ...predicate.Platform) predicate.Organization {
return predicate.Organization(func(s *sql.Selector) {
step := newPlatformsStep()
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.Organization) predicate.Organization {
return predicate.Organization(sql.AndPredicates(predicates...))

View File

@@ -14,6 +14,7 @@ import (
"entgo.io/ent/schema/field"
"github.com/gofrs/uuid"
"github.com/holos-run/holos/internal/ent/organization"
"github.com/holos-run/holos/internal/ent/platform"
"github.com/holos-run/holos/internal/ent/user"
)
@@ -105,6 +106,21 @@ func (oc *OrganizationCreate) AddUsers(u ...*User) *OrganizationCreate {
return oc.AddUserIDs(ids...)
}
// AddPlatformIDs adds the "platforms" edge to the Platform entity by IDs.
func (oc *OrganizationCreate) AddPlatformIDs(ids ...uuid.UUID) *OrganizationCreate {
oc.mutation.AddPlatformIDs(ids...)
return oc
}
// AddPlatforms adds the "platforms" edges to the Platform entity.
func (oc *OrganizationCreate) AddPlatforms(p ...*Platform) *OrganizationCreate {
ids := make([]uuid.UUID, len(p))
for i := range p {
ids[i] = p[i].ID
}
return oc.AddPlatformIDs(ids...)
}
// Mutation returns the OrganizationMutation object of the builder.
func (oc *OrganizationCreate) Mutation() *OrganizationMutation {
return oc.mutation
@@ -264,6 +280,22 @@ func (oc *OrganizationCreate) createSpec() (*Organization, *sqlgraph.CreateSpec)
}
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := oc.mutation.PlatformsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: organization.PlatformsTable,
Columns: []string{organization.PlatformsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(platform.FieldID, field.TypeUUID),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}

View File

@@ -13,6 +13,7 @@ import (
"entgo.io/ent/schema/field"
"github.com/gofrs/uuid"
"github.com/holos-run/holos/internal/ent/organization"
"github.com/holos-run/holos/internal/ent/platform"
"github.com/holos-run/holos/internal/ent/predicate"
"github.com/holos-run/holos/internal/ent/user"
)
@@ -20,12 +21,13 @@ import (
// OrganizationQuery is the builder for querying Organization entities.
type OrganizationQuery struct {
config
ctx *QueryContext
order []organization.OrderOption
inters []Interceptor
predicates []predicate.Organization
withCreator *UserQuery
withUsers *UserQuery
ctx *QueryContext
order []organization.OrderOption
inters []Interceptor
predicates []predicate.Organization
withCreator *UserQuery
withUsers *UserQuery
withPlatforms *PlatformQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
@@ -106,6 +108,28 @@ func (oq *OrganizationQuery) QueryUsers() *UserQuery {
return query
}
// QueryPlatforms chains the current query on the "platforms" edge.
func (oq *OrganizationQuery) QueryPlatforms() *PlatformQuery {
query := (&PlatformClient{config: oq.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := oq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := oq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(organization.Table, organization.FieldID, selector),
sqlgraph.To(platform.Table, platform.FieldID),
sqlgraph.Edge(sqlgraph.O2M, true, organization.PlatformsTable, organization.PlatformsColumn),
)
fromU = sqlgraph.SetNeighbors(oq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Organization entity from the query.
// Returns a *NotFoundError when no Organization was found.
func (oq *OrganizationQuery) First(ctx context.Context) (*Organization, error) {
@@ -293,13 +317,14 @@ func (oq *OrganizationQuery) Clone() *OrganizationQuery {
return nil
}
return &OrganizationQuery{
config: oq.config,
ctx: oq.ctx.Clone(),
order: append([]organization.OrderOption{}, oq.order...),
inters: append([]Interceptor{}, oq.inters...),
predicates: append([]predicate.Organization{}, oq.predicates...),
withCreator: oq.withCreator.Clone(),
withUsers: oq.withUsers.Clone(),
config: oq.config,
ctx: oq.ctx.Clone(),
order: append([]organization.OrderOption{}, oq.order...),
inters: append([]Interceptor{}, oq.inters...),
predicates: append([]predicate.Organization{}, oq.predicates...),
withCreator: oq.withCreator.Clone(),
withUsers: oq.withUsers.Clone(),
withPlatforms: oq.withPlatforms.Clone(),
// clone intermediate query.
sql: oq.sql.Clone(),
path: oq.path,
@@ -328,6 +353,17 @@ func (oq *OrganizationQuery) WithUsers(opts ...func(*UserQuery)) *OrganizationQu
return oq
}
// WithPlatforms tells the query-builder to eager-load the nodes that are connected to
// the "platforms" edge. The optional arguments are used to configure the query builder of the edge.
func (oq *OrganizationQuery) WithPlatforms(opts ...func(*PlatformQuery)) *OrganizationQuery {
query := (&PlatformClient{config: oq.config}).Query()
for _, opt := range opts {
opt(query)
}
oq.withPlatforms = query
return oq
}
// 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.
//
@@ -406,9 +442,10 @@ func (oq *OrganizationQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]
var (
nodes = []*Organization{}
_spec = oq.querySpec()
loadedTypes = [2]bool{
loadedTypes = [3]bool{
oq.withCreator != nil,
oq.withUsers != nil,
oq.withPlatforms != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
@@ -442,6 +479,13 @@ func (oq *OrganizationQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]
return nil, err
}
}
if query := oq.withPlatforms; query != nil {
if err := oq.loadPlatforms(ctx, query, nodes,
func(n *Organization) { n.Edges.Platforms = []*Platform{} },
func(n *Organization, e *Platform) { n.Edges.Platforms = append(n.Edges.Platforms, e) }); err != nil {
return nil, err
}
}
return nodes, nil
}
@@ -535,6 +579,36 @@ func (oq *OrganizationQuery) loadUsers(ctx context.Context, query *UserQuery, no
}
return nil
}
func (oq *OrganizationQuery) loadPlatforms(ctx context.Context, query *PlatformQuery, nodes []*Organization, init func(*Organization), assign func(*Organization, *Platform)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[uuid.UUID]*Organization)
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(platform.FieldOrgID)
}
query.Where(predicate.Platform(func(s *sql.Selector) {
s.Where(sql.InValues(s.C(organization.PlatformsColumn), fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.OrgID
node, ok := nodeids[fk]
if !ok {
return fmt.Errorf(`unexpected referenced foreign-key "org_id" returned %v for node %v`, fk, n.ID)
}
assign(node, n)
}
return nil
}
func (oq *OrganizationQuery) sqlCount(ctx context.Context) (int, error) {
_spec := oq.querySpec()

View File

@@ -13,6 +13,7 @@ import (
"entgo.io/ent/schema/field"
"github.com/gofrs/uuid"
"github.com/holos-run/holos/internal/ent/organization"
"github.com/holos-run/holos/internal/ent/platform"
"github.com/holos-run/holos/internal/ent/predicate"
"github.com/holos-run/holos/internal/ent/user"
)
@@ -98,6 +99,21 @@ func (ou *OrganizationUpdate) AddUsers(u ...*User) *OrganizationUpdate {
return ou.AddUserIDs(ids...)
}
// AddPlatformIDs adds the "platforms" edge to the Platform entity by IDs.
func (ou *OrganizationUpdate) AddPlatformIDs(ids ...uuid.UUID) *OrganizationUpdate {
ou.mutation.AddPlatformIDs(ids...)
return ou
}
// AddPlatforms adds the "platforms" edges to the Platform entity.
func (ou *OrganizationUpdate) AddPlatforms(p ...*Platform) *OrganizationUpdate {
ids := make([]uuid.UUID, len(p))
for i := range p {
ids[i] = p[i].ID
}
return ou.AddPlatformIDs(ids...)
}
// Mutation returns the OrganizationMutation object of the builder.
func (ou *OrganizationUpdate) Mutation() *OrganizationMutation {
return ou.mutation
@@ -130,6 +146,27 @@ func (ou *OrganizationUpdate) RemoveUsers(u ...*User) *OrganizationUpdate {
return ou.RemoveUserIDs(ids...)
}
// ClearPlatforms clears all "platforms" edges to the Platform entity.
func (ou *OrganizationUpdate) ClearPlatforms() *OrganizationUpdate {
ou.mutation.ClearPlatforms()
return ou
}
// RemovePlatformIDs removes the "platforms" edge to Platform entities by IDs.
func (ou *OrganizationUpdate) RemovePlatformIDs(ids ...uuid.UUID) *OrganizationUpdate {
ou.mutation.RemovePlatformIDs(ids...)
return ou
}
// RemovePlatforms removes "platforms" edges to Platform entities.
func (ou *OrganizationUpdate) RemovePlatforms(p ...*Platform) *OrganizationUpdate {
ids := make([]uuid.UUID, len(p))
for i := range p {
ids[i] = p[i].ID
}
return ou.RemovePlatformIDs(ids...)
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (ou *OrganizationUpdate) Save(ctx context.Context) (int, error) {
ou.defaults()
@@ -274,6 +311,51 @@ func (ou *OrganizationUpdate) sqlSave(ctx context.Context) (n int, err error) {
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if ou.mutation.PlatformsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: organization.PlatformsTable,
Columns: []string{organization.PlatformsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(platform.FieldID, field.TypeUUID),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := ou.mutation.RemovedPlatformsIDs(); len(nodes) > 0 && !ou.mutation.PlatformsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: organization.PlatformsTable,
Columns: []string{organization.PlatformsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(platform.FieldID, field.TypeUUID),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := ou.mutation.PlatformsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: organization.PlatformsTable,
Columns: []string{organization.PlatformsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(platform.FieldID, field.TypeUUID),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if n, err = sqlgraph.UpdateNodes(ctx, ou.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{organization.Label}
@@ -362,6 +444,21 @@ func (ouo *OrganizationUpdateOne) AddUsers(u ...*User) *OrganizationUpdateOne {
return ouo.AddUserIDs(ids...)
}
// AddPlatformIDs adds the "platforms" edge to the Platform entity by IDs.
func (ouo *OrganizationUpdateOne) AddPlatformIDs(ids ...uuid.UUID) *OrganizationUpdateOne {
ouo.mutation.AddPlatformIDs(ids...)
return ouo
}
// AddPlatforms adds the "platforms" edges to the Platform entity.
func (ouo *OrganizationUpdateOne) AddPlatforms(p ...*Platform) *OrganizationUpdateOne {
ids := make([]uuid.UUID, len(p))
for i := range p {
ids[i] = p[i].ID
}
return ouo.AddPlatformIDs(ids...)
}
// Mutation returns the OrganizationMutation object of the builder.
func (ouo *OrganizationUpdateOne) Mutation() *OrganizationMutation {
return ouo.mutation
@@ -394,6 +491,27 @@ func (ouo *OrganizationUpdateOne) RemoveUsers(u ...*User) *OrganizationUpdateOne
return ouo.RemoveUserIDs(ids...)
}
// ClearPlatforms clears all "platforms" edges to the Platform entity.
func (ouo *OrganizationUpdateOne) ClearPlatforms() *OrganizationUpdateOne {
ouo.mutation.ClearPlatforms()
return ouo
}
// RemovePlatformIDs removes the "platforms" edge to Platform entities by IDs.
func (ouo *OrganizationUpdateOne) RemovePlatformIDs(ids ...uuid.UUID) *OrganizationUpdateOne {
ouo.mutation.RemovePlatformIDs(ids...)
return ouo
}
// RemovePlatforms removes "platforms" edges to Platform entities.
func (ouo *OrganizationUpdateOne) RemovePlatforms(p ...*Platform) *OrganizationUpdateOne {
ids := make([]uuid.UUID, len(p))
for i := range p {
ids[i] = p[i].ID
}
return ouo.RemovePlatformIDs(ids...)
}
// Where appends a list predicates to the OrganizationUpdate builder.
func (ouo *OrganizationUpdateOne) Where(ps ...predicate.Organization) *OrganizationUpdateOne {
ouo.mutation.Where(ps...)
@@ -568,6 +686,51 @@ func (ouo *OrganizationUpdateOne) sqlSave(ctx context.Context) (_node *Organizat
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if ouo.mutation.PlatformsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: organization.PlatformsTable,
Columns: []string{organization.PlatformsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(platform.FieldID, field.TypeUUID),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := ouo.mutation.RemovedPlatformsIDs(); len(nodes) > 0 && !ouo.mutation.PlatformsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: organization.PlatformsTable,
Columns: []string{organization.PlatformsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(platform.FieldID, field.TypeUUID),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := ouo.mutation.PlatformsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: true,
Table: organization.PlatformsTable,
Columns: []string{organization.PlatformsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(platform.FieldID, field.TypeUUID),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &Organization{config: ouo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues

210
internal/ent/platform.go Normal file
View File

@@ -0,0 +1,210 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"github.com/gofrs/uuid"
"github.com/holos-run/holos/internal/ent/organization"
"github.com/holos-run/holos/internal/ent/platform"
"github.com/holos-run/holos/internal/ent/user"
)
// Platform is the model entity for the Platform schema.
type Platform struct {
config `json:"-"`
// ID of the ent.
ID uuid.UUID `json:"id,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt time.Time `json:"created_at,omitempty"`
// UpdatedAt holds the value of the "updated_at" field.
UpdatedAt time.Time `json:"updated_at,omitempty"`
// OrgID holds the value of the "org_id" field.
OrgID uuid.UUID `json:"org_id,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// DisplayName holds the value of the "display_name" field.
DisplayName string `json:"display_name,omitempty"`
// CreatorID holds the value of the "creator_id" field.
CreatorID uuid.UUID `json:"creator_id,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the PlatformQuery when eager-loading is set.
Edges PlatformEdges `json:"edges"`
selectValues sql.SelectValues
}
// PlatformEdges holds the relations/edges for other nodes in the graph.
type PlatformEdges struct {
// Creator holds the value of the creator edge.
Creator *User `json:"creator,omitempty"`
// Organization holds the value of the organization edge.
Organization *Organization `json:"organization,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
}
// CreatorOrErr returns the Creator value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e PlatformEdges) CreatorOrErr() (*User, error) {
if e.Creator != nil {
return e.Creator, nil
} else if e.loadedTypes[0] {
return nil, &NotFoundError{label: user.Label}
}
return nil, &NotLoadedError{edge: "creator"}
}
// OrganizationOrErr returns the Organization value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e PlatformEdges) OrganizationOrErr() (*Organization, error) {
if e.Organization != nil {
return e.Organization, nil
} else if e.loadedTypes[1] {
return nil, &NotFoundError{label: organization.Label}
}
return nil, &NotLoadedError{edge: "organization"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Platform) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case platform.FieldName, platform.FieldDisplayName:
values[i] = new(sql.NullString)
case platform.FieldCreatedAt, platform.FieldUpdatedAt:
values[i] = new(sql.NullTime)
case platform.FieldID, platform.FieldOrgID, platform.FieldCreatorID:
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 Platform fields.
func (pl *Platform) 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 platform.FieldID:
if value, ok := values[i].(*uuid.UUID); !ok {
return fmt.Errorf("unexpected type %T for field id", values[i])
} else if value != nil {
pl.ID = *value
}
case platform.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 {
pl.CreatedAt = value.Time
}
case platform.FieldUpdatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
} else if value.Valid {
pl.UpdatedAt = value.Time
}
case platform.FieldOrgID:
if value, ok := values[i].(*uuid.UUID); !ok {
return fmt.Errorf("unexpected type %T for field org_id", values[i])
} else if value != nil {
pl.OrgID = *value
}
case platform.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
pl.Name = value.String
}
case platform.FieldDisplayName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field display_name", values[i])
} else if value.Valid {
pl.DisplayName = value.String
}
case platform.FieldCreatorID:
if value, ok := values[i].(*uuid.UUID); !ok {
return fmt.Errorf("unexpected type %T for field creator_id", values[i])
} else if value != nil {
pl.CreatorID = *value
}
default:
pl.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Platform.
// This includes values selected through modifiers, order, etc.
func (pl *Platform) Value(name string) (ent.Value, error) {
return pl.selectValues.Get(name)
}
// QueryCreator queries the "creator" edge of the Platform entity.
func (pl *Platform) QueryCreator() *UserQuery {
return NewPlatformClient(pl.config).QueryCreator(pl)
}
// QueryOrganization queries the "organization" edge of the Platform entity.
func (pl *Platform) QueryOrganization() *OrganizationQuery {
return NewPlatformClient(pl.config).QueryOrganization(pl)
}
// Update returns a builder for updating this Platform.
// Note that you need to call Platform.Unwrap() before calling this method if this Platform
// was returned from a transaction, and the transaction was committed or rolled back.
func (pl *Platform) Update() *PlatformUpdateOne {
return NewPlatformClient(pl.config).UpdateOne(pl)
}
// Unwrap unwraps the Platform 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 (pl *Platform) Unwrap() *Platform {
_tx, ok := pl.config.driver.(*txDriver)
if !ok {
panic("ent: Platform is not a transactional entity")
}
pl.config.driver = _tx.drv
return pl
}
// String implements the fmt.Stringer.
func (pl *Platform) String() string {
var builder strings.Builder
builder.WriteString("Platform(")
builder.WriteString(fmt.Sprintf("id=%v, ", pl.ID))
builder.WriteString("created_at=")
builder.WriteString(pl.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(pl.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("org_id=")
builder.WriteString(fmt.Sprintf("%v", pl.OrgID))
builder.WriteString(", ")
builder.WriteString("name=")
builder.WriteString(pl.Name)
builder.WriteString(", ")
builder.WriteString("display_name=")
builder.WriteString(pl.DisplayName)
builder.WriteString(", ")
builder.WriteString("creator_id=")
builder.WriteString(fmt.Sprintf("%v", pl.CreatorID))
builder.WriteByte(')')
return builder.String()
}
// Platforms is a parsable slice of Platform.
type Platforms []*Platform

View File

@@ -0,0 +1,150 @@
// Code generated by ent, DO NOT EDIT.
package platform
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/gofrs/uuid"
)
const (
// Label holds the string label denoting the platform type in the database.
Label = "platform"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// FieldUpdatedAt holds the string denoting the updated_at field in the database.
FieldUpdatedAt = "updated_at"
// FieldOrgID holds the string denoting the org_id field in the database.
FieldOrgID = "org_id"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// FieldDisplayName holds the string denoting the display_name field in the database.
FieldDisplayName = "display_name"
// FieldCreatorID holds the string denoting the creator_id field in the database.
FieldCreatorID = "creator_id"
// EdgeCreator holds the string denoting the creator edge name in mutations.
EdgeCreator = "creator"
// EdgeOrganization holds the string denoting the organization edge name in mutations.
EdgeOrganization = "organization"
// Table holds the table name of the platform in the database.
Table = "platforms"
// CreatorTable is the table that holds the creator relation/edge.
CreatorTable = "platforms"
// CreatorInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
CreatorInverseTable = "users"
// CreatorColumn is the table column denoting the creator relation/edge.
CreatorColumn = "creator_id"
// OrganizationTable is the table that holds the organization relation/edge.
OrganizationTable = "platforms"
// OrganizationInverseTable is the table name for the Organization entity.
// It exists in this package in order to avoid circular dependency with the "organization" package.
OrganizationInverseTable = "organizations"
// OrganizationColumn is the table column denoting the organization relation/edge.
OrganizationColumn = "org_id"
)
// Columns holds all SQL columns for platform fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldOrgID,
FieldName,
FieldDisplayName,
FieldCreatorID,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
// UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
UpdateDefaultUpdatedAt func() time.Time
// NameValidator is a validator for the "name" field. It is called by the builders before save.
NameValidator func(string) error
// DefaultID holds the default value on creation for the "id" field.
DefaultID func() uuid.UUID
)
// OrderOption defines the ordering options for the Platform queries.
type OrderOption func(*sql.Selector)
// ByID orders the results by the id field.
func ByID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldID, opts...).ToFunc()
}
// ByCreatedAt orders the results by the created_at field.
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
}
// ByUpdatedAt orders the results by the updated_at field.
func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
}
// ByOrgID orders the results by the org_id field.
func ByOrgID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldOrgID, opts...).ToFunc()
}
// ByName orders the results by the name field.
func ByName(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldName, opts...).ToFunc()
}
// ByDisplayName orders the results by the display_name field.
func ByDisplayName(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDisplayName, opts...).ToFunc()
}
// ByCreatorID orders the results by the creator_id field.
func ByCreatorID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCreatorID, opts...).ToFunc()
}
// ByCreatorField orders the results by creator field.
func ByCreatorField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newCreatorStep(), sql.OrderByField(field, opts...))
}
}
// ByOrganizationField orders the results by organization field.
func ByOrganizationField(field string, opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {
sqlgraph.OrderByNeighborTerms(s, newOrganizationStep(), sql.OrderByField(field, opts...))
}
}
func newCreatorStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(CreatorInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, CreatorTable, CreatorColumn),
)
}
func newOrganizationStep() *sqlgraph.Step {
return sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(OrganizationInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, OrganizationTable, OrganizationColumn),
)
}

View File

@@ -0,0 +1,398 @@
// Code generated by ent, DO NOT EDIT.
package platform
import (
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/gofrs/uuid"
"github.com/holos-run/holos/internal/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id uuid.UUID) predicate.Platform {
return predicate.Platform(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id uuid.UUID) predicate.Platform {
return predicate.Platform(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id uuid.UUID) predicate.Platform {
return predicate.Platform(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...uuid.UUID) predicate.Platform {
return predicate.Platform(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...uuid.UUID) predicate.Platform {
return predicate.Platform(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id uuid.UUID) predicate.Platform {
return predicate.Platform(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id uuid.UUID) predicate.Platform {
return predicate.Platform(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id uuid.UUID) predicate.Platform {
return predicate.Platform(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id uuid.UUID) predicate.Platform {
return predicate.Platform(sql.FieldLTE(FieldID, id))
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v time.Time) predicate.Platform {
return predicate.Platform(sql.FieldEQ(FieldCreatedAt, v))
}
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
func UpdatedAt(v time.Time) predicate.Platform {
return predicate.Platform(sql.FieldEQ(FieldUpdatedAt, v))
}
// OrgID applies equality check predicate on the "org_id" field. It's identical to OrgIDEQ.
func OrgID(v uuid.UUID) predicate.Platform {
return predicate.Platform(sql.FieldEQ(FieldOrgID, v))
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.Platform {
return predicate.Platform(sql.FieldEQ(FieldName, v))
}
// DisplayName applies equality check predicate on the "display_name" field. It's identical to DisplayNameEQ.
func DisplayName(v string) predicate.Platform {
return predicate.Platform(sql.FieldEQ(FieldDisplayName, v))
}
// CreatorID applies equality check predicate on the "creator_id" field. It's identical to CreatorIDEQ.
func CreatorID(v uuid.UUID) predicate.Platform {
return predicate.Platform(sql.FieldEQ(FieldCreatorID, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.Platform {
return predicate.Platform(sql.FieldEQ(FieldCreatedAt, v))
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v time.Time) predicate.Platform {
return predicate.Platform(sql.FieldNEQ(FieldCreatedAt, v))
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...time.Time) predicate.Platform {
return predicate.Platform(sql.FieldIn(FieldCreatedAt, vs...))
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...time.Time) predicate.Platform {
return predicate.Platform(sql.FieldNotIn(FieldCreatedAt, vs...))
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v time.Time) predicate.Platform {
return predicate.Platform(sql.FieldGT(FieldCreatedAt, v))
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v time.Time) predicate.Platform {
return predicate.Platform(sql.FieldGTE(FieldCreatedAt, v))
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v time.Time) predicate.Platform {
return predicate.Platform(sql.FieldLT(FieldCreatedAt, v))
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v time.Time) predicate.Platform {
return predicate.Platform(sql.FieldLTE(FieldCreatedAt, v))
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v time.Time) predicate.Platform {
return predicate.Platform(sql.FieldEQ(FieldUpdatedAt, v))
}
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
func UpdatedAtNEQ(v time.Time) predicate.Platform {
return predicate.Platform(sql.FieldNEQ(FieldUpdatedAt, v))
}
// UpdatedAtIn applies the In predicate on the "updated_at" field.
func UpdatedAtIn(vs ...time.Time) predicate.Platform {
return predicate.Platform(sql.FieldIn(FieldUpdatedAt, vs...))
}
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
func UpdatedAtNotIn(vs ...time.Time) predicate.Platform {
return predicate.Platform(sql.FieldNotIn(FieldUpdatedAt, vs...))
}
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
func UpdatedAtGT(v time.Time) predicate.Platform {
return predicate.Platform(sql.FieldGT(FieldUpdatedAt, v))
}
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
func UpdatedAtGTE(v time.Time) predicate.Platform {
return predicate.Platform(sql.FieldGTE(FieldUpdatedAt, v))
}
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
func UpdatedAtLT(v time.Time) predicate.Platform {
return predicate.Platform(sql.FieldLT(FieldUpdatedAt, v))
}
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
func UpdatedAtLTE(v time.Time) predicate.Platform {
return predicate.Platform(sql.FieldLTE(FieldUpdatedAt, v))
}
// OrgIDEQ applies the EQ predicate on the "org_id" field.
func OrgIDEQ(v uuid.UUID) predicate.Platform {
return predicate.Platform(sql.FieldEQ(FieldOrgID, v))
}
// OrgIDNEQ applies the NEQ predicate on the "org_id" field.
func OrgIDNEQ(v uuid.UUID) predicate.Platform {
return predicate.Platform(sql.FieldNEQ(FieldOrgID, v))
}
// OrgIDIn applies the In predicate on the "org_id" field.
func OrgIDIn(vs ...uuid.UUID) predicate.Platform {
return predicate.Platform(sql.FieldIn(FieldOrgID, vs...))
}
// OrgIDNotIn applies the NotIn predicate on the "org_id" field.
func OrgIDNotIn(vs ...uuid.UUID) predicate.Platform {
return predicate.Platform(sql.FieldNotIn(FieldOrgID, vs...))
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.Platform {
return predicate.Platform(sql.FieldEQ(FieldName, v))
}
// NameNEQ applies the NEQ predicate on the "name" field.
func NameNEQ(v string) predicate.Platform {
return predicate.Platform(sql.FieldNEQ(FieldName, v))
}
// NameIn applies the In predicate on the "name" field.
func NameIn(vs ...string) predicate.Platform {
return predicate.Platform(sql.FieldIn(FieldName, vs...))
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.Platform {
return predicate.Platform(sql.FieldNotIn(FieldName, vs...))
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.Platform {
return predicate.Platform(sql.FieldGT(FieldName, v))
}
// NameGTE applies the GTE predicate on the "name" field.
func NameGTE(v string) predicate.Platform {
return predicate.Platform(sql.FieldGTE(FieldName, v))
}
// NameLT applies the LT predicate on the "name" field.
func NameLT(v string) predicate.Platform {
return predicate.Platform(sql.FieldLT(FieldName, v))
}
// NameLTE applies the LTE predicate on the "name" field.
func NameLTE(v string) predicate.Platform {
return predicate.Platform(sql.FieldLTE(FieldName, v))
}
// NameContains applies the Contains predicate on the "name" field.
func NameContains(v string) predicate.Platform {
return predicate.Platform(sql.FieldContains(FieldName, v))
}
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
func NameHasPrefix(v string) predicate.Platform {
return predicate.Platform(sql.FieldHasPrefix(FieldName, v))
}
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
func NameHasSuffix(v string) predicate.Platform {
return predicate.Platform(sql.FieldHasSuffix(FieldName, v))
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.Platform {
return predicate.Platform(sql.FieldEqualFold(FieldName, v))
}
// NameContainsFold applies the ContainsFold predicate on the "name" field.
func NameContainsFold(v string) predicate.Platform {
return predicate.Platform(sql.FieldContainsFold(FieldName, v))
}
// DisplayNameEQ applies the EQ predicate on the "display_name" field.
func DisplayNameEQ(v string) predicate.Platform {
return predicate.Platform(sql.FieldEQ(FieldDisplayName, v))
}
// DisplayNameNEQ applies the NEQ predicate on the "display_name" field.
func DisplayNameNEQ(v string) predicate.Platform {
return predicate.Platform(sql.FieldNEQ(FieldDisplayName, v))
}
// DisplayNameIn applies the In predicate on the "display_name" field.
func DisplayNameIn(vs ...string) predicate.Platform {
return predicate.Platform(sql.FieldIn(FieldDisplayName, vs...))
}
// DisplayNameNotIn applies the NotIn predicate on the "display_name" field.
func DisplayNameNotIn(vs ...string) predicate.Platform {
return predicate.Platform(sql.FieldNotIn(FieldDisplayName, vs...))
}
// DisplayNameGT applies the GT predicate on the "display_name" field.
func DisplayNameGT(v string) predicate.Platform {
return predicate.Platform(sql.FieldGT(FieldDisplayName, v))
}
// DisplayNameGTE applies the GTE predicate on the "display_name" field.
func DisplayNameGTE(v string) predicate.Platform {
return predicate.Platform(sql.FieldGTE(FieldDisplayName, v))
}
// DisplayNameLT applies the LT predicate on the "display_name" field.
func DisplayNameLT(v string) predicate.Platform {
return predicate.Platform(sql.FieldLT(FieldDisplayName, v))
}
// DisplayNameLTE applies the LTE predicate on the "display_name" field.
func DisplayNameLTE(v string) predicate.Platform {
return predicate.Platform(sql.FieldLTE(FieldDisplayName, v))
}
// DisplayNameContains applies the Contains predicate on the "display_name" field.
func DisplayNameContains(v string) predicate.Platform {
return predicate.Platform(sql.FieldContains(FieldDisplayName, v))
}
// DisplayNameHasPrefix applies the HasPrefix predicate on the "display_name" field.
func DisplayNameHasPrefix(v string) predicate.Platform {
return predicate.Platform(sql.FieldHasPrefix(FieldDisplayName, v))
}
// DisplayNameHasSuffix applies the HasSuffix predicate on the "display_name" field.
func DisplayNameHasSuffix(v string) predicate.Platform {
return predicate.Platform(sql.FieldHasSuffix(FieldDisplayName, v))
}
// DisplayNameEqualFold applies the EqualFold predicate on the "display_name" field.
func DisplayNameEqualFold(v string) predicate.Platform {
return predicate.Platform(sql.FieldEqualFold(FieldDisplayName, v))
}
// DisplayNameContainsFold applies the ContainsFold predicate on the "display_name" field.
func DisplayNameContainsFold(v string) predicate.Platform {
return predicate.Platform(sql.FieldContainsFold(FieldDisplayName, v))
}
// CreatorIDEQ applies the EQ predicate on the "creator_id" field.
func CreatorIDEQ(v uuid.UUID) predicate.Platform {
return predicate.Platform(sql.FieldEQ(FieldCreatorID, v))
}
// CreatorIDNEQ applies the NEQ predicate on the "creator_id" field.
func CreatorIDNEQ(v uuid.UUID) predicate.Platform {
return predicate.Platform(sql.FieldNEQ(FieldCreatorID, v))
}
// CreatorIDIn applies the In predicate on the "creator_id" field.
func CreatorIDIn(vs ...uuid.UUID) predicate.Platform {
return predicate.Platform(sql.FieldIn(FieldCreatorID, vs...))
}
// CreatorIDNotIn applies the NotIn predicate on the "creator_id" field.
func CreatorIDNotIn(vs ...uuid.UUID) predicate.Platform {
return predicate.Platform(sql.FieldNotIn(FieldCreatorID, vs...))
}
// HasCreator applies the HasEdge predicate on the "creator" edge.
func HasCreator() predicate.Platform {
return predicate.Platform(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, CreatorTable, CreatorColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasCreatorWith applies the HasEdge predicate on the "creator" edge with a given conditions (other predicates).
func HasCreatorWith(preds ...predicate.User) predicate.Platform {
return predicate.Platform(func(s *sql.Selector) {
step := newCreatorStep()
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasOrganization applies the HasEdge predicate on the "organization" edge.
func HasOrganization() predicate.Platform {
return predicate.Platform(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, OrganizationTable, OrganizationColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasOrganizationWith applies the HasEdge predicate on the "organization" edge with a given conditions (other predicates).
func HasOrganizationWith(preds ...predicate.Organization) predicate.Platform {
return predicate.Platform(func(s *sql.Selector) {
step := newOrganizationStep()
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.Platform) predicate.Platform {
return predicate.Platform(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Platform) predicate.Platform {
return predicate.Platform(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Platform) predicate.Platform {
return predicate.Platform(sql.NotPredicates(p))
}

View File

@@ -0,0 +1,819 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/gofrs/uuid"
"github.com/holos-run/holos/internal/ent/organization"
"github.com/holos-run/holos/internal/ent/platform"
"github.com/holos-run/holos/internal/ent/user"
)
// PlatformCreate is the builder for creating a Platform entity.
type PlatformCreate struct {
config
mutation *PlatformMutation
hooks []Hook
conflict []sql.ConflictOption
}
// SetCreatedAt sets the "created_at" field.
func (pc *PlatformCreate) SetCreatedAt(t time.Time) *PlatformCreate {
pc.mutation.SetCreatedAt(t)
return pc
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (pc *PlatformCreate) SetNillableCreatedAt(t *time.Time) *PlatformCreate {
if t != nil {
pc.SetCreatedAt(*t)
}
return pc
}
// SetUpdatedAt sets the "updated_at" field.
func (pc *PlatformCreate) SetUpdatedAt(t time.Time) *PlatformCreate {
pc.mutation.SetUpdatedAt(t)
return pc
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (pc *PlatformCreate) SetNillableUpdatedAt(t *time.Time) *PlatformCreate {
if t != nil {
pc.SetUpdatedAt(*t)
}
return pc
}
// SetOrgID sets the "org_id" field.
func (pc *PlatformCreate) SetOrgID(u uuid.UUID) *PlatformCreate {
pc.mutation.SetOrgID(u)
return pc
}
// SetName sets the "name" field.
func (pc *PlatformCreate) SetName(s string) *PlatformCreate {
pc.mutation.SetName(s)
return pc
}
// SetDisplayName sets the "display_name" field.
func (pc *PlatformCreate) SetDisplayName(s string) *PlatformCreate {
pc.mutation.SetDisplayName(s)
return pc
}
// SetCreatorID sets the "creator_id" field.
func (pc *PlatformCreate) SetCreatorID(u uuid.UUID) *PlatformCreate {
pc.mutation.SetCreatorID(u)
return pc
}
// SetID sets the "id" field.
func (pc *PlatformCreate) SetID(u uuid.UUID) *PlatformCreate {
pc.mutation.SetID(u)
return pc
}
// SetNillableID sets the "id" field if the given value is not nil.
func (pc *PlatformCreate) SetNillableID(u *uuid.UUID) *PlatformCreate {
if u != nil {
pc.SetID(*u)
}
return pc
}
// SetCreator sets the "creator" edge to the User entity.
func (pc *PlatformCreate) SetCreator(u *User) *PlatformCreate {
return pc.SetCreatorID(u.ID)
}
// SetOrganizationID sets the "organization" edge to the Organization entity by ID.
func (pc *PlatformCreate) SetOrganizationID(id uuid.UUID) *PlatformCreate {
pc.mutation.SetOrganizationID(id)
return pc
}
// SetOrganization sets the "organization" edge to the Organization entity.
func (pc *PlatformCreate) SetOrganization(o *Organization) *PlatformCreate {
return pc.SetOrganizationID(o.ID)
}
// Mutation returns the PlatformMutation object of the builder.
func (pc *PlatformCreate) Mutation() *PlatformMutation {
return pc.mutation
}
// Save creates the Platform in the database.
func (pc *PlatformCreate) Save(ctx context.Context) (*Platform, error) {
pc.defaults()
return withHooks(ctx, pc.sqlSave, pc.mutation, pc.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (pc *PlatformCreate) SaveX(ctx context.Context) *Platform {
v, err := pc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (pc *PlatformCreate) Exec(ctx context.Context) error {
_, err := pc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (pc *PlatformCreate) ExecX(ctx context.Context) {
if err := pc.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (pc *PlatformCreate) defaults() {
if _, ok := pc.mutation.CreatedAt(); !ok {
v := platform.DefaultCreatedAt()
pc.mutation.SetCreatedAt(v)
}
if _, ok := pc.mutation.UpdatedAt(); !ok {
v := platform.DefaultUpdatedAt()
pc.mutation.SetUpdatedAt(v)
}
if _, ok := pc.mutation.ID(); !ok {
v := platform.DefaultID()
pc.mutation.SetID(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (pc *PlatformCreate) check() error {
if _, ok := pc.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Platform.created_at"`)}
}
if _, ok := pc.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Platform.updated_at"`)}
}
if _, ok := pc.mutation.OrgID(); !ok {
return &ValidationError{Name: "org_id", err: errors.New(`ent: missing required field "Platform.org_id"`)}
}
if _, ok := pc.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Platform.name"`)}
}
if v, ok := pc.mutation.Name(); ok {
if err := platform.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Platform.name": %w`, err)}
}
}
if _, ok := pc.mutation.DisplayName(); !ok {
return &ValidationError{Name: "display_name", err: errors.New(`ent: missing required field "Platform.display_name"`)}
}
if _, ok := pc.mutation.CreatorID(); !ok {
return &ValidationError{Name: "creator_id", err: errors.New(`ent: missing required field "Platform.creator_id"`)}
}
if _, ok := pc.mutation.CreatorID(); !ok {
return &ValidationError{Name: "creator", err: errors.New(`ent: missing required edge "Platform.creator"`)}
}
if _, ok := pc.mutation.OrganizationID(); !ok {
return &ValidationError{Name: "organization", err: errors.New(`ent: missing required edge "Platform.organization"`)}
}
return nil
}
func (pc *PlatformCreate) sqlSave(ctx context.Context) (*Platform, error) {
if err := pc.check(); err != nil {
return nil, err
}
_node, _spec := pc.createSpec()
if err := sqlgraph.CreateNode(ctx, pc.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
if _spec.ID.Value != nil {
if id, ok := _spec.ID.Value.(*uuid.UUID); ok {
_node.ID = *id
} else if err := _node.ID.Scan(_spec.ID.Value); err != nil {
return nil, err
}
}
pc.mutation.id = &_node.ID
pc.mutation.done = true
return _node, nil
}
func (pc *PlatformCreate) createSpec() (*Platform, *sqlgraph.CreateSpec) {
var (
_node = &Platform{config: pc.config}
_spec = sqlgraph.NewCreateSpec(platform.Table, sqlgraph.NewFieldSpec(platform.FieldID, field.TypeUUID))
)
_spec.OnConflict = pc.conflict
if id, ok := pc.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = &id
}
if value, ok := pc.mutation.CreatedAt(); ok {
_spec.SetField(platform.FieldCreatedAt, field.TypeTime, value)
_node.CreatedAt = value
}
if value, ok := pc.mutation.UpdatedAt(); ok {
_spec.SetField(platform.FieldUpdatedAt, field.TypeTime, value)
_node.UpdatedAt = value
}
if value, ok := pc.mutation.Name(); ok {
_spec.SetField(platform.FieldName, field.TypeString, value)
_node.Name = value
}
if value, ok := pc.mutation.DisplayName(); ok {
_spec.SetField(platform.FieldDisplayName, field.TypeString, value)
_node.DisplayName = value
}
if nodes := pc.mutation.CreatorIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: platform.CreatorTable,
Columns: []string{platform.CreatorColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.CreatorID = nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := pc.mutation.OrganizationIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: platform.OrganizationTable,
Columns: []string{platform.OrganizationColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(organization.FieldID, field.TypeUUID),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.OrgID = 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.Platform.Create().
// SetCreatedAt(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.PlatformUpsert) {
// SetCreatedAt(v+v).
// }).
// Exec(ctx)
func (pc *PlatformCreate) OnConflict(opts ...sql.ConflictOption) *PlatformUpsertOne {
pc.conflict = opts
return &PlatformUpsertOne{
create: pc,
}
}
// OnConflictColumns calls `OnConflict` and configures the columns
// as conflict target. Using this option is equivalent to using:
//
// client.Platform.Create().
// OnConflict(sql.ConflictColumns(columns...)).
// Exec(ctx)
func (pc *PlatformCreate) OnConflictColumns(columns ...string) *PlatformUpsertOne {
pc.conflict = append(pc.conflict, sql.ConflictColumns(columns...))
return &PlatformUpsertOne{
create: pc,
}
}
type (
// PlatformUpsertOne is the builder for "upsert"-ing
// one Platform node.
PlatformUpsertOne struct {
create *PlatformCreate
}
// PlatformUpsert is the "OnConflict" setter.
PlatformUpsert struct {
*sql.UpdateSet
}
)
// SetUpdatedAt sets the "updated_at" field.
func (u *PlatformUpsert) SetUpdatedAt(v time.Time) *PlatformUpsert {
u.Set(platform.FieldUpdatedAt, v)
return u
}
// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
func (u *PlatformUpsert) UpdateUpdatedAt() *PlatformUpsert {
u.SetExcluded(platform.FieldUpdatedAt)
return u
}
// SetOrgID sets the "org_id" field.
func (u *PlatformUpsert) SetOrgID(v uuid.UUID) *PlatformUpsert {
u.Set(platform.FieldOrgID, v)
return u
}
// UpdateOrgID sets the "org_id" field to the value that was provided on create.
func (u *PlatformUpsert) UpdateOrgID() *PlatformUpsert {
u.SetExcluded(platform.FieldOrgID)
return u
}
// SetName sets the "name" field.
func (u *PlatformUpsert) SetName(v string) *PlatformUpsert {
u.Set(platform.FieldName, v)
return u
}
// UpdateName sets the "name" field to the value that was provided on create.
func (u *PlatformUpsert) UpdateName() *PlatformUpsert {
u.SetExcluded(platform.FieldName)
return u
}
// SetDisplayName sets the "display_name" field.
func (u *PlatformUpsert) SetDisplayName(v string) *PlatformUpsert {
u.Set(platform.FieldDisplayName, v)
return u
}
// UpdateDisplayName sets the "display_name" field to the value that was provided on create.
func (u *PlatformUpsert) UpdateDisplayName() *PlatformUpsert {
u.SetExcluded(platform.FieldDisplayName)
return u
}
// SetCreatorID sets the "creator_id" field.
func (u *PlatformUpsert) SetCreatorID(v uuid.UUID) *PlatformUpsert {
u.Set(platform.FieldCreatorID, v)
return u
}
// UpdateCreatorID sets the "creator_id" field to the value that was provided on create.
func (u *PlatformUpsert) UpdateCreatorID() *PlatformUpsert {
u.SetExcluded(platform.FieldCreatorID)
return u
}
// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field.
// Using this option is equivalent to using:
//
// client.Platform.Create().
// OnConflict(
// sql.ResolveWithNewValues(),
// sql.ResolveWith(func(u *sql.UpdateSet) {
// u.SetIgnore(platform.FieldID)
// }),
// ).
// Exec(ctx)
func (u *PlatformUpsertOne) UpdateNewValues() *PlatformUpsertOne {
u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
if _, exists := u.create.mutation.ID(); exists {
s.SetIgnore(platform.FieldID)
}
if _, exists := u.create.mutation.CreatedAt(); exists {
s.SetIgnore(platform.FieldCreatedAt)
}
}))
return u
}
// Ignore sets each column to itself in case of conflict.
// Using this option is equivalent to using:
//
// client.Platform.Create().
// OnConflict(sql.ResolveWithIgnore()).
// Exec(ctx)
func (u *PlatformUpsertOne) Ignore() *PlatformUpsertOne {
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 *PlatformUpsertOne) DoNothing() *PlatformUpsertOne {
u.create.conflict = append(u.create.conflict, sql.DoNothing())
return u
}
// Update allows overriding fields `UPDATE` values. See the PlatformCreate.OnConflict
// documentation for more info.
func (u *PlatformUpsertOne) Update(set func(*PlatformUpsert)) *PlatformUpsertOne {
u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
set(&PlatformUpsert{UpdateSet: update})
}))
return u
}
// SetUpdatedAt sets the "updated_at" field.
func (u *PlatformUpsertOne) SetUpdatedAt(v time.Time) *PlatformUpsertOne {
return u.Update(func(s *PlatformUpsert) {
s.SetUpdatedAt(v)
})
}
// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
func (u *PlatformUpsertOne) UpdateUpdatedAt() *PlatformUpsertOne {
return u.Update(func(s *PlatformUpsert) {
s.UpdateUpdatedAt()
})
}
// SetOrgID sets the "org_id" field.
func (u *PlatformUpsertOne) SetOrgID(v uuid.UUID) *PlatformUpsertOne {
return u.Update(func(s *PlatformUpsert) {
s.SetOrgID(v)
})
}
// UpdateOrgID sets the "org_id" field to the value that was provided on create.
func (u *PlatformUpsertOne) UpdateOrgID() *PlatformUpsertOne {
return u.Update(func(s *PlatformUpsert) {
s.UpdateOrgID()
})
}
// SetName sets the "name" field.
func (u *PlatformUpsertOne) SetName(v string) *PlatformUpsertOne {
return u.Update(func(s *PlatformUpsert) {
s.SetName(v)
})
}
// UpdateName sets the "name" field to the value that was provided on create.
func (u *PlatformUpsertOne) UpdateName() *PlatformUpsertOne {
return u.Update(func(s *PlatformUpsert) {
s.UpdateName()
})
}
// SetDisplayName sets the "display_name" field.
func (u *PlatformUpsertOne) SetDisplayName(v string) *PlatformUpsertOne {
return u.Update(func(s *PlatformUpsert) {
s.SetDisplayName(v)
})
}
// UpdateDisplayName sets the "display_name" field to the value that was provided on create.
func (u *PlatformUpsertOne) UpdateDisplayName() *PlatformUpsertOne {
return u.Update(func(s *PlatformUpsert) {
s.UpdateDisplayName()
})
}
// SetCreatorID sets the "creator_id" field.
func (u *PlatformUpsertOne) SetCreatorID(v uuid.UUID) *PlatformUpsertOne {
return u.Update(func(s *PlatformUpsert) {
s.SetCreatorID(v)
})
}
// UpdateCreatorID sets the "creator_id" field to the value that was provided on create.
func (u *PlatformUpsertOne) UpdateCreatorID() *PlatformUpsertOne {
return u.Update(func(s *PlatformUpsert) {
s.UpdateCreatorID()
})
}
// Exec executes the query.
func (u *PlatformUpsertOne) Exec(ctx context.Context) error {
if len(u.create.conflict) == 0 {
return errors.New("ent: missing options for PlatformCreate.OnConflict")
}
return u.create.Exec(ctx)
}
// ExecX is like Exec, but panics if an error occurs.
func (u *PlatformUpsertOne) ExecX(ctx context.Context) {
if err := u.create.Exec(ctx); err != nil {
panic(err)
}
}
// Exec executes the UPSERT query and returns the inserted/updated ID.
func (u *PlatformUpsertOne) ID(ctx context.Context) (id uuid.UUID, err error) {
if u.create.driver.Dialect() == dialect.MySQL {
// In case of "ON CONFLICT", there is no way to get back non-numeric ID
// fields from the database since MySQL does not support the RETURNING clause.
return id, errors.New("ent: PlatformUpsertOne.ID is not supported by MySQL driver. Use PlatformUpsertOne.Exec instead")
}
node, err := u.create.Save(ctx)
if err != nil {
return id, err
}
return node.ID, nil
}
// IDX is like ID, but panics if an error occurs.
func (u *PlatformUpsertOne) IDX(ctx context.Context) uuid.UUID {
id, err := u.ID(ctx)
if err != nil {
panic(err)
}
return id
}
// PlatformCreateBulk is the builder for creating many Platform entities in bulk.
type PlatformCreateBulk struct {
config
err error
builders []*PlatformCreate
conflict []sql.ConflictOption
}
// Save creates the Platform entities in the database.
func (pcb *PlatformCreateBulk) Save(ctx context.Context) ([]*Platform, error) {
if pcb.err != nil {
return nil, pcb.err
}
specs := make([]*sqlgraph.CreateSpec, len(pcb.builders))
nodes := make([]*Platform, len(pcb.builders))
mutators := make([]Mutator, len(pcb.builders))
for i := range pcb.builders {
func(i int, root context.Context) {
builder := pcb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*PlatformMutation)
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, pcb.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
spec.OnConflict = pcb.conflict
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, pcb.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, pcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (pcb *PlatformCreateBulk) SaveX(ctx context.Context) []*Platform {
v, err := pcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (pcb *PlatformCreateBulk) Exec(ctx context.Context) error {
_, err := pcb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (pcb *PlatformCreateBulk) ExecX(ctx context.Context) {
if err := pcb.Exec(ctx); err != nil {
panic(err)
}
}
// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
// of the `INSERT` statement. For example:
//
// client.Platform.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.PlatformUpsert) {
// SetCreatedAt(v+v).
// }).
// Exec(ctx)
func (pcb *PlatformCreateBulk) OnConflict(opts ...sql.ConflictOption) *PlatformUpsertBulk {
pcb.conflict = opts
return &PlatformUpsertBulk{
create: pcb,
}
}
// OnConflictColumns calls `OnConflict` and configures the columns
// as conflict target. Using this option is equivalent to using:
//
// client.Platform.Create().
// OnConflict(sql.ConflictColumns(columns...)).
// Exec(ctx)
func (pcb *PlatformCreateBulk) OnConflictColumns(columns ...string) *PlatformUpsertBulk {
pcb.conflict = append(pcb.conflict, sql.ConflictColumns(columns...))
return &PlatformUpsertBulk{
create: pcb,
}
}
// PlatformUpsertBulk is the builder for "upsert"-ing
// a bulk of Platform nodes.
type PlatformUpsertBulk struct {
create *PlatformCreateBulk
}
// UpdateNewValues updates the mutable fields using the new values that
// were set on create. Using this option is equivalent to using:
//
// client.Platform.Create().
// OnConflict(
// sql.ResolveWithNewValues(),
// sql.ResolveWith(func(u *sql.UpdateSet) {
// u.SetIgnore(platform.FieldID)
// }),
// ).
// Exec(ctx)
func (u *PlatformUpsertBulk) UpdateNewValues() *PlatformUpsertBulk {
u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
for _, b := range u.create.builders {
if _, exists := b.mutation.ID(); exists {
s.SetIgnore(platform.FieldID)
}
if _, exists := b.mutation.CreatedAt(); exists {
s.SetIgnore(platform.FieldCreatedAt)
}
}
}))
return u
}
// Ignore sets each column to itself in case of conflict.
// Using this option is equivalent to using:
//
// client.Platform.Create().
// OnConflict(sql.ResolveWithIgnore()).
// Exec(ctx)
func (u *PlatformUpsertBulk) Ignore() *PlatformUpsertBulk {
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 *PlatformUpsertBulk) DoNothing() *PlatformUpsertBulk {
u.create.conflict = append(u.create.conflict, sql.DoNothing())
return u
}
// Update allows overriding fields `UPDATE` values. See the PlatformCreateBulk.OnConflict
// documentation for more info.
func (u *PlatformUpsertBulk) Update(set func(*PlatformUpsert)) *PlatformUpsertBulk {
u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
set(&PlatformUpsert{UpdateSet: update})
}))
return u
}
// SetUpdatedAt sets the "updated_at" field.
func (u *PlatformUpsertBulk) SetUpdatedAt(v time.Time) *PlatformUpsertBulk {
return u.Update(func(s *PlatformUpsert) {
s.SetUpdatedAt(v)
})
}
// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
func (u *PlatformUpsertBulk) UpdateUpdatedAt() *PlatformUpsertBulk {
return u.Update(func(s *PlatformUpsert) {
s.UpdateUpdatedAt()
})
}
// SetOrgID sets the "org_id" field.
func (u *PlatformUpsertBulk) SetOrgID(v uuid.UUID) *PlatformUpsertBulk {
return u.Update(func(s *PlatformUpsert) {
s.SetOrgID(v)
})
}
// UpdateOrgID sets the "org_id" field to the value that was provided on create.
func (u *PlatformUpsertBulk) UpdateOrgID() *PlatformUpsertBulk {
return u.Update(func(s *PlatformUpsert) {
s.UpdateOrgID()
})
}
// SetName sets the "name" field.
func (u *PlatformUpsertBulk) SetName(v string) *PlatformUpsertBulk {
return u.Update(func(s *PlatformUpsert) {
s.SetName(v)
})
}
// UpdateName sets the "name" field to the value that was provided on create.
func (u *PlatformUpsertBulk) UpdateName() *PlatformUpsertBulk {
return u.Update(func(s *PlatformUpsert) {
s.UpdateName()
})
}
// SetDisplayName sets the "display_name" field.
func (u *PlatformUpsertBulk) SetDisplayName(v string) *PlatformUpsertBulk {
return u.Update(func(s *PlatformUpsert) {
s.SetDisplayName(v)
})
}
// UpdateDisplayName sets the "display_name" field to the value that was provided on create.
func (u *PlatformUpsertBulk) UpdateDisplayName() *PlatformUpsertBulk {
return u.Update(func(s *PlatformUpsert) {
s.UpdateDisplayName()
})
}
// SetCreatorID sets the "creator_id" field.
func (u *PlatformUpsertBulk) SetCreatorID(v uuid.UUID) *PlatformUpsertBulk {
return u.Update(func(s *PlatformUpsert) {
s.SetCreatorID(v)
})
}
// UpdateCreatorID sets the "creator_id" field to the value that was provided on create.
func (u *PlatformUpsertBulk) UpdateCreatorID() *PlatformUpsertBulk {
return u.Update(func(s *PlatformUpsert) {
s.UpdateCreatorID()
})
}
// Exec executes the query.
func (u *PlatformUpsertBulk) 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 PlatformCreateBulk instead", i)
}
}
if len(u.create.conflict) == 0 {
return errors.New("ent: missing options for PlatformCreateBulk.OnConflict")
}
return u.create.Exec(ctx)
}
// ExecX is like Exec, but panics if an error occurs.
func (u *PlatformUpsertBulk) ExecX(ctx context.Context) {
if err := u.create.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,88 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/holos-run/holos/internal/ent/platform"
"github.com/holos-run/holos/internal/ent/predicate"
)
// PlatformDelete is the builder for deleting a Platform entity.
type PlatformDelete struct {
config
hooks []Hook
mutation *PlatformMutation
}
// Where appends a list predicates to the PlatformDelete builder.
func (pd *PlatformDelete) Where(ps ...predicate.Platform) *PlatformDelete {
pd.mutation.Where(ps...)
return pd
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (pd *PlatformDelete) Exec(ctx context.Context) (int, error) {
return withHooks(ctx, pd.sqlExec, pd.mutation, pd.hooks)
}
// ExecX is like Exec, but panics if an error occurs.
func (pd *PlatformDelete) ExecX(ctx context.Context) int {
n, err := pd.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (pd *PlatformDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(platform.Table, sqlgraph.NewFieldSpec(platform.FieldID, field.TypeUUID))
if ps := pd.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, pd.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
pd.mutation.done = true
return affected, err
}
// PlatformDeleteOne is the builder for deleting a single Platform entity.
type PlatformDeleteOne struct {
pd *PlatformDelete
}
// Where appends a list predicates to the PlatformDelete builder.
func (pdo *PlatformDeleteOne) Where(ps ...predicate.Platform) *PlatformDeleteOne {
pdo.pd.mutation.Where(ps...)
return pdo
}
// Exec executes the deletion query.
func (pdo *PlatformDeleteOne) Exec(ctx context.Context) error {
n, err := pdo.pd.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{platform.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (pdo *PlatformDeleteOne) ExecX(ctx context.Context) {
if err := pdo.Exec(ctx); err != nil {
panic(err)
}
}

View File

@@ -0,0 +1,681 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/gofrs/uuid"
"github.com/holos-run/holos/internal/ent/organization"
"github.com/holos-run/holos/internal/ent/platform"
"github.com/holos-run/holos/internal/ent/predicate"
"github.com/holos-run/holos/internal/ent/user"
)
// PlatformQuery is the builder for querying Platform entities.
type PlatformQuery struct {
config
ctx *QueryContext
order []platform.OrderOption
inters []Interceptor
predicates []predicate.Platform
withCreator *UserQuery
withOrganization *OrganizationQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the PlatformQuery builder.
func (pq *PlatformQuery) Where(ps ...predicate.Platform) *PlatformQuery {
pq.predicates = append(pq.predicates, ps...)
return pq
}
// Limit the number of records to be returned by this query.
func (pq *PlatformQuery) Limit(limit int) *PlatformQuery {
pq.ctx.Limit = &limit
return pq
}
// Offset to start from.
func (pq *PlatformQuery) Offset(offset int) *PlatformQuery {
pq.ctx.Offset = &offset
return pq
}
// 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 (pq *PlatformQuery) Unique(unique bool) *PlatformQuery {
pq.ctx.Unique = &unique
return pq
}
// Order specifies how the records should be ordered.
func (pq *PlatformQuery) Order(o ...platform.OrderOption) *PlatformQuery {
pq.order = append(pq.order, o...)
return pq
}
// QueryCreator chains the current query on the "creator" edge.
func (pq *PlatformQuery) QueryCreator() *UserQuery {
query := (&UserClient{config: pq.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := pq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := pq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(platform.Table, platform.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, platform.CreatorTable, platform.CreatorColumn),
)
fromU = sqlgraph.SetNeighbors(pq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryOrganization chains the current query on the "organization" edge.
func (pq *PlatformQuery) QueryOrganization() *OrganizationQuery {
query := (&OrganizationClient{config: pq.config}).Query()
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := pq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := pq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(platform.Table, platform.FieldID, selector),
sqlgraph.To(organization.Table, organization.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, platform.OrganizationTable, platform.OrganizationColumn),
)
fromU = sqlgraph.SetNeighbors(pq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Platform entity from the query.
// Returns a *NotFoundError when no Platform was found.
func (pq *PlatformQuery) First(ctx context.Context) (*Platform, error) {
nodes, err := pq.Limit(1).All(setContextOp(ctx, pq.ctx, "First"))
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{platform.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (pq *PlatformQuery) FirstX(ctx context.Context) *Platform {
node, err := pq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Platform ID from the query.
// Returns a *NotFoundError when no Platform ID was found.
func (pq *PlatformQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = pq.Limit(1).IDs(setContextOp(ctx, pq.ctx, "FirstID")); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{platform.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (pq *PlatformQuery) FirstIDX(ctx context.Context) uuid.UUID {
id, err := pq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Platform entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Platform entity is found.
// Returns a *NotFoundError when no Platform entities are found.
func (pq *PlatformQuery) Only(ctx context.Context) (*Platform, error) {
nodes, err := pq.Limit(2).All(setContextOp(ctx, pq.ctx, "Only"))
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{platform.Label}
default:
return nil, &NotSingularError{platform.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (pq *PlatformQuery) OnlyX(ctx context.Context) *Platform {
node, err := pq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Platform ID in the query.
// Returns a *NotSingularError when more than one Platform ID is found.
// Returns a *NotFoundError when no entities are found.
func (pq *PlatformQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = pq.Limit(2).IDs(setContextOp(ctx, pq.ctx, "OnlyID")); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{platform.Label}
default:
err = &NotSingularError{platform.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (pq *PlatformQuery) OnlyIDX(ctx context.Context) uuid.UUID {
id, err := pq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Platforms.
func (pq *PlatformQuery) All(ctx context.Context) ([]*Platform, error) {
ctx = setContextOp(ctx, pq.ctx, "All")
if err := pq.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Platform, *PlatformQuery]()
return withInterceptors[[]*Platform](ctx, pq, qr, pq.inters)
}
// AllX is like All, but panics if an error occurs.
func (pq *PlatformQuery) AllX(ctx context.Context) []*Platform {
nodes, err := pq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Platform IDs.
func (pq *PlatformQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) {
if pq.ctx.Unique == nil && pq.path != nil {
pq.Unique(true)
}
ctx = setContextOp(ctx, pq.ctx, "IDs")
if err = pq.Select(platform.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (pq *PlatformQuery) IDsX(ctx context.Context) []uuid.UUID {
ids, err := pq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (pq *PlatformQuery) Count(ctx context.Context) (int, error) {
ctx = setContextOp(ctx, pq.ctx, "Count")
if err := pq.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, pq, querierCount[*PlatformQuery](), pq.inters)
}
// CountX is like Count, but panics if an error occurs.
func (pq *PlatformQuery) CountX(ctx context.Context) int {
count, err := pq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (pq *PlatformQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, pq.ctx, "Exist")
switch _, err := pq.FirstID(ctx); {
case IsNotFound(err):
return false, nil
case err != nil:
return false, fmt.Errorf("ent: check existence: %w", err)
default:
return true, nil
}
}
// ExistX is like Exist, but panics if an error occurs.
func (pq *PlatformQuery) ExistX(ctx context.Context) bool {
exist, err := pq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the PlatformQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (pq *PlatformQuery) Clone() *PlatformQuery {
if pq == nil {
return nil
}
return &PlatformQuery{
config: pq.config,
ctx: pq.ctx.Clone(),
order: append([]platform.OrderOption{}, pq.order...),
inters: append([]Interceptor{}, pq.inters...),
predicates: append([]predicate.Platform{}, pq.predicates...),
withCreator: pq.withCreator.Clone(),
withOrganization: pq.withOrganization.Clone(),
// clone intermediate query.
sql: pq.sql.Clone(),
path: pq.path,
}
}
// WithCreator tells the query-builder to eager-load the nodes that are connected to
// the "creator" edge. The optional arguments are used to configure the query builder of the edge.
func (pq *PlatformQuery) WithCreator(opts ...func(*UserQuery)) *PlatformQuery {
query := (&UserClient{config: pq.config}).Query()
for _, opt := range opts {
opt(query)
}
pq.withCreator = query
return pq
}
// WithOrganization tells the query-builder to eager-load the nodes that are connected to
// the "organization" edge. The optional arguments are used to configure the query builder of the edge.
func (pq *PlatformQuery) WithOrganization(opts ...func(*OrganizationQuery)) *PlatformQuery {
query := (&OrganizationClient{config: pq.config}).Query()
for _, opt := range opts {
opt(query)
}
pq.withOrganization = query
return pq
}
// 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 {
// CreatedAt time.Time `json:"created_at,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Platform.Query().
// GroupBy(platform.FieldCreatedAt).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (pq *PlatformQuery) GroupBy(field string, fields ...string) *PlatformGroupBy {
pq.ctx.Fields = append([]string{field}, fields...)
grbuild := &PlatformGroupBy{build: pq}
grbuild.flds = &pq.ctx.Fields
grbuild.label = platform.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 {
// CreatedAt time.Time `json:"created_at,omitempty"`
// }
//
// client.Platform.Query().
// Select(platform.FieldCreatedAt).
// Scan(ctx, &v)
func (pq *PlatformQuery) Select(fields ...string) *PlatformSelect {
pq.ctx.Fields = append(pq.ctx.Fields, fields...)
sbuild := &PlatformSelect{PlatformQuery: pq}
sbuild.label = platform.Label
sbuild.flds, sbuild.scan = &pq.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a PlatformSelect configured with the given aggregations.
func (pq *PlatformQuery) Aggregate(fns ...AggregateFunc) *PlatformSelect {
return pq.Select().Aggregate(fns...)
}
func (pq *PlatformQuery) prepareQuery(ctx context.Context) error {
for _, inter := range pq.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, pq); err != nil {
return err
}
}
}
for _, f := range pq.ctx.Fields {
if !platform.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if pq.path != nil {
prev, err := pq.path(ctx)
if err != nil {
return err
}
pq.sql = prev
}
return nil
}
func (pq *PlatformQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Platform, error) {
var (
nodes = []*Platform{}
_spec = pq.querySpec()
loadedTypes = [2]bool{
pq.withCreator != nil,
pq.withOrganization != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Platform).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Platform{config: pq.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, pq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := pq.withCreator; query != nil {
if err := pq.loadCreator(ctx, query, nodes, nil,
func(n *Platform, e *User) { n.Edges.Creator = e }); err != nil {
return nil, err
}
}
if query := pq.withOrganization; query != nil {
if err := pq.loadOrganization(ctx, query, nodes, nil,
func(n *Platform, e *Organization) { n.Edges.Organization = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (pq *PlatformQuery) loadCreator(ctx context.Context, query *UserQuery, nodes []*Platform, init func(*Platform), assign func(*Platform, *User)) error {
ids := make([]uuid.UUID, 0, len(nodes))
nodeids := make(map[uuid.UUID][]*Platform)
for i := range nodes {
fk := nodes[i].CreatorID
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(user.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return fmt.Errorf(`unexpected foreign-key "creator_id" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (pq *PlatformQuery) loadOrganization(ctx context.Context, query *OrganizationQuery, nodes []*Platform, init func(*Platform), assign func(*Platform, *Organization)) error {
ids := make([]uuid.UUID, 0, len(nodes))
nodeids := make(map[uuid.UUID][]*Platform)
for i := range nodes {
fk := nodes[i].OrgID
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
if len(ids) == 0 {
return nil
}
query.Where(organization.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 "org_id" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (pq *PlatformQuery) sqlCount(ctx context.Context) (int, error) {
_spec := pq.querySpec()
_spec.Node.Columns = pq.ctx.Fields
if len(pq.ctx.Fields) > 0 {
_spec.Unique = pq.ctx.Unique != nil && *pq.ctx.Unique
}
return sqlgraph.CountNodes(ctx, pq.driver, _spec)
}
func (pq *PlatformQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(platform.Table, platform.Columns, sqlgraph.NewFieldSpec(platform.FieldID, field.TypeUUID))
_spec.From = pq.sql
if unique := pq.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if pq.path != nil {
_spec.Unique = true
}
if fields := pq.ctx.Fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, platform.FieldID)
for i := range fields {
if fields[i] != platform.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
if pq.withCreator != nil {
_spec.Node.AddColumnOnce(platform.FieldCreatorID)
}
if pq.withOrganization != nil {
_spec.Node.AddColumnOnce(platform.FieldOrgID)
}
}
if ps := pq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := pq.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := pq.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := pq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (pq *PlatformQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(pq.driver.Dialect())
t1 := builder.Table(platform.Table)
columns := pq.ctx.Fields
if len(columns) == 0 {
columns = platform.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if pq.sql != nil {
selector = pq.sql
selector.Select(selector.Columns(columns...)...)
}
if pq.ctx.Unique != nil && *pq.ctx.Unique {
selector.Distinct()
}
for _, p := range pq.predicates {
p(selector)
}
for _, p := range pq.order {
p(selector)
}
if offset := pq.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 := pq.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// PlatformGroupBy is the group-by builder for Platform entities.
type PlatformGroupBy struct {
selector
build *PlatformQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (pgb *PlatformGroupBy) Aggregate(fns ...AggregateFunc) *PlatformGroupBy {
pgb.fns = append(pgb.fns, fns...)
return pgb
}
// Scan applies the selector query and scans the result into the given value.
func (pgb *PlatformGroupBy) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, pgb.build.ctx, "GroupBy")
if err := pgb.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*PlatformQuery, *PlatformGroupBy](ctx, pgb.build, pgb, pgb.build.inters, v)
}
func (pgb *PlatformGroupBy) sqlScan(ctx context.Context, root *PlatformQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(pgb.fns))
for _, fn := range pgb.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*pgb.flds)+len(pgb.fns))
for _, f := range *pgb.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*pgb.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := pgb.build.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// PlatformSelect is the builder for selecting fields of Platform entities.
type PlatformSelect struct {
*PlatformQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (ps *PlatformSelect) Aggregate(fns ...AggregateFunc) *PlatformSelect {
ps.fns = append(ps.fns, fns...)
return ps
}
// Scan applies the selector query and scans the result into the given value.
func (ps *PlatformSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, ps.ctx, "Select")
if err := ps.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*PlatformQuery, *PlatformSelect](ctx, ps.PlatformQuery, ps, ps.inters, v)
}
func (ps *PlatformSelect) sqlScan(ctx context.Context, root *PlatformQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(ps.fns))
for _, fn := range ps.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*ps.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 := ps.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

View File

@@ -0,0 +1,549 @@
// 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/gofrs/uuid"
"github.com/holos-run/holos/internal/ent/organization"
"github.com/holos-run/holos/internal/ent/platform"
"github.com/holos-run/holos/internal/ent/predicate"
"github.com/holos-run/holos/internal/ent/user"
)
// PlatformUpdate is the builder for updating Platform entities.
type PlatformUpdate struct {
config
hooks []Hook
mutation *PlatformMutation
}
// Where appends a list predicates to the PlatformUpdate builder.
func (pu *PlatformUpdate) Where(ps ...predicate.Platform) *PlatformUpdate {
pu.mutation.Where(ps...)
return pu
}
// SetUpdatedAt sets the "updated_at" field.
func (pu *PlatformUpdate) SetUpdatedAt(t time.Time) *PlatformUpdate {
pu.mutation.SetUpdatedAt(t)
return pu
}
// SetOrgID sets the "org_id" field.
func (pu *PlatformUpdate) SetOrgID(u uuid.UUID) *PlatformUpdate {
pu.mutation.SetOrgID(u)
return pu
}
// SetNillableOrgID sets the "org_id" field if the given value is not nil.
func (pu *PlatformUpdate) SetNillableOrgID(u *uuid.UUID) *PlatformUpdate {
if u != nil {
pu.SetOrgID(*u)
}
return pu
}
// SetName sets the "name" field.
func (pu *PlatformUpdate) SetName(s string) *PlatformUpdate {
pu.mutation.SetName(s)
return pu
}
// SetNillableName sets the "name" field if the given value is not nil.
func (pu *PlatformUpdate) SetNillableName(s *string) *PlatformUpdate {
if s != nil {
pu.SetName(*s)
}
return pu
}
// SetDisplayName sets the "display_name" field.
func (pu *PlatformUpdate) SetDisplayName(s string) *PlatformUpdate {
pu.mutation.SetDisplayName(s)
return pu
}
// SetNillableDisplayName sets the "display_name" field if the given value is not nil.
func (pu *PlatformUpdate) SetNillableDisplayName(s *string) *PlatformUpdate {
if s != nil {
pu.SetDisplayName(*s)
}
return pu
}
// SetCreatorID sets the "creator_id" field.
func (pu *PlatformUpdate) SetCreatorID(u uuid.UUID) *PlatformUpdate {
pu.mutation.SetCreatorID(u)
return pu
}
// SetNillableCreatorID sets the "creator_id" field if the given value is not nil.
func (pu *PlatformUpdate) SetNillableCreatorID(u *uuid.UUID) *PlatformUpdate {
if u != nil {
pu.SetCreatorID(*u)
}
return pu
}
// SetCreator sets the "creator" edge to the User entity.
func (pu *PlatformUpdate) SetCreator(u *User) *PlatformUpdate {
return pu.SetCreatorID(u.ID)
}
// SetOrganizationID sets the "organization" edge to the Organization entity by ID.
func (pu *PlatformUpdate) SetOrganizationID(id uuid.UUID) *PlatformUpdate {
pu.mutation.SetOrganizationID(id)
return pu
}
// SetOrganization sets the "organization" edge to the Organization entity.
func (pu *PlatformUpdate) SetOrganization(o *Organization) *PlatformUpdate {
return pu.SetOrganizationID(o.ID)
}
// Mutation returns the PlatformMutation object of the builder.
func (pu *PlatformUpdate) Mutation() *PlatformMutation {
return pu.mutation
}
// ClearCreator clears the "creator" edge to the User entity.
func (pu *PlatformUpdate) ClearCreator() *PlatformUpdate {
pu.mutation.ClearCreator()
return pu
}
// ClearOrganization clears the "organization" edge to the Organization entity.
func (pu *PlatformUpdate) ClearOrganization() *PlatformUpdate {
pu.mutation.ClearOrganization()
return pu
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (pu *PlatformUpdate) Save(ctx context.Context) (int, error) {
pu.defaults()
return withHooks(ctx, pu.sqlSave, pu.mutation, pu.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (pu *PlatformUpdate) SaveX(ctx context.Context) int {
affected, err := pu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (pu *PlatformUpdate) Exec(ctx context.Context) error {
_, err := pu.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (pu *PlatformUpdate) ExecX(ctx context.Context) {
if err := pu.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (pu *PlatformUpdate) defaults() {
if _, ok := pu.mutation.UpdatedAt(); !ok {
v := platform.UpdateDefaultUpdatedAt()
pu.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (pu *PlatformUpdate) check() error {
if v, ok := pu.mutation.Name(); ok {
if err := platform.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Platform.name": %w`, err)}
}
}
if _, ok := pu.mutation.CreatorID(); pu.mutation.CreatorCleared() && !ok {
return errors.New(`ent: clearing a required unique edge "Platform.creator"`)
}
if _, ok := pu.mutation.OrganizationID(); pu.mutation.OrganizationCleared() && !ok {
return errors.New(`ent: clearing a required unique edge "Platform.organization"`)
}
return nil
}
func (pu *PlatformUpdate) sqlSave(ctx context.Context) (n int, err error) {
if err := pu.check(); err != nil {
return n, err
}
_spec := sqlgraph.NewUpdateSpec(platform.Table, platform.Columns, sqlgraph.NewFieldSpec(platform.FieldID, field.TypeUUID))
if ps := pu.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := pu.mutation.UpdatedAt(); ok {
_spec.SetField(platform.FieldUpdatedAt, field.TypeTime, value)
}
if value, ok := pu.mutation.Name(); ok {
_spec.SetField(platform.FieldName, field.TypeString, value)
}
if value, ok := pu.mutation.DisplayName(); ok {
_spec.SetField(platform.FieldDisplayName, field.TypeString, value)
}
if pu.mutation.CreatorCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: platform.CreatorTable,
Columns: []string{platform.CreatorColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := pu.mutation.CreatorIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: platform.CreatorTable,
Columns: []string{platform.CreatorColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if pu.mutation.OrganizationCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: platform.OrganizationTable,
Columns: []string{platform.OrganizationColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(organization.FieldID, field.TypeUUID),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := pu.mutation.OrganizationIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: platform.OrganizationTable,
Columns: []string{platform.OrganizationColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(organization.FieldID, field.TypeUUID),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if n, err = sqlgraph.UpdateNodes(ctx, pu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{platform.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
pu.mutation.done = true
return n, nil
}
// PlatformUpdateOne is the builder for updating a single Platform entity.
type PlatformUpdateOne struct {
config
fields []string
hooks []Hook
mutation *PlatformMutation
}
// SetUpdatedAt sets the "updated_at" field.
func (puo *PlatformUpdateOne) SetUpdatedAt(t time.Time) *PlatformUpdateOne {
puo.mutation.SetUpdatedAt(t)
return puo
}
// SetOrgID sets the "org_id" field.
func (puo *PlatformUpdateOne) SetOrgID(u uuid.UUID) *PlatformUpdateOne {
puo.mutation.SetOrgID(u)
return puo
}
// SetNillableOrgID sets the "org_id" field if the given value is not nil.
func (puo *PlatformUpdateOne) SetNillableOrgID(u *uuid.UUID) *PlatformUpdateOne {
if u != nil {
puo.SetOrgID(*u)
}
return puo
}
// SetName sets the "name" field.
func (puo *PlatformUpdateOne) SetName(s string) *PlatformUpdateOne {
puo.mutation.SetName(s)
return puo
}
// SetNillableName sets the "name" field if the given value is not nil.
func (puo *PlatformUpdateOne) SetNillableName(s *string) *PlatformUpdateOne {
if s != nil {
puo.SetName(*s)
}
return puo
}
// SetDisplayName sets the "display_name" field.
func (puo *PlatformUpdateOne) SetDisplayName(s string) *PlatformUpdateOne {
puo.mutation.SetDisplayName(s)
return puo
}
// SetNillableDisplayName sets the "display_name" field if the given value is not nil.
func (puo *PlatformUpdateOne) SetNillableDisplayName(s *string) *PlatformUpdateOne {
if s != nil {
puo.SetDisplayName(*s)
}
return puo
}
// SetCreatorID sets the "creator_id" field.
func (puo *PlatformUpdateOne) SetCreatorID(u uuid.UUID) *PlatformUpdateOne {
puo.mutation.SetCreatorID(u)
return puo
}
// SetNillableCreatorID sets the "creator_id" field if the given value is not nil.
func (puo *PlatformUpdateOne) SetNillableCreatorID(u *uuid.UUID) *PlatformUpdateOne {
if u != nil {
puo.SetCreatorID(*u)
}
return puo
}
// SetCreator sets the "creator" edge to the User entity.
func (puo *PlatformUpdateOne) SetCreator(u *User) *PlatformUpdateOne {
return puo.SetCreatorID(u.ID)
}
// SetOrganizationID sets the "organization" edge to the Organization entity by ID.
func (puo *PlatformUpdateOne) SetOrganizationID(id uuid.UUID) *PlatformUpdateOne {
puo.mutation.SetOrganizationID(id)
return puo
}
// SetOrganization sets the "organization" edge to the Organization entity.
func (puo *PlatformUpdateOne) SetOrganization(o *Organization) *PlatformUpdateOne {
return puo.SetOrganizationID(o.ID)
}
// Mutation returns the PlatformMutation object of the builder.
func (puo *PlatformUpdateOne) Mutation() *PlatformMutation {
return puo.mutation
}
// ClearCreator clears the "creator" edge to the User entity.
func (puo *PlatformUpdateOne) ClearCreator() *PlatformUpdateOne {
puo.mutation.ClearCreator()
return puo
}
// ClearOrganization clears the "organization" edge to the Organization entity.
func (puo *PlatformUpdateOne) ClearOrganization() *PlatformUpdateOne {
puo.mutation.ClearOrganization()
return puo
}
// Where appends a list predicates to the PlatformUpdate builder.
func (puo *PlatformUpdateOne) Where(ps ...predicate.Platform) *PlatformUpdateOne {
puo.mutation.Where(ps...)
return puo
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (puo *PlatformUpdateOne) Select(field string, fields ...string) *PlatformUpdateOne {
puo.fields = append([]string{field}, fields...)
return puo
}
// Save executes the query and returns the updated Platform entity.
func (puo *PlatformUpdateOne) Save(ctx context.Context) (*Platform, error) {
puo.defaults()
return withHooks(ctx, puo.sqlSave, puo.mutation, puo.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (puo *PlatformUpdateOne) SaveX(ctx context.Context) *Platform {
node, err := puo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (puo *PlatformUpdateOne) Exec(ctx context.Context) error {
_, err := puo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (puo *PlatformUpdateOne) ExecX(ctx context.Context) {
if err := puo.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (puo *PlatformUpdateOne) defaults() {
if _, ok := puo.mutation.UpdatedAt(); !ok {
v := platform.UpdateDefaultUpdatedAt()
puo.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (puo *PlatformUpdateOne) check() error {
if v, ok := puo.mutation.Name(); ok {
if err := platform.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Platform.name": %w`, err)}
}
}
if _, ok := puo.mutation.CreatorID(); puo.mutation.CreatorCleared() && !ok {
return errors.New(`ent: clearing a required unique edge "Platform.creator"`)
}
if _, ok := puo.mutation.OrganizationID(); puo.mutation.OrganizationCleared() && !ok {
return errors.New(`ent: clearing a required unique edge "Platform.organization"`)
}
return nil
}
func (puo *PlatformUpdateOne) sqlSave(ctx context.Context) (_node *Platform, err error) {
if err := puo.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(platform.Table, platform.Columns, sqlgraph.NewFieldSpec(platform.FieldID, field.TypeUUID))
id, ok := puo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Platform.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := puo.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, platform.FieldID)
for _, f := range fields {
if !platform.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != platform.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := puo.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := puo.mutation.UpdatedAt(); ok {
_spec.SetField(platform.FieldUpdatedAt, field.TypeTime, value)
}
if value, ok := puo.mutation.Name(); ok {
_spec.SetField(platform.FieldName, field.TypeString, value)
}
if value, ok := puo.mutation.DisplayName(); ok {
_spec.SetField(platform.FieldDisplayName, field.TypeString, value)
}
if puo.mutation.CreatorCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: platform.CreatorTable,
Columns: []string{platform.CreatorColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := puo.mutation.CreatorIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: platform.CreatorTable,
Columns: []string{platform.CreatorColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if puo.mutation.OrganizationCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: platform.OrganizationTable,
Columns: []string{platform.OrganizationColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(organization.FieldID, field.TypeUUID),
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := puo.mutation.OrganizationIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: false,
Table: platform.OrganizationTable,
Columns: []string{platform.OrganizationColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: sqlgraph.NewFieldSpec(organization.FieldID, field.TypeUUID),
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &Platform{config: puo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, puo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{platform.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
puo.mutation.done = true
return _node, nil
}

View File

@@ -9,5 +9,8 @@ import (
// Organization is the predicate function for organization builders.
type Organization func(*sql.Selector)
// Platform is the predicate function for platform builders.
type Platform func(*sql.Selector)
// User is the predicate function for user builders.
type User func(*sql.Selector)

View File

@@ -7,6 +7,7 @@ import (
"github.com/gofrs/uuid"
"github.com/holos-run/holos/internal/ent/organization"
"github.com/holos-run/holos/internal/ent/platform"
"github.com/holos-run/holos/internal/ent/schema"
"github.com/holos-run/holos/internal/ent/user"
)
@@ -40,6 +41,31 @@ func init() {
organizationDescID := organizationMixinFields0[0].Descriptor()
// organization.DefaultID holds the default value on creation for the id field.
organization.DefaultID = organizationDescID.Default.(func() uuid.UUID)
platformMixin := schema.Platform{}.Mixin()
platformMixinFields0 := platformMixin[0].Fields()
_ = platformMixinFields0
platformMixinFields1 := platformMixin[1].Fields()
_ = platformMixinFields1
platformFields := schema.Platform{}.Fields()
_ = platformFields
// platformDescCreatedAt is the schema descriptor for created_at field.
platformDescCreatedAt := platformMixinFields1[0].Descriptor()
// platform.DefaultCreatedAt holds the default value on creation for the created_at field.
platform.DefaultCreatedAt = platformDescCreatedAt.Default.(func() time.Time)
// platformDescUpdatedAt is the schema descriptor for updated_at field.
platformDescUpdatedAt := platformMixinFields1[1].Descriptor()
// platform.DefaultUpdatedAt holds the default value on creation for the updated_at field.
platform.DefaultUpdatedAt = platformDescUpdatedAt.Default.(func() time.Time)
// platform.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
platform.UpdateDefaultUpdatedAt = platformDescUpdatedAt.UpdateDefault.(func() time.Time)
// platformDescName is the schema descriptor for name field.
platformDescName := platformFields[1].Descriptor()
// platform.NameValidator is a validator for the "name" field. It is called by the builders before save.
platform.NameValidator = platformDescName.Validators[0].(func(string) error)
// platformDescID is the schema descriptor for id field.
platformDescID := platformMixinFields0[0].Descriptor()
// platform.DefaultID holds the default value on creation for the id field.
platform.DefaultID = platformDescID.Default.(func() uuid.UUID)
userMixin := schema.User{}.Mixin()
userMixinFields0 := userMixin[0].Fields()
_ = userMixinFields0

View File

@@ -34,5 +34,7 @@ func (Organization) Edges() []ent.Edge {
Unique().
Required(),
edge.To("users", User.Type),
edge.From("platforms", Platform.Type).
Ref("organization"),
}
}

View File

@@ -0,0 +1,41 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"github.com/gofrs/uuid"
)
type Platform struct {
ent.Schema
}
func (Platform) Mixin() []ent.Mixin {
return []ent.Mixin{
BaseMixin{},
TimeMixin{},
}
}
func (Platform) Fields() []ent.Field {
return []ent.Field{
field.UUID("org_id", uuid.UUID{}),
field.String("name").NotEmpty(),
field.String("display_name"),
field.UUID("creator_id", uuid.UUID{}),
}
}
func (Platform) Edges() []ent.Edge {
return []ent.Edge{
edge.To("creator", User.Type).
Field("creator_id").
Unique().
Required(),
edge.To("organization", Organization.Type).
Field("org_id").
Unique().
Required(),
}
}

View File

@@ -14,6 +14,8 @@ type Tx struct {
config
// Organization is the client for interacting with the Organization builders.
Organization *OrganizationClient
// Platform is the client for interacting with the Platform builders.
Platform *PlatformClient
// User is the client for interacting with the User builders.
User *UserClient
@@ -148,6 +150,7 @@ func (tx *Tx) Client() *Client {
func (tx *Tx) init() {
tx.Organization = NewOrganizationClient(tx.config)
tx.Platform = NewPlatformClient(tx.config)
tx.User = NewUserClient(tx.config)
}

View File

@@ -22,6 +22,8 @@
"@connectrpc/connect": "^1.4.0",
"@connectrpc/connect-query": "^1.3.1",
"@connectrpc/connect-web": "^1.4.0",
"@ngx-formly/core": "^6.3.0",
"@ngx-formly/material": "^6.3.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
@@ -34,6 +36,7 @@
"@bufbuild/protoc-gen-es": "^1.9.0",
"@connectrpc/protoc-gen-connect-es": "^1.4.0",
"@connectrpc/protoc-gen-connect-query": "^1.3.1",
"@ngx-formly/schematics": "^6.3.0",
"@types/jasmine": "~5.1.0",
"jasmine-core": "~5.1.0",
"karma": "~6.4.0",
@@ -3943,6 +3946,160 @@
"webpack": "^5.54.0"
}
},
"node_modules/@ngx-formly/core": {
"version": "6.3.0",
"resolved": "https://registry.npmjs.org/@ngx-formly/core/-/core-6.3.0.tgz",
"integrity": "sha512-9qCoPdLLVShoruzXeJUjMdIhfIlHCI+TggA3Wc01ISHTK2vXx1gNIFLuS+hez3JEzu8nIDRuA/nWqj4j8fJCNg==",
"dependencies": {
"tslib": "^2.0.0"
},
"peerDependencies": {
"@angular/forms": ">=13.2.0",
"rxjs": "^6.5.3 || ^7.0.0"
}
},
"node_modules/@ngx-formly/material": {
"version": "6.3.0",
"resolved": "https://registry.npmjs.org/@ngx-formly/material/-/material-6.3.0.tgz",
"integrity": "sha512-kzNNXQhOtPf2Uc4l02CO7njwKNJsaP+dpLt6cvYQA04fVALrO/dEJNbgUW6rlVp0oQQmobiu83lN1qWKmqAcng==",
"dependencies": {
"tslib": "^2.0.0"
},
"peerDependencies": {
"@angular/material": ">=13.0.0",
"@ngx-formly/core": "6.3.0"
}
},
"node_modules/@ngx-formly/schematics": {
"version": "6.3.0",
"resolved": "https://registry.npmjs.org/@ngx-formly/schematics/-/schematics-6.3.0.tgz",
"integrity": "sha512-XSzOvrZ1NoUhmd733bcgUFkl+26pSw8eyXChi9LwrS26nEPweR8RA/JxN+lFvIb92MWzLShLd1DY2oBz/0r0ZQ==",
"dev": true,
"dependencies": {
"@angular-devkit/core": "^13.0.3",
"@angular-devkit/schematics": "^13.0.3",
"@schematics/angular": "^13.0.3"
}
},
"node_modules/@ngx-formly/schematics/node_modules/@angular-devkit/core": {
"version": "13.3.11",
"resolved": "https://registry.npmjs.org/@angular-devkit/core/-/core-13.3.11.tgz",
"integrity": "sha512-rfqoLMRYhlz0wzKlHx7FfyIyQq8dKTsmbCoIVU1cEIH0gyTMVY7PbVzwRRcO6xp5waY+0hA+0Brriujpuhkm4w==",
"dev": true,
"dependencies": {
"ajv": "8.9.0",
"ajv-formats": "2.1.1",
"fast-json-stable-stringify": "2.1.0",
"magic-string": "0.25.7",
"rxjs": "6.6.7",
"source-map": "0.7.3"
},
"engines": {
"node": "^12.20.0 || ^14.15.0 || >=16.10.0",
"npm": "^6.11.0 || ^7.5.6 || >=8.0.0",
"yarn": ">= 1.13.0"
},
"peerDependencies": {
"chokidar": "^3.5.2"
},
"peerDependenciesMeta": {
"chokidar": {
"optional": true
}
}
},
"node_modules/@ngx-formly/schematics/node_modules/@angular-devkit/schematics": {
"version": "13.3.11",
"resolved": "https://registry.npmjs.org/@angular-devkit/schematics/-/schematics-13.3.11.tgz",
"integrity": "sha512-ben+EGXpCrClnIVAAnEQmhQdKmnnqFhMp5BqMxgOslSYBAmCutLA6rBu5vsc8kZcGian1wt+lueF7G1Uk5cGBg==",
"dev": true,
"dependencies": {
"@angular-devkit/core": "13.3.11",
"jsonc-parser": "3.0.0",
"magic-string": "0.25.7",
"ora": "5.4.1",
"rxjs": "6.6.7"
},
"engines": {
"node": "^12.20.0 || ^14.15.0 || >=16.10.0",
"npm": "^6.11.0 || ^7.5.6 || >=8.0.0",
"yarn": ">= 1.13.0"
}
},
"node_modules/@ngx-formly/schematics/node_modules/@schematics/angular": {
"version": "13.3.11",
"resolved": "https://registry.npmjs.org/@schematics/angular/-/angular-13.3.11.tgz",
"integrity": "sha512-imKBnKYEse0SBVELZO/753nkpt3eEgpjrYkB+AFWF9YfO/4RGnYXDHoH8CFkzxPH9QQCgNrmsVFNiYGS+P/S1A==",
"dev": true,
"dependencies": {
"@angular-devkit/core": "13.3.11",
"@angular-devkit/schematics": "13.3.11",
"jsonc-parser": "3.0.0"
},
"engines": {
"node": "^12.20.0 || ^14.15.0 || >=16.10.0",
"npm": "^6.11.0 || ^7.5.6 || >=8.0.0",
"yarn": ">= 1.13.0"
}
},
"node_modules/@ngx-formly/schematics/node_modules/ajv": {
"version": "8.9.0",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.9.0.tgz",
"integrity": "sha512-qOKJyNj/h+OWx7s5DePL6Zu1KeM9jPZhwBqs+7DzP6bGOvqzVCSf0xueYmVuaC/oQ/VtS2zLMLHdQFbkka+XDQ==",
"dev": true,
"dependencies": {
"fast-deep-equal": "^3.1.1",
"json-schema-traverse": "^1.0.0",
"require-from-string": "^2.0.2",
"uri-js": "^4.2.2"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/epoberezkin"
}
},
"node_modules/@ngx-formly/schematics/node_modules/jsonc-parser": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.0.0.tgz",
"integrity": "sha512-fQzRfAbIBnR0IQvftw9FJveWiHp72Fg20giDrHz6TdfB12UH/uue0D3hm57UB5KgAVuniLMCaS8P1IMj9NR7cA==",
"dev": true
},
"node_modules/@ngx-formly/schematics/node_modules/magic-string": {
"version": "0.25.7",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.25.7.tgz",
"integrity": "sha512-4CrMT5DOHTDk4HYDlzmwu4FVCcIYI8gauveasrdCu2IKIFOJ3f0v/8MDGJCDL9oD2ppz/Av1b0Nj345H9M+XIA==",
"dev": true,
"dependencies": {
"sourcemap-codec": "^1.4.4"
}
},
"node_modules/@ngx-formly/schematics/node_modules/rxjs": {
"version": "6.6.7",
"resolved": "https://registry.npmjs.org/rxjs/-/rxjs-6.6.7.tgz",
"integrity": "sha512-hTdwr+7yYNIT5n4AMYp85KA6yw2Va0FLa3Rguvbpa4W3I5xynaBZo41cM3XM+4Q6fRMj3sBYIR1VAmZMXYJvRQ==",
"dev": true,
"dependencies": {
"tslib": "^1.9.0"
},
"engines": {
"npm": ">=2.0.0"
}
},
"node_modules/@ngx-formly/schematics/node_modules/source-map": {
"version": "0.7.3",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.3.tgz",
"integrity": "sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ==",
"dev": true,
"engines": {
"node": ">= 8"
}
},
"node_modules/@ngx-formly/schematics/node_modules/tslib": {
"version": "1.14.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz",
"integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==",
"dev": true
},
"node_modules/@nodelib/fs.scandir": {
"version": "2.1.5",
"resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz",
@@ -11874,6 +12031,13 @@
"node": ">=0.10.0"
}
},
"node_modules/sourcemap-codec": {
"version": "1.4.8",
"resolved": "https://registry.npmjs.org/sourcemap-codec/-/sourcemap-codec-1.4.8.tgz",
"integrity": "sha512-9NykojV5Uih4lgo5So5dtw+f0JgJX30KCNI8gwhz2J9A15wD0Ml6tjHKwf6fTSa6fAdVBdZeNOs9eJ71qCk8vA==",
"deprecated": "Please use @jridgewell/sourcemap-codec instead",
"dev": true
},
"node_modules/spdx-correct": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.2.0.tgz",

View File

@@ -24,6 +24,8 @@
"@connectrpc/connect": "^1.4.0",
"@connectrpc/connect-query": "^1.3.1",
"@connectrpc/connect-web": "^1.4.0",
"@ngx-formly/core": "^6.3.0",
"@ngx-formly/material": "^6.3.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.3"
@@ -36,6 +38,7 @@
"@bufbuild/protoc-gen-es": "^1.9.0",
"@connectrpc/protoc-gen-connect-es": "^1.4.0",
"@connectrpc/protoc-gen-connect-query": "^1.3.1",
"@ngx-formly/schematics": "^6.3.0",
"@types/jasmine": "~5.1.0",
"jasmine-core": "~5.1.0",
"karma": "~6.4.0",

View File

@@ -1,7 +1,7 @@
import { ApplicationConfig, importProvidersFrom } from '@angular/core';
import { provideRouter } from '@angular/router';
import { FormlyModule } from '@ngx-formly/core';
// import { provideHttpClient, withFetch } from '@angular/common/http';
import { routes } from './app.routes';
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
import { ConnectModule } from '../connect/connect.module';
@@ -20,6 +20,7 @@ export const appConfig: ApplicationConfig = {
ConnectModule.forRoot({
baseUrl: window.location.origin
}),
FormlyModule.forRoot(),
),
]
};

View File

@@ -2,8 +2,12 @@ import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { ClusterListComponent } from './cluster-list/cluster-list.component';
import { ErrorNotFoundComponent } from './error-not-found/error-not-found.component';
import { PlatformConfigComponent } from './views/platform-config/platform-config.component';
import { AddressFormComponent } from './examples/address-form/address-form.component';
export const routes: Routes = [
{ path: 'platform-config', component: PlatformConfigComponent },
{ path: 'address-form', component: AddressFormComponent },
{ path: 'home', component: HomeComponent },
{ path: 'clusters', component: ClusterListComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' },

View File

@@ -0,0 +1,99 @@
<form [formGroup]="addressForm" novalidate (ngSubmit)="onSubmit()">
<mat-card class="shipping-card">
<mat-card-header>
<mat-card-title>Shipping Information</mat-card-title>
</mat-card-header>
<mat-card-content>
<div class="row">
<div class="col">
<mat-form-field class="full-width">
<input matInput placeholder="Company" formControlName="company">
</mat-form-field>
</div>
</div>
<div class="row">
<div class="col">
<mat-form-field class="full-width">
<input matInput placeholder="First name" formControlName="firstName">
@if (addressForm.controls['firstName'].hasError('required')) {
<mat-error>First name is <strong>required</strong></mat-error>
}
</mat-form-field>
</div>
<div class="col">
<mat-form-field class="full-width">
<input matInput placeholder="Last name" formControlName="lastName">
@if (addressForm.controls['lastName'].hasError('required')) {
<mat-error>Last name is <strong>required</strong></mat-error>
}
</mat-form-field>
</div>
</div>
<div class="row">
<div class="col">
<mat-form-field class="full-width">
<textarea matInput placeholder="Address" formControlName="address"></textarea>
@if (addressForm.controls['address'].hasError('required')) {
<mat-error>Address is <strong>required</strong></mat-error>
}
</mat-form-field>
</div>
</div>
<div class="row">
<div class="col">
@if (hasUnitNumber) {
<mat-form-field class="full-width">
<textarea matInput placeholder="Address 2" formControlName="address2"></textarea>
</mat-form-field>
} @else {
<button mat-button type="button" (click)="hasUnitNumber = !hasUnitNumber">
+ Add C/O, Apt, Suite, Unit
</button>
}
</div>
</div>
<div class="row">
<div class="col">
<mat-form-field class="full-width">
<input matInput placeholder="City" formControlName="city">
@if (addressForm.controls['city'].hasError('required')) {
<mat-error>City is <strong>required</strong></mat-error>
}
</mat-form-field>
</div>
<div class="col">
<mat-form-field class="full-width">
<mat-select placeholder="State" formControlName="state">
@for (state of states; track state) {
<mat-option [value]="state.abbreviation">{{ state.name }}</mat-option>
}
</mat-select>
@if (addressForm.controls['state'].hasError('required')) {
<mat-error>State is <strong>required</strong></mat-error>
}
</mat-form-field>
</div>
</div>
<div class="row">
<div class="col">
<mat-form-field class="full-width">
<input matInput #postalCode maxlength="5" placeholder="Postal Code" type="number" formControlName="postalCode">
<mat-hint align="end">{{postalCode.value.length}} / 5</mat-hint>
</mat-form-field>
</div>
</div>
<div class="row">
<div class="col">
<mat-radio-group formControlName="shipping">
<mat-radio-button value="free">Free Shipping</mat-radio-button>
<mat-radio-button value="priority">Priority Shipping</mat-radio-button>
<mat-radio-button value="nextday">Next Day Shipping</mat-radio-button>
</mat-radio-group>
</div>
</div>
</mat-card-content>
<mat-card-actions>
<button mat-raised-button color="primary" type="submit">Submit</button>
</mat-card-actions>
</mat-card>
</form>

View File

@@ -0,0 +1,27 @@
.full-width {
width: 100%;
}
.shipping-card {
min-width: 120px;
margin: 20px auto;
}
.mat-radio-button {
display: block;
margin: 5px 0;
}
.row {
display: flex;
flex-direction: row;
}
.col {
flex: 1;
margin-right: 20px;
}
.col:last-child {
margin-right: 0;
}

View File

@@ -0,0 +1,25 @@
import { waitForAsync, ComponentFixture, TestBed } from '@angular/core/testing';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { AddressFormComponent } from './address-form.component';
describe('AddressFormComponent', () => {
let component: AddressFormComponent;
let fixture: ComponentFixture<AddressFormComponent>;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [NoopAnimationsModule]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AddressFormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should compile', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,108 @@
import { Component, inject } from '@angular/core';
import { ReactiveFormsModule, FormBuilder, Validators } from '@angular/forms';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
import { MatSelectModule } from '@angular/material/select';
import { MatRadioModule } from '@angular/material/radio';
import { MatCardModule } from '@angular/material/card';
@Component({
selector: 'app-address-form',
templateUrl: './address-form.component.html',
styleUrl: './address-form.component.scss',
standalone: true,
imports: [
MatInputModule,
MatButtonModule,
MatSelectModule,
MatRadioModule,
MatCardModule,
ReactiveFormsModule
]
})
export class AddressFormComponent {
private fb = inject(FormBuilder);
addressForm = this.fb.group({
company: null,
firstName: [null, Validators.required],
lastName: [null, Validators.required],
address: [null, Validators.required],
address2: null,
city: [null, Validators.required],
state: [null, Validators.required],
postalCode: [null, Validators.compose([
Validators.required, Validators.minLength(5), Validators.maxLength(5)])
],
shipping: ['free', Validators.required]
});
hasUnitNumber = false;
states = [
{name: 'Alabama', abbreviation: 'AL'},
{name: 'Alaska', abbreviation: 'AK'},
{name: 'American Samoa', abbreviation: 'AS'},
{name: 'Arizona', abbreviation: 'AZ'},
{name: 'Arkansas', abbreviation: 'AR'},
{name: 'California', abbreviation: 'CA'},
{name: 'Colorado', abbreviation: 'CO'},
{name: 'Connecticut', abbreviation: 'CT'},
{name: 'Delaware', abbreviation: 'DE'},
{name: 'District Of Columbia', abbreviation: 'DC'},
{name: 'Federated States Of Micronesia', abbreviation: 'FM'},
{name: 'Florida', abbreviation: 'FL'},
{name: 'Georgia', abbreviation: 'GA'},
{name: 'Guam', abbreviation: 'GU'},
{name: 'Hawaii', abbreviation: 'HI'},
{name: 'Idaho', abbreviation: 'ID'},
{name: 'Illinois', abbreviation: 'IL'},
{name: 'Indiana', abbreviation: 'IN'},
{name: 'Iowa', abbreviation: 'IA'},
{name: 'Kansas', abbreviation: 'KS'},
{name: 'Kentucky', abbreviation: 'KY'},
{name: 'Louisiana', abbreviation: 'LA'},
{name: 'Maine', abbreviation: 'ME'},
{name: 'Marshall Islands', abbreviation: 'MH'},
{name: 'Maryland', abbreviation: 'MD'},
{name: 'Massachusetts', abbreviation: 'MA'},
{name: 'Michigan', abbreviation: 'MI'},
{name: 'Minnesota', abbreviation: 'MN'},
{name: 'Mississippi', abbreviation: 'MS'},
{name: 'Missouri', abbreviation: 'MO'},
{name: 'Montana', abbreviation: 'MT'},
{name: 'Nebraska', abbreviation: 'NE'},
{name: 'Nevada', abbreviation: 'NV'},
{name: 'New Hampshire', abbreviation: 'NH'},
{name: 'New Jersey', abbreviation: 'NJ'},
{name: 'New Mexico', abbreviation: 'NM'},
{name: 'New York', abbreviation: 'NY'},
{name: 'North Carolina', abbreviation: 'NC'},
{name: 'North Dakota', abbreviation: 'ND'},
{name: 'Northern Mariana Islands', abbreviation: 'MP'},
{name: 'Ohio', abbreviation: 'OH'},
{name: 'Oklahoma', abbreviation: 'OK'},
{name: 'Oregon', abbreviation: 'OR'},
{name: 'Palau', abbreviation: 'PW'},
{name: 'Pennsylvania', abbreviation: 'PA'},
{name: 'Puerto Rico', abbreviation: 'PR'},
{name: 'Rhode Island', abbreviation: 'RI'},
{name: 'South Carolina', abbreviation: 'SC'},
{name: 'South Dakota', abbreviation: 'SD'},
{name: 'Tennessee', abbreviation: 'TN'},
{name: 'Texas', abbreviation: 'TX'},
{name: 'Utah', abbreviation: 'UT'},
{name: 'Vermont', abbreviation: 'VT'},
{name: 'Virgin Islands', abbreviation: 'VI'},
{name: 'Virginia', abbreviation: 'VA'},
{name: 'Washington', abbreviation: 'WA'},
{name: 'West Virginia', abbreviation: 'WV'},
{name: 'Wisconsin', abbreviation: 'WI'},
{name: 'Wyoming', abbreviation: 'WY'}
];
onSubmit(): void {
alert('Thanks!');
}
}

View File

@@ -6,7 +6,7 @@
import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf";
import { Message, proto3 } from "@bufbuild/protobuf";
import { Timestamps } from "./timestamps_pb.js";
import { User } from "./user_pb.js";
import { Creator, User } from "./user_pb.js";
/**
* @generated from message holos.v1alpha1.Organization
@@ -34,6 +34,11 @@ export class Organization extends Message<Organization> {
*/
timestamps?: Timestamps;
/**
* @generated from field: holos.v1alpha1.Creator creator = 5;
*/
creator?: Creator;
constructor(data?: PartialMessage<Organization>) {
super();
proto3.util.initPartial(data, this);
@@ -46,6 +51,7 @@ export class Organization extends Message<Organization> {
{ no: 2, name: "name", kind: "scalar", T: 9 /* ScalarType.STRING */ },
{ no: 3, name: "display_name", kind: "scalar", T: 9 /* ScalarType.STRING */ },
{ no: 4, name: "timestamps", kind: "message", T: Timestamps },
{ no: 5, name: "creator", kind: "message", T: Creator },
]);
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): Organization {

View File

@@ -0,0 +1,35 @@
// @generated by protoc-gen-connect-query v1.3.1 with parameter "target=ts"
// @generated from file holos/v1alpha1/platform.proto (package holos.v1alpha1, syntax proto3)
/* eslint-disable */
// @ts-nocheck
import { MethodKind } from "@bufbuild/protobuf";
import { AddPlatformRequest, GetPlatformsRequest, GetPlatformsResponse } from "./platform_pb.js";
/**
* @generated from rpc holos.v1alpha1.PlatformService.GetPlatforms
*/
export const getPlatforms = {
localName: "getPlatforms",
name: "GetPlatforms",
kind: MethodKind.Unary,
I: GetPlatformsRequest,
O: GetPlatformsResponse,
service: {
typeName: "holos.v1alpha1.PlatformService"
}
} as const;
/**
* @generated from rpc holos.v1alpha1.PlatformService.AddPlatform
*/
export const addPlatform = {
localName: "addPlatform",
name: "AddPlatform",
kind: MethodKind.Unary,
I: AddPlatformRequest,
O: GetPlatformsResponse,
service: {
typeName: "holos.v1alpha1.PlatformService"
}
} as const;

View File

@@ -0,0 +1,35 @@
// @generated by protoc-gen-connect-es v1.4.0 with parameter "target=ts"
// @generated from file holos/v1alpha1/platform.proto (package holos.v1alpha1, syntax proto3)
/* eslint-disable */
// @ts-nocheck
import { AddPlatformRequest, GetPlatformsRequest, GetPlatformsResponse } from "./platform_pb.js";
import { MethodKind } from "@bufbuild/protobuf";
/**
* @generated from service holos.v1alpha1.PlatformService
*/
export const PlatformService = {
typeName: "holos.v1alpha1.PlatformService",
methods: {
/**
* @generated from rpc holos.v1alpha1.PlatformService.GetPlatforms
*/
getPlatforms: {
name: "GetPlatforms",
I: GetPlatformsRequest,
O: GetPlatformsResponse,
kind: MethodKind.Unary,
},
/**
* @generated from rpc holos.v1alpha1.PlatformService.AddPlatform
*/
addPlatform: {
name: "AddPlatform",
I: AddPlatformRequest,
O: GetPlatformsResponse,
kind: MethodKind.Unary,
},
}
} as const;

View File

@@ -0,0 +1,202 @@
// @generated by protoc-gen-es v1.9.0 with parameter "target=ts"
// @generated from file holos/v1alpha1/platform.proto (package holos.v1alpha1, syntax proto3)
/* eslint-disable */
// @ts-nocheck
import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf";
import { Message, proto3 } from "@bufbuild/protobuf";
import { Timestamps } from "./timestamps_pb.js";
import { Creator } from "./user_pb.js";
/**
* @generated from message holos.v1alpha1.Platform
*/
export class Platform extends Message<Platform> {
/**
* Unique id assigned by the server.
*
* @generated from field: string id = 1;
*/
id = "";
/**
* @generated from field: string name = 2;
*/
name = "";
/**
* @generated from field: string display_name = 3;
*/
displayName = "";
/**
* @generated from field: holos.v1alpha1.Timestamps timestamps = 4;
*/
timestamps?: Timestamps;
/**
* @generated from field: holos.v1alpha1.Creator creator = 5;
*/
creator?: Creator;
constructor(data?: PartialMessage<Platform>) {
super();
proto3.util.initPartial(data, this);
}
static readonly runtime: typeof proto3 = proto3;
static readonly typeName = "holos.v1alpha1.Platform";
static readonly fields: FieldList = proto3.util.newFieldList(() => [
{ no: 1, name: "id", kind: "scalar", T: 9 /* ScalarType.STRING */ },
{ no: 2, name: "name", kind: "scalar", T: 9 /* ScalarType.STRING */ },
{ no: 3, name: "display_name", kind: "scalar", T: 9 /* ScalarType.STRING */ },
{ no: 4, name: "timestamps", kind: "message", T: Timestamps },
{ no: 5, name: "creator", kind: "message", T: Creator },
]);
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): Platform {
return new Platform().fromBinary(bytes, options);
}
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): Platform {
return new Platform().fromJson(jsonValue, options);
}
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): Platform {
return new Platform().fromJsonString(jsonString, options);
}
static equals(a: Platform | PlainMessage<Platform> | undefined, b: Platform | PlainMessage<Platform> | undefined): boolean {
return proto3.util.equals(Platform, a, b);
}
}
/**
* @generated from message holos.v1alpha1.GetPlatformsRequest
*/
export class GetPlatformsRequest extends Message<GetPlatformsRequest> {
/**
* @generated from field: string org_id = 1;
*/
orgId = "";
constructor(data?: PartialMessage<GetPlatformsRequest>) {
super();
proto3.util.initPartial(data, this);
}
static readonly runtime: typeof proto3 = proto3;
static readonly typeName = "holos.v1alpha1.GetPlatformsRequest";
static readonly fields: FieldList = proto3.util.newFieldList(() => [
{ no: 1, name: "org_id", kind: "scalar", T: 9 /* ScalarType.STRING */ },
]);
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): GetPlatformsRequest {
return new GetPlatformsRequest().fromBinary(bytes, options);
}
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): GetPlatformsRequest {
return new GetPlatformsRequest().fromJson(jsonValue, options);
}
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): GetPlatformsRequest {
return new GetPlatformsRequest().fromJsonString(jsonString, options);
}
static equals(a: GetPlatformsRequest | PlainMessage<GetPlatformsRequest> | undefined, b: GetPlatformsRequest | PlainMessage<GetPlatformsRequest> | undefined): boolean {
return proto3.util.equals(GetPlatformsRequest, a, b);
}
}
/**
* @generated from message holos.v1alpha1.GetPlatformsResponse
*/
export class GetPlatformsResponse extends Message<GetPlatformsResponse> {
/**
* @generated from field: string org_id = 1;
*/
orgId = "";
/**
* @generated from field: repeated holos.v1alpha1.Platform platforms = 2;
*/
platforms: Platform[] = [];
constructor(data?: PartialMessage<GetPlatformsResponse>) {
super();
proto3.util.initPartial(data, this);
}
static readonly runtime: typeof proto3 = proto3;
static readonly typeName = "holos.v1alpha1.GetPlatformsResponse";
static readonly fields: FieldList = proto3.util.newFieldList(() => [
{ no: 1, name: "org_id", kind: "scalar", T: 9 /* ScalarType.STRING */ },
{ no: 2, name: "platforms", kind: "message", T: Platform, repeated: true },
]);
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): GetPlatformsResponse {
return new GetPlatformsResponse().fromBinary(bytes, options);
}
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): GetPlatformsResponse {
return new GetPlatformsResponse().fromJson(jsonValue, options);
}
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): GetPlatformsResponse {
return new GetPlatformsResponse().fromJsonString(jsonString, options);
}
static equals(a: GetPlatformsResponse | PlainMessage<GetPlatformsResponse> | undefined, b: GetPlatformsResponse | PlainMessage<GetPlatformsResponse> | undefined): boolean {
return proto3.util.equals(GetPlatformsResponse, a, b);
}
}
/**
* @generated from message holos.v1alpha1.AddPlatformRequest
*/
export class AddPlatformRequest extends Message<AddPlatformRequest> {
/**
* @generated from field: string org_id = 1;
*/
orgId = "";
/**
* @generated from field: string name = 2;
*/
name = "";
/**
* @generated from field: string display_name = 3;
*/
displayName = "";
constructor(data?: PartialMessage<AddPlatformRequest>) {
super();
proto3.util.initPartial(data, this);
}
static readonly runtime: typeof proto3 = proto3;
static readonly typeName = "holos.v1alpha1.AddPlatformRequest";
static readonly fields: FieldList = proto3.util.newFieldList(() => [
{ no: 1, name: "org_id", kind: "scalar", T: 9 /* ScalarType.STRING */ },
{ no: 2, name: "name", kind: "scalar", T: 9 /* ScalarType.STRING */ },
{ no: 3, name: "display_name", kind: "scalar", T: 9 /* ScalarType.STRING */ },
]);
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): AddPlatformRequest {
return new AddPlatformRequest().fromBinary(bytes, options);
}
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): AddPlatformRequest {
return new AddPlatformRequest().fromJson(jsonValue, options);
}
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): AddPlatformRequest {
return new AddPlatformRequest().fromJsonString(jsonString, options);
}
static equals(a: AddPlatformRequest | PlainMessage<AddPlatformRequest> | undefined, b: AddPlatformRequest | PlainMessage<AddPlatformRequest> | undefined): boolean {
return proto3.util.equals(AddPlatformRequest, a, b);
}
}

View File

@@ -256,6 +256,43 @@ export class Claims extends Message<Claims> {
}
}
/**
* @generated from message holos.v1alpha1.Creator
*/
export class Creator extends Message<Creator> {
/**
* @generated from field: string id = 1;
*/
id = "";
constructor(data?: PartialMessage<Creator>) {
super();
proto3.util.initPartial(data, this);
}
static readonly runtime: typeof proto3 = proto3;
static readonly typeName = "holos.v1alpha1.Creator";
static readonly fields: FieldList = proto3.util.newFieldList(() => [
{ no: 1, name: "id", kind: "scalar", T: 9 /* ScalarType.STRING */ },
]);
static fromBinary(bytes: Uint8Array, options?: Partial<BinaryReadOptions>): Creator {
return new Creator().fromBinary(bytes, options);
}
static fromJson(jsonValue: JsonValue, options?: Partial<JsonReadOptions>): Creator {
return new Creator().fromJson(jsonValue, options);
}
static fromJsonString(jsonString: string, options?: Partial<JsonReadOptions>): Creator {
return new Creator().fromJsonString(jsonString, options);
}
static equals(a: Creator | PlainMessage<Creator> | undefined, b: Creator | PlainMessage<Creator> | undefined): boolean {
return proto3.util.equals(Creator, a, b);
}
}
/**
* UserClaims represents id token claims
*

View File

@@ -7,8 +7,10 @@
<span>Menu</span>
</mat-toolbar>
<mat-nav-list>
<a mat-list-item routerLink="/platform-config" routerLinkActive="active-link">Platform Config</a>
<a mat-list-item routerLink="/home" routerLinkActive="active-link">Home</a>
<a mat-list-item routerLink="/clusters" routerLinkActive="active-link">Clusters</a>
<a mat-list-item routerLink="/address-form" routerLinkActive="active-link">Address Form</a>
</mat-nav-list>
</mat-sidenav>
<mat-sidenav-content>

View File

@@ -0,0 +1,56 @@
<mat-tab-group>
<mat-tab label="Organization">
<form [formGroup]="form" (ngSubmit)="onSubmit(model)">
<mat-card class="config-card">
<mat-card-header>
<mat-card-title>Organization</mat-card-title>
</mat-card-header>
<mat-card-content>
<p>Organization config values are used to derive more specific configuration values throughout the platform.</p>
<formly-form [form]="form" [fields]="fields" [model]="model">
</formly-form>
</mat-card-content>
<mat-card-actions>
<button mat-raised-button color="primary" type="submit">Submit</button>
</mat-card-actions>
</mat-card>
</form>
</mat-tab>
<mat-tab label="Integrations">
<form [formGroup]="form" (ngSubmit)="onSubmit(model)">
<mat-card class="config-card">
<mat-card-header>
<mat-card-title>Integrations</mat-card-title>
</mat-card-header>
<mat-card-content>
<p>Configure integrations with your DNS and version control service providers.</p>
<formly-form [form]="form" [fields]="integrationFields" [model]="model">
</formly-form>
</mat-card-content>
<mat-card-actions>
<button mat-raised-button color="primary" type="submit">Submit</button>
</mat-card-actions>
</mat-card>
</form>
</mat-tab>
<mat-tab label="Provisioner">
<form [formGroup]="form" (ngSubmit)="onSubmit(model)">
<mat-card class="config-card">
<mat-card-header>
<mat-card-title>Provisioner Cluster</mat-card-title>
</mat-card-header>
<mat-card-content>
<p>Provide the connection details used to sync secrets among platform clusters.</p>
<formly-form [form]="form" [fields]="provisionerFields" [model]="model">
</formly-form>
</mat-card-content>
<mat-card-actions>
<button mat-raised-button color="primary" type="submit">Submit</button>
</mat-card-actions>
</mat-card>
</form>
</mat-tab>
<mat-tab label="OAuth Clients"></mat-tab>
</mat-tab-group>

View File

@@ -0,0 +1,27 @@
.full-width {
width: 100%;
}
.config-card {
min-width: 120px;
margin: 20px auto;
}
.mat-radio-button {
display: block;
margin: 5px 0;
}
.row {
display: flex;
flex-direction: row;
}
.col {
flex: 1;
margin-right: 20px;
}
.col:last-child {
margin-right: 0;
}

View File

@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { PlatformConfigComponent } from './platform-config.component';
describe('PlatformConfigComponent', () => {
let component: PlatformConfigComponent;
let fixture: ComponentFixture<PlatformConfigComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [PlatformConfigComponent]
})
.compileComponents();
fixture = TestBed.createComponent(PlatformConfigComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,122 @@
import { Component } from '@angular/core';
import { FormGroup, ReactiveFormsModule } from '@angular/forms';
import { MatTabsModule } from '@angular/material/tabs';
import { MatButton } from '@angular/material/button';
import { MatCard, MatCardActions, MatCardContent, MatCardHeader, MatCardTitle } from '@angular/material/card';
import { FormlyModule, FormlyFieldConfig } from '@ngx-formly/core';
import { FormlyMaterialModule } from '@ngx-formly/material';
@Component({
selector: 'app-platform-config',
standalone: true,
imports: [
ReactiveFormsModule,
FormlyMaterialModule,
FormlyModule,
MatTabsModule,
MatCard,
MatCardHeader,
MatCardTitle,
MatCardContent,
MatCardActions,
MatButton,
],
templateUrl: './platform-config.component.html',
styleUrl: './platform-config.component.scss'
})
export class PlatformConfigComponent {
form = new FormGroup({});
model: any = {};
fields: FormlyFieldConfig[] = [
{
key: 'name',
type: 'input',
props: {
label: 'Name',
placeholder: 'example',
required: true,
description: "DNS label, e.g. 'example'"
}
},
{
key: 'domain',
type: 'input',
props: {
label: 'Domain',
placeholder: 'example.com',
required: true,
description: "DNS domain, e.g. 'example.com'"
}
},
{
key: 'displayName',
type: 'input',
props: {
label: 'Display Name',
placeholder: 'Example Organization',
required: true,
description: "Display name, e.g. 'My Organization'"
}
},
{
key: 'contactEmail',
type: 'input',
props: {
label: 'Contact Email',
placeholder: '',
required: true,
description: "Organization technical contact."
}
},
];
integrationFields: FormlyFieldConfig[] = [
{
key: 'cloudflareEmail',
type: 'input',
props: {
label: 'Cloudflare Account',
placeholder: 'example@example.com',
required: true,
description: "Cloudflare account email address."
}
},
{
key: 'githubPrimaryOrg',
type: 'input',
props: {
label: 'Github Organization',
placeholder: 'ExampleOrg',
required: true,
description: "Github organization, e.g. 'ExampleOrg'"
}
}
];
provisionerFields: FormlyFieldConfig[] = [
{
key: 'provisionerCABundle',
type: 'input',
props: {
label: 'Provisioner API CA Bundle',
placeholder: 'LS0tLS1CRUdJTiBDRVJUSUZJQXXXXXXXXXXXXXXXXXXXXXXX',
required: true,
description: "kubectl config view --minify --flatten -ojsonpath='{.clusters[0].cluster.certificate-authority-data}'"
}
},
{
key: 'provisionerURL',
type: 'input',
props: {
label: 'Provisioner API URL',
placeholder: 'https://1.2.3.4',
required: true,
description: "kubectl config view --minify --flatten -ojsonpath='{.clusters[0].cluster.server}'"
}
}
]
onSubmit(model: any) {
console.log(model);
}
}

View File

@@ -0,0 +1,31 @@
package holos
import ( "encoding/yaml"
)
// The platform configmap is a simple component that manages a configmap named
// platform in the default namespace. The purpose is to exercise end to end
// validation of platform configuration values provided by the holos web ui to
// each cluster in the platform.
platform: #Platform & {metadata: name: "bare"}
let PLATFORM = platform
// spec represents the output provided to holos
spec: components: KubernetesObjectsList: [
#KubernetesObjects & {
metadata: name: "platform-configmap"
apiObjectMap: OBJECTS.apiObjectMap
},
]
// OBJECTS represents the kubernetes api objects to manage.
let OBJECTS = #APIObjects & {
apiObjects: ConfigMap: platform: {
metadata: {
name: "platform"
namespace: "default"
}
data: platform: yaml.Marshal(PLATFORM)
}
}

View File

@@ -0,0 +1,43 @@
package forms
import formsv1 "github.com/holos-run/forms/v1alpha1"
let Platform = formsv1.#Platform & {
name: "bare"
displayName: "Bare Platform"
sections: org: {
displayName: "Organization"
description: "Organization config values are used to derive more specific configuration values throughout the platform."
fieldConfigs: {
// platform.org.name
name: props: {
label: "Name"
placeholder: "example"
description: "DNS label, e.g. 'example'"
}
// platform.org.domain
domain: props: {
label: "Domain"
placeholder: "example.com"
description: "DNS domain, e.g. 'example.com'"
}
// platform.org.displayName
displayName: props: {
label: "Display Name"
placeholder: "Example Organization"
description: "Display name, e.g. 'Example Organization'"
}
// platform.org.contactEmail
contactEmail: props: {
label: "Contact Email"
placeholder: "platform-team@example.com"
description: "Technical contact email address"
}
}
}
}
// Provide the output form fields
Platform.Form

View File

@@ -0,0 +1,63 @@
package holos
import (
h "github.com/holos-run/holos/api/v1alpha1"
"encoding/yaml"
)
// CUE provides a #BuildPlan to the holos cli. Holos requires the output of CUE
// to conform to the #BuildPlan schema.
{} & h.#BuildPlan
// #HolosComponent defines struct fields common to all holos component types.
#HolosComponent: {
h.#HolosComponent
metadata: name: string
_NameLengthConstraint: len(metadata.name) & >=1
...
}
#KubernetesObjects: #HolosComponent & h.#KubernetesObjects
// #HolosTypeMeta is similar to kubernetes api TypeMeta, but for holos api
// objects such as the Platform config resource.
#HolosTypeMeta: {
kind: string @go(Kind)
apiVersion: string @go(APIVersion)
}
// #HolosObjectMeta is similar to kubernetes api ObjectMeta, but for holos api
// objects.
#HolosObjectMeta: {
name: string @go(Name)
labels: {[string]: string} @go(Labels,map[string]string)
annotations: {[string]: string} @go(Annotations,map[string]string)
}
// #APIObjects defines the output format for kubernetes api objects. The holos
// cli expects the yaml representation of each api object in the apiObjectMap
// field.
#APIObjects: {
// apiObjects represents the un-marshalled form of each kubernetes api object
// managed by a holos component.
apiObjects: {
[Kind=_]: {
[string]: {
kind: Kind
...
}
}
ConfigMap?: [Name=_]: #ConfigMap & {metadata: name: Name}
}
// apiObjectMap holds the marshalled representation of apiObjects
apiObjectMap: {
for kind, v in apiObjects {
"\(kind)": {
for name, obj in v {
"\(name)": yaml.Marshal(obj)
}
}
}
}
}

View File

@@ -0,0 +1,13 @@
package holos
import (
corev1 "k8s.io/api/core/v1"
)
_NamespaceObject: {
metadata: name: string
metadata: namespace: string
metadata: labels: "app.holos.run/managed": "true"
}
#ConfigMap: _NamespaceObject & corev1.#ConfigMap

View File

@@ -0,0 +1,25 @@
package holos
// #Platform represents the user supplied platform configuration.
#Platform: {
#HolosTypeMeta
kind: "Platform"
apiVersion: "app.holos.run/v1alpha1"
metadata: #HolosObjectMeta
spec: #PlatformSpec
holos: #Holos
}
// #Holos represents the holos reserved field in the #Platform schema defined by the holos development team.
#Holos: {
// flags represents config values provided by holos command line flags.
flags: {
// cluster represents the holos render --cluster-name flag.
cluster: string @tag(cluster, type=string)
}
}
// #PlatformSpec represents configuration values defined by the platform
// designer. Config values are organized by section, then simple strings for
// each section.
#PlatformSpec: {[string]: {[string]: string | bool | [...string]}}

View File

@@ -0,0 +1 @@
{"platform":{"spec":{"org":{"name":"ois"}}}}

View File

@@ -0,0 +1 @@
package holos

View File

@@ -0,0 +1,26 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go github.com/holos-run/holos/api/v1alpha1
package v1alpha1
// BuildPlan is the primary interface between CUE and the Holos cli.
#BuildPlan: {
#TypeMeta
// Metadata represents the holos component name
metadata?: #ObjectMeta @go(Metadata)
spec?: #BuildPlanSpec @go(Spec)
}
#BuildPlanSpec: {
disabled?: bool @go(Disabled)
components?: #BuildPlanComponents @go(Components)
}
#BuildPlanComponents: {
helmChartList?: [...#HelmChart] @go(HelmChartList,[]HelmChart)
kubernetesObjectsList?: [...#KubernetesObjects] @go(KubernetesObjectsList,[]KubernetesObjects)
kustomizeBuildList?: [...#KustomizeBuild] @go(KustomizeBuildList,[]KustomizeBuild)
resources?: {[string]: #KubernetesObjects} @go(Resources,map[string]KubernetesObjects)
}

View File

@@ -0,0 +1,24 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go github.com/holos-run/holos/api/v1alpha1
package v1alpha1
// HolosComponent defines the fields common to all holos component kinds including the Render Result.
#HolosComponent: {
#TypeMeta
// Metadata represents the holos component name
metadata?: #ObjectMeta @go(Metadata)
// APIObjectMap holds the marshalled representation of api objects. Think of
// these as resources overlaid at the back of the render pipeline.
apiObjectMap?: #APIObjectMap @go(APIObjectMap)
#Kustomization
#Kustomize
// Skip causes holos to take no action regarding the component.
Skip: bool
}

View File

@@ -0,0 +1,15 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go github.com/holos-run/holos/api/v1alpha1
package v1alpha1
#APIVersion: "holos.run/v1alpha1"
#BuildPlanKind: "BuildPlan"
#HelmChartKind: "HelmChart"
// ChartDir is the directory name created in the holos component directory to cache a chart.
#ChartDir: "vendor"
// ResourcesFile is the file name used to store component output when post-processing with kustomize.
#ResourcesFile: "resources.yaml"

View File

@@ -0,0 +1,6 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go github.com/holos-run/holos/api/v1alpha1
// Package v1alpha1 defines the api boundary between CUE and Holos.
package v1alpha1

View File

@@ -0,0 +1,28 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go github.com/holos-run/holos/api/v1alpha1
package v1alpha1
// A HelmChart represents a helm command to provide chart values in order to render kubernetes api objects.
#HelmChart: {
#HolosComponent
// Namespace is the namespace to install into. TODO: Use metadata.namespace instead.
namespace: string @go(Namespace)
chart: #Chart @go(Chart)
valuesContent: string @go(ValuesContent)
enableHooks: bool @go(EnableHooks)
}
#Chart: {
name: string @go(Name)
version: string @go(Version)
release: string @go(Release)
repository?: #Repository @go(Repository)
}
#Repository: {
name: string @go(Name)
url: string @go(URL)
}

View File

@@ -0,0 +1,12 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go github.com/holos-run/holos/api/v1alpha1
package v1alpha1
#KubernetesObjectsKind: "KubernetesObjects"
// KubernetesObjects represents CUE output which directly provides Kubernetes api objects to holos.
#KubernetesObjects: {
#HolosComponent
}

View File

@@ -0,0 +1,11 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go github.com/holos-run/holos/api/v1alpha1
package v1alpha1
// Kustomization holds the rendered flux kustomization api object content for git ops.
#Kustomization: {
// KsContent is the yaml representation of the flux kustomization for gitops.
ksContent?: string @go(KsContent)
}

View File

@@ -0,0 +1,25 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go github.com/holos-run/holos/api/v1alpha1
package v1alpha1
#KustomizeBuildKind: "KustomizeBuild"
// Kustomize represents resources necessary to execute a kustomize build.
// Intended for at least two use cases:
//
// 1. Process raw yaml file resources in a holos component directory.
// 2. Post process a HelmChart to inject istio, add custom labels, etc...
#Kustomize: {
// KustomizeFiles holds file contents for kustomize, e.g. patch files.
kustomizeFiles?: #FileContentMap @go(KustomizeFiles)
// ResourcesFile is the file name used for api objects in kustomization.yaml
resourcesFile?: string @go(ResourcesFile)
}
// KustomizeBuild renders plain yaml files in the holos component directory using kubectl kustomize build.
#KustomizeBuild: {
#HolosComponent
}

View File

@@ -0,0 +1,12 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go github.com/holos-run/holos/api/v1alpha1
package v1alpha1
#KustomizeBuildKind: "KustomizeBuild"
// KustomizeBuild
#KustomizeBuild: {
#HolosComponent
}

View File

@@ -0,0 +1,18 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go github.com/holos-run/holos/api/v1alpha1
package v1alpha1
// Label is an arbitrary unique identifier. Defined as a type for clarity and type checking.
#Label: string
// Kind is a kubernetes api object kind. Defined as a type for clarity and type checking.
#Kind: string
// APIObjectMap is the shape of marshalled api objects returned from cue to the
// holos cli. A map is used to improve the clarity of error messages from cue.
#APIObjectMap: {[string]: [string]: string}
// FileContentMap is a map of file names to file contents.
#FileContentMap: {[string]: string}

View File

@@ -0,0 +1,22 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go github.com/holos-run/holos/api/v1alpha1
package v1alpha1
// ObjectMeta represents metadata of a holos component object. The fields are a
// copy of upstream kubernetes api machinery but are by holos objects distinct
// from kubernetes api objects.
#ObjectMeta: {
// Name uniquely identifies the holos component instance and must be suitable as a file name.
name?: string @go(Name)
// Namespace confines a holos component to a single namespace via kustomize if set.
namespace?: string @go(Namespace)
// Labels are not used but are copied from api machinery ObjectMeta for completeness.
labels?: {[string]: string} @go(Labels,map[string]string)
// Annotations are not used but are copied from api machinery ObjectMeta for completeness.
annotations?: {[string]: string} @go(Annotations,map[string]string)
}

View File

@@ -0,0 +1,7 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go github.com/holos-run/holos/api/v1alpha1
package v1alpha1
#Renderer: _

View File

@@ -0,0 +1,10 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go github.com/holos-run/holos/api/v1alpha1
package v1alpha1
// Result is the build result for display or writing. Holos components Render the Result as a data pipeline.
#Result: {
HolosComponent: #HolosComponent
}

View File

@@ -0,0 +1,10 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go github.com/holos-run/holos/api/v1alpha1
package v1alpha1
#TypeMeta: {
kind?: string @go(Kind)
apiVersion?: string @go(APIVersion)
}

View File

@@ -0,0 +1,147 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/api/core/v1
package v1
// ImagePolicyFailedOpenKey is added to pods created by failing open when the image policy
// webhook backend fails.
#ImagePolicyFailedOpenKey: "alpha.image-policy.k8s.io/failed-open"
// MirrorAnnotationKey represents the annotation key set by kubelets when creating mirror pods
#MirrorPodAnnotationKey: "kubernetes.io/config.mirror"
// TolerationsAnnotationKey represents the key of tolerations data (json serialized)
// in the Annotations of a Pod.
#TolerationsAnnotationKey: "scheduler.alpha.kubernetes.io/tolerations"
// TaintsAnnotationKey represents the key of taints data (json serialized)
// in the Annotations of a Node.
#TaintsAnnotationKey: "scheduler.alpha.kubernetes.io/taints"
// SeccompPodAnnotationKey represents the key of a seccomp profile applied
// to all containers of a pod.
// Deprecated: set a pod security context `seccompProfile` field.
#SeccompPodAnnotationKey: "seccomp.security.alpha.kubernetes.io/pod"
// SeccompContainerAnnotationKeyPrefix represents the key of a seccomp profile applied
// to one container of a pod.
// Deprecated: set a container security context `seccompProfile` field.
#SeccompContainerAnnotationKeyPrefix: "container.seccomp.security.alpha.kubernetes.io/"
// SeccompProfileRuntimeDefault represents the default seccomp profile used by container runtime.
// Deprecated: set a pod or container security context `seccompProfile` of type "RuntimeDefault" instead.
#SeccompProfileRuntimeDefault: "runtime/default"
// SeccompProfileNameUnconfined is the unconfined seccomp profile.
#SeccompProfileNameUnconfined: "unconfined"
// SeccompLocalhostProfileNamePrefix is the prefix for specifying profiles loaded from the node's disk.
#SeccompLocalhostProfileNamePrefix: "localhost/"
// AppArmorBetaContainerAnnotationKeyPrefix is the prefix to an annotation key specifying a container's apparmor profile.
#AppArmorBetaContainerAnnotationKeyPrefix: "container.apparmor.security.beta.kubernetes.io/"
// AppArmorBetaDefaultProfileAnnotationKey is the annotation key specifying the default AppArmor profile.
#AppArmorBetaDefaultProfileAnnotationKey: "apparmor.security.beta.kubernetes.io/defaultProfileName"
// AppArmorBetaAllowedProfilesAnnotationKey is the annotation key specifying the allowed AppArmor profiles.
#AppArmorBetaAllowedProfilesAnnotationKey: "apparmor.security.beta.kubernetes.io/allowedProfileNames"
// AppArmorBetaProfileRuntimeDefault is the profile specifying the runtime default.
#AppArmorBetaProfileRuntimeDefault: "runtime/default"
// AppArmorBetaProfileNamePrefix is the prefix for specifying profiles loaded on the node.
#AppArmorBetaProfileNamePrefix: "localhost/"
// AppArmorBetaProfileNameUnconfined is the Unconfined AppArmor profile
#AppArmorBetaProfileNameUnconfined: "unconfined"
// DeprecatedSeccompProfileDockerDefault represents the default seccomp profile used by docker.
// Deprecated: set a pod or container security context `seccompProfile` of type "RuntimeDefault" instead.
#DeprecatedSeccompProfileDockerDefault: "docker/default"
// PreferAvoidPodsAnnotationKey represents the key of preferAvoidPods data (json serialized)
// in the Annotations of a Node.
#PreferAvoidPodsAnnotationKey: "scheduler.alpha.kubernetes.io/preferAvoidPods"
// ObjectTTLAnnotationKey represents a suggestion for kubelet for how long it can cache
// an object (e.g. secret, config map) before fetching it again from apiserver.
// This annotation can be attached to node.
#ObjectTTLAnnotationKey: "node.alpha.kubernetes.io/ttl"
// annotation key prefix used to identify non-convertible json paths.
#NonConvertibleAnnotationPrefix: "non-convertible.kubernetes.io"
_#kubectlPrefix: "kubectl.kubernetes.io/"
// LastAppliedConfigAnnotation is the annotation used to store the previous
// configuration of a resource for use in a three way diff by UpdateApplyAnnotation.
#LastAppliedConfigAnnotation: "kubectl.kubernetes.io/last-applied-configuration"
// AnnotationLoadBalancerSourceRangesKey is the key of the annotation on a service to set allowed ingress ranges on their LoadBalancers
//
// It should be a comma-separated list of CIDRs, e.g. `0.0.0.0/0` to
// allow full access (the default) or `18.0.0.0/8,56.0.0.0/8` to allow
// access only from the CIDRs currently allocated to MIT & the USPS.
//
// Not all cloud providers support this annotation, though AWS & GCE do.
#AnnotationLoadBalancerSourceRangesKey: "service.beta.kubernetes.io/load-balancer-source-ranges"
// EndpointsLastChangeTriggerTime is the annotation key, set for endpoints objects, that
// represents the timestamp (stored as RFC 3339 date-time string, e.g. '2018-10-22T19:32:52.1Z')
// of the last change, of some Pod or Service object, that triggered the endpoints object change.
// In other words, if a Pod / Service changed at time T0, that change was observed by endpoints
// controller at T1, and the Endpoints object was changed at T2, the
// EndpointsLastChangeTriggerTime would be set to T0.
//
// The "endpoints change trigger" here means any Pod or Service change that resulted in the
// Endpoints object change.
//
// Given the definition of the "endpoints change trigger", please note that this annotation will
// be set ONLY for endpoints object changes triggered by either Pod or Service change. If the
// Endpoints object changes due to other reasons, this annotation won't be set (or updated if it's
// already set).
//
// This annotation will be used to compute the in-cluster network programming latency SLI, see
// https://github.com/kubernetes/community/blob/master/sig-scalability/slos/network_programming_latency.md
#EndpointsLastChangeTriggerTime: "endpoints.kubernetes.io/last-change-trigger-time"
// EndpointsOverCapacity will be set on an Endpoints resource when it
// exceeds the maximum capacity of 1000 addresses. Initially the Endpoints
// controller will set this annotation with a value of "warning". In a
// future release, the controller may set this annotation with a value of
// "truncated" to indicate that any addresses exceeding the limit of 1000
// have been truncated from the Endpoints resource.
#EndpointsOverCapacity: "endpoints.kubernetes.io/over-capacity"
// MigratedPluginsAnnotationKey is the annotation key, set for CSINode objects, that is a comma-separated
// list of in-tree plugins that will be serviced by the CSI backend on the Node represented by CSINode.
// This annotation is used by the Attach Detach Controller to determine whether to use the in-tree or
// CSI Backend for a volume plugin on a specific node.
#MigratedPluginsAnnotationKey: "storage.alpha.kubernetes.io/migrated-plugins"
// PodDeletionCost can be used to set to an int32 that represent the cost of deleting
// a pod compared to other pods belonging to the same ReplicaSet. Pods with lower
// deletion cost are preferred to be deleted before pods with higher deletion cost.
// Note that this is honored on a best-effort basis, and so it does not offer guarantees on
// pod deletion order.
// The implicit deletion cost for pods that don't set the annotation is 0, negative values are permitted.
//
// This annotation is beta-level and is only honored when PodDeletionCost feature is enabled.
#PodDeletionCost: "controller.kubernetes.io/pod-deletion-cost"
// DeprecatedAnnotationTopologyAwareHints can be used to enable or disable
// Topology Aware Hints for a Service. This may be set to "Auto" or
// "Disabled". Any other value is treated as "Disabled". This annotation has
// been deprecated in favor of the "service.kubernetes.io/topology-mode"
// annotation.
#DeprecatedAnnotationTopologyAwareHints: "service.kubernetes.io/topology-aware-hints"
// AnnotationTopologyMode can be used to enable or disable Topology Aware
// Routing for a Service. Well known values are "Auto" and "Disabled".
// Implementations may choose to develop new topology approaches, exposing
// them with domain-prefixed values. For example, "example.com/lowest-rtt"
// could be a valid implementation-specific value for this annotation. These
// heuristics will often populate topology hints on EndpointSlices, but that
// is not a requirement.
#AnnotationTopologyMode: "service.kubernetes.io/topology-mode"

View File

@@ -0,0 +1,6 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/api/core/v1
// Package v1 is the v1 version of the core API.
package v1

View File

@@ -0,0 +1,7 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/api/core/v1
package v1
#GroupName: ""

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,59 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/api/core/v1
package v1
#LabelHostname: "kubernetes.io/hostname"
// Label value is the network location of kube-apiserver stored as <ip:port>
// Stored in APIServer Identity lease objects to view what address is used for peer proxy
#AnnotationPeerAdvertiseAddress: "kubernetes.io/peer-advertise-address"
#LabelTopologyZone: "topology.kubernetes.io/zone"
#LabelTopologyRegion: "topology.kubernetes.io/region"
// These label have been deprecated since 1.17, but will be supported for
// the foreseeable future, to accommodate things like long-lived PVs that
// use them. New users should prefer the "topology.kubernetes.io/*"
// equivalents.
#LabelFailureDomainBetaZone: "failure-domain.beta.kubernetes.io/zone"
#LabelFailureDomainBetaRegion: "failure-domain.beta.kubernetes.io/region"
// Retained for compat when vendored. Do not use these consts in new code.
#LabelZoneFailureDomain: "failure-domain.beta.kubernetes.io/zone"
#LabelZoneRegion: "failure-domain.beta.kubernetes.io/region"
#LabelZoneFailureDomainStable: "topology.kubernetes.io/zone"
#LabelZoneRegionStable: "topology.kubernetes.io/region"
#LabelInstanceType: "beta.kubernetes.io/instance-type"
#LabelInstanceTypeStable: "node.kubernetes.io/instance-type"
#LabelOSStable: "kubernetes.io/os"
#LabelArchStable: "kubernetes.io/arch"
// LabelWindowsBuild is used on Windows nodes to specify the Windows build number starting with v1.17.0.
// It's in the format MajorVersion.MinorVersion.BuildNumber (for ex: 10.0.17763)
#LabelWindowsBuild: "node.kubernetes.io/windows-build"
// LabelNamespaceSuffixKubelet is an allowed label namespace suffix kubelets can self-set ([*.]kubelet.kubernetes.io/*)
#LabelNamespaceSuffixKubelet: "kubelet.kubernetes.io"
// LabelNamespaceSuffixNode is an allowed label namespace suffix kubelets can self-set ([*.]node.kubernetes.io/*)
#LabelNamespaceSuffixNode: "node.kubernetes.io"
// LabelNamespaceNodeRestriction is a forbidden label namespace that kubelets may not self-set when the NodeRestriction admission plugin is enabled
#LabelNamespaceNodeRestriction: "node-restriction.kubernetes.io"
// IsHeadlessService is added by Controller to an Endpoint denoting if its parent
// Service is Headless. The existence of this label can be used further by other
// controllers and kube-proxy to check if the Endpoint objects should be replicated when
// using Headless Services
#IsHeadlessService: "service.kubernetes.io/headless"
// LabelNodeExcludeBalancers specifies that the node should not be considered as a target
// for external load-balancers which use nodes as a second hop (e.g. many cloud LBs which only
// understand nodes). For services that use externalTrafficPolicy=Local, this may mean that
// any backends on excluded nodes are not reachable by those external load-balancers.
// Implementations of this exclusion may vary based on provider.
#LabelNodeExcludeBalancers: "node.kubernetes.io/exclude-from-external-load-balancers"
// LabelMetadataName is the label name which, in-tree, is used to automatically label namespaces, so they can be selected easily by tools which require definitive labels
#LabelMetadataName: "kubernetes.io/metadata.name"

View File

@@ -0,0 +1,38 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/api/core/v1
package v1
// TaintNodeNotReady will be added when node is not ready
// and removed when node becomes ready.
#TaintNodeNotReady: "node.kubernetes.io/not-ready"
// TaintNodeUnreachable will be added when node becomes unreachable
// (corresponding to NodeReady status ConditionUnknown)
// and removed when node becomes reachable (NodeReady status ConditionTrue).
#TaintNodeUnreachable: "node.kubernetes.io/unreachable"
// TaintNodeUnschedulable will be added when node becomes unschedulable
// and removed when node becomes schedulable.
#TaintNodeUnschedulable: "node.kubernetes.io/unschedulable"
// TaintNodeMemoryPressure will be added when node has memory pressure
// and removed when node has enough memory.
#TaintNodeMemoryPressure: "node.kubernetes.io/memory-pressure"
// TaintNodeDiskPressure will be added when node has disk pressure
// and removed when node has enough disk.
#TaintNodeDiskPressure: "node.kubernetes.io/disk-pressure"
// TaintNodeNetworkUnavailable will be added when node's network is unavailable
// and removed when network becomes ready.
#TaintNodeNetworkUnavailable: "node.kubernetes.io/network-unavailable"
// TaintNodePIDPressure will be added when node has pid pressure
// and removed when node has enough pid.
#TaintNodePIDPressure: "node.kubernetes.io/pid-pressure"
// TaintNodeOutOfService can be added when node is out of service in case of
// a non-graceful shutdown
#TaintNodeOutOfService: "node.kubernetes.io/out-of-service"

View File

@@ -0,0 +1,47 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/api/resource
package resource
// Scale is used for getting and setting the base-10 scaled value.
// Base-2 scales are omitted for mathematical simplicity.
// See Quantity.ScaledValue for more details.
#Scale: int32 // #enumScale
#enumScale:
#Nano |
#Micro |
#Milli |
#Kilo |
#Mega |
#Giga |
#Tera |
#Peta |
#Exa
#values_Scale: {
Nano: #Nano
Micro: #Micro
Milli: #Milli
Kilo: #Kilo
Mega: #Mega
Giga: #Giga
Tera: #Tera
Peta: #Peta
Exa: #Exa
}
#Nano: #Scale & -9
#Micro: #Scale & -6
#Milli: #Scale & -3
#Kilo: #Scale & 3
#Mega: #Scale & 6
#Giga: #Scale & 9
#Tera: #Scale & 12
#Peta: #Scale & 15
#Exa: #Scale & 18
// infDecAmount implements common operations over an inf.Dec that are specific to the quantity
// representation.
_#infDecAmount: string

View File

@@ -0,0 +1,13 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/api/resource
package resource
// maxInt64Factors is the highest value that will be checked when removing factors of 10 from an int64.
// It is also the maximum decimal digits that can be represented with an int64.
_#maxInt64Factors: 18
_#mostNegative: -9223372036854775808
_#mostPositive: 9223372036854775807

View File

@@ -0,0 +1,107 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/api/resource
package resource
// Quantity is a fixed-point representation of a number.
// It provides convenient marshaling/unmarshaling in JSON and YAML,
// in addition to String() and AsInt64() accessors.
//
// The serialization format is:
//
// ```
// <quantity> ::= <signedNumber><suffix>
//
// (Note that <suffix> may be empty, from the "" case in <decimalSI>.)
//
// <digit> ::= 0 | 1 | ... | 9
// <digits> ::= <digit> | <digit><digits>
// <number> ::= <digits> | <digits>.<digits> | <digits>. | .<digits>
// <sign> ::= "+" | "-"
// <signedNumber> ::= <number> | <sign><number>
// <suffix> ::= <binarySI> | <decimalExponent> | <decimalSI>
// <binarySI> ::= Ki | Mi | Gi | Ti | Pi | Ei
//
// (International System of units; See: http://physics.nist.gov/cuu/Units/binary.html)
//
// <decimalSI> ::= m | "" | k | M | G | T | P | E
//
// (Note that 1024 = 1Ki but 1000 = 1k; I didn't choose the capitalization.)
//
// <decimalExponent> ::= "e" <signedNumber> | "E" <signedNumber>
// ```
//
// No matter which of the three exponent forms is used, no quantity may represent
// a number greater than 2^63-1 in magnitude, nor may it have more than 3 decimal
// places. Numbers larger or more precise will be capped or rounded up.
// (E.g.: 0.1m will rounded up to 1m.)
// This may be extended in the future if we require larger or smaller quantities.
//
// When a Quantity is parsed from a string, it will remember the type of suffix
// it had, and will use the same type again when it is serialized.
//
// Before serializing, Quantity will be put in "canonical form".
// This means that Exponent/suffix will be adjusted up or down (with a
// corresponding increase or decrease in Mantissa) such that:
//
// - No precision is lost
// - No fractional digits will be emitted
// - The exponent (or suffix) is as large as possible.
//
// The sign will be omitted unless the number is negative.
//
// Examples:
//
// - 1.5 will be serialized as "1500m"
// - 1.5Gi will be serialized as "1536Mi"
//
// Note that the quantity will NEVER be internally represented by a
// floating point number. That is the whole point of this exercise.
//
// Non-canonical values will still parse as long as they are well formed,
// but will be re-emitted in their canonical form. (So always use canonical
// form, or don't diff.)
//
// This format is intended to make it difficult to use these numbers without
// writing some sort of special handling code in the hopes that that will
// cause implementors to also use a fixed point implementation.
//
// +protobuf=true
// +protobuf.embed=string
// +protobuf.options.marshal=false
// +protobuf.options.(gogoproto.goproto_stringer)=false
// +k8s:deepcopy-gen=true
// +k8s:openapi-gen=true
#Quantity: _
// CanonicalValue allows a quantity amount to be converted to a string.
#CanonicalValue: _
// Format lists the three possible formattings of a quantity.
#Format: string // #enumFormat
#enumFormat:
#DecimalExponent |
#BinarySI |
#DecimalSI
#DecimalExponent: #Format & "DecimalExponent"
#BinarySI: #Format & "BinarySI"
#DecimalSI: #Format & "DecimalSI"
// splitREString is used to separate a number from its suffix; as such,
// this is overly permissive, but that's OK-- it will be checked later.
_#splitREString: "^([+-]?[0-9.]+)([eEinumkKMGTP]*[-+]?[0-9]*)$"
_#int64QuantityExpectedBytes: 18
// QuantityValue makes it possible to use a Quantity as value for a command
// line parameter.
//
// +protobuf=true
// +protobuf.embed=string
// +protobuf.options.marshal=false
// +protobuf.options.(gogoproto.goproto_stringer)=false
// +k8s:deepcopy-gen=true
#QuantityValue: _

View File

@@ -0,0 +1,10 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/api/resource
package resource
_#suffix: string
// suffixer can interpret and construct suffixes.
_#suffixer: _

View File

@@ -0,0 +1,10 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/apis/meta/v1
package v1
// Duration is a wrapper around time.Duration which supports correct
// marshaling to YAML and JSON. In particular, it marshals into strings, which
// can be used as map keys in json.
#Duration: _

View File

@@ -0,0 +1,48 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/apis/meta/v1
package v1
// GroupResource specifies a Group and a Resource, but does not force a version. This is useful for identifying
// concepts during lookup stages without having partially valid types
//
// +protobuf.options.(gogoproto.goproto_stringer)=false
#GroupResource: {
group: string @go(Group) @protobuf(1,bytes,opt)
resource: string @go(Resource) @protobuf(2,bytes,opt)
}
// GroupVersionResource unambiguously identifies a resource. It doesn't anonymously include GroupVersion
// to avoid automatic coercion. It doesn't use a GroupVersion to avoid custom marshalling
//
// +protobuf.options.(gogoproto.goproto_stringer)=false
#GroupVersionResource: {
group: string @go(Group) @protobuf(1,bytes,opt)
version: string @go(Version) @protobuf(2,bytes,opt)
resource: string @go(Resource) @protobuf(3,bytes,opt)
}
// GroupKind specifies a Group and a Kind, but does not force a version. This is useful for identifying
// concepts during lookup stages without having partially valid types
//
// +protobuf.options.(gogoproto.goproto_stringer)=false
#GroupKind: {
group: string @go(Group) @protobuf(1,bytes,opt)
kind: string @go(Kind) @protobuf(2,bytes,opt)
}
// GroupVersionKind unambiguously identifies a kind. It doesn't anonymously include GroupVersion
// to avoid automatic coercion. It doesn't use a GroupVersion to avoid custom marshalling
//
// +protobuf.options.(gogoproto.goproto_stringer)=false
#GroupVersionKind: {
group: string @go(Group) @protobuf(1,bytes,opt)
version: string @go(Version) @protobuf(2,bytes,opt)
kind: string @go(Kind) @protobuf(3,bytes,opt)
}
// GroupVersion contains the "group" and the "version", which uniquely identifies the API.
//
// +protobuf.options.(gogoproto.goproto_stringer)=false
#GroupVersion: _

View File

@@ -0,0 +1,33 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/apis/meta/v1
package v1
// TODO: move this, Object, List, and Type to a different package
#ObjectMetaAccessor: _
// Object lets you work with object metadata from any of the versioned or
// internal API objects. Attempting to set or retrieve a field on an object that does
// not support that field (Name, UID, Namespace on lists) will be a no-op and return
// a default value.
#Object: _
// ListMetaAccessor retrieves the list interface from an object
#ListMetaAccessor: _
// Common lets you work with core metadata from any of the versioned or
// internal API objects. Attempting to set or retrieve a field on an object that does
// not support that field will be a no-op and return a default value.
// TODO: move this, and TypeMeta and ListMeta, to a different package
#Common: _
// ListInterface lets you work with list metadata from any of the versioned or
// internal API objects. Attempting to set or retrieve a field on an object that does
// not support that field will be a no-op and return a default value.
// TODO: move this, and TypeMeta and ListMeta, to a different package
#ListInterface: _
// Type exposes the type and APIVersion of versioned or internal API objects.
// TODO: move this, and TypeMeta and ListMeta, to a different package
#Type: _

View File

@@ -0,0 +1,14 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/apis/meta/v1
package v1
#RFC3339Micro: "2006-01-02T15:04:05.000000Z07:00"
// MicroTime is version of Time with microsecond level precision.
//
// +protobuf.options.marshal=false
// +protobuf.as=Timestamp
// +protobuf.options.(gogoproto.goproto_stringer)=false
#MicroTime: _

View File

@@ -0,0 +1,9 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/apis/meta/v1
package v1
#GroupName: "meta.k8s.io"
#WatchEventKind: "WatchEvent"

View File

@@ -0,0 +1,14 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/apis/meta/v1
package v1
// Time is a wrapper around time.Time which supports correct
// marshaling to YAML and JSON. Wrappers are provided for many
// of the factory methods that the time package offers.
//
// +protobuf.options.marshal=false
// +protobuf.as=Timestamp
// +protobuf.options.(gogoproto.goproto_stringer)=false
#Time: _

View File

@@ -0,0 +1,21 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/apis/meta/v1
package v1
// Timestamp is a struct that is equivalent to Time, but intended for
// protobuf marshalling/unmarshalling. It is generated into a serialization
// that matches Time. Do not use in Go structs.
#Timestamp: {
// Represents seconds of UTC time since Unix epoch
// 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
// 9999-12-31T23:59:59Z inclusive.
seconds: int64 @go(Seconds) @protobuf(1,varint,opt)
// Non-negative fractions of a second at nanosecond resolution. Negative
// second values with fractions must still have non-negative nanos values
// that count forward in time. Must be from 0 to 999,999,999
// inclusive. This field may be limited in precision depending on context.
nanos: int32 @go(Nanos) @protobuf(2,varint,opt)
}

View File

@@ -0,0 +1,30 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/apis/meta/v1
package v1
import (
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
)
// Event represents a single event to a watched resource.
//
// +protobuf=true
// +k8s:deepcopy-gen=true
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
#WatchEvent: {
type: string @go(Type) @protobuf(1,bytes,opt)
// Object is:
// * If Type is Added or Modified: the new state of the object.
// * If Type is Deleted: the state of the object immediately before deletion.
// * If Type is Error: *Status is recommended; other types may make sense
// depending on context.
object: runtime.#RawExtension @go(Object) @protobuf(2,bytes,opt)
}
// InternalEvent makes watch.Event versioned
// +protobuf=false
#InternalEvent: watch.#Event

View File

@@ -0,0 +1,10 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/runtime
package runtime
// SimpleAllocator a wrapper around make([]byte)
// conforms to the MemoryAllocator interface
#SimpleAllocator: {
}

View File

@@ -0,0 +1,37 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/runtime
package runtime
// codec binds an encoder and decoder.
_#codec: {
Encoder: #Encoder
Decoder: #Decoder
}
// NoopEncoder converts an Decoder to a Serializer or Codec for code that expects them but only uses decoding.
#NoopEncoder: {
Decoder: #Decoder
}
_#noopEncoderIdentifier: #Identifier & "noop"
// NoopDecoder converts an Encoder to a Serializer or Codec for code that expects them but only uses encoding.
#NoopDecoder: {
Encoder: #Encoder
}
_#base64Serializer: {
Encoder: #Encoder
Decoder: #Decoder
}
_#internalGroupVersionerIdentifier: "internal"
_#disabledGroupVersionerIdentifier: "disabled"
_#internalGroupVersioner: {
}
_#disabledGroupVersioner: {
}

View File

@@ -0,0 +1,7 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/runtime
// Package runtime defines conversions between generic types and structs to map query strings
// to struct objects.
package runtime

View File

@@ -0,0 +1,9 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/runtime
package runtime
// UnstructuredConverter is an interface for converting between interface{}
// and map[string]interface representation.
#UnstructuredConverter: _

View File

@@ -0,0 +1,39 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/runtime
// Package runtime includes helper functions for working with API objects
// that follow the kubernetes API object conventions, which are:
//
// 0. Your API objects have a common metadata struct member, TypeMeta.
//
// 1. Your code refers to an internal set of API objects.
//
// 2. In a separate package, you have an external set of API objects.
//
// 3. The external set is considered to be versioned, and no breaking
// changes are ever made to it (fields may be added but not changed
// or removed).
//
// 4. As your api evolves, you'll make an additional versioned package
// with every major change.
//
// 5. Versioned packages have conversion functions which convert to
// and from the internal version.
//
// 6. You'll continue to support older versions according to your
// deprecation policy, and you can easily provide a program/library
// to update old versions into new versions because of 5.
//
// 7. All of your serializations and deserializations are handled in a
// centralized place.
//
// Package runtime provides a conversion helper to make 5 easy, and the
// Encode/Decode/DecodeInto trio to accomplish 7. You can also register
// additional "codecs" which use a version of your choice. It's
// recommended that you register your types with runtime in your
// package's init function.
//
// As a bonus, a few common types useful from all api objects and versions
// are provided in types.go.
package runtime

View File

@@ -0,0 +1,7 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/runtime
package runtime
_#encodable: _

View File

@@ -0,0 +1,23 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/runtime
package runtime
// MultiObjectTyper returns the types of objects across multiple schemes in order.
#MultiObjectTyper: [...#ObjectTyper]
_#defaultFramer: {
}
// WithVersionEncoder serializes an object and ensures the GVK is set.
#WithVersionEncoder: {
Version: #GroupVersioner
Encoder: #Encoder
ObjectTyper: #ObjectTyper
}
// WithoutVersionDecoder clears the group version kind of a deserialized object.
#WithoutVersionDecoder: {
Decoder: #Decoder
}

View File

@@ -0,0 +1,165 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/runtime
package runtime
// APIVersionInternal may be used if you are registering a type that should not
// be considered stable or serialized - it is a convention only and has no
// special behavior in this package.
#APIVersionInternal: "__internal"
// GroupVersioner refines a set of possible conversion targets into a single option.
#GroupVersioner: _
// Identifier represents an identifier.
// Identitier of two different objects should be equal if and only if for every
// input the output they produce is exactly the same.
#Identifier: string // #enumIdentifier
#enumIdentifier:
_#noopEncoderIdentifier
// Encoder writes objects to a serialized form
#Encoder: _
// MemoryAllocator is responsible for allocating memory.
// By encapsulating memory allocation into its own interface, we can reuse the memory
// across many operations in places we know it can significantly improve the performance.
#MemoryAllocator: _
// EncoderWithAllocator serializes objects in a way that allows callers to manage any additional memory allocations.
#EncoderWithAllocator: _
// Decoder attempts to load an object from data.
#Decoder: _
// Serializer is the core interface for transforming objects into a serialized format and back.
// Implementations may choose to perform conversion of the object, but no assumptions should be made.
#Serializer: _
// Codec is a Serializer that deals with the details of versioning objects. It offers the same
// interface as Serializer, so this is a marker to consumers that care about the version of the objects
// they receive.
#Codec: #Serializer
// ParameterCodec defines methods for serializing and deserializing API objects to url.Values and
// performing any necessary conversion. Unlike the normal Codec, query parameters are not self describing
// and the desired version must be specified.
#ParameterCodec: _
// Framer is a factory for creating readers and writers that obey a particular framing pattern.
#Framer: _
// SerializerInfo contains information about a specific serialization format
#SerializerInfo: {
// MediaType is the value that represents this serializer over the wire.
MediaType: string
// MediaTypeType is the first part of the MediaType ("application" in "application/json").
MediaTypeType: string
// MediaTypeSubType is the second part of the MediaType ("json" in "application/json").
MediaTypeSubType: string
// EncodesAsText indicates this serializer can be encoded to UTF-8 safely.
EncodesAsText: bool
// Serializer is the individual object serializer for this media type.
Serializer: #Serializer
// PrettySerializer, if set, can serialize this object in a form biased towards
// readability.
PrettySerializer: #Serializer
// StrictSerializer, if set, deserializes this object strictly,
// erring on unknown fields.
StrictSerializer: #Serializer
// StreamSerializer, if set, describes the streaming serialization format
// for this media type.
StreamSerializer?: null | #StreamSerializerInfo @go(,*StreamSerializerInfo)
}
// StreamSerializerInfo contains information about a specific stream serialization format
#StreamSerializerInfo: {
// EncodesAsText indicates this serializer can be encoded to UTF-8 safely.
EncodesAsText: bool
// Serializer is the top level object serializer for this type when streaming
Serializer: #Serializer
// Framer is the factory for retrieving streams that separate objects on the wire
Framer: #Framer
}
// NegotiatedSerializer is an interface used for obtaining encoders, decoders, and serializers
// for multiple supported media types. This would commonly be accepted by a server component
// that performs HTTP content negotiation to accept multiple formats.
#NegotiatedSerializer: _
// ClientNegotiator handles turning an HTTP content type into the appropriate encoder.
// Use NewClientNegotiator or NewVersionedClientNegotiator to create this interface from
// a NegotiatedSerializer.
#ClientNegotiator: _
// StorageSerializer is an interface used for obtaining encoders, decoders, and serializers
// that can read and write data at rest. This would commonly be used by client tools that must
// read files, or server side storage interfaces that persist restful objects.
#StorageSerializer: _
// NestedObjectEncoder is an optional interface that objects may implement to be given
// an opportunity to encode any nested Objects / RawExtensions during serialization.
#NestedObjectEncoder: _
// NestedObjectDecoder is an optional interface that objects may implement to be given
// an opportunity to decode any nested Objects / RawExtensions during serialization.
// It is possible for DecodeNestedObjects to return a non-nil error but for the decoding
// to have succeeded in the case of strict decoding errors (e.g. unknown/duplicate fields).
// As such it is important for callers of DecodeNestedObjects to check to confirm whether
// an error is a runtime.StrictDecodingError before short circuiting.
// Similarly, implementations of DecodeNestedObjects should ensure that a runtime.StrictDecodingError
// is only returned when the rest of decoding has succeeded.
#NestedObjectDecoder: _
#ObjectDefaulter: _
#ObjectVersioner: _
// ObjectConvertor converts an object to a different version.
#ObjectConvertor: _
// ObjectTyper contains methods for extracting the APIVersion and Kind
// of objects.
#ObjectTyper: _
// ObjectCreater contains methods for instantiating an object by kind and version.
#ObjectCreater: _
// EquivalentResourceMapper provides information about resources that address the same underlying data as a specified resource
#EquivalentResourceMapper: _
// EquivalentResourceRegistry provides an EquivalentResourceMapper interface,
// and allows registering known resource[/subresource] -> kind
#EquivalentResourceRegistry: _
// ResourceVersioner provides methods for setting and retrieving
// the resource version from an API object.
#ResourceVersioner: _
// Namer provides methods for retrieving name and namespace of an API object.
#Namer: _
// Object interface must be supported by all API types registered with Scheme. Since objects in a scheme are
// expected to be serialized to the wire, the interface an Object must provide to the Scheme allows
// serializers to set the kind, version, and group the object is represented as. An Object may choose
// to return a no-op ObjectKindAccessor in cases where it is not expected to be serialized.
#Object: _
// CacheableObject allows an object to cache its different serializations
// to avoid performing the same serialization multiple times.
#CacheableObject: _
// Unstructured objects store values as map[string]interface{}, with only values that can be serialized
// to JSON allowed.
#Unstructured: _

View File

@@ -0,0 +1,12 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/runtime
package runtime
// NegotiateError is returned when a ClientNegotiator is unable to locate
// a serializer for the requested operation.
#NegotiateError: {
ContentType: string
Stream: bool
}

View File

@@ -0,0 +1,12 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/runtime
package runtime
// Splice is the interface that wraps the Splice method.
//
// Splice moves data from given slice without copying the underlying data for
// efficiency purpose. Therefore, the caller should make sure the underlying
// data is not changed later.
#Splice: _

View File

@@ -0,0 +1,14 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/runtime
package runtime
// Pair of strings. We keed the name of fields and the doc
#Pair: {
Name: string
Doc: string
}
// KubeTypes is an array to represent all available types in a parsed file. [0] is for the type itself
#KubeTypes: [...#Pair]

View File

@@ -0,0 +1,97 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/runtime
package runtime
// TypeMeta is shared by all top level objects. The proper way to use it is to inline it in your type,
// like this:
//
// type MyAwesomeAPIObject struct {
// runtime.TypeMeta `json:",inline"`
// ... // other fields
// }
//
// func (obj *MyAwesomeAPIObject) SetGroupVersionKind(gvk *metav1.GroupVersionKind) { metav1.UpdateTypeMeta(obj,gvk) }; GroupVersionKind() *GroupVersionKind
//
// TypeMeta is provided here for convenience. You may use it directly from this package or define
// your own with the same fields.
//
// +k8s:deepcopy-gen=false
// +protobuf=true
// +k8s:openapi-gen=true
#TypeMeta: {
// +optional
apiVersion?: string @go(APIVersion) @protobuf(1,bytes,opt)
// +optional
kind?: string @go(Kind) @protobuf(2,bytes,opt)
}
#ContentTypeJSON: "application/json"
#ContentTypeYAML: "application/yaml"
#ContentTypeProtobuf: "application/vnd.kubernetes.protobuf"
// RawExtension is used to hold extensions in external versions.
//
// To use this, make a field which has RawExtension as its type in your external, versioned
// struct, and Object in your internal struct. You also need to register your
// various plugin types.
//
// // Internal package:
//
// type MyAPIObject struct {
// runtime.TypeMeta `json:",inline"`
// MyPlugin runtime.Object `json:"myPlugin"`
// }
//
// type PluginA struct {
// AOption string `json:"aOption"`
// }
//
// // External package:
//
// type MyAPIObject struct {
// runtime.TypeMeta `json:",inline"`
// MyPlugin runtime.RawExtension `json:"myPlugin"`
// }
//
// type PluginA struct {
// AOption string `json:"aOption"`
// }
//
// // On the wire, the JSON will look something like this:
//
// {
// "kind":"MyAPIObject",
// "apiVersion":"v1",
// "myPlugin": {
// "kind":"PluginA",
// "aOption":"foo",
// },
// }
//
// So what happens? Decode first uses json or yaml to unmarshal the serialized data into
// your external MyAPIObject. That causes the raw JSON to be stored, but not unpacked.
// The next step is to copy (using pkg/conversion) into the internal struct. The runtime
// package's DefaultScheme has conversion functions installed which will unpack the
// JSON stored in RawExtension, turning it into the correct object type, and storing it
// in the Object. (TODO: In the case where the object is of an unknown type, a
// runtime.Unknown object will be created and stored.)
//
// +k8s:deepcopy-gen=true
// +protobuf=true
// +k8s:openapi-gen=true
#RawExtension: _
// Unknown allows api objects with unknown types to be passed-through. This can be used
// to deal with the API objects from a plug-in. Unknown objects still have functioning
// TypeMeta features-- kind, version, etc.
// TODO: Make this object have easy access to field based accessors and settors for
// metadata and field mutatation.
//
// +k8s:deepcopy-gen=true
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// +protobuf=true
// +k8s:openapi-gen=true
#Unknown: _

View File

@@ -0,0 +1,9 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/runtime
package runtime
#ProtobufMarshaller: _
#ProtobufReverseMarshaller: _

View File

@@ -0,0 +1,6 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/types
// Package types implements various generic types used throughout kubernetes.
package types

View File

@@ -0,0 +1,12 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/types
package types
#NamespacedName: {
Namespace: string
Name: string
}
#Separator: 47 // '/'

View File

@@ -0,0 +1,31 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/types
package types
// NodeName is a type that holds a api.Node's Name identifier.
// Being a type captures intent and helps make sure that the node name
// is not confused with similar concepts (the hostname, the cloud provider id,
// the cloud provider name etc)
//
// To clarify the various types:
//
// - Node.Name is the Name field of the Node in the API. This should be stored in a NodeName.
// Unfortunately, because Name is part of ObjectMeta, we can't store it as a NodeName at the API level.
//
// - Hostname is the hostname of the local machine (from uname -n).
// However, some components allow the user to pass in a --hostname-override flag,
// which will override this in most places. In the absence of anything more meaningful,
// kubelet will use Hostname as the Node.Name when it creates the Node.
//
// * The cloudproviders have the own names: GCE has InstanceName, AWS has InstanceId.
//
// For GCE, InstanceName is the Name of an Instance object in the GCE API. On GCE, Instance.Name becomes the
// Hostname, and thus it makes sense also to use it as the Node.Name. But that is GCE specific, and it is up
// to the cloudprovider how to do this mapping.
//
// For AWS, the InstanceID is not yet suitable for use as a Node.Name, so we actually use the
// PrivateDnsName for the Node.Name. And this is _not_ always the same as the hostname: if
// we are using a custom DHCP domain it won't be.
#NodeName: string

View File

@@ -0,0 +1,21 @@
// Code generated by cue get go. DO NOT EDIT.
//cue:generate cue get go k8s.io/apimachinery/pkg/types
package types
// Similarly to above, these are constants to support HTTP PATCH utilized by
// both the client and server that didn't make sense for a whole package to be
// dedicated to.
#PatchType: string // #enumPatchType
#enumPatchType:
#JSONPatchType |
#MergePatchType |
#StrategicMergePatchType |
#ApplyPatchType
#JSONPatchType: #PatchType & "application/json-patch+json"
#MergePatchType: #PatchType & "application/merge-patch+json"
#StrategicMergePatchType: #PatchType & "application/strategic-merge-patch+json"
#ApplyPatchType: #PatchType & "application/apply-patch+yaml"

Some files were not shown because too many files have changed in this diff Show More