diff --git a/backend/app/api/main.go b/backend/app/api/main.go index c505eea..08fe52c 100644 --- a/backend/app/api/main.go +++ b/backend/app/api/main.go @@ -7,7 +7,9 @@ import ( "path/filepath" "time" + "ariga.io/atlas/sql/migrate" atlas "ariga.io/atlas/sql/migrate" + "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql/schema" "github.com/hay-kot/homebox/backend/app/api/static/docs" "github.com/hay-kot/homebox/backend/internal/core/services" @@ -93,6 +95,14 @@ func run(cfg *config.Config) error { schema.WithDir(dir), schema.WithDropColumn(true), schema.WithDropIndex(true), + schema.WithAtlas(true), + schema.WithApplyHook(func(next schema.Applier) schema.Applier { + return schema.ApplyFunc(func(ctx context.Context, conn dialect.ExecQuerier, plan *migrate.Plan) error { + // Log the plan. + log.Info().Msgf("Applying migration %s", plan.Version) + return next.Apply(ctx, conn, plan) + }) + }), } err = c.Schema.Create(context.Background(), options...) diff --git a/backend/app/tools/migrations/main.go b/backend/app/tools/migrations/main.go index a2f6624..e53e7ba 100644 --- a/backend/app/tools/migrations/main.go +++ b/backend/app/tools/migrations/main.go @@ -2,6 +2,7 @@ package main import ( "context" + "fmt" "log" "os" @@ -39,4 +40,6 @@ func main() { if err != nil { log.Fatalf("failed generating migration file: %v", err) } + + fmt.Println("Migration file generated successfully.") } diff --git a/backend/internal/data/ent/client.go b/backend/internal/data/ent/client.go index 85ac645..eb66c20 100644 --- a/backend/internal/data/ent/client.go +++ b/backend/internal/data/ent/client.go @@ -21,6 +21,7 @@ import ( "github.com/hay-kot/homebox/backend/internal/data/ent/itemfield" "github.com/hay-kot/homebox/backend/internal/data/ent/label" "github.com/hay-kot/homebox/backend/internal/data/ent/location" + "github.com/hay-kot/homebox/backend/internal/data/ent/maintenanceentry" "github.com/hay-kot/homebox/backend/internal/data/ent/user" "entgo.io/ent/dialect" @@ -53,6 +54,8 @@ type Client struct { Label *LabelClient // Location is the client for interacting with the Location builders. Location *LocationClient + // MaintenanceEntry is the client for interacting with the MaintenanceEntry builders. + MaintenanceEntry *MaintenanceEntryClient // User is the client for interacting with the User builders. User *UserClient } @@ -78,6 +81,7 @@ func (c *Client) init() { c.ItemField = NewItemFieldClient(c.config) c.Label = NewLabelClient(c.config) c.Location = NewLocationClient(c.config) + c.MaintenanceEntry = NewMaintenanceEntryClient(c.config) c.User = NewUserClient(c.config) } @@ -122,6 +126,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { ItemField: NewItemFieldClient(cfg), Label: NewLabelClient(cfg), Location: NewLocationClient(cfg), + MaintenanceEntry: NewMaintenanceEntryClient(cfg), User: NewUserClient(cfg), }, nil } @@ -152,6 +157,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) ItemField: NewItemFieldClient(cfg), Label: NewLabelClient(cfg), Location: NewLocationClient(cfg), + MaintenanceEntry: NewMaintenanceEntryClient(cfg), User: NewUserClient(cfg), }, nil } @@ -191,6 +197,7 @@ func (c *Client) Use(hooks ...Hook) { c.ItemField.Use(hooks...) c.Label.Use(hooks...) c.Location.Use(hooks...) + c.MaintenanceEntry.Use(hooks...) c.User.Use(hooks...) } @@ -1139,6 +1146,22 @@ func (c *ItemClient) QueryFields(i *Item) *ItemFieldQuery { return query } +// QueryMaintenanceEntries queries the maintenance_entries edge of a Item. +func (c *ItemClient) QueryMaintenanceEntries(i *Item) *MaintenanceEntryQuery { + query := &MaintenanceEntryQuery{config: c.config} + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := i.ID + step := sqlgraph.NewStep( + sqlgraph.From(item.Table, item.FieldID, id), + sqlgraph.To(maintenanceentry.Table, maintenanceentry.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, item.MaintenanceEntriesTable, item.MaintenanceEntriesColumn), + ) + fromV = sqlgraph.Neighbors(i.driver.Dialect(), step) + return fromV, nil + } + return query +} + // QueryAttachments queries the attachments edge of a Item. func (c *ItemClient) QueryAttachments(i *Item) *AttachmentQuery { query := &AttachmentQuery{config: c.config} @@ -1542,6 +1565,112 @@ func (c *LocationClient) Hooks() []Hook { return c.hooks.Location } +// MaintenanceEntryClient is a client for the MaintenanceEntry schema. +type MaintenanceEntryClient struct { + config +} + +// NewMaintenanceEntryClient returns a client for the MaintenanceEntry from the given config. +func NewMaintenanceEntryClient(c config) *MaintenanceEntryClient { + return &MaintenanceEntryClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `maintenanceentry.Hooks(f(g(h())))`. +func (c *MaintenanceEntryClient) Use(hooks ...Hook) { + c.hooks.MaintenanceEntry = append(c.hooks.MaintenanceEntry, hooks...) +} + +// Create returns a builder for creating a MaintenanceEntry entity. +func (c *MaintenanceEntryClient) Create() *MaintenanceEntryCreate { + mutation := newMaintenanceEntryMutation(c.config, OpCreate) + return &MaintenanceEntryCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of MaintenanceEntry entities. +func (c *MaintenanceEntryClient) CreateBulk(builders ...*MaintenanceEntryCreate) *MaintenanceEntryCreateBulk { + return &MaintenanceEntryCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for MaintenanceEntry. +func (c *MaintenanceEntryClient) Update() *MaintenanceEntryUpdate { + mutation := newMaintenanceEntryMutation(c.config, OpUpdate) + return &MaintenanceEntryUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *MaintenanceEntryClient) UpdateOne(me *MaintenanceEntry) *MaintenanceEntryUpdateOne { + mutation := newMaintenanceEntryMutation(c.config, OpUpdateOne, withMaintenanceEntry(me)) + return &MaintenanceEntryUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *MaintenanceEntryClient) UpdateOneID(id uuid.UUID) *MaintenanceEntryUpdateOne { + mutation := newMaintenanceEntryMutation(c.config, OpUpdateOne, withMaintenanceEntryID(id)) + return &MaintenanceEntryUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for MaintenanceEntry. +func (c *MaintenanceEntryClient) Delete() *MaintenanceEntryDelete { + mutation := newMaintenanceEntryMutation(c.config, OpDelete) + return &MaintenanceEntryDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *MaintenanceEntryClient) DeleteOne(me *MaintenanceEntry) *MaintenanceEntryDeleteOne { + return c.DeleteOneID(me.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *MaintenanceEntryClient) DeleteOneID(id uuid.UUID) *MaintenanceEntryDeleteOne { + builder := c.Delete().Where(maintenanceentry.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &MaintenanceEntryDeleteOne{builder} +} + +// Query returns a query builder for MaintenanceEntry. +func (c *MaintenanceEntryClient) Query() *MaintenanceEntryQuery { + return &MaintenanceEntryQuery{ + config: c.config, + } +} + +// Get returns a MaintenanceEntry entity by its id. +func (c *MaintenanceEntryClient) Get(ctx context.Context, id uuid.UUID) (*MaintenanceEntry, error) { + return c.Query().Where(maintenanceentry.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *MaintenanceEntryClient) GetX(ctx context.Context, id uuid.UUID) *MaintenanceEntry { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryItem queries the item edge of a MaintenanceEntry. +func (c *MaintenanceEntryClient) QueryItem(me *MaintenanceEntry) *ItemQuery { + query := &ItemQuery{config: c.config} + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := me.ID + step := sqlgraph.NewStep( + sqlgraph.From(maintenanceentry.Table, maintenanceentry.FieldID, id), + sqlgraph.To(item.Table, item.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, maintenanceentry.ItemTable, maintenanceentry.ItemColumn), + ) + fromV = sqlgraph.Neighbors(me.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *MaintenanceEntryClient) Hooks() []Hook { + return c.hooks.MaintenanceEntry +} + // UserClient is a client for the User schema. type UserClient struct { config diff --git a/backend/internal/data/ent/config.go b/backend/internal/data/ent/config.go index 3937124..9cba253 100644 --- a/backend/internal/data/ent/config.go +++ b/backend/internal/data/ent/config.go @@ -34,6 +34,7 @@ type hooks struct { ItemField []ent.Hook Label []ent.Hook Location []ent.Hook + MaintenanceEntry []ent.Hook User []ent.Hook } diff --git a/backend/internal/data/ent/ent.go b/backend/internal/data/ent/ent.go index f4fe103..adf8df3 100644 --- a/backend/internal/data/ent/ent.go +++ b/backend/internal/data/ent/ent.go @@ -20,6 +20,7 @@ import ( "github.com/hay-kot/homebox/backend/internal/data/ent/itemfield" "github.com/hay-kot/homebox/backend/internal/data/ent/label" "github.com/hay-kot/homebox/backend/internal/data/ent/location" + "github.com/hay-kot/homebox/backend/internal/data/ent/maintenanceentry" "github.com/hay-kot/homebox/backend/internal/data/ent/user" ) @@ -51,6 +52,7 @@ func columnChecker(table string) func(string) error { itemfield.Table: itemfield.ValidColumn, label.Table: label.ValidColumn, location.Table: location.ValidColumn, + maintenanceentry.Table: maintenanceentry.ValidColumn, user.Table: user.ValidColumn, } check, ok := checks[table] diff --git a/backend/internal/data/ent/has_id.go b/backend/internal/data/ent/has_id.go index 7132131..875ba0d 100644 --- a/backend/internal/data/ent/has_id.go +++ b/backend/internal/data/ent/has_id.go @@ -44,6 +44,10 @@ func (l *Location) GetID() uuid.UUID { return l.ID } +func (me *MaintenanceEntry) GetID() uuid.UUID { + return me.ID +} + func (u *User) GetID() uuid.UUID { return u.ID } diff --git a/backend/internal/data/ent/hook/hook.go b/backend/internal/data/ent/hook/hook.go index cc24278..08c9401 100644 --- a/backend/internal/data/ent/hook/hook.go +++ b/backend/internal/data/ent/hook/hook.go @@ -139,6 +139,19 @@ func (f LocationFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, er return f(ctx, mv) } +// The MaintenanceEntryFunc type is an adapter to allow the use of ordinary +// function as MaintenanceEntry mutator. +type MaintenanceEntryFunc func(context.Context, *ent.MaintenanceEntryMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f MaintenanceEntryFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + mv, ok := m.(*ent.MaintenanceEntryMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.MaintenanceEntryMutation", m) + } + return f(ctx, mv) +} + // 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) diff --git a/backend/internal/data/ent/item.go b/backend/internal/data/ent/item.go index a780945..bcca2c7 100644 --- a/backend/internal/data/ent/item.go +++ b/backend/internal/data/ent/item.go @@ -87,11 +87,13 @@ type ItemEdges struct { Location *Location `json:"location,omitempty"` // Fields holds the value of the fields edge. Fields []*ItemField `json:"fields,omitempty"` + // MaintenanceEntries holds the value of the maintenance_entries edge. + MaintenanceEntries []*MaintenanceEntry `json:"maintenance_entries,omitempty"` // Attachments holds the value of the attachments edge. Attachments []*Attachment `json:"attachments,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [7]bool + loadedTypes [8]bool } // ParentOrErr returns the Parent value or an error if the edge @@ -160,10 +162,19 @@ func (e ItemEdges) FieldsOrErr() ([]*ItemField, error) { return nil, &NotLoadedError{edge: "fields"} } +// MaintenanceEntriesOrErr returns the MaintenanceEntries value or an error if the edge +// was not loaded in eager-loading. +func (e ItemEdges) MaintenanceEntriesOrErr() ([]*MaintenanceEntry, error) { + if e.loadedTypes[6] { + return e.MaintenanceEntries, nil + } + return nil, &NotLoadedError{edge: "maintenance_entries"} +} + // AttachmentsOrErr returns the Attachments value or an error if the edge // was not loaded in eager-loading. func (e ItemEdges) AttachmentsOrErr() ([]*Attachment, error) { - if e.loadedTypes[6] { + if e.loadedTypes[7] { return e.Attachments, nil } return nil, &NotLoadedError{edge: "attachments"} @@ -407,6 +418,11 @@ func (i *Item) QueryFields() *ItemFieldQuery { return (&ItemClient{config: i.config}).QueryFields(i) } +// QueryMaintenanceEntries queries the "maintenance_entries" edge of the Item entity. +func (i *Item) QueryMaintenanceEntries() *MaintenanceEntryQuery { + return (&ItemClient{config: i.config}).QueryMaintenanceEntries(i) +} + // QueryAttachments queries the "attachments" edge of the Item entity. func (i *Item) QueryAttachments() *AttachmentQuery { return (&ItemClient{config: i.config}).QueryAttachments(i) diff --git a/backend/internal/data/ent/item/item.go b/backend/internal/data/ent/item/item.go index ab3b43f..2cb7f6d 100644 --- a/backend/internal/data/ent/item/item.go +++ b/backend/internal/data/ent/item/item.go @@ -71,6 +71,8 @@ const ( EdgeLocation = "location" // EdgeFields holds the string denoting the fields edge name in mutations. EdgeFields = "fields" + // EdgeMaintenanceEntries holds the string denoting the maintenance_entries edge name in mutations. + EdgeMaintenanceEntries = "maintenance_entries" // EdgeAttachments holds the string denoting the attachments edge name in mutations. EdgeAttachments = "attachments" // Table holds the table name of the item in the database. @@ -109,6 +111,13 @@ const ( FieldsInverseTable = "item_fields" // FieldsColumn is the table column denoting the fields relation/edge. FieldsColumn = "item_fields" + // MaintenanceEntriesTable is the table that holds the maintenance_entries relation/edge. + MaintenanceEntriesTable = "maintenance_entries" + // MaintenanceEntriesInverseTable is the table name for the MaintenanceEntry entity. + // It exists in this package in order to avoid circular dependency with the "maintenanceentry" package. + MaintenanceEntriesInverseTable = "maintenance_entries" + // MaintenanceEntriesColumn is the table column denoting the maintenance_entries relation/edge. + MaintenanceEntriesColumn = "item_id" // AttachmentsTable is the table that holds the attachments relation/edge. AttachmentsTable = "attachments" // AttachmentsInverseTable is the table name for the Attachment entity. diff --git a/backend/internal/data/ent/item/where.go b/backend/internal/data/ent/item/where.go index 2174432..cef11f4 100644 --- a/backend/internal/data/ent/item/where.go +++ b/backend/internal/data/ent/item/where.go @@ -2300,6 +2300,34 @@ func HasFieldsWith(preds ...predicate.ItemField) predicate.Item { }) } +// HasMaintenanceEntries applies the HasEdge predicate on the "maintenance_entries" edge. +func HasMaintenanceEntries() predicate.Item { + return predicate.Item(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(MaintenanceEntriesTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, MaintenanceEntriesTable, MaintenanceEntriesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasMaintenanceEntriesWith applies the HasEdge predicate on the "maintenance_entries" edge with a given conditions (other predicates). +func HasMaintenanceEntriesWith(preds ...predicate.MaintenanceEntry) predicate.Item { + return predicate.Item(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(MaintenanceEntriesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, MaintenanceEntriesTable, MaintenanceEntriesColumn), + ) + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + // HasAttachments applies the HasEdge predicate on the "attachments" edge. func HasAttachments() predicate.Item { return predicate.Item(func(s *sql.Selector) { diff --git a/backend/internal/data/ent/item_create.go b/backend/internal/data/ent/item_create.go index 97938f9..4a7c5aa 100644 --- a/backend/internal/data/ent/item_create.go +++ b/backend/internal/data/ent/item_create.go @@ -17,6 +17,7 @@ import ( "github.com/hay-kot/homebox/backend/internal/data/ent/itemfield" "github.com/hay-kot/homebox/backend/internal/data/ent/label" "github.com/hay-kot/homebox/backend/internal/data/ent/location" + "github.com/hay-kot/homebox/backend/internal/data/ent/maintenanceentry" ) // ItemCreate is the builder for creating a Item entity. @@ -448,6 +449,21 @@ func (ic *ItemCreate) AddFields(i ...*ItemField) *ItemCreate { return ic.AddFieldIDs(ids...) } +// AddMaintenanceEntryIDs adds the "maintenance_entries" edge to the MaintenanceEntry entity by IDs. +func (ic *ItemCreate) AddMaintenanceEntryIDs(ids ...uuid.UUID) *ItemCreate { + ic.mutation.AddMaintenanceEntryIDs(ids...) + return ic +} + +// AddMaintenanceEntries adds the "maintenance_entries" edges to the MaintenanceEntry entity. +func (ic *ItemCreate) AddMaintenanceEntries(m ...*MaintenanceEntry) *ItemCreate { + ids := make([]uuid.UUID, len(m)) + for i := range m { + ids[i] = m[i].ID + } + return ic.AddMaintenanceEntryIDs(ids...) +} + // AddAttachmentIDs adds the "attachments" edge to the Attachment entity by IDs. func (ic *ItemCreate) AddAttachmentIDs(ids ...uuid.UUID) *ItemCreate { ic.mutation.AddAttachmentIDs(ids...) @@ -907,6 +923,25 @@ func (ic *ItemCreate) createSpec() (*Item, *sqlgraph.CreateSpec) { } _spec.Edges = append(_spec.Edges, edge) } + if nodes := ic.mutation.MaintenanceEntriesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: item.MaintenanceEntriesTable, + Columns: []string{item.MaintenanceEntriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: maintenanceentry.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } if nodes := ic.mutation.AttachmentsIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, diff --git a/backend/internal/data/ent/item_query.go b/backend/internal/data/ent/item_query.go index 0040a42..8891469 100644 --- a/backend/internal/data/ent/item_query.go +++ b/backend/internal/data/ent/item_query.go @@ -18,26 +18,28 @@ import ( "github.com/hay-kot/homebox/backend/internal/data/ent/itemfield" "github.com/hay-kot/homebox/backend/internal/data/ent/label" "github.com/hay-kot/homebox/backend/internal/data/ent/location" + "github.com/hay-kot/homebox/backend/internal/data/ent/maintenanceentry" "github.com/hay-kot/homebox/backend/internal/data/ent/predicate" ) // ItemQuery is the builder for querying Item entities. type ItemQuery struct { config - limit *int - offset *int - unique *bool - order []OrderFunc - fields []string - predicates []predicate.Item - withParent *ItemQuery - withChildren *ItemQuery - withGroup *GroupQuery - withLabel *LabelQuery - withLocation *LocationQuery - withFields *ItemFieldQuery - withAttachments *AttachmentQuery - withFKs bool + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.Item + withParent *ItemQuery + withChildren *ItemQuery + withGroup *GroupQuery + withLabel *LabelQuery + withLocation *LocationQuery + withFields *ItemFieldQuery + withMaintenanceEntries *MaintenanceEntryQuery + withAttachments *AttachmentQuery + withFKs bool // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) @@ -206,6 +208,28 @@ func (iq *ItemQuery) QueryFields() *ItemFieldQuery { return query } +// QueryMaintenanceEntries chains the current query on the "maintenance_entries" edge. +func (iq *ItemQuery) QueryMaintenanceEntries() *MaintenanceEntryQuery { + query := &MaintenanceEntryQuery{config: iq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := iq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := iq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(item.Table, item.FieldID, selector), + sqlgraph.To(maintenanceentry.Table, maintenanceentry.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, item.MaintenanceEntriesTable, item.MaintenanceEntriesColumn), + ) + fromU = sqlgraph.SetNeighbors(iq.driver.Dialect(), step) + return fromU, nil + } + return query +} + // QueryAttachments chains the current query on the "attachments" edge. func (iq *ItemQuery) QueryAttachments() *AttachmentQuery { query := &AttachmentQuery{config: iq.config} @@ -404,18 +428,19 @@ func (iq *ItemQuery) Clone() *ItemQuery { return nil } return &ItemQuery{ - config: iq.config, - limit: iq.limit, - offset: iq.offset, - order: append([]OrderFunc{}, iq.order...), - predicates: append([]predicate.Item{}, iq.predicates...), - withParent: iq.withParent.Clone(), - withChildren: iq.withChildren.Clone(), - withGroup: iq.withGroup.Clone(), - withLabel: iq.withLabel.Clone(), - withLocation: iq.withLocation.Clone(), - withFields: iq.withFields.Clone(), - withAttachments: iq.withAttachments.Clone(), + config: iq.config, + limit: iq.limit, + offset: iq.offset, + order: append([]OrderFunc{}, iq.order...), + predicates: append([]predicate.Item{}, iq.predicates...), + withParent: iq.withParent.Clone(), + withChildren: iq.withChildren.Clone(), + withGroup: iq.withGroup.Clone(), + withLabel: iq.withLabel.Clone(), + withLocation: iq.withLocation.Clone(), + withFields: iq.withFields.Clone(), + withMaintenanceEntries: iq.withMaintenanceEntries.Clone(), + withAttachments: iq.withAttachments.Clone(), // clone intermediate query. sql: iq.sql.Clone(), path: iq.path, @@ -489,6 +514,17 @@ func (iq *ItemQuery) WithFields(opts ...func(*ItemFieldQuery)) *ItemQuery { return iq } +// WithMaintenanceEntries tells the query-builder to eager-load the nodes that are connected to +// the "maintenance_entries" edge. The optional arguments are used to configure the query builder of the edge. +func (iq *ItemQuery) WithMaintenanceEntries(opts ...func(*MaintenanceEntryQuery)) *ItemQuery { + query := &MaintenanceEntryQuery{config: iq.config} + for _, opt := range opts { + opt(query) + } + iq.withMaintenanceEntries = query + return iq +} + // WithAttachments tells the query-builder to eager-load the nodes that are connected to // the "attachments" edge. The optional arguments are used to configure the query builder of the edge. func (iq *ItemQuery) WithAttachments(opts ...func(*AttachmentQuery)) *ItemQuery { @@ -574,13 +610,14 @@ func (iq *ItemQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Item, e nodes = []*Item{} withFKs = iq.withFKs _spec = iq.querySpec() - loadedTypes = [7]bool{ + loadedTypes = [8]bool{ iq.withParent != nil, iq.withChildren != nil, iq.withGroup != nil, iq.withLabel != nil, iq.withLocation != nil, iq.withFields != nil, + iq.withMaintenanceEntries != nil, iq.withAttachments != nil, } ) @@ -647,6 +684,13 @@ func (iq *ItemQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Item, e return nil, err } } + if query := iq.withMaintenanceEntries; query != nil { + if err := iq.loadMaintenanceEntries(ctx, query, nodes, + func(n *Item) { n.Edges.MaintenanceEntries = []*MaintenanceEntry{} }, + func(n *Item, e *MaintenanceEntry) { n.Edges.MaintenanceEntries = append(n.Edges.MaintenanceEntries, e) }); err != nil { + return nil, err + } + } if query := iq.withAttachments; query != nil { if err := iq.loadAttachments(ctx, query, nodes, func(n *Item) { n.Edges.Attachments = []*Attachment{} }, @@ -864,6 +908,33 @@ func (iq *ItemQuery) loadFields(ctx context.Context, query *ItemFieldQuery, node } return nil } +func (iq *ItemQuery) loadMaintenanceEntries(ctx context.Context, query *MaintenanceEntryQuery, nodes []*Item, init func(*Item), assign func(*Item, *MaintenanceEntry)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[uuid.UUID]*Item) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + query.Where(predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.InValues(item.MaintenanceEntriesColumn, fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.ItemID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected foreign-key "item_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} func (iq *ItemQuery) loadAttachments(ctx context.Context, query *AttachmentQuery, nodes []*Item, init func(*Item), assign func(*Item, *Attachment)) error { fks := make([]driver.Value, 0, len(nodes)) nodeids := make(map[uuid.UUID]*Item) diff --git a/backend/internal/data/ent/item_update.go b/backend/internal/data/ent/item_update.go index 236f363..b7a9b79 100644 --- a/backend/internal/data/ent/item_update.go +++ b/backend/internal/data/ent/item_update.go @@ -18,6 +18,7 @@ import ( "github.com/hay-kot/homebox/backend/internal/data/ent/itemfield" "github.com/hay-kot/homebox/backend/internal/data/ent/label" "github.com/hay-kot/homebox/backend/internal/data/ent/location" + "github.com/hay-kot/homebox/backend/internal/data/ent/maintenanceentry" "github.com/hay-kot/homebox/backend/internal/data/ent/predicate" ) @@ -506,6 +507,21 @@ func (iu *ItemUpdate) AddFields(i ...*ItemField) *ItemUpdate { return iu.AddFieldIDs(ids...) } +// AddMaintenanceEntryIDs adds the "maintenance_entries" edge to the MaintenanceEntry entity by IDs. +func (iu *ItemUpdate) AddMaintenanceEntryIDs(ids ...uuid.UUID) *ItemUpdate { + iu.mutation.AddMaintenanceEntryIDs(ids...) + return iu +} + +// AddMaintenanceEntries adds the "maintenance_entries" edges to the MaintenanceEntry entity. +func (iu *ItemUpdate) AddMaintenanceEntries(m ...*MaintenanceEntry) *ItemUpdate { + ids := make([]uuid.UUID, len(m)) + for i := range m { + ids[i] = m[i].ID + } + return iu.AddMaintenanceEntryIDs(ids...) +} + // AddAttachmentIDs adds the "attachments" edge to the Attachment entity by IDs. func (iu *ItemUpdate) AddAttachmentIDs(ids ...uuid.UUID) *ItemUpdate { iu.mutation.AddAttachmentIDs(ids...) @@ -607,6 +623,27 @@ func (iu *ItemUpdate) RemoveFields(i ...*ItemField) *ItemUpdate { return iu.RemoveFieldIDs(ids...) } +// ClearMaintenanceEntries clears all "maintenance_entries" edges to the MaintenanceEntry entity. +func (iu *ItemUpdate) ClearMaintenanceEntries() *ItemUpdate { + iu.mutation.ClearMaintenanceEntries() + return iu +} + +// RemoveMaintenanceEntryIDs removes the "maintenance_entries" edge to MaintenanceEntry entities by IDs. +func (iu *ItemUpdate) RemoveMaintenanceEntryIDs(ids ...uuid.UUID) *ItemUpdate { + iu.mutation.RemoveMaintenanceEntryIDs(ids...) + return iu +} + +// RemoveMaintenanceEntries removes "maintenance_entries" edges to MaintenanceEntry entities. +func (iu *ItemUpdate) RemoveMaintenanceEntries(m ...*MaintenanceEntry) *ItemUpdate { + ids := make([]uuid.UUID, len(m)) + for i := range m { + ids[i] = m[i].ID + } + return iu.RemoveMaintenanceEntryIDs(ids...) +} + // ClearAttachments clears all "attachments" edges to the Attachment entity. func (iu *ItemUpdate) ClearAttachments() *ItemUpdate { iu.mutation.ClearAttachments() @@ -1144,6 +1181,60 @@ func (iu *ItemUpdate) sqlSave(ctx context.Context) (n int, err error) { } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if iu.mutation.MaintenanceEntriesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: item.MaintenanceEntriesTable, + Columns: []string{item.MaintenanceEntriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: maintenanceentry.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := iu.mutation.RemovedMaintenanceEntriesIDs(); len(nodes) > 0 && !iu.mutation.MaintenanceEntriesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: item.MaintenanceEntriesTable, + Columns: []string{item.MaintenanceEntriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: maintenanceentry.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := iu.mutation.MaintenanceEntriesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: item.MaintenanceEntriesTable, + Columns: []string{item.MaintenanceEntriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: maintenanceentry.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if iu.mutation.AttachmentsCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, @@ -1689,6 +1780,21 @@ func (iuo *ItemUpdateOne) AddFields(i ...*ItemField) *ItemUpdateOne { return iuo.AddFieldIDs(ids...) } +// AddMaintenanceEntryIDs adds the "maintenance_entries" edge to the MaintenanceEntry entity by IDs. +func (iuo *ItemUpdateOne) AddMaintenanceEntryIDs(ids ...uuid.UUID) *ItemUpdateOne { + iuo.mutation.AddMaintenanceEntryIDs(ids...) + return iuo +} + +// AddMaintenanceEntries adds the "maintenance_entries" edges to the MaintenanceEntry entity. +func (iuo *ItemUpdateOne) AddMaintenanceEntries(m ...*MaintenanceEntry) *ItemUpdateOne { + ids := make([]uuid.UUID, len(m)) + for i := range m { + ids[i] = m[i].ID + } + return iuo.AddMaintenanceEntryIDs(ids...) +} + // AddAttachmentIDs adds the "attachments" edge to the Attachment entity by IDs. func (iuo *ItemUpdateOne) AddAttachmentIDs(ids ...uuid.UUID) *ItemUpdateOne { iuo.mutation.AddAttachmentIDs(ids...) @@ -1790,6 +1896,27 @@ func (iuo *ItemUpdateOne) RemoveFields(i ...*ItemField) *ItemUpdateOne { return iuo.RemoveFieldIDs(ids...) } +// ClearMaintenanceEntries clears all "maintenance_entries" edges to the MaintenanceEntry entity. +func (iuo *ItemUpdateOne) ClearMaintenanceEntries() *ItemUpdateOne { + iuo.mutation.ClearMaintenanceEntries() + return iuo +} + +// RemoveMaintenanceEntryIDs removes the "maintenance_entries" edge to MaintenanceEntry entities by IDs. +func (iuo *ItemUpdateOne) RemoveMaintenanceEntryIDs(ids ...uuid.UUID) *ItemUpdateOne { + iuo.mutation.RemoveMaintenanceEntryIDs(ids...) + return iuo +} + +// RemoveMaintenanceEntries removes "maintenance_entries" edges to MaintenanceEntry entities. +func (iuo *ItemUpdateOne) RemoveMaintenanceEntries(m ...*MaintenanceEntry) *ItemUpdateOne { + ids := make([]uuid.UUID, len(m)) + for i := range m { + ids[i] = m[i].ID + } + return iuo.RemoveMaintenanceEntryIDs(ids...) +} + // ClearAttachments clears all "attachments" edges to the Attachment entity. func (iuo *ItemUpdateOne) ClearAttachments() *ItemUpdateOne { iuo.mutation.ClearAttachments() @@ -2357,6 +2484,60 @@ func (iuo *ItemUpdateOne) sqlSave(ctx context.Context) (_node *Item, err error) } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if iuo.mutation.MaintenanceEntriesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: item.MaintenanceEntriesTable, + Columns: []string{item.MaintenanceEntriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: maintenanceentry.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := iuo.mutation.RemovedMaintenanceEntriesIDs(); len(nodes) > 0 && !iuo.mutation.MaintenanceEntriesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: item.MaintenanceEntriesTable, + Columns: []string{item.MaintenanceEntriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: maintenanceentry.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := iuo.mutation.MaintenanceEntriesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: item.MaintenanceEntriesTable, + Columns: []string{item.MaintenanceEntriesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: maintenanceentry.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if iuo.mutation.AttachmentsCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, diff --git a/backend/internal/data/ent/maintenanceentry.go b/backend/internal/data/ent/maintenanceentry.go new file mode 100644 index 0000000..4d0b078 --- /dev/null +++ b/backend/internal/data/ent/maintenanceentry.go @@ -0,0 +1,202 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + "time" + + "entgo.io/ent/dialect/sql" + "github.com/google/uuid" + "github.com/hay-kot/homebox/backend/internal/data/ent/item" + "github.com/hay-kot/homebox/backend/internal/data/ent/maintenanceentry" +) + +// MaintenanceEntry is the model entity for the MaintenanceEntry schema. +type MaintenanceEntry 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"` + // ItemID holds the value of the "item_id" field. + ItemID uuid.UUID `json:"item_id,omitempty"` + // Date holds the value of the "date" field. + Date time.Time `json:"date,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Description holds the value of the "description" field. + Description string `json:"description,omitempty"` + // Cost holds the value of the "cost" field. + Cost float64 `json:"cost,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the MaintenanceEntryQuery when eager-loading is set. + Edges MaintenanceEntryEdges `json:"edges"` +} + +// MaintenanceEntryEdges holds the relations/edges for other nodes in the graph. +type MaintenanceEntryEdges struct { + // Item holds the value of the item edge. + Item *Item `json:"item,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// ItemOrErr returns the Item value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e MaintenanceEntryEdges) ItemOrErr() (*Item, error) { + if e.loadedTypes[0] { + if e.Item == nil { + // Edge was loaded but was not found. + return nil, &NotFoundError{label: item.Label} + } + return e.Item, nil + } + return nil, &NotLoadedError{edge: "item"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*MaintenanceEntry) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case maintenanceentry.FieldCost: + values[i] = new(sql.NullFloat64) + case maintenanceentry.FieldName, maintenanceentry.FieldDescription: + values[i] = new(sql.NullString) + case maintenanceentry.FieldCreatedAt, maintenanceentry.FieldUpdatedAt, maintenanceentry.FieldDate: + values[i] = new(sql.NullTime) + case maintenanceentry.FieldID, maintenanceentry.FieldItemID: + values[i] = new(uuid.UUID) + default: + return nil, fmt.Errorf("unexpected column %q for type MaintenanceEntry", columns[i]) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the MaintenanceEntry fields. +func (me *MaintenanceEntry) 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 maintenanceentry.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + me.ID = *value + } + case maintenanceentry.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 { + me.CreatedAt = value.Time + } + case maintenanceentry.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 { + me.UpdatedAt = value.Time + } + case maintenanceentry.FieldItemID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field item_id", values[i]) + } else if value != nil { + me.ItemID = *value + } + case maintenanceentry.FieldDate: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field date", values[i]) + } else if value.Valid { + me.Date = value.Time + } + case maintenanceentry.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + me.Name = value.String + } + case maintenanceentry.FieldDescription: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field description", values[i]) + } else if value.Valid { + me.Description = value.String + } + case maintenanceentry.FieldCost: + if value, ok := values[i].(*sql.NullFloat64); !ok { + return fmt.Errorf("unexpected type %T for field cost", values[i]) + } else if value.Valid { + me.Cost = value.Float64 + } + } + } + return nil +} + +// QueryItem queries the "item" edge of the MaintenanceEntry entity. +func (me *MaintenanceEntry) QueryItem() *ItemQuery { + return (&MaintenanceEntryClient{config: me.config}).QueryItem(me) +} + +// Update returns a builder for updating this MaintenanceEntry. +// Note that you need to call MaintenanceEntry.Unwrap() before calling this method if this MaintenanceEntry +// was returned from a transaction, and the transaction was committed or rolled back. +func (me *MaintenanceEntry) Update() *MaintenanceEntryUpdateOne { + return (&MaintenanceEntryClient{config: me.config}).UpdateOne(me) +} + +// Unwrap unwraps the MaintenanceEntry 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 (me *MaintenanceEntry) Unwrap() *MaintenanceEntry { + _tx, ok := me.config.driver.(*txDriver) + if !ok { + panic("ent: MaintenanceEntry is not a transactional entity") + } + me.config.driver = _tx.drv + return me +} + +// String implements the fmt.Stringer. +func (me *MaintenanceEntry) String() string { + var builder strings.Builder + builder.WriteString("MaintenanceEntry(") + builder.WriteString(fmt.Sprintf("id=%v, ", me.ID)) + builder.WriteString("created_at=") + builder.WriteString(me.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("updated_at=") + builder.WriteString(me.UpdatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("item_id=") + builder.WriteString(fmt.Sprintf("%v", me.ItemID)) + builder.WriteString(", ") + builder.WriteString("date=") + builder.WriteString(me.Date.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("name=") + builder.WriteString(me.Name) + builder.WriteString(", ") + builder.WriteString("description=") + builder.WriteString(me.Description) + builder.WriteString(", ") + builder.WriteString("cost=") + builder.WriteString(fmt.Sprintf("%v", me.Cost)) + builder.WriteByte(')') + return builder.String() +} + +// MaintenanceEntries is a parsable slice of MaintenanceEntry. +type MaintenanceEntries []*MaintenanceEntry + +func (me MaintenanceEntries) config(cfg config) { + for _i := range me { + me[_i].config = cfg + } +} diff --git a/backend/internal/data/ent/maintenanceentry/maintenanceentry.go b/backend/internal/data/ent/maintenanceentry/maintenanceentry.go new file mode 100644 index 0000000..c1dcffc --- /dev/null +++ b/backend/internal/data/ent/maintenanceentry/maintenanceentry.go @@ -0,0 +1,82 @@ +// Code generated by ent, DO NOT EDIT. + +package maintenanceentry + +import ( + "time" + + "github.com/google/uuid" +) + +const ( + // Label holds the string label denoting the maintenanceentry type in the database. + Label = "maintenance_entry" + // 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" + // FieldItemID holds the string denoting the item_id field in the database. + FieldItemID = "item_id" + // FieldDate holds the string denoting the date field in the database. + FieldDate = "date" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldDescription holds the string denoting the description field in the database. + FieldDescription = "description" + // FieldCost holds the string denoting the cost field in the database. + FieldCost = "cost" + // EdgeItem holds the string denoting the item edge name in mutations. + EdgeItem = "item" + // Table holds the table name of the maintenanceentry in the database. + Table = "maintenance_entries" + // ItemTable is the table that holds the item relation/edge. + ItemTable = "maintenance_entries" + // ItemInverseTable is the table name for the Item entity. + // It exists in this package in order to avoid circular dependency with the "item" package. + ItemInverseTable = "items" + // ItemColumn is the table column denoting the item relation/edge. + ItemColumn = "item_id" +) + +// Columns holds all SQL columns for maintenanceentry fields. +var Columns = []string{ + FieldID, + FieldCreatedAt, + FieldUpdatedAt, + FieldItemID, + FieldDate, + FieldName, + FieldDescription, + FieldCost, +} + +// 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 + // DefaultDate holds the default value on creation for the "date" field. + DefaultDate func() time.Time + // NameValidator is a validator for the "name" field. It is called by the builders before save. + NameValidator func(string) error + // DescriptionValidator is a validator for the "description" field. It is called by the builders before save. + DescriptionValidator func(string) error + // DefaultCost holds the default value on creation for the "cost" field. + DefaultCost float64 + // DefaultID holds the default value on creation for the "id" field. + DefaultID func() uuid.UUID +) diff --git a/backend/internal/data/ent/maintenanceentry/where.go b/backend/internal/data/ent/maintenanceentry/where.go new file mode 100644 index 0000000..02d9633 --- /dev/null +++ b/backend/internal/data/ent/maintenanceentry/where.go @@ -0,0 +1,696 @@ +// Code generated by ent, DO NOT EDIT. + +package maintenanceentry + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/google/uuid" + "github.com/hay-kot/homebox/backend/internal/data/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id uuid.UUID) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldID), id)) + }) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldID), id)) + }) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + v := make([]any, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.In(s.C(FieldID), v...)) + }) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + v := make([]any, len(ids)) + for i := range v { + v[i] = ids[i] + } + s.Where(sql.NotIn(s.C(FieldID), v...)) + }) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldID), id)) + }) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldID), id)) + }) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldID), id)) + }) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldID), id)) + }) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCreatedAt), v)) + }) +} + +// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. +func UpdatedAt(v time.Time) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUpdatedAt), v)) + }) +} + +// ItemID applies equality check predicate on the "item_id" field. It's identical to ItemIDEQ. +func ItemID(v uuid.UUID) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldItemID), v)) + }) +} + +// Date applies equality check predicate on the "date" field. It's identical to DateEQ. +func Date(v time.Time) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldDate), v)) + }) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldName), v)) + }) +} + +// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ. +func Description(v string) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldDescription), v)) + }) +} + +// Cost applies equality check predicate on the "cost" field. It's identical to CostEQ. +func Cost(v float64) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCost), v)) + }) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCreatedAt), v)) + }) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldCreatedAt), v)) + }) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.MaintenanceEntry { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.In(s.C(FieldCreatedAt), v...)) + }) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.MaintenanceEntry { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.NotIn(s.C(FieldCreatedAt), v...)) + }) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldCreatedAt), v)) + }) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldCreatedAt), v)) + }) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldCreatedAt), v)) + }) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldCreatedAt), v)) + }) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldUpdatedAt), v)) + }) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldUpdatedAt), v)) + }) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.MaintenanceEntry { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.In(s.C(FieldUpdatedAt), v...)) + }) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.MaintenanceEntry { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.NotIn(s.C(FieldUpdatedAt), v...)) + }) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldUpdatedAt), v)) + }) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldUpdatedAt), v)) + }) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldUpdatedAt), v)) + }) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldUpdatedAt), v)) + }) +} + +// ItemIDEQ applies the EQ predicate on the "item_id" field. +func ItemIDEQ(v uuid.UUID) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldItemID), v)) + }) +} + +// ItemIDNEQ applies the NEQ predicate on the "item_id" field. +func ItemIDNEQ(v uuid.UUID) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldItemID), v)) + }) +} + +// ItemIDIn applies the In predicate on the "item_id" field. +func ItemIDIn(vs ...uuid.UUID) predicate.MaintenanceEntry { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.In(s.C(FieldItemID), v...)) + }) +} + +// ItemIDNotIn applies the NotIn predicate on the "item_id" field. +func ItemIDNotIn(vs ...uuid.UUID) predicate.MaintenanceEntry { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.NotIn(s.C(FieldItemID), v...)) + }) +} + +// DateEQ applies the EQ predicate on the "date" field. +func DateEQ(v time.Time) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldDate), v)) + }) +} + +// DateNEQ applies the NEQ predicate on the "date" field. +func DateNEQ(v time.Time) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldDate), v)) + }) +} + +// DateIn applies the In predicate on the "date" field. +func DateIn(vs ...time.Time) predicate.MaintenanceEntry { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.In(s.C(FieldDate), v...)) + }) +} + +// DateNotIn applies the NotIn predicate on the "date" field. +func DateNotIn(vs ...time.Time) predicate.MaintenanceEntry { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.NotIn(s.C(FieldDate), v...)) + }) +} + +// DateGT applies the GT predicate on the "date" field. +func DateGT(v time.Time) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldDate), v)) + }) +} + +// DateGTE applies the GTE predicate on the "date" field. +func DateGTE(v time.Time) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldDate), v)) + }) +} + +// DateLT applies the LT predicate on the "date" field. +func DateLT(v time.Time) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldDate), v)) + }) +} + +// DateLTE applies the LTE predicate on the "date" field. +func DateLTE(v time.Time) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldDate), v)) + }) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldName), v)) + }) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldName), v)) + }) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.MaintenanceEntry { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.In(s.C(FieldName), v...)) + }) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.MaintenanceEntry { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.NotIn(s.C(FieldName), v...)) + }) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldName), v)) + }) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldName), v)) + }) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldName), v)) + }) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldName), v)) + }) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldName), v)) + }) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldName), v)) + }) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldName), v)) + }) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldName), v)) + }) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldName), v)) + }) +} + +// DescriptionEQ applies the EQ predicate on the "description" field. +func DescriptionEQ(v string) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldDescription), v)) + }) +} + +// DescriptionNEQ applies the NEQ predicate on the "description" field. +func DescriptionNEQ(v string) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldDescription), v)) + }) +} + +// DescriptionIn applies the In predicate on the "description" field. +func DescriptionIn(vs ...string) predicate.MaintenanceEntry { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.In(s.C(FieldDescription), v...)) + }) +} + +// DescriptionNotIn applies the NotIn predicate on the "description" field. +func DescriptionNotIn(vs ...string) predicate.MaintenanceEntry { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.NotIn(s.C(FieldDescription), v...)) + }) +} + +// DescriptionGT applies the GT predicate on the "description" field. +func DescriptionGT(v string) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldDescription), v)) + }) +} + +// DescriptionGTE applies the GTE predicate on the "description" field. +func DescriptionGTE(v string) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldDescription), v)) + }) +} + +// DescriptionLT applies the LT predicate on the "description" field. +func DescriptionLT(v string) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldDescription), v)) + }) +} + +// DescriptionLTE applies the LTE predicate on the "description" field. +func DescriptionLTE(v string) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldDescription), v)) + }) +} + +// DescriptionContains applies the Contains predicate on the "description" field. +func DescriptionContains(v string) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.Contains(s.C(FieldDescription), v)) + }) +} + +// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field. +func DescriptionHasPrefix(v string) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.HasPrefix(s.C(FieldDescription), v)) + }) +} + +// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field. +func DescriptionHasSuffix(v string) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.HasSuffix(s.C(FieldDescription), v)) + }) +} + +// DescriptionIsNil applies the IsNil predicate on the "description" field. +func DescriptionIsNil() predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.IsNull(s.C(FieldDescription))) + }) +} + +// DescriptionNotNil applies the NotNil predicate on the "description" field. +func DescriptionNotNil() predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.NotNull(s.C(FieldDescription))) + }) +} + +// DescriptionEqualFold applies the EqualFold predicate on the "description" field. +func DescriptionEqualFold(v string) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.EqualFold(s.C(FieldDescription), v)) + }) +} + +// DescriptionContainsFold applies the ContainsFold predicate on the "description" field. +func DescriptionContainsFold(v string) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.ContainsFold(s.C(FieldDescription), v)) + }) +} + +// CostEQ applies the EQ predicate on the "cost" field. +func CostEQ(v float64) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.EQ(s.C(FieldCost), v)) + }) +} + +// CostNEQ applies the NEQ predicate on the "cost" field. +func CostNEQ(v float64) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.NEQ(s.C(FieldCost), v)) + }) +} + +// CostIn applies the In predicate on the "cost" field. +func CostIn(vs ...float64) predicate.MaintenanceEntry { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.In(s.C(FieldCost), v...)) + }) +} + +// CostNotIn applies the NotIn predicate on the "cost" field. +func CostNotIn(vs ...float64) predicate.MaintenanceEntry { + v := make([]any, len(vs)) + for i := range v { + v[i] = vs[i] + } + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.NotIn(s.C(FieldCost), v...)) + }) +} + +// CostGT applies the GT predicate on the "cost" field. +func CostGT(v float64) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.GT(s.C(FieldCost), v)) + }) +} + +// CostGTE applies the GTE predicate on the "cost" field. +func CostGTE(v float64) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.GTE(s.C(FieldCost), v)) + }) +} + +// CostLT applies the LT predicate on the "cost" field. +func CostLT(v float64) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.LT(s.C(FieldCost), v)) + }) +} + +// CostLTE applies the LTE predicate on the "cost" field. +func CostLTE(v float64) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s.Where(sql.LTE(s.C(FieldCost), v)) + }) +} + +// HasItem applies the HasEdge predicate on the "item" edge. +func HasItem() predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ItemTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ItemTable, ItemColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasItemWith applies the HasEdge predicate on the "item" edge with a given conditions (other predicates). +func HasItemWith(preds ...predicate.Item) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ItemInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ItemTable, ItemColumn), + ) + 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.MaintenanceEntry) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for _, p := range predicates { + p(s1) + } + s.Where(s1.P()) + }) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.MaintenanceEntry) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + s1 := s.Clone().SetP(nil) + for i, p := range predicates { + if i > 0 { + s1.Or() + } + p(s1) + } + s.Where(s1.P()) + }) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.MaintenanceEntry) predicate.MaintenanceEntry { + return predicate.MaintenanceEntry(func(s *sql.Selector) { + p(s.Not()) + }) +} diff --git a/backend/internal/data/ent/maintenanceentry_create.go b/backend/internal/data/ent/maintenanceentry_create.go new file mode 100644 index 0000000..3abaa84 --- /dev/null +++ b/backend/internal/data/ent/maintenanceentry_create.go @@ -0,0 +1,419 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/google/uuid" + "github.com/hay-kot/homebox/backend/internal/data/ent/item" + "github.com/hay-kot/homebox/backend/internal/data/ent/maintenanceentry" +) + +// MaintenanceEntryCreate is the builder for creating a MaintenanceEntry entity. +type MaintenanceEntryCreate struct { + config + mutation *MaintenanceEntryMutation + hooks []Hook +} + +// SetCreatedAt sets the "created_at" field. +func (mec *MaintenanceEntryCreate) SetCreatedAt(t time.Time) *MaintenanceEntryCreate { + mec.mutation.SetCreatedAt(t) + return mec +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (mec *MaintenanceEntryCreate) SetNillableCreatedAt(t *time.Time) *MaintenanceEntryCreate { + if t != nil { + mec.SetCreatedAt(*t) + } + return mec +} + +// SetUpdatedAt sets the "updated_at" field. +func (mec *MaintenanceEntryCreate) SetUpdatedAt(t time.Time) *MaintenanceEntryCreate { + mec.mutation.SetUpdatedAt(t) + return mec +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (mec *MaintenanceEntryCreate) SetNillableUpdatedAt(t *time.Time) *MaintenanceEntryCreate { + if t != nil { + mec.SetUpdatedAt(*t) + } + return mec +} + +// SetItemID sets the "item_id" field. +func (mec *MaintenanceEntryCreate) SetItemID(u uuid.UUID) *MaintenanceEntryCreate { + mec.mutation.SetItemID(u) + return mec +} + +// SetDate sets the "date" field. +func (mec *MaintenanceEntryCreate) SetDate(t time.Time) *MaintenanceEntryCreate { + mec.mutation.SetDate(t) + return mec +} + +// SetNillableDate sets the "date" field if the given value is not nil. +func (mec *MaintenanceEntryCreate) SetNillableDate(t *time.Time) *MaintenanceEntryCreate { + if t != nil { + mec.SetDate(*t) + } + return mec +} + +// SetName sets the "name" field. +func (mec *MaintenanceEntryCreate) SetName(s string) *MaintenanceEntryCreate { + mec.mutation.SetName(s) + return mec +} + +// SetDescription sets the "description" field. +func (mec *MaintenanceEntryCreate) SetDescription(s string) *MaintenanceEntryCreate { + mec.mutation.SetDescription(s) + return mec +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (mec *MaintenanceEntryCreate) SetNillableDescription(s *string) *MaintenanceEntryCreate { + if s != nil { + mec.SetDescription(*s) + } + return mec +} + +// SetCost sets the "cost" field. +func (mec *MaintenanceEntryCreate) SetCost(f float64) *MaintenanceEntryCreate { + mec.mutation.SetCost(f) + return mec +} + +// SetNillableCost sets the "cost" field if the given value is not nil. +func (mec *MaintenanceEntryCreate) SetNillableCost(f *float64) *MaintenanceEntryCreate { + if f != nil { + mec.SetCost(*f) + } + return mec +} + +// SetID sets the "id" field. +func (mec *MaintenanceEntryCreate) SetID(u uuid.UUID) *MaintenanceEntryCreate { + mec.mutation.SetID(u) + return mec +} + +// SetNillableID sets the "id" field if the given value is not nil. +func (mec *MaintenanceEntryCreate) SetNillableID(u *uuid.UUID) *MaintenanceEntryCreate { + if u != nil { + mec.SetID(*u) + } + return mec +} + +// SetItem sets the "item" edge to the Item entity. +func (mec *MaintenanceEntryCreate) SetItem(i *Item) *MaintenanceEntryCreate { + return mec.SetItemID(i.ID) +} + +// Mutation returns the MaintenanceEntryMutation object of the builder. +func (mec *MaintenanceEntryCreate) Mutation() *MaintenanceEntryMutation { + return mec.mutation +} + +// Save creates the MaintenanceEntry in the database. +func (mec *MaintenanceEntryCreate) Save(ctx context.Context) (*MaintenanceEntry, error) { + var ( + err error + node *MaintenanceEntry + ) + mec.defaults() + if len(mec.hooks) == 0 { + if err = mec.check(); err != nil { + return nil, err + } + node, err = mec.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*MaintenanceEntryMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = mec.check(); err != nil { + return nil, err + } + mec.mutation = mutation + if node, err = mec.sqlSave(ctx); err != nil { + return nil, err + } + mutation.id = &node.ID + mutation.done = true + return node, err + }) + for i := len(mec.hooks) - 1; i >= 0; i-- { + if mec.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = mec.hooks[i](mut) + } + v, err := mut.Mutate(ctx, mec.mutation) + if err != nil { + return nil, err + } + nv, ok := v.(*MaintenanceEntry) + if !ok { + return nil, fmt.Errorf("unexpected node type %T returned from MaintenanceEntryMutation", v) + } + node = nv + } + return node, err +} + +// SaveX calls Save and panics if Save returns an error. +func (mec *MaintenanceEntryCreate) SaveX(ctx context.Context) *MaintenanceEntry { + v, err := mec.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (mec *MaintenanceEntryCreate) Exec(ctx context.Context) error { + _, err := mec.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (mec *MaintenanceEntryCreate) ExecX(ctx context.Context) { + if err := mec.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (mec *MaintenanceEntryCreate) defaults() { + if _, ok := mec.mutation.CreatedAt(); !ok { + v := maintenanceentry.DefaultCreatedAt() + mec.mutation.SetCreatedAt(v) + } + if _, ok := mec.mutation.UpdatedAt(); !ok { + v := maintenanceentry.DefaultUpdatedAt() + mec.mutation.SetUpdatedAt(v) + } + if _, ok := mec.mutation.Date(); !ok { + v := maintenanceentry.DefaultDate() + mec.mutation.SetDate(v) + } + if _, ok := mec.mutation.Cost(); !ok { + v := maintenanceentry.DefaultCost + mec.mutation.SetCost(v) + } + if _, ok := mec.mutation.ID(); !ok { + v := maintenanceentry.DefaultID() + mec.mutation.SetID(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (mec *MaintenanceEntryCreate) check() error { + if _, ok := mec.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "MaintenanceEntry.created_at"`)} + } + if _, ok := mec.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "MaintenanceEntry.updated_at"`)} + } + if _, ok := mec.mutation.ItemID(); !ok { + return &ValidationError{Name: "item_id", err: errors.New(`ent: missing required field "MaintenanceEntry.item_id"`)} + } + if _, ok := mec.mutation.Date(); !ok { + return &ValidationError{Name: "date", err: errors.New(`ent: missing required field "MaintenanceEntry.date"`)} + } + if _, ok := mec.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "MaintenanceEntry.name"`)} + } + if v, ok := mec.mutation.Name(); ok { + if err := maintenanceentry.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "MaintenanceEntry.name": %w`, err)} + } + } + if v, ok := mec.mutation.Description(); ok { + if err := maintenanceentry.DescriptionValidator(v); err != nil { + return &ValidationError{Name: "description", err: fmt.Errorf(`ent: validator failed for field "MaintenanceEntry.description": %w`, err)} + } + } + if _, ok := mec.mutation.Cost(); !ok { + return &ValidationError{Name: "cost", err: errors.New(`ent: missing required field "MaintenanceEntry.cost"`)} + } + if _, ok := mec.mutation.ItemID(); !ok { + return &ValidationError{Name: "item", err: errors.New(`ent: missing required edge "MaintenanceEntry.item"`)} + } + return nil +} + +func (mec *MaintenanceEntryCreate) sqlSave(ctx context.Context) (*MaintenanceEntry, error) { + _node, _spec := mec.createSpec() + if err := sqlgraph.CreateNode(ctx, mec.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 + } + } + return _node, nil +} + +func (mec *MaintenanceEntryCreate) createSpec() (*MaintenanceEntry, *sqlgraph.CreateSpec) { + var ( + _node = &MaintenanceEntry{config: mec.config} + _spec = &sqlgraph.CreateSpec{ + Table: maintenanceentry.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: maintenanceentry.FieldID, + }, + } + ) + if id, ok := mec.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := mec.mutation.CreatedAt(); ok { + _spec.SetField(maintenanceentry.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := mec.mutation.UpdatedAt(); ok { + _spec.SetField(maintenanceentry.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if value, ok := mec.mutation.Date(); ok { + _spec.SetField(maintenanceentry.FieldDate, field.TypeTime, value) + _node.Date = value + } + if value, ok := mec.mutation.Name(); ok { + _spec.SetField(maintenanceentry.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := mec.mutation.Description(); ok { + _spec.SetField(maintenanceentry.FieldDescription, field.TypeString, value) + _node.Description = value + } + if value, ok := mec.mutation.Cost(); ok { + _spec.SetField(maintenanceentry.FieldCost, field.TypeFloat64, value) + _node.Cost = value + } + if nodes := mec.mutation.ItemIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: maintenanceentry.ItemTable, + Columns: []string{maintenanceentry.ItemColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: item.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.ItemID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// MaintenanceEntryCreateBulk is the builder for creating many MaintenanceEntry entities in bulk. +type MaintenanceEntryCreateBulk struct { + config + builders []*MaintenanceEntryCreate +} + +// Save creates the MaintenanceEntry entities in the database. +func (mecb *MaintenanceEntryCreateBulk) Save(ctx context.Context) ([]*MaintenanceEntry, error) { + specs := make([]*sqlgraph.CreateSpec, len(mecb.builders)) + nodes := make([]*MaintenanceEntry, len(mecb.builders)) + mutators := make([]Mutator, len(mecb.builders)) + for i := range mecb.builders { + func(i int, root context.Context) { + builder := mecb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*MaintenanceEntryMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + nodes[i], specs[i] = builder.createSpec() + var err error + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, mecb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, mecb.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, mecb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (mecb *MaintenanceEntryCreateBulk) SaveX(ctx context.Context) []*MaintenanceEntry { + v, err := mecb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (mecb *MaintenanceEntryCreateBulk) Exec(ctx context.Context) error { + _, err := mecb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (mecb *MaintenanceEntryCreateBulk) ExecX(ctx context.Context) { + if err := mecb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/internal/data/ent/maintenanceentry_delete.go b/backend/internal/data/ent/maintenanceentry_delete.go new file mode 100644 index 0000000..ea0ed2a --- /dev/null +++ b/backend/internal/data/ent/maintenanceentry_delete.go @@ -0,0 +1,115 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/hay-kot/homebox/backend/internal/data/ent/maintenanceentry" + "github.com/hay-kot/homebox/backend/internal/data/ent/predicate" +) + +// MaintenanceEntryDelete is the builder for deleting a MaintenanceEntry entity. +type MaintenanceEntryDelete struct { + config + hooks []Hook + mutation *MaintenanceEntryMutation +} + +// Where appends a list predicates to the MaintenanceEntryDelete builder. +func (med *MaintenanceEntryDelete) Where(ps ...predicate.MaintenanceEntry) *MaintenanceEntryDelete { + med.mutation.Where(ps...) + return med +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (med *MaintenanceEntryDelete) Exec(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + if len(med.hooks) == 0 { + affected, err = med.sqlExec(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*MaintenanceEntryMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + med.mutation = mutation + affected, err = med.sqlExec(ctx) + mutation.done = true + return affected, err + }) + for i := len(med.hooks) - 1; i >= 0; i-- { + if med.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = med.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, med.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// ExecX is like Exec, but panics if an error occurs. +func (med *MaintenanceEntryDelete) ExecX(ctx context.Context) int { + n, err := med.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (med *MaintenanceEntryDelete) sqlExec(ctx context.Context) (int, error) { + _spec := &sqlgraph.DeleteSpec{ + Node: &sqlgraph.NodeSpec{ + Table: maintenanceentry.Table, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: maintenanceentry.FieldID, + }, + }, + } + if ps := med.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, med.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return affected, err +} + +// MaintenanceEntryDeleteOne is the builder for deleting a single MaintenanceEntry entity. +type MaintenanceEntryDeleteOne struct { + med *MaintenanceEntryDelete +} + +// Exec executes the deletion query. +func (medo *MaintenanceEntryDeleteOne) Exec(ctx context.Context) error { + n, err := medo.med.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{maintenanceentry.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (medo *MaintenanceEntryDeleteOne) ExecX(ctx context.Context) { + medo.med.ExecX(ctx) +} diff --git a/backend/internal/data/ent/maintenanceentry_query.go b/backend/internal/data/ent/maintenanceentry_query.go new file mode 100644 index 0000000..bcc95b5 --- /dev/null +++ b/backend/internal/data/ent/maintenanceentry_query.go @@ -0,0 +1,622 @@ +// 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/google/uuid" + "github.com/hay-kot/homebox/backend/internal/data/ent/item" + "github.com/hay-kot/homebox/backend/internal/data/ent/maintenanceentry" + "github.com/hay-kot/homebox/backend/internal/data/ent/predicate" +) + +// MaintenanceEntryQuery is the builder for querying MaintenanceEntry entities. +type MaintenanceEntryQuery struct { + config + limit *int + offset *int + unique *bool + order []OrderFunc + fields []string + predicates []predicate.MaintenanceEntry + withItem *ItemQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the MaintenanceEntryQuery builder. +func (meq *MaintenanceEntryQuery) Where(ps ...predicate.MaintenanceEntry) *MaintenanceEntryQuery { + meq.predicates = append(meq.predicates, ps...) + return meq +} + +// Limit adds a limit step to the query. +func (meq *MaintenanceEntryQuery) Limit(limit int) *MaintenanceEntryQuery { + meq.limit = &limit + return meq +} + +// Offset adds an offset step to the query. +func (meq *MaintenanceEntryQuery) Offset(offset int) *MaintenanceEntryQuery { + meq.offset = &offset + return meq +} + +// 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 (meq *MaintenanceEntryQuery) Unique(unique bool) *MaintenanceEntryQuery { + meq.unique = &unique + return meq +} + +// Order adds an order step to the query. +func (meq *MaintenanceEntryQuery) Order(o ...OrderFunc) *MaintenanceEntryQuery { + meq.order = append(meq.order, o...) + return meq +} + +// QueryItem chains the current query on the "item" edge. +func (meq *MaintenanceEntryQuery) QueryItem() *ItemQuery { + query := &ItemQuery{config: meq.config} + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := meq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := meq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(maintenanceentry.Table, maintenanceentry.FieldID, selector), + sqlgraph.To(item.Table, item.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, maintenanceentry.ItemTable, maintenanceentry.ItemColumn), + ) + fromU = sqlgraph.SetNeighbors(meq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first MaintenanceEntry entity from the query. +// Returns a *NotFoundError when no MaintenanceEntry was found. +func (meq *MaintenanceEntryQuery) First(ctx context.Context) (*MaintenanceEntry, error) { + nodes, err := meq.Limit(1).All(ctx) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{maintenanceentry.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (meq *MaintenanceEntryQuery) FirstX(ctx context.Context) *MaintenanceEntry { + node, err := meq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first MaintenanceEntry ID from the query. +// Returns a *NotFoundError when no MaintenanceEntry ID was found. +func (meq *MaintenanceEntryQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = meq.Limit(1).IDs(ctx); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{maintenanceentry.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (meq *MaintenanceEntryQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := meq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single MaintenanceEntry entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one MaintenanceEntry entity is found. +// Returns a *NotFoundError when no MaintenanceEntry entities are found. +func (meq *MaintenanceEntryQuery) Only(ctx context.Context) (*MaintenanceEntry, error) { + nodes, err := meq.Limit(2).All(ctx) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{maintenanceentry.Label} + default: + return nil, &NotSingularError{maintenanceentry.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (meq *MaintenanceEntryQuery) OnlyX(ctx context.Context) *MaintenanceEntry { + node, err := meq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only MaintenanceEntry ID in the query. +// Returns a *NotSingularError when more than one MaintenanceEntry ID is found. +// Returns a *NotFoundError when no entities are found. +func (meq *MaintenanceEntryQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = meq.Limit(2).IDs(ctx); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{maintenanceentry.Label} + default: + err = &NotSingularError{maintenanceentry.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (meq *MaintenanceEntryQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := meq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of MaintenanceEntries. +func (meq *MaintenanceEntryQuery) All(ctx context.Context) ([]*MaintenanceEntry, error) { + if err := meq.prepareQuery(ctx); err != nil { + return nil, err + } + return meq.sqlAll(ctx) +} + +// AllX is like All, but panics if an error occurs. +func (meq *MaintenanceEntryQuery) AllX(ctx context.Context) []*MaintenanceEntry { + nodes, err := meq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of MaintenanceEntry IDs. +func (meq *MaintenanceEntryQuery) IDs(ctx context.Context) ([]uuid.UUID, error) { + var ids []uuid.UUID + if err := meq.Select(maintenanceentry.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (meq *MaintenanceEntryQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := meq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (meq *MaintenanceEntryQuery) Count(ctx context.Context) (int, error) { + if err := meq.prepareQuery(ctx); err != nil { + return 0, err + } + return meq.sqlCount(ctx) +} + +// CountX is like Count, but panics if an error occurs. +func (meq *MaintenanceEntryQuery) CountX(ctx context.Context) int { + count, err := meq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (meq *MaintenanceEntryQuery) Exist(ctx context.Context) (bool, error) { + if err := meq.prepareQuery(ctx); err != nil { + return false, err + } + return meq.sqlExist(ctx) +} + +// ExistX is like Exist, but panics if an error occurs. +func (meq *MaintenanceEntryQuery) ExistX(ctx context.Context) bool { + exist, err := meq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the MaintenanceEntryQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (meq *MaintenanceEntryQuery) Clone() *MaintenanceEntryQuery { + if meq == nil { + return nil + } + return &MaintenanceEntryQuery{ + config: meq.config, + limit: meq.limit, + offset: meq.offset, + order: append([]OrderFunc{}, meq.order...), + predicates: append([]predicate.MaintenanceEntry{}, meq.predicates...), + withItem: meq.withItem.Clone(), + // clone intermediate query. + sql: meq.sql.Clone(), + path: meq.path, + unique: meq.unique, + } +} + +// WithItem tells the query-builder to eager-load the nodes that are connected to +// the "item" edge. The optional arguments are used to configure the query builder of the edge. +func (meq *MaintenanceEntryQuery) WithItem(opts ...func(*ItemQuery)) *MaintenanceEntryQuery { + query := &ItemQuery{config: meq.config} + for _, opt := range opts { + opt(query) + } + meq.withItem = query + return meq +} + +// 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.MaintenanceEntry.Query(). +// GroupBy(maintenanceentry.FieldCreatedAt). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (meq *MaintenanceEntryQuery) GroupBy(field string, fields ...string) *MaintenanceEntryGroupBy { + grbuild := &MaintenanceEntryGroupBy{config: meq.config} + grbuild.fields = append([]string{field}, fields...) + grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) { + if err := meq.prepareQuery(ctx); err != nil { + return nil, err + } + return meq.sqlQuery(ctx), nil + } + grbuild.label = maintenanceentry.Label + grbuild.flds, grbuild.scan = &grbuild.fields, 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.MaintenanceEntry.Query(). +// Select(maintenanceentry.FieldCreatedAt). +// Scan(ctx, &v) +func (meq *MaintenanceEntryQuery) Select(fields ...string) *MaintenanceEntrySelect { + meq.fields = append(meq.fields, fields...) + selbuild := &MaintenanceEntrySelect{MaintenanceEntryQuery: meq} + selbuild.label = maintenanceentry.Label + selbuild.flds, selbuild.scan = &meq.fields, selbuild.Scan + return selbuild +} + +// Aggregate returns a MaintenanceEntrySelect configured with the given aggregations. +func (meq *MaintenanceEntryQuery) Aggregate(fns ...AggregateFunc) *MaintenanceEntrySelect { + return meq.Select().Aggregate(fns...) +} + +func (meq *MaintenanceEntryQuery) prepareQuery(ctx context.Context) error { + for _, f := range meq.fields { + if !maintenanceentry.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if meq.path != nil { + prev, err := meq.path(ctx) + if err != nil { + return err + } + meq.sql = prev + } + return nil +} + +func (meq *MaintenanceEntryQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*MaintenanceEntry, error) { + var ( + nodes = []*MaintenanceEntry{} + _spec = meq.querySpec() + loadedTypes = [1]bool{ + meq.withItem != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*MaintenanceEntry).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &MaintenanceEntry{config: meq.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, meq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := meq.withItem; query != nil { + if err := meq.loadItem(ctx, query, nodes, nil, + func(n *MaintenanceEntry, e *Item) { n.Edges.Item = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (meq *MaintenanceEntryQuery) loadItem(ctx context.Context, query *ItemQuery, nodes []*MaintenanceEntry, init func(*MaintenanceEntry), assign func(*MaintenanceEntry, *Item)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*MaintenanceEntry) + for i := range nodes { + fk := nodes[i].ItemID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + query.Where(item.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 "item_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (meq *MaintenanceEntryQuery) sqlCount(ctx context.Context) (int, error) { + _spec := meq.querySpec() + _spec.Node.Columns = meq.fields + if len(meq.fields) > 0 { + _spec.Unique = meq.unique != nil && *meq.unique + } + return sqlgraph.CountNodes(ctx, meq.driver, _spec) +} + +func (meq *MaintenanceEntryQuery) sqlExist(ctx context.Context) (bool, error) { + switch _, err := meq.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +func (meq *MaintenanceEntryQuery) querySpec() *sqlgraph.QuerySpec { + _spec := &sqlgraph.QuerySpec{ + Node: &sqlgraph.NodeSpec{ + Table: maintenanceentry.Table, + Columns: maintenanceentry.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: maintenanceentry.FieldID, + }, + }, + From: meq.sql, + Unique: true, + } + if unique := meq.unique; unique != nil { + _spec.Unique = *unique + } + if fields := meq.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, maintenanceentry.FieldID) + for i := range fields { + if fields[i] != maintenanceentry.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := meq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := meq.limit; limit != nil { + _spec.Limit = *limit + } + if offset := meq.offset; offset != nil { + _spec.Offset = *offset + } + if ps := meq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (meq *MaintenanceEntryQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(meq.driver.Dialect()) + t1 := builder.Table(maintenanceentry.Table) + columns := meq.fields + if len(columns) == 0 { + columns = maintenanceentry.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if meq.sql != nil { + selector = meq.sql + selector.Select(selector.Columns(columns...)...) + } + if meq.unique != nil && *meq.unique { + selector.Distinct() + } + for _, p := range meq.predicates { + p(selector) + } + for _, p := range meq.order { + p(selector) + } + if offset := meq.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 := meq.limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// MaintenanceEntryGroupBy is the group-by builder for MaintenanceEntry entities. +type MaintenanceEntryGroupBy struct { + config + selector + fields []string + fns []AggregateFunc + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (megb *MaintenanceEntryGroupBy) Aggregate(fns ...AggregateFunc) *MaintenanceEntryGroupBy { + megb.fns = append(megb.fns, fns...) + return megb +} + +// Scan applies the group-by query and scans the result into the given value. +func (megb *MaintenanceEntryGroupBy) Scan(ctx context.Context, v any) error { + query, err := megb.path(ctx) + if err != nil { + return err + } + megb.sql = query + return megb.sqlScan(ctx, v) +} + +func (megb *MaintenanceEntryGroupBy) sqlScan(ctx context.Context, v any) error { + for _, f := range megb.fields { + if !maintenanceentry.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)} + } + } + selector := megb.sqlQuery() + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := megb.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +func (megb *MaintenanceEntryGroupBy) sqlQuery() *sql.Selector { + selector := megb.sql.Select() + aggregation := make([]string, 0, len(megb.fns)) + for _, fn := range megb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(megb.fields)+len(megb.fns)) + for _, f := range megb.fields { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + return selector.GroupBy(selector.Columns(megb.fields...)...) +} + +// MaintenanceEntrySelect is the builder for selecting fields of MaintenanceEntry entities. +type MaintenanceEntrySelect struct { + *MaintenanceEntryQuery + selector + // intermediate query (i.e. traversal path). + sql *sql.Selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (mes *MaintenanceEntrySelect) Aggregate(fns ...AggregateFunc) *MaintenanceEntrySelect { + mes.fns = append(mes.fns, fns...) + return mes +} + +// Scan applies the selector query and scans the result into the given value. +func (mes *MaintenanceEntrySelect) Scan(ctx context.Context, v any) error { + if err := mes.prepareQuery(ctx); err != nil { + return err + } + mes.sql = mes.MaintenanceEntryQuery.sqlQuery(ctx) + return mes.sqlScan(ctx, v) +} + +func (mes *MaintenanceEntrySelect) sqlScan(ctx context.Context, v any) error { + aggregation := make([]string, 0, len(mes.fns)) + for _, fn := range mes.fns { + aggregation = append(aggregation, fn(mes.sql)) + } + switch n := len(*mes.selector.flds); { + case n == 0 && len(aggregation) > 0: + mes.sql.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + mes.sql.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := mes.sql.Query() + if err := mes.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} diff --git a/backend/internal/data/ent/maintenanceentry_update.go b/backend/internal/data/ent/maintenanceentry_update.go new file mode 100644 index 0000000..af0aafd --- /dev/null +++ b/backend/internal/data/ent/maintenanceentry_update.go @@ -0,0 +1,594 @@ +// 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/google/uuid" + "github.com/hay-kot/homebox/backend/internal/data/ent/item" + "github.com/hay-kot/homebox/backend/internal/data/ent/maintenanceentry" + "github.com/hay-kot/homebox/backend/internal/data/ent/predicate" +) + +// MaintenanceEntryUpdate is the builder for updating MaintenanceEntry entities. +type MaintenanceEntryUpdate struct { + config + hooks []Hook + mutation *MaintenanceEntryMutation +} + +// Where appends a list predicates to the MaintenanceEntryUpdate builder. +func (meu *MaintenanceEntryUpdate) Where(ps ...predicate.MaintenanceEntry) *MaintenanceEntryUpdate { + meu.mutation.Where(ps...) + return meu +} + +// SetUpdatedAt sets the "updated_at" field. +func (meu *MaintenanceEntryUpdate) SetUpdatedAt(t time.Time) *MaintenanceEntryUpdate { + meu.mutation.SetUpdatedAt(t) + return meu +} + +// SetItemID sets the "item_id" field. +func (meu *MaintenanceEntryUpdate) SetItemID(u uuid.UUID) *MaintenanceEntryUpdate { + meu.mutation.SetItemID(u) + return meu +} + +// SetDate sets the "date" field. +func (meu *MaintenanceEntryUpdate) SetDate(t time.Time) *MaintenanceEntryUpdate { + meu.mutation.SetDate(t) + return meu +} + +// SetNillableDate sets the "date" field if the given value is not nil. +func (meu *MaintenanceEntryUpdate) SetNillableDate(t *time.Time) *MaintenanceEntryUpdate { + if t != nil { + meu.SetDate(*t) + } + return meu +} + +// SetName sets the "name" field. +func (meu *MaintenanceEntryUpdate) SetName(s string) *MaintenanceEntryUpdate { + meu.mutation.SetName(s) + return meu +} + +// SetDescription sets the "description" field. +func (meu *MaintenanceEntryUpdate) SetDescription(s string) *MaintenanceEntryUpdate { + meu.mutation.SetDescription(s) + return meu +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (meu *MaintenanceEntryUpdate) SetNillableDescription(s *string) *MaintenanceEntryUpdate { + if s != nil { + meu.SetDescription(*s) + } + return meu +} + +// ClearDescription clears the value of the "description" field. +func (meu *MaintenanceEntryUpdate) ClearDescription() *MaintenanceEntryUpdate { + meu.mutation.ClearDescription() + return meu +} + +// SetCost sets the "cost" field. +func (meu *MaintenanceEntryUpdate) SetCost(f float64) *MaintenanceEntryUpdate { + meu.mutation.ResetCost() + meu.mutation.SetCost(f) + return meu +} + +// SetNillableCost sets the "cost" field if the given value is not nil. +func (meu *MaintenanceEntryUpdate) SetNillableCost(f *float64) *MaintenanceEntryUpdate { + if f != nil { + meu.SetCost(*f) + } + return meu +} + +// AddCost adds f to the "cost" field. +func (meu *MaintenanceEntryUpdate) AddCost(f float64) *MaintenanceEntryUpdate { + meu.mutation.AddCost(f) + return meu +} + +// SetItem sets the "item" edge to the Item entity. +func (meu *MaintenanceEntryUpdate) SetItem(i *Item) *MaintenanceEntryUpdate { + return meu.SetItemID(i.ID) +} + +// Mutation returns the MaintenanceEntryMutation object of the builder. +func (meu *MaintenanceEntryUpdate) Mutation() *MaintenanceEntryMutation { + return meu.mutation +} + +// ClearItem clears the "item" edge to the Item entity. +func (meu *MaintenanceEntryUpdate) ClearItem() *MaintenanceEntryUpdate { + meu.mutation.ClearItem() + return meu +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (meu *MaintenanceEntryUpdate) Save(ctx context.Context) (int, error) { + var ( + err error + affected int + ) + meu.defaults() + if len(meu.hooks) == 0 { + if err = meu.check(); err != nil { + return 0, err + } + affected, err = meu.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*MaintenanceEntryMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = meu.check(); err != nil { + return 0, err + } + meu.mutation = mutation + affected, err = meu.sqlSave(ctx) + mutation.done = true + return affected, err + }) + for i := len(meu.hooks) - 1; i >= 0; i-- { + if meu.hooks[i] == nil { + return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = meu.hooks[i](mut) + } + if _, err := mut.Mutate(ctx, meu.mutation); err != nil { + return 0, err + } + } + return affected, err +} + +// SaveX is like Save, but panics if an error occurs. +func (meu *MaintenanceEntryUpdate) SaveX(ctx context.Context) int { + affected, err := meu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (meu *MaintenanceEntryUpdate) Exec(ctx context.Context) error { + _, err := meu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (meu *MaintenanceEntryUpdate) ExecX(ctx context.Context) { + if err := meu.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (meu *MaintenanceEntryUpdate) defaults() { + if _, ok := meu.mutation.UpdatedAt(); !ok { + v := maintenanceentry.UpdateDefaultUpdatedAt() + meu.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (meu *MaintenanceEntryUpdate) check() error { + if v, ok := meu.mutation.Name(); ok { + if err := maintenanceentry.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "MaintenanceEntry.name": %w`, err)} + } + } + if v, ok := meu.mutation.Description(); ok { + if err := maintenanceentry.DescriptionValidator(v); err != nil { + return &ValidationError{Name: "description", err: fmt.Errorf(`ent: validator failed for field "MaintenanceEntry.description": %w`, err)} + } + } + if _, ok := meu.mutation.ItemID(); meu.mutation.ItemCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "MaintenanceEntry.item"`) + } + return nil +} + +func (meu *MaintenanceEntryUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: maintenanceentry.Table, + Columns: maintenanceentry.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: maintenanceentry.FieldID, + }, + }, + } + if ps := meu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := meu.mutation.UpdatedAt(); ok { + _spec.SetField(maintenanceentry.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := meu.mutation.Date(); ok { + _spec.SetField(maintenanceentry.FieldDate, field.TypeTime, value) + } + if value, ok := meu.mutation.Name(); ok { + _spec.SetField(maintenanceentry.FieldName, field.TypeString, value) + } + if value, ok := meu.mutation.Description(); ok { + _spec.SetField(maintenanceentry.FieldDescription, field.TypeString, value) + } + if meu.mutation.DescriptionCleared() { + _spec.ClearField(maintenanceentry.FieldDescription, field.TypeString) + } + if value, ok := meu.mutation.Cost(); ok { + _spec.SetField(maintenanceentry.FieldCost, field.TypeFloat64, value) + } + if value, ok := meu.mutation.AddedCost(); ok { + _spec.AddField(maintenanceentry.FieldCost, field.TypeFloat64, value) + } + if meu.mutation.ItemCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: maintenanceentry.ItemTable, + Columns: []string{maintenanceentry.ItemColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: item.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := meu.mutation.ItemIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: maintenanceentry.ItemTable, + Columns: []string{maintenanceentry.ItemColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: item.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if n, err = sqlgraph.UpdateNodes(ctx, meu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{maintenanceentry.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + return n, nil +} + +// MaintenanceEntryUpdateOne is the builder for updating a single MaintenanceEntry entity. +type MaintenanceEntryUpdateOne struct { + config + fields []string + hooks []Hook + mutation *MaintenanceEntryMutation +} + +// SetUpdatedAt sets the "updated_at" field. +func (meuo *MaintenanceEntryUpdateOne) SetUpdatedAt(t time.Time) *MaintenanceEntryUpdateOne { + meuo.mutation.SetUpdatedAt(t) + return meuo +} + +// SetItemID sets the "item_id" field. +func (meuo *MaintenanceEntryUpdateOne) SetItemID(u uuid.UUID) *MaintenanceEntryUpdateOne { + meuo.mutation.SetItemID(u) + return meuo +} + +// SetDate sets the "date" field. +func (meuo *MaintenanceEntryUpdateOne) SetDate(t time.Time) *MaintenanceEntryUpdateOne { + meuo.mutation.SetDate(t) + return meuo +} + +// SetNillableDate sets the "date" field if the given value is not nil. +func (meuo *MaintenanceEntryUpdateOne) SetNillableDate(t *time.Time) *MaintenanceEntryUpdateOne { + if t != nil { + meuo.SetDate(*t) + } + return meuo +} + +// SetName sets the "name" field. +func (meuo *MaintenanceEntryUpdateOne) SetName(s string) *MaintenanceEntryUpdateOne { + meuo.mutation.SetName(s) + return meuo +} + +// SetDescription sets the "description" field. +func (meuo *MaintenanceEntryUpdateOne) SetDescription(s string) *MaintenanceEntryUpdateOne { + meuo.mutation.SetDescription(s) + return meuo +} + +// SetNillableDescription sets the "description" field if the given value is not nil. +func (meuo *MaintenanceEntryUpdateOne) SetNillableDescription(s *string) *MaintenanceEntryUpdateOne { + if s != nil { + meuo.SetDescription(*s) + } + return meuo +} + +// ClearDescription clears the value of the "description" field. +func (meuo *MaintenanceEntryUpdateOne) ClearDescription() *MaintenanceEntryUpdateOne { + meuo.mutation.ClearDescription() + return meuo +} + +// SetCost sets the "cost" field. +func (meuo *MaintenanceEntryUpdateOne) SetCost(f float64) *MaintenanceEntryUpdateOne { + meuo.mutation.ResetCost() + meuo.mutation.SetCost(f) + return meuo +} + +// SetNillableCost sets the "cost" field if the given value is not nil. +func (meuo *MaintenanceEntryUpdateOne) SetNillableCost(f *float64) *MaintenanceEntryUpdateOne { + if f != nil { + meuo.SetCost(*f) + } + return meuo +} + +// AddCost adds f to the "cost" field. +func (meuo *MaintenanceEntryUpdateOne) AddCost(f float64) *MaintenanceEntryUpdateOne { + meuo.mutation.AddCost(f) + return meuo +} + +// SetItem sets the "item" edge to the Item entity. +func (meuo *MaintenanceEntryUpdateOne) SetItem(i *Item) *MaintenanceEntryUpdateOne { + return meuo.SetItemID(i.ID) +} + +// Mutation returns the MaintenanceEntryMutation object of the builder. +func (meuo *MaintenanceEntryUpdateOne) Mutation() *MaintenanceEntryMutation { + return meuo.mutation +} + +// ClearItem clears the "item" edge to the Item entity. +func (meuo *MaintenanceEntryUpdateOne) ClearItem() *MaintenanceEntryUpdateOne { + meuo.mutation.ClearItem() + return meuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (meuo *MaintenanceEntryUpdateOne) Select(field string, fields ...string) *MaintenanceEntryUpdateOne { + meuo.fields = append([]string{field}, fields...) + return meuo +} + +// Save executes the query and returns the updated MaintenanceEntry entity. +func (meuo *MaintenanceEntryUpdateOne) Save(ctx context.Context) (*MaintenanceEntry, error) { + var ( + err error + node *MaintenanceEntry + ) + meuo.defaults() + if len(meuo.hooks) == 0 { + if err = meuo.check(); err != nil { + return nil, err + } + node, err = meuo.sqlSave(ctx) + } else { + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*MaintenanceEntryMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err = meuo.check(); err != nil { + return nil, err + } + meuo.mutation = mutation + node, err = meuo.sqlSave(ctx) + mutation.done = true + return node, err + }) + for i := len(meuo.hooks) - 1; i >= 0; i-- { + if meuo.hooks[i] == nil { + return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = meuo.hooks[i](mut) + } + v, err := mut.Mutate(ctx, meuo.mutation) + if err != nil { + return nil, err + } + nv, ok := v.(*MaintenanceEntry) + if !ok { + return nil, fmt.Errorf("unexpected node type %T returned from MaintenanceEntryMutation", v) + } + node = nv + } + return node, err +} + +// SaveX is like Save, but panics if an error occurs. +func (meuo *MaintenanceEntryUpdateOne) SaveX(ctx context.Context) *MaintenanceEntry { + node, err := meuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (meuo *MaintenanceEntryUpdateOne) Exec(ctx context.Context) error { + _, err := meuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (meuo *MaintenanceEntryUpdateOne) ExecX(ctx context.Context) { + if err := meuo.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (meuo *MaintenanceEntryUpdateOne) defaults() { + if _, ok := meuo.mutation.UpdatedAt(); !ok { + v := maintenanceentry.UpdateDefaultUpdatedAt() + meuo.mutation.SetUpdatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (meuo *MaintenanceEntryUpdateOne) check() error { + if v, ok := meuo.mutation.Name(); ok { + if err := maintenanceentry.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "MaintenanceEntry.name": %w`, err)} + } + } + if v, ok := meuo.mutation.Description(); ok { + if err := maintenanceentry.DescriptionValidator(v); err != nil { + return &ValidationError{Name: "description", err: fmt.Errorf(`ent: validator failed for field "MaintenanceEntry.description": %w`, err)} + } + } + if _, ok := meuo.mutation.ItemID(); meuo.mutation.ItemCleared() && !ok { + return errors.New(`ent: clearing a required unique edge "MaintenanceEntry.item"`) + } + return nil +} + +func (meuo *MaintenanceEntryUpdateOne) sqlSave(ctx context.Context) (_node *MaintenanceEntry, err error) { + _spec := &sqlgraph.UpdateSpec{ + Node: &sqlgraph.NodeSpec{ + Table: maintenanceentry.Table, + Columns: maintenanceentry.Columns, + ID: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: maintenanceentry.FieldID, + }, + }, + } + id, ok := meuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "MaintenanceEntry.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := meuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, maintenanceentry.FieldID) + for _, f := range fields { + if !maintenanceentry.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != maintenanceentry.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := meuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := meuo.mutation.UpdatedAt(); ok { + _spec.SetField(maintenanceentry.FieldUpdatedAt, field.TypeTime, value) + } + if value, ok := meuo.mutation.Date(); ok { + _spec.SetField(maintenanceentry.FieldDate, field.TypeTime, value) + } + if value, ok := meuo.mutation.Name(); ok { + _spec.SetField(maintenanceentry.FieldName, field.TypeString, value) + } + if value, ok := meuo.mutation.Description(); ok { + _spec.SetField(maintenanceentry.FieldDescription, field.TypeString, value) + } + if meuo.mutation.DescriptionCleared() { + _spec.ClearField(maintenanceentry.FieldDescription, field.TypeString) + } + if value, ok := meuo.mutation.Cost(); ok { + _spec.SetField(maintenanceentry.FieldCost, field.TypeFloat64, value) + } + if value, ok := meuo.mutation.AddedCost(); ok { + _spec.AddField(maintenanceentry.FieldCost, field.TypeFloat64, value) + } + if meuo.mutation.ItemCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: maintenanceentry.ItemTable, + Columns: []string{maintenanceentry.ItemColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: item.FieldID, + }, + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := meuo.mutation.ItemIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: maintenanceentry.ItemTable, + Columns: []string{maintenanceentry.ItemColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: &sqlgraph.FieldSpec{ + Type: field.TypeUUID, + Column: item.FieldID, + }, + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &MaintenanceEntry{config: meuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, meuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{maintenanceentry.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + return _node, nil +} diff --git a/backend/internal/data/ent/migrate/schema.go b/backend/internal/data/ent/migrate/schema.go index fc2a146..c700d34 100644 --- a/backend/internal/data/ent/migrate/schema.go +++ b/backend/internal/data/ent/migrate/schema.go @@ -53,7 +53,7 @@ var ( Symbol: "auth_roles_auth_tokens_roles", Columns: []*schema.Column{AuthRolesColumns[2]}, RefColumns: []*schema.Column{AuthTokensColumns[0]}, - OnDelete: schema.SetNull, + OnDelete: schema.Cascade, }, }, } @@ -318,6 +318,31 @@ var ( }, }, } + // MaintenanceEntriesColumns holds the columns for the "maintenance_entries" table. + MaintenanceEntriesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "date", Type: field.TypeTime}, + {Name: "name", Type: field.TypeString, Size: 255}, + {Name: "description", Type: field.TypeString, Nullable: true, Size: 2500}, + {Name: "cost", Type: field.TypeFloat64, Default: 0}, + {Name: "item_id", Type: field.TypeUUID}, + } + // MaintenanceEntriesTable holds the schema information for the "maintenance_entries" table. + MaintenanceEntriesTable = &schema.Table{ + Name: "maintenance_entries", + Columns: MaintenanceEntriesColumns, + PrimaryKey: []*schema.Column{MaintenanceEntriesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "maintenance_entries_items_maintenance_entries", + Columns: []*schema.Column{MaintenanceEntriesColumns[7]}, + RefColumns: []*schema.Column{ItemsColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + } // UsersColumns holds the columns for the "users" table. UsersColumns = []*schema.Column{ {Name: "id", Type: field.TypeUUID}, @@ -383,6 +408,7 @@ var ( ItemFieldsTable, LabelsTable, LocationsTable, + MaintenanceEntriesTable, UsersTable, LabelItemsTable, } @@ -402,6 +428,7 @@ func init() { LabelsTable.ForeignKeys[0].RefTable = GroupsTable LocationsTable.ForeignKeys[0].RefTable = GroupsTable LocationsTable.ForeignKeys[1].RefTable = LocationsTable + MaintenanceEntriesTable.ForeignKeys[0].RefTable = ItemsTable UsersTable.ForeignKeys[0].RefTable = GroupsTable LabelItemsTable.ForeignKeys[0].RefTable = LabelsTable LabelItemsTable.ForeignKeys[1].RefTable = ItemsTable diff --git a/backend/internal/data/ent/mutation.go b/backend/internal/data/ent/mutation.go index 60f49f7..da57310 100644 --- a/backend/internal/data/ent/mutation.go +++ b/backend/internal/data/ent/mutation.go @@ -20,6 +20,7 @@ import ( "github.com/hay-kot/homebox/backend/internal/data/ent/itemfield" "github.com/hay-kot/homebox/backend/internal/data/ent/label" "github.com/hay-kot/homebox/backend/internal/data/ent/location" + "github.com/hay-kot/homebox/backend/internal/data/ent/maintenanceentry" "github.com/hay-kot/homebox/backend/internal/data/ent/predicate" "github.com/hay-kot/homebox/backend/internal/data/ent/user" @@ -45,6 +46,7 @@ const ( TypeItemField = "ItemField" TypeLabel = "Label" TypeLocation = "Location" + TypeMaintenanceEntry = "MaintenanceEntry" TypeUser = "User" ) @@ -3839,58 +3841,61 @@ func (m *GroupInvitationTokenMutation) ResetEdge(name string) error { // ItemMutation represents an operation that mutates the Item nodes in the graph. type ItemMutation struct { config - op Op - typ string - id *uuid.UUID - created_at *time.Time - updated_at *time.Time - name *string - description *string - import_ref *string - notes *string - quantity *int - addquantity *int - insured *bool - archived *bool - asset_id *int - addasset_id *int - serial_number *string - model_number *string - manufacturer *string - lifetime_warranty *bool - warranty_expires *time.Time - warranty_details *string - purchase_time *time.Time - purchase_from *string - purchase_price *float64 - addpurchase_price *float64 - sold_time *time.Time - sold_to *string - sold_price *float64 - addsold_price *float64 - sold_notes *string - clearedFields map[string]struct{} - parent *uuid.UUID - clearedparent bool - children map[uuid.UUID]struct{} - removedchildren map[uuid.UUID]struct{} - clearedchildren bool - group *uuid.UUID - clearedgroup bool - label map[uuid.UUID]struct{} - removedlabel map[uuid.UUID]struct{} - clearedlabel bool - location *uuid.UUID - clearedlocation bool - fields map[uuid.UUID]struct{} - removedfields map[uuid.UUID]struct{} - clearedfields bool - attachments map[uuid.UUID]struct{} - removedattachments map[uuid.UUID]struct{} - clearedattachments bool - done bool - oldValue func(context.Context) (*Item, error) - predicates []predicate.Item + op Op + typ string + id *uuid.UUID + created_at *time.Time + updated_at *time.Time + name *string + description *string + import_ref *string + notes *string + quantity *int + addquantity *int + insured *bool + archived *bool + asset_id *int + addasset_id *int + serial_number *string + model_number *string + manufacturer *string + lifetime_warranty *bool + warranty_expires *time.Time + warranty_details *string + purchase_time *time.Time + purchase_from *string + purchase_price *float64 + addpurchase_price *float64 + sold_time *time.Time + sold_to *string + sold_price *float64 + addsold_price *float64 + sold_notes *string + clearedFields map[string]struct{} + parent *uuid.UUID + clearedparent bool + children map[uuid.UUID]struct{} + removedchildren map[uuid.UUID]struct{} + clearedchildren bool + group *uuid.UUID + clearedgroup bool + label map[uuid.UUID]struct{} + removedlabel map[uuid.UUID]struct{} + clearedlabel bool + location *uuid.UUID + clearedlocation bool + fields map[uuid.UUID]struct{} + removedfields map[uuid.UUID]struct{} + clearedfields bool + maintenance_entries map[uuid.UUID]struct{} + removedmaintenance_entries map[uuid.UUID]struct{} + clearedmaintenance_entries bool + attachments map[uuid.UUID]struct{} + removedattachments map[uuid.UUID]struct{} + clearedattachments bool + done bool + oldValue func(context.Context) (*Item, error) + predicates []predicate.Item } var _ ent.Mutation = (*ItemMutation)(nil) @@ -5353,6 +5358,60 @@ func (m *ItemMutation) ResetFields() { m.removedfields = nil } +// AddMaintenanceEntryIDs adds the "maintenance_entries" edge to the MaintenanceEntry entity by ids. +func (m *ItemMutation) AddMaintenanceEntryIDs(ids ...uuid.UUID) { + if m.maintenance_entries == nil { + m.maintenance_entries = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.maintenance_entries[ids[i]] = struct{}{} + } +} + +// ClearMaintenanceEntries clears the "maintenance_entries" edge to the MaintenanceEntry entity. +func (m *ItemMutation) ClearMaintenanceEntries() { + m.clearedmaintenance_entries = true +} + +// MaintenanceEntriesCleared reports if the "maintenance_entries" edge to the MaintenanceEntry entity was cleared. +func (m *ItemMutation) MaintenanceEntriesCleared() bool { + return m.clearedmaintenance_entries +} + +// RemoveMaintenanceEntryIDs removes the "maintenance_entries" edge to the MaintenanceEntry entity by IDs. +func (m *ItemMutation) RemoveMaintenanceEntryIDs(ids ...uuid.UUID) { + if m.removedmaintenance_entries == nil { + m.removedmaintenance_entries = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.maintenance_entries, ids[i]) + m.removedmaintenance_entries[ids[i]] = struct{}{} + } +} + +// RemovedMaintenanceEntries returns the removed IDs of the "maintenance_entries" edge to the MaintenanceEntry entity. +func (m *ItemMutation) RemovedMaintenanceEntriesIDs() (ids []uuid.UUID) { + for id := range m.removedmaintenance_entries { + ids = append(ids, id) + } + return +} + +// MaintenanceEntriesIDs returns the "maintenance_entries" edge IDs in the mutation. +func (m *ItemMutation) MaintenanceEntriesIDs() (ids []uuid.UUID) { + for id := range m.maintenance_entries { + ids = append(ids, id) + } + return +} + +// ResetMaintenanceEntries resets all changes to the "maintenance_entries" edge. +func (m *ItemMutation) ResetMaintenanceEntries() { + m.maintenance_entries = nil + m.clearedmaintenance_entries = false + m.removedmaintenance_entries = nil +} + // AddAttachmentIDs adds the "attachments" edge to the Attachment entity by ids. func (m *ItemMutation) AddAttachmentIDs(ids ...uuid.UUID) { if m.attachments == nil { @@ -6031,7 +6090,7 @@ func (m *ItemMutation) ResetField(name string) error { // AddedEdges returns all edge names that were set/added in this mutation. func (m *ItemMutation) AddedEdges() []string { - edges := make([]string, 0, 7) + edges := make([]string, 0, 8) if m.parent != nil { edges = append(edges, item.EdgeParent) } @@ -6050,6 +6109,9 @@ func (m *ItemMutation) AddedEdges() []string { if m.fields != nil { edges = append(edges, item.EdgeFields) } + if m.maintenance_entries != nil { + edges = append(edges, item.EdgeMaintenanceEntries) + } if m.attachments != nil { edges = append(edges, item.EdgeAttachments) } @@ -6090,6 +6152,12 @@ func (m *ItemMutation) AddedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case item.EdgeMaintenanceEntries: + ids := make([]ent.Value, 0, len(m.maintenance_entries)) + for id := range m.maintenance_entries { + ids = append(ids, id) + } + return ids case item.EdgeAttachments: ids := make([]ent.Value, 0, len(m.attachments)) for id := range m.attachments { @@ -6102,7 +6170,7 @@ func (m *ItemMutation) AddedIDs(name string) []ent.Value { // RemovedEdges returns all edge names that were removed in this mutation. func (m *ItemMutation) RemovedEdges() []string { - edges := make([]string, 0, 7) + edges := make([]string, 0, 8) if m.removedchildren != nil { edges = append(edges, item.EdgeChildren) } @@ -6112,6 +6180,9 @@ func (m *ItemMutation) RemovedEdges() []string { if m.removedfields != nil { edges = append(edges, item.EdgeFields) } + if m.removedmaintenance_entries != nil { + edges = append(edges, item.EdgeMaintenanceEntries) + } if m.removedattachments != nil { edges = append(edges, item.EdgeAttachments) } @@ -6140,6 +6211,12 @@ func (m *ItemMutation) RemovedIDs(name string) []ent.Value { ids = append(ids, id) } return ids + case item.EdgeMaintenanceEntries: + ids := make([]ent.Value, 0, len(m.removedmaintenance_entries)) + for id := range m.removedmaintenance_entries { + ids = append(ids, id) + } + return ids case item.EdgeAttachments: ids := make([]ent.Value, 0, len(m.removedattachments)) for id := range m.removedattachments { @@ -6152,7 +6229,7 @@ func (m *ItemMutation) RemovedIDs(name string) []ent.Value { // ClearedEdges returns all edge names that were cleared in this mutation. func (m *ItemMutation) ClearedEdges() []string { - edges := make([]string, 0, 7) + edges := make([]string, 0, 8) if m.clearedparent { edges = append(edges, item.EdgeParent) } @@ -6171,6 +6248,9 @@ func (m *ItemMutation) ClearedEdges() []string { if m.clearedfields { edges = append(edges, item.EdgeFields) } + if m.clearedmaintenance_entries { + edges = append(edges, item.EdgeMaintenanceEntries) + } if m.clearedattachments { edges = append(edges, item.EdgeAttachments) } @@ -6193,6 +6273,8 @@ func (m *ItemMutation) EdgeCleared(name string) bool { return m.clearedlocation case item.EdgeFields: return m.clearedfields + case item.EdgeMaintenanceEntries: + return m.clearedmaintenance_entries case item.EdgeAttachments: return m.clearedattachments } @@ -6238,6 +6320,9 @@ func (m *ItemMutation) ResetEdge(name string) error { case item.EdgeFields: m.ResetFields() return nil + case item.EdgeMaintenanceEntries: + m.ResetMaintenanceEntries() + return nil case item.EdgeAttachments: m.ResetAttachments() return nil @@ -8679,6 +8764,758 @@ func (m *LocationMutation) ResetEdge(name string) error { return fmt.Errorf("unknown Location edge %s", name) } +// MaintenanceEntryMutation represents an operation that mutates the MaintenanceEntry nodes in the graph. +type MaintenanceEntryMutation struct { + config + op Op + typ string + id *uuid.UUID + created_at *time.Time + updated_at *time.Time + date *time.Time + name *string + description *string + cost *float64 + addcost *float64 + clearedFields map[string]struct{} + item *uuid.UUID + cleareditem bool + done bool + oldValue func(context.Context) (*MaintenanceEntry, error) + predicates []predicate.MaintenanceEntry +} + +var _ ent.Mutation = (*MaintenanceEntryMutation)(nil) + +// maintenanceentryOption allows management of the mutation configuration using functional options. +type maintenanceentryOption func(*MaintenanceEntryMutation) + +// newMaintenanceEntryMutation creates new mutation for the MaintenanceEntry entity. +func newMaintenanceEntryMutation(c config, op Op, opts ...maintenanceentryOption) *MaintenanceEntryMutation { + m := &MaintenanceEntryMutation{ + config: c, + op: op, + typ: TypeMaintenanceEntry, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withMaintenanceEntryID sets the ID field of the mutation. +func withMaintenanceEntryID(id uuid.UUID) maintenanceentryOption { + return func(m *MaintenanceEntryMutation) { + var ( + err error + once sync.Once + value *MaintenanceEntry + ) + m.oldValue = func(ctx context.Context) (*MaintenanceEntry, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().MaintenanceEntry.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withMaintenanceEntry sets the old MaintenanceEntry of the mutation. +func withMaintenanceEntry(node *MaintenanceEntry) maintenanceentryOption { + return func(m *MaintenanceEntryMutation) { + m.oldValue = func(context.Context) (*MaintenanceEntry, 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 MaintenanceEntryMutation) 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 MaintenanceEntryMutation) 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 MaintenanceEntry entities. +func (m *MaintenanceEntryMutation) 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 *MaintenanceEntryMutation) 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 *MaintenanceEntryMutation) 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().MaintenanceEntry.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 *MaintenanceEntryMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *MaintenanceEntryMutation) 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 MaintenanceEntry entity. +// If the MaintenanceEntry 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 *MaintenanceEntryMutation) 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 *MaintenanceEntryMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *MaintenanceEntryMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *MaintenanceEntryMutation) 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 MaintenanceEntry entity. +// If the MaintenanceEntry 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 *MaintenanceEntryMutation) 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 *MaintenanceEntryMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// SetItemID sets the "item_id" field. +func (m *MaintenanceEntryMutation) SetItemID(u uuid.UUID) { + m.item = &u +} + +// ItemID returns the value of the "item_id" field in the mutation. +func (m *MaintenanceEntryMutation) ItemID() (r uuid.UUID, exists bool) { + v := m.item + if v == nil { + return + } + return *v, true +} + +// OldItemID returns the old "item_id" field's value of the MaintenanceEntry entity. +// If the MaintenanceEntry 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 *MaintenanceEntryMutation) OldItemID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldItemID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldItemID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldItemID: %w", err) + } + return oldValue.ItemID, nil +} + +// ResetItemID resets all changes to the "item_id" field. +func (m *MaintenanceEntryMutation) ResetItemID() { + m.item = nil +} + +// SetDate sets the "date" field. +func (m *MaintenanceEntryMutation) SetDate(t time.Time) { + m.date = &t +} + +// Date returns the value of the "date" field in the mutation. +func (m *MaintenanceEntryMutation) Date() (r time.Time, exists bool) { + v := m.date + if v == nil { + return + } + return *v, true +} + +// OldDate returns the old "date" field's value of the MaintenanceEntry entity. +// If the MaintenanceEntry 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 *MaintenanceEntryMutation) OldDate(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDate is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDate requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDate: %w", err) + } + return oldValue.Date, nil +} + +// ResetDate resets all changes to the "date" field. +func (m *MaintenanceEntryMutation) ResetDate() { + m.date = nil +} + +// SetName sets the "name" field. +func (m *MaintenanceEntryMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *MaintenanceEntryMutation) 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 MaintenanceEntry entity. +// If the MaintenanceEntry 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 *MaintenanceEntryMutation) 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 *MaintenanceEntryMutation) ResetName() { + m.name = nil +} + +// SetDescription sets the "description" field. +func (m *MaintenanceEntryMutation) SetDescription(s string) { + m.description = &s +} + +// Description returns the value of the "description" field in the mutation. +func (m *MaintenanceEntryMutation) Description() (r string, exists bool) { + v := m.description + if v == nil { + return + } + return *v, true +} + +// OldDescription returns the old "description" field's value of the MaintenanceEntry entity. +// If the MaintenanceEntry 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 *MaintenanceEntryMutation) OldDescription(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDescription is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDescription requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDescription: %w", err) + } + return oldValue.Description, nil +} + +// ClearDescription clears the value of the "description" field. +func (m *MaintenanceEntryMutation) ClearDescription() { + m.description = nil + m.clearedFields[maintenanceentry.FieldDescription] = struct{}{} +} + +// DescriptionCleared returns if the "description" field was cleared in this mutation. +func (m *MaintenanceEntryMutation) DescriptionCleared() bool { + _, ok := m.clearedFields[maintenanceentry.FieldDescription] + return ok +} + +// ResetDescription resets all changes to the "description" field. +func (m *MaintenanceEntryMutation) ResetDescription() { + m.description = nil + delete(m.clearedFields, maintenanceentry.FieldDescription) +} + +// SetCost sets the "cost" field. +func (m *MaintenanceEntryMutation) SetCost(f float64) { + m.cost = &f + m.addcost = nil +} + +// Cost returns the value of the "cost" field in the mutation. +func (m *MaintenanceEntryMutation) Cost() (r float64, exists bool) { + v := m.cost + if v == nil { + return + } + return *v, true +} + +// OldCost returns the old "cost" field's value of the MaintenanceEntry entity. +// If the MaintenanceEntry 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 *MaintenanceEntryMutation) OldCost(ctx context.Context) (v float64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCost is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCost requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCost: %w", err) + } + return oldValue.Cost, nil +} + +// AddCost adds f to the "cost" field. +func (m *MaintenanceEntryMutation) AddCost(f float64) { + if m.addcost != nil { + *m.addcost += f + } else { + m.addcost = &f + } +} + +// AddedCost returns the value that was added to the "cost" field in this mutation. +func (m *MaintenanceEntryMutation) AddedCost() (r float64, exists bool) { + v := m.addcost + if v == nil { + return + } + return *v, true +} + +// ResetCost resets all changes to the "cost" field. +func (m *MaintenanceEntryMutation) ResetCost() { + m.cost = nil + m.addcost = nil +} + +// ClearItem clears the "item" edge to the Item entity. +func (m *MaintenanceEntryMutation) ClearItem() { + m.cleareditem = true +} + +// ItemCleared reports if the "item" edge to the Item entity was cleared. +func (m *MaintenanceEntryMutation) ItemCleared() bool { + return m.cleareditem +} + +// ItemIDs returns the "item" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// ItemID instead. It exists only for internal usage by the builders. +func (m *MaintenanceEntryMutation) ItemIDs() (ids []uuid.UUID) { + if id := m.item; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetItem resets all changes to the "item" edge. +func (m *MaintenanceEntryMutation) ResetItem() { + m.item = nil + m.cleareditem = false +} + +// Where appends a list predicates to the MaintenanceEntryMutation builder. +func (m *MaintenanceEntryMutation) Where(ps ...predicate.MaintenanceEntry) { + m.predicates = append(m.predicates, ps...) +} + +// Op returns the operation name. +func (m *MaintenanceEntryMutation) Op() Op { + return m.op +} + +// Type returns the node type of this mutation (MaintenanceEntry). +func (m *MaintenanceEntryMutation) 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 *MaintenanceEntryMutation) Fields() []string { + fields := make([]string, 0, 7) + if m.created_at != nil { + fields = append(fields, maintenanceentry.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, maintenanceentry.FieldUpdatedAt) + } + if m.item != nil { + fields = append(fields, maintenanceentry.FieldItemID) + } + if m.date != nil { + fields = append(fields, maintenanceentry.FieldDate) + } + if m.name != nil { + fields = append(fields, maintenanceentry.FieldName) + } + if m.description != nil { + fields = append(fields, maintenanceentry.FieldDescription) + } + if m.cost != nil { + fields = append(fields, maintenanceentry.FieldCost) + } + 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 *MaintenanceEntryMutation) Field(name string) (ent.Value, bool) { + switch name { + case maintenanceentry.FieldCreatedAt: + return m.CreatedAt() + case maintenanceentry.FieldUpdatedAt: + return m.UpdatedAt() + case maintenanceentry.FieldItemID: + return m.ItemID() + case maintenanceentry.FieldDate: + return m.Date() + case maintenanceentry.FieldName: + return m.Name() + case maintenanceentry.FieldDescription: + return m.Description() + case maintenanceentry.FieldCost: + return m.Cost() + } + 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 *MaintenanceEntryMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case maintenanceentry.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case maintenanceentry.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + case maintenanceentry.FieldItemID: + return m.OldItemID(ctx) + case maintenanceentry.FieldDate: + return m.OldDate(ctx) + case maintenanceentry.FieldName: + return m.OldName(ctx) + case maintenanceentry.FieldDescription: + return m.OldDescription(ctx) + case maintenanceentry.FieldCost: + return m.OldCost(ctx) + } + return nil, fmt.Errorf("unknown MaintenanceEntry 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 *MaintenanceEntryMutation) SetField(name string, value ent.Value) error { + switch name { + case maintenanceentry.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 maintenanceentry.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 maintenanceentry.FieldItemID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetItemID(v) + return nil + case maintenanceentry.FieldDate: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDate(v) + return nil + case maintenanceentry.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case maintenanceentry.FieldDescription: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDescription(v) + return nil + case maintenanceentry.FieldCost: + v, ok := value.(float64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCost(v) + return nil + } + return fmt.Errorf("unknown MaintenanceEntry field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *MaintenanceEntryMutation) AddedFields() []string { + var fields []string + if m.addcost != nil { + fields = append(fields, maintenanceentry.FieldCost) + } + return fields +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *MaintenanceEntryMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case maintenanceentry.FieldCost: + return m.AddedCost() + } + 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 *MaintenanceEntryMutation) AddField(name string, value ent.Value) error { + switch name { + case maintenanceentry.FieldCost: + v, ok := value.(float64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddCost(v) + return nil + } + return fmt.Errorf("unknown MaintenanceEntry numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *MaintenanceEntryMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(maintenanceentry.FieldDescription) { + fields = append(fields, maintenanceentry.FieldDescription) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *MaintenanceEntryMutation) 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 *MaintenanceEntryMutation) ClearField(name string) error { + switch name { + case maintenanceentry.FieldDescription: + m.ClearDescription() + return nil + } + return fmt.Errorf("unknown MaintenanceEntry 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 *MaintenanceEntryMutation) ResetField(name string) error { + switch name { + case maintenanceentry.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case maintenanceentry.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + case maintenanceentry.FieldItemID: + m.ResetItemID() + return nil + case maintenanceentry.FieldDate: + m.ResetDate() + return nil + case maintenanceentry.FieldName: + m.ResetName() + return nil + case maintenanceentry.FieldDescription: + m.ResetDescription() + return nil + case maintenanceentry.FieldCost: + m.ResetCost() + return nil + } + return fmt.Errorf("unknown MaintenanceEntry field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *MaintenanceEntryMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.item != nil { + edges = append(edges, maintenanceentry.EdgeItem) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *MaintenanceEntryMutation) AddedIDs(name string) []ent.Value { + switch name { + case maintenanceentry.EdgeItem: + if id := m.item; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *MaintenanceEntryMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *MaintenanceEntryMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *MaintenanceEntryMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.cleareditem { + edges = append(edges, maintenanceentry.EdgeItem) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *MaintenanceEntryMutation) EdgeCleared(name string) bool { + switch name { + case maintenanceentry.EdgeItem: + return m.cleareditem + } + 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 *MaintenanceEntryMutation) ClearEdge(name string) error { + switch name { + case maintenanceentry.EdgeItem: + m.ClearItem() + return nil + } + return fmt.Errorf("unknown MaintenanceEntry 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 *MaintenanceEntryMutation) ResetEdge(name string) error { + switch name { + case maintenanceentry.EdgeItem: + m.ResetItem() + return nil + } + return fmt.Errorf("unknown MaintenanceEntry edge %s", name) +} + // UserMutation represents an operation that mutates the User nodes in the graph. type UserMutation struct { config diff --git a/backend/internal/data/ent/predicate/predicate.go b/backend/internal/data/ent/predicate/predicate.go index e801e9b..b1fbe67 100644 --- a/backend/internal/data/ent/predicate/predicate.go +++ b/backend/internal/data/ent/predicate/predicate.go @@ -36,5 +36,8 @@ type Label func(*sql.Selector) // Location is the predicate function for location builders. type Location func(*sql.Selector) +// MaintenanceEntry is the predicate function for maintenanceentry builders. +type MaintenanceEntry func(*sql.Selector) + // User is the predicate function for user builders. type User func(*sql.Selector) diff --git a/backend/internal/data/ent/runtime.go b/backend/internal/data/ent/runtime.go index 42eabcc..4ce9d2c 100644 --- a/backend/internal/data/ent/runtime.go +++ b/backend/internal/data/ent/runtime.go @@ -15,6 +15,7 @@ import ( "github.com/hay-kot/homebox/backend/internal/data/ent/itemfield" "github.com/hay-kot/homebox/backend/internal/data/ent/label" "github.com/hay-kot/homebox/backend/internal/data/ent/location" + "github.com/hay-kot/homebox/backend/internal/data/ent/maintenanceentry" "github.com/hay-kot/homebox/backend/internal/data/ent/schema" "github.com/hay-kot/homebox/backend/internal/data/ent/user" ) @@ -430,6 +431,55 @@ func init() { locationDescID := locationMixinFields0[0].Descriptor() // location.DefaultID holds the default value on creation for the id field. location.DefaultID = locationDescID.Default.(func() uuid.UUID) + maintenanceentryMixin := schema.MaintenanceEntry{}.Mixin() + maintenanceentryMixinFields0 := maintenanceentryMixin[0].Fields() + _ = maintenanceentryMixinFields0 + maintenanceentryFields := schema.MaintenanceEntry{}.Fields() + _ = maintenanceentryFields + // maintenanceentryDescCreatedAt is the schema descriptor for created_at field. + maintenanceentryDescCreatedAt := maintenanceentryMixinFields0[1].Descriptor() + // maintenanceentry.DefaultCreatedAt holds the default value on creation for the created_at field. + maintenanceentry.DefaultCreatedAt = maintenanceentryDescCreatedAt.Default.(func() time.Time) + // maintenanceentryDescUpdatedAt is the schema descriptor for updated_at field. + maintenanceentryDescUpdatedAt := maintenanceentryMixinFields0[2].Descriptor() + // maintenanceentry.DefaultUpdatedAt holds the default value on creation for the updated_at field. + maintenanceentry.DefaultUpdatedAt = maintenanceentryDescUpdatedAt.Default.(func() time.Time) + // maintenanceentry.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. + maintenanceentry.UpdateDefaultUpdatedAt = maintenanceentryDescUpdatedAt.UpdateDefault.(func() time.Time) + // maintenanceentryDescDate is the schema descriptor for date field. + maintenanceentryDescDate := maintenanceentryFields[1].Descriptor() + // maintenanceentry.DefaultDate holds the default value on creation for the date field. + maintenanceentry.DefaultDate = maintenanceentryDescDate.Default.(func() time.Time) + // maintenanceentryDescName is the schema descriptor for name field. + maintenanceentryDescName := maintenanceentryFields[2].Descriptor() + // maintenanceentry.NameValidator is a validator for the "name" field. It is called by the builders before save. + maintenanceentry.NameValidator = func() func(string) error { + validators := maintenanceentryDescName.Validators + fns := [...]func(string) error{ + validators[0].(func(string) error), + validators[1].(func(string) error), + } + return func(name string) error { + for _, fn := range fns { + if err := fn(name); err != nil { + return err + } + } + return nil + } + }() + // maintenanceentryDescDescription is the schema descriptor for description field. + maintenanceentryDescDescription := maintenanceentryFields[3].Descriptor() + // maintenanceentry.DescriptionValidator is a validator for the "description" field. It is called by the builders before save. + maintenanceentry.DescriptionValidator = maintenanceentryDescDescription.Validators[0].(func(string) error) + // maintenanceentryDescCost is the schema descriptor for cost field. + maintenanceentryDescCost := maintenanceentryFields[4].Descriptor() + // maintenanceentry.DefaultCost holds the default value on creation for the cost field. + maintenanceentry.DefaultCost = maintenanceentryDescCost.Default.(float64) + // maintenanceentryDescID is the schema descriptor for id field. + maintenanceentryDescID := maintenanceentryMixinFields0[0].Descriptor() + // maintenanceentry.DefaultID holds the default value on creation for the id field. + maintenanceentry.DefaultID = maintenanceentryDescID.Default.(func() uuid.UUID) userMixin := schema.User{}.Mixin() userMixinFields0 := userMixin[0].Fields() _ = userMixinFields0 diff --git a/backend/internal/data/ent/schema/auth_tokens.go b/backend/internal/data/ent/schema/auth_tokens.go index e29b79a..71b22d7 100644 --- a/backend/internal/data/ent/schema/auth_tokens.go +++ b/backend/internal/data/ent/schema/auth_tokens.go @@ -4,6 +4,7 @@ import ( "time" "entgo.io/ent" + "entgo.io/ent/dialect/entsql" "entgo.io/ent/schema/edge" "entgo.io/ent/schema/field" "entgo.io/ent/schema/index" @@ -38,7 +39,10 @@ func (AuthTokens) Edges() []ent.Edge { Ref("auth_tokens"). Unique(), edge.To("roles", AuthRoles.Type). - Unique(), + Unique(). + Annotations(entsql.Annotation{ + OnDelete: entsql.Cascade, + }), } } diff --git a/backend/internal/data/ent/schema/item.go b/backend/internal/data/ent/schema/item.go index 388566d..5180f27 100644 --- a/backend/internal/data/ent/schema/item.go +++ b/backend/internal/data/ent/schema/item.go @@ -116,6 +116,10 @@ func (Item) Edges() []ent.Edge { Annotations(entsql.Annotation{ OnDelete: entsql.Cascade, }), + edge.To("maintenance_entries", MaintenanceEntry.Type). + Annotations(entsql.Annotation{ + OnDelete: entsql.Cascade, + }), edge.To("attachments", Attachment.Type). Annotations(entsql.Annotation{ OnDelete: entsql.Cascade, diff --git a/backend/internal/data/ent/schema/maintenance_entry.go b/backend/internal/data/ent/schema/maintenance_entry.go new file mode 100644 index 0000000..7fd9643 --- /dev/null +++ b/backend/internal/data/ent/schema/maintenance_entry.go @@ -0,0 +1,48 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "github.com/google/uuid" + "github.com/hay-kot/homebox/backend/internal/data/ent/schema/mixins" +) + +type MaintenanceEntry struct { + ent.Schema +} + +func (MaintenanceEntry) Mixin() []ent.Mixin { + return []ent.Mixin{ + mixins.BaseMixin{}, + } +} + +func (MaintenanceEntry) Fields() []ent.Field { + return []ent.Field{ + field.UUID("item_id", uuid.UUID{}), + field.Time("date"). + Default(time.Now), + field.String("name"). + MaxLen(255). + NotEmpty(), + field.String("description"). + MaxLen(2500). + Optional(), + field.Float("cost"). + Default(0.0), + } +} + +// Edges of the ItemField. +func (MaintenanceEntry) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("item", Item.Type). + Field("item_id"). + Ref("maintenance_entries"). + Required(). + Unique(), + } +} diff --git a/backend/internal/data/ent/tx.go b/backend/internal/data/ent/tx.go index 810c2cf..0703ce5 100644 --- a/backend/internal/data/ent/tx.go +++ b/backend/internal/data/ent/tx.go @@ -32,6 +32,8 @@ type Tx struct { Label *LabelClient // Location is the client for interacting with the Location builders. Location *LocationClient + // MaintenanceEntry is the client for interacting with the MaintenanceEntry builders. + MaintenanceEntry *MaintenanceEntryClient // User is the client for interacting with the User builders. User *UserClient @@ -175,6 +177,7 @@ func (tx *Tx) init() { tx.ItemField = NewItemFieldClient(tx.config) tx.Label = NewLabelClient(tx.config) tx.Location = NewLocationClient(tx.config) + tx.MaintenanceEntry = NewMaintenanceEntryClient(tx.config) tx.User = NewUserClient(tx.config) } diff --git a/backend/internal/data/migrations/migrations.go b/backend/internal/data/migrations/migrations.go index 5fcb8e3..fba84c5 100644 --- a/backend/internal/data/migrations/migrations.go +++ b/backend/internal/data/migrations/migrations.go @@ -6,7 +6,7 @@ import ( "path/filepath" ) -// go:embed all:migrations +//go:embed all:migrations var Files embed.FS // Write writes the embedded migrations to a temporary directory. @@ -18,7 +18,7 @@ func Write(temp string) error { return err } - fsDir, err := Files.ReadDir(".") + fsDir, err := Files.ReadDir("migrations") if err != nil { return err } diff --git a/backend/internal/data/migrations/migrations/20221205230404_drop_document_tokens.sql b/backend/internal/data/migrations/migrations/20221205230404_drop_document_tokens.sql new file mode 100644 index 0000000..e130abe --- /dev/null +++ b/backend/internal/data/migrations/migrations/20221205230404_drop_document_tokens.sql @@ -0,0 +1,5 @@ +-- disable the enforcement of foreign-keys constraints +PRAGMA foreign_keys = off; +DROP TABLE `document_tokens`; +-- enable back the enforcement of foreign-keys constraints +PRAGMA foreign_keys = on; \ No newline at end of file diff --git a/backend/internal/data/migrations/migrations/20221205234214_add_maintenance_entries.sql b/backend/internal/data/migrations/migrations/20221205234214_add_maintenance_entries.sql new file mode 100644 index 0000000..2491ec4 --- /dev/null +++ b/backend/internal/data/migrations/migrations/20221205234214_add_maintenance_entries.sql @@ -0,0 +1,2 @@ +-- create "maintenance_entries" table +CREATE TABLE `maintenance_entries` (`id` uuid NOT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, `date` datetime NOT NULL, `name` text NOT NULL, `description` text NULL, `cost` real NOT NULL DEFAULT 0, `item_id` uuid NOT NULL, PRIMARY KEY (`id`), CONSTRAINT `maintenance_entries_items_maintenance_entries` FOREIGN KEY (`item_id`) REFERENCES `items` (`id`) ON DELETE CASCADE); diff --git a/backend/internal/data/migrations/migrations/20221205234812_cascade_delete_roles.sql b/backend/internal/data/migrations/migrations/20221205234812_cascade_delete_roles.sql new file mode 100644 index 0000000..8a37c11 --- /dev/null +++ b/backend/internal/data/migrations/migrations/20221205234812_cascade_delete_roles.sql @@ -0,0 +1,16 @@ +-- disable the enforcement of foreign-keys constraints +PRAGMA foreign_keys = off; +-- create "new_auth_roles" table +CREATE TABLE `new_auth_roles` (`id` integer NOT NULL PRIMARY KEY AUTOINCREMENT, `role` text NOT NULL DEFAULT 'user', `auth_tokens_roles` uuid NULL, CONSTRAINT `auth_roles_auth_tokens_roles` FOREIGN KEY (`auth_tokens_roles`) REFERENCES `auth_tokens` (`id`) ON DELETE CASCADE); +-- copy rows from old table "auth_roles" to new temporary table "new_auth_roles" +INSERT INTO `new_auth_roles` (`id`, `role`, `auth_tokens_roles`) SELECT `id`, `role`, `auth_tokens_roles` FROM `auth_roles`; +-- drop "auth_roles" table after copying rows +DROP TABLE `auth_roles`; +-- rename temporary table "new_auth_roles" to "auth_roles" +ALTER TABLE `new_auth_roles` RENAME TO `auth_roles`; +-- create index "auth_roles_auth_tokens_roles_key" to table: "auth_roles" +CREATE UNIQUE INDEX `auth_roles_auth_tokens_roles_key` ON `auth_roles` (`auth_tokens_roles`); +-- delete where tokens is null +DELETE FROM `auth_roles` WHERE `auth_tokens_roles` IS NULL; +-- enable back the enforcement of foreign-keys constraints +PRAGMA foreign_keys = on; diff --git a/backend/internal/data/migrations/migrations/atlas.sum b/backend/internal/data/migrations/migrations/atlas.sum index 0c9927b..5de79cc 100644 --- a/backend/internal/data/migrations/migrations/atlas.sum +++ b/backend/internal/data/migrations/migrations/atlas.sum @@ -1,4 +1,4 @@ -h1:oo2QbYbKkbf4oTfkRXqo9XGPp8S76j33WQvDZITv5s8= +h1:dn3XsqwgjCxEtpLXmHlt2ALRwg2cZB6m8lg2faxeLXM= 20220929052825_init.sql h1:ZlCqm1wzjDmofeAcSX3jE4h4VcdTNGpRg2eabztDy9Q= 20221001210956_group_invitations.sql h1:YQKJFtE39wFOcRNbZQ/d+ZlHwrcfcsZlcv/pLEYdpjw= 20221009173029_add_user_roles.sql h1:vWmzAfgEWQeGk0Vn70zfVPCcfEZth3E0JcvyKTjpYyU= @@ -6,3 +6,6 @@ h1:oo2QbYbKkbf4oTfkRXqo9XGPp8S76j33WQvDZITv5s8= 20221101041931_add_archived_field.sql h1:L2WxiOh1svRn817cNURgqnEQg6DIcodZ1twK4tvxW94= 20221113012312_add_asset_id_field.sql h1:DjD7e1PS8OfxGBWic8h0nO/X6CNnHEMqQjDCaaQ3M3Q= 20221203053132_add_token_roles.sql h1:wFTIh+KBoHfLfy/L0ZmJz4cNXKHdACG9ZK/yvVKjF0M= +20221205230404_drop_document_tokens.sql h1:9dCbNFcjtsT6lEhkxCn/vYaGRmQrl1LefdEJgvkfhGg= +20221205234214_add_maintenance_entries.sql h1:B56VzCuDsed1k3/sYUoKlOkP90DcdLufxFK0qYvoafU= +20221205234812_cascade_delete_roles.sql h1:VIiaImR48nCHF3uFbOYOX1E79Ta5HsUBetGaSAbh9Gk= diff --git a/frontend/lib/api/types/data-contracts.ts b/frontend/lib/api/types/data-contracts.ts index 09f10e7..404aa5b 100644 --- a/frontend/lib/api/types/data-contracts.ts +++ b/frontend/lib/api/types/data-contracts.ts @@ -54,7 +54,6 @@ export interface ItemAttachmentUpdate { export interface ItemCreate { description: string; labelIds: string[]; - /** Edges */ locationId: string; name: string; @@ -73,8 +72,7 @@ export interface ItemField { export interface ItemOut { archived: boolean; - - /** @example 0 */ + /** @example "0" */ assetId: string; attachments: ItemAttachment[]; children: ItemSummary[]; @@ -84,33 +82,26 @@ export interface ItemOut { id: string; insured: boolean; labels: LabelSummary[]; - /** Warranty */ lifetimeWarranty: boolean; - /** Edges */ location: LocationSummary | null; manufacturer: string; modelNumber: string; name: string; - /** Extras */ notes: string; parent: ItemSummary | null; purchaseFrom: string; - - /** @example 0 */ + /** @example "0" */ purchasePrice: string; - /** Purchase */ purchaseTime: Date; quantity: number; serialNumber: string; soldNotes: string; - - /** @example 0 */ + /** @example "0" */ soldPrice: string; - /** Sold */ soldTime: Date; soldTo: string; @@ -126,7 +117,6 @@ export interface ItemSummary { id: string; insured: boolean; labels: LabelSummary[]; - /** Edges */ location: LocationSummary | null; name: string; @@ -142,35 +132,27 @@ export interface ItemUpdate { id: string; insured: boolean; labelIds: string[]; - /** Warranty */ lifetimeWarranty: boolean; - /** Edges */ locationId: string; manufacturer: string; modelNumber: string; name: string; - /** Extras */ notes: string; parentId: string | null; purchaseFrom: string; - - /** @example 0 */ + /** @example "0" */ purchasePrice: string; - /** Purchase */ purchaseTime: Date; quantity: number; - /** Identifications */ serialNumber: string; soldNotes: string; - - /** @example 0 */ + /** @example "0" */ soldPrice: string; - /** Sold */ soldTime: Date; soldTo: string;