refactor: remove empty services (#116)

* remove empty services

* remove old factory

* remove old static files

* cleanup more duplicate service code

* file/folder reorg
This commit is contained in:
Hayden 2022-10-29 20:05:38 -08:00 committed by GitHub
parent 6529549289
commit cd82fe0d89
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
179 changed files with 514 additions and 582 deletions

View file

@ -0,0 +1,197 @@
// 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/attachment"
"github.com/hay-kot/homebox/backend/internal/data/ent/document"
"github.com/hay-kot/homebox/backend/internal/data/ent/item"
)
// Attachment is the model entity for the Attachment schema.
type Attachment 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"`
// Type holds the value of the "type" field.
Type attachment.Type `json:"type,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the AttachmentQuery when eager-loading is set.
Edges AttachmentEdges `json:"edges"`
document_attachments *uuid.UUID
item_attachments *uuid.UUID
}
// AttachmentEdges holds the relations/edges for other nodes in the graph.
type AttachmentEdges struct {
// Item holds the value of the item edge.
Item *Item `json:"item,omitempty"`
// Document holds the value of the document edge.
Document *Document `json:"document,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]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 AttachmentEdges) 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"}
}
// DocumentOrErr returns the Document value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e AttachmentEdges) DocumentOrErr() (*Document, error) {
if e.loadedTypes[1] {
if e.Document == nil {
// Edge was loaded but was not found.
return nil, &NotFoundError{label: document.Label}
}
return e.Document, nil
}
return nil, &NotLoadedError{edge: "document"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Attachment) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case attachment.FieldType:
values[i] = new(sql.NullString)
case attachment.FieldCreatedAt, attachment.FieldUpdatedAt:
values[i] = new(sql.NullTime)
case attachment.FieldID:
values[i] = new(uuid.UUID)
case attachment.ForeignKeys[0]: // document_attachments
values[i] = &sql.NullScanner{S: new(uuid.UUID)}
case attachment.ForeignKeys[1]: // item_attachments
values[i] = &sql.NullScanner{S: new(uuid.UUID)}
default:
return nil, fmt.Errorf("unexpected column %q for type Attachment", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Attachment fields.
func (a *Attachment) 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 attachment.FieldID:
if value, ok := values[i].(*uuid.UUID); !ok {
return fmt.Errorf("unexpected type %T for field id", values[i])
} else if value != nil {
a.ID = *value
}
case attachment.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 {
a.CreatedAt = value.Time
}
case attachment.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 {
a.UpdatedAt = value.Time
}
case attachment.FieldType:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field type", values[i])
} else if value.Valid {
a.Type = attachment.Type(value.String)
}
case attachment.ForeignKeys[0]:
if value, ok := values[i].(*sql.NullScanner); !ok {
return fmt.Errorf("unexpected type %T for field document_attachments", values[i])
} else if value.Valid {
a.document_attachments = new(uuid.UUID)
*a.document_attachments = *value.S.(*uuid.UUID)
}
case attachment.ForeignKeys[1]:
if value, ok := values[i].(*sql.NullScanner); !ok {
return fmt.Errorf("unexpected type %T for field item_attachments", values[i])
} else if value.Valid {
a.item_attachments = new(uuid.UUID)
*a.item_attachments = *value.S.(*uuid.UUID)
}
}
}
return nil
}
// QueryItem queries the "item" edge of the Attachment entity.
func (a *Attachment) QueryItem() *ItemQuery {
return (&AttachmentClient{config: a.config}).QueryItem(a)
}
// QueryDocument queries the "document" edge of the Attachment entity.
func (a *Attachment) QueryDocument() *DocumentQuery {
return (&AttachmentClient{config: a.config}).QueryDocument(a)
}
// Update returns a builder for updating this Attachment.
// Note that you need to call Attachment.Unwrap() before calling this method if this Attachment
// was returned from a transaction, and the transaction was committed or rolled back.
func (a *Attachment) Update() *AttachmentUpdateOne {
return (&AttachmentClient{config: a.config}).UpdateOne(a)
}
// Unwrap unwraps the Attachment 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 (a *Attachment) Unwrap() *Attachment {
_tx, ok := a.config.driver.(*txDriver)
if !ok {
panic("ent: Attachment is not a transactional entity")
}
a.config.driver = _tx.drv
return a
}
// String implements the fmt.Stringer.
func (a *Attachment) String() string {
var builder strings.Builder
builder.WriteString("Attachment(")
builder.WriteString(fmt.Sprintf("id=%v, ", a.ID))
builder.WriteString("created_at=")
builder.WriteString(a.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(a.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("type=")
builder.WriteString(fmt.Sprintf("%v", a.Type))
builder.WriteByte(')')
return builder.String()
}
// Attachments is a parsable slice of Attachment.
type Attachments []*Attachment
func (a Attachments) config(cfg config) {
for _i := range a {
a[_i].config = cfg
}
}

View file

@ -0,0 +1,113 @@
// Code generated by ent, DO NOT EDIT.
package attachment
import (
"fmt"
"time"
"github.com/google/uuid"
)
const (
// Label holds the string label denoting the attachment type in the database.
Label = "attachment"
// 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"
// FieldType holds the string denoting the type field in the database.
FieldType = "type"
// EdgeItem holds the string denoting the item edge name in mutations.
EdgeItem = "item"
// EdgeDocument holds the string denoting the document edge name in mutations.
EdgeDocument = "document"
// Table holds the table name of the attachment in the database.
Table = "attachments"
// ItemTable is the table that holds the item relation/edge.
ItemTable = "attachments"
// 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_attachments"
// DocumentTable is the table that holds the document relation/edge.
DocumentTable = "attachments"
// DocumentInverseTable is the table name for the Document entity.
// It exists in this package in order to avoid circular dependency with the "document" package.
DocumentInverseTable = "documents"
// DocumentColumn is the table column denoting the document relation/edge.
DocumentColumn = "document_attachments"
)
// Columns holds all SQL columns for attachment fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldType,
}
// ForeignKeys holds the SQL foreign-keys that are owned by the "attachments"
// table and are not defined as standalone fields in the schema.
var ForeignKeys = []string{
"document_attachments",
"item_attachments",
}
// 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
}
}
for i := range ForeignKeys {
if column == ForeignKeys[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
// DefaultID holds the default value on creation for the "id" field.
DefaultID func() uuid.UUID
)
// Type defines the type for the "type" enum field.
type Type string
// TypeAttachment is the default value of the Type enum.
const DefaultType = TypeAttachment
// Type values.
const (
TypePhoto Type = "photo"
TypeManual Type = "manual"
TypeWarranty Type = "warranty"
TypeAttachment Type = "attachment"
TypeReceipt Type = "receipt"
)
func (_type Type) String() string {
return string(_type)
}
// TypeValidator is a validator for the "type" field enum values. It is called by the builders before save.
func TypeValidator(_type Type) error {
switch _type {
case TypePhoto, TypeManual, TypeWarranty, TypeAttachment, TypeReceipt:
return nil
default:
return fmt.Errorf("attachment: invalid enum value for type field: %q", _type)
}
}

View file

@ -0,0 +1,349 @@
// Code generated by ent, DO NOT EDIT.
package attachment
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.Attachment {
return predicate.Attachment(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.Attachment {
return predicate.Attachment(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.Attachment {
return predicate.Attachment(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.Attachment {
return predicate.Attachment(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.Attachment {
return predicate.Attachment(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.Attachment {
return predicate.Attachment(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.Attachment {
return predicate.Attachment(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.Attachment {
return predicate.Attachment(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.Attachment {
return predicate.Attachment(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.Attachment {
return predicate.Attachment(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.Attachment {
return predicate.Attachment(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
})
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.Attachment {
return predicate.Attachment(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.Attachment {
return predicate.Attachment(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.Attachment {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Attachment(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.Attachment {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Attachment(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.Attachment {
return predicate.Attachment(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.Attachment {
return predicate.Attachment(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.Attachment {
return predicate.Attachment(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.Attachment {
return predicate.Attachment(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.Attachment {
return predicate.Attachment(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.Attachment {
return predicate.Attachment(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.Attachment {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Attachment(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.Attachment {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Attachment(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.Attachment {
return predicate.Attachment(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.Attachment {
return predicate.Attachment(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.Attachment {
return predicate.Attachment(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.Attachment {
return predicate.Attachment(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldUpdatedAt), v))
})
}
// TypeEQ applies the EQ predicate on the "type" field.
func TypeEQ(v Type) predicate.Attachment {
return predicate.Attachment(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldType), v))
})
}
// TypeNEQ applies the NEQ predicate on the "type" field.
func TypeNEQ(v Type) predicate.Attachment {
return predicate.Attachment(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldType), v))
})
}
// TypeIn applies the In predicate on the "type" field.
func TypeIn(vs ...Type) predicate.Attachment {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Attachment(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldType), v...))
})
}
// TypeNotIn applies the NotIn predicate on the "type" field.
func TypeNotIn(vs ...Type) predicate.Attachment {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Attachment(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldType), v...))
})
}
// HasItem applies the HasEdge predicate on the "item" edge.
func HasItem() predicate.Attachment {
return predicate.Attachment(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.Attachment {
return predicate.Attachment(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)
}
})
})
}
// HasDocument applies the HasEdge predicate on the "document" edge.
func HasDocument() predicate.Attachment {
return predicate.Attachment(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(DocumentTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, DocumentTable, DocumentColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasDocumentWith applies the HasEdge predicate on the "document" edge with a given conditions (other predicates).
func HasDocumentWith(preds ...predicate.Document) predicate.Attachment {
return predicate.Attachment(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(DocumentInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, DocumentTable, DocumentColumn),
)
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.Attachment) predicate.Attachment {
return predicate.Attachment(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.Attachment) predicate.Attachment {
return predicate.Attachment(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.Attachment) predicate.Attachment {
return predicate.Attachment(func(s *sql.Selector) {
p(s.Not())
})
}

View file

@ -0,0 +1,402 @@
// 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/attachment"
"github.com/hay-kot/homebox/backend/internal/data/ent/document"
"github.com/hay-kot/homebox/backend/internal/data/ent/item"
)
// AttachmentCreate is the builder for creating a Attachment entity.
type AttachmentCreate struct {
config
mutation *AttachmentMutation
hooks []Hook
}
// SetCreatedAt sets the "created_at" field.
func (ac *AttachmentCreate) SetCreatedAt(t time.Time) *AttachmentCreate {
ac.mutation.SetCreatedAt(t)
return ac
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (ac *AttachmentCreate) SetNillableCreatedAt(t *time.Time) *AttachmentCreate {
if t != nil {
ac.SetCreatedAt(*t)
}
return ac
}
// SetUpdatedAt sets the "updated_at" field.
func (ac *AttachmentCreate) SetUpdatedAt(t time.Time) *AttachmentCreate {
ac.mutation.SetUpdatedAt(t)
return ac
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (ac *AttachmentCreate) SetNillableUpdatedAt(t *time.Time) *AttachmentCreate {
if t != nil {
ac.SetUpdatedAt(*t)
}
return ac
}
// SetType sets the "type" field.
func (ac *AttachmentCreate) SetType(a attachment.Type) *AttachmentCreate {
ac.mutation.SetType(a)
return ac
}
// SetNillableType sets the "type" field if the given value is not nil.
func (ac *AttachmentCreate) SetNillableType(a *attachment.Type) *AttachmentCreate {
if a != nil {
ac.SetType(*a)
}
return ac
}
// SetID sets the "id" field.
func (ac *AttachmentCreate) SetID(u uuid.UUID) *AttachmentCreate {
ac.mutation.SetID(u)
return ac
}
// SetNillableID sets the "id" field if the given value is not nil.
func (ac *AttachmentCreate) SetNillableID(u *uuid.UUID) *AttachmentCreate {
if u != nil {
ac.SetID(*u)
}
return ac
}
// SetItemID sets the "item" edge to the Item entity by ID.
func (ac *AttachmentCreate) SetItemID(id uuid.UUID) *AttachmentCreate {
ac.mutation.SetItemID(id)
return ac
}
// SetItem sets the "item" edge to the Item entity.
func (ac *AttachmentCreate) SetItem(i *Item) *AttachmentCreate {
return ac.SetItemID(i.ID)
}
// SetDocumentID sets the "document" edge to the Document entity by ID.
func (ac *AttachmentCreate) SetDocumentID(id uuid.UUID) *AttachmentCreate {
ac.mutation.SetDocumentID(id)
return ac
}
// SetDocument sets the "document" edge to the Document entity.
func (ac *AttachmentCreate) SetDocument(d *Document) *AttachmentCreate {
return ac.SetDocumentID(d.ID)
}
// Mutation returns the AttachmentMutation object of the builder.
func (ac *AttachmentCreate) Mutation() *AttachmentMutation {
return ac.mutation
}
// Save creates the Attachment in the database.
func (ac *AttachmentCreate) Save(ctx context.Context) (*Attachment, error) {
var (
err error
node *Attachment
)
ac.defaults()
if len(ac.hooks) == 0 {
if err = ac.check(); err != nil {
return nil, err
}
node, err = ac.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*AttachmentMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = ac.check(); err != nil {
return nil, err
}
ac.mutation = mutation
if node, err = ac.sqlSave(ctx); err != nil {
return nil, err
}
mutation.id = &node.ID
mutation.done = true
return node, err
})
for i := len(ac.hooks) - 1; i >= 0; i-- {
if ac.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = ac.hooks[i](mut)
}
v, err := mut.Mutate(ctx, ac.mutation)
if err != nil {
return nil, err
}
nv, ok := v.(*Attachment)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from AttachmentMutation", v)
}
node = nv
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (ac *AttachmentCreate) SaveX(ctx context.Context) *Attachment {
v, err := ac.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (ac *AttachmentCreate) Exec(ctx context.Context) error {
_, err := ac.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (ac *AttachmentCreate) ExecX(ctx context.Context) {
if err := ac.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (ac *AttachmentCreate) defaults() {
if _, ok := ac.mutation.CreatedAt(); !ok {
v := attachment.DefaultCreatedAt()
ac.mutation.SetCreatedAt(v)
}
if _, ok := ac.mutation.UpdatedAt(); !ok {
v := attachment.DefaultUpdatedAt()
ac.mutation.SetUpdatedAt(v)
}
if _, ok := ac.mutation.GetType(); !ok {
v := attachment.DefaultType
ac.mutation.SetType(v)
}
if _, ok := ac.mutation.ID(); !ok {
v := attachment.DefaultID()
ac.mutation.SetID(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (ac *AttachmentCreate) check() error {
if _, ok := ac.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Attachment.created_at"`)}
}
if _, ok := ac.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Attachment.updated_at"`)}
}
if _, ok := ac.mutation.GetType(); !ok {
return &ValidationError{Name: "type", err: errors.New(`ent: missing required field "Attachment.type"`)}
}
if v, ok := ac.mutation.GetType(); ok {
if err := attachment.TypeValidator(v); err != nil {
return &ValidationError{Name: "type", err: fmt.Errorf(`ent: validator failed for field "Attachment.type": %w`, err)}
}
}
if _, ok := ac.mutation.ItemID(); !ok {
return &ValidationError{Name: "item", err: errors.New(`ent: missing required edge "Attachment.item"`)}
}
if _, ok := ac.mutation.DocumentID(); !ok {
return &ValidationError{Name: "document", err: errors.New(`ent: missing required edge "Attachment.document"`)}
}
return nil
}
func (ac *AttachmentCreate) sqlSave(ctx context.Context) (*Attachment, error) {
_node, _spec := ac.createSpec()
if err := sqlgraph.CreateNode(ctx, ac.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 (ac *AttachmentCreate) createSpec() (*Attachment, *sqlgraph.CreateSpec) {
var (
_node = &Attachment{config: ac.config}
_spec = &sqlgraph.CreateSpec{
Table: attachment.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: attachment.FieldID,
},
}
)
if id, ok := ac.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = &id
}
if value, ok := ac.mutation.CreatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: attachment.FieldCreatedAt,
})
_node.CreatedAt = value
}
if value, ok := ac.mutation.UpdatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: attachment.FieldUpdatedAt,
})
_node.UpdatedAt = value
}
if value, ok := ac.mutation.GetType(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeEnum,
Value: value,
Column: attachment.FieldType,
})
_node.Type = value
}
if nodes := ac.mutation.ItemIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: attachment.ItemTable,
Columns: []string{attachment.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.item_attachments = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := ac.mutation.DocumentIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: attachment.DocumentTable,
Columns: []string{attachment.DocumentColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: document.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.document_attachments = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// AttachmentCreateBulk is the builder for creating many Attachment entities in bulk.
type AttachmentCreateBulk struct {
config
builders []*AttachmentCreate
}
// Save creates the Attachment entities in the database.
func (acb *AttachmentCreateBulk) Save(ctx context.Context) ([]*Attachment, error) {
specs := make([]*sqlgraph.CreateSpec, len(acb.builders))
nodes := make([]*Attachment, len(acb.builders))
mutators := make([]Mutator, len(acb.builders))
for i := range acb.builders {
func(i int, root context.Context) {
builder := acb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*AttachmentMutation)
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, acb.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, acb.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, acb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (acb *AttachmentCreateBulk) SaveX(ctx context.Context) []*Attachment {
v, err := acb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (acb *AttachmentCreateBulk) Exec(ctx context.Context) error {
_, err := acb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (acb *AttachmentCreateBulk) ExecX(ctx context.Context) {
if err := acb.Exec(ctx); err != nil {
panic(err)
}
}

View file

@ -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/attachment"
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
)
// AttachmentDelete is the builder for deleting a Attachment entity.
type AttachmentDelete struct {
config
hooks []Hook
mutation *AttachmentMutation
}
// Where appends a list predicates to the AttachmentDelete builder.
func (ad *AttachmentDelete) Where(ps ...predicate.Attachment) *AttachmentDelete {
ad.mutation.Where(ps...)
return ad
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (ad *AttachmentDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(ad.hooks) == 0 {
affected, err = ad.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*AttachmentMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
ad.mutation = mutation
affected, err = ad.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(ad.hooks) - 1; i >= 0; i-- {
if ad.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = ad.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, ad.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (ad *AttachmentDelete) ExecX(ctx context.Context) int {
n, err := ad.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (ad *AttachmentDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: attachment.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: attachment.FieldID,
},
},
}
if ps := ad.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, ad.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return affected, err
}
// AttachmentDeleteOne is the builder for deleting a single Attachment entity.
type AttachmentDeleteOne struct {
ad *AttachmentDelete
}
// Exec executes the deletion query.
func (ado *AttachmentDeleteOne) Exec(ctx context.Context) error {
n, err := ado.ad.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{attachment.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (ado *AttachmentDeleteOne) ExecX(ctx context.Context) {
ado.ad.ExecX(ctx)
}

View file

@ -0,0 +1,686 @@
// 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/attachment"
"github.com/hay-kot/homebox/backend/internal/data/ent/document"
"github.com/hay-kot/homebox/backend/internal/data/ent/item"
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
)
// AttachmentQuery is the builder for querying Attachment entities.
type AttachmentQuery struct {
config
limit *int
offset *int
unique *bool
order []OrderFunc
fields []string
predicates []predicate.Attachment
withItem *ItemQuery
withDocument *DocumentQuery
withFKs bool
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the AttachmentQuery builder.
func (aq *AttachmentQuery) Where(ps ...predicate.Attachment) *AttachmentQuery {
aq.predicates = append(aq.predicates, ps...)
return aq
}
// Limit adds a limit step to the query.
func (aq *AttachmentQuery) Limit(limit int) *AttachmentQuery {
aq.limit = &limit
return aq
}
// Offset adds an offset step to the query.
func (aq *AttachmentQuery) Offset(offset int) *AttachmentQuery {
aq.offset = &offset
return aq
}
// 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 (aq *AttachmentQuery) Unique(unique bool) *AttachmentQuery {
aq.unique = &unique
return aq
}
// Order adds an order step to the query.
func (aq *AttachmentQuery) Order(o ...OrderFunc) *AttachmentQuery {
aq.order = append(aq.order, o...)
return aq
}
// QueryItem chains the current query on the "item" edge.
func (aq *AttachmentQuery) QueryItem() *ItemQuery {
query := &ItemQuery{config: aq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := aq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := aq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(attachment.Table, attachment.FieldID, selector),
sqlgraph.To(item.Table, item.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, attachment.ItemTable, attachment.ItemColumn),
)
fromU = sqlgraph.SetNeighbors(aq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryDocument chains the current query on the "document" edge.
func (aq *AttachmentQuery) QueryDocument() *DocumentQuery {
query := &DocumentQuery{config: aq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := aq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := aq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(attachment.Table, attachment.FieldID, selector),
sqlgraph.To(document.Table, document.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, attachment.DocumentTable, attachment.DocumentColumn),
)
fromU = sqlgraph.SetNeighbors(aq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Attachment entity from the query.
// Returns a *NotFoundError when no Attachment was found.
func (aq *AttachmentQuery) First(ctx context.Context) (*Attachment, error) {
nodes, err := aq.Limit(1).All(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{attachment.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (aq *AttachmentQuery) FirstX(ctx context.Context) *Attachment {
node, err := aq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Attachment ID from the query.
// Returns a *NotFoundError when no Attachment ID was found.
func (aq *AttachmentQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = aq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{attachment.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (aq *AttachmentQuery) FirstIDX(ctx context.Context) uuid.UUID {
id, err := aq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Attachment entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Attachment entity is found.
// Returns a *NotFoundError when no Attachment entities are found.
func (aq *AttachmentQuery) Only(ctx context.Context) (*Attachment, error) {
nodes, err := aq.Limit(2).All(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{attachment.Label}
default:
return nil, &NotSingularError{attachment.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (aq *AttachmentQuery) OnlyX(ctx context.Context) *Attachment {
node, err := aq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Attachment ID in the query.
// Returns a *NotSingularError when more than one Attachment ID is found.
// Returns a *NotFoundError when no entities are found.
func (aq *AttachmentQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = aq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{attachment.Label}
default:
err = &NotSingularError{attachment.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (aq *AttachmentQuery) OnlyIDX(ctx context.Context) uuid.UUID {
id, err := aq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Attachments.
func (aq *AttachmentQuery) All(ctx context.Context) ([]*Attachment, error) {
if err := aq.prepareQuery(ctx); err != nil {
return nil, err
}
return aq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (aq *AttachmentQuery) AllX(ctx context.Context) []*Attachment {
nodes, err := aq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Attachment IDs.
func (aq *AttachmentQuery) IDs(ctx context.Context) ([]uuid.UUID, error) {
var ids []uuid.UUID
if err := aq.Select(attachment.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (aq *AttachmentQuery) IDsX(ctx context.Context) []uuid.UUID {
ids, err := aq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (aq *AttachmentQuery) Count(ctx context.Context) (int, error) {
if err := aq.prepareQuery(ctx); err != nil {
return 0, err
}
return aq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (aq *AttachmentQuery) CountX(ctx context.Context) int {
count, err := aq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (aq *AttachmentQuery) Exist(ctx context.Context) (bool, error) {
if err := aq.prepareQuery(ctx); err != nil {
return false, err
}
return aq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (aq *AttachmentQuery) ExistX(ctx context.Context) bool {
exist, err := aq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the AttachmentQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (aq *AttachmentQuery) Clone() *AttachmentQuery {
if aq == nil {
return nil
}
return &AttachmentQuery{
config: aq.config,
limit: aq.limit,
offset: aq.offset,
order: append([]OrderFunc{}, aq.order...),
predicates: append([]predicate.Attachment{}, aq.predicates...),
withItem: aq.withItem.Clone(),
withDocument: aq.withDocument.Clone(),
// clone intermediate query.
sql: aq.sql.Clone(),
path: aq.path,
unique: aq.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 (aq *AttachmentQuery) WithItem(opts ...func(*ItemQuery)) *AttachmentQuery {
query := &ItemQuery{config: aq.config}
for _, opt := range opts {
opt(query)
}
aq.withItem = query
return aq
}
// WithDocument tells the query-builder to eager-load the nodes that are connected to
// the "document" edge. The optional arguments are used to configure the query builder of the edge.
func (aq *AttachmentQuery) WithDocument(opts ...func(*DocumentQuery)) *AttachmentQuery {
query := &DocumentQuery{config: aq.config}
for _, opt := range opts {
opt(query)
}
aq.withDocument = query
return aq
}
// 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.Attachment.Query().
// GroupBy(attachment.FieldCreatedAt).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (aq *AttachmentQuery) GroupBy(field string, fields ...string) *AttachmentGroupBy {
grbuild := &AttachmentGroupBy{config: aq.config}
grbuild.fields = append([]string{field}, fields...)
grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := aq.prepareQuery(ctx); err != nil {
return nil, err
}
return aq.sqlQuery(ctx), nil
}
grbuild.label = attachment.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.Attachment.Query().
// Select(attachment.FieldCreatedAt).
// Scan(ctx, &v)
func (aq *AttachmentQuery) Select(fields ...string) *AttachmentSelect {
aq.fields = append(aq.fields, fields...)
selbuild := &AttachmentSelect{AttachmentQuery: aq}
selbuild.label = attachment.Label
selbuild.flds, selbuild.scan = &aq.fields, selbuild.Scan
return selbuild
}
func (aq *AttachmentQuery) prepareQuery(ctx context.Context) error {
for _, f := range aq.fields {
if !attachment.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if aq.path != nil {
prev, err := aq.path(ctx)
if err != nil {
return err
}
aq.sql = prev
}
return nil
}
func (aq *AttachmentQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Attachment, error) {
var (
nodes = []*Attachment{}
withFKs = aq.withFKs
_spec = aq.querySpec()
loadedTypes = [2]bool{
aq.withItem != nil,
aq.withDocument != nil,
}
)
if aq.withItem != nil || aq.withDocument != nil {
withFKs = true
}
if withFKs {
_spec.Node.Columns = append(_spec.Node.Columns, attachment.ForeignKeys...)
}
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Attachment).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Attachment{config: aq.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, aq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := aq.withItem; query != nil {
if err := aq.loadItem(ctx, query, nodes, nil,
func(n *Attachment, e *Item) { n.Edges.Item = e }); err != nil {
return nil, err
}
}
if query := aq.withDocument; query != nil {
if err := aq.loadDocument(ctx, query, nodes, nil,
func(n *Attachment, e *Document) { n.Edges.Document = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (aq *AttachmentQuery) loadItem(ctx context.Context, query *ItemQuery, nodes []*Attachment, init func(*Attachment), assign func(*Attachment, *Item)) error {
ids := make([]uuid.UUID, 0, len(nodes))
nodeids := make(map[uuid.UUID][]*Attachment)
for i := range nodes {
if nodes[i].item_attachments == nil {
continue
}
fk := *nodes[i].item_attachments
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_attachments" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (aq *AttachmentQuery) loadDocument(ctx context.Context, query *DocumentQuery, nodes []*Attachment, init func(*Attachment), assign func(*Attachment, *Document)) error {
ids := make([]uuid.UUID, 0, len(nodes))
nodeids := make(map[uuid.UUID][]*Attachment)
for i := range nodes {
if nodes[i].document_attachments == nil {
continue
}
fk := *nodes[i].document_attachments
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
query.Where(document.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 "document_attachments" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (aq *AttachmentQuery) sqlCount(ctx context.Context) (int, error) {
_spec := aq.querySpec()
_spec.Node.Columns = aq.fields
if len(aq.fields) > 0 {
_spec.Unique = aq.unique != nil && *aq.unique
}
return sqlgraph.CountNodes(ctx, aq.driver, _spec)
}
func (aq *AttachmentQuery) sqlExist(ctx context.Context) (bool, error) {
switch _, err := aq.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 (aq *AttachmentQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: attachment.Table,
Columns: attachment.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: attachment.FieldID,
},
},
From: aq.sql,
Unique: true,
}
if unique := aq.unique; unique != nil {
_spec.Unique = *unique
}
if fields := aq.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, attachment.FieldID)
for i := range fields {
if fields[i] != attachment.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := aq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := aq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := aq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := aq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (aq *AttachmentQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(aq.driver.Dialect())
t1 := builder.Table(attachment.Table)
columns := aq.fields
if len(columns) == 0 {
columns = attachment.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if aq.sql != nil {
selector = aq.sql
selector.Select(selector.Columns(columns...)...)
}
if aq.unique != nil && *aq.unique {
selector.Distinct()
}
for _, p := range aq.predicates {
p(selector)
}
for _, p := range aq.order {
p(selector)
}
if offset := aq.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 := aq.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// AttachmentGroupBy is the group-by builder for Attachment entities.
type AttachmentGroupBy 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 (agb *AttachmentGroupBy) Aggregate(fns ...AggregateFunc) *AttachmentGroupBy {
agb.fns = append(agb.fns, fns...)
return agb
}
// Scan applies the group-by query and scans the result into the given value.
func (agb *AttachmentGroupBy) Scan(ctx context.Context, v any) error {
query, err := agb.path(ctx)
if err != nil {
return err
}
agb.sql = query
return agb.sqlScan(ctx, v)
}
func (agb *AttachmentGroupBy) sqlScan(ctx context.Context, v any) error {
for _, f := range agb.fields {
if !attachment.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := agb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := agb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (agb *AttachmentGroupBy) sqlQuery() *sql.Selector {
selector := agb.sql.Select()
aggregation := make([]string, 0, len(agb.fns))
for _, fn := range agb.fns {
aggregation = append(aggregation, fn(selector))
}
// If no columns were selected in a custom aggregation function, the default
// selection is the fields used for "group-by", and the aggregation functions.
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(agb.fields)+len(agb.fns))
for _, f := range agb.fields {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
return selector.GroupBy(selector.Columns(agb.fields...)...)
}
// AttachmentSelect is the builder for selecting fields of Attachment entities.
type AttachmentSelect struct {
*AttachmentQuery
selector
// intermediate query (i.e. traversal path).
sql *sql.Selector
}
// Scan applies the selector query and scans the result into the given value.
func (as *AttachmentSelect) Scan(ctx context.Context, v any) error {
if err := as.prepareQuery(ctx); err != nil {
return err
}
as.sql = as.AttachmentQuery.sqlQuery(ctx)
return as.sqlScan(ctx, v)
}
func (as *AttachmentSelect) sqlScan(ctx context.Context, v any) error {
rows := &sql.Rows{}
query, args := as.sql.Query()
if err := as.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

View file

@ -0,0 +1,587 @@
// 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/attachment"
"github.com/hay-kot/homebox/backend/internal/data/ent/document"
"github.com/hay-kot/homebox/backend/internal/data/ent/item"
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
)
// AttachmentUpdate is the builder for updating Attachment entities.
type AttachmentUpdate struct {
config
hooks []Hook
mutation *AttachmentMutation
}
// Where appends a list predicates to the AttachmentUpdate builder.
func (au *AttachmentUpdate) Where(ps ...predicate.Attachment) *AttachmentUpdate {
au.mutation.Where(ps...)
return au
}
// SetUpdatedAt sets the "updated_at" field.
func (au *AttachmentUpdate) SetUpdatedAt(t time.Time) *AttachmentUpdate {
au.mutation.SetUpdatedAt(t)
return au
}
// SetType sets the "type" field.
func (au *AttachmentUpdate) SetType(a attachment.Type) *AttachmentUpdate {
au.mutation.SetType(a)
return au
}
// SetNillableType sets the "type" field if the given value is not nil.
func (au *AttachmentUpdate) SetNillableType(a *attachment.Type) *AttachmentUpdate {
if a != nil {
au.SetType(*a)
}
return au
}
// SetItemID sets the "item" edge to the Item entity by ID.
func (au *AttachmentUpdate) SetItemID(id uuid.UUID) *AttachmentUpdate {
au.mutation.SetItemID(id)
return au
}
// SetItem sets the "item" edge to the Item entity.
func (au *AttachmentUpdate) SetItem(i *Item) *AttachmentUpdate {
return au.SetItemID(i.ID)
}
// SetDocumentID sets the "document" edge to the Document entity by ID.
func (au *AttachmentUpdate) SetDocumentID(id uuid.UUID) *AttachmentUpdate {
au.mutation.SetDocumentID(id)
return au
}
// SetDocument sets the "document" edge to the Document entity.
func (au *AttachmentUpdate) SetDocument(d *Document) *AttachmentUpdate {
return au.SetDocumentID(d.ID)
}
// Mutation returns the AttachmentMutation object of the builder.
func (au *AttachmentUpdate) Mutation() *AttachmentMutation {
return au.mutation
}
// ClearItem clears the "item" edge to the Item entity.
func (au *AttachmentUpdate) ClearItem() *AttachmentUpdate {
au.mutation.ClearItem()
return au
}
// ClearDocument clears the "document" edge to the Document entity.
func (au *AttachmentUpdate) ClearDocument() *AttachmentUpdate {
au.mutation.ClearDocument()
return au
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (au *AttachmentUpdate) Save(ctx context.Context) (int, error) {
var (
err error
affected int
)
au.defaults()
if len(au.hooks) == 0 {
if err = au.check(); err != nil {
return 0, err
}
affected, err = au.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*AttachmentMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = au.check(); err != nil {
return 0, err
}
au.mutation = mutation
affected, err = au.sqlSave(ctx)
mutation.done = true
return affected, err
})
for i := len(au.hooks) - 1; i >= 0; i-- {
if au.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = au.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, au.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// SaveX is like Save, but panics if an error occurs.
func (au *AttachmentUpdate) SaveX(ctx context.Context) int {
affected, err := au.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (au *AttachmentUpdate) Exec(ctx context.Context) error {
_, err := au.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (au *AttachmentUpdate) ExecX(ctx context.Context) {
if err := au.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (au *AttachmentUpdate) defaults() {
if _, ok := au.mutation.UpdatedAt(); !ok {
v := attachment.UpdateDefaultUpdatedAt()
au.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (au *AttachmentUpdate) check() error {
if v, ok := au.mutation.GetType(); ok {
if err := attachment.TypeValidator(v); err != nil {
return &ValidationError{Name: "type", err: fmt.Errorf(`ent: validator failed for field "Attachment.type": %w`, err)}
}
}
if _, ok := au.mutation.ItemID(); au.mutation.ItemCleared() && !ok {
return errors.New(`ent: clearing a required unique edge "Attachment.item"`)
}
if _, ok := au.mutation.DocumentID(); au.mutation.DocumentCleared() && !ok {
return errors.New(`ent: clearing a required unique edge "Attachment.document"`)
}
return nil
}
func (au *AttachmentUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: attachment.Table,
Columns: attachment.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: attachment.FieldID,
},
},
}
if ps := au.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := au.mutation.UpdatedAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: attachment.FieldUpdatedAt,
})
}
if value, ok := au.mutation.GetType(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeEnum,
Value: value,
Column: attachment.FieldType,
})
}
if au.mutation.ItemCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: attachment.ItemTable,
Columns: []string{attachment.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 := au.mutation.ItemIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: attachment.ItemTable,
Columns: []string{attachment.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 au.mutation.DocumentCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: attachment.DocumentTable,
Columns: []string{attachment.DocumentColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: document.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := au.mutation.DocumentIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: attachment.DocumentTable,
Columns: []string{attachment.DocumentColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: document.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, au.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{attachment.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
return n, nil
}
// AttachmentUpdateOne is the builder for updating a single Attachment entity.
type AttachmentUpdateOne struct {
config
fields []string
hooks []Hook
mutation *AttachmentMutation
}
// SetUpdatedAt sets the "updated_at" field.
func (auo *AttachmentUpdateOne) SetUpdatedAt(t time.Time) *AttachmentUpdateOne {
auo.mutation.SetUpdatedAt(t)
return auo
}
// SetType sets the "type" field.
func (auo *AttachmentUpdateOne) SetType(a attachment.Type) *AttachmentUpdateOne {
auo.mutation.SetType(a)
return auo
}
// SetNillableType sets the "type" field if the given value is not nil.
func (auo *AttachmentUpdateOne) SetNillableType(a *attachment.Type) *AttachmentUpdateOne {
if a != nil {
auo.SetType(*a)
}
return auo
}
// SetItemID sets the "item" edge to the Item entity by ID.
func (auo *AttachmentUpdateOne) SetItemID(id uuid.UUID) *AttachmentUpdateOne {
auo.mutation.SetItemID(id)
return auo
}
// SetItem sets the "item" edge to the Item entity.
func (auo *AttachmentUpdateOne) SetItem(i *Item) *AttachmentUpdateOne {
return auo.SetItemID(i.ID)
}
// SetDocumentID sets the "document" edge to the Document entity by ID.
func (auo *AttachmentUpdateOne) SetDocumentID(id uuid.UUID) *AttachmentUpdateOne {
auo.mutation.SetDocumentID(id)
return auo
}
// SetDocument sets the "document" edge to the Document entity.
func (auo *AttachmentUpdateOne) SetDocument(d *Document) *AttachmentUpdateOne {
return auo.SetDocumentID(d.ID)
}
// Mutation returns the AttachmentMutation object of the builder.
func (auo *AttachmentUpdateOne) Mutation() *AttachmentMutation {
return auo.mutation
}
// ClearItem clears the "item" edge to the Item entity.
func (auo *AttachmentUpdateOne) ClearItem() *AttachmentUpdateOne {
auo.mutation.ClearItem()
return auo
}
// ClearDocument clears the "document" edge to the Document entity.
func (auo *AttachmentUpdateOne) ClearDocument() *AttachmentUpdateOne {
auo.mutation.ClearDocument()
return auo
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (auo *AttachmentUpdateOne) Select(field string, fields ...string) *AttachmentUpdateOne {
auo.fields = append([]string{field}, fields...)
return auo
}
// Save executes the query and returns the updated Attachment entity.
func (auo *AttachmentUpdateOne) Save(ctx context.Context) (*Attachment, error) {
var (
err error
node *Attachment
)
auo.defaults()
if len(auo.hooks) == 0 {
if err = auo.check(); err != nil {
return nil, err
}
node, err = auo.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*AttachmentMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = auo.check(); err != nil {
return nil, err
}
auo.mutation = mutation
node, err = auo.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(auo.hooks) - 1; i >= 0; i-- {
if auo.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = auo.hooks[i](mut)
}
v, err := mut.Mutate(ctx, auo.mutation)
if err != nil {
return nil, err
}
nv, ok := v.(*Attachment)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from AttachmentMutation", v)
}
node = nv
}
return node, err
}
// SaveX is like Save, but panics if an error occurs.
func (auo *AttachmentUpdateOne) SaveX(ctx context.Context) *Attachment {
node, err := auo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (auo *AttachmentUpdateOne) Exec(ctx context.Context) error {
_, err := auo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (auo *AttachmentUpdateOne) ExecX(ctx context.Context) {
if err := auo.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (auo *AttachmentUpdateOne) defaults() {
if _, ok := auo.mutation.UpdatedAt(); !ok {
v := attachment.UpdateDefaultUpdatedAt()
auo.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (auo *AttachmentUpdateOne) check() error {
if v, ok := auo.mutation.GetType(); ok {
if err := attachment.TypeValidator(v); err != nil {
return &ValidationError{Name: "type", err: fmt.Errorf(`ent: validator failed for field "Attachment.type": %w`, err)}
}
}
if _, ok := auo.mutation.ItemID(); auo.mutation.ItemCleared() && !ok {
return errors.New(`ent: clearing a required unique edge "Attachment.item"`)
}
if _, ok := auo.mutation.DocumentID(); auo.mutation.DocumentCleared() && !ok {
return errors.New(`ent: clearing a required unique edge "Attachment.document"`)
}
return nil
}
func (auo *AttachmentUpdateOne) sqlSave(ctx context.Context) (_node *Attachment, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: attachment.Table,
Columns: attachment.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: attachment.FieldID,
},
},
}
id, ok := auo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Attachment.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := auo.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, attachment.FieldID)
for _, f := range fields {
if !attachment.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != attachment.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := auo.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := auo.mutation.UpdatedAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: attachment.FieldUpdatedAt,
})
}
if value, ok := auo.mutation.GetType(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeEnum,
Value: value,
Column: attachment.FieldType,
})
}
if auo.mutation.ItemCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: attachment.ItemTable,
Columns: []string{attachment.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 := auo.mutation.ItemIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: attachment.ItemTable,
Columns: []string{attachment.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 auo.mutation.DocumentCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: attachment.DocumentTable,
Columns: []string{attachment.DocumentColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: document.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := auo.mutation.DocumentIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: attachment.DocumentTable,
Columns: []string{attachment.DocumentColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: document.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &Attachment{config: auo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, auo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{attachment.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
return _node, nil
}

View file

@ -0,0 +1,177 @@
// 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/authtokens"
"github.com/hay-kot/homebox/backend/internal/data/ent/user"
)
// AuthTokens is the model entity for the AuthTokens schema.
type AuthTokens 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"`
// Token holds the value of the "token" field.
Token []byte `json:"token,omitempty"`
// ExpiresAt holds the value of the "expires_at" field.
ExpiresAt time.Time `json:"expires_at,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the AuthTokensQuery when eager-loading is set.
Edges AuthTokensEdges `json:"edges"`
user_auth_tokens *uuid.UUID
}
// AuthTokensEdges holds the relations/edges for other nodes in the graph.
type AuthTokensEdges struct {
// User holds the value of the user edge.
User *User `json:"user,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [1]bool
}
// UserOrErr returns the User value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e AuthTokensEdges) UserOrErr() (*User, error) {
if e.loadedTypes[0] {
if e.User == nil {
// Edge was loaded but was not found.
return nil, &NotFoundError{label: user.Label}
}
return e.User, nil
}
return nil, &NotLoadedError{edge: "user"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*AuthTokens) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case authtokens.FieldToken:
values[i] = new([]byte)
case authtokens.FieldCreatedAt, authtokens.FieldUpdatedAt, authtokens.FieldExpiresAt:
values[i] = new(sql.NullTime)
case authtokens.FieldID:
values[i] = new(uuid.UUID)
case authtokens.ForeignKeys[0]: // user_auth_tokens
values[i] = &sql.NullScanner{S: new(uuid.UUID)}
default:
return nil, fmt.Errorf("unexpected column %q for type AuthTokens", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the AuthTokens fields.
func (at *AuthTokens) 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 authtokens.FieldID:
if value, ok := values[i].(*uuid.UUID); !ok {
return fmt.Errorf("unexpected type %T for field id", values[i])
} else if value != nil {
at.ID = *value
}
case authtokens.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 {
at.CreatedAt = value.Time
}
case authtokens.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 {
at.UpdatedAt = value.Time
}
case authtokens.FieldToken:
if value, ok := values[i].(*[]byte); !ok {
return fmt.Errorf("unexpected type %T for field token", values[i])
} else if value != nil {
at.Token = *value
}
case authtokens.FieldExpiresAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field expires_at", values[i])
} else if value.Valid {
at.ExpiresAt = value.Time
}
case authtokens.ForeignKeys[0]:
if value, ok := values[i].(*sql.NullScanner); !ok {
return fmt.Errorf("unexpected type %T for field user_auth_tokens", values[i])
} else if value.Valid {
at.user_auth_tokens = new(uuid.UUID)
*at.user_auth_tokens = *value.S.(*uuid.UUID)
}
}
}
return nil
}
// QueryUser queries the "user" edge of the AuthTokens entity.
func (at *AuthTokens) QueryUser() *UserQuery {
return (&AuthTokensClient{config: at.config}).QueryUser(at)
}
// Update returns a builder for updating this AuthTokens.
// Note that you need to call AuthTokens.Unwrap() before calling this method if this AuthTokens
// was returned from a transaction, and the transaction was committed or rolled back.
func (at *AuthTokens) Update() *AuthTokensUpdateOne {
return (&AuthTokensClient{config: at.config}).UpdateOne(at)
}
// Unwrap unwraps the AuthTokens 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 (at *AuthTokens) Unwrap() *AuthTokens {
_tx, ok := at.config.driver.(*txDriver)
if !ok {
panic("ent: AuthTokens is not a transactional entity")
}
at.config.driver = _tx.drv
return at
}
// String implements the fmt.Stringer.
func (at *AuthTokens) String() string {
var builder strings.Builder
builder.WriteString("AuthTokens(")
builder.WriteString(fmt.Sprintf("id=%v, ", at.ID))
builder.WriteString("created_at=")
builder.WriteString(at.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(at.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("token=")
builder.WriteString(fmt.Sprintf("%v", at.Token))
builder.WriteString(", ")
builder.WriteString("expires_at=")
builder.WriteString(at.ExpiresAt.Format(time.ANSIC))
builder.WriteByte(')')
return builder.String()
}
// AuthTokensSlice is a parsable slice of AuthTokens.
type AuthTokensSlice []*AuthTokens
func (at AuthTokensSlice) config(cfg config) {
for _i := range at {
at[_i].config = cfg
}
}

View file

@ -0,0 +1,78 @@
// Code generated by ent, DO NOT EDIT.
package authtokens
import (
"time"
"github.com/google/uuid"
)
const (
// Label holds the string label denoting the authtokens type in the database.
Label = "auth_tokens"
// 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"
// FieldToken holds the string denoting the token field in the database.
FieldToken = "token"
// FieldExpiresAt holds the string denoting the expires_at field in the database.
FieldExpiresAt = "expires_at"
// EdgeUser holds the string denoting the user edge name in mutations.
EdgeUser = "user"
// Table holds the table name of the authtokens in the database.
Table = "auth_tokens"
// UserTable is the table that holds the user relation/edge.
UserTable = "auth_tokens"
// UserInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
UserInverseTable = "users"
// UserColumn is the table column denoting the user relation/edge.
UserColumn = "user_auth_tokens"
)
// Columns holds all SQL columns for authtokens fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldToken,
FieldExpiresAt,
}
// ForeignKeys holds the SQL foreign-keys that are owned by the "auth_tokens"
// table and are not defined as standalone fields in the schema.
var ForeignKeys = []string{
"user_auth_tokens",
}
// 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
}
}
for i := range ForeignKeys {
if column == ForeignKeys[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
// DefaultExpiresAt holds the default value on creation for the "expires_at" field.
DefaultExpiresAt func() time.Time
// DefaultID holds the default value on creation for the "id" field.
DefaultID func() uuid.UUID
)

View file

@ -0,0 +1,427 @@
// Code generated by ent, DO NOT EDIT.
package authtokens
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.AuthTokens {
return predicate.AuthTokens(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.AuthTokens {
return predicate.AuthTokens(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.AuthTokens {
return predicate.AuthTokens(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.AuthTokens {
return predicate.AuthTokens(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.AuthTokens {
return predicate.AuthTokens(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.AuthTokens {
return predicate.AuthTokens(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.AuthTokens {
return predicate.AuthTokens(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.AuthTokens {
return predicate.AuthTokens(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.AuthTokens {
return predicate.AuthTokens(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.AuthTokens {
return predicate.AuthTokens(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.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
})
}
// Token applies equality check predicate on the "token" field. It's identical to TokenEQ.
func Token(v []byte) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldToken), v))
})
}
// ExpiresAt applies equality check predicate on the "expires_at" field. It's identical to ExpiresAtEQ.
func ExpiresAt(v time.Time) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldExpiresAt), v))
})
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.AuthTokens {
return predicate.AuthTokens(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.AuthTokens {
return predicate.AuthTokens(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.AuthTokens {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.AuthTokens(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.AuthTokens {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.AuthTokens(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.AuthTokens {
return predicate.AuthTokens(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.AuthTokens {
return predicate.AuthTokens(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.AuthTokens {
return predicate.AuthTokens(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.AuthTokens {
return predicate.AuthTokens(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.AuthTokens {
return predicate.AuthTokens(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.AuthTokens {
return predicate.AuthTokens(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.AuthTokens {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.AuthTokens(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.AuthTokens {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.AuthTokens(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.AuthTokens {
return predicate.AuthTokens(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.AuthTokens {
return predicate.AuthTokens(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.AuthTokens {
return predicate.AuthTokens(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.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldUpdatedAt), v))
})
}
// TokenEQ applies the EQ predicate on the "token" field.
func TokenEQ(v []byte) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldToken), v))
})
}
// TokenNEQ applies the NEQ predicate on the "token" field.
func TokenNEQ(v []byte) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldToken), v))
})
}
// TokenIn applies the In predicate on the "token" field.
func TokenIn(vs ...[]byte) predicate.AuthTokens {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldToken), v...))
})
}
// TokenNotIn applies the NotIn predicate on the "token" field.
func TokenNotIn(vs ...[]byte) predicate.AuthTokens {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldToken), v...))
})
}
// TokenGT applies the GT predicate on the "token" field.
func TokenGT(v []byte) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldToken), v))
})
}
// TokenGTE applies the GTE predicate on the "token" field.
func TokenGTE(v []byte) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldToken), v))
})
}
// TokenLT applies the LT predicate on the "token" field.
func TokenLT(v []byte) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldToken), v))
})
}
// TokenLTE applies the LTE predicate on the "token" field.
func TokenLTE(v []byte) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldToken), v))
})
}
// ExpiresAtEQ applies the EQ predicate on the "expires_at" field.
func ExpiresAtEQ(v time.Time) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldExpiresAt), v))
})
}
// ExpiresAtNEQ applies the NEQ predicate on the "expires_at" field.
func ExpiresAtNEQ(v time.Time) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldExpiresAt), v))
})
}
// ExpiresAtIn applies the In predicate on the "expires_at" field.
func ExpiresAtIn(vs ...time.Time) predicate.AuthTokens {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldExpiresAt), v...))
})
}
// ExpiresAtNotIn applies the NotIn predicate on the "expires_at" field.
func ExpiresAtNotIn(vs ...time.Time) predicate.AuthTokens {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldExpiresAt), v...))
})
}
// ExpiresAtGT applies the GT predicate on the "expires_at" field.
func ExpiresAtGT(v time.Time) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldExpiresAt), v))
})
}
// ExpiresAtGTE applies the GTE predicate on the "expires_at" field.
func ExpiresAtGTE(v time.Time) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldExpiresAt), v))
})
}
// ExpiresAtLT applies the LT predicate on the "expires_at" field.
func ExpiresAtLT(v time.Time) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldExpiresAt), v))
})
}
// ExpiresAtLTE applies the LTE predicate on the "expires_at" field.
func ExpiresAtLTE(v time.Time) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldExpiresAt), v))
})
}
// HasUser applies the HasEdge predicate on the "user" edge.
func HasUser() predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(UserTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates).
func HasUserWith(preds ...predicate.User) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(UserInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn),
)
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.AuthTokens) predicate.AuthTokens {
return predicate.AuthTokens(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.AuthTokens) predicate.AuthTokens {
return predicate.AuthTokens(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.AuthTokens) predicate.AuthTokens {
return predicate.AuthTokens(func(s *sql.Selector) {
p(s.Not())
})
}

View file

@ -0,0 +1,384 @@
// 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/authtokens"
"github.com/hay-kot/homebox/backend/internal/data/ent/user"
)
// AuthTokensCreate is the builder for creating a AuthTokens entity.
type AuthTokensCreate struct {
config
mutation *AuthTokensMutation
hooks []Hook
}
// SetCreatedAt sets the "created_at" field.
func (atc *AuthTokensCreate) SetCreatedAt(t time.Time) *AuthTokensCreate {
atc.mutation.SetCreatedAt(t)
return atc
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (atc *AuthTokensCreate) SetNillableCreatedAt(t *time.Time) *AuthTokensCreate {
if t != nil {
atc.SetCreatedAt(*t)
}
return atc
}
// SetUpdatedAt sets the "updated_at" field.
func (atc *AuthTokensCreate) SetUpdatedAt(t time.Time) *AuthTokensCreate {
atc.mutation.SetUpdatedAt(t)
return atc
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (atc *AuthTokensCreate) SetNillableUpdatedAt(t *time.Time) *AuthTokensCreate {
if t != nil {
atc.SetUpdatedAt(*t)
}
return atc
}
// SetToken sets the "token" field.
func (atc *AuthTokensCreate) SetToken(b []byte) *AuthTokensCreate {
atc.mutation.SetToken(b)
return atc
}
// SetExpiresAt sets the "expires_at" field.
func (atc *AuthTokensCreate) SetExpiresAt(t time.Time) *AuthTokensCreate {
atc.mutation.SetExpiresAt(t)
return atc
}
// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil.
func (atc *AuthTokensCreate) SetNillableExpiresAt(t *time.Time) *AuthTokensCreate {
if t != nil {
atc.SetExpiresAt(*t)
}
return atc
}
// SetID sets the "id" field.
func (atc *AuthTokensCreate) SetID(u uuid.UUID) *AuthTokensCreate {
atc.mutation.SetID(u)
return atc
}
// SetNillableID sets the "id" field if the given value is not nil.
func (atc *AuthTokensCreate) SetNillableID(u *uuid.UUID) *AuthTokensCreate {
if u != nil {
atc.SetID(*u)
}
return atc
}
// SetUserID sets the "user" edge to the User entity by ID.
func (atc *AuthTokensCreate) SetUserID(id uuid.UUID) *AuthTokensCreate {
atc.mutation.SetUserID(id)
return atc
}
// SetNillableUserID sets the "user" edge to the User entity by ID if the given value is not nil.
func (atc *AuthTokensCreate) SetNillableUserID(id *uuid.UUID) *AuthTokensCreate {
if id != nil {
atc = atc.SetUserID(*id)
}
return atc
}
// SetUser sets the "user" edge to the User entity.
func (atc *AuthTokensCreate) SetUser(u *User) *AuthTokensCreate {
return atc.SetUserID(u.ID)
}
// Mutation returns the AuthTokensMutation object of the builder.
func (atc *AuthTokensCreate) Mutation() *AuthTokensMutation {
return atc.mutation
}
// Save creates the AuthTokens in the database.
func (atc *AuthTokensCreate) Save(ctx context.Context) (*AuthTokens, error) {
var (
err error
node *AuthTokens
)
atc.defaults()
if len(atc.hooks) == 0 {
if err = atc.check(); err != nil {
return nil, err
}
node, err = atc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*AuthTokensMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = atc.check(); err != nil {
return nil, err
}
atc.mutation = mutation
if node, err = atc.sqlSave(ctx); err != nil {
return nil, err
}
mutation.id = &node.ID
mutation.done = true
return node, err
})
for i := len(atc.hooks) - 1; i >= 0; i-- {
if atc.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = atc.hooks[i](mut)
}
v, err := mut.Mutate(ctx, atc.mutation)
if err != nil {
return nil, err
}
nv, ok := v.(*AuthTokens)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from AuthTokensMutation", v)
}
node = nv
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (atc *AuthTokensCreate) SaveX(ctx context.Context) *AuthTokens {
v, err := atc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (atc *AuthTokensCreate) Exec(ctx context.Context) error {
_, err := atc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (atc *AuthTokensCreate) ExecX(ctx context.Context) {
if err := atc.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (atc *AuthTokensCreate) defaults() {
if _, ok := atc.mutation.CreatedAt(); !ok {
v := authtokens.DefaultCreatedAt()
atc.mutation.SetCreatedAt(v)
}
if _, ok := atc.mutation.UpdatedAt(); !ok {
v := authtokens.DefaultUpdatedAt()
atc.mutation.SetUpdatedAt(v)
}
if _, ok := atc.mutation.ExpiresAt(); !ok {
v := authtokens.DefaultExpiresAt()
atc.mutation.SetExpiresAt(v)
}
if _, ok := atc.mutation.ID(); !ok {
v := authtokens.DefaultID()
atc.mutation.SetID(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (atc *AuthTokensCreate) check() error {
if _, ok := atc.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "AuthTokens.created_at"`)}
}
if _, ok := atc.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "AuthTokens.updated_at"`)}
}
if _, ok := atc.mutation.Token(); !ok {
return &ValidationError{Name: "token", err: errors.New(`ent: missing required field "AuthTokens.token"`)}
}
if _, ok := atc.mutation.ExpiresAt(); !ok {
return &ValidationError{Name: "expires_at", err: errors.New(`ent: missing required field "AuthTokens.expires_at"`)}
}
return nil
}
func (atc *AuthTokensCreate) sqlSave(ctx context.Context) (*AuthTokens, error) {
_node, _spec := atc.createSpec()
if err := sqlgraph.CreateNode(ctx, atc.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 (atc *AuthTokensCreate) createSpec() (*AuthTokens, *sqlgraph.CreateSpec) {
var (
_node = &AuthTokens{config: atc.config}
_spec = &sqlgraph.CreateSpec{
Table: authtokens.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: authtokens.FieldID,
},
}
)
if id, ok := atc.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = &id
}
if value, ok := atc.mutation.CreatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: authtokens.FieldCreatedAt,
})
_node.CreatedAt = value
}
if value, ok := atc.mutation.UpdatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: authtokens.FieldUpdatedAt,
})
_node.UpdatedAt = value
}
if value, ok := atc.mutation.Token(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: authtokens.FieldToken,
})
_node.Token = value
}
if value, ok := atc.mutation.ExpiresAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: authtokens.FieldExpiresAt,
})
_node.ExpiresAt = value
}
if nodes := atc.mutation.UserIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: authtokens.UserTable,
Columns: []string{authtokens.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: user.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.user_auth_tokens = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// AuthTokensCreateBulk is the builder for creating many AuthTokens entities in bulk.
type AuthTokensCreateBulk struct {
config
builders []*AuthTokensCreate
}
// Save creates the AuthTokens entities in the database.
func (atcb *AuthTokensCreateBulk) Save(ctx context.Context) ([]*AuthTokens, error) {
specs := make([]*sqlgraph.CreateSpec, len(atcb.builders))
nodes := make([]*AuthTokens, len(atcb.builders))
mutators := make([]Mutator, len(atcb.builders))
for i := range atcb.builders {
func(i int, root context.Context) {
builder := atcb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*AuthTokensMutation)
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, atcb.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, atcb.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, atcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (atcb *AuthTokensCreateBulk) SaveX(ctx context.Context) []*AuthTokens {
v, err := atcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (atcb *AuthTokensCreateBulk) Exec(ctx context.Context) error {
_, err := atcb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (atcb *AuthTokensCreateBulk) ExecX(ctx context.Context) {
if err := atcb.Exec(ctx); err != nil {
panic(err)
}
}

View file

@ -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/authtokens"
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
)
// AuthTokensDelete is the builder for deleting a AuthTokens entity.
type AuthTokensDelete struct {
config
hooks []Hook
mutation *AuthTokensMutation
}
// Where appends a list predicates to the AuthTokensDelete builder.
func (atd *AuthTokensDelete) Where(ps ...predicate.AuthTokens) *AuthTokensDelete {
atd.mutation.Where(ps...)
return atd
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (atd *AuthTokensDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(atd.hooks) == 0 {
affected, err = atd.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*AuthTokensMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
atd.mutation = mutation
affected, err = atd.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(atd.hooks) - 1; i >= 0; i-- {
if atd.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = atd.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, atd.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (atd *AuthTokensDelete) ExecX(ctx context.Context) int {
n, err := atd.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (atd *AuthTokensDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: authtokens.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: authtokens.FieldID,
},
},
}
if ps := atd.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, atd.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return affected, err
}
// AuthTokensDeleteOne is the builder for deleting a single AuthTokens entity.
type AuthTokensDeleteOne struct {
atd *AuthTokensDelete
}
// Exec executes the deletion query.
func (atdo *AuthTokensDeleteOne) Exec(ctx context.Context) error {
n, err := atdo.atd.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{authtokens.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (atdo *AuthTokensDeleteOne) ExecX(ctx context.Context) {
atdo.atd.ExecX(ctx)
}

View file

@ -0,0 +1,614 @@
// 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/authtokens"
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
"github.com/hay-kot/homebox/backend/internal/data/ent/user"
)
// AuthTokensQuery is the builder for querying AuthTokens entities.
type AuthTokensQuery struct {
config
limit *int
offset *int
unique *bool
order []OrderFunc
fields []string
predicates []predicate.AuthTokens
withUser *UserQuery
withFKs bool
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the AuthTokensQuery builder.
func (atq *AuthTokensQuery) Where(ps ...predicate.AuthTokens) *AuthTokensQuery {
atq.predicates = append(atq.predicates, ps...)
return atq
}
// Limit adds a limit step to the query.
func (atq *AuthTokensQuery) Limit(limit int) *AuthTokensQuery {
atq.limit = &limit
return atq
}
// Offset adds an offset step to the query.
func (atq *AuthTokensQuery) Offset(offset int) *AuthTokensQuery {
atq.offset = &offset
return atq
}
// 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 (atq *AuthTokensQuery) Unique(unique bool) *AuthTokensQuery {
atq.unique = &unique
return atq
}
// Order adds an order step to the query.
func (atq *AuthTokensQuery) Order(o ...OrderFunc) *AuthTokensQuery {
atq.order = append(atq.order, o...)
return atq
}
// QueryUser chains the current query on the "user" edge.
func (atq *AuthTokensQuery) QueryUser() *UserQuery {
query := &UserQuery{config: atq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := atq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := atq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(authtokens.Table, authtokens.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, authtokens.UserTable, authtokens.UserColumn),
)
fromU = sqlgraph.SetNeighbors(atq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first AuthTokens entity from the query.
// Returns a *NotFoundError when no AuthTokens was found.
func (atq *AuthTokensQuery) First(ctx context.Context) (*AuthTokens, error) {
nodes, err := atq.Limit(1).All(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{authtokens.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (atq *AuthTokensQuery) FirstX(ctx context.Context) *AuthTokens {
node, err := atq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first AuthTokens ID from the query.
// Returns a *NotFoundError when no AuthTokens ID was found.
func (atq *AuthTokensQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = atq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{authtokens.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (atq *AuthTokensQuery) FirstIDX(ctx context.Context) uuid.UUID {
id, err := atq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single AuthTokens entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one AuthTokens entity is found.
// Returns a *NotFoundError when no AuthTokens entities are found.
func (atq *AuthTokensQuery) Only(ctx context.Context) (*AuthTokens, error) {
nodes, err := atq.Limit(2).All(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{authtokens.Label}
default:
return nil, &NotSingularError{authtokens.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (atq *AuthTokensQuery) OnlyX(ctx context.Context) *AuthTokens {
node, err := atq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only AuthTokens ID in the query.
// Returns a *NotSingularError when more than one AuthTokens ID is found.
// Returns a *NotFoundError when no entities are found.
func (atq *AuthTokensQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = atq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{authtokens.Label}
default:
err = &NotSingularError{authtokens.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (atq *AuthTokensQuery) OnlyIDX(ctx context.Context) uuid.UUID {
id, err := atq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of AuthTokensSlice.
func (atq *AuthTokensQuery) All(ctx context.Context) ([]*AuthTokens, error) {
if err := atq.prepareQuery(ctx); err != nil {
return nil, err
}
return atq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (atq *AuthTokensQuery) AllX(ctx context.Context) []*AuthTokens {
nodes, err := atq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of AuthTokens IDs.
func (atq *AuthTokensQuery) IDs(ctx context.Context) ([]uuid.UUID, error) {
var ids []uuid.UUID
if err := atq.Select(authtokens.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (atq *AuthTokensQuery) IDsX(ctx context.Context) []uuid.UUID {
ids, err := atq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (atq *AuthTokensQuery) Count(ctx context.Context) (int, error) {
if err := atq.prepareQuery(ctx); err != nil {
return 0, err
}
return atq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (atq *AuthTokensQuery) CountX(ctx context.Context) int {
count, err := atq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (atq *AuthTokensQuery) Exist(ctx context.Context) (bool, error) {
if err := atq.prepareQuery(ctx); err != nil {
return false, err
}
return atq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (atq *AuthTokensQuery) ExistX(ctx context.Context) bool {
exist, err := atq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the AuthTokensQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (atq *AuthTokensQuery) Clone() *AuthTokensQuery {
if atq == nil {
return nil
}
return &AuthTokensQuery{
config: atq.config,
limit: atq.limit,
offset: atq.offset,
order: append([]OrderFunc{}, atq.order...),
predicates: append([]predicate.AuthTokens{}, atq.predicates...),
withUser: atq.withUser.Clone(),
// clone intermediate query.
sql: atq.sql.Clone(),
path: atq.path,
unique: atq.unique,
}
}
// WithUser tells the query-builder to eager-load the nodes that are connected to
// the "user" edge. The optional arguments are used to configure the query builder of the edge.
func (atq *AuthTokensQuery) WithUser(opts ...func(*UserQuery)) *AuthTokensQuery {
query := &UserQuery{config: atq.config}
for _, opt := range opts {
opt(query)
}
atq.withUser = query
return atq
}
// 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.AuthTokens.Query().
// GroupBy(authtokens.FieldCreatedAt).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (atq *AuthTokensQuery) GroupBy(field string, fields ...string) *AuthTokensGroupBy {
grbuild := &AuthTokensGroupBy{config: atq.config}
grbuild.fields = append([]string{field}, fields...)
grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := atq.prepareQuery(ctx); err != nil {
return nil, err
}
return atq.sqlQuery(ctx), nil
}
grbuild.label = authtokens.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.AuthTokens.Query().
// Select(authtokens.FieldCreatedAt).
// Scan(ctx, &v)
func (atq *AuthTokensQuery) Select(fields ...string) *AuthTokensSelect {
atq.fields = append(atq.fields, fields...)
selbuild := &AuthTokensSelect{AuthTokensQuery: atq}
selbuild.label = authtokens.Label
selbuild.flds, selbuild.scan = &atq.fields, selbuild.Scan
return selbuild
}
func (atq *AuthTokensQuery) prepareQuery(ctx context.Context) error {
for _, f := range atq.fields {
if !authtokens.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if atq.path != nil {
prev, err := atq.path(ctx)
if err != nil {
return err
}
atq.sql = prev
}
return nil
}
func (atq *AuthTokensQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AuthTokens, error) {
var (
nodes = []*AuthTokens{}
withFKs = atq.withFKs
_spec = atq.querySpec()
loadedTypes = [1]bool{
atq.withUser != nil,
}
)
if atq.withUser != nil {
withFKs = true
}
if withFKs {
_spec.Node.Columns = append(_spec.Node.Columns, authtokens.ForeignKeys...)
}
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*AuthTokens).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &AuthTokens{config: atq.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, atq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := atq.withUser; query != nil {
if err := atq.loadUser(ctx, query, nodes, nil,
func(n *AuthTokens, e *User) { n.Edges.User = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (atq *AuthTokensQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*AuthTokens, init func(*AuthTokens), assign func(*AuthTokens, *User)) error {
ids := make([]uuid.UUID, 0, len(nodes))
nodeids := make(map[uuid.UUID][]*AuthTokens)
for i := range nodes {
if nodes[i].user_auth_tokens == nil {
continue
}
fk := *nodes[i].user_auth_tokens
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
query.Where(user.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return fmt.Errorf(`unexpected foreign-key "user_auth_tokens" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (atq *AuthTokensQuery) sqlCount(ctx context.Context) (int, error) {
_spec := atq.querySpec()
_spec.Node.Columns = atq.fields
if len(atq.fields) > 0 {
_spec.Unique = atq.unique != nil && *atq.unique
}
return sqlgraph.CountNodes(ctx, atq.driver, _spec)
}
func (atq *AuthTokensQuery) sqlExist(ctx context.Context) (bool, error) {
switch _, err := atq.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 (atq *AuthTokensQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: authtokens.Table,
Columns: authtokens.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: authtokens.FieldID,
},
},
From: atq.sql,
Unique: true,
}
if unique := atq.unique; unique != nil {
_spec.Unique = *unique
}
if fields := atq.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, authtokens.FieldID)
for i := range fields {
if fields[i] != authtokens.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := atq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := atq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := atq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := atq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (atq *AuthTokensQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(atq.driver.Dialect())
t1 := builder.Table(authtokens.Table)
columns := atq.fields
if len(columns) == 0 {
columns = authtokens.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if atq.sql != nil {
selector = atq.sql
selector.Select(selector.Columns(columns...)...)
}
if atq.unique != nil && *atq.unique {
selector.Distinct()
}
for _, p := range atq.predicates {
p(selector)
}
for _, p := range atq.order {
p(selector)
}
if offset := atq.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 := atq.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// AuthTokensGroupBy is the group-by builder for AuthTokens entities.
type AuthTokensGroupBy 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 (atgb *AuthTokensGroupBy) Aggregate(fns ...AggregateFunc) *AuthTokensGroupBy {
atgb.fns = append(atgb.fns, fns...)
return atgb
}
// Scan applies the group-by query and scans the result into the given value.
func (atgb *AuthTokensGroupBy) Scan(ctx context.Context, v any) error {
query, err := atgb.path(ctx)
if err != nil {
return err
}
atgb.sql = query
return atgb.sqlScan(ctx, v)
}
func (atgb *AuthTokensGroupBy) sqlScan(ctx context.Context, v any) error {
for _, f := range atgb.fields {
if !authtokens.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := atgb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := atgb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (atgb *AuthTokensGroupBy) sqlQuery() *sql.Selector {
selector := atgb.sql.Select()
aggregation := make([]string, 0, len(atgb.fns))
for _, fn := range atgb.fns {
aggregation = append(aggregation, fn(selector))
}
// If no columns were selected in a custom aggregation function, the default
// selection is the fields used for "group-by", and the aggregation functions.
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(atgb.fields)+len(atgb.fns))
for _, f := range atgb.fields {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
return selector.GroupBy(selector.Columns(atgb.fields...)...)
}
// AuthTokensSelect is the builder for selecting fields of AuthTokens entities.
type AuthTokensSelect struct {
*AuthTokensQuery
selector
// intermediate query (i.e. traversal path).
sql *sql.Selector
}
// Scan applies the selector query and scans the result into the given value.
func (ats *AuthTokensSelect) Scan(ctx context.Context, v any) error {
if err := ats.prepareQuery(ctx); err != nil {
return err
}
ats.sql = ats.AuthTokensQuery.sqlQuery(ctx)
return ats.sqlScan(ctx, v)
}
func (ats *AuthTokensSelect) sqlScan(ctx context.Context, v any) error {
rows := &sql.Rows{}
query, args := ats.sql.Query()
if err := ats.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

View file

@ -0,0 +1,480 @@
// 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/authtokens"
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
"github.com/hay-kot/homebox/backend/internal/data/ent/user"
)
// AuthTokensUpdate is the builder for updating AuthTokens entities.
type AuthTokensUpdate struct {
config
hooks []Hook
mutation *AuthTokensMutation
}
// Where appends a list predicates to the AuthTokensUpdate builder.
func (atu *AuthTokensUpdate) Where(ps ...predicate.AuthTokens) *AuthTokensUpdate {
atu.mutation.Where(ps...)
return atu
}
// SetUpdatedAt sets the "updated_at" field.
func (atu *AuthTokensUpdate) SetUpdatedAt(t time.Time) *AuthTokensUpdate {
atu.mutation.SetUpdatedAt(t)
return atu
}
// SetToken sets the "token" field.
func (atu *AuthTokensUpdate) SetToken(b []byte) *AuthTokensUpdate {
atu.mutation.SetToken(b)
return atu
}
// SetExpiresAt sets the "expires_at" field.
func (atu *AuthTokensUpdate) SetExpiresAt(t time.Time) *AuthTokensUpdate {
atu.mutation.SetExpiresAt(t)
return atu
}
// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil.
func (atu *AuthTokensUpdate) SetNillableExpiresAt(t *time.Time) *AuthTokensUpdate {
if t != nil {
atu.SetExpiresAt(*t)
}
return atu
}
// SetUserID sets the "user" edge to the User entity by ID.
func (atu *AuthTokensUpdate) SetUserID(id uuid.UUID) *AuthTokensUpdate {
atu.mutation.SetUserID(id)
return atu
}
// SetNillableUserID sets the "user" edge to the User entity by ID if the given value is not nil.
func (atu *AuthTokensUpdate) SetNillableUserID(id *uuid.UUID) *AuthTokensUpdate {
if id != nil {
atu = atu.SetUserID(*id)
}
return atu
}
// SetUser sets the "user" edge to the User entity.
func (atu *AuthTokensUpdate) SetUser(u *User) *AuthTokensUpdate {
return atu.SetUserID(u.ID)
}
// Mutation returns the AuthTokensMutation object of the builder.
func (atu *AuthTokensUpdate) Mutation() *AuthTokensMutation {
return atu.mutation
}
// ClearUser clears the "user" edge to the User entity.
func (atu *AuthTokensUpdate) ClearUser() *AuthTokensUpdate {
atu.mutation.ClearUser()
return atu
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (atu *AuthTokensUpdate) Save(ctx context.Context) (int, error) {
var (
err error
affected int
)
atu.defaults()
if len(atu.hooks) == 0 {
affected, err = atu.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*AuthTokensMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
atu.mutation = mutation
affected, err = atu.sqlSave(ctx)
mutation.done = true
return affected, err
})
for i := len(atu.hooks) - 1; i >= 0; i-- {
if atu.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = atu.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, atu.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// SaveX is like Save, but panics if an error occurs.
func (atu *AuthTokensUpdate) SaveX(ctx context.Context) int {
affected, err := atu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (atu *AuthTokensUpdate) Exec(ctx context.Context) error {
_, err := atu.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (atu *AuthTokensUpdate) ExecX(ctx context.Context) {
if err := atu.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (atu *AuthTokensUpdate) defaults() {
if _, ok := atu.mutation.UpdatedAt(); !ok {
v := authtokens.UpdateDefaultUpdatedAt()
atu.mutation.SetUpdatedAt(v)
}
}
func (atu *AuthTokensUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: authtokens.Table,
Columns: authtokens.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: authtokens.FieldID,
},
},
}
if ps := atu.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := atu.mutation.UpdatedAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: authtokens.FieldUpdatedAt,
})
}
if value, ok := atu.mutation.Token(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: authtokens.FieldToken,
})
}
if value, ok := atu.mutation.ExpiresAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: authtokens.FieldExpiresAt,
})
}
if atu.mutation.UserCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: authtokens.UserTable,
Columns: []string{authtokens.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: user.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := atu.mutation.UserIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: authtokens.UserTable,
Columns: []string{authtokens.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: user.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, atu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{authtokens.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
return n, nil
}
// AuthTokensUpdateOne is the builder for updating a single AuthTokens entity.
type AuthTokensUpdateOne struct {
config
fields []string
hooks []Hook
mutation *AuthTokensMutation
}
// SetUpdatedAt sets the "updated_at" field.
func (atuo *AuthTokensUpdateOne) SetUpdatedAt(t time.Time) *AuthTokensUpdateOne {
atuo.mutation.SetUpdatedAt(t)
return atuo
}
// SetToken sets the "token" field.
func (atuo *AuthTokensUpdateOne) SetToken(b []byte) *AuthTokensUpdateOne {
atuo.mutation.SetToken(b)
return atuo
}
// SetExpiresAt sets the "expires_at" field.
func (atuo *AuthTokensUpdateOne) SetExpiresAt(t time.Time) *AuthTokensUpdateOne {
atuo.mutation.SetExpiresAt(t)
return atuo
}
// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil.
func (atuo *AuthTokensUpdateOne) SetNillableExpiresAt(t *time.Time) *AuthTokensUpdateOne {
if t != nil {
atuo.SetExpiresAt(*t)
}
return atuo
}
// SetUserID sets the "user" edge to the User entity by ID.
func (atuo *AuthTokensUpdateOne) SetUserID(id uuid.UUID) *AuthTokensUpdateOne {
atuo.mutation.SetUserID(id)
return atuo
}
// SetNillableUserID sets the "user" edge to the User entity by ID if the given value is not nil.
func (atuo *AuthTokensUpdateOne) SetNillableUserID(id *uuid.UUID) *AuthTokensUpdateOne {
if id != nil {
atuo = atuo.SetUserID(*id)
}
return atuo
}
// SetUser sets the "user" edge to the User entity.
func (atuo *AuthTokensUpdateOne) SetUser(u *User) *AuthTokensUpdateOne {
return atuo.SetUserID(u.ID)
}
// Mutation returns the AuthTokensMutation object of the builder.
func (atuo *AuthTokensUpdateOne) Mutation() *AuthTokensMutation {
return atuo.mutation
}
// ClearUser clears the "user" edge to the User entity.
func (atuo *AuthTokensUpdateOne) ClearUser() *AuthTokensUpdateOne {
atuo.mutation.ClearUser()
return atuo
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (atuo *AuthTokensUpdateOne) Select(field string, fields ...string) *AuthTokensUpdateOne {
atuo.fields = append([]string{field}, fields...)
return atuo
}
// Save executes the query and returns the updated AuthTokens entity.
func (atuo *AuthTokensUpdateOne) Save(ctx context.Context) (*AuthTokens, error) {
var (
err error
node *AuthTokens
)
atuo.defaults()
if len(atuo.hooks) == 0 {
node, err = atuo.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*AuthTokensMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
atuo.mutation = mutation
node, err = atuo.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(atuo.hooks) - 1; i >= 0; i-- {
if atuo.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = atuo.hooks[i](mut)
}
v, err := mut.Mutate(ctx, atuo.mutation)
if err != nil {
return nil, err
}
nv, ok := v.(*AuthTokens)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from AuthTokensMutation", v)
}
node = nv
}
return node, err
}
// SaveX is like Save, but panics if an error occurs.
func (atuo *AuthTokensUpdateOne) SaveX(ctx context.Context) *AuthTokens {
node, err := atuo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (atuo *AuthTokensUpdateOne) Exec(ctx context.Context) error {
_, err := atuo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (atuo *AuthTokensUpdateOne) ExecX(ctx context.Context) {
if err := atuo.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (atuo *AuthTokensUpdateOne) defaults() {
if _, ok := atuo.mutation.UpdatedAt(); !ok {
v := authtokens.UpdateDefaultUpdatedAt()
atuo.mutation.SetUpdatedAt(v)
}
}
func (atuo *AuthTokensUpdateOne) sqlSave(ctx context.Context) (_node *AuthTokens, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: authtokens.Table,
Columns: authtokens.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: authtokens.FieldID,
},
},
}
id, ok := atuo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "AuthTokens.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := atuo.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, authtokens.FieldID)
for _, f := range fields {
if !authtokens.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != authtokens.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := atuo.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := atuo.mutation.UpdatedAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: authtokens.FieldUpdatedAt,
})
}
if value, ok := atuo.mutation.Token(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: authtokens.FieldToken,
})
}
if value, ok := atuo.mutation.ExpiresAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: authtokens.FieldExpiresAt,
})
}
if atuo.mutation.UserCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: authtokens.UserTable,
Columns: []string{authtokens.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: user.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := atuo.mutation.UserIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: authtokens.UserTable,
Columns: []string{authtokens.UserColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: user.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &AuthTokens{config: atuo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, atuo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{authtokens.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
return _node, nil
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,69 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"entgo.io/ent"
"entgo.io/ent/dialect"
)
// Option function to configure the client.
type Option func(*config)
// Config is the configuration for the client and its builder.
type config struct {
// driver used for executing database requests.
driver dialect.Driver
// debug enable a debug logging.
debug bool
// log used for logging on debug mode.
log func(...any)
// hooks to execute on mutations.
hooks *hooks
}
// hooks per client, for fast access.
type hooks struct {
Attachment []ent.Hook
AuthTokens []ent.Hook
Document []ent.Hook
DocumentToken []ent.Hook
Group []ent.Hook
GroupInvitationToken []ent.Hook
Item []ent.Hook
ItemField []ent.Hook
Label []ent.Hook
Location []ent.Hook
User []ent.Hook
}
// Options applies the options on the config object.
func (c *config) options(opts ...Option) {
for _, opt := range opts {
opt(c)
}
if c.debug {
c.driver = dialect.Debug(c.driver, c.log)
}
}
// Debug enables debug logging on the ent.Driver.
func Debug() Option {
return func(c *config) {
c.debug = true
}
}
// Log sets the logging function for debug mode.
func Log(fn func(...any)) Option {
return func(c *config) {
c.log = fn
}
}
// Driver configures the client driver.
func Driver(driver dialect.Driver) Option {
return func(c *config) {
c.driver = driver
}
}

View file

@ -0,0 +1,33 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
)
type clientCtxKey struct{}
// FromContext returns a Client stored inside a context, or nil if there isn't one.
func FromContext(ctx context.Context) *Client {
c, _ := ctx.Value(clientCtxKey{}).(*Client)
return c
}
// NewContext returns a new context with the given Client attached.
func NewContext(parent context.Context, c *Client) context.Context {
return context.WithValue(parent, clientCtxKey{}, c)
}
type txCtxKey struct{}
// TxFromContext returns a Tx stored inside a context, or nil if there isn't one.
func TxFromContext(ctx context.Context) *Tx {
tx, _ := ctx.Value(txCtxKey{}).(*Tx)
return tx
}
// NewTxContext returns a new context with the given Tx attached.
func NewTxContext(parent context.Context, tx *Tx) context.Context {
return context.WithValue(parent, txCtxKey{}, tx)
}

View file

@ -0,0 +1,209 @@
// 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/document"
"github.com/hay-kot/homebox/backend/internal/data/ent/group"
)
// Document is the model entity for the Document schema.
type Document 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"`
// Title holds the value of the "title" field.
Title string `json:"title,omitempty"`
// Path holds the value of the "path" field.
Path string `json:"path,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the DocumentQuery when eager-loading is set.
Edges DocumentEdges `json:"edges"`
group_documents *uuid.UUID
}
// DocumentEdges holds the relations/edges for other nodes in the graph.
type DocumentEdges struct {
// Group holds the value of the group edge.
Group *Group `json:"group,omitempty"`
// DocumentTokens holds the value of the document_tokens edge.
DocumentTokens []*DocumentToken `json:"document_tokens,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 [3]bool
}
// GroupOrErr returns the Group value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e DocumentEdges) GroupOrErr() (*Group, error) {
if e.loadedTypes[0] {
if e.Group == nil {
// Edge was loaded but was not found.
return nil, &NotFoundError{label: group.Label}
}
return e.Group, nil
}
return nil, &NotLoadedError{edge: "group"}
}
// DocumentTokensOrErr returns the DocumentTokens value or an error if the edge
// was not loaded in eager-loading.
func (e DocumentEdges) DocumentTokensOrErr() ([]*DocumentToken, error) {
if e.loadedTypes[1] {
return e.DocumentTokens, nil
}
return nil, &NotLoadedError{edge: "document_tokens"}
}
// AttachmentsOrErr returns the Attachments value or an error if the edge
// was not loaded in eager-loading.
func (e DocumentEdges) AttachmentsOrErr() ([]*Attachment, error) {
if e.loadedTypes[2] {
return e.Attachments, nil
}
return nil, &NotLoadedError{edge: "attachments"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Document) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case document.FieldTitle, document.FieldPath:
values[i] = new(sql.NullString)
case document.FieldCreatedAt, document.FieldUpdatedAt:
values[i] = new(sql.NullTime)
case document.FieldID:
values[i] = new(uuid.UUID)
case document.ForeignKeys[0]: // group_documents
values[i] = &sql.NullScanner{S: new(uuid.UUID)}
default:
return nil, fmt.Errorf("unexpected column %q for type Document", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Document fields.
func (d *Document) 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 document.FieldID:
if value, ok := values[i].(*uuid.UUID); !ok {
return fmt.Errorf("unexpected type %T for field id", values[i])
} else if value != nil {
d.ID = *value
}
case document.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 {
d.CreatedAt = value.Time
}
case document.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 {
d.UpdatedAt = value.Time
}
case document.FieldTitle:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field title", values[i])
} else if value.Valid {
d.Title = value.String
}
case document.FieldPath:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field path", values[i])
} else if value.Valid {
d.Path = value.String
}
case document.ForeignKeys[0]:
if value, ok := values[i].(*sql.NullScanner); !ok {
return fmt.Errorf("unexpected type %T for field group_documents", values[i])
} else if value.Valid {
d.group_documents = new(uuid.UUID)
*d.group_documents = *value.S.(*uuid.UUID)
}
}
}
return nil
}
// QueryGroup queries the "group" edge of the Document entity.
func (d *Document) QueryGroup() *GroupQuery {
return (&DocumentClient{config: d.config}).QueryGroup(d)
}
// QueryDocumentTokens queries the "document_tokens" edge of the Document entity.
func (d *Document) QueryDocumentTokens() *DocumentTokenQuery {
return (&DocumentClient{config: d.config}).QueryDocumentTokens(d)
}
// QueryAttachments queries the "attachments" edge of the Document entity.
func (d *Document) QueryAttachments() *AttachmentQuery {
return (&DocumentClient{config: d.config}).QueryAttachments(d)
}
// Update returns a builder for updating this Document.
// Note that you need to call Document.Unwrap() before calling this method if this Document
// was returned from a transaction, and the transaction was committed or rolled back.
func (d *Document) Update() *DocumentUpdateOne {
return (&DocumentClient{config: d.config}).UpdateOne(d)
}
// Unwrap unwraps the Document 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 (d *Document) Unwrap() *Document {
_tx, ok := d.config.driver.(*txDriver)
if !ok {
panic("ent: Document is not a transactional entity")
}
d.config.driver = _tx.drv
return d
}
// String implements the fmt.Stringer.
func (d *Document) String() string {
var builder strings.Builder
builder.WriteString("Document(")
builder.WriteString(fmt.Sprintf("id=%v, ", d.ID))
builder.WriteString("created_at=")
builder.WriteString(d.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(d.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("title=")
builder.WriteString(d.Title)
builder.WriteString(", ")
builder.WriteString("path=")
builder.WriteString(d.Path)
builder.WriteByte(')')
return builder.String()
}
// Documents is a parsable slice of Document.
type Documents []*Document
func (d Documents) config(cfg config) {
for _i := range d {
d[_i].config = cfg
}
}

View file

@ -0,0 +1,98 @@
// Code generated by ent, DO NOT EDIT.
package document
import (
"time"
"github.com/google/uuid"
)
const (
// Label holds the string label denoting the document type in the database.
Label = "document"
// 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"
// FieldTitle holds the string denoting the title field in the database.
FieldTitle = "title"
// FieldPath holds the string denoting the path field in the database.
FieldPath = "path"
// EdgeGroup holds the string denoting the group edge name in mutations.
EdgeGroup = "group"
// EdgeDocumentTokens holds the string denoting the document_tokens edge name in mutations.
EdgeDocumentTokens = "document_tokens"
// EdgeAttachments holds the string denoting the attachments edge name in mutations.
EdgeAttachments = "attachments"
// Table holds the table name of the document in the database.
Table = "documents"
// GroupTable is the table that holds the group relation/edge.
GroupTable = "documents"
// GroupInverseTable is the table name for the Group entity.
// It exists in this package in order to avoid circular dependency with the "group" package.
GroupInverseTable = "groups"
// GroupColumn is the table column denoting the group relation/edge.
GroupColumn = "group_documents"
// DocumentTokensTable is the table that holds the document_tokens relation/edge.
DocumentTokensTable = "document_tokens"
// DocumentTokensInverseTable is the table name for the DocumentToken entity.
// It exists in this package in order to avoid circular dependency with the "documenttoken" package.
DocumentTokensInverseTable = "document_tokens"
// DocumentTokensColumn is the table column denoting the document_tokens relation/edge.
DocumentTokensColumn = "document_document_tokens"
// AttachmentsTable is the table that holds the attachments relation/edge.
AttachmentsTable = "attachments"
// AttachmentsInverseTable is the table name for the Attachment entity.
// It exists in this package in order to avoid circular dependency with the "attachment" package.
AttachmentsInverseTable = "attachments"
// AttachmentsColumn is the table column denoting the attachments relation/edge.
AttachmentsColumn = "document_attachments"
)
// Columns holds all SQL columns for document fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldTitle,
FieldPath,
}
// ForeignKeys holds the SQL foreign-keys that are owned by the "documents"
// table and are not defined as standalone fields in the schema.
var ForeignKeys = []string{
"group_documents",
}
// 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
}
}
for i := range ForeignKeys {
if column == ForeignKeys[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
// TitleValidator is a validator for the "title" field. It is called by the builders before save.
TitleValidator func(string) error
// PathValidator is a validator for the "path" field. It is called by the builders before save.
PathValidator func(string) error
// DefaultID holds the default value on creation for the "id" field.
DefaultID func() uuid.UUID
)

View file

@ -0,0 +1,553 @@
// Code generated by ent, DO NOT EDIT.
package document
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.Document {
return predicate.Document(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.Document {
return predicate.Document(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.Document {
return predicate.Document(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.Document {
return predicate.Document(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.Document {
return predicate.Document(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.Document {
return predicate.Document(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.Document {
return predicate.Document(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.Document {
return predicate.Document(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.Document {
return predicate.Document(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.Document {
return predicate.Document(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.Document {
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
})
}
// Title applies equality check predicate on the "title" field. It's identical to TitleEQ.
func Title(v string) predicate.Document {
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldTitle), v))
})
}
// Path applies equality check predicate on the "path" field. It's identical to PathEQ.
func Path(v string) predicate.Document {
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldPath), v))
})
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.Document {
return predicate.Document(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.Document {
return predicate.Document(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.Document {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Document(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.Document {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Document(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.Document {
return predicate.Document(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.Document {
return predicate.Document(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.Document {
return predicate.Document(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.Document {
return predicate.Document(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.Document {
return predicate.Document(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.Document {
return predicate.Document(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.Document {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Document(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.Document {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Document(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.Document {
return predicate.Document(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.Document {
return predicate.Document(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.Document {
return predicate.Document(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.Document {
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldUpdatedAt), v))
})
}
// TitleEQ applies the EQ predicate on the "title" field.
func TitleEQ(v string) predicate.Document {
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldTitle), v))
})
}
// TitleNEQ applies the NEQ predicate on the "title" field.
func TitleNEQ(v string) predicate.Document {
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldTitle), v))
})
}
// TitleIn applies the In predicate on the "title" field.
func TitleIn(vs ...string) predicate.Document {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldTitle), v...))
})
}
// TitleNotIn applies the NotIn predicate on the "title" field.
func TitleNotIn(vs ...string) predicate.Document {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldTitle), v...))
})
}
// TitleGT applies the GT predicate on the "title" field.
func TitleGT(v string) predicate.Document {
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldTitle), v))
})
}
// TitleGTE applies the GTE predicate on the "title" field.
func TitleGTE(v string) predicate.Document {
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldTitle), v))
})
}
// TitleLT applies the LT predicate on the "title" field.
func TitleLT(v string) predicate.Document {
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldTitle), v))
})
}
// TitleLTE applies the LTE predicate on the "title" field.
func TitleLTE(v string) predicate.Document {
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldTitle), v))
})
}
// TitleContains applies the Contains predicate on the "title" field.
func TitleContains(v string) predicate.Document {
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldTitle), v))
})
}
// TitleHasPrefix applies the HasPrefix predicate on the "title" field.
func TitleHasPrefix(v string) predicate.Document {
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldTitle), v))
})
}
// TitleHasSuffix applies the HasSuffix predicate on the "title" field.
func TitleHasSuffix(v string) predicate.Document {
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldTitle), v))
})
}
// TitleEqualFold applies the EqualFold predicate on the "title" field.
func TitleEqualFold(v string) predicate.Document {
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldTitle), v))
})
}
// TitleContainsFold applies the ContainsFold predicate on the "title" field.
func TitleContainsFold(v string) predicate.Document {
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldTitle), v))
})
}
// PathEQ applies the EQ predicate on the "path" field.
func PathEQ(v string) predicate.Document {
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldPath), v))
})
}
// PathNEQ applies the NEQ predicate on the "path" field.
func PathNEQ(v string) predicate.Document {
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldPath), v))
})
}
// PathIn applies the In predicate on the "path" field.
func PathIn(vs ...string) predicate.Document {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldPath), v...))
})
}
// PathNotIn applies the NotIn predicate on the "path" field.
func PathNotIn(vs ...string) predicate.Document {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldPath), v...))
})
}
// PathGT applies the GT predicate on the "path" field.
func PathGT(v string) predicate.Document {
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldPath), v))
})
}
// PathGTE applies the GTE predicate on the "path" field.
func PathGTE(v string) predicate.Document {
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldPath), v))
})
}
// PathLT applies the LT predicate on the "path" field.
func PathLT(v string) predicate.Document {
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldPath), v))
})
}
// PathLTE applies the LTE predicate on the "path" field.
func PathLTE(v string) predicate.Document {
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldPath), v))
})
}
// PathContains applies the Contains predicate on the "path" field.
func PathContains(v string) predicate.Document {
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldPath), v))
})
}
// PathHasPrefix applies the HasPrefix predicate on the "path" field.
func PathHasPrefix(v string) predicate.Document {
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldPath), v))
})
}
// PathHasSuffix applies the HasSuffix predicate on the "path" field.
func PathHasSuffix(v string) predicate.Document {
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldPath), v))
})
}
// PathEqualFold applies the EqualFold predicate on the "path" field.
func PathEqualFold(v string) predicate.Document {
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldPath), v))
})
}
// PathContainsFold applies the ContainsFold predicate on the "path" field.
func PathContainsFold(v string) predicate.Document {
return predicate.Document(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldPath), v))
})
}
// HasGroup applies the HasEdge predicate on the "group" edge.
func HasGroup() predicate.Document {
return predicate.Document(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(GroupTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasGroupWith applies the HasEdge predicate on the "group" edge with a given conditions (other predicates).
func HasGroupWith(preds ...predicate.Group) predicate.Document {
return predicate.Document(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(GroupInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn),
)
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasDocumentTokens applies the HasEdge predicate on the "document_tokens" edge.
func HasDocumentTokens() predicate.Document {
return predicate.Document(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(DocumentTokensTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, DocumentTokensTable, DocumentTokensColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasDocumentTokensWith applies the HasEdge predicate on the "document_tokens" edge with a given conditions (other predicates).
func HasDocumentTokensWith(preds ...predicate.DocumentToken) predicate.Document {
return predicate.Document(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(DocumentTokensInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, DocumentTokensTable, DocumentTokensColumn),
)
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.Document {
return predicate.Document(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(AttachmentsTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, AttachmentsTable, AttachmentsColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasAttachmentsWith applies the HasEdge predicate on the "attachments" edge with a given conditions (other predicates).
func HasAttachmentsWith(preds ...predicate.Attachment) predicate.Document {
return predicate.Document(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(AttachmentsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, AttachmentsTable, AttachmentsColumn),
)
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.Document) predicate.Document {
return predicate.Document(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.Document) predicate.Document {
return predicate.Document(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.Document) predicate.Document {
return predicate.Document(func(s *sql.Selector) {
p(s.Not())
})
}

View file

@ -0,0 +1,447 @@
// 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/attachment"
"github.com/hay-kot/homebox/backend/internal/data/ent/document"
"github.com/hay-kot/homebox/backend/internal/data/ent/documenttoken"
"github.com/hay-kot/homebox/backend/internal/data/ent/group"
)
// DocumentCreate is the builder for creating a Document entity.
type DocumentCreate struct {
config
mutation *DocumentMutation
hooks []Hook
}
// SetCreatedAt sets the "created_at" field.
func (dc *DocumentCreate) SetCreatedAt(t time.Time) *DocumentCreate {
dc.mutation.SetCreatedAt(t)
return dc
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (dc *DocumentCreate) SetNillableCreatedAt(t *time.Time) *DocumentCreate {
if t != nil {
dc.SetCreatedAt(*t)
}
return dc
}
// SetUpdatedAt sets the "updated_at" field.
func (dc *DocumentCreate) SetUpdatedAt(t time.Time) *DocumentCreate {
dc.mutation.SetUpdatedAt(t)
return dc
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (dc *DocumentCreate) SetNillableUpdatedAt(t *time.Time) *DocumentCreate {
if t != nil {
dc.SetUpdatedAt(*t)
}
return dc
}
// SetTitle sets the "title" field.
func (dc *DocumentCreate) SetTitle(s string) *DocumentCreate {
dc.mutation.SetTitle(s)
return dc
}
// SetPath sets the "path" field.
func (dc *DocumentCreate) SetPath(s string) *DocumentCreate {
dc.mutation.SetPath(s)
return dc
}
// SetID sets the "id" field.
func (dc *DocumentCreate) SetID(u uuid.UUID) *DocumentCreate {
dc.mutation.SetID(u)
return dc
}
// SetNillableID sets the "id" field if the given value is not nil.
func (dc *DocumentCreate) SetNillableID(u *uuid.UUID) *DocumentCreate {
if u != nil {
dc.SetID(*u)
}
return dc
}
// SetGroupID sets the "group" edge to the Group entity by ID.
func (dc *DocumentCreate) SetGroupID(id uuid.UUID) *DocumentCreate {
dc.mutation.SetGroupID(id)
return dc
}
// SetGroup sets the "group" edge to the Group entity.
func (dc *DocumentCreate) SetGroup(g *Group) *DocumentCreate {
return dc.SetGroupID(g.ID)
}
// AddDocumentTokenIDs adds the "document_tokens" edge to the DocumentToken entity by IDs.
func (dc *DocumentCreate) AddDocumentTokenIDs(ids ...uuid.UUID) *DocumentCreate {
dc.mutation.AddDocumentTokenIDs(ids...)
return dc
}
// AddDocumentTokens adds the "document_tokens" edges to the DocumentToken entity.
func (dc *DocumentCreate) AddDocumentTokens(d ...*DocumentToken) *DocumentCreate {
ids := make([]uuid.UUID, len(d))
for i := range d {
ids[i] = d[i].ID
}
return dc.AddDocumentTokenIDs(ids...)
}
// AddAttachmentIDs adds the "attachments" edge to the Attachment entity by IDs.
func (dc *DocumentCreate) AddAttachmentIDs(ids ...uuid.UUID) *DocumentCreate {
dc.mutation.AddAttachmentIDs(ids...)
return dc
}
// AddAttachments adds the "attachments" edges to the Attachment entity.
func (dc *DocumentCreate) AddAttachments(a ...*Attachment) *DocumentCreate {
ids := make([]uuid.UUID, len(a))
for i := range a {
ids[i] = a[i].ID
}
return dc.AddAttachmentIDs(ids...)
}
// Mutation returns the DocumentMutation object of the builder.
func (dc *DocumentCreate) Mutation() *DocumentMutation {
return dc.mutation
}
// Save creates the Document in the database.
func (dc *DocumentCreate) Save(ctx context.Context) (*Document, error) {
var (
err error
node *Document
)
dc.defaults()
if len(dc.hooks) == 0 {
if err = dc.check(); err != nil {
return nil, err
}
node, err = dc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*DocumentMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = dc.check(); err != nil {
return nil, err
}
dc.mutation = mutation
if node, err = dc.sqlSave(ctx); err != nil {
return nil, err
}
mutation.id = &node.ID
mutation.done = true
return node, err
})
for i := len(dc.hooks) - 1; i >= 0; i-- {
if dc.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = dc.hooks[i](mut)
}
v, err := mut.Mutate(ctx, dc.mutation)
if err != nil {
return nil, err
}
nv, ok := v.(*Document)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from DocumentMutation", v)
}
node = nv
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (dc *DocumentCreate) SaveX(ctx context.Context) *Document {
v, err := dc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (dc *DocumentCreate) Exec(ctx context.Context) error {
_, err := dc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (dc *DocumentCreate) ExecX(ctx context.Context) {
if err := dc.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (dc *DocumentCreate) defaults() {
if _, ok := dc.mutation.CreatedAt(); !ok {
v := document.DefaultCreatedAt()
dc.mutation.SetCreatedAt(v)
}
if _, ok := dc.mutation.UpdatedAt(); !ok {
v := document.DefaultUpdatedAt()
dc.mutation.SetUpdatedAt(v)
}
if _, ok := dc.mutation.ID(); !ok {
v := document.DefaultID()
dc.mutation.SetID(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (dc *DocumentCreate) check() error {
if _, ok := dc.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Document.created_at"`)}
}
if _, ok := dc.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Document.updated_at"`)}
}
if _, ok := dc.mutation.Title(); !ok {
return &ValidationError{Name: "title", err: errors.New(`ent: missing required field "Document.title"`)}
}
if v, ok := dc.mutation.Title(); ok {
if err := document.TitleValidator(v); err != nil {
return &ValidationError{Name: "title", err: fmt.Errorf(`ent: validator failed for field "Document.title": %w`, err)}
}
}
if _, ok := dc.mutation.Path(); !ok {
return &ValidationError{Name: "path", err: errors.New(`ent: missing required field "Document.path"`)}
}
if v, ok := dc.mutation.Path(); ok {
if err := document.PathValidator(v); err != nil {
return &ValidationError{Name: "path", err: fmt.Errorf(`ent: validator failed for field "Document.path": %w`, err)}
}
}
if _, ok := dc.mutation.GroupID(); !ok {
return &ValidationError{Name: "group", err: errors.New(`ent: missing required edge "Document.group"`)}
}
return nil
}
func (dc *DocumentCreate) sqlSave(ctx context.Context) (*Document, error) {
_node, _spec := dc.createSpec()
if err := sqlgraph.CreateNode(ctx, dc.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 (dc *DocumentCreate) createSpec() (*Document, *sqlgraph.CreateSpec) {
var (
_node = &Document{config: dc.config}
_spec = &sqlgraph.CreateSpec{
Table: document.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: document.FieldID,
},
}
)
if id, ok := dc.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = &id
}
if value, ok := dc.mutation.CreatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: document.FieldCreatedAt,
})
_node.CreatedAt = value
}
if value, ok := dc.mutation.UpdatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: document.FieldUpdatedAt,
})
_node.UpdatedAt = value
}
if value, ok := dc.mutation.Title(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: document.FieldTitle,
})
_node.Title = value
}
if value, ok := dc.mutation.Path(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: document.FieldPath,
})
_node.Path = value
}
if nodes := dc.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: document.GroupTable,
Columns: []string{document.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.group_documents = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := dc.mutation.DocumentTokensIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: document.DocumentTokensTable,
Columns: []string{document.DocumentTokensColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: documenttoken.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := dc.mutation.AttachmentsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: document.AttachmentsTable,
Columns: []string{document.AttachmentsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: attachment.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// DocumentCreateBulk is the builder for creating many Document entities in bulk.
type DocumentCreateBulk struct {
config
builders []*DocumentCreate
}
// Save creates the Document entities in the database.
func (dcb *DocumentCreateBulk) Save(ctx context.Context) ([]*Document, error) {
specs := make([]*sqlgraph.CreateSpec, len(dcb.builders))
nodes := make([]*Document, len(dcb.builders))
mutators := make([]Mutator, len(dcb.builders))
for i := range dcb.builders {
func(i int, root context.Context) {
builder := dcb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*DocumentMutation)
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, dcb.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, dcb.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, dcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (dcb *DocumentCreateBulk) SaveX(ctx context.Context) []*Document {
v, err := dcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (dcb *DocumentCreateBulk) Exec(ctx context.Context) error {
_, err := dcb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (dcb *DocumentCreateBulk) ExecX(ctx context.Context) {
if err := dcb.Exec(ctx); err != nil {
panic(err)
}
}

View file

@ -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/document"
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
)
// DocumentDelete is the builder for deleting a Document entity.
type DocumentDelete struct {
config
hooks []Hook
mutation *DocumentMutation
}
// Where appends a list predicates to the DocumentDelete builder.
func (dd *DocumentDelete) Where(ps ...predicate.Document) *DocumentDelete {
dd.mutation.Where(ps...)
return dd
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (dd *DocumentDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(dd.hooks) == 0 {
affected, err = dd.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*DocumentMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
dd.mutation = mutation
affected, err = dd.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(dd.hooks) - 1; i >= 0; i-- {
if dd.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = dd.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, dd.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (dd *DocumentDelete) ExecX(ctx context.Context) int {
n, err := dd.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (dd *DocumentDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: document.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: document.FieldID,
},
},
}
if ps := dd.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, dd.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return affected, err
}
// DocumentDeleteOne is the builder for deleting a single Document entity.
type DocumentDeleteOne struct {
dd *DocumentDelete
}
// Exec executes the deletion query.
func (ddo *DocumentDeleteOne) Exec(ctx context.Context) error {
n, err := ddo.dd.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{document.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (ddo *DocumentDeleteOne) ExecX(ctx context.Context) {
ddo.dd.ExecX(ctx)
}

View file

@ -0,0 +1,765 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"database/sql/driver"
"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/attachment"
"github.com/hay-kot/homebox/backend/internal/data/ent/document"
"github.com/hay-kot/homebox/backend/internal/data/ent/documenttoken"
"github.com/hay-kot/homebox/backend/internal/data/ent/group"
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
)
// DocumentQuery is the builder for querying Document entities.
type DocumentQuery struct {
config
limit *int
offset *int
unique *bool
order []OrderFunc
fields []string
predicates []predicate.Document
withGroup *GroupQuery
withDocumentTokens *DocumentTokenQuery
withAttachments *AttachmentQuery
withFKs bool
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the DocumentQuery builder.
func (dq *DocumentQuery) Where(ps ...predicate.Document) *DocumentQuery {
dq.predicates = append(dq.predicates, ps...)
return dq
}
// Limit adds a limit step to the query.
func (dq *DocumentQuery) Limit(limit int) *DocumentQuery {
dq.limit = &limit
return dq
}
// Offset adds an offset step to the query.
func (dq *DocumentQuery) Offset(offset int) *DocumentQuery {
dq.offset = &offset
return dq
}
// 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 (dq *DocumentQuery) Unique(unique bool) *DocumentQuery {
dq.unique = &unique
return dq
}
// Order adds an order step to the query.
func (dq *DocumentQuery) Order(o ...OrderFunc) *DocumentQuery {
dq.order = append(dq.order, o...)
return dq
}
// QueryGroup chains the current query on the "group" edge.
func (dq *DocumentQuery) QueryGroup() *GroupQuery {
query := &GroupQuery{config: dq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := dq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := dq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(document.Table, document.FieldID, selector),
sqlgraph.To(group.Table, group.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, document.GroupTable, document.GroupColumn),
)
fromU = sqlgraph.SetNeighbors(dq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryDocumentTokens chains the current query on the "document_tokens" edge.
func (dq *DocumentQuery) QueryDocumentTokens() *DocumentTokenQuery {
query := &DocumentTokenQuery{config: dq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := dq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := dq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(document.Table, document.FieldID, selector),
sqlgraph.To(documenttoken.Table, documenttoken.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, document.DocumentTokensTable, document.DocumentTokensColumn),
)
fromU = sqlgraph.SetNeighbors(dq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryAttachments chains the current query on the "attachments" edge.
func (dq *DocumentQuery) QueryAttachments() *AttachmentQuery {
query := &AttachmentQuery{config: dq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := dq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := dq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(document.Table, document.FieldID, selector),
sqlgraph.To(attachment.Table, attachment.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, document.AttachmentsTable, document.AttachmentsColumn),
)
fromU = sqlgraph.SetNeighbors(dq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Document entity from the query.
// Returns a *NotFoundError when no Document was found.
func (dq *DocumentQuery) First(ctx context.Context) (*Document, error) {
nodes, err := dq.Limit(1).All(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{document.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (dq *DocumentQuery) FirstX(ctx context.Context) *Document {
node, err := dq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Document ID from the query.
// Returns a *NotFoundError when no Document ID was found.
func (dq *DocumentQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = dq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{document.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (dq *DocumentQuery) FirstIDX(ctx context.Context) uuid.UUID {
id, err := dq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Document entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Document entity is found.
// Returns a *NotFoundError when no Document entities are found.
func (dq *DocumentQuery) Only(ctx context.Context) (*Document, error) {
nodes, err := dq.Limit(2).All(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{document.Label}
default:
return nil, &NotSingularError{document.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (dq *DocumentQuery) OnlyX(ctx context.Context) *Document {
node, err := dq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Document ID in the query.
// Returns a *NotSingularError when more than one Document ID is found.
// Returns a *NotFoundError when no entities are found.
func (dq *DocumentQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = dq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{document.Label}
default:
err = &NotSingularError{document.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (dq *DocumentQuery) OnlyIDX(ctx context.Context) uuid.UUID {
id, err := dq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Documents.
func (dq *DocumentQuery) All(ctx context.Context) ([]*Document, error) {
if err := dq.prepareQuery(ctx); err != nil {
return nil, err
}
return dq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (dq *DocumentQuery) AllX(ctx context.Context) []*Document {
nodes, err := dq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Document IDs.
func (dq *DocumentQuery) IDs(ctx context.Context) ([]uuid.UUID, error) {
var ids []uuid.UUID
if err := dq.Select(document.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (dq *DocumentQuery) IDsX(ctx context.Context) []uuid.UUID {
ids, err := dq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (dq *DocumentQuery) Count(ctx context.Context) (int, error) {
if err := dq.prepareQuery(ctx); err != nil {
return 0, err
}
return dq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (dq *DocumentQuery) CountX(ctx context.Context) int {
count, err := dq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (dq *DocumentQuery) Exist(ctx context.Context) (bool, error) {
if err := dq.prepareQuery(ctx); err != nil {
return false, err
}
return dq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (dq *DocumentQuery) ExistX(ctx context.Context) bool {
exist, err := dq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the DocumentQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (dq *DocumentQuery) Clone() *DocumentQuery {
if dq == nil {
return nil
}
return &DocumentQuery{
config: dq.config,
limit: dq.limit,
offset: dq.offset,
order: append([]OrderFunc{}, dq.order...),
predicates: append([]predicate.Document{}, dq.predicates...),
withGroup: dq.withGroup.Clone(),
withDocumentTokens: dq.withDocumentTokens.Clone(),
withAttachments: dq.withAttachments.Clone(),
// clone intermediate query.
sql: dq.sql.Clone(),
path: dq.path,
unique: dq.unique,
}
}
// WithGroup tells the query-builder to eager-load the nodes that are connected to
// the "group" edge. The optional arguments are used to configure the query builder of the edge.
func (dq *DocumentQuery) WithGroup(opts ...func(*GroupQuery)) *DocumentQuery {
query := &GroupQuery{config: dq.config}
for _, opt := range opts {
opt(query)
}
dq.withGroup = query
return dq
}
// WithDocumentTokens tells the query-builder to eager-load the nodes that are connected to
// the "document_tokens" edge. The optional arguments are used to configure the query builder of the edge.
func (dq *DocumentQuery) WithDocumentTokens(opts ...func(*DocumentTokenQuery)) *DocumentQuery {
query := &DocumentTokenQuery{config: dq.config}
for _, opt := range opts {
opt(query)
}
dq.withDocumentTokens = query
return dq
}
// 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 (dq *DocumentQuery) WithAttachments(opts ...func(*AttachmentQuery)) *DocumentQuery {
query := &AttachmentQuery{config: dq.config}
for _, opt := range opts {
opt(query)
}
dq.withAttachments = query
return dq
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// CreatedAt time.Time `json:"created_at,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Document.Query().
// GroupBy(document.FieldCreatedAt).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (dq *DocumentQuery) GroupBy(field string, fields ...string) *DocumentGroupBy {
grbuild := &DocumentGroupBy{config: dq.config}
grbuild.fields = append([]string{field}, fields...)
grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := dq.prepareQuery(ctx); err != nil {
return nil, err
}
return dq.sqlQuery(ctx), nil
}
grbuild.label = document.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.Document.Query().
// Select(document.FieldCreatedAt).
// Scan(ctx, &v)
func (dq *DocumentQuery) Select(fields ...string) *DocumentSelect {
dq.fields = append(dq.fields, fields...)
selbuild := &DocumentSelect{DocumentQuery: dq}
selbuild.label = document.Label
selbuild.flds, selbuild.scan = &dq.fields, selbuild.Scan
return selbuild
}
func (dq *DocumentQuery) prepareQuery(ctx context.Context) error {
for _, f := range dq.fields {
if !document.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if dq.path != nil {
prev, err := dq.path(ctx)
if err != nil {
return err
}
dq.sql = prev
}
return nil
}
func (dq *DocumentQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Document, error) {
var (
nodes = []*Document{}
withFKs = dq.withFKs
_spec = dq.querySpec()
loadedTypes = [3]bool{
dq.withGroup != nil,
dq.withDocumentTokens != nil,
dq.withAttachments != nil,
}
)
if dq.withGroup != nil {
withFKs = true
}
if withFKs {
_spec.Node.Columns = append(_spec.Node.Columns, document.ForeignKeys...)
}
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Document).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Document{config: dq.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, dq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := dq.withGroup; query != nil {
if err := dq.loadGroup(ctx, query, nodes, nil,
func(n *Document, e *Group) { n.Edges.Group = e }); err != nil {
return nil, err
}
}
if query := dq.withDocumentTokens; query != nil {
if err := dq.loadDocumentTokens(ctx, query, nodes,
func(n *Document) { n.Edges.DocumentTokens = []*DocumentToken{} },
func(n *Document, e *DocumentToken) { n.Edges.DocumentTokens = append(n.Edges.DocumentTokens, e) }); err != nil {
return nil, err
}
}
if query := dq.withAttachments; query != nil {
if err := dq.loadAttachments(ctx, query, nodes,
func(n *Document) { n.Edges.Attachments = []*Attachment{} },
func(n *Document, e *Attachment) { n.Edges.Attachments = append(n.Edges.Attachments, e) }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (dq *DocumentQuery) loadGroup(ctx context.Context, query *GroupQuery, nodes []*Document, init func(*Document), assign func(*Document, *Group)) error {
ids := make([]uuid.UUID, 0, len(nodes))
nodeids := make(map[uuid.UUID][]*Document)
for i := range nodes {
if nodes[i].group_documents == nil {
continue
}
fk := *nodes[i].group_documents
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
query.Where(group.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 "group_documents" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (dq *DocumentQuery) loadDocumentTokens(ctx context.Context, query *DocumentTokenQuery, nodes []*Document, init func(*Document), assign func(*Document, *DocumentToken)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[uuid.UUID]*Document)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
query.withFKs = true
query.Where(predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.InValues(document.DocumentTokensColumn, fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.document_document_tokens
if fk == nil {
return fmt.Errorf(`foreign-key "document_document_tokens" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected foreign-key "document_document_tokens" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (dq *DocumentQuery) loadAttachments(ctx context.Context, query *AttachmentQuery, nodes []*Document, init func(*Document), assign func(*Document, *Attachment)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[uuid.UUID]*Document)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
query.withFKs = true
query.Where(predicate.Attachment(func(s *sql.Selector) {
s.Where(sql.InValues(document.AttachmentsColumn, fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.document_attachments
if fk == nil {
return fmt.Errorf(`foreign-key "document_attachments" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected foreign-key "document_attachments" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (dq *DocumentQuery) sqlCount(ctx context.Context) (int, error) {
_spec := dq.querySpec()
_spec.Node.Columns = dq.fields
if len(dq.fields) > 0 {
_spec.Unique = dq.unique != nil && *dq.unique
}
return sqlgraph.CountNodes(ctx, dq.driver, _spec)
}
func (dq *DocumentQuery) sqlExist(ctx context.Context) (bool, error) {
switch _, err := dq.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 (dq *DocumentQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: document.Table,
Columns: document.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: document.FieldID,
},
},
From: dq.sql,
Unique: true,
}
if unique := dq.unique; unique != nil {
_spec.Unique = *unique
}
if fields := dq.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, document.FieldID)
for i := range fields {
if fields[i] != document.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := dq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := dq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := dq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := dq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (dq *DocumentQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(dq.driver.Dialect())
t1 := builder.Table(document.Table)
columns := dq.fields
if len(columns) == 0 {
columns = document.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if dq.sql != nil {
selector = dq.sql
selector.Select(selector.Columns(columns...)...)
}
if dq.unique != nil && *dq.unique {
selector.Distinct()
}
for _, p := range dq.predicates {
p(selector)
}
for _, p := range dq.order {
p(selector)
}
if offset := dq.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 := dq.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// DocumentGroupBy is the group-by builder for Document entities.
type DocumentGroupBy 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 (dgb *DocumentGroupBy) Aggregate(fns ...AggregateFunc) *DocumentGroupBy {
dgb.fns = append(dgb.fns, fns...)
return dgb
}
// Scan applies the group-by query and scans the result into the given value.
func (dgb *DocumentGroupBy) Scan(ctx context.Context, v any) error {
query, err := dgb.path(ctx)
if err != nil {
return err
}
dgb.sql = query
return dgb.sqlScan(ctx, v)
}
func (dgb *DocumentGroupBy) sqlScan(ctx context.Context, v any) error {
for _, f := range dgb.fields {
if !document.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := dgb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := dgb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (dgb *DocumentGroupBy) sqlQuery() *sql.Selector {
selector := dgb.sql.Select()
aggregation := make([]string, 0, len(dgb.fns))
for _, fn := range dgb.fns {
aggregation = append(aggregation, fn(selector))
}
// If no columns were selected in a custom aggregation function, the default
// selection is the fields used for "group-by", and the aggregation functions.
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(dgb.fields)+len(dgb.fns))
for _, f := range dgb.fields {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
return selector.GroupBy(selector.Columns(dgb.fields...)...)
}
// DocumentSelect is the builder for selecting fields of Document entities.
type DocumentSelect struct {
*DocumentQuery
selector
// intermediate query (i.e. traversal path).
sql *sql.Selector
}
// Scan applies the selector query and scans the result into the given value.
func (ds *DocumentSelect) Scan(ctx context.Context, v any) error {
if err := ds.prepareQuery(ctx); err != nil {
return err
}
ds.sql = ds.DocumentQuery.sqlQuery(ctx)
return ds.sqlScan(ctx, v)
}
func (ds *DocumentSelect) sqlScan(ctx context.Context, v any) error {
rows := &sql.Rows{}
query, args := ds.sql.Query()
if err := ds.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

View file

@ -0,0 +1,858 @@
// 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/attachment"
"github.com/hay-kot/homebox/backend/internal/data/ent/document"
"github.com/hay-kot/homebox/backend/internal/data/ent/documenttoken"
"github.com/hay-kot/homebox/backend/internal/data/ent/group"
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
)
// DocumentUpdate is the builder for updating Document entities.
type DocumentUpdate struct {
config
hooks []Hook
mutation *DocumentMutation
}
// Where appends a list predicates to the DocumentUpdate builder.
func (du *DocumentUpdate) Where(ps ...predicate.Document) *DocumentUpdate {
du.mutation.Where(ps...)
return du
}
// SetUpdatedAt sets the "updated_at" field.
func (du *DocumentUpdate) SetUpdatedAt(t time.Time) *DocumentUpdate {
du.mutation.SetUpdatedAt(t)
return du
}
// SetTitle sets the "title" field.
func (du *DocumentUpdate) SetTitle(s string) *DocumentUpdate {
du.mutation.SetTitle(s)
return du
}
// SetPath sets the "path" field.
func (du *DocumentUpdate) SetPath(s string) *DocumentUpdate {
du.mutation.SetPath(s)
return du
}
// SetGroupID sets the "group" edge to the Group entity by ID.
func (du *DocumentUpdate) SetGroupID(id uuid.UUID) *DocumentUpdate {
du.mutation.SetGroupID(id)
return du
}
// SetGroup sets the "group" edge to the Group entity.
func (du *DocumentUpdate) SetGroup(g *Group) *DocumentUpdate {
return du.SetGroupID(g.ID)
}
// AddDocumentTokenIDs adds the "document_tokens" edge to the DocumentToken entity by IDs.
func (du *DocumentUpdate) AddDocumentTokenIDs(ids ...uuid.UUID) *DocumentUpdate {
du.mutation.AddDocumentTokenIDs(ids...)
return du
}
// AddDocumentTokens adds the "document_tokens" edges to the DocumentToken entity.
func (du *DocumentUpdate) AddDocumentTokens(d ...*DocumentToken) *DocumentUpdate {
ids := make([]uuid.UUID, len(d))
for i := range d {
ids[i] = d[i].ID
}
return du.AddDocumentTokenIDs(ids...)
}
// AddAttachmentIDs adds the "attachments" edge to the Attachment entity by IDs.
func (du *DocumentUpdate) AddAttachmentIDs(ids ...uuid.UUID) *DocumentUpdate {
du.mutation.AddAttachmentIDs(ids...)
return du
}
// AddAttachments adds the "attachments" edges to the Attachment entity.
func (du *DocumentUpdate) AddAttachments(a ...*Attachment) *DocumentUpdate {
ids := make([]uuid.UUID, len(a))
for i := range a {
ids[i] = a[i].ID
}
return du.AddAttachmentIDs(ids...)
}
// Mutation returns the DocumentMutation object of the builder.
func (du *DocumentUpdate) Mutation() *DocumentMutation {
return du.mutation
}
// ClearGroup clears the "group" edge to the Group entity.
func (du *DocumentUpdate) ClearGroup() *DocumentUpdate {
du.mutation.ClearGroup()
return du
}
// ClearDocumentTokens clears all "document_tokens" edges to the DocumentToken entity.
func (du *DocumentUpdate) ClearDocumentTokens() *DocumentUpdate {
du.mutation.ClearDocumentTokens()
return du
}
// RemoveDocumentTokenIDs removes the "document_tokens" edge to DocumentToken entities by IDs.
func (du *DocumentUpdate) RemoveDocumentTokenIDs(ids ...uuid.UUID) *DocumentUpdate {
du.mutation.RemoveDocumentTokenIDs(ids...)
return du
}
// RemoveDocumentTokens removes "document_tokens" edges to DocumentToken entities.
func (du *DocumentUpdate) RemoveDocumentTokens(d ...*DocumentToken) *DocumentUpdate {
ids := make([]uuid.UUID, len(d))
for i := range d {
ids[i] = d[i].ID
}
return du.RemoveDocumentTokenIDs(ids...)
}
// ClearAttachments clears all "attachments" edges to the Attachment entity.
func (du *DocumentUpdate) ClearAttachments() *DocumentUpdate {
du.mutation.ClearAttachments()
return du
}
// RemoveAttachmentIDs removes the "attachments" edge to Attachment entities by IDs.
func (du *DocumentUpdate) RemoveAttachmentIDs(ids ...uuid.UUID) *DocumentUpdate {
du.mutation.RemoveAttachmentIDs(ids...)
return du
}
// RemoveAttachments removes "attachments" edges to Attachment entities.
func (du *DocumentUpdate) RemoveAttachments(a ...*Attachment) *DocumentUpdate {
ids := make([]uuid.UUID, len(a))
for i := range a {
ids[i] = a[i].ID
}
return du.RemoveAttachmentIDs(ids...)
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (du *DocumentUpdate) Save(ctx context.Context) (int, error) {
var (
err error
affected int
)
du.defaults()
if len(du.hooks) == 0 {
if err = du.check(); err != nil {
return 0, err
}
affected, err = du.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*DocumentMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = du.check(); err != nil {
return 0, err
}
du.mutation = mutation
affected, err = du.sqlSave(ctx)
mutation.done = true
return affected, err
})
for i := len(du.hooks) - 1; i >= 0; i-- {
if du.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = du.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, du.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// SaveX is like Save, but panics if an error occurs.
func (du *DocumentUpdate) SaveX(ctx context.Context) int {
affected, err := du.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (du *DocumentUpdate) Exec(ctx context.Context) error {
_, err := du.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (du *DocumentUpdate) ExecX(ctx context.Context) {
if err := du.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (du *DocumentUpdate) defaults() {
if _, ok := du.mutation.UpdatedAt(); !ok {
v := document.UpdateDefaultUpdatedAt()
du.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (du *DocumentUpdate) check() error {
if v, ok := du.mutation.Title(); ok {
if err := document.TitleValidator(v); err != nil {
return &ValidationError{Name: "title", err: fmt.Errorf(`ent: validator failed for field "Document.title": %w`, err)}
}
}
if v, ok := du.mutation.Path(); ok {
if err := document.PathValidator(v); err != nil {
return &ValidationError{Name: "path", err: fmt.Errorf(`ent: validator failed for field "Document.path": %w`, err)}
}
}
if _, ok := du.mutation.GroupID(); du.mutation.GroupCleared() && !ok {
return errors.New(`ent: clearing a required unique edge "Document.group"`)
}
return nil
}
func (du *DocumentUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: document.Table,
Columns: document.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: document.FieldID,
},
},
}
if ps := du.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := du.mutation.UpdatedAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: document.FieldUpdatedAt,
})
}
if value, ok := du.mutation.Title(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: document.FieldTitle,
})
}
if value, ok := du.mutation.Path(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: document.FieldPath,
})
}
if du.mutation.GroupCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: document.GroupTable,
Columns: []string{document.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := du.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: document.GroupTable,
Columns: []string{document.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if du.mutation.DocumentTokensCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: document.DocumentTokensTable,
Columns: []string{document.DocumentTokensColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: documenttoken.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := du.mutation.RemovedDocumentTokensIDs(); len(nodes) > 0 && !du.mutation.DocumentTokensCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: document.DocumentTokensTable,
Columns: []string{document.DocumentTokensColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: documenttoken.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := du.mutation.DocumentTokensIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: document.DocumentTokensTable,
Columns: []string{document.DocumentTokensColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: documenttoken.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if du.mutation.AttachmentsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: document.AttachmentsTable,
Columns: []string{document.AttachmentsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: attachment.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := du.mutation.RemovedAttachmentsIDs(); len(nodes) > 0 && !du.mutation.AttachmentsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: document.AttachmentsTable,
Columns: []string{document.AttachmentsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: attachment.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := du.mutation.AttachmentsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: document.AttachmentsTable,
Columns: []string{document.AttachmentsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: attachment.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if n, err = sqlgraph.UpdateNodes(ctx, du.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{document.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
return n, nil
}
// DocumentUpdateOne is the builder for updating a single Document entity.
type DocumentUpdateOne struct {
config
fields []string
hooks []Hook
mutation *DocumentMutation
}
// SetUpdatedAt sets the "updated_at" field.
func (duo *DocumentUpdateOne) SetUpdatedAt(t time.Time) *DocumentUpdateOne {
duo.mutation.SetUpdatedAt(t)
return duo
}
// SetTitle sets the "title" field.
func (duo *DocumentUpdateOne) SetTitle(s string) *DocumentUpdateOne {
duo.mutation.SetTitle(s)
return duo
}
// SetPath sets the "path" field.
func (duo *DocumentUpdateOne) SetPath(s string) *DocumentUpdateOne {
duo.mutation.SetPath(s)
return duo
}
// SetGroupID sets the "group" edge to the Group entity by ID.
func (duo *DocumentUpdateOne) SetGroupID(id uuid.UUID) *DocumentUpdateOne {
duo.mutation.SetGroupID(id)
return duo
}
// SetGroup sets the "group" edge to the Group entity.
func (duo *DocumentUpdateOne) SetGroup(g *Group) *DocumentUpdateOne {
return duo.SetGroupID(g.ID)
}
// AddDocumentTokenIDs adds the "document_tokens" edge to the DocumentToken entity by IDs.
func (duo *DocumentUpdateOne) AddDocumentTokenIDs(ids ...uuid.UUID) *DocumentUpdateOne {
duo.mutation.AddDocumentTokenIDs(ids...)
return duo
}
// AddDocumentTokens adds the "document_tokens" edges to the DocumentToken entity.
func (duo *DocumentUpdateOne) AddDocumentTokens(d ...*DocumentToken) *DocumentUpdateOne {
ids := make([]uuid.UUID, len(d))
for i := range d {
ids[i] = d[i].ID
}
return duo.AddDocumentTokenIDs(ids...)
}
// AddAttachmentIDs adds the "attachments" edge to the Attachment entity by IDs.
func (duo *DocumentUpdateOne) AddAttachmentIDs(ids ...uuid.UUID) *DocumentUpdateOne {
duo.mutation.AddAttachmentIDs(ids...)
return duo
}
// AddAttachments adds the "attachments" edges to the Attachment entity.
func (duo *DocumentUpdateOne) AddAttachments(a ...*Attachment) *DocumentUpdateOne {
ids := make([]uuid.UUID, len(a))
for i := range a {
ids[i] = a[i].ID
}
return duo.AddAttachmentIDs(ids...)
}
// Mutation returns the DocumentMutation object of the builder.
func (duo *DocumentUpdateOne) Mutation() *DocumentMutation {
return duo.mutation
}
// ClearGroup clears the "group" edge to the Group entity.
func (duo *DocumentUpdateOne) ClearGroup() *DocumentUpdateOne {
duo.mutation.ClearGroup()
return duo
}
// ClearDocumentTokens clears all "document_tokens" edges to the DocumentToken entity.
func (duo *DocumentUpdateOne) ClearDocumentTokens() *DocumentUpdateOne {
duo.mutation.ClearDocumentTokens()
return duo
}
// RemoveDocumentTokenIDs removes the "document_tokens" edge to DocumentToken entities by IDs.
func (duo *DocumentUpdateOne) RemoveDocumentTokenIDs(ids ...uuid.UUID) *DocumentUpdateOne {
duo.mutation.RemoveDocumentTokenIDs(ids...)
return duo
}
// RemoveDocumentTokens removes "document_tokens" edges to DocumentToken entities.
func (duo *DocumentUpdateOne) RemoveDocumentTokens(d ...*DocumentToken) *DocumentUpdateOne {
ids := make([]uuid.UUID, len(d))
for i := range d {
ids[i] = d[i].ID
}
return duo.RemoveDocumentTokenIDs(ids...)
}
// ClearAttachments clears all "attachments" edges to the Attachment entity.
func (duo *DocumentUpdateOne) ClearAttachments() *DocumentUpdateOne {
duo.mutation.ClearAttachments()
return duo
}
// RemoveAttachmentIDs removes the "attachments" edge to Attachment entities by IDs.
func (duo *DocumentUpdateOne) RemoveAttachmentIDs(ids ...uuid.UUID) *DocumentUpdateOne {
duo.mutation.RemoveAttachmentIDs(ids...)
return duo
}
// RemoveAttachments removes "attachments" edges to Attachment entities.
func (duo *DocumentUpdateOne) RemoveAttachments(a ...*Attachment) *DocumentUpdateOne {
ids := make([]uuid.UUID, len(a))
for i := range a {
ids[i] = a[i].ID
}
return duo.RemoveAttachmentIDs(ids...)
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (duo *DocumentUpdateOne) Select(field string, fields ...string) *DocumentUpdateOne {
duo.fields = append([]string{field}, fields...)
return duo
}
// Save executes the query and returns the updated Document entity.
func (duo *DocumentUpdateOne) Save(ctx context.Context) (*Document, error) {
var (
err error
node *Document
)
duo.defaults()
if len(duo.hooks) == 0 {
if err = duo.check(); err != nil {
return nil, err
}
node, err = duo.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*DocumentMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = duo.check(); err != nil {
return nil, err
}
duo.mutation = mutation
node, err = duo.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(duo.hooks) - 1; i >= 0; i-- {
if duo.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = duo.hooks[i](mut)
}
v, err := mut.Mutate(ctx, duo.mutation)
if err != nil {
return nil, err
}
nv, ok := v.(*Document)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from DocumentMutation", v)
}
node = nv
}
return node, err
}
// SaveX is like Save, but panics if an error occurs.
func (duo *DocumentUpdateOne) SaveX(ctx context.Context) *Document {
node, err := duo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (duo *DocumentUpdateOne) Exec(ctx context.Context) error {
_, err := duo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (duo *DocumentUpdateOne) ExecX(ctx context.Context) {
if err := duo.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (duo *DocumentUpdateOne) defaults() {
if _, ok := duo.mutation.UpdatedAt(); !ok {
v := document.UpdateDefaultUpdatedAt()
duo.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (duo *DocumentUpdateOne) check() error {
if v, ok := duo.mutation.Title(); ok {
if err := document.TitleValidator(v); err != nil {
return &ValidationError{Name: "title", err: fmt.Errorf(`ent: validator failed for field "Document.title": %w`, err)}
}
}
if v, ok := duo.mutation.Path(); ok {
if err := document.PathValidator(v); err != nil {
return &ValidationError{Name: "path", err: fmt.Errorf(`ent: validator failed for field "Document.path": %w`, err)}
}
}
if _, ok := duo.mutation.GroupID(); duo.mutation.GroupCleared() && !ok {
return errors.New(`ent: clearing a required unique edge "Document.group"`)
}
return nil
}
func (duo *DocumentUpdateOne) sqlSave(ctx context.Context) (_node *Document, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: document.Table,
Columns: document.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: document.FieldID,
},
},
}
id, ok := duo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Document.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := duo.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, document.FieldID)
for _, f := range fields {
if !document.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != document.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := duo.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := duo.mutation.UpdatedAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: document.FieldUpdatedAt,
})
}
if value, ok := duo.mutation.Title(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: document.FieldTitle,
})
}
if value, ok := duo.mutation.Path(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: document.FieldPath,
})
}
if duo.mutation.GroupCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: document.GroupTable,
Columns: []string{document.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := duo.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: document.GroupTable,
Columns: []string{document.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if duo.mutation.DocumentTokensCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: document.DocumentTokensTable,
Columns: []string{document.DocumentTokensColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: documenttoken.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := duo.mutation.RemovedDocumentTokensIDs(); len(nodes) > 0 && !duo.mutation.DocumentTokensCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: document.DocumentTokensTable,
Columns: []string{document.DocumentTokensColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: documenttoken.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := duo.mutation.DocumentTokensIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: document.DocumentTokensTable,
Columns: []string{document.DocumentTokensColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: documenttoken.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if duo.mutation.AttachmentsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: document.AttachmentsTable,
Columns: []string{document.AttachmentsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: attachment.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := duo.mutation.RemovedAttachmentsIDs(); len(nodes) > 0 && !duo.mutation.AttachmentsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: document.AttachmentsTable,
Columns: []string{document.AttachmentsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: attachment.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := duo.mutation.AttachmentsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: document.AttachmentsTable,
Columns: []string{document.AttachmentsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: attachment.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &Document{config: duo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, duo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{document.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
return _node, nil
}

View file

@ -0,0 +1,190 @@
// 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/document"
"github.com/hay-kot/homebox/backend/internal/data/ent/documenttoken"
)
// DocumentToken is the model entity for the DocumentToken schema.
type DocumentToken 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"`
// Token holds the value of the "token" field.
Token []byte `json:"token,omitempty"`
// Uses holds the value of the "uses" field.
Uses int `json:"uses,omitempty"`
// ExpiresAt holds the value of the "expires_at" field.
ExpiresAt time.Time `json:"expires_at,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the DocumentTokenQuery when eager-loading is set.
Edges DocumentTokenEdges `json:"edges"`
document_document_tokens *uuid.UUID
}
// DocumentTokenEdges holds the relations/edges for other nodes in the graph.
type DocumentTokenEdges struct {
// Document holds the value of the document edge.
Document *Document `json:"document,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [1]bool
}
// DocumentOrErr returns the Document value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e DocumentTokenEdges) DocumentOrErr() (*Document, error) {
if e.loadedTypes[0] {
if e.Document == nil {
// Edge was loaded but was not found.
return nil, &NotFoundError{label: document.Label}
}
return e.Document, nil
}
return nil, &NotLoadedError{edge: "document"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*DocumentToken) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case documenttoken.FieldToken:
values[i] = new([]byte)
case documenttoken.FieldUses:
values[i] = new(sql.NullInt64)
case documenttoken.FieldCreatedAt, documenttoken.FieldUpdatedAt, documenttoken.FieldExpiresAt:
values[i] = new(sql.NullTime)
case documenttoken.FieldID:
values[i] = new(uuid.UUID)
case documenttoken.ForeignKeys[0]: // document_document_tokens
values[i] = &sql.NullScanner{S: new(uuid.UUID)}
default:
return nil, fmt.Errorf("unexpected column %q for type DocumentToken", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the DocumentToken fields.
func (dt *DocumentToken) 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 documenttoken.FieldID:
if value, ok := values[i].(*uuid.UUID); !ok {
return fmt.Errorf("unexpected type %T for field id", values[i])
} else if value != nil {
dt.ID = *value
}
case documenttoken.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 {
dt.CreatedAt = value.Time
}
case documenttoken.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 {
dt.UpdatedAt = value.Time
}
case documenttoken.FieldToken:
if value, ok := values[i].(*[]byte); !ok {
return fmt.Errorf("unexpected type %T for field token", values[i])
} else if value != nil {
dt.Token = *value
}
case documenttoken.FieldUses:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field uses", values[i])
} else if value.Valid {
dt.Uses = int(value.Int64)
}
case documenttoken.FieldExpiresAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field expires_at", values[i])
} else if value.Valid {
dt.ExpiresAt = value.Time
}
case documenttoken.ForeignKeys[0]:
if value, ok := values[i].(*sql.NullScanner); !ok {
return fmt.Errorf("unexpected type %T for field document_document_tokens", values[i])
} else if value.Valid {
dt.document_document_tokens = new(uuid.UUID)
*dt.document_document_tokens = *value.S.(*uuid.UUID)
}
}
}
return nil
}
// QueryDocument queries the "document" edge of the DocumentToken entity.
func (dt *DocumentToken) QueryDocument() *DocumentQuery {
return (&DocumentTokenClient{config: dt.config}).QueryDocument(dt)
}
// Update returns a builder for updating this DocumentToken.
// Note that you need to call DocumentToken.Unwrap() before calling this method if this DocumentToken
// was returned from a transaction, and the transaction was committed or rolled back.
func (dt *DocumentToken) Update() *DocumentTokenUpdateOne {
return (&DocumentTokenClient{config: dt.config}).UpdateOne(dt)
}
// Unwrap unwraps the DocumentToken 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 (dt *DocumentToken) Unwrap() *DocumentToken {
_tx, ok := dt.config.driver.(*txDriver)
if !ok {
panic("ent: DocumentToken is not a transactional entity")
}
dt.config.driver = _tx.drv
return dt
}
// String implements the fmt.Stringer.
func (dt *DocumentToken) String() string {
var builder strings.Builder
builder.WriteString("DocumentToken(")
builder.WriteString(fmt.Sprintf("id=%v, ", dt.ID))
builder.WriteString("created_at=")
builder.WriteString(dt.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(dt.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("token=")
builder.WriteString(fmt.Sprintf("%v", dt.Token))
builder.WriteString(", ")
builder.WriteString("uses=")
builder.WriteString(fmt.Sprintf("%v", dt.Uses))
builder.WriteString(", ")
builder.WriteString("expires_at=")
builder.WriteString(dt.ExpiresAt.Format(time.ANSIC))
builder.WriteByte(')')
return builder.String()
}
// DocumentTokens is a parsable slice of DocumentToken.
type DocumentTokens []*DocumentToken
func (dt DocumentTokens) config(cfg config) {
for _i := range dt {
dt[_i].config = cfg
}
}

View file

@ -0,0 +1,85 @@
// Code generated by ent, DO NOT EDIT.
package documenttoken
import (
"time"
"github.com/google/uuid"
)
const (
// Label holds the string label denoting the documenttoken type in the database.
Label = "document_token"
// 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"
// FieldToken holds the string denoting the token field in the database.
FieldToken = "token"
// FieldUses holds the string denoting the uses field in the database.
FieldUses = "uses"
// FieldExpiresAt holds the string denoting the expires_at field in the database.
FieldExpiresAt = "expires_at"
// EdgeDocument holds the string denoting the document edge name in mutations.
EdgeDocument = "document"
// Table holds the table name of the documenttoken in the database.
Table = "document_tokens"
// DocumentTable is the table that holds the document relation/edge.
DocumentTable = "document_tokens"
// DocumentInverseTable is the table name for the Document entity.
// It exists in this package in order to avoid circular dependency with the "document" package.
DocumentInverseTable = "documents"
// DocumentColumn is the table column denoting the document relation/edge.
DocumentColumn = "document_document_tokens"
)
// Columns holds all SQL columns for documenttoken fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldToken,
FieldUses,
FieldExpiresAt,
}
// ForeignKeys holds the SQL foreign-keys that are owned by the "document_tokens"
// table and are not defined as standalone fields in the schema.
var ForeignKeys = []string{
"document_document_tokens",
}
// 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
}
}
for i := range ForeignKeys {
if column == ForeignKeys[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
// TokenValidator is a validator for the "token" field. It is called by the builders before save.
TokenValidator func([]byte) error
// DefaultUses holds the default value on creation for the "uses" field.
DefaultUses int
// DefaultExpiresAt holds the default value on creation for the "expires_at" field.
DefaultExpiresAt func() time.Time
// DefaultID holds the default value on creation for the "id" field.
DefaultID func() uuid.UUID
)

View file

@ -0,0 +1,498 @@
// Code generated by ent, DO NOT EDIT.
package documenttoken
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.DocumentToken {
return predicate.DocumentToken(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.DocumentToken {
return predicate.DocumentToken(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.DocumentToken {
return predicate.DocumentToken(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.DocumentToken {
return predicate.DocumentToken(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.DocumentToken {
return predicate.DocumentToken(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.DocumentToken {
return predicate.DocumentToken(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.DocumentToken {
return predicate.DocumentToken(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.DocumentToken {
return predicate.DocumentToken(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.DocumentToken {
return predicate.DocumentToken(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.DocumentToken {
return predicate.DocumentToken(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.DocumentToken {
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
})
}
// Token applies equality check predicate on the "token" field. It's identical to TokenEQ.
func Token(v []byte) predicate.DocumentToken {
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldToken), v))
})
}
// Uses applies equality check predicate on the "uses" field. It's identical to UsesEQ.
func Uses(v int) predicate.DocumentToken {
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUses), v))
})
}
// ExpiresAt applies equality check predicate on the "expires_at" field. It's identical to ExpiresAtEQ.
func ExpiresAt(v time.Time) predicate.DocumentToken {
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldExpiresAt), v))
})
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.DocumentToken {
return predicate.DocumentToken(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.DocumentToken {
return predicate.DocumentToken(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.DocumentToken {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DocumentToken(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.DocumentToken {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DocumentToken(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.DocumentToken {
return predicate.DocumentToken(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.DocumentToken {
return predicate.DocumentToken(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.DocumentToken {
return predicate.DocumentToken(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.DocumentToken {
return predicate.DocumentToken(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.DocumentToken {
return predicate.DocumentToken(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.DocumentToken {
return predicate.DocumentToken(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.DocumentToken {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DocumentToken(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.DocumentToken {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DocumentToken(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.DocumentToken {
return predicate.DocumentToken(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.DocumentToken {
return predicate.DocumentToken(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.DocumentToken {
return predicate.DocumentToken(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.DocumentToken {
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldUpdatedAt), v))
})
}
// TokenEQ applies the EQ predicate on the "token" field.
func TokenEQ(v []byte) predicate.DocumentToken {
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldToken), v))
})
}
// TokenNEQ applies the NEQ predicate on the "token" field.
func TokenNEQ(v []byte) predicate.DocumentToken {
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldToken), v))
})
}
// TokenIn applies the In predicate on the "token" field.
func TokenIn(vs ...[]byte) predicate.DocumentToken {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldToken), v...))
})
}
// TokenNotIn applies the NotIn predicate on the "token" field.
func TokenNotIn(vs ...[]byte) predicate.DocumentToken {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldToken), v...))
})
}
// TokenGT applies the GT predicate on the "token" field.
func TokenGT(v []byte) predicate.DocumentToken {
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldToken), v))
})
}
// TokenGTE applies the GTE predicate on the "token" field.
func TokenGTE(v []byte) predicate.DocumentToken {
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldToken), v))
})
}
// TokenLT applies the LT predicate on the "token" field.
func TokenLT(v []byte) predicate.DocumentToken {
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldToken), v))
})
}
// TokenLTE applies the LTE predicate on the "token" field.
func TokenLTE(v []byte) predicate.DocumentToken {
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldToken), v))
})
}
// UsesEQ applies the EQ predicate on the "uses" field.
func UsesEQ(v int) predicate.DocumentToken {
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUses), v))
})
}
// UsesNEQ applies the NEQ predicate on the "uses" field.
func UsesNEQ(v int) predicate.DocumentToken {
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldUses), v))
})
}
// UsesIn applies the In predicate on the "uses" field.
func UsesIn(vs ...int) predicate.DocumentToken {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldUses), v...))
})
}
// UsesNotIn applies the NotIn predicate on the "uses" field.
func UsesNotIn(vs ...int) predicate.DocumentToken {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldUses), v...))
})
}
// UsesGT applies the GT predicate on the "uses" field.
func UsesGT(v int) predicate.DocumentToken {
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldUses), v))
})
}
// UsesGTE applies the GTE predicate on the "uses" field.
func UsesGTE(v int) predicate.DocumentToken {
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldUses), v))
})
}
// UsesLT applies the LT predicate on the "uses" field.
func UsesLT(v int) predicate.DocumentToken {
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldUses), v))
})
}
// UsesLTE applies the LTE predicate on the "uses" field.
func UsesLTE(v int) predicate.DocumentToken {
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldUses), v))
})
}
// ExpiresAtEQ applies the EQ predicate on the "expires_at" field.
func ExpiresAtEQ(v time.Time) predicate.DocumentToken {
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldExpiresAt), v))
})
}
// ExpiresAtNEQ applies the NEQ predicate on the "expires_at" field.
func ExpiresAtNEQ(v time.Time) predicate.DocumentToken {
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldExpiresAt), v))
})
}
// ExpiresAtIn applies the In predicate on the "expires_at" field.
func ExpiresAtIn(vs ...time.Time) predicate.DocumentToken {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldExpiresAt), v...))
})
}
// ExpiresAtNotIn applies the NotIn predicate on the "expires_at" field.
func ExpiresAtNotIn(vs ...time.Time) predicate.DocumentToken {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldExpiresAt), v...))
})
}
// ExpiresAtGT applies the GT predicate on the "expires_at" field.
func ExpiresAtGT(v time.Time) predicate.DocumentToken {
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldExpiresAt), v))
})
}
// ExpiresAtGTE applies the GTE predicate on the "expires_at" field.
func ExpiresAtGTE(v time.Time) predicate.DocumentToken {
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldExpiresAt), v))
})
}
// ExpiresAtLT applies the LT predicate on the "expires_at" field.
func ExpiresAtLT(v time.Time) predicate.DocumentToken {
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldExpiresAt), v))
})
}
// ExpiresAtLTE applies the LTE predicate on the "expires_at" field.
func ExpiresAtLTE(v time.Time) predicate.DocumentToken {
return predicate.DocumentToken(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldExpiresAt), v))
})
}
// HasDocument applies the HasEdge predicate on the "document" edge.
func HasDocument() predicate.DocumentToken {
return predicate.DocumentToken(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(DocumentTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, DocumentTable, DocumentColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasDocumentWith applies the HasEdge predicate on the "document" edge with a given conditions (other predicates).
func HasDocumentWith(preds ...predicate.Document) predicate.DocumentToken {
return predicate.DocumentToken(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(DocumentInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, DocumentTable, DocumentColumn),
)
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.DocumentToken) predicate.DocumentToken {
return predicate.DocumentToken(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.DocumentToken) predicate.DocumentToken {
return predicate.DocumentToken(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.DocumentToken) predicate.DocumentToken {
return predicate.DocumentToken(func(s *sql.Selector) {
p(s.Not())
})
}

View file

@ -0,0 +1,418 @@
// 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/document"
"github.com/hay-kot/homebox/backend/internal/data/ent/documenttoken"
)
// DocumentTokenCreate is the builder for creating a DocumentToken entity.
type DocumentTokenCreate struct {
config
mutation *DocumentTokenMutation
hooks []Hook
}
// SetCreatedAt sets the "created_at" field.
func (dtc *DocumentTokenCreate) SetCreatedAt(t time.Time) *DocumentTokenCreate {
dtc.mutation.SetCreatedAt(t)
return dtc
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (dtc *DocumentTokenCreate) SetNillableCreatedAt(t *time.Time) *DocumentTokenCreate {
if t != nil {
dtc.SetCreatedAt(*t)
}
return dtc
}
// SetUpdatedAt sets the "updated_at" field.
func (dtc *DocumentTokenCreate) SetUpdatedAt(t time.Time) *DocumentTokenCreate {
dtc.mutation.SetUpdatedAt(t)
return dtc
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (dtc *DocumentTokenCreate) SetNillableUpdatedAt(t *time.Time) *DocumentTokenCreate {
if t != nil {
dtc.SetUpdatedAt(*t)
}
return dtc
}
// SetToken sets the "token" field.
func (dtc *DocumentTokenCreate) SetToken(b []byte) *DocumentTokenCreate {
dtc.mutation.SetToken(b)
return dtc
}
// SetUses sets the "uses" field.
func (dtc *DocumentTokenCreate) SetUses(i int) *DocumentTokenCreate {
dtc.mutation.SetUses(i)
return dtc
}
// SetNillableUses sets the "uses" field if the given value is not nil.
func (dtc *DocumentTokenCreate) SetNillableUses(i *int) *DocumentTokenCreate {
if i != nil {
dtc.SetUses(*i)
}
return dtc
}
// SetExpiresAt sets the "expires_at" field.
func (dtc *DocumentTokenCreate) SetExpiresAt(t time.Time) *DocumentTokenCreate {
dtc.mutation.SetExpiresAt(t)
return dtc
}
// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil.
func (dtc *DocumentTokenCreate) SetNillableExpiresAt(t *time.Time) *DocumentTokenCreate {
if t != nil {
dtc.SetExpiresAt(*t)
}
return dtc
}
// SetID sets the "id" field.
func (dtc *DocumentTokenCreate) SetID(u uuid.UUID) *DocumentTokenCreate {
dtc.mutation.SetID(u)
return dtc
}
// SetNillableID sets the "id" field if the given value is not nil.
func (dtc *DocumentTokenCreate) SetNillableID(u *uuid.UUID) *DocumentTokenCreate {
if u != nil {
dtc.SetID(*u)
}
return dtc
}
// SetDocumentID sets the "document" edge to the Document entity by ID.
func (dtc *DocumentTokenCreate) SetDocumentID(id uuid.UUID) *DocumentTokenCreate {
dtc.mutation.SetDocumentID(id)
return dtc
}
// SetNillableDocumentID sets the "document" edge to the Document entity by ID if the given value is not nil.
func (dtc *DocumentTokenCreate) SetNillableDocumentID(id *uuid.UUID) *DocumentTokenCreate {
if id != nil {
dtc = dtc.SetDocumentID(*id)
}
return dtc
}
// SetDocument sets the "document" edge to the Document entity.
func (dtc *DocumentTokenCreate) SetDocument(d *Document) *DocumentTokenCreate {
return dtc.SetDocumentID(d.ID)
}
// Mutation returns the DocumentTokenMutation object of the builder.
func (dtc *DocumentTokenCreate) Mutation() *DocumentTokenMutation {
return dtc.mutation
}
// Save creates the DocumentToken in the database.
func (dtc *DocumentTokenCreate) Save(ctx context.Context) (*DocumentToken, error) {
var (
err error
node *DocumentToken
)
dtc.defaults()
if len(dtc.hooks) == 0 {
if err = dtc.check(); err != nil {
return nil, err
}
node, err = dtc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*DocumentTokenMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = dtc.check(); err != nil {
return nil, err
}
dtc.mutation = mutation
if node, err = dtc.sqlSave(ctx); err != nil {
return nil, err
}
mutation.id = &node.ID
mutation.done = true
return node, err
})
for i := len(dtc.hooks) - 1; i >= 0; i-- {
if dtc.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = dtc.hooks[i](mut)
}
v, err := mut.Mutate(ctx, dtc.mutation)
if err != nil {
return nil, err
}
nv, ok := v.(*DocumentToken)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from DocumentTokenMutation", v)
}
node = nv
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (dtc *DocumentTokenCreate) SaveX(ctx context.Context) *DocumentToken {
v, err := dtc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (dtc *DocumentTokenCreate) Exec(ctx context.Context) error {
_, err := dtc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (dtc *DocumentTokenCreate) ExecX(ctx context.Context) {
if err := dtc.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (dtc *DocumentTokenCreate) defaults() {
if _, ok := dtc.mutation.CreatedAt(); !ok {
v := documenttoken.DefaultCreatedAt()
dtc.mutation.SetCreatedAt(v)
}
if _, ok := dtc.mutation.UpdatedAt(); !ok {
v := documenttoken.DefaultUpdatedAt()
dtc.mutation.SetUpdatedAt(v)
}
if _, ok := dtc.mutation.Uses(); !ok {
v := documenttoken.DefaultUses
dtc.mutation.SetUses(v)
}
if _, ok := dtc.mutation.ExpiresAt(); !ok {
v := documenttoken.DefaultExpiresAt()
dtc.mutation.SetExpiresAt(v)
}
if _, ok := dtc.mutation.ID(); !ok {
v := documenttoken.DefaultID()
dtc.mutation.SetID(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (dtc *DocumentTokenCreate) check() error {
if _, ok := dtc.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "DocumentToken.created_at"`)}
}
if _, ok := dtc.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "DocumentToken.updated_at"`)}
}
if _, ok := dtc.mutation.Token(); !ok {
return &ValidationError{Name: "token", err: errors.New(`ent: missing required field "DocumentToken.token"`)}
}
if v, ok := dtc.mutation.Token(); ok {
if err := documenttoken.TokenValidator(v); err != nil {
return &ValidationError{Name: "token", err: fmt.Errorf(`ent: validator failed for field "DocumentToken.token": %w`, err)}
}
}
if _, ok := dtc.mutation.Uses(); !ok {
return &ValidationError{Name: "uses", err: errors.New(`ent: missing required field "DocumentToken.uses"`)}
}
if _, ok := dtc.mutation.ExpiresAt(); !ok {
return &ValidationError{Name: "expires_at", err: errors.New(`ent: missing required field "DocumentToken.expires_at"`)}
}
return nil
}
func (dtc *DocumentTokenCreate) sqlSave(ctx context.Context) (*DocumentToken, error) {
_node, _spec := dtc.createSpec()
if err := sqlgraph.CreateNode(ctx, dtc.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 (dtc *DocumentTokenCreate) createSpec() (*DocumentToken, *sqlgraph.CreateSpec) {
var (
_node = &DocumentToken{config: dtc.config}
_spec = &sqlgraph.CreateSpec{
Table: documenttoken.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: documenttoken.FieldID,
},
}
)
if id, ok := dtc.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = &id
}
if value, ok := dtc.mutation.CreatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: documenttoken.FieldCreatedAt,
})
_node.CreatedAt = value
}
if value, ok := dtc.mutation.UpdatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: documenttoken.FieldUpdatedAt,
})
_node.UpdatedAt = value
}
if value, ok := dtc.mutation.Token(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: documenttoken.FieldToken,
})
_node.Token = value
}
if value, ok := dtc.mutation.Uses(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: documenttoken.FieldUses,
})
_node.Uses = value
}
if value, ok := dtc.mutation.ExpiresAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: documenttoken.FieldExpiresAt,
})
_node.ExpiresAt = value
}
if nodes := dtc.mutation.DocumentIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: documenttoken.DocumentTable,
Columns: []string{documenttoken.DocumentColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: document.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.document_document_tokens = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// DocumentTokenCreateBulk is the builder for creating many DocumentToken entities in bulk.
type DocumentTokenCreateBulk struct {
config
builders []*DocumentTokenCreate
}
// Save creates the DocumentToken entities in the database.
func (dtcb *DocumentTokenCreateBulk) Save(ctx context.Context) ([]*DocumentToken, error) {
specs := make([]*sqlgraph.CreateSpec, len(dtcb.builders))
nodes := make([]*DocumentToken, len(dtcb.builders))
mutators := make([]Mutator, len(dtcb.builders))
for i := range dtcb.builders {
func(i int, root context.Context) {
builder := dtcb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*DocumentTokenMutation)
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, dtcb.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, dtcb.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, dtcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (dtcb *DocumentTokenCreateBulk) SaveX(ctx context.Context) []*DocumentToken {
v, err := dtcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (dtcb *DocumentTokenCreateBulk) Exec(ctx context.Context) error {
_, err := dtcb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (dtcb *DocumentTokenCreateBulk) ExecX(ctx context.Context) {
if err := dtcb.Exec(ctx); err != nil {
panic(err)
}
}

View file

@ -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/documenttoken"
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
)
// DocumentTokenDelete is the builder for deleting a DocumentToken entity.
type DocumentTokenDelete struct {
config
hooks []Hook
mutation *DocumentTokenMutation
}
// Where appends a list predicates to the DocumentTokenDelete builder.
func (dtd *DocumentTokenDelete) Where(ps ...predicate.DocumentToken) *DocumentTokenDelete {
dtd.mutation.Where(ps...)
return dtd
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (dtd *DocumentTokenDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(dtd.hooks) == 0 {
affected, err = dtd.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*DocumentTokenMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
dtd.mutation = mutation
affected, err = dtd.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(dtd.hooks) - 1; i >= 0; i-- {
if dtd.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = dtd.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, dtd.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (dtd *DocumentTokenDelete) ExecX(ctx context.Context) int {
n, err := dtd.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (dtd *DocumentTokenDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: documenttoken.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: documenttoken.FieldID,
},
},
}
if ps := dtd.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, dtd.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return affected, err
}
// DocumentTokenDeleteOne is the builder for deleting a single DocumentToken entity.
type DocumentTokenDeleteOne struct {
dtd *DocumentTokenDelete
}
// Exec executes the deletion query.
func (dtdo *DocumentTokenDeleteOne) Exec(ctx context.Context) error {
n, err := dtdo.dtd.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{documenttoken.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (dtdo *DocumentTokenDeleteOne) ExecX(ctx context.Context) {
dtdo.dtd.ExecX(ctx)
}

View file

@ -0,0 +1,614 @@
// 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/document"
"github.com/hay-kot/homebox/backend/internal/data/ent/documenttoken"
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
)
// DocumentTokenQuery is the builder for querying DocumentToken entities.
type DocumentTokenQuery struct {
config
limit *int
offset *int
unique *bool
order []OrderFunc
fields []string
predicates []predicate.DocumentToken
withDocument *DocumentQuery
withFKs bool
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the DocumentTokenQuery builder.
func (dtq *DocumentTokenQuery) Where(ps ...predicate.DocumentToken) *DocumentTokenQuery {
dtq.predicates = append(dtq.predicates, ps...)
return dtq
}
// Limit adds a limit step to the query.
func (dtq *DocumentTokenQuery) Limit(limit int) *DocumentTokenQuery {
dtq.limit = &limit
return dtq
}
// Offset adds an offset step to the query.
func (dtq *DocumentTokenQuery) Offset(offset int) *DocumentTokenQuery {
dtq.offset = &offset
return dtq
}
// 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 (dtq *DocumentTokenQuery) Unique(unique bool) *DocumentTokenQuery {
dtq.unique = &unique
return dtq
}
// Order adds an order step to the query.
func (dtq *DocumentTokenQuery) Order(o ...OrderFunc) *DocumentTokenQuery {
dtq.order = append(dtq.order, o...)
return dtq
}
// QueryDocument chains the current query on the "document" edge.
func (dtq *DocumentTokenQuery) QueryDocument() *DocumentQuery {
query := &DocumentQuery{config: dtq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := dtq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := dtq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(documenttoken.Table, documenttoken.FieldID, selector),
sqlgraph.To(document.Table, document.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, documenttoken.DocumentTable, documenttoken.DocumentColumn),
)
fromU = sqlgraph.SetNeighbors(dtq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first DocumentToken entity from the query.
// Returns a *NotFoundError when no DocumentToken was found.
func (dtq *DocumentTokenQuery) First(ctx context.Context) (*DocumentToken, error) {
nodes, err := dtq.Limit(1).All(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{documenttoken.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (dtq *DocumentTokenQuery) FirstX(ctx context.Context) *DocumentToken {
node, err := dtq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first DocumentToken ID from the query.
// Returns a *NotFoundError when no DocumentToken ID was found.
func (dtq *DocumentTokenQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = dtq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{documenttoken.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (dtq *DocumentTokenQuery) FirstIDX(ctx context.Context) uuid.UUID {
id, err := dtq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single DocumentToken entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one DocumentToken entity is found.
// Returns a *NotFoundError when no DocumentToken entities are found.
func (dtq *DocumentTokenQuery) Only(ctx context.Context) (*DocumentToken, error) {
nodes, err := dtq.Limit(2).All(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{documenttoken.Label}
default:
return nil, &NotSingularError{documenttoken.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (dtq *DocumentTokenQuery) OnlyX(ctx context.Context) *DocumentToken {
node, err := dtq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only DocumentToken ID in the query.
// Returns a *NotSingularError when more than one DocumentToken ID is found.
// Returns a *NotFoundError when no entities are found.
func (dtq *DocumentTokenQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = dtq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{documenttoken.Label}
default:
err = &NotSingularError{documenttoken.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (dtq *DocumentTokenQuery) OnlyIDX(ctx context.Context) uuid.UUID {
id, err := dtq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of DocumentTokens.
func (dtq *DocumentTokenQuery) All(ctx context.Context) ([]*DocumentToken, error) {
if err := dtq.prepareQuery(ctx); err != nil {
return nil, err
}
return dtq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (dtq *DocumentTokenQuery) AllX(ctx context.Context) []*DocumentToken {
nodes, err := dtq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of DocumentToken IDs.
func (dtq *DocumentTokenQuery) IDs(ctx context.Context) ([]uuid.UUID, error) {
var ids []uuid.UUID
if err := dtq.Select(documenttoken.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (dtq *DocumentTokenQuery) IDsX(ctx context.Context) []uuid.UUID {
ids, err := dtq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (dtq *DocumentTokenQuery) Count(ctx context.Context) (int, error) {
if err := dtq.prepareQuery(ctx); err != nil {
return 0, err
}
return dtq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (dtq *DocumentTokenQuery) CountX(ctx context.Context) int {
count, err := dtq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (dtq *DocumentTokenQuery) Exist(ctx context.Context) (bool, error) {
if err := dtq.prepareQuery(ctx); err != nil {
return false, err
}
return dtq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (dtq *DocumentTokenQuery) ExistX(ctx context.Context) bool {
exist, err := dtq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the DocumentTokenQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (dtq *DocumentTokenQuery) Clone() *DocumentTokenQuery {
if dtq == nil {
return nil
}
return &DocumentTokenQuery{
config: dtq.config,
limit: dtq.limit,
offset: dtq.offset,
order: append([]OrderFunc{}, dtq.order...),
predicates: append([]predicate.DocumentToken{}, dtq.predicates...),
withDocument: dtq.withDocument.Clone(),
// clone intermediate query.
sql: dtq.sql.Clone(),
path: dtq.path,
unique: dtq.unique,
}
}
// WithDocument tells the query-builder to eager-load the nodes that are connected to
// the "document" edge. The optional arguments are used to configure the query builder of the edge.
func (dtq *DocumentTokenQuery) WithDocument(opts ...func(*DocumentQuery)) *DocumentTokenQuery {
query := &DocumentQuery{config: dtq.config}
for _, opt := range opts {
opt(query)
}
dtq.withDocument = query
return dtq
}
// 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.DocumentToken.Query().
// GroupBy(documenttoken.FieldCreatedAt).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (dtq *DocumentTokenQuery) GroupBy(field string, fields ...string) *DocumentTokenGroupBy {
grbuild := &DocumentTokenGroupBy{config: dtq.config}
grbuild.fields = append([]string{field}, fields...)
grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := dtq.prepareQuery(ctx); err != nil {
return nil, err
}
return dtq.sqlQuery(ctx), nil
}
grbuild.label = documenttoken.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.DocumentToken.Query().
// Select(documenttoken.FieldCreatedAt).
// Scan(ctx, &v)
func (dtq *DocumentTokenQuery) Select(fields ...string) *DocumentTokenSelect {
dtq.fields = append(dtq.fields, fields...)
selbuild := &DocumentTokenSelect{DocumentTokenQuery: dtq}
selbuild.label = documenttoken.Label
selbuild.flds, selbuild.scan = &dtq.fields, selbuild.Scan
return selbuild
}
func (dtq *DocumentTokenQuery) prepareQuery(ctx context.Context) error {
for _, f := range dtq.fields {
if !documenttoken.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if dtq.path != nil {
prev, err := dtq.path(ctx)
if err != nil {
return err
}
dtq.sql = prev
}
return nil
}
func (dtq *DocumentTokenQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*DocumentToken, error) {
var (
nodes = []*DocumentToken{}
withFKs = dtq.withFKs
_spec = dtq.querySpec()
loadedTypes = [1]bool{
dtq.withDocument != nil,
}
)
if dtq.withDocument != nil {
withFKs = true
}
if withFKs {
_spec.Node.Columns = append(_spec.Node.Columns, documenttoken.ForeignKeys...)
}
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*DocumentToken).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &DocumentToken{config: dtq.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, dtq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := dtq.withDocument; query != nil {
if err := dtq.loadDocument(ctx, query, nodes, nil,
func(n *DocumentToken, e *Document) { n.Edges.Document = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (dtq *DocumentTokenQuery) loadDocument(ctx context.Context, query *DocumentQuery, nodes []*DocumentToken, init func(*DocumentToken), assign func(*DocumentToken, *Document)) error {
ids := make([]uuid.UUID, 0, len(nodes))
nodeids := make(map[uuid.UUID][]*DocumentToken)
for i := range nodes {
if nodes[i].document_document_tokens == nil {
continue
}
fk := *nodes[i].document_document_tokens
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
query.Where(document.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 "document_document_tokens" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (dtq *DocumentTokenQuery) sqlCount(ctx context.Context) (int, error) {
_spec := dtq.querySpec()
_spec.Node.Columns = dtq.fields
if len(dtq.fields) > 0 {
_spec.Unique = dtq.unique != nil && *dtq.unique
}
return sqlgraph.CountNodes(ctx, dtq.driver, _spec)
}
func (dtq *DocumentTokenQuery) sqlExist(ctx context.Context) (bool, error) {
switch _, err := dtq.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 (dtq *DocumentTokenQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: documenttoken.Table,
Columns: documenttoken.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: documenttoken.FieldID,
},
},
From: dtq.sql,
Unique: true,
}
if unique := dtq.unique; unique != nil {
_spec.Unique = *unique
}
if fields := dtq.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, documenttoken.FieldID)
for i := range fields {
if fields[i] != documenttoken.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := dtq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := dtq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := dtq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := dtq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (dtq *DocumentTokenQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(dtq.driver.Dialect())
t1 := builder.Table(documenttoken.Table)
columns := dtq.fields
if len(columns) == 0 {
columns = documenttoken.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if dtq.sql != nil {
selector = dtq.sql
selector.Select(selector.Columns(columns...)...)
}
if dtq.unique != nil && *dtq.unique {
selector.Distinct()
}
for _, p := range dtq.predicates {
p(selector)
}
for _, p := range dtq.order {
p(selector)
}
if offset := dtq.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 := dtq.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// DocumentTokenGroupBy is the group-by builder for DocumentToken entities.
type DocumentTokenGroupBy 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 (dtgb *DocumentTokenGroupBy) Aggregate(fns ...AggregateFunc) *DocumentTokenGroupBy {
dtgb.fns = append(dtgb.fns, fns...)
return dtgb
}
// Scan applies the group-by query and scans the result into the given value.
func (dtgb *DocumentTokenGroupBy) Scan(ctx context.Context, v any) error {
query, err := dtgb.path(ctx)
if err != nil {
return err
}
dtgb.sql = query
return dtgb.sqlScan(ctx, v)
}
func (dtgb *DocumentTokenGroupBy) sqlScan(ctx context.Context, v any) error {
for _, f := range dtgb.fields {
if !documenttoken.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := dtgb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := dtgb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (dtgb *DocumentTokenGroupBy) sqlQuery() *sql.Selector {
selector := dtgb.sql.Select()
aggregation := make([]string, 0, len(dtgb.fns))
for _, fn := range dtgb.fns {
aggregation = append(aggregation, fn(selector))
}
// If no columns were selected in a custom aggregation function, the default
// selection is the fields used for "group-by", and the aggregation functions.
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(dtgb.fields)+len(dtgb.fns))
for _, f := range dtgb.fields {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
return selector.GroupBy(selector.Columns(dtgb.fields...)...)
}
// DocumentTokenSelect is the builder for selecting fields of DocumentToken entities.
type DocumentTokenSelect struct {
*DocumentTokenQuery
selector
// intermediate query (i.e. traversal path).
sql *sql.Selector
}
// Scan applies the selector query and scans the result into the given value.
func (dts *DocumentTokenSelect) Scan(ctx context.Context, v any) error {
if err := dts.prepareQuery(ctx); err != nil {
return err
}
dts.sql = dts.DocumentTokenQuery.sqlQuery(ctx)
return dts.sqlScan(ctx, v)
}
func (dts *DocumentTokenSelect) sqlScan(ctx context.Context, v any) error {
rows := &sql.Rows{}
query, args := dts.sql.Query()
if err := dts.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

View file

@ -0,0 +1,582 @@
// 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/document"
"github.com/hay-kot/homebox/backend/internal/data/ent/documenttoken"
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
)
// DocumentTokenUpdate is the builder for updating DocumentToken entities.
type DocumentTokenUpdate struct {
config
hooks []Hook
mutation *DocumentTokenMutation
}
// Where appends a list predicates to the DocumentTokenUpdate builder.
func (dtu *DocumentTokenUpdate) Where(ps ...predicate.DocumentToken) *DocumentTokenUpdate {
dtu.mutation.Where(ps...)
return dtu
}
// SetUpdatedAt sets the "updated_at" field.
func (dtu *DocumentTokenUpdate) SetUpdatedAt(t time.Time) *DocumentTokenUpdate {
dtu.mutation.SetUpdatedAt(t)
return dtu
}
// SetToken sets the "token" field.
func (dtu *DocumentTokenUpdate) SetToken(b []byte) *DocumentTokenUpdate {
dtu.mutation.SetToken(b)
return dtu
}
// SetUses sets the "uses" field.
func (dtu *DocumentTokenUpdate) SetUses(i int) *DocumentTokenUpdate {
dtu.mutation.ResetUses()
dtu.mutation.SetUses(i)
return dtu
}
// SetNillableUses sets the "uses" field if the given value is not nil.
func (dtu *DocumentTokenUpdate) SetNillableUses(i *int) *DocumentTokenUpdate {
if i != nil {
dtu.SetUses(*i)
}
return dtu
}
// AddUses adds i to the "uses" field.
func (dtu *DocumentTokenUpdate) AddUses(i int) *DocumentTokenUpdate {
dtu.mutation.AddUses(i)
return dtu
}
// SetExpiresAt sets the "expires_at" field.
func (dtu *DocumentTokenUpdate) SetExpiresAt(t time.Time) *DocumentTokenUpdate {
dtu.mutation.SetExpiresAt(t)
return dtu
}
// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil.
func (dtu *DocumentTokenUpdate) SetNillableExpiresAt(t *time.Time) *DocumentTokenUpdate {
if t != nil {
dtu.SetExpiresAt(*t)
}
return dtu
}
// SetDocumentID sets the "document" edge to the Document entity by ID.
func (dtu *DocumentTokenUpdate) SetDocumentID(id uuid.UUID) *DocumentTokenUpdate {
dtu.mutation.SetDocumentID(id)
return dtu
}
// SetNillableDocumentID sets the "document" edge to the Document entity by ID if the given value is not nil.
func (dtu *DocumentTokenUpdate) SetNillableDocumentID(id *uuid.UUID) *DocumentTokenUpdate {
if id != nil {
dtu = dtu.SetDocumentID(*id)
}
return dtu
}
// SetDocument sets the "document" edge to the Document entity.
func (dtu *DocumentTokenUpdate) SetDocument(d *Document) *DocumentTokenUpdate {
return dtu.SetDocumentID(d.ID)
}
// Mutation returns the DocumentTokenMutation object of the builder.
func (dtu *DocumentTokenUpdate) Mutation() *DocumentTokenMutation {
return dtu.mutation
}
// ClearDocument clears the "document" edge to the Document entity.
func (dtu *DocumentTokenUpdate) ClearDocument() *DocumentTokenUpdate {
dtu.mutation.ClearDocument()
return dtu
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (dtu *DocumentTokenUpdate) Save(ctx context.Context) (int, error) {
var (
err error
affected int
)
dtu.defaults()
if len(dtu.hooks) == 0 {
if err = dtu.check(); err != nil {
return 0, err
}
affected, err = dtu.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*DocumentTokenMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = dtu.check(); err != nil {
return 0, err
}
dtu.mutation = mutation
affected, err = dtu.sqlSave(ctx)
mutation.done = true
return affected, err
})
for i := len(dtu.hooks) - 1; i >= 0; i-- {
if dtu.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = dtu.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, dtu.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// SaveX is like Save, but panics if an error occurs.
func (dtu *DocumentTokenUpdate) SaveX(ctx context.Context) int {
affected, err := dtu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (dtu *DocumentTokenUpdate) Exec(ctx context.Context) error {
_, err := dtu.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (dtu *DocumentTokenUpdate) ExecX(ctx context.Context) {
if err := dtu.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (dtu *DocumentTokenUpdate) defaults() {
if _, ok := dtu.mutation.UpdatedAt(); !ok {
v := documenttoken.UpdateDefaultUpdatedAt()
dtu.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (dtu *DocumentTokenUpdate) check() error {
if v, ok := dtu.mutation.Token(); ok {
if err := documenttoken.TokenValidator(v); err != nil {
return &ValidationError{Name: "token", err: fmt.Errorf(`ent: validator failed for field "DocumentToken.token": %w`, err)}
}
}
return nil
}
func (dtu *DocumentTokenUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: documenttoken.Table,
Columns: documenttoken.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: documenttoken.FieldID,
},
},
}
if ps := dtu.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := dtu.mutation.UpdatedAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: documenttoken.FieldUpdatedAt,
})
}
if value, ok := dtu.mutation.Token(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: documenttoken.FieldToken,
})
}
if value, ok := dtu.mutation.Uses(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: documenttoken.FieldUses,
})
}
if value, ok := dtu.mutation.AddedUses(); ok {
_spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: documenttoken.FieldUses,
})
}
if value, ok := dtu.mutation.ExpiresAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: documenttoken.FieldExpiresAt,
})
}
if dtu.mutation.DocumentCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: documenttoken.DocumentTable,
Columns: []string{documenttoken.DocumentColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: document.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := dtu.mutation.DocumentIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: documenttoken.DocumentTable,
Columns: []string{documenttoken.DocumentColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: document.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, dtu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{documenttoken.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
return n, nil
}
// DocumentTokenUpdateOne is the builder for updating a single DocumentToken entity.
type DocumentTokenUpdateOne struct {
config
fields []string
hooks []Hook
mutation *DocumentTokenMutation
}
// SetUpdatedAt sets the "updated_at" field.
func (dtuo *DocumentTokenUpdateOne) SetUpdatedAt(t time.Time) *DocumentTokenUpdateOne {
dtuo.mutation.SetUpdatedAt(t)
return dtuo
}
// SetToken sets the "token" field.
func (dtuo *DocumentTokenUpdateOne) SetToken(b []byte) *DocumentTokenUpdateOne {
dtuo.mutation.SetToken(b)
return dtuo
}
// SetUses sets the "uses" field.
func (dtuo *DocumentTokenUpdateOne) SetUses(i int) *DocumentTokenUpdateOne {
dtuo.mutation.ResetUses()
dtuo.mutation.SetUses(i)
return dtuo
}
// SetNillableUses sets the "uses" field if the given value is not nil.
func (dtuo *DocumentTokenUpdateOne) SetNillableUses(i *int) *DocumentTokenUpdateOne {
if i != nil {
dtuo.SetUses(*i)
}
return dtuo
}
// AddUses adds i to the "uses" field.
func (dtuo *DocumentTokenUpdateOne) AddUses(i int) *DocumentTokenUpdateOne {
dtuo.mutation.AddUses(i)
return dtuo
}
// SetExpiresAt sets the "expires_at" field.
func (dtuo *DocumentTokenUpdateOne) SetExpiresAt(t time.Time) *DocumentTokenUpdateOne {
dtuo.mutation.SetExpiresAt(t)
return dtuo
}
// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil.
func (dtuo *DocumentTokenUpdateOne) SetNillableExpiresAt(t *time.Time) *DocumentTokenUpdateOne {
if t != nil {
dtuo.SetExpiresAt(*t)
}
return dtuo
}
// SetDocumentID sets the "document" edge to the Document entity by ID.
func (dtuo *DocumentTokenUpdateOne) SetDocumentID(id uuid.UUID) *DocumentTokenUpdateOne {
dtuo.mutation.SetDocumentID(id)
return dtuo
}
// SetNillableDocumentID sets the "document" edge to the Document entity by ID if the given value is not nil.
func (dtuo *DocumentTokenUpdateOne) SetNillableDocumentID(id *uuid.UUID) *DocumentTokenUpdateOne {
if id != nil {
dtuo = dtuo.SetDocumentID(*id)
}
return dtuo
}
// SetDocument sets the "document" edge to the Document entity.
func (dtuo *DocumentTokenUpdateOne) SetDocument(d *Document) *DocumentTokenUpdateOne {
return dtuo.SetDocumentID(d.ID)
}
// Mutation returns the DocumentTokenMutation object of the builder.
func (dtuo *DocumentTokenUpdateOne) Mutation() *DocumentTokenMutation {
return dtuo.mutation
}
// ClearDocument clears the "document" edge to the Document entity.
func (dtuo *DocumentTokenUpdateOne) ClearDocument() *DocumentTokenUpdateOne {
dtuo.mutation.ClearDocument()
return dtuo
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (dtuo *DocumentTokenUpdateOne) Select(field string, fields ...string) *DocumentTokenUpdateOne {
dtuo.fields = append([]string{field}, fields...)
return dtuo
}
// Save executes the query and returns the updated DocumentToken entity.
func (dtuo *DocumentTokenUpdateOne) Save(ctx context.Context) (*DocumentToken, error) {
var (
err error
node *DocumentToken
)
dtuo.defaults()
if len(dtuo.hooks) == 0 {
if err = dtuo.check(); err != nil {
return nil, err
}
node, err = dtuo.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*DocumentTokenMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = dtuo.check(); err != nil {
return nil, err
}
dtuo.mutation = mutation
node, err = dtuo.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(dtuo.hooks) - 1; i >= 0; i-- {
if dtuo.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = dtuo.hooks[i](mut)
}
v, err := mut.Mutate(ctx, dtuo.mutation)
if err != nil {
return nil, err
}
nv, ok := v.(*DocumentToken)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from DocumentTokenMutation", v)
}
node = nv
}
return node, err
}
// SaveX is like Save, but panics if an error occurs.
func (dtuo *DocumentTokenUpdateOne) SaveX(ctx context.Context) *DocumentToken {
node, err := dtuo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (dtuo *DocumentTokenUpdateOne) Exec(ctx context.Context) error {
_, err := dtuo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (dtuo *DocumentTokenUpdateOne) ExecX(ctx context.Context) {
if err := dtuo.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (dtuo *DocumentTokenUpdateOne) defaults() {
if _, ok := dtuo.mutation.UpdatedAt(); !ok {
v := documenttoken.UpdateDefaultUpdatedAt()
dtuo.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (dtuo *DocumentTokenUpdateOne) check() error {
if v, ok := dtuo.mutation.Token(); ok {
if err := documenttoken.TokenValidator(v); err != nil {
return &ValidationError{Name: "token", err: fmt.Errorf(`ent: validator failed for field "DocumentToken.token": %w`, err)}
}
}
return nil
}
func (dtuo *DocumentTokenUpdateOne) sqlSave(ctx context.Context) (_node *DocumentToken, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: documenttoken.Table,
Columns: documenttoken.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: documenttoken.FieldID,
},
},
}
id, ok := dtuo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "DocumentToken.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := dtuo.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, documenttoken.FieldID)
for _, f := range fields {
if !documenttoken.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != documenttoken.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := dtuo.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := dtuo.mutation.UpdatedAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: documenttoken.FieldUpdatedAt,
})
}
if value, ok := dtuo.mutation.Token(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: documenttoken.FieldToken,
})
}
if value, ok := dtuo.mutation.Uses(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: documenttoken.FieldUses,
})
}
if value, ok := dtuo.mutation.AddedUses(); ok {
_spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: documenttoken.FieldUses,
})
}
if value, ok := dtuo.mutation.ExpiresAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: documenttoken.FieldExpiresAt,
})
}
if dtuo.mutation.DocumentCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: documenttoken.DocumentTable,
Columns: []string{documenttoken.DocumentColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: document.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := dtuo.mutation.DocumentIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: documenttoken.DocumentTable,
Columns: []string{documenttoken.DocumentColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: document.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &DocumentToken{config: dtuo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, dtuo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{documenttoken.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
return _node, nil
}

View file

@ -0,0 +1,485 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/hay-kot/homebox/backend/internal/data/ent/attachment"
"github.com/hay-kot/homebox/backend/internal/data/ent/authtokens"
"github.com/hay-kot/homebox/backend/internal/data/ent/document"
"github.com/hay-kot/homebox/backend/internal/data/ent/documenttoken"
"github.com/hay-kot/homebox/backend/internal/data/ent/group"
"github.com/hay-kot/homebox/backend/internal/data/ent/groupinvitationtoken"
"github.com/hay-kot/homebox/backend/internal/data/ent/item"
"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/user"
)
// ent aliases to avoid import conflicts in user's code.
type (
Op = ent.Op
Hook = ent.Hook
Value = ent.Value
Query = ent.Query
Policy = ent.Policy
Mutator = ent.Mutator
Mutation = ent.Mutation
MutateFunc = ent.MutateFunc
)
// OrderFunc applies an ordering on the sql selector.
type OrderFunc func(*sql.Selector)
// columnChecker returns a function indicates if the column exists in the given column.
func columnChecker(table string) func(string) error {
checks := map[string]func(string) bool{
attachment.Table: attachment.ValidColumn,
authtokens.Table: authtokens.ValidColumn,
document.Table: document.ValidColumn,
documenttoken.Table: documenttoken.ValidColumn,
group.Table: group.ValidColumn,
groupinvitationtoken.Table: groupinvitationtoken.ValidColumn,
item.Table: item.ValidColumn,
itemfield.Table: itemfield.ValidColumn,
label.Table: label.ValidColumn,
location.Table: location.ValidColumn,
user.Table: user.ValidColumn,
}
check, ok := checks[table]
if !ok {
return func(string) error {
return fmt.Errorf("unknown table %q", table)
}
}
return func(column string) error {
if !check(column) {
return fmt.Errorf("unknown column %q for table %q", column, table)
}
return nil
}
}
// Asc applies the given fields in ASC order.
func Asc(fields ...string) OrderFunc {
return func(s *sql.Selector) {
check := columnChecker(s.TableName())
for _, f := range fields {
if err := check(f); err != nil {
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)})
}
s.OrderBy(sql.Asc(s.C(f)))
}
}
}
// Desc applies the given fields in DESC order.
func Desc(fields ...string) OrderFunc {
return func(s *sql.Selector) {
check := columnChecker(s.TableName())
for _, f := range fields {
if err := check(f); err != nil {
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)})
}
s.OrderBy(sql.Desc(s.C(f)))
}
}
}
// AggregateFunc applies an aggregation step on the group-by traversal/selector.
type AggregateFunc func(*sql.Selector) string
// As is a pseudo aggregation function for renaming another other functions with custom names. For example:
//
// GroupBy(field1, field2).
// Aggregate(ent.As(ent.Sum(field1), "sum_field1"), (ent.As(ent.Sum(field2), "sum_field2")).
// Scan(ctx, &v)
func As(fn AggregateFunc, end string) AggregateFunc {
return func(s *sql.Selector) string {
return sql.As(fn(s), end)
}
}
// Count applies the "count" aggregation function on each group.
func Count() AggregateFunc {
return func(s *sql.Selector) string {
return sql.Count("*")
}
}
// Max applies the "max" aggregation function on the given field of each group.
func Max(field string) AggregateFunc {
return func(s *sql.Selector) string {
check := columnChecker(s.TableName())
if err := check(field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Max(s.C(field))
}
}
// Mean applies the "mean" aggregation function on the given field of each group.
func Mean(field string) AggregateFunc {
return func(s *sql.Selector) string {
check := columnChecker(s.TableName())
if err := check(field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Avg(s.C(field))
}
}
// Min applies the "min" aggregation function on the given field of each group.
func Min(field string) AggregateFunc {
return func(s *sql.Selector) string {
check := columnChecker(s.TableName())
if err := check(field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Min(s.C(field))
}
}
// Sum applies the "sum" aggregation function on the given field of each group.
func Sum(field string) AggregateFunc {
return func(s *sql.Selector) string {
check := columnChecker(s.TableName())
if err := check(field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Sum(s.C(field))
}
}
// ValidationError returns when validating a field or edge fails.
type ValidationError struct {
Name string // Field or edge name.
err error
}
// Error implements the error interface.
func (e *ValidationError) Error() string {
return e.err.Error()
}
// Unwrap implements the errors.Wrapper interface.
func (e *ValidationError) Unwrap() error {
return e.err
}
// IsValidationError returns a boolean indicating whether the error is a validation error.
func IsValidationError(err error) bool {
if err == nil {
return false
}
var e *ValidationError
return errors.As(err, &e)
}
// NotFoundError returns when trying to fetch a specific entity and it was not found in the database.
type NotFoundError struct {
label string
}
// Error implements the error interface.
func (e *NotFoundError) Error() string {
return "ent: " + e.label + " not found"
}
// IsNotFound returns a boolean indicating whether the error is a not found error.
func IsNotFound(err error) bool {
if err == nil {
return false
}
var e *NotFoundError
return errors.As(err, &e)
}
// MaskNotFound masks not found error.
func MaskNotFound(err error) error {
if IsNotFound(err) {
return nil
}
return err
}
// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database.
type NotSingularError struct {
label string
}
// Error implements the error interface.
func (e *NotSingularError) Error() string {
return "ent: " + e.label + " not singular"
}
// IsNotSingular returns a boolean indicating whether the error is a not singular error.
func IsNotSingular(err error) bool {
if err == nil {
return false
}
var e *NotSingularError
return errors.As(err, &e)
}
// NotLoadedError returns when trying to get a node that was not loaded by the query.
type NotLoadedError struct {
edge string
}
// Error implements the error interface.
func (e *NotLoadedError) Error() string {
return "ent: " + e.edge + " edge was not loaded"
}
// IsNotLoaded returns a boolean indicating whether the error is a not loaded error.
func IsNotLoaded(err error) bool {
if err == nil {
return false
}
var e *NotLoadedError
return errors.As(err, &e)
}
// ConstraintError returns when trying to create/update one or more entities and
// one or more of their constraints failed. For example, violation of edge or
// field uniqueness.
type ConstraintError struct {
msg string
wrap error
}
// Error implements the error interface.
func (e ConstraintError) Error() string {
return "ent: constraint failed: " + e.msg
}
// Unwrap implements the errors.Wrapper interface.
func (e *ConstraintError) Unwrap() error {
return e.wrap
}
// IsConstraintError returns a boolean indicating whether the error is a constraint failure.
func IsConstraintError(err error) bool {
if err == nil {
return false
}
var e *ConstraintError
return errors.As(err, &e)
}
// selector embedded by the different Select/GroupBy builders.
type selector struct {
label string
flds *[]string
scan func(context.Context, any) error
}
// ScanX is like Scan, but panics if an error occurs.
func (s *selector) ScanX(ctx context.Context, v any) {
if err := s.scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from a selector. It is only allowed when selecting one field.
func (s *selector) Strings(ctx context.Context) ([]string, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (s *selector) StringsX(ctx context.Context) []string {
v, err := s.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a selector. It is only allowed when selecting one field.
func (s *selector) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = s.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (s *selector) StringX(ctx context.Context) string {
v, err := s.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from a selector. It is only allowed when selecting one field.
func (s *selector) Ints(ctx context.Context) ([]int, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (s *selector) IntsX(ctx context.Context) []int {
v, err := s.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a selector. It is only allowed when selecting one field.
func (s *selector) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = s.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (s *selector) IntX(ctx context.Context) int {
v, err := s.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
func (s *selector) Float64s(ctx context.Context) ([]float64, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (s *selector) Float64sX(ctx context.Context) []float64 {
v, err := s.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
func (s *selector) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = s.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (s *selector) Float64X(ctx context.Context) float64 {
v, err := s.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from a selector. It is only allowed when selecting one field.
func (s *selector) Bools(ctx context.Context) ([]bool, error) {
if len(*s.flds) > 1 {
return nil, errors.New("ent: Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (s *selector) BoolsX(ctx context.Context) []bool {
v, err := s.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a selector. It is only allowed when selecting one field.
func (s *selector) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = s.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("ent: Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (s *selector) BoolX(ctx context.Context) bool {
v, err := s.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
// queryHook describes an internal hook for the different sqlAll methods.
type queryHook func(context.Context, *sqlgraph.QuerySpec)

View file

@ -0,0 +1,84 @@
// Code generated by ent, DO NOT EDIT.
package enttest
import (
"context"
"github.com/hay-kot/homebox/backend/internal/data/ent"
// required by schema hooks.
_ "github.com/hay-kot/homebox/backend/internal/data/ent/runtime"
"entgo.io/ent/dialect/sql/schema"
"github.com/hay-kot/homebox/backend/internal/data/ent/migrate"
)
type (
// TestingT is the interface that is shared between
// testing.T and testing.B and used by enttest.
TestingT interface {
FailNow()
Error(...any)
}
// Option configures client creation.
Option func(*options)
options struct {
opts []ent.Option
migrateOpts []schema.MigrateOption
}
)
// WithOptions forwards options to client creation.
func WithOptions(opts ...ent.Option) Option {
return func(o *options) {
o.opts = append(o.opts, opts...)
}
}
// WithMigrateOptions forwards options to auto migration.
func WithMigrateOptions(opts ...schema.MigrateOption) Option {
return func(o *options) {
o.migrateOpts = append(o.migrateOpts, opts...)
}
}
func newOptions(opts []Option) *options {
o := &options{}
for _, opt := range opts {
opt(o)
}
return o
}
// Open calls ent.Open and auto-run migration.
func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *ent.Client {
o := newOptions(opts)
c, err := ent.Open(driverName, dataSourceName, o.opts...)
if err != nil {
t.Error(err)
t.FailNow()
}
migrateSchema(t, c, o)
return c
}
// NewClient calls ent.NewClient and auto-run migration.
func NewClient(t TestingT, opts ...Option) *ent.Client {
o := newOptions(opts)
c := ent.NewClient(o.opts...)
migrateSchema(t, c, o)
return c
}
func migrateSchema(t TestingT, c *ent.Client, o *options) {
tables, err := schema.CopyTables(migrate.Tables)
if err != nil {
t.Error(err)
t.FailNow()
}
if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil {
t.Error(err)
t.FailNow()
}
}

View file

@ -0,0 +1,13 @@
package ent
import (
"database/sql"
entsql "entgo.io/ent/dialect/sql"
)
// Sql exposes the underlying database connection in the ent client
// so that we can use it to perform custom queries.
func (c *Client) Sql() *sql.DB {
return c.driver.(*entsql.Driver).DB()
}

View file

@ -0,0 +1,3 @@
package ent
//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate --feature sql/versioned-migration ./schema

View file

@ -0,0 +1,242 @@
// 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/group"
)
// Group is the model entity for the Group schema.
type Group 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"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// Currency holds the value of the "currency" field.
Currency group.Currency `json:"currency,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the GroupQuery when eager-loading is set.
Edges GroupEdges `json:"edges"`
}
// GroupEdges holds the relations/edges for other nodes in the graph.
type GroupEdges struct {
// Users holds the value of the users edge.
Users []*User `json:"users,omitempty"`
// Locations holds the value of the locations edge.
Locations []*Location `json:"locations,omitempty"`
// Items holds the value of the items edge.
Items []*Item `json:"items,omitempty"`
// Labels holds the value of the labels edge.
Labels []*Label `json:"labels,omitempty"`
// Documents holds the value of the documents edge.
Documents []*Document `json:"documents,omitempty"`
// InvitationTokens holds the value of the invitation_tokens edge.
InvitationTokens []*GroupInvitationToken `json:"invitation_tokens,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [6]bool
}
// UsersOrErr returns the Users value or an error if the edge
// was not loaded in eager-loading.
func (e GroupEdges) UsersOrErr() ([]*User, error) {
if e.loadedTypes[0] {
return e.Users, nil
}
return nil, &NotLoadedError{edge: "users"}
}
// LocationsOrErr returns the Locations value or an error if the edge
// was not loaded in eager-loading.
func (e GroupEdges) LocationsOrErr() ([]*Location, error) {
if e.loadedTypes[1] {
return e.Locations, nil
}
return nil, &NotLoadedError{edge: "locations"}
}
// ItemsOrErr returns the Items value or an error if the edge
// was not loaded in eager-loading.
func (e GroupEdges) ItemsOrErr() ([]*Item, error) {
if e.loadedTypes[2] {
return e.Items, nil
}
return nil, &NotLoadedError{edge: "items"}
}
// LabelsOrErr returns the Labels value or an error if the edge
// was not loaded in eager-loading.
func (e GroupEdges) LabelsOrErr() ([]*Label, error) {
if e.loadedTypes[3] {
return e.Labels, nil
}
return nil, &NotLoadedError{edge: "labels"}
}
// DocumentsOrErr returns the Documents value or an error if the edge
// was not loaded in eager-loading.
func (e GroupEdges) DocumentsOrErr() ([]*Document, error) {
if e.loadedTypes[4] {
return e.Documents, nil
}
return nil, &NotLoadedError{edge: "documents"}
}
// InvitationTokensOrErr returns the InvitationTokens value or an error if the edge
// was not loaded in eager-loading.
func (e GroupEdges) InvitationTokensOrErr() ([]*GroupInvitationToken, error) {
if e.loadedTypes[5] {
return e.InvitationTokens, nil
}
return nil, &NotLoadedError{edge: "invitation_tokens"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Group) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case group.FieldName, group.FieldCurrency:
values[i] = new(sql.NullString)
case group.FieldCreatedAt, group.FieldUpdatedAt:
values[i] = new(sql.NullTime)
case group.FieldID:
values[i] = new(uuid.UUID)
default:
return nil, fmt.Errorf("unexpected column %q for type Group", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Group fields.
func (gr *Group) 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 group.FieldID:
if value, ok := values[i].(*uuid.UUID); !ok {
return fmt.Errorf("unexpected type %T for field id", values[i])
} else if value != nil {
gr.ID = *value
}
case group.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 {
gr.CreatedAt = value.Time
}
case group.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 {
gr.UpdatedAt = value.Time
}
case group.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
gr.Name = value.String
}
case group.FieldCurrency:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field currency", values[i])
} else if value.Valid {
gr.Currency = group.Currency(value.String)
}
}
}
return nil
}
// QueryUsers queries the "users" edge of the Group entity.
func (gr *Group) QueryUsers() *UserQuery {
return (&GroupClient{config: gr.config}).QueryUsers(gr)
}
// QueryLocations queries the "locations" edge of the Group entity.
func (gr *Group) QueryLocations() *LocationQuery {
return (&GroupClient{config: gr.config}).QueryLocations(gr)
}
// QueryItems queries the "items" edge of the Group entity.
func (gr *Group) QueryItems() *ItemQuery {
return (&GroupClient{config: gr.config}).QueryItems(gr)
}
// QueryLabels queries the "labels" edge of the Group entity.
func (gr *Group) QueryLabels() *LabelQuery {
return (&GroupClient{config: gr.config}).QueryLabels(gr)
}
// QueryDocuments queries the "documents" edge of the Group entity.
func (gr *Group) QueryDocuments() *DocumentQuery {
return (&GroupClient{config: gr.config}).QueryDocuments(gr)
}
// QueryInvitationTokens queries the "invitation_tokens" edge of the Group entity.
func (gr *Group) QueryInvitationTokens() *GroupInvitationTokenQuery {
return (&GroupClient{config: gr.config}).QueryInvitationTokens(gr)
}
// Update returns a builder for updating this Group.
// Note that you need to call Group.Unwrap() before calling this method if this Group
// was returned from a transaction, and the transaction was committed or rolled back.
func (gr *Group) Update() *GroupUpdateOne {
return (&GroupClient{config: gr.config}).UpdateOne(gr)
}
// Unwrap unwraps the Group 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 (gr *Group) Unwrap() *Group {
_tx, ok := gr.config.driver.(*txDriver)
if !ok {
panic("ent: Group is not a transactional entity")
}
gr.config.driver = _tx.drv
return gr
}
// String implements the fmt.Stringer.
func (gr *Group) String() string {
var builder strings.Builder
builder.WriteString("Group(")
builder.WriteString(fmt.Sprintf("id=%v, ", gr.ID))
builder.WriteString("created_at=")
builder.WriteString(gr.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(gr.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("name=")
builder.WriteString(gr.Name)
builder.WriteString(", ")
builder.WriteString("currency=")
builder.WriteString(fmt.Sprintf("%v", gr.Currency))
builder.WriteByte(')')
return builder.String()
}
// Groups is a parsable slice of Group.
type Groups []*Group
func (gr Groups) config(cfg config) {
for _i := range gr {
gr[_i].config = cfg
}
}

View file

@ -0,0 +1,141 @@
// Code generated by ent, DO NOT EDIT.
package group
import (
"fmt"
"time"
"github.com/google/uuid"
)
const (
// Label holds the string label denoting the group type in the database.
Label = "group"
// 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"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// FieldCurrency holds the string denoting the currency field in the database.
FieldCurrency = "currency"
// EdgeUsers holds the string denoting the users edge name in mutations.
EdgeUsers = "users"
// EdgeLocations holds the string denoting the locations edge name in mutations.
EdgeLocations = "locations"
// EdgeItems holds the string denoting the items edge name in mutations.
EdgeItems = "items"
// EdgeLabels holds the string denoting the labels edge name in mutations.
EdgeLabels = "labels"
// EdgeDocuments holds the string denoting the documents edge name in mutations.
EdgeDocuments = "documents"
// EdgeInvitationTokens holds the string denoting the invitation_tokens edge name in mutations.
EdgeInvitationTokens = "invitation_tokens"
// Table holds the table name of the group in the database.
Table = "groups"
// UsersTable is the table that holds the users relation/edge.
UsersTable = "users"
// UsersInverseTable is the table name for the User entity.
// It exists in this package in order to avoid circular dependency with the "user" package.
UsersInverseTable = "users"
// UsersColumn is the table column denoting the users relation/edge.
UsersColumn = "group_users"
// LocationsTable is the table that holds the locations relation/edge.
LocationsTable = "locations"
// LocationsInverseTable is the table name for the Location entity.
// It exists in this package in order to avoid circular dependency with the "location" package.
LocationsInverseTable = "locations"
// LocationsColumn is the table column denoting the locations relation/edge.
LocationsColumn = "group_locations"
// ItemsTable is the table that holds the items relation/edge.
ItemsTable = "items"
// ItemsInverseTable is the table name for the Item entity.
// It exists in this package in order to avoid circular dependency with the "item" package.
ItemsInverseTable = "items"
// ItemsColumn is the table column denoting the items relation/edge.
ItemsColumn = "group_items"
// LabelsTable is the table that holds the labels relation/edge.
LabelsTable = "labels"
// LabelsInverseTable is the table name for the Label entity.
// It exists in this package in order to avoid circular dependency with the "label" package.
LabelsInverseTable = "labels"
// LabelsColumn is the table column denoting the labels relation/edge.
LabelsColumn = "group_labels"
// DocumentsTable is the table that holds the documents relation/edge.
DocumentsTable = "documents"
// DocumentsInverseTable is the table name for the Document entity.
// It exists in this package in order to avoid circular dependency with the "document" package.
DocumentsInverseTable = "documents"
// DocumentsColumn is the table column denoting the documents relation/edge.
DocumentsColumn = "group_documents"
// InvitationTokensTable is the table that holds the invitation_tokens relation/edge.
InvitationTokensTable = "group_invitation_tokens"
// InvitationTokensInverseTable is the table name for the GroupInvitationToken entity.
// It exists in this package in order to avoid circular dependency with the "groupinvitationtoken" package.
InvitationTokensInverseTable = "group_invitation_tokens"
// InvitationTokensColumn is the table column denoting the invitation_tokens relation/edge.
InvitationTokensColumn = "group_invitation_tokens"
)
// Columns holds all SQL columns for group fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldName,
FieldCurrency,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
// UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
UpdateDefaultUpdatedAt func() time.Time
// NameValidator is a validator for the "name" field. It is called by the builders before save.
NameValidator func(string) error
// DefaultID holds the default value on creation for the "id" field.
DefaultID func() uuid.UUID
)
// Currency defines the type for the "currency" enum field.
type Currency string
// CurrencyUsd is the default value of the Currency enum.
const DefaultCurrency = CurrencyUsd
// Currency values.
const (
CurrencyUsd Currency = "usd"
CurrencyEur Currency = "eur"
CurrencyGbp Currency = "gbp"
CurrencyJpy Currency = "jpy"
)
func (c Currency) String() string {
return string(c)
}
// CurrencyValidator is a validator for the "currency" field enum values. It is called by the builders before save.
func CurrencyValidator(c Currency) error {
switch c {
case CurrencyUsd, CurrencyEur, CurrencyGbp, CurrencyJpy:
return nil
default:
return fmt.Errorf("group: invalid enum value for currency field: %q", c)
}
}

View file

@ -0,0 +1,567 @@
// Code generated by ent, DO NOT EDIT.
package group
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.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
})
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldName), v))
})
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Group(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.Group {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Group(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.Group {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldUpdatedAt), v))
})
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Group(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.Group {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(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.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldName), v))
})
}
// CurrencyEQ applies the EQ predicate on the "currency" field.
func CurrencyEQ(v Currency) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldCurrency), v))
})
}
// CurrencyNEQ applies the NEQ predicate on the "currency" field.
func CurrencyNEQ(v Currency) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldCurrency), v))
})
}
// CurrencyIn applies the In predicate on the "currency" field.
func CurrencyIn(vs ...Currency) predicate.Group {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldCurrency), v...))
})
}
// CurrencyNotIn applies the NotIn predicate on the "currency" field.
func CurrencyNotIn(vs ...Currency) predicate.Group {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Group(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldCurrency), v...))
})
}
// HasUsers applies the HasEdge predicate on the "users" edge.
func HasUsers() predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(UsersTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, UsersTable, UsersColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasUsersWith applies the HasEdge predicate on the "users" edge with a given conditions (other predicates).
func HasUsersWith(preds ...predicate.User) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(UsersInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, UsersTable, UsersColumn),
)
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasLocations applies the HasEdge predicate on the "locations" edge.
func HasLocations() predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(LocationsTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, LocationsTable, LocationsColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasLocationsWith applies the HasEdge predicate on the "locations" edge with a given conditions (other predicates).
func HasLocationsWith(preds ...predicate.Location) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(LocationsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, LocationsTable, LocationsColumn),
)
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasItems applies the HasEdge predicate on the "items" edge.
func HasItems() predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(ItemsTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, ItemsTable, ItemsColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasItemsWith applies the HasEdge predicate on the "items" edge with a given conditions (other predicates).
func HasItemsWith(preds ...predicate.Item) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(ItemsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, ItemsTable, ItemsColumn),
)
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasLabels applies the HasEdge predicate on the "labels" edge.
func HasLabels() predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(LabelsTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, LabelsTable, LabelsColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasLabelsWith applies the HasEdge predicate on the "labels" edge with a given conditions (other predicates).
func HasLabelsWith(preds ...predicate.Label) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(LabelsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, LabelsTable, LabelsColumn),
)
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasDocuments applies the HasEdge predicate on the "documents" edge.
func HasDocuments() predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(DocumentsTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, DocumentsTable, DocumentsColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasDocumentsWith applies the HasEdge predicate on the "documents" edge with a given conditions (other predicates).
func HasDocumentsWith(preds ...predicate.Document) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(DocumentsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, DocumentsTable, DocumentsColumn),
)
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasInvitationTokens applies the HasEdge predicate on the "invitation_tokens" edge.
func HasInvitationTokens() predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(InvitationTokensTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, InvitationTokensTable, InvitationTokensColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasInvitationTokensWith applies the HasEdge predicate on the "invitation_tokens" edge with a given conditions (other predicates).
func HasInvitationTokensWith(preds ...predicate.GroupInvitationToken) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(InvitationTokensInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, InvitationTokensTable, InvitationTokensColumn),
)
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.Group) predicate.Group {
return predicate.Group(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.Group) predicate.Group {
return predicate.Group(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.Group) predicate.Group {
return predicate.Group(func(s *sql.Selector) {
p(s.Not())
})
}

View file

@ -0,0 +1,564 @@
// 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/document"
"github.com/hay-kot/homebox/backend/internal/data/ent/group"
"github.com/hay-kot/homebox/backend/internal/data/ent/groupinvitationtoken"
"github.com/hay-kot/homebox/backend/internal/data/ent/item"
"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/user"
)
// GroupCreate is the builder for creating a Group entity.
type GroupCreate struct {
config
mutation *GroupMutation
hooks []Hook
}
// SetCreatedAt sets the "created_at" field.
func (gc *GroupCreate) SetCreatedAt(t time.Time) *GroupCreate {
gc.mutation.SetCreatedAt(t)
return gc
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (gc *GroupCreate) SetNillableCreatedAt(t *time.Time) *GroupCreate {
if t != nil {
gc.SetCreatedAt(*t)
}
return gc
}
// SetUpdatedAt sets the "updated_at" field.
func (gc *GroupCreate) SetUpdatedAt(t time.Time) *GroupCreate {
gc.mutation.SetUpdatedAt(t)
return gc
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (gc *GroupCreate) SetNillableUpdatedAt(t *time.Time) *GroupCreate {
if t != nil {
gc.SetUpdatedAt(*t)
}
return gc
}
// SetName sets the "name" field.
func (gc *GroupCreate) SetName(s string) *GroupCreate {
gc.mutation.SetName(s)
return gc
}
// SetCurrency sets the "currency" field.
func (gc *GroupCreate) SetCurrency(gr group.Currency) *GroupCreate {
gc.mutation.SetCurrency(gr)
return gc
}
// SetNillableCurrency sets the "currency" field if the given value is not nil.
func (gc *GroupCreate) SetNillableCurrency(gr *group.Currency) *GroupCreate {
if gr != nil {
gc.SetCurrency(*gr)
}
return gc
}
// SetID sets the "id" field.
func (gc *GroupCreate) SetID(u uuid.UUID) *GroupCreate {
gc.mutation.SetID(u)
return gc
}
// SetNillableID sets the "id" field if the given value is not nil.
func (gc *GroupCreate) SetNillableID(u *uuid.UUID) *GroupCreate {
if u != nil {
gc.SetID(*u)
}
return gc
}
// AddUserIDs adds the "users" edge to the User entity by IDs.
func (gc *GroupCreate) AddUserIDs(ids ...uuid.UUID) *GroupCreate {
gc.mutation.AddUserIDs(ids...)
return gc
}
// AddUsers adds the "users" edges to the User entity.
func (gc *GroupCreate) AddUsers(u ...*User) *GroupCreate {
ids := make([]uuid.UUID, len(u))
for i := range u {
ids[i] = u[i].ID
}
return gc.AddUserIDs(ids...)
}
// AddLocationIDs adds the "locations" edge to the Location entity by IDs.
func (gc *GroupCreate) AddLocationIDs(ids ...uuid.UUID) *GroupCreate {
gc.mutation.AddLocationIDs(ids...)
return gc
}
// AddLocations adds the "locations" edges to the Location entity.
func (gc *GroupCreate) AddLocations(l ...*Location) *GroupCreate {
ids := make([]uuid.UUID, len(l))
for i := range l {
ids[i] = l[i].ID
}
return gc.AddLocationIDs(ids...)
}
// AddItemIDs adds the "items" edge to the Item entity by IDs.
func (gc *GroupCreate) AddItemIDs(ids ...uuid.UUID) *GroupCreate {
gc.mutation.AddItemIDs(ids...)
return gc
}
// AddItems adds the "items" edges to the Item entity.
func (gc *GroupCreate) AddItems(i ...*Item) *GroupCreate {
ids := make([]uuid.UUID, len(i))
for j := range i {
ids[j] = i[j].ID
}
return gc.AddItemIDs(ids...)
}
// AddLabelIDs adds the "labels" edge to the Label entity by IDs.
func (gc *GroupCreate) AddLabelIDs(ids ...uuid.UUID) *GroupCreate {
gc.mutation.AddLabelIDs(ids...)
return gc
}
// AddLabels adds the "labels" edges to the Label entity.
func (gc *GroupCreate) AddLabels(l ...*Label) *GroupCreate {
ids := make([]uuid.UUID, len(l))
for i := range l {
ids[i] = l[i].ID
}
return gc.AddLabelIDs(ids...)
}
// AddDocumentIDs adds the "documents" edge to the Document entity by IDs.
func (gc *GroupCreate) AddDocumentIDs(ids ...uuid.UUID) *GroupCreate {
gc.mutation.AddDocumentIDs(ids...)
return gc
}
// AddDocuments adds the "documents" edges to the Document entity.
func (gc *GroupCreate) AddDocuments(d ...*Document) *GroupCreate {
ids := make([]uuid.UUID, len(d))
for i := range d {
ids[i] = d[i].ID
}
return gc.AddDocumentIDs(ids...)
}
// AddInvitationTokenIDs adds the "invitation_tokens" edge to the GroupInvitationToken entity by IDs.
func (gc *GroupCreate) AddInvitationTokenIDs(ids ...uuid.UUID) *GroupCreate {
gc.mutation.AddInvitationTokenIDs(ids...)
return gc
}
// AddInvitationTokens adds the "invitation_tokens" edges to the GroupInvitationToken entity.
func (gc *GroupCreate) AddInvitationTokens(g ...*GroupInvitationToken) *GroupCreate {
ids := make([]uuid.UUID, len(g))
for i := range g {
ids[i] = g[i].ID
}
return gc.AddInvitationTokenIDs(ids...)
}
// Mutation returns the GroupMutation object of the builder.
func (gc *GroupCreate) Mutation() *GroupMutation {
return gc.mutation
}
// Save creates the Group in the database.
func (gc *GroupCreate) Save(ctx context.Context) (*Group, error) {
var (
err error
node *Group
)
gc.defaults()
if len(gc.hooks) == 0 {
if err = gc.check(); err != nil {
return nil, err
}
node, err = gc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*GroupMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = gc.check(); err != nil {
return nil, err
}
gc.mutation = mutation
if node, err = gc.sqlSave(ctx); err != nil {
return nil, err
}
mutation.id = &node.ID
mutation.done = true
return node, err
})
for i := len(gc.hooks) - 1; i >= 0; i-- {
if gc.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = gc.hooks[i](mut)
}
v, err := mut.Mutate(ctx, gc.mutation)
if err != nil {
return nil, err
}
nv, ok := v.(*Group)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from GroupMutation", v)
}
node = nv
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (gc *GroupCreate) SaveX(ctx context.Context) *Group {
v, err := gc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (gc *GroupCreate) Exec(ctx context.Context) error {
_, err := gc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (gc *GroupCreate) ExecX(ctx context.Context) {
if err := gc.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (gc *GroupCreate) defaults() {
if _, ok := gc.mutation.CreatedAt(); !ok {
v := group.DefaultCreatedAt()
gc.mutation.SetCreatedAt(v)
}
if _, ok := gc.mutation.UpdatedAt(); !ok {
v := group.DefaultUpdatedAt()
gc.mutation.SetUpdatedAt(v)
}
if _, ok := gc.mutation.Currency(); !ok {
v := group.DefaultCurrency
gc.mutation.SetCurrency(v)
}
if _, ok := gc.mutation.ID(); !ok {
v := group.DefaultID()
gc.mutation.SetID(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (gc *GroupCreate) check() error {
if _, ok := gc.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Group.created_at"`)}
}
if _, ok := gc.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Group.updated_at"`)}
}
if _, ok := gc.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Group.name"`)}
}
if v, ok := gc.mutation.Name(); ok {
if err := group.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Group.name": %w`, err)}
}
}
if _, ok := gc.mutation.Currency(); !ok {
return &ValidationError{Name: "currency", err: errors.New(`ent: missing required field "Group.currency"`)}
}
if v, ok := gc.mutation.Currency(); ok {
if err := group.CurrencyValidator(v); err != nil {
return &ValidationError{Name: "currency", err: fmt.Errorf(`ent: validator failed for field "Group.currency": %w`, err)}
}
}
return nil
}
func (gc *GroupCreate) sqlSave(ctx context.Context) (*Group, error) {
_node, _spec := gc.createSpec()
if err := sqlgraph.CreateNode(ctx, gc.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 (gc *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) {
var (
_node = &Group{config: gc.config}
_spec = &sqlgraph.CreateSpec{
Table: group.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
}
)
if id, ok := gc.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = &id
}
if value, ok := gc.mutation.CreatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: group.FieldCreatedAt,
})
_node.CreatedAt = value
}
if value, ok := gc.mutation.UpdatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: group.FieldUpdatedAt,
})
_node.UpdatedAt = value
}
if value, ok := gc.mutation.Name(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: group.FieldName,
})
_node.Name = value
}
if value, ok := gc.mutation.Currency(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeEnum,
Value: value,
Column: group.FieldCurrency,
})
_node.Currency = value
}
if nodes := gc.mutation.UsersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: group.UsersTable,
Columns: []string{group.UsersColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: user.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := gc.mutation.LocationsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: group.LocationsTable,
Columns: []string{group.LocationsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: location.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := gc.mutation.ItemsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: group.ItemsTable,
Columns: []string{group.ItemsColumn},
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 = append(_spec.Edges, edge)
}
if nodes := gc.mutation.LabelsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: group.LabelsTable,
Columns: []string{group.LabelsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: label.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := gc.mutation.DocumentsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: group.DocumentsTable,
Columns: []string{group.DocumentsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: document.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := gc.mutation.InvitationTokensIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: group.InvitationTokensTable,
Columns: []string{group.InvitationTokensColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: groupinvitationtoken.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// GroupCreateBulk is the builder for creating many Group entities in bulk.
type GroupCreateBulk struct {
config
builders []*GroupCreate
}
// Save creates the Group entities in the database.
func (gcb *GroupCreateBulk) Save(ctx context.Context) ([]*Group, error) {
specs := make([]*sqlgraph.CreateSpec, len(gcb.builders))
nodes := make([]*Group, len(gcb.builders))
mutators := make([]Mutator, len(gcb.builders))
for i := range gcb.builders {
func(i int, root context.Context) {
builder := gcb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*GroupMutation)
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, gcb.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, gcb.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, gcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (gcb *GroupCreateBulk) SaveX(ctx context.Context) []*Group {
v, err := gcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (gcb *GroupCreateBulk) Exec(ctx context.Context) error {
_, err := gcb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (gcb *GroupCreateBulk) ExecX(ctx context.Context) {
if err := gcb.Exec(ctx); err != nil {
panic(err)
}
}

View file

@ -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/group"
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
)
// GroupDelete is the builder for deleting a Group entity.
type GroupDelete struct {
config
hooks []Hook
mutation *GroupMutation
}
// Where appends a list predicates to the GroupDelete builder.
func (gd *GroupDelete) Where(ps ...predicate.Group) *GroupDelete {
gd.mutation.Where(ps...)
return gd
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (gd *GroupDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(gd.hooks) == 0 {
affected, err = gd.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*GroupMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
gd.mutation = mutation
affected, err = gd.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(gd.hooks) - 1; i >= 0; i-- {
if gd.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = gd.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, gd.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (gd *GroupDelete) ExecX(ctx context.Context) int {
n, err := gd.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (gd *GroupDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: group.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
if ps := gd.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, gd.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return affected, err
}
// GroupDeleteOne is the builder for deleting a single Group entity.
type GroupDeleteOne struct {
gd *GroupDelete
}
// Exec executes the deletion query.
func (gdo *GroupDeleteOne) Exec(ctx context.Context) error {
n, err := gdo.gd.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{group.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (gdo *GroupDeleteOne) ExecX(ctx context.Context) {
gdo.gd.ExecX(ctx)
}

View file

@ -0,0 +1,987 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"database/sql/driver"
"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/document"
"github.com/hay-kot/homebox/backend/internal/data/ent/group"
"github.com/hay-kot/homebox/backend/internal/data/ent/groupinvitationtoken"
"github.com/hay-kot/homebox/backend/internal/data/ent/item"
"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/predicate"
"github.com/hay-kot/homebox/backend/internal/data/ent/user"
)
// GroupQuery is the builder for querying Group entities.
type GroupQuery struct {
config
limit *int
offset *int
unique *bool
order []OrderFunc
fields []string
predicates []predicate.Group
withUsers *UserQuery
withLocations *LocationQuery
withItems *ItemQuery
withLabels *LabelQuery
withDocuments *DocumentQuery
withInvitationTokens *GroupInvitationTokenQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the GroupQuery builder.
func (gq *GroupQuery) Where(ps ...predicate.Group) *GroupQuery {
gq.predicates = append(gq.predicates, ps...)
return gq
}
// Limit adds a limit step to the query.
func (gq *GroupQuery) Limit(limit int) *GroupQuery {
gq.limit = &limit
return gq
}
// Offset adds an offset step to the query.
func (gq *GroupQuery) Offset(offset int) *GroupQuery {
gq.offset = &offset
return gq
}
// 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 (gq *GroupQuery) Unique(unique bool) *GroupQuery {
gq.unique = &unique
return gq
}
// Order adds an order step to the query.
func (gq *GroupQuery) Order(o ...OrderFunc) *GroupQuery {
gq.order = append(gq.order, o...)
return gq
}
// QueryUsers chains the current query on the "users" edge.
func (gq *GroupQuery) QueryUsers() *UserQuery {
query := &UserQuery{config: gq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := gq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := gq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(group.Table, group.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, group.UsersTable, group.UsersColumn),
)
fromU = sqlgraph.SetNeighbors(gq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryLocations chains the current query on the "locations" edge.
func (gq *GroupQuery) QueryLocations() *LocationQuery {
query := &LocationQuery{config: gq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := gq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := gq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(group.Table, group.FieldID, selector),
sqlgraph.To(location.Table, location.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, group.LocationsTable, group.LocationsColumn),
)
fromU = sqlgraph.SetNeighbors(gq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryItems chains the current query on the "items" edge.
func (gq *GroupQuery) QueryItems() *ItemQuery {
query := &ItemQuery{config: gq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := gq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := gq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(group.Table, group.FieldID, selector),
sqlgraph.To(item.Table, item.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, group.ItemsTable, group.ItemsColumn),
)
fromU = sqlgraph.SetNeighbors(gq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryLabels chains the current query on the "labels" edge.
func (gq *GroupQuery) QueryLabels() *LabelQuery {
query := &LabelQuery{config: gq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := gq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := gq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(group.Table, group.FieldID, selector),
sqlgraph.To(label.Table, label.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, group.LabelsTable, group.LabelsColumn),
)
fromU = sqlgraph.SetNeighbors(gq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryDocuments chains the current query on the "documents" edge.
func (gq *GroupQuery) QueryDocuments() *DocumentQuery {
query := &DocumentQuery{config: gq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := gq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := gq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(group.Table, group.FieldID, selector),
sqlgraph.To(document.Table, document.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, group.DocumentsTable, group.DocumentsColumn),
)
fromU = sqlgraph.SetNeighbors(gq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryInvitationTokens chains the current query on the "invitation_tokens" edge.
func (gq *GroupQuery) QueryInvitationTokens() *GroupInvitationTokenQuery {
query := &GroupInvitationTokenQuery{config: gq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := gq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := gq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(group.Table, group.FieldID, selector),
sqlgraph.To(groupinvitationtoken.Table, groupinvitationtoken.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, group.InvitationTokensTable, group.InvitationTokensColumn),
)
fromU = sqlgraph.SetNeighbors(gq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Group entity from the query.
// Returns a *NotFoundError when no Group was found.
func (gq *GroupQuery) First(ctx context.Context) (*Group, error) {
nodes, err := gq.Limit(1).All(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{group.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (gq *GroupQuery) FirstX(ctx context.Context) *Group {
node, err := gq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Group ID from the query.
// Returns a *NotFoundError when no Group ID was found.
func (gq *GroupQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = gq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{group.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (gq *GroupQuery) FirstIDX(ctx context.Context) uuid.UUID {
id, err := gq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Group entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Group entity is found.
// Returns a *NotFoundError when no Group entities are found.
func (gq *GroupQuery) Only(ctx context.Context) (*Group, error) {
nodes, err := gq.Limit(2).All(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{group.Label}
default:
return nil, &NotSingularError{group.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (gq *GroupQuery) OnlyX(ctx context.Context) *Group {
node, err := gq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Group ID in the query.
// Returns a *NotSingularError when more than one Group ID is found.
// Returns a *NotFoundError when no entities are found.
func (gq *GroupQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = gq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{group.Label}
default:
err = &NotSingularError{group.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (gq *GroupQuery) OnlyIDX(ctx context.Context) uuid.UUID {
id, err := gq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Groups.
func (gq *GroupQuery) All(ctx context.Context) ([]*Group, error) {
if err := gq.prepareQuery(ctx); err != nil {
return nil, err
}
return gq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (gq *GroupQuery) AllX(ctx context.Context) []*Group {
nodes, err := gq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Group IDs.
func (gq *GroupQuery) IDs(ctx context.Context) ([]uuid.UUID, error) {
var ids []uuid.UUID
if err := gq.Select(group.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (gq *GroupQuery) IDsX(ctx context.Context) []uuid.UUID {
ids, err := gq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (gq *GroupQuery) Count(ctx context.Context) (int, error) {
if err := gq.prepareQuery(ctx); err != nil {
return 0, err
}
return gq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (gq *GroupQuery) CountX(ctx context.Context) int {
count, err := gq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (gq *GroupQuery) Exist(ctx context.Context) (bool, error) {
if err := gq.prepareQuery(ctx); err != nil {
return false, err
}
return gq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (gq *GroupQuery) ExistX(ctx context.Context) bool {
exist, err := gq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the GroupQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (gq *GroupQuery) Clone() *GroupQuery {
if gq == nil {
return nil
}
return &GroupQuery{
config: gq.config,
limit: gq.limit,
offset: gq.offset,
order: append([]OrderFunc{}, gq.order...),
predicates: append([]predicate.Group{}, gq.predicates...),
withUsers: gq.withUsers.Clone(),
withLocations: gq.withLocations.Clone(),
withItems: gq.withItems.Clone(),
withLabels: gq.withLabels.Clone(),
withDocuments: gq.withDocuments.Clone(),
withInvitationTokens: gq.withInvitationTokens.Clone(),
// clone intermediate query.
sql: gq.sql.Clone(),
path: gq.path,
unique: gq.unique,
}
}
// WithUsers tells the query-builder to eager-load the nodes that are connected to
// the "users" edge. The optional arguments are used to configure the query builder of the edge.
func (gq *GroupQuery) WithUsers(opts ...func(*UserQuery)) *GroupQuery {
query := &UserQuery{config: gq.config}
for _, opt := range opts {
opt(query)
}
gq.withUsers = query
return gq
}
// WithLocations tells the query-builder to eager-load the nodes that are connected to
// the "locations" edge. The optional arguments are used to configure the query builder of the edge.
func (gq *GroupQuery) WithLocations(opts ...func(*LocationQuery)) *GroupQuery {
query := &LocationQuery{config: gq.config}
for _, opt := range opts {
opt(query)
}
gq.withLocations = query
return gq
}
// WithItems tells the query-builder to eager-load the nodes that are connected to
// the "items" edge. The optional arguments are used to configure the query builder of the edge.
func (gq *GroupQuery) WithItems(opts ...func(*ItemQuery)) *GroupQuery {
query := &ItemQuery{config: gq.config}
for _, opt := range opts {
opt(query)
}
gq.withItems = query
return gq
}
// WithLabels tells the query-builder to eager-load the nodes that are connected to
// the "labels" edge. The optional arguments are used to configure the query builder of the edge.
func (gq *GroupQuery) WithLabels(opts ...func(*LabelQuery)) *GroupQuery {
query := &LabelQuery{config: gq.config}
for _, opt := range opts {
opt(query)
}
gq.withLabels = query
return gq
}
// WithDocuments tells the query-builder to eager-load the nodes that are connected to
// the "documents" edge. The optional arguments are used to configure the query builder of the edge.
func (gq *GroupQuery) WithDocuments(opts ...func(*DocumentQuery)) *GroupQuery {
query := &DocumentQuery{config: gq.config}
for _, opt := range opts {
opt(query)
}
gq.withDocuments = query
return gq
}
// WithInvitationTokens tells the query-builder to eager-load the nodes that are connected to
// the "invitation_tokens" edge. The optional arguments are used to configure the query builder of the edge.
func (gq *GroupQuery) WithInvitationTokens(opts ...func(*GroupInvitationTokenQuery)) *GroupQuery {
query := &GroupInvitationTokenQuery{config: gq.config}
for _, opt := range opts {
opt(query)
}
gq.withInvitationTokens = query
return gq
}
// 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.Group.Query().
// GroupBy(group.FieldCreatedAt).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (gq *GroupQuery) GroupBy(field string, fields ...string) *GroupGroupBy {
grbuild := &GroupGroupBy{config: gq.config}
grbuild.fields = append([]string{field}, fields...)
grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := gq.prepareQuery(ctx); err != nil {
return nil, err
}
return gq.sqlQuery(ctx), nil
}
grbuild.label = group.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.Group.Query().
// Select(group.FieldCreatedAt).
// Scan(ctx, &v)
func (gq *GroupQuery) Select(fields ...string) *GroupSelect {
gq.fields = append(gq.fields, fields...)
selbuild := &GroupSelect{GroupQuery: gq}
selbuild.label = group.Label
selbuild.flds, selbuild.scan = &gq.fields, selbuild.Scan
return selbuild
}
func (gq *GroupQuery) prepareQuery(ctx context.Context) error {
for _, f := range gq.fields {
if !group.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if gq.path != nil {
prev, err := gq.path(ctx)
if err != nil {
return err
}
gq.sql = prev
}
return nil
}
func (gq *GroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Group, error) {
var (
nodes = []*Group{}
_spec = gq.querySpec()
loadedTypes = [6]bool{
gq.withUsers != nil,
gq.withLocations != nil,
gq.withItems != nil,
gq.withLabels != nil,
gq.withDocuments != nil,
gq.withInvitationTokens != nil,
}
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Group).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Group{config: gq.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, gq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := gq.withUsers; query != nil {
if err := gq.loadUsers(ctx, query, nodes,
func(n *Group) { n.Edges.Users = []*User{} },
func(n *Group, e *User) { n.Edges.Users = append(n.Edges.Users, e) }); err != nil {
return nil, err
}
}
if query := gq.withLocations; query != nil {
if err := gq.loadLocations(ctx, query, nodes,
func(n *Group) { n.Edges.Locations = []*Location{} },
func(n *Group, e *Location) { n.Edges.Locations = append(n.Edges.Locations, e) }); err != nil {
return nil, err
}
}
if query := gq.withItems; query != nil {
if err := gq.loadItems(ctx, query, nodes,
func(n *Group) { n.Edges.Items = []*Item{} },
func(n *Group, e *Item) { n.Edges.Items = append(n.Edges.Items, e) }); err != nil {
return nil, err
}
}
if query := gq.withLabels; query != nil {
if err := gq.loadLabels(ctx, query, nodes,
func(n *Group) { n.Edges.Labels = []*Label{} },
func(n *Group, e *Label) { n.Edges.Labels = append(n.Edges.Labels, e) }); err != nil {
return nil, err
}
}
if query := gq.withDocuments; query != nil {
if err := gq.loadDocuments(ctx, query, nodes,
func(n *Group) { n.Edges.Documents = []*Document{} },
func(n *Group, e *Document) { n.Edges.Documents = append(n.Edges.Documents, e) }); err != nil {
return nil, err
}
}
if query := gq.withInvitationTokens; query != nil {
if err := gq.loadInvitationTokens(ctx, query, nodes,
func(n *Group) { n.Edges.InvitationTokens = []*GroupInvitationToken{} },
func(n *Group, e *GroupInvitationToken) {
n.Edges.InvitationTokens = append(n.Edges.InvitationTokens, e)
}); err != nil {
return nil, err
}
}
return nodes, nil
}
func (gq *GroupQuery) loadUsers(ctx context.Context, query *UserQuery, nodes []*Group, init func(*Group), assign func(*Group, *User)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[uuid.UUID]*Group)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
query.withFKs = true
query.Where(predicate.User(func(s *sql.Selector) {
s.Where(sql.InValues(group.UsersColumn, fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.group_users
if fk == nil {
return fmt.Errorf(`foreign-key "group_users" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected foreign-key "group_users" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (gq *GroupQuery) loadLocations(ctx context.Context, query *LocationQuery, nodes []*Group, init func(*Group), assign func(*Group, *Location)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[uuid.UUID]*Group)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
query.withFKs = true
query.Where(predicate.Location(func(s *sql.Selector) {
s.Where(sql.InValues(group.LocationsColumn, fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.group_locations
if fk == nil {
return fmt.Errorf(`foreign-key "group_locations" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected foreign-key "group_locations" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (gq *GroupQuery) loadItems(ctx context.Context, query *ItemQuery, nodes []*Group, init func(*Group), assign func(*Group, *Item)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[uuid.UUID]*Group)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
query.withFKs = true
query.Where(predicate.Item(func(s *sql.Selector) {
s.Where(sql.InValues(group.ItemsColumn, fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.group_items
if fk == nil {
return fmt.Errorf(`foreign-key "group_items" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected foreign-key "group_items" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (gq *GroupQuery) loadLabels(ctx context.Context, query *LabelQuery, nodes []*Group, init func(*Group), assign func(*Group, *Label)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[uuid.UUID]*Group)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
query.withFKs = true
query.Where(predicate.Label(func(s *sql.Selector) {
s.Where(sql.InValues(group.LabelsColumn, fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.group_labels
if fk == nil {
return fmt.Errorf(`foreign-key "group_labels" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected foreign-key "group_labels" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (gq *GroupQuery) loadDocuments(ctx context.Context, query *DocumentQuery, nodes []*Group, init func(*Group), assign func(*Group, *Document)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[uuid.UUID]*Group)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
query.withFKs = true
query.Where(predicate.Document(func(s *sql.Selector) {
s.Where(sql.InValues(group.DocumentsColumn, fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.group_documents
if fk == nil {
return fmt.Errorf(`foreign-key "group_documents" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected foreign-key "group_documents" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (gq *GroupQuery) loadInvitationTokens(ctx context.Context, query *GroupInvitationTokenQuery, nodes []*Group, init func(*Group), assign func(*Group, *GroupInvitationToken)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[uuid.UUID]*Group)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
query.withFKs = true
query.Where(predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.InValues(group.InvitationTokensColumn, fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.group_invitation_tokens
if fk == nil {
return fmt.Errorf(`foreign-key "group_invitation_tokens" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected foreign-key "group_invitation_tokens" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (gq *GroupQuery) sqlCount(ctx context.Context) (int, error) {
_spec := gq.querySpec()
_spec.Node.Columns = gq.fields
if len(gq.fields) > 0 {
_spec.Unique = gq.unique != nil && *gq.unique
}
return sqlgraph.CountNodes(ctx, gq.driver, _spec)
}
func (gq *GroupQuery) sqlExist(ctx context.Context) (bool, error) {
switch _, err := gq.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 (gq *GroupQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: group.Table,
Columns: group.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
From: gq.sql,
Unique: true,
}
if unique := gq.unique; unique != nil {
_spec.Unique = *unique
}
if fields := gq.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, group.FieldID)
for i := range fields {
if fields[i] != group.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := gq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := gq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := gq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := gq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (gq *GroupQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(gq.driver.Dialect())
t1 := builder.Table(group.Table)
columns := gq.fields
if len(columns) == 0 {
columns = group.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if gq.sql != nil {
selector = gq.sql
selector.Select(selector.Columns(columns...)...)
}
if gq.unique != nil && *gq.unique {
selector.Distinct()
}
for _, p := range gq.predicates {
p(selector)
}
for _, p := range gq.order {
p(selector)
}
if offset := gq.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 := gq.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// GroupGroupBy is the group-by builder for Group entities.
type GroupGroupBy 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 (ggb *GroupGroupBy) Aggregate(fns ...AggregateFunc) *GroupGroupBy {
ggb.fns = append(ggb.fns, fns...)
return ggb
}
// Scan applies the group-by query and scans the result into the given value.
func (ggb *GroupGroupBy) Scan(ctx context.Context, v any) error {
query, err := ggb.path(ctx)
if err != nil {
return err
}
ggb.sql = query
return ggb.sqlScan(ctx, v)
}
func (ggb *GroupGroupBy) sqlScan(ctx context.Context, v any) error {
for _, f := range ggb.fields {
if !group.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := ggb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := ggb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (ggb *GroupGroupBy) sqlQuery() *sql.Selector {
selector := ggb.sql.Select()
aggregation := make([]string, 0, len(ggb.fns))
for _, fn := range ggb.fns {
aggregation = append(aggregation, fn(selector))
}
// If no columns were selected in a custom aggregation function, the default
// selection is the fields used for "group-by", and the aggregation functions.
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(ggb.fields)+len(ggb.fns))
for _, f := range ggb.fields {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
return selector.GroupBy(selector.Columns(ggb.fields...)...)
}
// GroupSelect is the builder for selecting fields of Group entities.
type GroupSelect struct {
*GroupQuery
selector
// intermediate query (i.e. traversal path).
sql *sql.Selector
}
// Scan applies the selector query and scans the result into the given value.
func (gs *GroupSelect) Scan(ctx context.Context, v any) error {
if err := gs.prepareQuery(ctx); err != nil {
return err
}
gs.sql = gs.GroupQuery.sqlQuery(ctx)
return gs.sqlScan(ctx, v)
}
func (gs *GroupSelect) sqlScan(ctx context.Context, v any) error {
rows := &sql.Rows{}
query, args := gs.sql.Query()
if err := gs.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,190 @@
// 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/group"
"github.com/hay-kot/homebox/backend/internal/data/ent/groupinvitationtoken"
)
// GroupInvitationToken is the model entity for the GroupInvitationToken schema.
type GroupInvitationToken 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"`
// Token holds the value of the "token" field.
Token []byte `json:"token,omitempty"`
// ExpiresAt holds the value of the "expires_at" field.
ExpiresAt time.Time `json:"expires_at,omitempty"`
// Uses holds the value of the "uses" field.
Uses int `json:"uses,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the GroupInvitationTokenQuery when eager-loading is set.
Edges GroupInvitationTokenEdges `json:"edges"`
group_invitation_tokens *uuid.UUID
}
// GroupInvitationTokenEdges holds the relations/edges for other nodes in the graph.
type GroupInvitationTokenEdges struct {
// Group holds the value of the group edge.
Group *Group `json:"group,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [1]bool
}
// GroupOrErr returns the Group value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e GroupInvitationTokenEdges) GroupOrErr() (*Group, error) {
if e.loadedTypes[0] {
if e.Group == nil {
// Edge was loaded but was not found.
return nil, &NotFoundError{label: group.Label}
}
return e.Group, nil
}
return nil, &NotLoadedError{edge: "group"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*GroupInvitationToken) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case groupinvitationtoken.FieldToken:
values[i] = new([]byte)
case groupinvitationtoken.FieldUses:
values[i] = new(sql.NullInt64)
case groupinvitationtoken.FieldCreatedAt, groupinvitationtoken.FieldUpdatedAt, groupinvitationtoken.FieldExpiresAt:
values[i] = new(sql.NullTime)
case groupinvitationtoken.FieldID:
values[i] = new(uuid.UUID)
case groupinvitationtoken.ForeignKeys[0]: // group_invitation_tokens
values[i] = &sql.NullScanner{S: new(uuid.UUID)}
default:
return nil, fmt.Errorf("unexpected column %q for type GroupInvitationToken", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the GroupInvitationToken fields.
func (git *GroupInvitationToken) 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 groupinvitationtoken.FieldID:
if value, ok := values[i].(*uuid.UUID); !ok {
return fmt.Errorf("unexpected type %T for field id", values[i])
} else if value != nil {
git.ID = *value
}
case groupinvitationtoken.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 {
git.CreatedAt = value.Time
}
case groupinvitationtoken.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 {
git.UpdatedAt = value.Time
}
case groupinvitationtoken.FieldToken:
if value, ok := values[i].(*[]byte); !ok {
return fmt.Errorf("unexpected type %T for field token", values[i])
} else if value != nil {
git.Token = *value
}
case groupinvitationtoken.FieldExpiresAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field expires_at", values[i])
} else if value.Valid {
git.ExpiresAt = value.Time
}
case groupinvitationtoken.FieldUses:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field uses", values[i])
} else if value.Valid {
git.Uses = int(value.Int64)
}
case groupinvitationtoken.ForeignKeys[0]:
if value, ok := values[i].(*sql.NullScanner); !ok {
return fmt.Errorf("unexpected type %T for field group_invitation_tokens", values[i])
} else if value.Valid {
git.group_invitation_tokens = new(uuid.UUID)
*git.group_invitation_tokens = *value.S.(*uuid.UUID)
}
}
}
return nil
}
// QueryGroup queries the "group" edge of the GroupInvitationToken entity.
func (git *GroupInvitationToken) QueryGroup() *GroupQuery {
return (&GroupInvitationTokenClient{config: git.config}).QueryGroup(git)
}
// Update returns a builder for updating this GroupInvitationToken.
// Note that you need to call GroupInvitationToken.Unwrap() before calling this method if this GroupInvitationToken
// was returned from a transaction, and the transaction was committed or rolled back.
func (git *GroupInvitationToken) Update() *GroupInvitationTokenUpdateOne {
return (&GroupInvitationTokenClient{config: git.config}).UpdateOne(git)
}
// Unwrap unwraps the GroupInvitationToken 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 (git *GroupInvitationToken) Unwrap() *GroupInvitationToken {
_tx, ok := git.config.driver.(*txDriver)
if !ok {
panic("ent: GroupInvitationToken is not a transactional entity")
}
git.config.driver = _tx.drv
return git
}
// String implements the fmt.Stringer.
func (git *GroupInvitationToken) String() string {
var builder strings.Builder
builder.WriteString("GroupInvitationToken(")
builder.WriteString(fmt.Sprintf("id=%v, ", git.ID))
builder.WriteString("created_at=")
builder.WriteString(git.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(git.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("token=")
builder.WriteString(fmt.Sprintf("%v", git.Token))
builder.WriteString(", ")
builder.WriteString("expires_at=")
builder.WriteString(git.ExpiresAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("uses=")
builder.WriteString(fmt.Sprintf("%v", git.Uses))
builder.WriteByte(')')
return builder.String()
}
// GroupInvitationTokens is a parsable slice of GroupInvitationToken.
type GroupInvitationTokens []*GroupInvitationToken
func (git GroupInvitationTokens) config(cfg config) {
for _i := range git {
git[_i].config = cfg
}
}

View file

@ -0,0 +1,83 @@
// Code generated by ent, DO NOT EDIT.
package groupinvitationtoken
import (
"time"
"github.com/google/uuid"
)
const (
// Label holds the string label denoting the groupinvitationtoken type in the database.
Label = "group_invitation_token"
// 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"
// FieldToken holds the string denoting the token field in the database.
FieldToken = "token"
// FieldExpiresAt holds the string denoting the expires_at field in the database.
FieldExpiresAt = "expires_at"
// FieldUses holds the string denoting the uses field in the database.
FieldUses = "uses"
// EdgeGroup holds the string denoting the group edge name in mutations.
EdgeGroup = "group"
// Table holds the table name of the groupinvitationtoken in the database.
Table = "group_invitation_tokens"
// GroupTable is the table that holds the group relation/edge.
GroupTable = "group_invitation_tokens"
// GroupInverseTable is the table name for the Group entity.
// It exists in this package in order to avoid circular dependency with the "group" package.
GroupInverseTable = "groups"
// GroupColumn is the table column denoting the group relation/edge.
GroupColumn = "group_invitation_tokens"
)
// Columns holds all SQL columns for groupinvitationtoken fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldToken,
FieldExpiresAt,
FieldUses,
}
// ForeignKeys holds the SQL foreign-keys that are owned by the "group_invitation_tokens"
// table and are not defined as standalone fields in the schema.
var ForeignKeys = []string{
"group_invitation_tokens",
}
// 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
}
}
for i := range ForeignKeys {
if column == ForeignKeys[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
// DefaultExpiresAt holds the default value on creation for the "expires_at" field.
DefaultExpiresAt func() time.Time
// DefaultUses holds the default value on creation for the "uses" field.
DefaultUses int
// DefaultID holds the default value on creation for the "id" field.
DefaultID func() uuid.UUID
)

View file

@ -0,0 +1,498 @@
// Code generated by ent, DO NOT EDIT.
package groupinvitationtoken
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.GroupInvitationToken {
return predicate.GroupInvitationToken(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.GroupInvitationToken {
return predicate.GroupInvitationToken(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.GroupInvitationToken {
return predicate.GroupInvitationToken(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.GroupInvitationToken {
return predicate.GroupInvitationToken(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.GroupInvitationToken {
return predicate.GroupInvitationToken(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.GroupInvitationToken {
return predicate.GroupInvitationToken(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.GroupInvitationToken {
return predicate.GroupInvitationToken(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.GroupInvitationToken {
return predicate.GroupInvitationToken(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.GroupInvitationToken {
return predicate.GroupInvitationToken(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.GroupInvitationToken {
return predicate.GroupInvitationToken(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.GroupInvitationToken {
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
})
}
// Token applies equality check predicate on the "token" field. It's identical to TokenEQ.
func Token(v []byte) predicate.GroupInvitationToken {
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldToken), v))
})
}
// ExpiresAt applies equality check predicate on the "expires_at" field. It's identical to ExpiresAtEQ.
func ExpiresAt(v time.Time) predicate.GroupInvitationToken {
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldExpiresAt), v))
})
}
// Uses applies equality check predicate on the "uses" field. It's identical to UsesEQ.
func Uses(v int) predicate.GroupInvitationToken {
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUses), v))
})
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.GroupInvitationToken {
return predicate.GroupInvitationToken(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.GroupInvitationToken {
return predicate.GroupInvitationToken(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.GroupInvitationToken {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GroupInvitationToken(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.GroupInvitationToken {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GroupInvitationToken(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.GroupInvitationToken {
return predicate.GroupInvitationToken(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.GroupInvitationToken {
return predicate.GroupInvitationToken(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.GroupInvitationToken {
return predicate.GroupInvitationToken(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.GroupInvitationToken {
return predicate.GroupInvitationToken(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.GroupInvitationToken {
return predicate.GroupInvitationToken(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.GroupInvitationToken {
return predicate.GroupInvitationToken(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.GroupInvitationToken {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GroupInvitationToken(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.GroupInvitationToken {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GroupInvitationToken(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.GroupInvitationToken {
return predicate.GroupInvitationToken(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.GroupInvitationToken {
return predicate.GroupInvitationToken(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.GroupInvitationToken {
return predicate.GroupInvitationToken(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.GroupInvitationToken {
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldUpdatedAt), v))
})
}
// TokenEQ applies the EQ predicate on the "token" field.
func TokenEQ(v []byte) predicate.GroupInvitationToken {
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldToken), v))
})
}
// TokenNEQ applies the NEQ predicate on the "token" field.
func TokenNEQ(v []byte) predicate.GroupInvitationToken {
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldToken), v))
})
}
// TokenIn applies the In predicate on the "token" field.
func TokenIn(vs ...[]byte) predicate.GroupInvitationToken {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldToken), v...))
})
}
// TokenNotIn applies the NotIn predicate on the "token" field.
func TokenNotIn(vs ...[]byte) predicate.GroupInvitationToken {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldToken), v...))
})
}
// TokenGT applies the GT predicate on the "token" field.
func TokenGT(v []byte) predicate.GroupInvitationToken {
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldToken), v))
})
}
// TokenGTE applies the GTE predicate on the "token" field.
func TokenGTE(v []byte) predicate.GroupInvitationToken {
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldToken), v))
})
}
// TokenLT applies the LT predicate on the "token" field.
func TokenLT(v []byte) predicate.GroupInvitationToken {
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldToken), v))
})
}
// TokenLTE applies the LTE predicate on the "token" field.
func TokenLTE(v []byte) predicate.GroupInvitationToken {
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldToken), v))
})
}
// ExpiresAtEQ applies the EQ predicate on the "expires_at" field.
func ExpiresAtEQ(v time.Time) predicate.GroupInvitationToken {
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldExpiresAt), v))
})
}
// ExpiresAtNEQ applies the NEQ predicate on the "expires_at" field.
func ExpiresAtNEQ(v time.Time) predicate.GroupInvitationToken {
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldExpiresAt), v))
})
}
// ExpiresAtIn applies the In predicate on the "expires_at" field.
func ExpiresAtIn(vs ...time.Time) predicate.GroupInvitationToken {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldExpiresAt), v...))
})
}
// ExpiresAtNotIn applies the NotIn predicate on the "expires_at" field.
func ExpiresAtNotIn(vs ...time.Time) predicate.GroupInvitationToken {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldExpiresAt), v...))
})
}
// ExpiresAtGT applies the GT predicate on the "expires_at" field.
func ExpiresAtGT(v time.Time) predicate.GroupInvitationToken {
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldExpiresAt), v))
})
}
// ExpiresAtGTE applies the GTE predicate on the "expires_at" field.
func ExpiresAtGTE(v time.Time) predicate.GroupInvitationToken {
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldExpiresAt), v))
})
}
// ExpiresAtLT applies the LT predicate on the "expires_at" field.
func ExpiresAtLT(v time.Time) predicate.GroupInvitationToken {
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldExpiresAt), v))
})
}
// ExpiresAtLTE applies the LTE predicate on the "expires_at" field.
func ExpiresAtLTE(v time.Time) predicate.GroupInvitationToken {
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldExpiresAt), v))
})
}
// UsesEQ applies the EQ predicate on the "uses" field.
func UsesEQ(v int) predicate.GroupInvitationToken {
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUses), v))
})
}
// UsesNEQ applies the NEQ predicate on the "uses" field.
func UsesNEQ(v int) predicate.GroupInvitationToken {
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldUses), v))
})
}
// UsesIn applies the In predicate on the "uses" field.
func UsesIn(vs ...int) predicate.GroupInvitationToken {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldUses), v...))
})
}
// UsesNotIn applies the NotIn predicate on the "uses" field.
func UsesNotIn(vs ...int) predicate.GroupInvitationToken {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldUses), v...))
})
}
// UsesGT applies the GT predicate on the "uses" field.
func UsesGT(v int) predicate.GroupInvitationToken {
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldUses), v))
})
}
// UsesGTE applies the GTE predicate on the "uses" field.
func UsesGTE(v int) predicate.GroupInvitationToken {
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldUses), v))
})
}
// UsesLT applies the LT predicate on the "uses" field.
func UsesLT(v int) predicate.GroupInvitationToken {
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldUses), v))
})
}
// UsesLTE applies the LTE predicate on the "uses" field.
func UsesLTE(v int) predicate.GroupInvitationToken {
return predicate.GroupInvitationToken(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldUses), v))
})
}
// HasGroup applies the HasEdge predicate on the "group" edge.
func HasGroup() predicate.GroupInvitationToken {
return predicate.GroupInvitationToken(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(GroupTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasGroupWith applies the HasEdge predicate on the "group" edge with a given conditions (other predicates).
func HasGroupWith(preds ...predicate.Group) predicate.GroupInvitationToken {
return predicate.GroupInvitationToken(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(GroupInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn),
)
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.GroupInvitationToken) predicate.GroupInvitationToken {
return predicate.GroupInvitationToken(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.GroupInvitationToken) predicate.GroupInvitationToken {
return predicate.GroupInvitationToken(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.GroupInvitationToken) predicate.GroupInvitationToken {
return predicate.GroupInvitationToken(func(s *sql.Selector) {
p(s.Not())
})
}

View file

@ -0,0 +1,413 @@
// 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/group"
"github.com/hay-kot/homebox/backend/internal/data/ent/groupinvitationtoken"
)
// GroupInvitationTokenCreate is the builder for creating a GroupInvitationToken entity.
type GroupInvitationTokenCreate struct {
config
mutation *GroupInvitationTokenMutation
hooks []Hook
}
// SetCreatedAt sets the "created_at" field.
func (gitc *GroupInvitationTokenCreate) SetCreatedAt(t time.Time) *GroupInvitationTokenCreate {
gitc.mutation.SetCreatedAt(t)
return gitc
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (gitc *GroupInvitationTokenCreate) SetNillableCreatedAt(t *time.Time) *GroupInvitationTokenCreate {
if t != nil {
gitc.SetCreatedAt(*t)
}
return gitc
}
// SetUpdatedAt sets the "updated_at" field.
func (gitc *GroupInvitationTokenCreate) SetUpdatedAt(t time.Time) *GroupInvitationTokenCreate {
gitc.mutation.SetUpdatedAt(t)
return gitc
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (gitc *GroupInvitationTokenCreate) SetNillableUpdatedAt(t *time.Time) *GroupInvitationTokenCreate {
if t != nil {
gitc.SetUpdatedAt(*t)
}
return gitc
}
// SetToken sets the "token" field.
func (gitc *GroupInvitationTokenCreate) SetToken(b []byte) *GroupInvitationTokenCreate {
gitc.mutation.SetToken(b)
return gitc
}
// SetExpiresAt sets the "expires_at" field.
func (gitc *GroupInvitationTokenCreate) SetExpiresAt(t time.Time) *GroupInvitationTokenCreate {
gitc.mutation.SetExpiresAt(t)
return gitc
}
// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil.
func (gitc *GroupInvitationTokenCreate) SetNillableExpiresAt(t *time.Time) *GroupInvitationTokenCreate {
if t != nil {
gitc.SetExpiresAt(*t)
}
return gitc
}
// SetUses sets the "uses" field.
func (gitc *GroupInvitationTokenCreate) SetUses(i int) *GroupInvitationTokenCreate {
gitc.mutation.SetUses(i)
return gitc
}
// SetNillableUses sets the "uses" field if the given value is not nil.
func (gitc *GroupInvitationTokenCreate) SetNillableUses(i *int) *GroupInvitationTokenCreate {
if i != nil {
gitc.SetUses(*i)
}
return gitc
}
// SetID sets the "id" field.
func (gitc *GroupInvitationTokenCreate) SetID(u uuid.UUID) *GroupInvitationTokenCreate {
gitc.mutation.SetID(u)
return gitc
}
// SetNillableID sets the "id" field if the given value is not nil.
func (gitc *GroupInvitationTokenCreate) SetNillableID(u *uuid.UUID) *GroupInvitationTokenCreate {
if u != nil {
gitc.SetID(*u)
}
return gitc
}
// SetGroupID sets the "group" edge to the Group entity by ID.
func (gitc *GroupInvitationTokenCreate) SetGroupID(id uuid.UUID) *GroupInvitationTokenCreate {
gitc.mutation.SetGroupID(id)
return gitc
}
// SetNillableGroupID sets the "group" edge to the Group entity by ID if the given value is not nil.
func (gitc *GroupInvitationTokenCreate) SetNillableGroupID(id *uuid.UUID) *GroupInvitationTokenCreate {
if id != nil {
gitc = gitc.SetGroupID(*id)
}
return gitc
}
// SetGroup sets the "group" edge to the Group entity.
func (gitc *GroupInvitationTokenCreate) SetGroup(g *Group) *GroupInvitationTokenCreate {
return gitc.SetGroupID(g.ID)
}
// Mutation returns the GroupInvitationTokenMutation object of the builder.
func (gitc *GroupInvitationTokenCreate) Mutation() *GroupInvitationTokenMutation {
return gitc.mutation
}
// Save creates the GroupInvitationToken in the database.
func (gitc *GroupInvitationTokenCreate) Save(ctx context.Context) (*GroupInvitationToken, error) {
var (
err error
node *GroupInvitationToken
)
gitc.defaults()
if len(gitc.hooks) == 0 {
if err = gitc.check(); err != nil {
return nil, err
}
node, err = gitc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*GroupInvitationTokenMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = gitc.check(); err != nil {
return nil, err
}
gitc.mutation = mutation
if node, err = gitc.sqlSave(ctx); err != nil {
return nil, err
}
mutation.id = &node.ID
mutation.done = true
return node, err
})
for i := len(gitc.hooks) - 1; i >= 0; i-- {
if gitc.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = gitc.hooks[i](mut)
}
v, err := mut.Mutate(ctx, gitc.mutation)
if err != nil {
return nil, err
}
nv, ok := v.(*GroupInvitationToken)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from GroupInvitationTokenMutation", v)
}
node = nv
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (gitc *GroupInvitationTokenCreate) SaveX(ctx context.Context) *GroupInvitationToken {
v, err := gitc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (gitc *GroupInvitationTokenCreate) Exec(ctx context.Context) error {
_, err := gitc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (gitc *GroupInvitationTokenCreate) ExecX(ctx context.Context) {
if err := gitc.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (gitc *GroupInvitationTokenCreate) defaults() {
if _, ok := gitc.mutation.CreatedAt(); !ok {
v := groupinvitationtoken.DefaultCreatedAt()
gitc.mutation.SetCreatedAt(v)
}
if _, ok := gitc.mutation.UpdatedAt(); !ok {
v := groupinvitationtoken.DefaultUpdatedAt()
gitc.mutation.SetUpdatedAt(v)
}
if _, ok := gitc.mutation.ExpiresAt(); !ok {
v := groupinvitationtoken.DefaultExpiresAt()
gitc.mutation.SetExpiresAt(v)
}
if _, ok := gitc.mutation.Uses(); !ok {
v := groupinvitationtoken.DefaultUses
gitc.mutation.SetUses(v)
}
if _, ok := gitc.mutation.ID(); !ok {
v := groupinvitationtoken.DefaultID()
gitc.mutation.SetID(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (gitc *GroupInvitationTokenCreate) check() error {
if _, ok := gitc.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "GroupInvitationToken.created_at"`)}
}
if _, ok := gitc.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "GroupInvitationToken.updated_at"`)}
}
if _, ok := gitc.mutation.Token(); !ok {
return &ValidationError{Name: "token", err: errors.New(`ent: missing required field "GroupInvitationToken.token"`)}
}
if _, ok := gitc.mutation.ExpiresAt(); !ok {
return &ValidationError{Name: "expires_at", err: errors.New(`ent: missing required field "GroupInvitationToken.expires_at"`)}
}
if _, ok := gitc.mutation.Uses(); !ok {
return &ValidationError{Name: "uses", err: errors.New(`ent: missing required field "GroupInvitationToken.uses"`)}
}
return nil
}
func (gitc *GroupInvitationTokenCreate) sqlSave(ctx context.Context) (*GroupInvitationToken, error) {
_node, _spec := gitc.createSpec()
if err := sqlgraph.CreateNode(ctx, gitc.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 (gitc *GroupInvitationTokenCreate) createSpec() (*GroupInvitationToken, *sqlgraph.CreateSpec) {
var (
_node = &GroupInvitationToken{config: gitc.config}
_spec = &sqlgraph.CreateSpec{
Table: groupinvitationtoken.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: groupinvitationtoken.FieldID,
},
}
)
if id, ok := gitc.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = &id
}
if value, ok := gitc.mutation.CreatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: groupinvitationtoken.FieldCreatedAt,
})
_node.CreatedAt = value
}
if value, ok := gitc.mutation.UpdatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: groupinvitationtoken.FieldUpdatedAt,
})
_node.UpdatedAt = value
}
if value, ok := gitc.mutation.Token(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: groupinvitationtoken.FieldToken,
})
_node.Token = value
}
if value, ok := gitc.mutation.ExpiresAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: groupinvitationtoken.FieldExpiresAt,
})
_node.ExpiresAt = value
}
if value, ok := gitc.mutation.Uses(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: groupinvitationtoken.FieldUses,
})
_node.Uses = value
}
if nodes := gitc.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: groupinvitationtoken.GroupTable,
Columns: []string{groupinvitationtoken.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.group_invitation_tokens = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// GroupInvitationTokenCreateBulk is the builder for creating many GroupInvitationToken entities in bulk.
type GroupInvitationTokenCreateBulk struct {
config
builders []*GroupInvitationTokenCreate
}
// Save creates the GroupInvitationToken entities in the database.
func (gitcb *GroupInvitationTokenCreateBulk) Save(ctx context.Context) ([]*GroupInvitationToken, error) {
specs := make([]*sqlgraph.CreateSpec, len(gitcb.builders))
nodes := make([]*GroupInvitationToken, len(gitcb.builders))
mutators := make([]Mutator, len(gitcb.builders))
for i := range gitcb.builders {
func(i int, root context.Context) {
builder := gitcb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*GroupInvitationTokenMutation)
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, gitcb.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, gitcb.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, gitcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (gitcb *GroupInvitationTokenCreateBulk) SaveX(ctx context.Context) []*GroupInvitationToken {
v, err := gitcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (gitcb *GroupInvitationTokenCreateBulk) Exec(ctx context.Context) error {
_, err := gitcb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (gitcb *GroupInvitationTokenCreateBulk) ExecX(ctx context.Context) {
if err := gitcb.Exec(ctx); err != nil {
panic(err)
}
}

View file

@ -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/groupinvitationtoken"
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
)
// GroupInvitationTokenDelete is the builder for deleting a GroupInvitationToken entity.
type GroupInvitationTokenDelete struct {
config
hooks []Hook
mutation *GroupInvitationTokenMutation
}
// Where appends a list predicates to the GroupInvitationTokenDelete builder.
func (gitd *GroupInvitationTokenDelete) Where(ps ...predicate.GroupInvitationToken) *GroupInvitationTokenDelete {
gitd.mutation.Where(ps...)
return gitd
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (gitd *GroupInvitationTokenDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(gitd.hooks) == 0 {
affected, err = gitd.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*GroupInvitationTokenMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
gitd.mutation = mutation
affected, err = gitd.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(gitd.hooks) - 1; i >= 0; i-- {
if gitd.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = gitd.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, gitd.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (gitd *GroupInvitationTokenDelete) ExecX(ctx context.Context) int {
n, err := gitd.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (gitd *GroupInvitationTokenDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: groupinvitationtoken.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: groupinvitationtoken.FieldID,
},
},
}
if ps := gitd.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, gitd.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return affected, err
}
// GroupInvitationTokenDeleteOne is the builder for deleting a single GroupInvitationToken entity.
type GroupInvitationTokenDeleteOne struct {
gitd *GroupInvitationTokenDelete
}
// Exec executes the deletion query.
func (gitdo *GroupInvitationTokenDeleteOne) Exec(ctx context.Context) error {
n, err := gitdo.gitd.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{groupinvitationtoken.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (gitdo *GroupInvitationTokenDeleteOne) ExecX(ctx context.Context) {
gitdo.gitd.ExecX(ctx)
}

View file

@ -0,0 +1,614 @@
// 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/group"
"github.com/hay-kot/homebox/backend/internal/data/ent/groupinvitationtoken"
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
)
// GroupInvitationTokenQuery is the builder for querying GroupInvitationToken entities.
type GroupInvitationTokenQuery struct {
config
limit *int
offset *int
unique *bool
order []OrderFunc
fields []string
predicates []predicate.GroupInvitationToken
withGroup *GroupQuery
withFKs bool
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the GroupInvitationTokenQuery builder.
func (gitq *GroupInvitationTokenQuery) Where(ps ...predicate.GroupInvitationToken) *GroupInvitationTokenQuery {
gitq.predicates = append(gitq.predicates, ps...)
return gitq
}
// Limit adds a limit step to the query.
func (gitq *GroupInvitationTokenQuery) Limit(limit int) *GroupInvitationTokenQuery {
gitq.limit = &limit
return gitq
}
// Offset adds an offset step to the query.
func (gitq *GroupInvitationTokenQuery) Offset(offset int) *GroupInvitationTokenQuery {
gitq.offset = &offset
return gitq
}
// 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 (gitq *GroupInvitationTokenQuery) Unique(unique bool) *GroupInvitationTokenQuery {
gitq.unique = &unique
return gitq
}
// Order adds an order step to the query.
func (gitq *GroupInvitationTokenQuery) Order(o ...OrderFunc) *GroupInvitationTokenQuery {
gitq.order = append(gitq.order, o...)
return gitq
}
// QueryGroup chains the current query on the "group" edge.
func (gitq *GroupInvitationTokenQuery) QueryGroup() *GroupQuery {
query := &GroupQuery{config: gitq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := gitq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := gitq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(groupinvitationtoken.Table, groupinvitationtoken.FieldID, selector),
sqlgraph.To(group.Table, group.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, groupinvitationtoken.GroupTable, groupinvitationtoken.GroupColumn),
)
fromU = sqlgraph.SetNeighbors(gitq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first GroupInvitationToken entity from the query.
// Returns a *NotFoundError when no GroupInvitationToken was found.
func (gitq *GroupInvitationTokenQuery) First(ctx context.Context) (*GroupInvitationToken, error) {
nodes, err := gitq.Limit(1).All(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{groupinvitationtoken.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (gitq *GroupInvitationTokenQuery) FirstX(ctx context.Context) *GroupInvitationToken {
node, err := gitq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first GroupInvitationToken ID from the query.
// Returns a *NotFoundError when no GroupInvitationToken ID was found.
func (gitq *GroupInvitationTokenQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = gitq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{groupinvitationtoken.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (gitq *GroupInvitationTokenQuery) FirstIDX(ctx context.Context) uuid.UUID {
id, err := gitq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single GroupInvitationToken entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one GroupInvitationToken entity is found.
// Returns a *NotFoundError when no GroupInvitationToken entities are found.
func (gitq *GroupInvitationTokenQuery) Only(ctx context.Context) (*GroupInvitationToken, error) {
nodes, err := gitq.Limit(2).All(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{groupinvitationtoken.Label}
default:
return nil, &NotSingularError{groupinvitationtoken.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (gitq *GroupInvitationTokenQuery) OnlyX(ctx context.Context) *GroupInvitationToken {
node, err := gitq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only GroupInvitationToken ID in the query.
// Returns a *NotSingularError when more than one GroupInvitationToken ID is found.
// Returns a *NotFoundError when no entities are found.
func (gitq *GroupInvitationTokenQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = gitq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{groupinvitationtoken.Label}
default:
err = &NotSingularError{groupinvitationtoken.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (gitq *GroupInvitationTokenQuery) OnlyIDX(ctx context.Context) uuid.UUID {
id, err := gitq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of GroupInvitationTokens.
func (gitq *GroupInvitationTokenQuery) All(ctx context.Context) ([]*GroupInvitationToken, error) {
if err := gitq.prepareQuery(ctx); err != nil {
return nil, err
}
return gitq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (gitq *GroupInvitationTokenQuery) AllX(ctx context.Context) []*GroupInvitationToken {
nodes, err := gitq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of GroupInvitationToken IDs.
func (gitq *GroupInvitationTokenQuery) IDs(ctx context.Context) ([]uuid.UUID, error) {
var ids []uuid.UUID
if err := gitq.Select(groupinvitationtoken.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (gitq *GroupInvitationTokenQuery) IDsX(ctx context.Context) []uuid.UUID {
ids, err := gitq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (gitq *GroupInvitationTokenQuery) Count(ctx context.Context) (int, error) {
if err := gitq.prepareQuery(ctx); err != nil {
return 0, err
}
return gitq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (gitq *GroupInvitationTokenQuery) CountX(ctx context.Context) int {
count, err := gitq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (gitq *GroupInvitationTokenQuery) Exist(ctx context.Context) (bool, error) {
if err := gitq.prepareQuery(ctx); err != nil {
return false, err
}
return gitq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (gitq *GroupInvitationTokenQuery) ExistX(ctx context.Context) bool {
exist, err := gitq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the GroupInvitationTokenQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (gitq *GroupInvitationTokenQuery) Clone() *GroupInvitationTokenQuery {
if gitq == nil {
return nil
}
return &GroupInvitationTokenQuery{
config: gitq.config,
limit: gitq.limit,
offset: gitq.offset,
order: append([]OrderFunc{}, gitq.order...),
predicates: append([]predicate.GroupInvitationToken{}, gitq.predicates...),
withGroup: gitq.withGroup.Clone(),
// clone intermediate query.
sql: gitq.sql.Clone(),
path: gitq.path,
unique: gitq.unique,
}
}
// WithGroup tells the query-builder to eager-load the nodes that are connected to
// the "group" edge. The optional arguments are used to configure the query builder of the edge.
func (gitq *GroupInvitationTokenQuery) WithGroup(opts ...func(*GroupQuery)) *GroupInvitationTokenQuery {
query := &GroupQuery{config: gitq.config}
for _, opt := range opts {
opt(query)
}
gitq.withGroup = query
return gitq
}
// 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.GroupInvitationToken.Query().
// GroupBy(groupinvitationtoken.FieldCreatedAt).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (gitq *GroupInvitationTokenQuery) GroupBy(field string, fields ...string) *GroupInvitationTokenGroupBy {
grbuild := &GroupInvitationTokenGroupBy{config: gitq.config}
grbuild.fields = append([]string{field}, fields...)
grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := gitq.prepareQuery(ctx); err != nil {
return nil, err
}
return gitq.sqlQuery(ctx), nil
}
grbuild.label = groupinvitationtoken.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.GroupInvitationToken.Query().
// Select(groupinvitationtoken.FieldCreatedAt).
// Scan(ctx, &v)
func (gitq *GroupInvitationTokenQuery) Select(fields ...string) *GroupInvitationTokenSelect {
gitq.fields = append(gitq.fields, fields...)
selbuild := &GroupInvitationTokenSelect{GroupInvitationTokenQuery: gitq}
selbuild.label = groupinvitationtoken.Label
selbuild.flds, selbuild.scan = &gitq.fields, selbuild.Scan
return selbuild
}
func (gitq *GroupInvitationTokenQuery) prepareQuery(ctx context.Context) error {
for _, f := range gitq.fields {
if !groupinvitationtoken.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if gitq.path != nil {
prev, err := gitq.path(ctx)
if err != nil {
return err
}
gitq.sql = prev
}
return nil
}
func (gitq *GroupInvitationTokenQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*GroupInvitationToken, error) {
var (
nodes = []*GroupInvitationToken{}
withFKs = gitq.withFKs
_spec = gitq.querySpec()
loadedTypes = [1]bool{
gitq.withGroup != nil,
}
)
if gitq.withGroup != nil {
withFKs = true
}
if withFKs {
_spec.Node.Columns = append(_spec.Node.Columns, groupinvitationtoken.ForeignKeys...)
}
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*GroupInvitationToken).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &GroupInvitationToken{config: gitq.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, gitq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := gitq.withGroup; query != nil {
if err := gitq.loadGroup(ctx, query, nodes, nil,
func(n *GroupInvitationToken, e *Group) { n.Edges.Group = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (gitq *GroupInvitationTokenQuery) loadGroup(ctx context.Context, query *GroupQuery, nodes []*GroupInvitationToken, init func(*GroupInvitationToken), assign func(*GroupInvitationToken, *Group)) error {
ids := make([]uuid.UUID, 0, len(nodes))
nodeids := make(map[uuid.UUID][]*GroupInvitationToken)
for i := range nodes {
if nodes[i].group_invitation_tokens == nil {
continue
}
fk := *nodes[i].group_invitation_tokens
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
query.Where(group.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 "group_invitation_tokens" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (gitq *GroupInvitationTokenQuery) sqlCount(ctx context.Context) (int, error) {
_spec := gitq.querySpec()
_spec.Node.Columns = gitq.fields
if len(gitq.fields) > 0 {
_spec.Unique = gitq.unique != nil && *gitq.unique
}
return sqlgraph.CountNodes(ctx, gitq.driver, _spec)
}
func (gitq *GroupInvitationTokenQuery) sqlExist(ctx context.Context) (bool, error) {
switch _, err := gitq.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 (gitq *GroupInvitationTokenQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: groupinvitationtoken.Table,
Columns: groupinvitationtoken.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: groupinvitationtoken.FieldID,
},
},
From: gitq.sql,
Unique: true,
}
if unique := gitq.unique; unique != nil {
_spec.Unique = *unique
}
if fields := gitq.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, groupinvitationtoken.FieldID)
for i := range fields {
if fields[i] != groupinvitationtoken.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := gitq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := gitq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := gitq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := gitq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (gitq *GroupInvitationTokenQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(gitq.driver.Dialect())
t1 := builder.Table(groupinvitationtoken.Table)
columns := gitq.fields
if len(columns) == 0 {
columns = groupinvitationtoken.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if gitq.sql != nil {
selector = gitq.sql
selector.Select(selector.Columns(columns...)...)
}
if gitq.unique != nil && *gitq.unique {
selector.Distinct()
}
for _, p := range gitq.predicates {
p(selector)
}
for _, p := range gitq.order {
p(selector)
}
if offset := gitq.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 := gitq.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// GroupInvitationTokenGroupBy is the group-by builder for GroupInvitationToken entities.
type GroupInvitationTokenGroupBy 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 (gitgb *GroupInvitationTokenGroupBy) Aggregate(fns ...AggregateFunc) *GroupInvitationTokenGroupBy {
gitgb.fns = append(gitgb.fns, fns...)
return gitgb
}
// Scan applies the group-by query and scans the result into the given value.
func (gitgb *GroupInvitationTokenGroupBy) Scan(ctx context.Context, v any) error {
query, err := gitgb.path(ctx)
if err != nil {
return err
}
gitgb.sql = query
return gitgb.sqlScan(ctx, v)
}
func (gitgb *GroupInvitationTokenGroupBy) sqlScan(ctx context.Context, v any) error {
for _, f := range gitgb.fields {
if !groupinvitationtoken.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := gitgb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := gitgb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (gitgb *GroupInvitationTokenGroupBy) sqlQuery() *sql.Selector {
selector := gitgb.sql.Select()
aggregation := make([]string, 0, len(gitgb.fns))
for _, fn := range gitgb.fns {
aggregation = append(aggregation, fn(selector))
}
// If no columns were selected in a custom aggregation function, the default
// selection is the fields used for "group-by", and the aggregation functions.
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(gitgb.fields)+len(gitgb.fns))
for _, f := range gitgb.fields {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
return selector.GroupBy(selector.Columns(gitgb.fields...)...)
}
// GroupInvitationTokenSelect is the builder for selecting fields of GroupInvitationToken entities.
type GroupInvitationTokenSelect struct {
*GroupInvitationTokenQuery
selector
// intermediate query (i.e. traversal path).
sql *sql.Selector
}
// Scan applies the selector query and scans the result into the given value.
func (gits *GroupInvitationTokenSelect) Scan(ctx context.Context, v any) error {
if err := gits.prepareQuery(ctx); err != nil {
return err
}
gits.sql = gits.GroupInvitationTokenQuery.sqlQuery(ctx)
return gits.sqlScan(ctx, v)
}
func (gits *GroupInvitationTokenSelect) sqlScan(ctx context.Context, v any) error {
rows := &sql.Rows{}
query, args := gits.sql.Query()
if err := gits.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

View file

@ -0,0 +1,550 @@
// 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/group"
"github.com/hay-kot/homebox/backend/internal/data/ent/groupinvitationtoken"
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
)
// GroupInvitationTokenUpdate is the builder for updating GroupInvitationToken entities.
type GroupInvitationTokenUpdate struct {
config
hooks []Hook
mutation *GroupInvitationTokenMutation
}
// Where appends a list predicates to the GroupInvitationTokenUpdate builder.
func (gitu *GroupInvitationTokenUpdate) Where(ps ...predicate.GroupInvitationToken) *GroupInvitationTokenUpdate {
gitu.mutation.Where(ps...)
return gitu
}
// SetUpdatedAt sets the "updated_at" field.
func (gitu *GroupInvitationTokenUpdate) SetUpdatedAt(t time.Time) *GroupInvitationTokenUpdate {
gitu.mutation.SetUpdatedAt(t)
return gitu
}
// SetToken sets the "token" field.
func (gitu *GroupInvitationTokenUpdate) SetToken(b []byte) *GroupInvitationTokenUpdate {
gitu.mutation.SetToken(b)
return gitu
}
// SetExpiresAt sets the "expires_at" field.
func (gitu *GroupInvitationTokenUpdate) SetExpiresAt(t time.Time) *GroupInvitationTokenUpdate {
gitu.mutation.SetExpiresAt(t)
return gitu
}
// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil.
func (gitu *GroupInvitationTokenUpdate) SetNillableExpiresAt(t *time.Time) *GroupInvitationTokenUpdate {
if t != nil {
gitu.SetExpiresAt(*t)
}
return gitu
}
// SetUses sets the "uses" field.
func (gitu *GroupInvitationTokenUpdate) SetUses(i int) *GroupInvitationTokenUpdate {
gitu.mutation.ResetUses()
gitu.mutation.SetUses(i)
return gitu
}
// SetNillableUses sets the "uses" field if the given value is not nil.
func (gitu *GroupInvitationTokenUpdate) SetNillableUses(i *int) *GroupInvitationTokenUpdate {
if i != nil {
gitu.SetUses(*i)
}
return gitu
}
// AddUses adds i to the "uses" field.
func (gitu *GroupInvitationTokenUpdate) AddUses(i int) *GroupInvitationTokenUpdate {
gitu.mutation.AddUses(i)
return gitu
}
// SetGroupID sets the "group" edge to the Group entity by ID.
func (gitu *GroupInvitationTokenUpdate) SetGroupID(id uuid.UUID) *GroupInvitationTokenUpdate {
gitu.mutation.SetGroupID(id)
return gitu
}
// SetNillableGroupID sets the "group" edge to the Group entity by ID if the given value is not nil.
func (gitu *GroupInvitationTokenUpdate) SetNillableGroupID(id *uuid.UUID) *GroupInvitationTokenUpdate {
if id != nil {
gitu = gitu.SetGroupID(*id)
}
return gitu
}
// SetGroup sets the "group" edge to the Group entity.
func (gitu *GroupInvitationTokenUpdate) SetGroup(g *Group) *GroupInvitationTokenUpdate {
return gitu.SetGroupID(g.ID)
}
// Mutation returns the GroupInvitationTokenMutation object of the builder.
func (gitu *GroupInvitationTokenUpdate) Mutation() *GroupInvitationTokenMutation {
return gitu.mutation
}
// ClearGroup clears the "group" edge to the Group entity.
func (gitu *GroupInvitationTokenUpdate) ClearGroup() *GroupInvitationTokenUpdate {
gitu.mutation.ClearGroup()
return gitu
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (gitu *GroupInvitationTokenUpdate) Save(ctx context.Context) (int, error) {
var (
err error
affected int
)
gitu.defaults()
if len(gitu.hooks) == 0 {
affected, err = gitu.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*GroupInvitationTokenMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
gitu.mutation = mutation
affected, err = gitu.sqlSave(ctx)
mutation.done = true
return affected, err
})
for i := len(gitu.hooks) - 1; i >= 0; i-- {
if gitu.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = gitu.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, gitu.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// SaveX is like Save, but panics if an error occurs.
func (gitu *GroupInvitationTokenUpdate) SaveX(ctx context.Context) int {
affected, err := gitu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (gitu *GroupInvitationTokenUpdate) Exec(ctx context.Context) error {
_, err := gitu.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (gitu *GroupInvitationTokenUpdate) ExecX(ctx context.Context) {
if err := gitu.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (gitu *GroupInvitationTokenUpdate) defaults() {
if _, ok := gitu.mutation.UpdatedAt(); !ok {
v := groupinvitationtoken.UpdateDefaultUpdatedAt()
gitu.mutation.SetUpdatedAt(v)
}
}
func (gitu *GroupInvitationTokenUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: groupinvitationtoken.Table,
Columns: groupinvitationtoken.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: groupinvitationtoken.FieldID,
},
},
}
if ps := gitu.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := gitu.mutation.UpdatedAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: groupinvitationtoken.FieldUpdatedAt,
})
}
if value, ok := gitu.mutation.Token(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: groupinvitationtoken.FieldToken,
})
}
if value, ok := gitu.mutation.ExpiresAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: groupinvitationtoken.FieldExpiresAt,
})
}
if value, ok := gitu.mutation.Uses(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: groupinvitationtoken.FieldUses,
})
}
if value, ok := gitu.mutation.AddedUses(); ok {
_spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: groupinvitationtoken.FieldUses,
})
}
if gitu.mutation.GroupCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: groupinvitationtoken.GroupTable,
Columns: []string{groupinvitationtoken.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := gitu.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: groupinvitationtoken.GroupTable,
Columns: []string{groupinvitationtoken.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.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, gitu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{groupinvitationtoken.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
return n, nil
}
// GroupInvitationTokenUpdateOne is the builder for updating a single GroupInvitationToken entity.
type GroupInvitationTokenUpdateOne struct {
config
fields []string
hooks []Hook
mutation *GroupInvitationTokenMutation
}
// SetUpdatedAt sets the "updated_at" field.
func (gituo *GroupInvitationTokenUpdateOne) SetUpdatedAt(t time.Time) *GroupInvitationTokenUpdateOne {
gituo.mutation.SetUpdatedAt(t)
return gituo
}
// SetToken sets the "token" field.
func (gituo *GroupInvitationTokenUpdateOne) SetToken(b []byte) *GroupInvitationTokenUpdateOne {
gituo.mutation.SetToken(b)
return gituo
}
// SetExpiresAt sets the "expires_at" field.
func (gituo *GroupInvitationTokenUpdateOne) SetExpiresAt(t time.Time) *GroupInvitationTokenUpdateOne {
gituo.mutation.SetExpiresAt(t)
return gituo
}
// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil.
func (gituo *GroupInvitationTokenUpdateOne) SetNillableExpiresAt(t *time.Time) *GroupInvitationTokenUpdateOne {
if t != nil {
gituo.SetExpiresAt(*t)
}
return gituo
}
// SetUses sets the "uses" field.
func (gituo *GroupInvitationTokenUpdateOne) SetUses(i int) *GroupInvitationTokenUpdateOne {
gituo.mutation.ResetUses()
gituo.mutation.SetUses(i)
return gituo
}
// SetNillableUses sets the "uses" field if the given value is not nil.
func (gituo *GroupInvitationTokenUpdateOne) SetNillableUses(i *int) *GroupInvitationTokenUpdateOne {
if i != nil {
gituo.SetUses(*i)
}
return gituo
}
// AddUses adds i to the "uses" field.
func (gituo *GroupInvitationTokenUpdateOne) AddUses(i int) *GroupInvitationTokenUpdateOne {
gituo.mutation.AddUses(i)
return gituo
}
// SetGroupID sets the "group" edge to the Group entity by ID.
func (gituo *GroupInvitationTokenUpdateOne) SetGroupID(id uuid.UUID) *GroupInvitationTokenUpdateOne {
gituo.mutation.SetGroupID(id)
return gituo
}
// SetNillableGroupID sets the "group" edge to the Group entity by ID if the given value is not nil.
func (gituo *GroupInvitationTokenUpdateOne) SetNillableGroupID(id *uuid.UUID) *GroupInvitationTokenUpdateOne {
if id != nil {
gituo = gituo.SetGroupID(*id)
}
return gituo
}
// SetGroup sets the "group" edge to the Group entity.
func (gituo *GroupInvitationTokenUpdateOne) SetGroup(g *Group) *GroupInvitationTokenUpdateOne {
return gituo.SetGroupID(g.ID)
}
// Mutation returns the GroupInvitationTokenMutation object of the builder.
func (gituo *GroupInvitationTokenUpdateOne) Mutation() *GroupInvitationTokenMutation {
return gituo.mutation
}
// ClearGroup clears the "group" edge to the Group entity.
func (gituo *GroupInvitationTokenUpdateOne) ClearGroup() *GroupInvitationTokenUpdateOne {
gituo.mutation.ClearGroup()
return gituo
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (gituo *GroupInvitationTokenUpdateOne) Select(field string, fields ...string) *GroupInvitationTokenUpdateOne {
gituo.fields = append([]string{field}, fields...)
return gituo
}
// Save executes the query and returns the updated GroupInvitationToken entity.
func (gituo *GroupInvitationTokenUpdateOne) Save(ctx context.Context) (*GroupInvitationToken, error) {
var (
err error
node *GroupInvitationToken
)
gituo.defaults()
if len(gituo.hooks) == 0 {
node, err = gituo.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*GroupInvitationTokenMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
gituo.mutation = mutation
node, err = gituo.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(gituo.hooks) - 1; i >= 0; i-- {
if gituo.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = gituo.hooks[i](mut)
}
v, err := mut.Mutate(ctx, gituo.mutation)
if err != nil {
return nil, err
}
nv, ok := v.(*GroupInvitationToken)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from GroupInvitationTokenMutation", v)
}
node = nv
}
return node, err
}
// SaveX is like Save, but panics if an error occurs.
func (gituo *GroupInvitationTokenUpdateOne) SaveX(ctx context.Context) *GroupInvitationToken {
node, err := gituo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (gituo *GroupInvitationTokenUpdateOne) Exec(ctx context.Context) error {
_, err := gituo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (gituo *GroupInvitationTokenUpdateOne) ExecX(ctx context.Context) {
if err := gituo.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (gituo *GroupInvitationTokenUpdateOne) defaults() {
if _, ok := gituo.mutation.UpdatedAt(); !ok {
v := groupinvitationtoken.UpdateDefaultUpdatedAt()
gituo.mutation.SetUpdatedAt(v)
}
}
func (gituo *GroupInvitationTokenUpdateOne) sqlSave(ctx context.Context) (_node *GroupInvitationToken, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: groupinvitationtoken.Table,
Columns: groupinvitationtoken.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: groupinvitationtoken.FieldID,
},
},
}
id, ok := gituo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "GroupInvitationToken.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := gituo.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, groupinvitationtoken.FieldID)
for _, f := range fields {
if !groupinvitationtoken.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != groupinvitationtoken.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := gituo.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := gituo.mutation.UpdatedAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: groupinvitationtoken.FieldUpdatedAt,
})
}
if value, ok := gituo.mutation.Token(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: groupinvitationtoken.FieldToken,
})
}
if value, ok := gituo.mutation.ExpiresAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: groupinvitationtoken.FieldExpiresAt,
})
}
if value, ok := gituo.mutation.Uses(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: groupinvitationtoken.FieldUses,
})
}
if value, ok := gituo.mutation.AddedUses(); ok {
_spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: groupinvitationtoken.FieldUses,
})
}
if gituo.mutation.GroupCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: groupinvitationtoken.GroupTable,
Columns: []string{groupinvitationtoken.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := gituo.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: groupinvitationtoken.GroupTable,
Columns: []string{groupinvitationtoken.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
_node = &GroupInvitationToken{config: gituo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, gituo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{groupinvitationtoken.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
return _node, nil
}

View file

@ -0,0 +1,45 @@
// Code generated by ent, DO NOT EDIT.
package ent
import "github.com/google/uuid"
func (a *Attachment) GetID() uuid.UUID {
return a.ID
}
func (at *AuthTokens) GetID() uuid.UUID {
return at.ID
}
func (d *Document) GetID() uuid.UUID {
return d.ID
}
func (dt *DocumentToken) GetID() uuid.UUID {
return dt.ID
}
func (gr *Group) GetID() uuid.UUID {
return gr.ID
}
func (i *Item) GetID() uuid.UUID {
return i.ID
}
func (_if *ItemField) GetID() uuid.UUID {
return _if.ID
}
func (l *Label) GetID() uuid.UUID {
return l.ID
}
func (l *Location) GetID() uuid.UUID {
return l.ID
}
func (u *User) GetID() uuid.UUID {
return u.ID
}

View file

@ -0,0 +1,330 @@
// Code generated by ent, DO NOT EDIT.
package hook
import (
"context"
"fmt"
"github.com/hay-kot/homebox/backend/internal/data/ent"
)
// The AttachmentFunc type is an adapter to allow the use of ordinary
// function as Attachment mutator.
type AttachmentFunc func(context.Context, *ent.AttachmentMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f AttachmentFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
mv, ok := m.(*ent.AttachmentMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.AttachmentMutation", m)
}
return f(ctx, mv)
}
// The AuthTokensFunc type is an adapter to allow the use of ordinary
// function as AuthTokens mutator.
type AuthTokensFunc func(context.Context, *ent.AuthTokensMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f AuthTokensFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
mv, ok := m.(*ent.AuthTokensMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.AuthTokensMutation", m)
}
return f(ctx, mv)
}
// The DocumentFunc type is an adapter to allow the use of ordinary
// function as Document mutator.
type DocumentFunc func(context.Context, *ent.DocumentMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f DocumentFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
mv, ok := m.(*ent.DocumentMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.DocumentMutation", m)
}
return f(ctx, mv)
}
// The DocumentTokenFunc type is an adapter to allow the use of ordinary
// function as DocumentToken mutator.
type DocumentTokenFunc func(context.Context, *ent.DocumentTokenMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f DocumentTokenFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
mv, ok := m.(*ent.DocumentTokenMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.DocumentTokenMutation", m)
}
return f(ctx, mv)
}
// The GroupFunc type is an adapter to allow the use of ordinary
// function as Group mutator.
type GroupFunc func(context.Context, *ent.GroupMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f GroupFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
mv, ok := m.(*ent.GroupMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.GroupMutation", m)
}
return f(ctx, mv)
}
// The GroupInvitationTokenFunc type is an adapter to allow the use of ordinary
// function as GroupInvitationToken mutator.
type GroupInvitationTokenFunc func(context.Context, *ent.GroupInvitationTokenMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f GroupInvitationTokenFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
mv, ok := m.(*ent.GroupInvitationTokenMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.GroupInvitationTokenMutation", m)
}
return f(ctx, mv)
}
// The ItemFunc type is an adapter to allow the use of ordinary
// function as Item mutator.
type ItemFunc func(context.Context, *ent.ItemMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f ItemFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
mv, ok := m.(*ent.ItemMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.ItemMutation", m)
}
return f(ctx, mv)
}
// The ItemFieldFunc type is an adapter to allow the use of ordinary
// function as ItemField mutator.
type ItemFieldFunc func(context.Context, *ent.ItemFieldMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f ItemFieldFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
mv, ok := m.(*ent.ItemFieldMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.ItemFieldMutation", m)
}
return f(ctx, mv)
}
// The LabelFunc type is an adapter to allow the use of ordinary
// function as Label mutator.
type LabelFunc func(context.Context, *ent.LabelMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f LabelFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
mv, ok := m.(*ent.LabelMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.LabelMutation", m)
}
return f(ctx, mv)
}
// The LocationFunc type is an adapter to allow the use of ordinary
// function as Location mutator.
type LocationFunc func(context.Context, *ent.LocationMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f LocationFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
mv, ok := m.(*ent.LocationMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.LocationMutation", 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)
// Mutate calls f(ctx, m).
func (f UserFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
mv, ok := m.(*ent.UserMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserMutation", m)
}
return f(ctx, mv)
}
// Condition is a hook condition function.
type Condition func(context.Context, ent.Mutation) bool
// And groups conditions with the AND operator.
func And(first, second Condition, rest ...Condition) Condition {
return func(ctx context.Context, m ent.Mutation) bool {
if !first(ctx, m) || !second(ctx, m) {
return false
}
for _, cond := range rest {
if !cond(ctx, m) {
return false
}
}
return true
}
}
// Or groups conditions with the OR operator.
func Or(first, second Condition, rest ...Condition) Condition {
return func(ctx context.Context, m ent.Mutation) bool {
if first(ctx, m) || second(ctx, m) {
return true
}
for _, cond := range rest {
if cond(ctx, m) {
return true
}
}
return false
}
}
// Not negates a given condition.
func Not(cond Condition) Condition {
return func(ctx context.Context, m ent.Mutation) bool {
return !cond(ctx, m)
}
}
// HasOp is a condition testing mutation operation.
func HasOp(op ent.Op) Condition {
return func(_ context.Context, m ent.Mutation) bool {
return m.Op().Is(op)
}
}
// HasAddedFields is a condition validating `.AddedField` on fields.
func HasAddedFields(field string, fields ...string) Condition {
return func(_ context.Context, m ent.Mutation) bool {
if _, exists := m.AddedField(field); !exists {
return false
}
for _, field := range fields {
if _, exists := m.AddedField(field); !exists {
return false
}
}
return true
}
}
// HasClearedFields is a condition validating `.FieldCleared` on fields.
func HasClearedFields(field string, fields ...string) Condition {
return func(_ context.Context, m ent.Mutation) bool {
if exists := m.FieldCleared(field); !exists {
return false
}
for _, field := range fields {
if exists := m.FieldCleared(field); !exists {
return false
}
}
return true
}
}
// HasFields is a condition validating `.Field` on fields.
func HasFields(field string, fields ...string) Condition {
return func(_ context.Context, m ent.Mutation) bool {
if _, exists := m.Field(field); !exists {
return false
}
for _, field := range fields {
if _, exists := m.Field(field); !exists {
return false
}
}
return true
}
}
// If executes the given hook under condition.
//
// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...)))
func If(hk ent.Hook, cond Condition) ent.Hook {
return func(next ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if cond(ctx, m) {
return hk(next).Mutate(ctx, m)
}
return next.Mutate(ctx, m)
})
}
}
// On executes the given hook only for the given operation.
//
// hook.On(Log, ent.Delete|ent.Create)
func On(hk ent.Hook, op ent.Op) ent.Hook {
return If(hk, HasOp(op))
}
// Unless skips the given hook only for the given operation.
//
// hook.Unless(Log, ent.Update|ent.UpdateOne)
func Unless(hk ent.Hook, op ent.Op) ent.Hook {
return If(hk, Not(HasOp(op)))
}
// FixedError is a hook returning a fixed error.
func FixedError(err error) ent.Hook {
return func(ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(context.Context, ent.Mutation) (ent.Value, error) {
return nil, err
})
}
}
// Reject returns a hook that rejects all operations that match op.
//
// func (T) Hooks() []ent.Hook {
// return []ent.Hook{
// Reject(ent.Delete|ent.Update),
// }
// }
func Reject(op ent.Op) ent.Hook {
hk := FixedError(fmt.Errorf("%s operation is not allowed", op))
return On(hk, op)
}
// Chain acts as a list of hooks and is effectively immutable.
// Once created, it will always hold the same set of hooks in the same order.
type Chain struct {
hooks []ent.Hook
}
// NewChain creates a new chain of hooks.
func NewChain(hooks ...ent.Hook) Chain {
return Chain{append([]ent.Hook(nil), hooks...)}
}
// Hook chains the list of hooks and returns the final hook.
func (c Chain) Hook() ent.Hook {
return func(mutator ent.Mutator) ent.Mutator {
for i := len(c.hooks) - 1; i >= 0; i-- {
mutator = c.hooks[i](mutator)
}
return mutator
}
}
// Append extends a chain, adding the specified hook
// as the last ones in the mutation flow.
func (c Chain) Append(hooks ...ent.Hook) Chain {
newHooks := make([]ent.Hook, 0, len(c.hooks)+len(hooks))
newHooks = append(newHooks, c.hooks...)
newHooks = append(newHooks, hooks...)
return Chain{newHooks}
}
// Extend extends a chain, adding the specified chain
// as the last ones in the mutation flow.
func (c Chain) Extend(chain Chain) Chain {
return c.Append(chain.hooks...)
}

View file

@ -0,0 +1,495 @@
// 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/group"
"github.com/hay-kot/homebox/backend/internal/data/ent/item"
"github.com/hay-kot/homebox/backend/internal/data/ent/location"
)
// Item is the model entity for the Item schema.
type Item 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"`
// 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"`
// ImportRef holds the value of the "import_ref" field.
ImportRef string `json:"import_ref,omitempty"`
// Notes holds the value of the "notes" field.
Notes string `json:"notes,omitempty"`
// Quantity holds the value of the "quantity" field.
Quantity int `json:"quantity,omitempty"`
// Insured holds the value of the "insured" field.
Insured bool `json:"insured,omitempty"`
// SerialNumber holds the value of the "serial_number" field.
SerialNumber string `json:"serial_number,omitempty"`
// ModelNumber holds the value of the "model_number" field.
ModelNumber string `json:"model_number,omitempty"`
// Manufacturer holds the value of the "manufacturer" field.
Manufacturer string `json:"manufacturer,omitempty"`
// LifetimeWarranty holds the value of the "lifetime_warranty" field.
LifetimeWarranty bool `json:"lifetime_warranty,omitempty"`
// WarrantyExpires holds the value of the "warranty_expires" field.
WarrantyExpires time.Time `json:"warranty_expires,omitempty"`
// WarrantyDetails holds the value of the "warranty_details" field.
WarrantyDetails string `json:"warranty_details,omitempty"`
// PurchaseTime holds the value of the "purchase_time" field.
PurchaseTime time.Time `json:"purchase_time,omitempty"`
// PurchaseFrom holds the value of the "purchase_from" field.
PurchaseFrom string `json:"purchase_from,omitempty"`
// PurchasePrice holds the value of the "purchase_price" field.
PurchasePrice float64 `json:"purchase_price,omitempty"`
// SoldTime holds the value of the "sold_time" field.
SoldTime time.Time `json:"sold_time,omitempty"`
// SoldTo holds the value of the "sold_to" field.
SoldTo string `json:"sold_to,omitempty"`
// SoldPrice holds the value of the "sold_price" field.
SoldPrice float64 `json:"sold_price,omitempty"`
// SoldNotes holds the value of the "sold_notes" field.
SoldNotes string `json:"sold_notes,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the ItemQuery when eager-loading is set.
Edges ItemEdges `json:"edges"`
group_items *uuid.UUID
item_children *uuid.UUID
location_items *uuid.UUID
}
// ItemEdges holds the relations/edges for other nodes in the graph.
type ItemEdges struct {
// Parent holds the value of the parent edge.
Parent *Item `json:"parent,omitempty"`
// Children holds the value of the children edge.
Children []*Item `json:"children,omitempty"`
// Group holds the value of the group edge.
Group *Group `json:"group,omitempty"`
// Label holds the value of the label edge.
Label []*Label `json:"label,omitempty"`
// Location holds the value of the location edge.
Location *Location `json:"location,omitempty"`
// Fields holds the value of the fields edge.
Fields []*ItemField `json:"fields,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
}
// ParentOrErr returns the Parent value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e ItemEdges) ParentOrErr() (*Item, error) {
if e.loadedTypes[0] {
if e.Parent == nil {
// Edge was loaded but was not found.
return nil, &NotFoundError{label: item.Label}
}
return e.Parent, nil
}
return nil, &NotLoadedError{edge: "parent"}
}
// ChildrenOrErr returns the Children value or an error if the edge
// was not loaded in eager-loading.
func (e ItemEdges) ChildrenOrErr() ([]*Item, error) {
if e.loadedTypes[1] {
return e.Children, nil
}
return nil, &NotLoadedError{edge: "children"}
}
// GroupOrErr returns the Group value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e ItemEdges) GroupOrErr() (*Group, error) {
if e.loadedTypes[2] {
if e.Group == nil {
// Edge was loaded but was not found.
return nil, &NotFoundError{label: group.Label}
}
return e.Group, nil
}
return nil, &NotLoadedError{edge: "group"}
}
// LabelOrErr returns the Label value or an error if the edge
// was not loaded in eager-loading.
func (e ItemEdges) LabelOrErr() ([]*Label, error) {
if e.loadedTypes[3] {
return e.Label, nil
}
return nil, &NotLoadedError{edge: "label"}
}
// LocationOrErr returns the Location value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e ItemEdges) LocationOrErr() (*Location, error) {
if e.loadedTypes[4] {
if e.Location == nil {
// Edge was loaded but was not found.
return nil, &NotFoundError{label: location.Label}
}
return e.Location, nil
}
return nil, &NotLoadedError{edge: "location"}
}
// FieldsOrErr returns the Fields value or an error if the edge
// was not loaded in eager-loading.
func (e ItemEdges) FieldsOrErr() ([]*ItemField, error) {
if e.loadedTypes[5] {
return e.Fields, nil
}
return nil, &NotLoadedError{edge: "fields"}
}
// 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] {
return e.Attachments, nil
}
return nil, &NotLoadedError{edge: "attachments"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Item) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case item.FieldInsured, item.FieldLifetimeWarranty:
values[i] = new(sql.NullBool)
case item.FieldPurchasePrice, item.FieldSoldPrice:
values[i] = new(sql.NullFloat64)
case item.FieldQuantity:
values[i] = new(sql.NullInt64)
case item.FieldName, item.FieldDescription, item.FieldImportRef, item.FieldNotes, item.FieldSerialNumber, item.FieldModelNumber, item.FieldManufacturer, item.FieldWarrantyDetails, item.FieldPurchaseFrom, item.FieldSoldTo, item.FieldSoldNotes:
values[i] = new(sql.NullString)
case item.FieldCreatedAt, item.FieldUpdatedAt, item.FieldWarrantyExpires, item.FieldPurchaseTime, item.FieldSoldTime:
values[i] = new(sql.NullTime)
case item.FieldID:
values[i] = new(uuid.UUID)
case item.ForeignKeys[0]: // group_items
values[i] = &sql.NullScanner{S: new(uuid.UUID)}
case item.ForeignKeys[1]: // item_children
values[i] = &sql.NullScanner{S: new(uuid.UUID)}
case item.ForeignKeys[2]: // location_items
values[i] = &sql.NullScanner{S: new(uuid.UUID)}
default:
return nil, fmt.Errorf("unexpected column %q for type Item", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Item fields.
func (i *Item) 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 j := range columns {
switch columns[j] {
case item.FieldID:
if value, ok := values[j].(*uuid.UUID); !ok {
return fmt.Errorf("unexpected type %T for field id", values[j])
} else if value != nil {
i.ID = *value
}
case item.FieldCreatedAt:
if value, ok := values[j].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[j])
} else if value.Valid {
i.CreatedAt = value.Time
}
case item.FieldUpdatedAt:
if value, ok := values[j].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[j])
} else if value.Valid {
i.UpdatedAt = value.Time
}
case item.FieldName:
if value, ok := values[j].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[j])
} else if value.Valid {
i.Name = value.String
}
case item.FieldDescription:
if value, ok := values[j].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field description", values[j])
} else if value.Valid {
i.Description = value.String
}
case item.FieldImportRef:
if value, ok := values[j].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field import_ref", values[j])
} else if value.Valid {
i.ImportRef = value.String
}
case item.FieldNotes:
if value, ok := values[j].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field notes", values[j])
} else if value.Valid {
i.Notes = value.String
}
case item.FieldQuantity:
if value, ok := values[j].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field quantity", values[j])
} else if value.Valid {
i.Quantity = int(value.Int64)
}
case item.FieldInsured:
if value, ok := values[j].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field insured", values[j])
} else if value.Valid {
i.Insured = value.Bool
}
case item.FieldSerialNumber:
if value, ok := values[j].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field serial_number", values[j])
} else if value.Valid {
i.SerialNumber = value.String
}
case item.FieldModelNumber:
if value, ok := values[j].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field model_number", values[j])
} else if value.Valid {
i.ModelNumber = value.String
}
case item.FieldManufacturer:
if value, ok := values[j].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field manufacturer", values[j])
} else if value.Valid {
i.Manufacturer = value.String
}
case item.FieldLifetimeWarranty:
if value, ok := values[j].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field lifetime_warranty", values[j])
} else if value.Valid {
i.LifetimeWarranty = value.Bool
}
case item.FieldWarrantyExpires:
if value, ok := values[j].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field warranty_expires", values[j])
} else if value.Valid {
i.WarrantyExpires = value.Time
}
case item.FieldWarrantyDetails:
if value, ok := values[j].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field warranty_details", values[j])
} else if value.Valid {
i.WarrantyDetails = value.String
}
case item.FieldPurchaseTime:
if value, ok := values[j].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field purchase_time", values[j])
} else if value.Valid {
i.PurchaseTime = value.Time
}
case item.FieldPurchaseFrom:
if value, ok := values[j].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field purchase_from", values[j])
} else if value.Valid {
i.PurchaseFrom = value.String
}
case item.FieldPurchasePrice:
if value, ok := values[j].(*sql.NullFloat64); !ok {
return fmt.Errorf("unexpected type %T for field purchase_price", values[j])
} else if value.Valid {
i.PurchasePrice = value.Float64
}
case item.FieldSoldTime:
if value, ok := values[j].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field sold_time", values[j])
} else if value.Valid {
i.SoldTime = value.Time
}
case item.FieldSoldTo:
if value, ok := values[j].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field sold_to", values[j])
} else if value.Valid {
i.SoldTo = value.String
}
case item.FieldSoldPrice:
if value, ok := values[j].(*sql.NullFloat64); !ok {
return fmt.Errorf("unexpected type %T for field sold_price", values[j])
} else if value.Valid {
i.SoldPrice = value.Float64
}
case item.FieldSoldNotes:
if value, ok := values[j].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field sold_notes", values[j])
} else if value.Valid {
i.SoldNotes = value.String
}
case item.ForeignKeys[0]:
if value, ok := values[j].(*sql.NullScanner); !ok {
return fmt.Errorf("unexpected type %T for field group_items", values[j])
} else if value.Valid {
i.group_items = new(uuid.UUID)
*i.group_items = *value.S.(*uuid.UUID)
}
case item.ForeignKeys[1]:
if value, ok := values[j].(*sql.NullScanner); !ok {
return fmt.Errorf("unexpected type %T for field item_children", values[j])
} else if value.Valid {
i.item_children = new(uuid.UUID)
*i.item_children = *value.S.(*uuid.UUID)
}
case item.ForeignKeys[2]:
if value, ok := values[j].(*sql.NullScanner); !ok {
return fmt.Errorf("unexpected type %T for field location_items", values[j])
} else if value.Valid {
i.location_items = new(uuid.UUID)
*i.location_items = *value.S.(*uuid.UUID)
}
}
}
return nil
}
// QueryParent queries the "parent" edge of the Item entity.
func (i *Item) QueryParent() *ItemQuery {
return (&ItemClient{config: i.config}).QueryParent(i)
}
// QueryChildren queries the "children" edge of the Item entity.
func (i *Item) QueryChildren() *ItemQuery {
return (&ItemClient{config: i.config}).QueryChildren(i)
}
// QueryGroup queries the "group" edge of the Item entity.
func (i *Item) QueryGroup() *GroupQuery {
return (&ItemClient{config: i.config}).QueryGroup(i)
}
// QueryLabel queries the "label" edge of the Item entity.
func (i *Item) QueryLabel() *LabelQuery {
return (&ItemClient{config: i.config}).QueryLabel(i)
}
// QueryLocation queries the "location" edge of the Item entity.
func (i *Item) QueryLocation() *LocationQuery {
return (&ItemClient{config: i.config}).QueryLocation(i)
}
// QueryFields queries the "fields" edge of the Item entity.
func (i *Item) QueryFields() *ItemFieldQuery {
return (&ItemClient{config: i.config}).QueryFields(i)
}
// QueryAttachments queries the "attachments" edge of the Item entity.
func (i *Item) QueryAttachments() *AttachmentQuery {
return (&ItemClient{config: i.config}).QueryAttachments(i)
}
// Update returns a builder for updating this Item.
// Note that you need to call Item.Unwrap() before calling this method if this Item
// was returned from a transaction, and the transaction was committed or rolled back.
func (i *Item) Update() *ItemUpdateOne {
return (&ItemClient{config: i.config}).UpdateOne(i)
}
// Unwrap unwraps the Item 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 (i *Item) Unwrap() *Item {
_tx, ok := i.config.driver.(*txDriver)
if !ok {
panic("ent: Item is not a transactional entity")
}
i.config.driver = _tx.drv
return i
}
// String implements the fmt.Stringer.
func (i *Item) String() string {
var builder strings.Builder
builder.WriteString("Item(")
builder.WriteString(fmt.Sprintf("id=%v, ", i.ID))
builder.WriteString("created_at=")
builder.WriteString(i.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(i.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("name=")
builder.WriteString(i.Name)
builder.WriteString(", ")
builder.WriteString("description=")
builder.WriteString(i.Description)
builder.WriteString(", ")
builder.WriteString("import_ref=")
builder.WriteString(i.ImportRef)
builder.WriteString(", ")
builder.WriteString("notes=")
builder.WriteString(i.Notes)
builder.WriteString(", ")
builder.WriteString("quantity=")
builder.WriteString(fmt.Sprintf("%v", i.Quantity))
builder.WriteString(", ")
builder.WriteString("insured=")
builder.WriteString(fmt.Sprintf("%v", i.Insured))
builder.WriteString(", ")
builder.WriteString("serial_number=")
builder.WriteString(i.SerialNumber)
builder.WriteString(", ")
builder.WriteString("model_number=")
builder.WriteString(i.ModelNumber)
builder.WriteString(", ")
builder.WriteString("manufacturer=")
builder.WriteString(i.Manufacturer)
builder.WriteString(", ")
builder.WriteString("lifetime_warranty=")
builder.WriteString(fmt.Sprintf("%v", i.LifetimeWarranty))
builder.WriteString(", ")
builder.WriteString("warranty_expires=")
builder.WriteString(i.WarrantyExpires.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("warranty_details=")
builder.WriteString(i.WarrantyDetails)
builder.WriteString(", ")
builder.WriteString("purchase_time=")
builder.WriteString(i.PurchaseTime.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("purchase_from=")
builder.WriteString(i.PurchaseFrom)
builder.WriteString(", ")
builder.WriteString("purchase_price=")
builder.WriteString(fmt.Sprintf("%v", i.PurchasePrice))
builder.WriteString(", ")
builder.WriteString("sold_time=")
builder.WriteString(i.SoldTime.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("sold_to=")
builder.WriteString(i.SoldTo)
builder.WriteString(", ")
builder.WriteString("sold_price=")
builder.WriteString(fmt.Sprintf("%v", i.SoldPrice))
builder.WriteString(", ")
builder.WriteString("sold_notes=")
builder.WriteString(i.SoldNotes)
builder.WriteByte(')')
return builder.String()
}
// Items is a parsable slice of Item.
type Items []*Item
func (i Items) config(cfg config) {
for _i := range i {
i[_i].config = cfg
}
}

View file

@ -0,0 +1,209 @@
// Code generated by ent, DO NOT EDIT.
package item
import (
"time"
"github.com/google/uuid"
)
const (
// Label holds the string label denoting the item type in the database.
Label = "item"
// 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"
// 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"
// FieldImportRef holds the string denoting the import_ref field in the database.
FieldImportRef = "import_ref"
// FieldNotes holds the string denoting the notes field in the database.
FieldNotes = "notes"
// FieldQuantity holds the string denoting the quantity field in the database.
FieldQuantity = "quantity"
// FieldInsured holds the string denoting the insured field in the database.
FieldInsured = "insured"
// FieldSerialNumber holds the string denoting the serial_number field in the database.
FieldSerialNumber = "serial_number"
// FieldModelNumber holds the string denoting the model_number field in the database.
FieldModelNumber = "model_number"
// FieldManufacturer holds the string denoting the manufacturer field in the database.
FieldManufacturer = "manufacturer"
// FieldLifetimeWarranty holds the string denoting the lifetime_warranty field in the database.
FieldLifetimeWarranty = "lifetime_warranty"
// FieldWarrantyExpires holds the string denoting the warranty_expires field in the database.
FieldWarrantyExpires = "warranty_expires"
// FieldWarrantyDetails holds the string denoting the warranty_details field in the database.
FieldWarrantyDetails = "warranty_details"
// FieldPurchaseTime holds the string denoting the purchase_time field in the database.
FieldPurchaseTime = "purchase_time"
// FieldPurchaseFrom holds the string denoting the purchase_from field in the database.
FieldPurchaseFrom = "purchase_from"
// FieldPurchasePrice holds the string denoting the purchase_price field in the database.
FieldPurchasePrice = "purchase_price"
// FieldSoldTime holds the string denoting the sold_time field in the database.
FieldSoldTime = "sold_time"
// FieldSoldTo holds the string denoting the sold_to field in the database.
FieldSoldTo = "sold_to"
// FieldSoldPrice holds the string denoting the sold_price field in the database.
FieldSoldPrice = "sold_price"
// FieldSoldNotes holds the string denoting the sold_notes field in the database.
FieldSoldNotes = "sold_notes"
// EdgeParent holds the string denoting the parent edge name in mutations.
EdgeParent = "parent"
// EdgeChildren holds the string denoting the children edge name in mutations.
EdgeChildren = "children"
// EdgeGroup holds the string denoting the group edge name in mutations.
EdgeGroup = "group"
// EdgeLabel holds the string denoting the label edge name in mutations.
EdgeLabel = "label"
// EdgeLocation holds the string denoting the location edge name in mutations.
EdgeLocation = "location"
// EdgeFields holds the string denoting the fields edge name in mutations.
EdgeFields = "fields"
// EdgeAttachments holds the string denoting the attachments edge name in mutations.
EdgeAttachments = "attachments"
// Table holds the table name of the item in the database.
Table = "items"
// ParentTable is the table that holds the parent relation/edge.
ParentTable = "items"
// ParentColumn is the table column denoting the parent relation/edge.
ParentColumn = "item_children"
// ChildrenTable is the table that holds the children relation/edge.
ChildrenTable = "items"
// ChildrenColumn is the table column denoting the children relation/edge.
ChildrenColumn = "item_children"
// GroupTable is the table that holds the group relation/edge.
GroupTable = "items"
// GroupInverseTable is the table name for the Group entity.
// It exists in this package in order to avoid circular dependency with the "group" package.
GroupInverseTable = "groups"
// GroupColumn is the table column denoting the group relation/edge.
GroupColumn = "group_items"
// LabelTable is the table that holds the label relation/edge. The primary key declared below.
LabelTable = "label_items"
// LabelInverseTable is the table name for the Label entity.
// It exists in this package in order to avoid circular dependency with the "label" package.
LabelInverseTable = "labels"
// LocationTable is the table that holds the location relation/edge.
LocationTable = "items"
// LocationInverseTable is the table name for the Location entity.
// It exists in this package in order to avoid circular dependency with the "location" package.
LocationInverseTable = "locations"
// LocationColumn is the table column denoting the location relation/edge.
LocationColumn = "location_items"
// FieldsTable is the table that holds the fields relation/edge.
FieldsTable = "item_fields"
// FieldsInverseTable is the table name for the ItemField entity.
// It exists in this package in order to avoid circular dependency with the "itemfield" package.
FieldsInverseTable = "item_fields"
// FieldsColumn is the table column denoting the fields relation/edge.
FieldsColumn = "item_fields"
// AttachmentsTable is the table that holds the attachments relation/edge.
AttachmentsTable = "attachments"
// AttachmentsInverseTable is the table name for the Attachment entity.
// It exists in this package in order to avoid circular dependency with the "attachment" package.
AttachmentsInverseTable = "attachments"
// AttachmentsColumn is the table column denoting the attachments relation/edge.
AttachmentsColumn = "item_attachments"
)
// Columns holds all SQL columns for item fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldName,
FieldDescription,
FieldImportRef,
FieldNotes,
FieldQuantity,
FieldInsured,
FieldSerialNumber,
FieldModelNumber,
FieldManufacturer,
FieldLifetimeWarranty,
FieldWarrantyExpires,
FieldWarrantyDetails,
FieldPurchaseTime,
FieldPurchaseFrom,
FieldPurchasePrice,
FieldSoldTime,
FieldSoldTo,
FieldSoldPrice,
FieldSoldNotes,
}
// ForeignKeys holds the SQL foreign-keys that are owned by the "items"
// table and are not defined as standalone fields in the schema.
var ForeignKeys = []string{
"group_items",
"item_children",
"location_items",
}
var (
// LabelPrimaryKey and LabelColumn2 are the table columns denoting the
// primary key for the label relation (M2M).
LabelPrimaryKey = []string{"label_id", "item_id"}
)
// 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
}
}
for i := range ForeignKeys {
if column == ForeignKeys[i] {
return true
}
}
return false
}
var (
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
// UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
UpdateDefaultUpdatedAt func() time.Time
// NameValidator is a validator for the "name" field. It is called by the builders before save.
NameValidator func(string) error
// DescriptionValidator is a validator for the "description" field. It is called by the builders before save.
DescriptionValidator func(string) error
// ImportRefValidator is a validator for the "import_ref" field. It is called by the builders before save.
ImportRefValidator func(string) error
// NotesValidator is a validator for the "notes" field. It is called by the builders before save.
NotesValidator func(string) error
// DefaultQuantity holds the default value on creation for the "quantity" field.
DefaultQuantity int
// DefaultInsured holds the default value on creation for the "insured" field.
DefaultInsured bool
// SerialNumberValidator is a validator for the "serial_number" field. It is called by the builders before save.
SerialNumberValidator func(string) error
// ModelNumberValidator is a validator for the "model_number" field. It is called by the builders before save.
ModelNumberValidator func(string) error
// ManufacturerValidator is a validator for the "manufacturer" field. It is called by the builders before save.
ManufacturerValidator func(string) error
// DefaultLifetimeWarranty holds the default value on creation for the "lifetime_warranty" field.
DefaultLifetimeWarranty bool
// WarrantyDetailsValidator is a validator for the "warranty_details" field. It is called by the builders before save.
WarrantyDetailsValidator func(string) error
// DefaultPurchasePrice holds the default value on creation for the "purchase_price" field.
DefaultPurchasePrice float64
// DefaultSoldPrice holds the default value on creation for the "sold_price" field.
DefaultSoldPrice float64
// SoldNotesValidator is a validator for the "sold_notes" field. It is called by the builders before save.
SoldNotesValidator func(string) error
// DefaultID holds the default value on creation for the "id" field.
DefaultID func() uuid.UUID
)

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -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/item"
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
)
// ItemDelete is the builder for deleting a Item entity.
type ItemDelete struct {
config
hooks []Hook
mutation *ItemMutation
}
// Where appends a list predicates to the ItemDelete builder.
func (id *ItemDelete) Where(ps ...predicate.Item) *ItemDelete {
id.mutation.Where(ps...)
return id
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (id *ItemDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(id.hooks) == 0 {
affected, err = id.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*ItemMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
id.mutation = mutation
affected, err = id.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(id.hooks) - 1; i >= 0; i-- {
if id.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = id.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, id.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (id *ItemDelete) ExecX(ctx context.Context) int {
n, err := id.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (id *ItemDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: item.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: item.FieldID,
},
},
}
if ps := id.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, id.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return affected, err
}
// ItemDeleteOne is the builder for deleting a single Item entity.
type ItemDeleteOne struct {
id *ItemDelete
}
// Exec executes the deletion query.
func (ido *ItemDeleteOne) Exec(ctx context.Context) error {
n, err := ido.id.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{item.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (ido *ItemDeleteOne) ExecX(ctx context.Context) {
ido.id.ExecX(ctx)
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,236 @@
// 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/itemfield"
)
// ItemField is the model entity for the ItemField schema.
type ItemField 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"`
// 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"`
// Type holds the value of the "type" field.
Type itemfield.Type `json:"type,omitempty"`
// TextValue holds the value of the "text_value" field.
TextValue string `json:"text_value,omitempty"`
// NumberValue holds the value of the "number_value" field.
NumberValue int `json:"number_value,omitempty"`
// BooleanValue holds the value of the "boolean_value" field.
BooleanValue bool `json:"boolean_value,omitempty"`
// TimeValue holds the value of the "time_value" field.
TimeValue time.Time `json:"time_value,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the ItemFieldQuery when eager-loading is set.
Edges ItemFieldEdges `json:"edges"`
item_fields *uuid.UUID
}
// ItemFieldEdges holds the relations/edges for other nodes in the graph.
type ItemFieldEdges 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 ItemFieldEdges) 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 (*ItemField) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case itemfield.FieldBooleanValue:
values[i] = new(sql.NullBool)
case itemfield.FieldNumberValue:
values[i] = new(sql.NullInt64)
case itemfield.FieldName, itemfield.FieldDescription, itemfield.FieldType, itemfield.FieldTextValue:
values[i] = new(sql.NullString)
case itemfield.FieldCreatedAt, itemfield.FieldUpdatedAt, itemfield.FieldTimeValue:
values[i] = new(sql.NullTime)
case itemfield.FieldID:
values[i] = new(uuid.UUID)
case itemfield.ForeignKeys[0]: // item_fields
values[i] = &sql.NullScanner{S: new(uuid.UUID)}
default:
return nil, fmt.Errorf("unexpected column %q for type ItemField", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the ItemField fields.
func (_if *ItemField) 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 itemfield.FieldID:
if value, ok := values[i].(*uuid.UUID); !ok {
return fmt.Errorf("unexpected type %T for field id", values[i])
} else if value != nil {
_if.ID = *value
}
case itemfield.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 {
_if.CreatedAt = value.Time
}
case itemfield.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 {
_if.UpdatedAt = value.Time
}
case itemfield.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
_if.Name = value.String
}
case itemfield.FieldDescription:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field description", values[i])
} else if value.Valid {
_if.Description = value.String
}
case itemfield.FieldType:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field type", values[i])
} else if value.Valid {
_if.Type = itemfield.Type(value.String)
}
case itemfield.FieldTextValue:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field text_value", values[i])
} else if value.Valid {
_if.TextValue = value.String
}
case itemfield.FieldNumberValue:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field number_value", values[i])
} else if value.Valid {
_if.NumberValue = int(value.Int64)
}
case itemfield.FieldBooleanValue:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field boolean_value", values[i])
} else if value.Valid {
_if.BooleanValue = value.Bool
}
case itemfield.FieldTimeValue:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field time_value", values[i])
} else if value.Valid {
_if.TimeValue = value.Time
}
case itemfield.ForeignKeys[0]:
if value, ok := values[i].(*sql.NullScanner); !ok {
return fmt.Errorf("unexpected type %T for field item_fields", values[i])
} else if value.Valid {
_if.item_fields = new(uuid.UUID)
*_if.item_fields = *value.S.(*uuid.UUID)
}
}
}
return nil
}
// QueryItem queries the "item" edge of the ItemField entity.
func (_if *ItemField) QueryItem() *ItemQuery {
return (&ItemFieldClient{config: _if.config}).QueryItem(_if)
}
// Update returns a builder for updating this ItemField.
// Note that you need to call ItemField.Unwrap() before calling this method if this ItemField
// was returned from a transaction, and the transaction was committed or rolled back.
func (_if *ItemField) Update() *ItemFieldUpdateOne {
return (&ItemFieldClient{config: _if.config}).UpdateOne(_if)
}
// Unwrap unwraps the ItemField 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 (_if *ItemField) Unwrap() *ItemField {
_tx, ok := _if.config.driver.(*txDriver)
if !ok {
panic("ent: ItemField is not a transactional entity")
}
_if.config.driver = _tx.drv
return _if
}
// String implements the fmt.Stringer.
func (_if *ItemField) String() string {
var builder strings.Builder
builder.WriteString("ItemField(")
builder.WriteString(fmt.Sprintf("id=%v, ", _if.ID))
builder.WriteString("created_at=")
builder.WriteString(_if.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(_if.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("name=")
builder.WriteString(_if.Name)
builder.WriteString(", ")
builder.WriteString("description=")
builder.WriteString(_if.Description)
builder.WriteString(", ")
builder.WriteString("type=")
builder.WriteString(fmt.Sprintf("%v", _if.Type))
builder.WriteString(", ")
builder.WriteString("text_value=")
builder.WriteString(_if.TextValue)
builder.WriteString(", ")
builder.WriteString("number_value=")
builder.WriteString(fmt.Sprintf("%v", _if.NumberValue))
builder.WriteString(", ")
builder.WriteString("boolean_value=")
builder.WriteString(fmt.Sprintf("%v", _if.BooleanValue))
builder.WriteString(", ")
builder.WriteString("time_value=")
builder.WriteString(_if.TimeValue.Format(time.ANSIC))
builder.WriteByte(')')
return builder.String()
}
// ItemFields is a parsable slice of ItemField.
type ItemFields []*ItemField
func (_if ItemFields) config(cfg config) {
for _i := range _if {
_if[_i].config = cfg
}
}

View file

@ -0,0 +1,127 @@
// Code generated by ent, DO NOT EDIT.
package itemfield
import (
"fmt"
"time"
"github.com/google/uuid"
)
const (
// Label holds the string label denoting the itemfield type in the database.
Label = "item_field"
// 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"
// 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"
// FieldType holds the string denoting the type field in the database.
FieldType = "type"
// FieldTextValue holds the string denoting the text_value field in the database.
FieldTextValue = "text_value"
// FieldNumberValue holds the string denoting the number_value field in the database.
FieldNumberValue = "number_value"
// FieldBooleanValue holds the string denoting the boolean_value field in the database.
FieldBooleanValue = "boolean_value"
// FieldTimeValue holds the string denoting the time_value field in the database.
FieldTimeValue = "time_value"
// EdgeItem holds the string denoting the item edge name in mutations.
EdgeItem = "item"
// Table holds the table name of the itemfield in the database.
Table = "item_fields"
// ItemTable is the table that holds the item relation/edge.
ItemTable = "item_fields"
// 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_fields"
)
// Columns holds all SQL columns for itemfield fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldName,
FieldDescription,
FieldType,
FieldTextValue,
FieldNumberValue,
FieldBooleanValue,
FieldTimeValue,
}
// ForeignKeys holds the SQL foreign-keys that are owned by the "item_fields"
// table and are not defined as standalone fields in the schema.
var ForeignKeys = []string{
"item_fields",
}
// 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
}
}
for i := range ForeignKeys {
if column == ForeignKeys[i] {
return true
}
}
return false
}
var (
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
// UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
UpdateDefaultUpdatedAt func() time.Time
// NameValidator is a validator for the "name" field. It is called by the builders before save.
NameValidator func(string) error
// DescriptionValidator is a validator for the "description" field. It is called by the builders before save.
DescriptionValidator func(string) error
// TextValueValidator is a validator for the "text_value" field. It is called by the builders before save.
TextValueValidator func(string) error
// DefaultBooleanValue holds the default value on creation for the "boolean_value" field.
DefaultBooleanValue bool
// DefaultTimeValue holds the default value on creation for the "time_value" field.
DefaultTimeValue func() time.Time
// DefaultID holds the default value on creation for the "id" field.
DefaultID func() uuid.UUID
)
// Type defines the type for the "type" enum field.
type Type string
// Type values.
const (
TypeText Type = "text"
TypeNumber Type = "number"
TypeBoolean Type = "boolean"
TypeTime Type = "time"
)
func (_type Type) String() string {
return string(_type)
}
// TypeValidator is a validator for the "type" field enum values. It is called by the builders before save.
func TypeValidator(_type Type) error {
switch _type {
case TypeText, TypeNumber, TypeBoolean, TypeTime:
return nil
default:
return fmt.Errorf("itemfield: invalid enum value for type field: %q", _type)
}
}

View file

@ -0,0 +1,844 @@
// Code generated by ent, DO NOT EDIT.
package itemfield
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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
})
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldDescription), v))
})
}
// TextValue applies equality check predicate on the "text_value" field. It's identical to TextValueEQ.
func TextValue(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldTextValue), v))
})
}
// NumberValue applies equality check predicate on the "number_value" field. It's identical to NumberValueEQ.
func NumberValue(v int) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldNumberValue), v))
})
}
// BooleanValue applies equality check predicate on the "boolean_value" field. It's identical to BooleanValueEQ.
func BooleanValue(v bool) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldBooleanValue), v))
})
}
// TimeValue applies equality check predicate on the "time_value" field. It's identical to TimeValueEQ.
func TimeValue(v time.Time) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldTimeValue), v))
})
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(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.ItemField {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(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.ItemField {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldUpdatedAt), v))
})
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(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.ItemField {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(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.ItemField {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldDescription), v))
})
}
// DescriptionIsNil applies the IsNil predicate on the "description" field.
func DescriptionIsNil() predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldDescription)))
})
}
// DescriptionNotNil applies the NotNil predicate on the "description" field.
func DescriptionNotNil() predicate.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldDescription), v))
})
}
// TypeEQ applies the EQ predicate on the "type" field.
func TypeEQ(v Type) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldType), v))
})
}
// TypeNEQ applies the NEQ predicate on the "type" field.
func TypeNEQ(v Type) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldType), v))
})
}
// TypeIn applies the In predicate on the "type" field.
func TypeIn(vs ...Type) predicate.ItemField {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldType), v...))
})
}
// TypeNotIn applies the NotIn predicate on the "type" field.
func TypeNotIn(vs ...Type) predicate.ItemField {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldType), v...))
})
}
// TextValueEQ applies the EQ predicate on the "text_value" field.
func TextValueEQ(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldTextValue), v))
})
}
// TextValueNEQ applies the NEQ predicate on the "text_value" field.
func TextValueNEQ(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldTextValue), v))
})
}
// TextValueIn applies the In predicate on the "text_value" field.
func TextValueIn(vs ...string) predicate.ItemField {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldTextValue), v...))
})
}
// TextValueNotIn applies the NotIn predicate on the "text_value" field.
func TextValueNotIn(vs ...string) predicate.ItemField {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldTextValue), v...))
})
}
// TextValueGT applies the GT predicate on the "text_value" field.
func TextValueGT(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldTextValue), v))
})
}
// TextValueGTE applies the GTE predicate on the "text_value" field.
func TextValueGTE(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldTextValue), v))
})
}
// TextValueLT applies the LT predicate on the "text_value" field.
func TextValueLT(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldTextValue), v))
})
}
// TextValueLTE applies the LTE predicate on the "text_value" field.
func TextValueLTE(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldTextValue), v))
})
}
// TextValueContains applies the Contains predicate on the "text_value" field.
func TextValueContains(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldTextValue), v))
})
}
// TextValueHasPrefix applies the HasPrefix predicate on the "text_value" field.
func TextValueHasPrefix(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldTextValue), v))
})
}
// TextValueHasSuffix applies the HasSuffix predicate on the "text_value" field.
func TextValueHasSuffix(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldTextValue), v))
})
}
// TextValueIsNil applies the IsNil predicate on the "text_value" field.
func TextValueIsNil() predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldTextValue)))
})
}
// TextValueNotNil applies the NotNil predicate on the "text_value" field.
func TextValueNotNil() predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NotNull(s.C(FieldTextValue)))
})
}
// TextValueEqualFold applies the EqualFold predicate on the "text_value" field.
func TextValueEqualFold(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldTextValue), v))
})
}
// TextValueContainsFold applies the ContainsFold predicate on the "text_value" field.
func TextValueContainsFold(v string) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldTextValue), v))
})
}
// NumberValueEQ applies the EQ predicate on the "number_value" field.
func NumberValueEQ(v int) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldNumberValue), v))
})
}
// NumberValueNEQ applies the NEQ predicate on the "number_value" field.
func NumberValueNEQ(v int) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldNumberValue), v))
})
}
// NumberValueIn applies the In predicate on the "number_value" field.
func NumberValueIn(vs ...int) predicate.ItemField {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldNumberValue), v...))
})
}
// NumberValueNotIn applies the NotIn predicate on the "number_value" field.
func NumberValueNotIn(vs ...int) predicate.ItemField {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldNumberValue), v...))
})
}
// NumberValueGT applies the GT predicate on the "number_value" field.
func NumberValueGT(v int) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldNumberValue), v))
})
}
// NumberValueGTE applies the GTE predicate on the "number_value" field.
func NumberValueGTE(v int) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldNumberValue), v))
})
}
// NumberValueLT applies the LT predicate on the "number_value" field.
func NumberValueLT(v int) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldNumberValue), v))
})
}
// NumberValueLTE applies the LTE predicate on the "number_value" field.
func NumberValueLTE(v int) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldNumberValue), v))
})
}
// NumberValueIsNil applies the IsNil predicate on the "number_value" field.
func NumberValueIsNil() predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldNumberValue)))
})
}
// NumberValueNotNil applies the NotNil predicate on the "number_value" field.
func NumberValueNotNil() predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NotNull(s.C(FieldNumberValue)))
})
}
// BooleanValueEQ applies the EQ predicate on the "boolean_value" field.
func BooleanValueEQ(v bool) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldBooleanValue), v))
})
}
// BooleanValueNEQ applies the NEQ predicate on the "boolean_value" field.
func BooleanValueNEQ(v bool) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldBooleanValue), v))
})
}
// TimeValueEQ applies the EQ predicate on the "time_value" field.
func TimeValueEQ(v time.Time) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldTimeValue), v))
})
}
// TimeValueNEQ applies the NEQ predicate on the "time_value" field.
func TimeValueNEQ(v time.Time) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldTimeValue), v))
})
}
// TimeValueIn applies the In predicate on the "time_value" field.
func TimeValueIn(vs ...time.Time) predicate.ItemField {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldTimeValue), v...))
})
}
// TimeValueNotIn applies the NotIn predicate on the "time_value" field.
func TimeValueNotIn(vs ...time.Time) predicate.ItemField {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldTimeValue), v...))
})
}
// TimeValueGT applies the GT predicate on the "time_value" field.
func TimeValueGT(v time.Time) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldTimeValue), v))
})
}
// TimeValueGTE applies the GTE predicate on the "time_value" field.
func TimeValueGTE(v time.Time) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldTimeValue), v))
})
}
// TimeValueLT applies the LT predicate on the "time_value" field.
func TimeValueLT(v time.Time) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldTimeValue), v))
})
}
// TimeValueLTE applies the LTE predicate on the "time_value" field.
func TimeValueLTE(v time.Time) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldTimeValue), v))
})
}
// HasItem applies the HasEdge predicate on the "item" edge.
func HasItem() predicate.ItemField {
return predicate.ItemField(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.ItemField {
return predicate.ItemField(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.ItemField) predicate.ItemField {
return predicate.ItemField(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.ItemField) predicate.ItemField {
return predicate.ItemField(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.ItemField) predicate.ItemField {
return predicate.ItemField(func(s *sql.Selector) {
p(s.Not())
})
}

View file

@ -0,0 +1,516 @@
// 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/itemfield"
)
// ItemFieldCreate is the builder for creating a ItemField entity.
type ItemFieldCreate struct {
config
mutation *ItemFieldMutation
hooks []Hook
}
// SetCreatedAt sets the "created_at" field.
func (ifc *ItemFieldCreate) SetCreatedAt(t time.Time) *ItemFieldCreate {
ifc.mutation.SetCreatedAt(t)
return ifc
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (ifc *ItemFieldCreate) SetNillableCreatedAt(t *time.Time) *ItemFieldCreate {
if t != nil {
ifc.SetCreatedAt(*t)
}
return ifc
}
// SetUpdatedAt sets the "updated_at" field.
func (ifc *ItemFieldCreate) SetUpdatedAt(t time.Time) *ItemFieldCreate {
ifc.mutation.SetUpdatedAt(t)
return ifc
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (ifc *ItemFieldCreate) SetNillableUpdatedAt(t *time.Time) *ItemFieldCreate {
if t != nil {
ifc.SetUpdatedAt(*t)
}
return ifc
}
// SetName sets the "name" field.
func (ifc *ItemFieldCreate) SetName(s string) *ItemFieldCreate {
ifc.mutation.SetName(s)
return ifc
}
// SetDescription sets the "description" field.
func (ifc *ItemFieldCreate) SetDescription(s string) *ItemFieldCreate {
ifc.mutation.SetDescription(s)
return ifc
}
// SetNillableDescription sets the "description" field if the given value is not nil.
func (ifc *ItemFieldCreate) SetNillableDescription(s *string) *ItemFieldCreate {
if s != nil {
ifc.SetDescription(*s)
}
return ifc
}
// SetType sets the "type" field.
func (ifc *ItemFieldCreate) SetType(i itemfield.Type) *ItemFieldCreate {
ifc.mutation.SetType(i)
return ifc
}
// SetTextValue sets the "text_value" field.
func (ifc *ItemFieldCreate) SetTextValue(s string) *ItemFieldCreate {
ifc.mutation.SetTextValue(s)
return ifc
}
// SetNillableTextValue sets the "text_value" field if the given value is not nil.
func (ifc *ItemFieldCreate) SetNillableTextValue(s *string) *ItemFieldCreate {
if s != nil {
ifc.SetTextValue(*s)
}
return ifc
}
// SetNumberValue sets the "number_value" field.
func (ifc *ItemFieldCreate) SetNumberValue(i int) *ItemFieldCreate {
ifc.mutation.SetNumberValue(i)
return ifc
}
// SetNillableNumberValue sets the "number_value" field if the given value is not nil.
func (ifc *ItemFieldCreate) SetNillableNumberValue(i *int) *ItemFieldCreate {
if i != nil {
ifc.SetNumberValue(*i)
}
return ifc
}
// SetBooleanValue sets the "boolean_value" field.
func (ifc *ItemFieldCreate) SetBooleanValue(b bool) *ItemFieldCreate {
ifc.mutation.SetBooleanValue(b)
return ifc
}
// SetNillableBooleanValue sets the "boolean_value" field if the given value is not nil.
func (ifc *ItemFieldCreate) SetNillableBooleanValue(b *bool) *ItemFieldCreate {
if b != nil {
ifc.SetBooleanValue(*b)
}
return ifc
}
// SetTimeValue sets the "time_value" field.
func (ifc *ItemFieldCreate) SetTimeValue(t time.Time) *ItemFieldCreate {
ifc.mutation.SetTimeValue(t)
return ifc
}
// SetNillableTimeValue sets the "time_value" field if the given value is not nil.
func (ifc *ItemFieldCreate) SetNillableTimeValue(t *time.Time) *ItemFieldCreate {
if t != nil {
ifc.SetTimeValue(*t)
}
return ifc
}
// SetID sets the "id" field.
func (ifc *ItemFieldCreate) SetID(u uuid.UUID) *ItemFieldCreate {
ifc.mutation.SetID(u)
return ifc
}
// SetNillableID sets the "id" field if the given value is not nil.
func (ifc *ItemFieldCreate) SetNillableID(u *uuid.UUID) *ItemFieldCreate {
if u != nil {
ifc.SetID(*u)
}
return ifc
}
// SetItemID sets the "item" edge to the Item entity by ID.
func (ifc *ItemFieldCreate) SetItemID(id uuid.UUID) *ItemFieldCreate {
ifc.mutation.SetItemID(id)
return ifc
}
// SetNillableItemID sets the "item" edge to the Item entity by ID if the given value is not nil.
func (ifc *ItemFieldCreate) SetNillableItemID(id *uuid.UUID) *ItemFieldCreate {
if id != nil {
ifc = ifc.SetItemID(*id)
}
return ifc
}
// SetItem sets the "item" edge to the Item entity.
func (ifc *ItemFieldCreate) SetItem(i *Item) *ItemFieldCreate {
return ifc.SetItemID(i.ID)
}
// Mutation returns the ItemFieldMutation object of the builder.
func (ifc *ItemFieldCreate) Mutation() *ItemFieldMutation {
return ifc.mutation
}
// Save creates the ItemField in the database.
func (ifc *ItemFieldCreate) Save(ctx context.Context) (*ItemField, error) {
var (
err error
node *ItemField
)
ifc.defaults()
if len(ifc.hooks) == 0 {
if err = ifc.check(); err != nil {
return nil, err
}
node, err = ifc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*ItemFieldMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = ifc.check(); err != nil {
return nil, err
}
ifc.mutation = mutation
if node, err = ifc.sqlSave(ctx); err != nil {
return nil, err
}
mutation.id = &node.ID
mutation.done = true
return node, err
})
for i := len(ifc.hooks) - 1; i >= 0; i-- {
if ifc.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = ifc.hooks[i](mut)
}
v, err := mut.Mutate(ctx, ifc.mutation)
if err != nil {
return nil, err
}
nv, ok := v.(*ItemField)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from ItemFieldMutation", v)
}
node = nv
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (ifc *ItemFieldCreate) SaveX(ctx context.Context) *ItemField {
v, err := ifc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (ifc *ItemFieldCreate) Exec(ctx context.Context) error {
_, err := ifc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (ifc *ItemFieldCreate) ExecX(ctx context.Context) {
if err := ifc.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (ifc *ItemFieldCreate) defaults() {
if _, ok := ifc.mutation.CreatedAt(); !ok {
v := itemfield.DefaultCreatedAt()
ifc.mutation.SetCreatedAt(v)
}
if _, ok := ifc.mutation.UpdatedAt(); !ok {
v := itemfield.DefaultUpdatedAt()
ifc.mutation.SetUpdatedAt(v)
}
if _, ok := ifc.mutation.BooleanValue(); !ok {
v := itemfield.DefaultBooleanValue
ifc.mutation.SetBooleanValue(v)
}
if _, ok := ifc.mutation.TimeValue(); !ok {
v := itemfield.DefaultTimeValue()
ifc.mutation.SetTimeValue(v)
}
if _, ok := ifc.mutation.ID(); !ok {
v := itemfield.DefaultID()
ifc.mutation.SetID(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (ifc *ItemFieldCreate) check() error {
if _, ok := ifc.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "ItemField.created_at"`)}
}
if _, ok := ifc.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "ItemField.updated_at"`)}
}
if _, ok := ifc.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "ItemField.name"`)}
}
if v, ok := ifc.mutation.Name(); ok {
if err := itemfield.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "ItemField.name": %w`, err)}
}
}
if v, ok := ifc.mutation.Description(); ok {
if err := itemfield.DescriptionValidator(v); err != nil {
return &ValidationError{Name: "description", err: fmt.Errorf(`ent: validator failed for field "ItemField.description": %w`, err)}
}
}
if _, ok := ifc.mutation.GetType(); !ok {
return &ValidationError{Name: "type", err: errors.New(`ent: missing required field "ItemField.type"`)}
}
if v, ok := ifc.mutation.GetType(); ok {
if err := itemfield.TypeValidator(v); err != nil {
return &ValidationError{Name: "type", err: fmt.Errorf(`ent: validator failed for field "ItemField.type": %w`, err)}
}
}
if v, ok := ifc.mutation.TextValue(); ok {
if err := itemfield.TextValueValidator(v); err != nil {
return &ValidationError{Name: "text_value", err: fmt.Errorf(`ent: validator failed for field "ItemField.text_value": %w`, err)}
}
}
if _, ok := ifc.mutation.BooleanValue(); !ok {
return &ValidationError{Name: "boolean_value", err: errors.New(`ent: missing required field "ItemField.boolean_value"`)}
}
if _, ok := ifc.mutation.TimeValue(); !ok {
return &ValidationError{Name: "time_value", err: errors.New(`ent: missing required field "ItemField.time_value"`)}
}
return nil
}
func (ifc *ItemFieldCreate) sqlSave(ctx context.Context) (*ItemField, error) {
_node, _spec := ifc.createSpec()
if err := sqlgraph.CreateNode(ctx, ifc.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 (ifc *ItemFieldCreate) createSpec() (*ItemField, *sqlgraph.CreateSpec) {
var (
_node = &ItemField{config: ifc.config}
_spec = &sqlgraph.CreateSpec{
Table: itemfield.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: itemfield.FieldID,
},
}
)
if id, ok := ifc.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = &id
}
if value, ok := ifc.mutation.CreatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: itemfield.FieldCreatedAt,
})
_node.CreatedAt = value
}
if value, ok := ifc.mutation.UpdatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: itemfield.FieldUpdatedAt,
})
_node.UpdatedAt = value
}
if value, ok := ifc.mutation.Name(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: itemfield.FieldName,
})
_node.Name = value
}
if value, ok := ifc.mutation.Description(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: itemfield.FieldDescription,
})
_node.Description = value
}
if value, ok := ifc.mutation.GetType(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeEnum,
Value: value,
Column: itemfield.FieldType,
})
_node.Type = value
}
if value, ok := ifc.mutation.TextValue(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: itemfield.FieldTextValue,
})
_node.TextValue = value
}
if value, ok := ifc.mutation.NumberValue(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: itemfield.FieldNumberValue,
})
_node.NumberValue = value
}
if value, ok := ifc.mutation.BooleanValue(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: itemfield.FieldBooleanValue,
})
_node.BooleanValue = value
}
if value, ok := ifc.mutation.TimeValue(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: itemfield.FieldTimeValue,
})
_node.TimeValue = value
}
if nodes := ifc.mutation.ItemIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: itemfield.ItemTable,
Columns: []string{itemfield.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.item_fields = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// ItemFieldCreateBulk is the builder for creating many ItemField entities in bulk.
type ItemFieldCreateBulk struct {
config
builders []*ItemFieldCreate
}
// Save creates the ItemField entities in the database.
func (ifcb *ItemFieldCreateBulk) Save(ctx context.Context) ([]*ItemField, error) {
specs := make([]*sqlgraph.CreateSpec, len(ifcb.builders))
nodes := make([]*ItemField, len(ifcb.builders))
mutators := make([]Mutator, len(ifcb.builders))
for i := range ifcb.builders {
func(i int, root context.Context) {
builder := ifcb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*ItemFieldMutation)
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, ifcb.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, ifcb.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, ifcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (ifcb *ItemFieldCreateBulk) SaveX(ctx context.Context) []*ItemField {
v, err := ifcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (ifcb *ItemFieldCreateBulk) Exec(ctx context.Context) error {
_, err := ifcb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (ifcb *ItemFieldCreateBulk) ExecX(ctx context.Context) {
if err := ifcb.Exec(ctx); err != nil {
panic(err)
}
}

View file

@ -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/itemfield"
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
)
// ItemFieldDelete is the builder for deleting a ItemField entity.
type ItemFieldDelete struct {
config
hooks []Hook
mutation *ItemFieldMutation
}
// Where appends a list predicates to the ItemFieldDelete builder.
func (ifd *ItemFieldDelete) Where(ps ...predicate.ItemField) *ItemFieldDelete {
ifd.mutation.Where(ps...)
return ifd
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (ifd *ItemFieldDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(ifd.hooks) == 0 {
affected, err = ifd.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*ItemFieldMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
ifd.mutation = mutation
affected, err = ifd.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(ifd.hooks) - 1; i >= 0; i-- {
if ifd.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = ifd.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, ifd.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (ifd *ItemFieldDelete) ExecX(ctx context.Context) int {
n, err := ifd.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (ifd *ItemFieldDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: itemfield.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: itemfield.FieldID,
},
},
}
if ps := ifd.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, ifd.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return affected, err
}
// ItemFieldDeleteOne is the builder for deleting a single ItemField entity.
type ItemFieldDeleteOne struct {
ifd *ItemFieldDelete
}
// Exec executes the deletion query.
func (ifdo *ItemFieldDeleteOne) Exec(ctx context.Context) error {
n, err := ifdo.ifd.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{itemfield.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (ifdo *ItemFieldDeleteOne) ExecX(ctx context.Context) {
ifdo.ifd.ExecX(ctx)
}

View file

@ -0,0 +1,614 @@
// 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/itemfield"
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
)
// ItemFieldQuery is the builder for querying ItemField entities.
type ItemFieldQuery struct {
config
limit *int
offset *int
unique *bool
order []OrderFunc
fields []string
predicates []predicate.ItemField
withItem *ItemQuery
withFKs bool
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the ItemFieldQuery builder.
func (ifq *ItemFieldQuery) Where(ps ...predicate.ItemField) *ItemFieldQuery {
ifq.predicates = append(ifq.predicates, ps...)
return ifq
}
// Limit adds a limit step to the query.
func (ifq *ItemFieldQuery) Limit(limit int) *ItemFieldQuery {
ifq.limit = &limit
return ifq
}
// Offset adds an offset step to the query.
func (ifq *ItemFieldQuery) Offset(offset int) *ItemFieldQuery {
ifq.offset = &offset
return ifq
}
// 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 (ifq *ItemFieldQuery) Unique(unique bool) *ItemFieldQuery {
ifq.unique = &unique
return ifq
}
// Order adds an order step to the query.
func (ifq *ItemFieldQuery) Order(o ...OrderFunc) *ItemFieldQuery {
ifq.order = append(ifq.order, o...)
return ifq
}
// QueryItem chains the current query on the "item" edge.
func (ifq *ItemFieldQuery) QueryItem() *ItemQuery {
query := &ItemQuery{config: ifq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := ifq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := ifq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(itemfield.Table, itemfield.FieldID, selector),
sqlgraph.To(item.Table, item.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, itemfield.ItemTable, itemfield.ItemColumn),
)
fromU = sqlgraph.SetNeighbors(ifq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first ItemField entity from the query.
// Returns a *NotFoundError when no ItemField was found.
func (ifq *ItemFieldQuery) First(ctx context.Context) (*ItemField, error) {
nodes, err := ifq.Limit(1).All(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{itemfield.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (ifq *ItemFieldQuery) FirstX(ctx context.Context) *ItemField {
node, err := ifq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first ItemField ID from the query.
// Returns a *NotFoundError when no ItemField ID was found.
func (ifq *ItemFieldQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = ifq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{itemfield.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (ifq *ItemFieldQuery) FirstIDX(ctx context.Context) uuid.UUID {
id, err := ifq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single ItemField entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one ItemField entity is found.
// Returns a *NotFoundError when no ItemField entities are found.
func (ifq *ItemFieldQuery) Only(ctx context.Context) (*ItemField, error) {
nodes, err := ifq.Limit(2).All(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{itemfield.Label}
default:
return nil, &NotSingularError{itemfield.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (ifq *ItemFieldQuery) OnlyX(ctx context.Context) *ItemField {
node, err := ifq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only ItemField ID in the query.
// Returns a *NotSingularError when more than one ItemField ID is found.
// Returns a *NotFoundError when no entities are found.
func (ifq *ItemFieldQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = ifq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{itemfield.Label}
default:
err = &NotSingularError{itemfield.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (ifq *ItemFieldQuery) OnlyIDX(ctx context.Context) uuid.UUID {
id, err := ifq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of ItemFields.
func (ifq *ItemFieldQuery) All(ctx context.Context) ([]*ItemField, error) {
if err := ifq.prepareQuery(ctx); err != nil {
return nil, err
}
return ifq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (ifq *ItemFieldQuery) AllX(ctx context.Context) []*ItemField {
nodes, err := ifq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of ItemField IDs.
func (ifq *ItemFieldQuery) IDs(ctx context.Context) ([]uuid.UUID, error) {
var ids []uuid.UUID
if err := ifq.Select(itemfield.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (ifq *ItemFieldQuery) IDsX(ctx context.Context) []uuid.UUID {
ids, err := ifq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (ifq *ItemFieldQuery) Count(ctx context.Context) (int, error) {
if err := ifq.prepareQuery(ctx); err != nil {
return 0, err
}
return ifq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (ifq *ItemFieldQuery) CountX(ctx context.Context) int {
count, err := ifq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (ifq *ItemFieldQuery) Exist(ctx context.Context) (bool, error) {
if err := ifq.prepareQuery(ctx); err != nil {
return false, err
}
return ifq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (ifq *ItemFieldQuery) ExistX(ctx context.Context) bool {
exist, err := ifq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the ItemFieldQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (ifq *ItemFieldQuery) Clone() *ItemFieldQuery {
if ifq == nil {
return nil
}
return &ItemFieldQuery{
config: ifq.config,
limit: ifq.limit,
offset: ifq.offset,
order: append([]OrderFunc{}, ifq.order...),
predicates: append([]predicate.ItemField{}, ifq.predicates...),
withItem: ifq.withItem.Clone(),
// clone intermediate query.
sql: ifq.sql.Clone(),
path: ifq.path,
unique: ifq.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 (ifq *ItemFieldQuery) WithItem(opts ...func(*ItemQuery)) *ItemFieldQuery {
query := &ItemQuery{config: ifq.config}
for _, opt := range opts {
opt(query)
}
ifq.withItem = query
return ifq
}
// 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.ItemField.Query().
// GroupBy(itemfield.FieldCreatedAt).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (ifq *ItemFieldQuery) GroupBy(field string, fields ...string) *ItemFieldGroupBy {
grbuild := &ItemFieldGroupBy{config: ifq.config}
grbuild.fields = append([]string{field}, fields...)
grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := ifq.prepareQuery(ctx); err != nil {
return nil, err
}
return ifq.sqlQuery(ctx), nil
}
grbuild.label = itemfield.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.ItemField.Query().
// Select(itemfield.FieldCreatedAt).
// Scan(ctx, &v)
func (ifq *ItemFieldQuery) Select(fields ...string) *ItemFieldSelect {
ifq.fields = append(ifq.fields, fields...)
selbuild := &ItemFieldSelect{ItemFieldQuery: ifq}
selbuild.label = itemfield.Label
selbuild.flds, selbuild.scan = &ifq.fields, selbuild.Scan
return selbuild
}
func (ifq *ItemFieldQuery) prepareQuery(ctx context.Context) error {
for _, f := range ifq.fields {
if !itemfield.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if ifq.path != nil {
prev, err := ifq.path(ctx)
if err != nil {
return err
}
ifq.sql = prev
}
return nil
}
func (ifq *ItemFieldQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*ItemField, error) {
var (
nodes = []*ItemField{}
withFKs = ifq.withFKs
_spec = ifq.querySpec()
loadedTypes = [1]bool{
ifq.withItem != nil,
}
)
if ifq.withItem != nil {
withFKs = true
}
if withFKs {
_spec.Node.Columns = append(_spec.Node.Columns, itemfield.ForeignKeys...)
}
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*ItemField).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &ItemField{config: ifq.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, ifq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := ifq.withItem; query != nil {
if err := ifq.loadItem(ctx, query, nodes, nil,
func(n *ItemField, e *Item) { n.Edges.Item = e }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (ifq *ItemFieldQuery) loadItem(ctx context.Context, query *ItemQuery, nodes []*ItemField, init func(*ItemField), assign func(*ItemField, *Item)) error {
ids := make([]uuid.UUID, 0, len(nodes))
nodeids := make(map[uuid.UUID][]*ItemField)
for i := range nodes {
if nodes[i].item_fields == nil {
continue
}
fk := *nodes[i].item_fields
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_fields" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (ifq *ItemFieldQuery) sqlCount(ctx context.Context) (int, error) {
_spec := ifq.querySpec()
_spec.Node.Columns = ifq.fields
if len(ifq.fields) > 0 {
_spec.Unique = ifq.unique != nil && *ifq.unique
}
return sqlgraph.CountNodes(ctx, ifq.driver, _spec)
}
func (ifq *ItemFieldQuery) sqlExist(ctx context.Context) (bool, error) {
switch _, err := ifq.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 (ifq *ItemFieldQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: itemfield.Table,
Columns: itemfield.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: itemfield.FieldID,
},
},
From: ifq.sql,
Unique: true,
}
if unique := ifq.unique; unique != nil {
_spec.Unique = *unique
}
if fields := ifq.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, itemfield.FieldID)
for i := range fields {
if fields[i] != itemfield.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := ifq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := ifq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := ifq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := ifq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (ifq *ItemFieldQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(ifq.driver.Dialect())
t1 := builder.Table(itemfield.Table)
columns := ifq.fields
if len(columns) == 0 {
columns = itemfield.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if ifq.sql != nil {
selector = ifq.sql
selector.Select(selector.Columns(columns...)...)
}
if ifq.unique != nil && *ifq.unique {
selector.Distinct()
}
for _, p := range ifq.predicates {
p(selector)
}
for _, p := range ifq.order {
p(selector)
}
if offset := ifq.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 := ifq.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// ItemFieldGroupBy is the group-by builder for ItemField entities.
type ItemFieldGroupBy 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 (ifgb *ItemFieldGroupBy) Aggregate(fns ...AggregateFunc) *ItemFieldGroupBy {
ifgb.fns = append(ifgb.fns, fns...)
return ifgb
}
// Scan applies the group-by query and scans the result into the given value.
func (ifgb *ItemFieldGroupBy) Scan(ctx context.Context, v any) error {
query, err := ifgb.path(ctx)
if err != nil {
return err
}
ifgb.sql = query
return ifgb.sqlScan(ctx, v)
}
func (ifgb *ItemFieldGroupBy) sqlScan(ctx context.Context, v any) error {
for _, f := range ifgb.fields {
if !itemfield.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := ifgb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := ifgb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (ifgb *ItemFieldGroupBy) sqlQuery() *sql.Selector {
selector := ifgb.sql.Select()
aggregation := make([]string, 0, len(ifgb.fns))
for _, fn := range ifgb.fns {
aggregation = append(aggregation, fn(selector))
}
// If no columns were selected in a custom aggregation function, the default
// selection is the fields used for "group-by", and the aggregation functions.
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(ifgb.fields)+len(ifgb.fns))
for _, f := range ifgb.fields {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
return selector.GroupBy(selector.Columns(ifgb.fields...)...)
}
// ItemFieldSelect is the builder for selecting fields of ItemField entities.
type ItemFieldSelect struct {
*ItemFieldQuery
selector
// intermediate query (i.e. traversal path).
sql *sql.Selector
}
// Scan applies the selector query and scans the result into the given value.
func (ifs *ItemFieldSelect) Scan(ctx context.Context, v any) error {
if err := ifs.prepareQuery(ctx); err != nil {
return err
}
ifs.sql = ifs.ItemFieldQuery.sqlQuery(ctx)
return ifs.sqlScan(ctx, v)
}
func (ifs *ItemFieldSelect) sqlScan(ctx context.Context, v any) error {
rows := &sql.Rows{}
query, args := ifs.sql.Query()
if err := ifs.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

View file

@ -0,0 +1,836 @@
// 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/itemfield"
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
)
// ItemFieldUpdate is the builder for updating ItemField entities.
type ItemFieldUpdate struct {
config
hooks []Hook
mutation *ItemFieldMutation
}
// Where appends a list predicates to the ItemFieldUpdate builder.
func (ifu *ItemFieldUpdate) Where(ps ...predicate.ItemField) *ItemFieldUpdate {
ifu.mutation.Where(ps...)
return ifu
}
// SetUpdatedAt sets the "updated_at" field.
func (ifu *ItemFieldUpdate) SetUpdatedAt(t time.Time) *ItemFieldUpdate {
ifu.mutation.SetUpdatedAt(t)
return ifu
}
// SetName sets the "name" field.
func (ifu *ItemFieldUpdate) SetName(s string) *ItemFieldUpdate {
ifu.mutation.SetName(s)
return ifu
}
// SetDescription sets the "description" field.
func (ifu *ItemFieldUpdate) SetDescription(s string) *ItemFieldUpdate {
ifu.mutation.SetDescription(s)
return ifu
}
// SetNillableDescription sets the "description" field if the given value is not nil.
func (ifu *ItemFieldUpdate) SetNillableDescription(s *string) *ItemFieldUpdate {
if s != nil {
ifu.SetDescription(*s)
}
return ifu
}
// ClearDescription clears the value of the "description" field.
func (ifu *ItemFieldUpdate) ClearDescription() *ItemFieldUpdate {
ifu.mutation.ClearDescription()
return ifu
}
// SetType sets the "type" field.
func (ifu *ItemFieldUpdate) SetType(i itemfield.Type) *ItemFieldUpdate {
ifu.mutation.SetType(i)
return ifu
}
// SetTextValue sets the "text_value" field.
func (ifu *ItemFieldUpdate) SetTextValue(s string) *ItemFieldUpdate {
ifu.mutation.SetTextValue(s)
return ifu
}
// SetNillableTextValue sets the "text_value" field if the given value is not nil.
func (ifu *ItemFieldUpdate) SetNillableTextValue(s *string) *ItemFieldUpdate {
if s != nil {
ifu.SetTextValue(*s)
}
return ifu
}
// ClearTextValue clears the value of the "text_value" field.
func (ifu *ItemFieldUpdate) ClearTextValue() *ItemFieldUpdate {
ifu.mutation.ClearTextValue()
return ifu
}
// SetNumberValue sets the "number_value" field.
func (ifu *ItemFieldUpdate) SetNumberValue(i int) *ItemFieldUpdate {
ifu.mutation.ResetNumberValue()
ifu.mutation.SetNumberValue(i)
return ifu
}
// SetNillableNumberValue sets the "number_value" field if the given value is not nil.
func (ifu *ItemFieldUpdate) SetNillableNumberValue(i *int) *ItemFieldUpdate {
if i != nil {
ifu.SetNumberValue(*i)
}
return ifu
}
// AddNumberValue adds i to the "number_value" field.
func (ifu *ItemFieldUpdate) AddNumberValue(i int) *ItemFieldUpdate {
ifu.mutation.AddNumberValue(i)
return ifu
}
// ClearNumberValue clears the value of the "number_value" field.
func (ifu *ItemFieldUpdate) ClearNumberValue() *ItemFieldUpdate {
ifu.mutation.ClearNumberValue()
return ifu
}
// SetBooleanValue sets the "boolean_value" field.
func (ifu *ItemFieldUpdate) SetBooleanValue(b bool) *ItemFieldUpdate {
ifu.mutation.SetBooleanValue(b)
return ifu
}
// SetNillableBooleanValue sets the "boolean_value" field if the given value is not nil.
func (ifu *ItemFieldUpdate) SetNillableBooleanValue(b *bool) *ItemFieldUpdate {
if b != nil {
ifu.SetBooleanValue(*b)
}
return ifu
}
// SetTimeValue sets the "time_value" field.
func (ifu *ItemFieldUpdate) SetTimeValue(t time.Time) *ItemFieldUpdate {
ifu.mutation.SetTimeValue(t)
return ifu
}
// SetNillableTimeValue sets the "time_value" field if the given value is not nil.
func (ifu *ItemFieldUpdate) SetNillableTimeValue(t *time.Time) *ItemFieldUpdate {
if t != nil {
ifu.SetTimeValue(*t)
}
return ifu
}
// SetItemID sets the "item" edge to the Item entity by ID.
func (ifu *ItemFieldUpdate) SetItemID(id uuid.UUID) *ItemFieldUpdate {
ifu.mutation.SetItemID(id)
return ifu
}
// SetNillableItemID sets the "item" edge to the Item entity by ID if the given value is not nil.
func (ifu *ItemFieldUpdate) SetNillableItemID(id *uuid.UUID) *ItemFieldUpdate {
if id != nil {
ifu = ifu.SetItemID(*id)
}
return ifu
}
// SetItem sets the "item" edge to the Item entity.
func (ifu *ItemFieldUpdate) SetItem(i *Item) *ItemFieldUpdate {
return ifu.SetItemID(i.ID)
}
// Mutation returns the ItemFieldMutation object of the builder.
func (ifu *ItemFieldUpdate) Mutation() *ItemFieldMutation {
return ifu.mutation
}
// ClearItem clears the "item" edge to the Item entity.
func (ifu *ItemFieldUpdate) ClearItem() *ItemFieldUpdate {
ifu.mutation.ClearItem()
return ifu
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (ifu *ItemFieldUpdate) Save(ctx context.Context) (int, error) {
var (
err error
affected int
)
ifu.defaults()
if len(ifu.hooks) == 0 {
if err = ifu.check(); err != nil {
return 0, err
}
affected, err = ifu.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*ItemFieldMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = ifu.check(); err != nil {
return 0, err
}
ifu.mutation = mutation
affected, err = ifu.sqlSave(ctx)
mutation.done = true
return affected, err
})
for i := len(ifu.hooks) - 1; i >= 0; i-- {
if ifu.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = ifu.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, ifu.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// SaveX is like Save, but panics if an error occurs.
func (ifu *ItemFieldUpdate) SaveX(ctx context.Context) int {
affected, err := ifu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (ifu *ItemFieldUpdate) Exec(ctx context.Context) error {
_, err := ifu.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (ifu *ItemFieldUpdate) ExecX(ctx context.Context) {
if err := ifu.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (ifu *ItemFieldUpdate) defaults() {
if _, ok := ifu.mutation.UpdatedAt(); !ok {
v := itemfield.UpdateDefaultUpdatedAt()
ifu.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (ifu *ItemFieldUpdate) check() error {
if v, ok := ifu.mutation.Name(); ok {
if err := itemfield.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "ItemField.name": %w`, err)}
}
}
if v, ok := ifu.mutation.Description(); ok {
if err := itemfield.DescriptionValidator(v); err != nil {
return &ValidationError{Name: "description", err: fmt.Errorf(`ent: validator failed for field "ItemField.description": %w`, err)}
}
}
if v, ok := ifu.mutation.GetType(); ok {
if err := itemfield.TypeValidator(v); err != nil {
return &ValidationError{Name: "type", err: fmt.Errorf(`ent: validator failed for field "ItemField.type": %w`, err)}
}
}
if v, ok := ifu.mutation.TextValue(); ok {
if err := itemfield.TextValueValidator(v); err != nil {
return &ValidationError{Name: "text_value", err: fmt.Errorf(`ent: validator failed for field "ItemField.text_value": %w`, err)}
}
}
return nil
}
func (ifu *ItemFieldUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: itemfield.Table,
Columns: itemfield.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: itemfield.FieldID,
},
},
}
if ps := ifu.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := ifu.mutation.UpdatedAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: itemfield.FieldUpdatedAt,
})
}
if value, ok := ifu.mutation.Name(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: itemfield.FieldName,
})
}
if value, ok := ifu.mutation.Description(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: itemfield.FieldDescription,
})
}
if ifu.mutation.DescriptionCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: itemfield.FieldDescription,
})
}
if value, ok := ifu.mutation.GetType(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeEnum,
Value: value,
Column: itemfield.FieldType,
})
}
if value, ok := ifu.mutation.TextValue(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: itemfield.FieldTextValue,
})
}
if ifu.mutation.TextValueCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: itemfield.FieldTextValue,
})
}
if value, ok := ifu.mutation.NumberValue(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: itemfield.FieldNumberValue,
})
}
if value, ok := ifu.mutation.AddedNumberValue(); ok {
_spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: itemfield.FieldNumberValue,
})
}
if ifu.mutation.NumberValueCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: itemfield.FieldNumberValue,
})
}
if value, ok := ifu.mutation.BooleanValue(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: itemfield.FieldBooleanValue,
})
}
if value, ok := ifu.mutation.TimeValue(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: itemfield.FieldTimeValue,
})
}
if ifu.mutation.ItemCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: itemfield.ItemTable,
Columns: []string{itemfield.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 := ifu.mutation.ItemIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: itemfield.ItemTable,
Columns: []string{itemfield.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, ifu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{itemfield.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
return n, nil
}
// ItemFieldUpdateOne is the builder for updating a single ItemField entity.
type ItemFieldUpdateOne struct {
config
fields []string
hooks []Hook
mutation *ItemFieldMutation
}
// SetUpdatedAt sets the "updated_at" field.
func (ifuo *ItemFieldUpdateOne) SetUpdatedAt(t time.Time) *ItemFieldUpdateOne {
ifuo.mutation.SetUpdatedAt(t)
return ifuo
}
// SetName sets the "name" field.
func (ifuo *ItemFieldUpdateOne) SetName(s string) *ItemFieldUpdateOne {
ifuo.mutation.SetName(s)
return ifuo
}
// SetDescription sets the "description" field.
func (ifuo *ItemFieldUpdateOne) SetDescription(s string) *ItemFieldUpdateOne {
ifuo.mutation.SetDescription(s)
return ifuo
}
// SetNillableDescription sets the "description" field if the given value is not nil.
func (ifuo *ItemFieldUpdateOne) SetNillableDescription(s *string) *ItemFieldUpdateOne {
if s != nil {
ifuo.SetDescription(*s)
}
return ifuo
}
// ClearDescription clears the value of the "description" field.
func (ifuo *ItemFieldUpdateOne) ClearDescription() *ItemFieldUpdateOne {
ifuo.mutation.ClearDescription()
return ifuo
}
// SetType sets the "type" field.
func (ifuo *ItemFieldUpdateOne) SetType(i itemfield.Type) *ItemFieldUpdateOne {
ifuo.mutation.SetType(i)
return ifuo
}
// SetTextValue sets the "text_value" field.
func (ifuo *ItemFieldUpdateOne) SetTextValue(s string) *ItemFieldUpdateOne {
ifuo.mutation.SetTextValue(s)
return ifuo
}
// SetNillableTextValue sets the "text_value" field if the given value is not nil.
func (ifuo *ItemFieldUpdateOne) SetNillableTextValue(s *string) *ItemFieldUpdateOne {
if s != nil {
ifuo.SetTextValue(*s)
}
return ifuo
}
// ClearTextValue clears the value of the "text_value" field.
func (ifuo *ItemFieldUpdateOne) ClearTextValue() *ItemFieldUpdateOne {
ifuo.mutation.ClearTextValue()
return ifuo
}
// SetNumberValue sets the "number_value" field.
func (ifuo *ItemFieldUpdateOne) SetNumberValue(i int) *ItemFieldUpdateOne {
ifuo.mutation.ResetNumberValue()
ifuo.mutation.SetNumberValue(i)
return ifuo
}
// SetNillableNumberValue sets the "number_value" field if the given value is not nil.
func (ifuo *ItemFieldUpdateOne) SetNillableNumberValue(i *int) *ItemFieldUpdateOne {
if i != nil {
ifuo.SetNumberValue(*i)
}
return ifuo
}
// AddNumberValue adds i to the "number_value" field.
func (ifuo *ItemFieldUpdateOne) AddNumberValue(i int) *ItemFieldUpdateOne {
ifuo.mutation.AddNumberValue(i)
return ifuo
}
// ClearNumberValue clears the value of the "number_value" field.
func (ifuo *ItemFieldUpdateOne) ClearNumberValue() *ItemFieldUpdateOne {
ifuo.mutation.ClearNumberValue()
return ifuo
}
// SetBooleanValue sets the "boolean_value" field.
func (ifuo *ItemFieldUpdateOne) SetBooleanValue(b bool) *ItemFieldUpdateOne {
ifuo.mutation.SetBooleanValue(b)
return ifuo
}
// SetNillableBooleanValue sets the "boolean_value" field if the given value is not nil.
func (ifuo *ItemFieldUpdateOne) SetNillableBooleanValue(b *bool) *ItemFieldUpdateOne {
if b != nil {
ifuo.SetBooleanValue(*b)
}
return ifuo
}
// SetTimeValue sets the "time_value" field.
func (ifuo *ItemFieldUpdateOne) SetTimeValue(t time.Time) *ItemFieldUpdateOne {
ifuo.mutation.SetTimeValue(t)
return ifuo
}
// SetNillableTimeValue sets the "time_value" field if the given value is not nil.
func (ifuo *ItemFieldUpdateOne) SetNillableTimeValue(t *time.Time) *ItemFieldUpdateOne {
if t != nil {
ifuo.SetTimeValue(*t)
}
return ifuo
}
// SetItemID sets the "item" edge to the Item entity by ID.
func (ifuo *ItemFieldUpdateOne) SetItemID(id uuid.UUID) *ItemFieldUpdateOne {
ifuo.mutation.SetItemID(id)
return ifuo
}
// SetNillableItemID sets the "item" edge to the Item entity by ID if the given value is not nil.
func (ifuo *ItemFieldUpdateOne) SetNillableItemID(id *uuid.UUID) *ItemFieldUpdateOne {
if id != nil {
ifuo = ifuo.SetItemID(*id)
}
return ifuo
}
// SetItem sets the "item" edge to the Item entity.
func (ifuo *ItemFieldUpdateOne) SetItem(i *Item) *ItemFieldUpdateOne {
return ifuo.SetItemID(i.ID)
}
// Mutation returns the ItemFieldMutation object of the builder.
func (ifuo *ItemFieldUpdateOne) Mutation() *ItemFieldMutation {
return ifuo.mutation
}
// ClearItem clears the "item" edge to the Item entity.
func (ifuo *ItemFieldUpdateOne) ClearItem() *ItemFieldUpdateOne {
ifuo.mutation.ClearItem()
return ifuo
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (ifuo *ItemFieldUpdateOne) Select(field string, fields ...string) *ItemFieldUpdateOne {
ifuo.fields = append([]string{field}, fields...)
return ifuo
}
// Save executes the query and returns the updated ItemField entity.
func (ifuo *ItemFieldUpdateOne) Save(ctx context.Context) (*ItemField, error) {
var (
err error
node *ItemField
)
ifuo.defaults()
if len(ifuo.hooks) == 0 {
if err = ifuo.check(); err != nil {
return nil, err
}
node, err = ifuo.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*ItemFieldMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = ifuo.check(); err != nil {
return nil, err
}
ifuo.mutation = mutation
node, err = ifuo.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(ifuo.hooks) - 1; i >= 0; i-- {
if ifuo.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = ifuo.hooks[i](mut)
}
v, err := mut.Mutate(ctx, ifuo.mutation)
if err != nil {
return nil, err
}
nv, ok := v.(*ItemField)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from ItemFieldMutation", v)
}
node = nv
}
return node, err
}
// SaveX is like Save, but panics if an error occurs.
func (ifuo *ItemFieldUpdateOne) SaveX(ctx context.Context) *ItemField {
node, err := ifuo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (ifuo *ItemFieldUpdateOne) Exec(ctx context.Context) error {
_, err := ifuo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (ifuo *ItemFieldUpdateOne) ExecX(ctx context.Context) {
if err := ifuo.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (ifuo *ItemFieldUpdateOne) defaults() {
if _, ok := ifuo.mutation.UpdatedAt(); !ok {
v := itemfield.UpdateDefaultUpdatedAt()
ifuo.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (ifuo *ItemFieldUpdateOne) check() error {
if v, ok := ifuo.mutation.Name(); ok {
if err := itemfield.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "ItemField.name": %w`, err)}
}
}
if v, ok := ifuo.mutation.Description(); ok {
if err := itemfield.DescriptionValidator(v); err != nil {
return &ValidationError{Name: "description", err: fmt.Errorf(`ent: validator failed for field "ItemField.description": %w`, err)}
}
}
if v, ok := ifuo.mutation.GetType(); ok {
if err := itemfield.TypeValidator(v); err != nil {
return &ValidationError{Name: "type", err: fmt.Errorf(`ent: validator failed for field "ItemField.type": %w`, err)}
}
}
if v, ok := ifuo.mutation.TextValue(); ok {
if err := itemfield.TextValueValidator(v); err != nil {
return &ValidationError{Name: "text_value", err: fmt.Errorf(`ent: validator failed for field "ItemField.text_value": %w`, err)}
}
}
return nil
}
func (ifuo *ItemFieldUpdateOne) sqlSave(ctx context.Context) (_node *ItemField, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: itemfield.Table,
Columns: itemfield.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: itemfield.FieldID,
},
},
}
id, ok := ifuo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "ItemField.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := ifuo.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, itemfield.FieldID)
for _, f := range fields {
if !itemfield.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != itemfield.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := ifuo.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := ifuo.mutation.UpdatedAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: itemfield.FieldUpdatedAt,
})
}
if value, ok := ifuo.mutation.Name(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: itemfield.FieldName,
})
}
if value, ok := ifuo.mutation.Description(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: itemfield.FieldDescription,
})
}
if ifuo.mutation.DescriptionCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: itemfield.FieldDescription,
})
}
if value, ok := ifuo.mutation.GetType(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeEnum,
Value: value,
Column: itemfield.FieldType,
})
}
if value, ok := ifuo.mutation.TextValue(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: itemfield.FieldTextValue,
})
}
if ifuo.mutation.TextValueCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: itemfield.FieldTextValue,
})
}
if value, ok := ifuo.mutation.NumberValue(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: itemfield.FieldNumberValue,
})
}
if value, ok := ifuo.mutation.AddedNumberValue(); ok {
_spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: itemfield.FieldNumberValue,
})
}
if ifuo.mutation.NumberValueCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: itemfield.FieldNumberValue,
})
}
if value, ok := ifuo.mutation.BooleanValue(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: itemfield.FieldBooleanValue,
})
}
if value, ok := ifuo.mutation.TimeValue(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: itemfield.FieldTimeValue,
})
}
if ifuo.mutation.ItemCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: itemfield.ItemTable,
Columns: []string{itemfield.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 := ifuo.mutation.ItemIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: itemfield.ItemTable,
Columns: []string{itemfield.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 = &ItemField{config: ifuo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, ifuo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{itemfield.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
return _node, nil
}

View file

@ -0,0 +1,204 @@
// 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/group"
"github.com/hay-kot/homebox/backend/internal/data/ent/label"
)
// Label is the model entity for the Label schema.
type Label 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"`
// 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"`
// Color holds the value of the "color" field.
Color string `json:"color,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the LabelQuery when eager-loading is set.
Edges LabelEdges `json:"edges"`
group_labels *uuid.UUID
}
// LabelEdges holds the relations/edges for other nodes in the graph.
type LabelEdges struct {
// Group holds the value of the group edge.
Group *Group `json:"group,omitempty"`
// Items holds the value of the items edge.
Items []*Item `json:"items,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
}
// GroupOrErr returns the Group value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e LabelEdges) GroupOrErr() (*Group, error) {
if e.loadedTypes[0] {
if e.Group == nil {
// Edge was loaded but was not found.
return nil, &NotFoundError{label: group.Label}
}
return e.Group, nil
}
return nil, &NotLoadedError{edge: "group"}
}
// ItemsOrErr returns the Items value or an error if the edge
// was not loaded in eager-loading.
func (e LabelEdges) ItemsOrErr() ([]*Item, error) {
if e.loadedTypes[1] {
return e.Items, nil
}
return nil, &NotLoadedError{edge: "items"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Label) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case label.FieldName, label.FieldDescription, label.FieldColor:
values[i] = new(sql.NullString)
case label.FieldCreatedAt, label.FieldUpdatedAt:
values[i] = new(sql.NullTime)
case label.FieldID:
values[i] = new(uuid.UUID)
case label.ForeignKeys[0]: // group_labels
values[i] = &sql.NullScanner{S: new(uuid.UUID)}
default:
return nil, fmt.Errorf("unexpected column %q for type Label", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Label fields.
func (l *Label) 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 label.FieldID:
if value, ok := values[i].(*uuid.UUID); !ok {
return fmt.Errorf("unexpected type %T for field id", values[i])
} else if value != nil {
l.ID = *value
}
case label.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 {
l.CreatedAt = value.Time
}
case label.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 {
l.UpdatedAt = value.Time
}
case label.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
l.Name = value.String
}
case label.FieldDescription:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field description", values[i])
} else if value.Valid {
l.Description = value.String
}
case label.FieldColor:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field color", values[i])
} else if value.Valid {
l.Color = value.String
}
case label.ForeignKeys[0]:
if value, ok := values[i].(*sql.NullScanner); !ok {
return fmt.Errorf("unexpected type %T for field group_labels", values[i])
} else if value.Valid {
l.group_labels = new(uuid.UUID)
*l.group_labels = *value.S.(*uuid.UUID)
}
}
}
return nil
}
// QueryGroup queries the "group" edge of the Label entity.
func (l *Label) QueryGroup() *GroupQuery {
return (&LabelClient{config: l.config}).QueryGroup(l)
}
// QueryItems queries the "items" edge of the Label entity.
func (l *Label) QueryItems() *ItemQuery {
return (&LabelClient{config: l.config}).QueryItems(l)
}
// Update returns a builder for updating this Label.
// Note that you need to call Label.Unwrap() before calling this method if this Label
// was returned from a transaction, and the transaction was committed or rolled back.
func (l *Label) Update() *LabelUpdateOne {
return (&LabelClient{config: l.config}).UpdateOne(l)
}
// Unwrap unwraps the Label 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 (l *Label) Unwrap() *Label {
_tx, ok := l.config.driver.(*txDriver)
if !ok {
panic("ent: Label is not a transactional entity")
}
l.config.driver = _tx.drv
return l
}
// String implements the fmt.Stringer.
func (l *Label) String() string {
var builder strings.Builder
builder.WriteString("Label(")
builder.WriteString(fmt.Sprintf("id=%v, ", l.ID))
builder.WriteString("created_at=")
builder.WriteString(l.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(l.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("name=")
builder.WriteString(l.Name)
builder.WriteString(", ")
builder.WriteString("description=")
builder.WriteString(l.Description)
builder.WriteString(", ")
builder.WriteString("color=")
builder.WriteString(l.Color)
builder.WriteByte(')')
return builder.String()
}
// Labels is a parsable slice of Label.
type Labels []*Label
func (l Labels) config(cfg config) {
for _i := range l {
l[_i].config = cfg
}
}

View file

@ -0,0 +1,98 @@
// Code generated by ent, DO NOT EDIT.
package label
import (
"time"
"github.com/google/uuid"
)
const (
// Label holds the string label denoting the label type in the database.
Label = "label"
// 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"
// 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"
// FieldColor holds the string denoting the color field in the database.
FieldColor = "color"
// EdgeGroup holds the string denoting the group edge name in mutations.
EdgeGroup = "group"
// EdgeItems holds the string denoting the items edge name in mutations.
EdgeItems = "items"
// Table holds the table name of the label in the database.
Table = "labels"
// GroupTable is the table that holds the group relation/edge.
GroupTable = "labels"
// GroupInverseTable is the table name for the Group entity.
// It exists in this package in order to avoid circular dependency with the "group" package.
GroupInverseTable = "groups"
// GroupColumn is the table column denoting the group relation/edge.
GroupColumn = "group_labels"
// ItemsTable is the table that holds the items relation/edge. The primary key declared below.
ItemsTable = "label_items"
// ItemsInverseTable is the table name for the Item entity.
// It exists in this package in order to avoid circular dependency with the "item" package.
ItemsInverseTable = "items"
)
// Columns holds all SQL columns for label fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldName,
FieldDescription,
FieldColor,
}
// ForeignKeys holds the SQL foreign-keys that are owned by the "labels"
// table and are not defined as standalone fields in the schema.
var ForeignKeys = []string{
"group_labels",
}
var (
// ItemsPrimaryKey and ItemsColumn2 are the table columns denoting the
// primary key for the items relation (M2M).
ItemsPrimaryKey = []string{"label_id", "item_id"}
)
// 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
}
}
for i := range ForeignKeys {
if column == ForeignKeys[i] {
return true
}
}
return false
}
var (
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
// UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
UpdateDefaultUpdatedAt func() time.Time
// NameValidator is a validator for the "name" field. It is called by the builders before save.
NameValidator func(string) error
// DescriptionValidator is a validator for the "description" field. It is called by the builders before save.
DescriptionValidator func(string) error
// ColorValidator is a validator for the "color" field. It is called by the builders before save.
ColorValidator func(string) error
// DefaultID holds the default value on creation for the "id" field.
DefaultID func() uuid.UUID
)

View file

@ -0,0 +1,659 @@
// Code generated by ent, DO NOT EDIT.
package label
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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
})
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.Label {
return predicate.Label(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.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldDescription), v))
})
}
// Color applies equality check predicate on the "color" field. It's identical to ColorEQ.
func Color(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldColor), v))
})
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Label(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.Label {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Label(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.Label {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldUpdatedAt), v))
})
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Label(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.Label {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Label(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.Label {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldDescription), v))
})
}
// DescriptionIsNil applies the IsNil predicate on the "description" field.
func DescriptionIsNil() predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldDescription)))
})
}
// DescriptionNotNil applies the NotNil predicate on the "description" field.
func DescriptionNotNil() predicate.Label {
return predicate.Label(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.Label {
return predicate.Label(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.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldDescription), v))
})
}
// ColorEQ applies the EQ predicate on the "color" field.
func ColorEQ(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldColor), v))
})
}
// ColorNEQ applies the NEQ predicate on the "color" field.
func ColorNEQ(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldColor), v))
})
}
// ColorIn applies the In predicate on the "color" field.
func ColorIn(vs ...string) predicate.Label {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.In(s.C(FieldColor), v...))
})
}
// ColorNotIn applies the NotIn predicate on the "color" field.
func ColorNotIn(vs ...string) predicate.Label {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.NotIn(s.C(FieldColor), v...))
})
}
// ColorGT applies the GT predicate on the "color" field.
func ColorGT(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldColor), v))
})
}
// ColorGTE applies the GTE predicate on the "color" field.
func ColorGTE(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldColor), v))
})
}
// ColorLT applies the LT predicate on the "color" field.
func ColorLT(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldColor), v))
})
}
// ColorLTE applies the LTE predicate on the "color" field.
func ColorLTE(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldColor), v))
})
}
// ColorContains applies the Contains predicate on the "color" field.
func ColorContains(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldColor), v))
})
}
// ColorHasPrefix applies the HasPrefix predicate on the "color" field.
func ColorHasPrefix(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldColor), v))
})
}
// ColorHasSuffix applies the HasSuffix predicate on the "color" field.
func ColorHasSuffix(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldColor), v))
})
}
// ColorIsNil applies the IsNil predicate on the "color" field.
func ColorIsNil() predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldColor)))
})
}
// ColorNotNil applies the NotNil predicate on the "color" field.
func ColorNotNil() predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.NotNull(s.C(FieldColor)))
})
}
// ColorEqualFold applies the EqualFold predicate on the "color" field.
func ColorEqualFold(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldColor), v))
})
}
// ColorContainsFold applies the ContainsFold predicate on the "color" field.
func ColorContainsFold(v string) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldColor), v))
})
}
// HasGroup applies the HasEdge predicate on the "group" edge.
func HasGroup() predicate.Label {
return predicate.Label(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(GroupTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasGroupWith applies the HasEdge predicate on the "group" edge with a given conditions (other predicates).
func HasGroupWith(preds ...predicate.Group) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(GroupInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn),
)
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasItems applies the HasEdge predicate on the "items" edge.
func HasItems() predicate.Label {
return predicate.Label(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(ItemsTable, FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, ItemsTable, ItemsPrimaryKey...),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasItemsWith applies the HasEdge predicate on the "items" edge with a given conditions (other predicates).
func HasItemsWith(preds ...predicate.Item) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(ItemsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, ItemsTable, ItemsPrimaryKey...),
)
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.Label) predicate.Label {
return predicate.Label(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.Label) predicate.Label {
return predicate.Label(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.Label) predicate.Label {
return predicate.Label(func(s *sql.Selector) {
p(s.Not())
})
}

View file

@ -0,0 +1,444 @@
// 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/group"
"github.com/hay-kot/homebox/backend/internal/data/ent/item"
"github.com/hay-kot/homebox/backend/internal/data/ent/label"
)
// LabelCreate is the builder for creating a Label entity.
type LabelCreate struct {
config
mutation *LabelMutation
hooks []Hook
}
// SetCreatedAt sets the "created_at" field.
func (lc *LabelCreate) SetCreatedAt(t time.Time) *LabelCreate {
lc.mutation.SetCreatedAt(t)
return lc
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (lc *LabelCreate) SetNillableCreatedAt(t *time.Time) *LabelCreate {
if t != nil {
lc.SetCreatedAt(*t)
}
return lc
}
// SetUpdatedAt sets the "updated_at" field.
func (lc *LabelCreate) SetUpdatedAt(t time.Time) *LabelCreate {
lc.mutation.SetUpdatedAt(t)
return lc
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (lc *LabelCreate) SetNillableUpdatedAt(t *time.Time) *LabelCreate {
if t != nil {
lc.SetUpdatedAt(*t)
}
return lc
}
// SetName sets the "name" field.
func (lc *LabelCreate) SetName(s string) *LabelCreate {
lc.mutation.SetName(s)
return lc
}
// SetDescription sets the "description" field.
func (lc *LabelCreate) SetDescription(s string) *LabelCreate {
lc.mutation.SetDescription(s)
return lc
}
// SetNillableDescription sets the "description" field if the given value is not nil.
func (lc *LabelCreate) SetNillableDescription(s *string) *LabelCreate {
if s != nil {
lc.SetDescription(*s)
}
return lc
}
// SetColor sets the "color" field.
func (lc *LabelCreate) SetColor(s string) *LabelCreate {
lc.mutation.SetColor(s)
return lc
}
// SetNillableColor sets the "color" field if the given value is not nil.
func (lc *LabelCreate) SetNillableColor(s *string) *LabelCreate {
if s != nil {
lc.SetColor(*s)
}
return lc
}
// SetID sets the "id" field.
func (lc *LabelCreate) SetID(u uuid.UUID) *LabelCreate {
lc.mutation.SetID(u)
return lc
}
// SetNillableID sets the "id" field if the given value is not nil.
func (lc *LabelCreate) SetNillableID(u *uuid.UUID) *LabelCreate {
if u != nil {
lc.SetID(*u)
}
return lc
}
// SetGroupID sets the "group" edge to the Group entity by ID.
func (lc *LabelCreate) SetGroupID(id uuid.UUID) *LabelCreate {
lc.mutation.SetGroupID(id)
return lc
}
// SetGroup sets the "group" edge to the Group entity.
func (lc *LabelCreate) SetGroup(g *Group) *LabelCreate {
return lc.SetGroupID(g.ID)
}
// AddItemIDs adds the "items" edge to the Item entity by IDs.
func (lc *LabelCreate) AddItemIDs(ids ...uuid.UUID) *LabelCreate {
lc.mutation.AddItemIDs(ids...)
return lc
}
// AddItems adds the "items" edges to the Item entity.
func (lc *LabelCreate) AddItems(i ...*Item) *LabelCreate {
ids := make([]uuid.UUID, len(i))
for j := range i {
ids[j] = i[j].ID
}
return lc.AddItemIDs(ids...)
}
// Mutation returns the LabelMutation object of the builder.
func (lc *LabelCreate) Mutation() *LabelMutation {
return lc.mutation
}
// Save creates the Label in the database.
func (lc *LabelCreate) Save(ctx context.Context) (*Label, error) {
var (
err error
node *Label
)
lc.defaults()
if len(lc.hooks) == 0 {
if err = lc.check(); err != nil {
return nil, err
}
node, err = lc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*LabelMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = lc.check(); err != nil {
return nil, err
}
lc.mutation = mutation
if node, err = lc.sqlSave(ctx); err != nil {
return nil, err
}
mutation.id = &node.ID
mutation.done = true
return node, err
})
for i := len(lc.hooks) - 1; i >= 0; i-- {
if lc.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = lc.hooks[i](mut)
}
v, err := mut.Mutate(ctx, lc.mutation)
if err != nil {
return nil, err
}
nv, ok := v.(*Label)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from LabelMutation", v)
}
node = nv
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (lc *LabelCreate) SaveX(ctx context.Context) *Label {
v, err := lc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (lc *LabelCreate) Exec(ctx context.Context) error {
_, err := lc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (lc *LabelCreate) ExecX(ctx context.Context) {
if err := lc.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (lc *LabelCreate) defaults() {
if _, ok := lc.mutation.CreatedAt(); !ok {
v := label.DefaultCreatedAt()
lc.mutation.SetCreatedAt(v)
}
if _, ok := lc.mutation.UpdatedAt(); !ok {
v := label.DefaultUpdatedAt()
lc.mutation.SetUpdatedAt(v)
}
if _, ok := lc.mutation.ID(); !ok {
v := label.DefaultID()
lc.mutation.SetID(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (lc *LabelCreate) check() error {
if _, ok := lc.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Label.created_at"`)}
}
if _, ok := lc.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Label.updated_at"`)}
}
if _, ok := lc.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Label.name"`)}
}
if v, ok := lc.mutation.Name(); ok {
if err := label.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Label.name": %w`, err)}
}
}
if v, ok := lc.mutation.Description(); ok {
if err := label.DescriptionValidator(v); err != nil {
return &ValidationError{Name: "description", err: fmt.Errorf(`ent: validator failed for field "Label.description": %w`, err)}
}
}
if v, ok := lc.mutation.Color(); ok {
if err := label.ColorValidator(v); err != nil {
return &ValidationError{Name: "color", err: fmt.Errorf(`ent: validator failed for field "Label.color": %w`, err)}
}
}
if _, ok := lc.mutation.GroupID(); !ok {
return &ValidationError{Name: "group", err: errors.New(`ent: missing required edge "Label.group"`)}
}
return nil
}
func (lc *LabelCreate) sqlSave(ctx context.Context) (*Label, error) {
_node, _spec := lc.createSpec()
if err := sqlgraph.CreateNode(ctx, lc.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 (lc *LabelCreate) createSpec() (*Label, *sqlgraph.CreateSpec) {
var (
_node = &Label{config: lc.config}
_spec = &sqlgraph.CreateSpec{
Table: label.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: label.FieldID,
},
}
)
if id, ok := lc.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = &id
}
if value, ok := lc.mutation.CreatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: label.FieldCreatedAt,
})
_node.CreatedAt = value
}
if value, ok := lc.mutation.UpdatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: label.FieldUpdatedAt,
})
_node.UpdatedAt = value
}
if value, ok := lc.mutation.Name(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: label.FieldName,
})
_node.Name = value
}
if value, ok := lc.mutation.Description(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: label.FieldDescription,
})
_node.Description = value
}
if value, ok := lc.mutation.Color(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: label.FieldColor,
})
_node.Color = value
}
if nodes := lc.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: label.GroupTable,
Columns: []string{label.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.group_labels = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := lc.mutation.ItemsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: label.ItemsTable,
Columns: label.ItemsPrimaryKey,
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 = append(_spec.Edges, edge)
}
return _node, _spec
}
// LabelCreateBulk is the builder for creating many Label entities in bulk.
type LabelCreateBulk struct {
config
builders []*LabelCreate
}
// Save creates the Label entities in the database.
func (lcb *LabelCreateBulk) Save(ctx context.Context) ([]*Label, error) {
specs := make([]*sqlgraph.CreateSpec, len(lcb.builders))
nodes := make([]*Label, len(lcb.builders))
mutators := make([]Mutator, len(lcb.builders))
for i := range lcb.builders {
func(i int, root context.Context) {
builder := lcb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*LabelMutation)
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, lcb.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, lcb.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, lcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (lcb *LabelCreateBulk) SaveX(ctx context.Context) []*Label {
v, err := lcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (lcb *LabelCreateBulk) Exec(ctx context.Context) error {
_, err := lcb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (lcb *LabelCreateBulk) ExecX(ctx context.Context) {
if err := lcb.Exec(ctx); err != nil {
panic(err)
}
}

View file

@ -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/label"
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
)
// LabelDelete is the builder for deleting a Label entity.
type LabelDelete struct {
config
hooks []Hook
mutation *LabelMutation
}
// Where appends a list predicates to the LabelDelete builder.
func (ld *LabelDelete) Where(ps ...predicate.Label) *LabelDelete {
ld.mutation.Where(ps...)
return ld
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (ld *LabelDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(ld.hooks) == 0 {
affected, err = ld.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*LabelMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
ld.mutation = mutation
affected, err = ld.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(ld.hooks) - 1; i >= 0; i-- {
if ld.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = ld.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, ld.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (ld *LabelDelete) ExecX(ctx context.Context) int {
n, err := ld.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (ld *LabelDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: label.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: label.FieldID,
},
},
}
if ps := ld.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, ld.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return affected, err
}
// LabelDeleteOne is the builder for deleting a single Label entity.
type LabelDeleteOne struct {
ld *LabelDelete
}
// Exec executes the deletion query.
func (ldo *LabelDeleteOne) Exec(ctx context.Context) error {
n, err := ldo.ld.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{label.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (ldo *LabelDeleteOne) ExecX(ctx context.Context) {
ldo.ld.ExecX(ctx)
}

View file

@ -0,0 +1,717 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"database/sql/driver"
"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/group"
"github.com/hay-kot/homebox/backend/internal/data/ent/item"
"github.com/hay-kot/homebox/backend/internal/data/ent/label"
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
)
// LabelQuery is the builder for querying Label entities.
type LabelQuery struct {
config
limit *int
offset *int
unique *bool
order []OrderFunc
fields []string
predicates []predicate.Label
withGroup *GroupQuery
withItems *ItemQuery
withFKs bool
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the LabelQuery builder.
func (lq *LabelQuery) Where(ps ...predicate.Label) *LabelQuery {
lq.predicates = append(lq.predicates, ps...)
return lq
}
// Limit adds a limit step to the query.
func (lq *LabelQuery) Limit(limit int) *LabelQuery {
lq.limit = &limit
return lq
}
// Offset adds an offset step to the query.
func (lq *LabelQuery) Offset(offset int) *LabelQuery {
lq.offset = &offset
return lq
}
// 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 (lq *LabelQuery) Unique(unique bool) *LabelQuery {
lq.unique = &unique
return lq
}
// Order adds an order step to the query.
func (lq *LabelQuery) Order(o ...OrderFunc) *LabelQuery {
lq.order = append(lq.order, o...)
return lq
}
// QueryGroup chains the current query on the "group" edge.
func (lq *LabelQuery) QueryGroup() *GroupQuery {
query := &GroupQuery{config: lq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := lq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := lq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(label.Table, label.FieldID, selector),
sqlgraph.To(group.Table, group.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, label.GroupTable, label.GroupColumn),
)
fromU = sqlgraph.SetNeighbors(lq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryItems chains the current query on the "items" edge.
func (lq *LabelQuery) QueryItems() *ItemQuery {
query := &ItemQuery{config: lq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := lq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := lq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(label.Table, label.FieldID, selector),
sqlgraph.To(item.Table, item.FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, label.ItemsTable, label.ItemsPrimaryKey...),
)
fromU = sqlgraph.SetNeighbors(lq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Label entity from the query.
// Returns a *NotFoundError when no Label was found.
func (lq *LabelQuery) First(ctx context.Context) (*Label, error) {
nodes, err := lq.Limit(1).All(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{label.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (lq *LabelQuery) FirstX(ctx context.Context) *Label {
node, err := lq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Label ID from the query.
// Returns a *NotFoundError when no Label ID was found.
func (lq *LabelQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = lq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{label.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (lq *LabelQuery) FirstIDX(ctx context.Context) uuid.UUID {
id, err := lq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Label entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Label entity is found.
// Returns a *NotFoundError when no Label entities are found.
func (lq *LabelQuery) Only(ctx context.Context) (*Label, error) {
nodes, err := lq.Limit(2).All(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{label.Label}
default:
return nil, &NotSingularError{label.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (lq *LabelQuery) OnlyX(ctx context.Context) *Label {
node, err := lq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Label ID in the query.
// Returns a *NotSingularError when more than one Label ID is found.
// Returns a *NotFoundError when no entities are found.
func (lq *LabelQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = lq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{label.Label}
default:
err = &NotSingularError{label.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (lq *LabelQuery) OnlyIDX(ctx context.Context) uuid.UUID {
id, err := lq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Labels.
func (lq *LabelQuery) All(ctx context.Context) ([]*Label, error) {
if err := lq.prepareQuery(ctx); err != nil {
return nil, err
}
return lq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (lq *LabelQuery) AllX(ctx context.Context) []*Label {
nodes, err := lq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Label IDs.
func (lq *LabelQuery) IDs(ctx context.Context) ([]uuid.UUID, error) {
var ids []uuid.UUID
if err := lq.Select(label.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (lq *LabelQuery) IDsX(ctx context.Context) []uuid.UUID {
ids, err := lq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (lq *LabelQuery) Count(ctx context.Context) (int, error) {
if err := lq.prepareQuery(ctx); err != nil {
return 0, err
}
return lq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (lq *LabelQuery) CountX(ctx context.Context) int {
count, err := lq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (lq *LabelQuery) Exist(ctx context.Context) (bool, error) {
if err := lq.prepareQuery(ctx); err != nil {
return false, err
}
return lq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (lq *LabelQuery) ExistX(ctx context.Context) bool {
exist, err := lq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the LabelQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (lq *LabelQuery) Clone() *LabelQuery {
if lq == nil {
return nil
}
return &LabelQuery{
config: lq.config,
limit: lq.limit,
offset: lq.offset,
order: append([]OrderFunc{}, lq.order...),
predicates: append([]predicate.Label{}, lq.predicates...),
withGroup: lq.withGroup.Clone(),
withItems: lq.withItems.Clone(),
// clone intermediate query.
sql: lq.sql.Clone(),
path: lq.path,
unique: lq.unique,
}
}
// WithGroup tells the query-builder to eager-load the nodes that are connected to
// the "group" edge. The optional arguments are used to configure the query builder of the edge.
func (lq *LabelQuery) WithGroup(opts ...func(*GroupQuery)) *LabelQuery {
query := &GroupQuery{config: lq.config}
for _, opt := range opts {
opt(query)
}
lq.withGroup = query
return lq
}
// WithItems tells the query-builder to eager-load the nodes that are connected to
// the "items" edge. The optional arguments are used to configure the query builder of the edge.
func (lq *LabelQuery) WithItems(opts ...func(*ItemQuery)) *LabelQuery {
query := &ItemQuery{config: lq.config}
for _, opt := range opts {
opt(query)
}
lq.withItems = query
return lq
}
// 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.Label.Query().
// GroupBy(label.FieldCreatedAt).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (lq *LabelQuery) GroupBy(field string, fields ...string) *LabelGroupBy {
grbuild := &LabelGroupBy{config: lq.config}
grbuild.fields = append([]string{field}, fields...)
grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := lq.prepareQuery(ctx); err != nil {
return nil, err
}
return lq.sqlQuery(ctx), nil
}
grbuild.label = label.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.Label.Query().
// Select(label.FieldCreatedAt).
// Scan(ctx, &v)
func (lq *LabelQuery) Select(fields ...string) *LabelSelect {
lq.fields = append(lq.fields, fields...)
selbuild := &LabelSelect{LabelQuery: lq}
selbuild.label = label.Label
selbuild.flds, selbuild.scan = &lq.fields, selbuild.Scan
return selbuild
}
func (lq *LabelQuery) prepareQuery(ctx context.Context) error {
for _, f := range lq.fields {
if !label.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if lq.path != nil {
prev, err := lq.path(ctx)
if err != nil {
return err
}
lq.sql = prev
}
return nil
}
func (lq *LabelQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Label, error) {
var (
nodes = []*Label{}
withFKs = lq.withFKs
_spec = lq.querySpec()
loadedTypes = [2]bool{
lq.withGroup != nil,
lq.withItems != nil,
}
)
if lq.withGroup != nil {
withFKs = true
}
if withFKs {
_spec.Node.Columns = append(_spec.Node.Columns, label.ForeignKeys...)
}
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Label).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Label{config: lq.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, lq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := lq.withGroup; query != nil {
if err := lq.loadGroup(ctx, query, nodes, nil,
func(n *Label, e *Group) { n.Edges.Group = e }); err != nil {
return nil, err
}
}
if query := lq.withItems; query != nil {
if err := lq.loadItems(ctx, query, nodes,
func(n *Label) { n.Edges.Items = []*Item{} },
func(n *Label, e *Item) { n.Edges.Items = append(n.Edges.Items, e) }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (lq *LabelQuery) loadGroup(ctx context.Context, query *GroupQuery, nodes []*Label, init func(*Label), assign func(*Label, *Group)) error {
ids := make([]uuid.UUID, 0, len(nodes))
nodeids := make(map[uuid.UUID][]*Label)
for i := range nodes {
if nodes[i].group_labels == nil {
continue
}
fk := *nodes[i].group_labels
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
query.Where(group.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 "group_labels" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (lq *LabelQuery) loadItems(ctx context.Context, query *ItemQuery, nodes []*Label, init func(*Label), assign func(*Label, *Item)) error {
edgeIDs := make([]driver.Value, len(nodes))
byID := make(map[uuid.UUID]*Label)
nids := make(map[uuid.UUID]map[*Label]struct{})
for i, node := range nodes {
edgeIDs[i] = node.ID
byID[node.ID] = node
if init != nil {
init(node)
}
}
query.Where(func(s *sql.Selector) {
joinT := sql.Table(label.ItemsTable)
s.Join(joinT).On(s.C(item.FieldID), joinT.C(label.ItemsPrimaryKey[1]))
s.Where(sql.InValues(joinT.C(label.ItemsPrimaryKey[0]), edgeIDs...))
columns := s.SelectedColumns()
s.Select(joinT.C(label.ItemsPrimaryKey[0]))
s.AppendSelect(columns...)
s.SetDistinct(false)
})
if err := query.prepareQuery(ctx); err != nil {
return err
}
neighbors, err := query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) {
assign := spec.Assign
values := spec.ScanValues
spec.ScanValues = func(columns []string) ([]any, error) {
values, err := values(columns[1:])
if err != nil {
return nil, err
}
return append([]any{new(uuid.UUID)}, values...), nil
}
spec.Assign = func(columns []string, values []any) error {
outValue := *values[0].(*uuid.UUID)
inValue := *values[1].(*uuid.UUID)
if nids[inValue] == nil {
nids[inValue] = map[*Label]struct{}{byID[outValue]: struct{}{}}
return assign(columns[1:], values[1:])
}
nids[inValue][byID[outValue]] = struct{}{}
return nil
}
})
if err != nil {
return err
}
for _, n := range neighbors {
nodes, ok := nids[n.ID]
if !ok {
return fmt.Errorf(`unexpected "items" node returned %v`, n.ID)
}
for kn := range nodes {
assign(kn, n)
}
}
return nil
}
func (lq *LabelQuery) sqlCount(ctx context.Context) (int, error) {
_spec := lq.querySpec()
_spec.Node.Columns = lq.fields
if len(lq.fields) > 0 {
_spec.Unique = lq.unique != nil && *lq.unique
}
return sqlgraph.CountNodes(ctx, lq.driver, _spec)
}
func (lq *LabelQuery) sqlExist(ctx context.Context) (bool, error) {
switch _, err := lq.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 (lq *LabelQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: label.Table,
Columns: label.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: label.FieldID,
},
},
From: lq.sql,
Unique: true,
}
if unique := lq.unique; unique != nil {
_spec.Unique = *unique
}
if fields := lq.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, label.FieldID)
for i := range fields {
if fields[i] != label.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := lq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := lq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := lq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := lq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (lq *LabelQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(lq.driver.Dialect())
t1 := builder.Table(label.Table)
columns := lq.fields
if len(columns) == 0 {
columns = label.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if lq.sql != nil {
selector = lq.sql
selector.Select(selector.Columns(columns...)...)
}
if lq.unique != nil && *lq.unique {
selector.Distinct()
}
for _, p := range lq.predicates {
p(selector)
}
for _, p := range lq.order {
p(selector)
}
if offset := lq.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 := lq.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// LabelGroupBy is the group-by builder for Label entities.
type LabelGroupBy 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 (lgb *LabelGroupBy) Aggregate(fns ...AggregateFunc) *LabelGroupBy {
lgb.fns = append(lgb.fns, fns...)
return lgb
}
// Scan applies the group-by query and scans the result into the given value.
func (lgb *LabelGroupBy) Scan(ctx context.Context, v any) error {
query, err := lgb.path(ctx)
if err != nil {
return err
}
lgb.sql = query
return lgb.sqlScan(ctx, v)
}
func (lgb *LabelGroupBy) sqlScan(ctx context.Context, v any) error {
for _, f := range lgb.fields {
if !label.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := lgb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := lgb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (lgb *LabelGroupBy) sqlQuery() *sql.Selector {
selector := lgb.sql.Select()
aggregation := make([]string, 0, len(lgb.fns))
for _, fn := range lgb.fns {
aggregation = append(aggregation, fn(selector))
}
// If no columns were selected in a custom aggregation function, the default
// selection is the fields used for "group-by", and the aggregation functions.
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(lgb.fields)+len(lgb.fns))
for _, f := range lgb.fields {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
return selector.GroupBy(selector.Columns(lgb.fields...)...)
}
// LabelSelect is the builder for selecting fields of Label entities.
type LabelSelect struct {
*LabelQuery
selector
// intermediate query (i.e. traversal path).
sql *sql.Selector
}
// Scan applies the selector query and scans the result into the given value.
func (ls *LabelSelect) Scan(ctx context.Context, v any) error {
if err := ls.prepareQuery(ctx); err != nil {
return err
}
ls.sql = ls.LabelQuery.sqlQuery(ctx)
return ls.sqlScan(ctx, v)
}
func (ls *LabelSelect) sqlScan(ctx context.Context, v any) error {
rows := &sql.Rows{}
query, args := ls.sql.Query()
if err := ls.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

View file

@ -0,0 +1,793 @@
// 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/group"
"github.com/hay-kot/homebox/backend/internal/data/ent/item"
"github.com/hay-kot/homebox/backend/internal/data/ent/label"
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
)
// LabelUpdate is the builder for updating Label entities.
type LabelUpdate struct {
config
hooks []Hook
mutation *LabelMutation
}
// Where appends a list predicates to the LabelUpdate builder.
func (lu *LabelUpdate) Where(ps ...predicate.Label) *LabelUpdate {
lu.mutation.Where(ps...)
return lu
}
// SetUpdatedAt sets the "updated_at" field.
func (lu *LabelUpdate) SetUpdatedAt(t time.Time) *LabelUpdate {
lu.mutation.SetUpdatedAt(t)
return lu
}
// SetName sets the "name" field.
func (lu *LabelUpdate) SetName(s string) *LabelUpdate {
lu.mutation.SetName(s)
return lu
}
// SetDescription sets the "description" field.
func (lu *LabelUpdate) SetDescription(s string) *LabelUpdate {
lu.mutation.SetDescription(s)
return lu
}
// SetNillableDescription sets the "description" field if the given value is not nil.
func (lu *LabelUpdate) SetNillableDescription(s *string) *LabelUpdate {
if s != nil {
lu.SetDescription(*s)
}
return lu
}
// ClearDescription clears the value of the "description" field.
func (lu *LabelUpdate) ClearDescription() *LabelUpdate {
lu.mutation.ClearDescription()
return lu
}
// SetColor sets the "color" field.
func (lu *LabelUpdate) SetColor(s string) *LabelUpdate {
lu.mutation.SetColor(s)
return lu
}
// SetNillableColor sets the "color" field if the given value is not nil.
func (lu *LabelUpdate) SetNillableColor(s *string) *LabelUpdate {
if s != nil {
lu.SetColor(*s)
}
return lu
}
// ClearColor clears the value of the "color" field.
func (lu *LabelUpdate) ClearColor() *LabelUpdate {
lu.mutation.ClearColor()
return lu
}
// SetGroupID sets the "group" edge to the Group entity by ID.
func (lu *LabelUpdate) SetGroupID(id uuid.UUID) *LabelUpdate {
lu.mutation.SetGroupID(id)
return lu
}
// SetGroup sets the "group" edge to the Group entity.
func (lu *LabelUpdate) SetGroup(g *Group) *LabelUpdate {
return lu.SetGroupID(g.ID)
}
// AddItemIDs adds the "items" edge to the Item entity by IDs.
func (lu *LabelUpdate) AddItemIDs(ids ...uuid.UUID) *LabelUpdate {
lu.mutation.AddItemIDs(ids...)
return lu
}
// AddItems adds the "items" edges to the Item entity.
func (lu *LabelUpdate) AddItems(i ...*Item) *LabelUpdate {
ids := make([]uuid.UUID, len(i))
for j := range i {
ids[j] = i[j].ID
}
return lu.AddItemIDs(ids...)
}
// Mutation returns the LabelMutation object of the builder.
func (lu *LabelUpdate) Mutation() *LabelMutation {
return lu.mutation
}
// ClearGroup clears the "group" edge to the Group entity.
func (lu *LabelUpdate) ClearGroup() *LabelUpdate {
lu.mutation.ClearGroup()
return lu
}
// ClearItems clears all "items" edges to the Item entity.
func (lu *LabelUpdate) ClearItems() *LabelUpdate {
lu.mutation.ClearItems()
return lu
}
// RemoveItemIDs removes the "items" edge to Item entities by IDs.
func (lu *LabelUpdate) RemoveItemIDs(ids ...uuid.UUID) *LabelUpdate {
lu.mutation.RemoveItemIDs(ids...)
return lu
}
// RemoveItems removes "items" edges to Item entities.
func (lu *LabelUpdate) RemoveItems(i ...*Item) *LabelUpdate {
ids := make([]uuid.UUID, len(i))
for j := range i {
ids[j] = i[j].ID
}
return lu.RemoveItemIDs(ids...)
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (lu *LabelUpdate) Save(ctx context.Context) (int, error) {
var (
err error
affected int
)
lu.defaults()
if len(lu.hooks) == 0 {
if err = lu.check(); err != nil {
return 0, err
}
affected, err = lu.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*LabelMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = lu.check(); err != nil {
return 0, err
}
lu.mutation = mutation
affected, err = lu.sqlSave(ctx)
mutation.done = true
return affected, err
})
for i := len(lu.hooks) - 1; i >= 0; i-- {
if lu.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = lu.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, lu.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// SaveX is like Save, but panics if an error occurs.
func (lu *LabelUpdate) SaveX(ctx context.Context) int {
affected, err := lu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (lu *LabelUpdate) Exec(ctx context.Context) error {
_, err := lu.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (lu *LabelUpdate) ExecX(ctx context.Context) {
if err := lu.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (lu *LabelUpdate) defaults() {
if _, ok := lu.mutation.UpdatedAt(); !ok {
v := label.UpdateDefaultUpdatedAt()
lu.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (lu *LabelUpdate) check() error {
if v, ok := lu.mutation.Name(); ok {
if err := label.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Label.name": %w`, err)}
}
}
if v, ok := lu.mutation.Description(); ok {
if err := label.DescriptionValidator(v); err != nil {
return &ValidationError{Name: "description", err: fmt.Errorf(`ent: validator failed for field "Label.description": %w`, err)}
}
}
if v, ok := lu.mutation.Color(); ok {
if err := label.ColorValidator(v); err != nil {
return &ValidationError{Name: "color", err: fmt.Errorf(`ent: validator failed for field "Label.color": %w`, err)}
}
}
if _, ok := lu.mutation.GroupID(); lu.mutation.GroupCleared() && !ok {
return errors.New(`ent: clearing a required unique edge "Label.group"`)
}
return nil
}
func (lu *LabelUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: label.Table,
Columns: label.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: label.FieldID,
},
},
}
if ps := lu.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := lu.mutation.UpdatedAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: label.FieldUpdatedAt,
})
}
if value, ok := lu.mutation.Name(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: label.FieldName,
})
}
if value, ok := lu.mutation.Description(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: label.FieldDescription,
})
}
if lu.mutation.DescriptionCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: label.FieldDescription,
})
}
if value, ok := lu.mutation.Color(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: label.FieldColor,
})
}
if lu.mutation.ColorCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: label.FieldColor,
})
}
if lu.mutation.GroupCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: label.GroupTable,
Columns: []string{label.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := lu.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: label.GroupTable,
Columns: []string{label.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if lu.mutation.ItemsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: label.ItemsTable,
Columns: label.ItemsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: item.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := lu.mutation.RemovedItemsIDs(); len(nodes) > 0 && !lu.mutation.ItemsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: label.ItemsTable,
Columns: label.ItemsPrimaryKey,
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.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := lu.mutation.ItemsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: label.ItemsTable,
Columns: label.ItemsPrimaryKey,
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, lu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{label.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
return n, nil
}
// LabelUpdateOne is the builder for updating a single Label entity.
type LabelUpdateOne struct {
config
fields []string
hooks []Hook
mutation *LabelMutation
}
// SetUpdatedAt sets the "updated_at" field.
func (luo *LabelUpdateOne) SetUpdatedAt(t time.Time) *LabelUpdateOne {
luo.mutation.SetUpdatedAt(t)
return luo
}
// SetName sets the "name" field.
func (luo *LabelUpdateOne) SetName(s string) *LabelUpdateOne {
luo.mutation.SetName(s)
return luo
}
// SetDescription sets the "description" field.
func (luo *LabelUpdateOne) SetDescription(s string) *LabelUpdateOne {
luo.mutation.SetDescription(s)
return luo
}
// SetNillableDescription sets the "description" field if the given value is not nil.
func (luo *LabelUpdateOne) SetNillableDescription(s *string) *LabelUpdateOne {
if s != nil {
luo.SetDescription(*s)
}
return luo
}
// ClearDescription clears the value of the "description" field.
func (luo *LabelUpdateOne) ClearDescription() *LabelUpdateOne {
luo.mutation.ClearDescription()
return luo
}
// SetColor sets the "color" field.
func (luo *LabelUpdateOne) SetColor(s string) *LabelUpdateOne {
luo.mutation.SetColor(s)
return luo
}
// SetNillableColor sets the "color" field if the given value is not nil.
func (luo *LabelUpdateOne) SetNillableColor(s *string) *LabelUpdateOne {
if s != nil {
luo.SetColor(*s)
}
return luo
}
// ClearColor clears the value of the "color" field.
func (luo *LabelUpdateOne) ClearColor() *LabelUpdateOne {
luo.mutation.ClearColor()
return luo
}
// SetGroupID sets the "group" edge to the Group entity by ID.
func (luo *LabelUpdateOne) SetGroupID(id uuid.UUID) *LabelUpdateOne {
luo.mutation.SetGroupID(id)
return luo
}
// SetGroup sets the "group" edge to the Group entity.
func (luo *LabelUpdateOne) SetGroup(g *Group) *LabelUpdateOne {
return luo.SetGroupID(g.ID)
}
// AddItemIDs adds the "items" edge to the Item entity by IDs.
func (luo *LabelUpdateOne) AddItemIDs(ids ...uuid.UUID) *LabelUpdateOne {
luo.mutation.AddItemIDs(ids...)
return luo
}
// AddItems adds the "items" edges to the Item entity.
func (luo *LabelUpdateOne) AddItems(i ...*Item) *LabelUpdateOne {
ids := make([]uuid.UUID, len(i))
for j := range i {
ids[j] = i[j].ID
}
return luo.AddItemIDs(ids...)
}
// Mutation returns the LabelMutation object of the builder.
func (luo *LabelUpdateOne) Mutation() *LabelMutation {
return luo.mutation
}
// ClearGroup clears the "group" edge to the Group entity.
func (luo *LabelUpdateOne) ClearGroup() *LabelUpdateOne {
luo.mutation.ClearGroup()
return luo
}
// ClearItems clears all "items" edges to the Item entity.
func (luo *LabelUpdateOne) ClearItems() *LabelUpdateOne {
luo.mutation.ClearItems()
return luo
}
// RemoveItemIDs removes the "items" edge to Item entities by IDs.
func (luo *LabelUpdateOne) RemoveItemIDs(ids ...uuid.UUID) *LabelUpdateOne {
luo.mutation.RemoveItemIDs(ids...)
return luo
}
// RemoveItems removes "items" edges to Item entities.
func (luo *LabelUpdateOne) RemoveItems(i ...*Item) *LabelUpdateOne {
ids := make([]uuid.UUID, len(i))
for j := range i {
ids[j] = i[j].ID
}
return luo.RemoveItemIDs(ids...)
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (luo *LabelUpdateOne) Select(field string, fields ...string) *LabelUpdateOne {
luo.fields = append([]string{field}, fields...)
return luo
}
// Save executes the query and returns the updated Label entity.
func (luo *LabelUpdateOne) Save(ctx context.Context) (*Label, error) {
var (
err error
node *Label
)
luo.defaults()
if len(luo.hooks) == 0 {
if err = luo.check(); err != nil {
return nil, err
}
node, err = luo.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*LabelMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = luo.check(); err != nil {
return nil, err
}
luo.mutation = mutation
node, err = luo.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(luo.hooks) - 1; i >= 0; i-- {
if luo.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = luo.hooks[i](mut)
}
v, err := mut.Mutate(ctx, luo.mutation)
if err != nil {
return nil, err
}
nv, ok := v.(*Label)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from LabelMutation", v)
}
node = nv
}
return node, err
}
// SaveX is like Save, but panics if an error occurs.
func (luo *LabelUpdateOne) SaveX(ctx context.Context) *Label {
node, err := luo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (luo *LabelUpdateOne) Exec(ctx context.Context) error {
_, err := luo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (luo *LabelUpdateOne) ExecX(ctx context.Context) {
if err := luo.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (luo *LabelUpdateOne) defaults() {
if _, ok := luo.mutation.UpdatedAt(); !ok {
v := label.UpdateDefaultUpdatedAt()
luo.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (luo *LabelUpdateOne) check() error {
if v, ok := luo.mutation.Name(); ok {
if err := label.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Label.name": %w`, err)}
}
}
if v, ok := luo.mutation.Description(); ok {
if err := label.DescriptionValidator(v); err != nil {
return &ValidationError{Name: "description", err: fmt.Errorf(`ent: validator failed for field "Label.description": %w`, err)}
}
}
if v, ok := luo.mutation.Color(); ok {
if err := label.ColorValidator(v); err != nil {
return &ValidationError{Name: "color", err: fmt.Errorf(`ent: validator failed for field "Label.color": %w`, err)}
}
}
if _, ok := luo.mutation.GroupID(); luo.mutation.GroupCleared() && !ok {
return errors.New(`ent: clearing a required unique edge "Label.group"`)
}
return nil
}
func (luo *LabelUpdateOne) sqlSave(ctx context.Context) (_node *Label, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: label.Table,
Columns: label.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: label.FieldID,
},
},
}
id, ok := luo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Label.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := luo.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, label.FieldID)
for _, f := range fields {
if !label.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != label.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := luo.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := luo.mutation.UpdatedAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: label.FieldUpdatedAt,
})
}
if value, ok := luo.mutation.Name(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: label.FieldName,
})
}
if value, ok := luo.mutation.Description(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: label.FieldDescription,
})
}
if luo.mutation.DescriptionCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: label.FieldDescription,
})
}
if value, ok := luo.mutation.Color(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: label.FieldColor,
})
}
if luo.mutation.ColorCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: label.FieldColor,
})
}
if luo.mutation.GroupCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: label.GroupTable,
Columns: []string{label.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := luo.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: label.GroupTable,
Columns: []string{label.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges.Add = append(_spec.Edges.Add, edge)
}
if luo.mutation.ItemsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: label.ItemsTable,
Columns: label.ItemsPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: item.FieldID,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := luo.mutation.RemovedItemsIDs(); len(nodes) > 0 && !luo.mutation.ItemsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: label.ItemsTable,
Columns: label.ItemsPrimaryKey,
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.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := luo.mutation.ItemsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: label.ItemsTable,
Columns: label.ItemsPrimaryKey,
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 = &Label{config: luo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, luo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{label.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
return _node, nil
}

View file

@ -0,0 +1,239 @@
// 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/group"
"github.com/hay-kot/homebox/backend/internal/data/ent/location"
)
// Location is the model entity for the Location schema.
type Location 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"`
// 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"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the LocationQuery when eager-loading is set.
Edges LocationEdges `json:"edges"`
group_locations *uuid.UUID
location_children *uuid.UUID
}
// LocationEdges holds the relations/edges for other nodes in the graph.
type LocationEdges struct {
// Parent holds the value of the parent edge.
Parent *Location `json:"parent,omitempty"`
// Children holds the value of the children edge.
Children []*Location `json:"children,omitempty"`
// Group holds the value of the group edge.
Group *Group `json:"group,omitempty"`
// Items holds the value of the items edge.
Items []*Item `json:"items,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [4]bool
}
// ParentOrErr returns the Parent value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e LocationEdges) ParentOrErr() (*Location, error) {
if e.loadedTypes[0] {
if e.Parent == nil {
// Edge was loaded but was not found.
return nil, &NotFoundError{label: location.Label}
}
return e.Parent, nil
}
return nil, &NotLoadedError{edge: "parent"}
}
// ChildrenOrErr returns the Children value or an error if the edge
// was not loaded in eager-loading.
func (e LocationEdges) ChildrenOrErr() ([]*Location, error) {
if e.loadedTypes[1] {
return e.Children, nil
}
return nil, &NotLoadedError{edge: "children"}
}
// GroupOrErr returns the Group value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e LocationEdges) GroupOrErr() (*Group, error) {
if e.loadedTypes[2] {
if e.Group == nil {
// Edge was loaded but was not found.
return nil, &NotFoundError{label: group.Label}
}
return e.Group, nil
}
return nil, &NotLoadedError{edge: "group"}
}
// ItemsOrErr returns the Items value or an error if the edge
// was not loaded in eager-loading.
func (e LocationEdges) ItemsOrErr() ([]*Item, error) {
if e.loadedTypes[3] {
return e.Items, nil
}
return nil, &NotLoadedError{edge: "items"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Location) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case location.FieldName, location.FieldDescription:
values[i] = new(sql.NullString)
case location.FieldCreatedAt, location.FieldUpdatedAt:
values[i] = new(sql.NullTime)
case location.FieldID:
values[i] = new(uuid.UUID)
case location.ForeignKeys[0]: // group_locations
values[i] = &sql.NullScanner{S: new(uuid.UUID)}
case location.ForeignKeys[1]: // location_children
values[i] = &sql.NullScanner{S: new(uuid.UUID)}
default:
return nil, fmt.Errorf("unexpected column %q for type Location", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Location fields.
func (l *Location) 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 location.FieldID:
if value, ok := values[i].(*uuid.UUID); !ok {
return fmt.Errorf("unexpected type %T for field id", values[i])
} else if value != nil {
l.ID = *value
}
case location.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 {
l.CreatedAt = value.Time
}
case location.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 {
l.UpdatedAt = value.Time
}
case location.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
l.Name = value.String
}
case location.FieldDescription:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field description", values[i])
} else if value.Valid {
l.Description = value.String
}
case location.ForeignKeys[0]:
if value, ok := values[i].(*sql.NullScanner); !ok {
return fmt.Errorf("unexpected type %T for field group_locations", values[i])
} else if value.Valid {
l.group_locations = new(uuid.UUID)
*l.group_locations = *value.S.(*uuid.UUID)
}
case location.ForeignKeys[1]:
if value, ok := values[i].(*sql.NullScanner); !ok {
return fmt.Errorf("unexpected type %T for field location_children", values[i])
} else if value.Valid {
l.location_children = new(uuid.UUID)
*l.location_children = *value.S.(*uuid.UUID)
}
}
}
return nil
}
// QueryParent queries the "parent" edge of the Location entity.
func (l *Location) QueryParent() *LocationQuery {
return (&LocationClient{config: l.config}).QueryParent(l)
}
// QueryChildren queries the "children" edge of the Location entity.
func (l *Location) QueryChildren() *LocationQuery {
return (&LocationClient{config: l.config}).QueryChildren(l)
}
// QueryGroup queries the "group" edge of the Location entity.
func (l *Location) QueryGroup() *GroupQuery {
return (&LocationClient{config: l.config}).QueryGroup(l)
}
// QueryItems queries the "items" edge of the Location entity.
func (l *Location) QueryItems() *ItemQuery {
return (&LocationClient{config: l.config}).QueryItems(l)
}
// Update returns a builder for updating this Location.
// Note that you need to call Location.Unwrap() before calling this method if this Location
// was returned from a transaction, and the transaction was committed or rolled back.
func (l *Location) Update() *LocationUpdateOne {
return (&LocationClient{config: l.config}).UpdateOne(l)
}
// Unwrap unwraps the Location 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 (l *Location) Unwrap() *Location {
_tx, ok := l.config.driver.(*txDriver)
if !ok {
panic("ent: Location is not a transactional entity")
}
l.config.driver = _tx.drv
return l
}
// String implements the fmt.Stringer.
func (l *Location) String() string {
var builder strings.Builder
builder.WriteString("Location(")
builder.WriteString(fmt.Sprintf("id=%v, ", l.ID))
builder.WriteString("created_at=")
builder.WriteString(l.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(l.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("name=")
builder.WriteString(l.Name)
builder.WriteString(", ")
builder.WriteString("description=")
builder.WriteString(l.Description)
builder.WriteByte(')')
return builder.String()
}
// Locations is a parsable slice of Location.
type Locations []*Location
func (l Locations) config(cfg config) {
for _i := range l {
l[_i].config = cfg
}
}

View file

@ -0,0 +1,102 @@
// Code generated by ent, DO NOT EDIT.
package location
import (
"time"
"github.com/google/uuid"
)
const (
// Label holds the string label denoting the location type in the database.
Label = "location"
// 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"
// 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"
// EdgeParent holds the string denoting the parent edge name in mutations.
EdgeParent = "parent"
// EdgeChildren holds the string denoting the children edge name in mutations.
EdgeChildren = "children"
// EdgeGroup holds the string denoting the group edge name in mutations.
EdgeGroup = "group"
// EdgeItems holds the string denoting the items edge name in mutations.
EdgeItems = "items"
// Table holds the table name of the location in the database.
Table = "locations"
// ParentTable is the table that holds the parent relation/edge.
ParentTable = "locations"
// ParentColumn is the table column denoting the parent relation/edge.
ParentColumn = "location_children"
// ChildrenTable is the table that holds the children relation/edge.
ChildrenTable = "locations"
// ChildrenColumn is the table column denoting the children relation/edge.
ChildrenColumn = "location_children"
// GroupTable is the table that holds the group relation/edge.
GroupTable = "locations"
// GroupInverseTable is the table name for the Group entity.
// It exists in this package in order to avoid circular dependency with the "group" package.
GroupInverseTable = "groups"
// GroupColumn is the table column denoting the group relation/edge.
GroupColumn = "group_locations"
// ItemsTable is the table that holds the items relation/edge.
ItemsTable = "items"
// ItemsInverseTable is the table name for the Item entity.
// It exists in this package in order to avoid circular dependency with the "item" package.
ItemsInverseTable = "items"
// ItemsColumn is the table column denoting the items relation/edge.
ItemsColumn = "location_items"
)
// Columns holds all SQL columns for location fields.
var Columns = []string{
FieldID,
FieldCreatedAt,
FieldUpdatedAt,
FieldName,
FieldDescription,
}
// ForeignKeys holds the SQL foreign-keys that are owned by the "locations"
// table and are not defined as standalone fields in the schema.
var ForeignKeys = []string{
"group_locations",
"location_children",
}
// 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
}
}
for i := range ForeignKeys {
if column == ForeignKeys[i] {
return true
}
}
return false
}
var (
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
// UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
UpdateDefaultUpdatedAt func() time.Time
// NameValidator is a validator for the "name" field. It is called by the builders before save.
NameValidator func(string) error
// DescriptionValidator is a validator for the "description" field. It is called by the builders before save.
DescriptionValidator func(string) error
// DefaultID holds the default value on creation for the "id" field.
DefaultID func() uuid.UUID
)

View file

@ -0,0 +1,595 @@
// Code generated by ent, DO NOT EDIT.
package location
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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUpdatedAt), v))
})
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.Location {
return predicate.Location(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.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldDescription), v))
})
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Location(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.Location {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Location(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.Location {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldUpdatedAt), v))
})
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Location(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.Location {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Location(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.Location {
v := make([]any, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldDescription), v))
})
}
// DescriptionIsNil applies the IsNil predicate on the "description" field.
func DescriptionIsNil() predicate.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldDescription)))
})
}
// DescriptionNotNil applies the NotNil predicate on the "description" field.
func DescriptionNotNil() predicate.Location {
return predicate.Location(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.Location {
return predicate.Location(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.Location {
return predicate.Location(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldDescription), v))
})
}
// HasParent applies the HasEdge predicate on the "parent" edge.
func HasParent() predicate.Location {
return predicate.Location(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(ParentTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, ParentTable, ParentColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasParentWith applies the HasEdge predicate on the "parent" edge with a given conditions (other predicates).
func HasParentWith(preds ...predicate.Location) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(Table, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, ParentTable, ParentColumn),
)
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasChildren applies the HasEdge predicate on the "children" edge.
func HasChildren() predicate.Location {
return predicate.Location(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(ChildrenTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, ChildrenTable, ChildrenColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasChildrenWith applies the HasEdge predicate on the "children" edge with a given conditions (other predicates).
func HasChildrenWith(preds ...predicate.Location) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(Table, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, ChildrenTable, ChildrenColumn),
)
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasGroup applies the HasEdge predicate on the "group" edge.
func HasGroup() predicate.Location {
return predicate.Location(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(GroupTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasGroupWith applies the HasEdge predicate on the "group" edge with a given conditions (other predicates).
func HasGroupWith(preds ...predicate.Group) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(GroupInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, GroupTable, GroupColumn),
)
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasItems applies the HasEdge predicate on the "items" edge.
func HasItems() predicate.Location {
return predicate.Location(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(ItemsTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, ItemsTable, ItemsColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasItemsWith applies the HasEdge predicate on the "items" edge with a given conditions (other predicates).
func HasItemsWith(preds ...predicate.Item) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(ItemsInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, ItemsTable, ItemsColumn),
)
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.Location) predicate.Location {
return predicate.Location(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.Location) predicate.Location {
return predicate.Location(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.Location) predicate.Location {
return predicate.Location(func(s *sql.Selector) {
p(s.Not())
})
}

View file

@ -0,0 +1,490 @@
// 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/group"
"github.com/hay-kot/homebox/backend/internal/data/ent/item"
"github.com/hay-kot/homebox/backend/internal/data/ent/location"
)
// LocationCreate is the builder for creating a Location entity.
type LocationCreate struct {
config
mutation *LocationMutation
hooks []Hook
}
// SetCreatedAt sets the "created_at" field.
func (lc *LocationCreate) SetCreatedAt(t time.Time) *LocationCreate {
lc.mutation.SetCreatedAt(t)
return lc
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (lc *LocationCreate) SetNillableCreatedAt(t *time.Time) *LocationCreate {
if t != nil {
lc.SetCreatedAt(*t)
}
return lc
}
// SetUpdatedAt sets the "updated_at" field.
func (lc *LocationCreate) SetUpdatedAt(t time.Time) *LocationCreate {
lc.mutation.SetUpdatedAt(t)
return lc
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (lc *LocationCreate) SetNillableUpdatedAt(t *time.Time) *LocationCreate {
if t != nil {
lc.SetUpdatedAt(*t)
}
return lc
}
// SetName sets the "name" field.
func (lc *LocationCreate) SetName(s string) *LocationCreate {
lc.mutation.SetName(s)
return lc
}
// SetDescription sets the "description" field.
func (lc *LocationCreate) SetDescription(s string) *LocationCreate {
lc.mutation.SetDescription(s)
return lc
}
// SetNillableDescription sets the "description" field if the given value is not nil.
func (lc *LocationCreate) SetNillableDescription(s *string) *LocationCreate {
if s != nil {
lc.SetDescription(*s)
}
return lc
}
// SetID sets the "id" field.
func (lc *LocationCreate) SetID(u uuid.UUID) *LocationCreate {
lc.mutation.SetID(u)
return lc
}
// SetNillableID sets the "id" field if the given value is not nil.
func (lc *LocationCreate) SetNillableID(u *uuid.UUID) *LocationCreate {
if u != nil {
lc.SetID(*u)
}
return lc
}
// SetParentID sets the "parent" edge to the Location entity by ID.
func (lc *LocationCreate) SetParentID(id uuid.UUID) *LocationCreate {
lc.mutation.SetParentID(id)
return lc
}
// SetNillableParentID sets the "parent" edge to the Location entity by ID if the given value is not nil.
func (lc *LocationCreate) SetNillableParentID(id *uuid.UUID) *LocationCreate {
if id != nil {
lc = lc.SetParentID(*id)
}
return lc
}
// SetParent sets the "parent" edge to the Location entity.
func (lc *LocationCreate) SetParent(l *Location) *LocationCreate {
return lc.SetParentID(l.ID)
}
// AddChildIDs adds the "children" edge to the Location entity by IDs.
func (lc *LocationCreate) AddChildIDs(ids ...uuid.UUID) *LocationCreate {
lc.mutation.AddChildIDs(ids...)
return lc
}
// AddChildren adds the "children" edges to the Location entity.
func (lc *LocationCreate) AddChildren(l ...*Location) *LocationCreate {
ids := make([]uuid.UUID, len(l))
for i := range l {
ids[i] = l[i].ID
}
return lc.AddChildIDs(ids...)
}
// SetGroupID sets the "group" edge to the Group entity by ID.
func (lc *LocationCreate) SetGroupID(id uuid.UUID) *LocationCreate {
lc.mutation.SetGroupID(id)
return lc
}
// SetGroup sets the "group" edge to the Group entity.
func (lc *LocationCreate) SetGroup(g *Group) *LocationCreate {
return lc.SetGroupID(g.ID)
}
// AddItemIDs adds the "items" edge to the Item entity by IDs.
func (lc *LocationCreate) AddItemIDs(ids ...uuid.UUID) *LocationCreate {
lc.mutation.AddItemIDs(ids...)
return lc
}
// AddItems adds the "items" edges to the Item entity.
func (lc *LocationCreate) AddItems(i ...*Item) *LocationCreate {
ids := make([]uuid.UUID, len(i))
for j := range i {
ids[j] = i[j].ID
}
return lc.AddItemIDs(ids...)
}
// Mutation returns the LocationMutation object of the builder.
func (lc *LocationCreate) Mutation() *LocationMutation {
return lc.mutation
}
// Save creates the Location in the database.
func (lc *LocationCreate) Save(ctx context.Context) (*Location, error) {
var (
err error
node *Location
)
lc.defaults()
if len(lc.hooks) == 0 {
if err = lc.check(); err != nil {
return nil, err
}
node, err = lc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*LocationMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = lc.check(); err != nil {
return nil, err
}
lc.mutation = mutation
if node, err = lc.sqlSave(ctx); err != nil {
return nil, err
}
mutation.id = &node.ID
mutation.done = true
return node, err
})
for i := len(lc.hooks) - 1; i >= 0; i-- {
if lc.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = lc.hooks[i](mut)
}
v, err := mut.Mutate(ctx, lc.mutation)
if err != nil {
return nil, err
}
nv, ok := v.(*Location)
if !ok {
return nil, fmt.Errorf("unexpected node type %T returned from LocationMutation", v)
}
node = nv
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (lc *LocationCreate) SaveX(ctx context.Context) *Location {
v, err := lc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (lc *LocationCreate) Exec(ctx context.Context) error {
_, err := lc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (lc *LocationCreate) ExecX(ctx context.Context) {
if err := lc.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (lc *LocationCreate) defaults() {
if _, ok := lc.mutation.CreatedAt(); !ok {
v := location.DefaultCreatedAt()
lc.mutation.SetCreatedAt(v)
}
if _, ok := lc.mutation.UpdatedAt(); !ok {
v := location.DefaultUpdatedAt()
lc.mutation.SetUpdatedAt(v)
}
if _, ok := lc.mutation.ID(); !ok {
v := location.DefaultID()
lc.mutation.SetID(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (lc *LocationCreate) check() error {
if _, ok := lc.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Location.created_at"`)}
}
if _, ok := lc.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Location.updated_at"`)}
}
if _, ok := lc.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Location.name"`)}
}
if v, ok := lc.mutation.Name(); ok {
if err := location.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Location.name": %w`, err)}
}
}
if v, ok := lc.mutation.Description(); ok {
if err := location.DescriptionValidator(v); err != nil {
return &ValidationError{Name: "description", err: fmt.Errorf(`ent: validator failed for field "Location.description": %w`, err)}
}
}
if _, ok := lc.mutation.GroupID(); !ok {
return &ValidationError{Name: "group", err: errors.New(`ent: missing required edge "Location.group"`)}
}
return nil
}
func (lc *LocationCreate) sqlSave(ctx context.Context) (*Location, error) {
_node, _spec := lc.createSpec()
if err := sqlgraph.CreateNode(ctx, lc.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 (lc *LocationCreate) createSpec() (*Location, *sqlgraph.CreateSpec) {
var (
_node = &Location{config: lc.config}
_spec = &sqlgraph.CreateSpec{
Table: location.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: location.FieldID,
},
}
)
if id, ok := lc.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = &id
}
if value, ok := lc.mutation.CreatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: location.FieldCreatedAt,
})
_node.CreatedAt = value
}
if value, ok := lc.mutation.UpdatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: location.FieldUpdatedAt,
})
_node.UpdatedAt = value
}
if value, ok := lc.mutation.Name(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: location.FieldName,
})
_node.Name = value
}
if value, ok := lc.mutation.Description(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: location.FieldDescription,
})
_node.Description = value
}
if nodes := lc.mutation.ParentIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: location.ParentTable,
Columns: []string{location.ParentColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: location.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.location_children = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := lc.mutation.ChildrenIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: location.ChildrenTable,
Columns: []string{location.ChildrenColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: location.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := lc.mutation.GroupIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: location.GroupTable,
Columns: []string{location.GroupColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: group.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.group_locations = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := lc.mutation.ItemsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: location.ItemsTable,
Columns: []string{location.ItemsColumn},
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 = append(_spec.Edges, edge)
}
return _node, _spec
}
// LocationCreateBulk is the builder for creating many Location entities in bulk.
type LocationCreateBulk struct {
config
builders []*LocationCreate
}
// Save creates the Location entities in the database.
func (lcb *LocationCreateBulk) Save(ctx context.Context) ([]*Location, error) {
specs := make([]*sqlgraph.CreateSpec, len(lcb.builders))
nodes := make([]*Location, len(lcb.builders))
mutators := make([]Mutator, len(lcb.builders))
for i := range lcb.builders {
func(i int, root context.Context) {
builder := lcb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*LocationMutation)
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, lcb.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, lcb.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, lcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (lcb *LocationCreateBulk) SaveX(ctx context.Context) []*Location {
v, err := lcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (lcb *LocationCreateBulk) Exec(ctx context.Context) error {
_, err := lcb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (lcb *LocationCreateBulk) ExecX(ctx context.Context) {
if err := lcb.Exec(ctx); err != nil {
panic(err)
}
}

View file

@ -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/location"
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
)
// LocationDelete is the builder for deleting a Location entity.
type LocationDelete struct {
config
hooks []Hook
mutation *LocationMutation
}
// Where appends a list predicates to the LocationDelete builder.
func (ld *LocationDelete) Where(ps ...predicate.Location) *LocationDelete {
ld.mutation.Where(ps...)
return ld
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (ld *LocationDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(ld.hooks) == 0 {
affected, err = ld.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*LocationMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
ld.mutation = mutation
affected, err = ld.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(ld.hooks) - 1; i >= 0; i-- {
if ld.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = ld.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, ld.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (ld *LocationDelete) ExecX(ctx context.Context) int {
n, err := ld.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (ld *LocationDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: location.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: location.FieldID,
},
},
}
if ps := ld.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, ld.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return affected, err
}
// LocationDeleteOne is the builder for deleting a single Location entity.
type LocationDeleteOne struct {
ld *LocationDelete
}
// Exec executes the deletion query.
func (ldo *LocationDeleteOne) Exec(ctx context.Context) error {
n, err := ldo.ld.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{location.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (ldo *LocationDeleteOne) ExecX(ctx context.Context) {
ldo.ld.ExecX(ctx)
}

View file

@ -0,0 +1,835 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"database/sql/driver"
"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/group"
"github.com/hay-kot/homebox/backend/internal/data/ent/item"
"github.com/hay-kot/homebox/backend/internal/data/ent/location"
"github.com/hay-kot/homebox/backend/internal/data/ent/predicate"
)
// LocationQuery is the builder for querying Location entities.
type LocationQuery struct {
config
limit *int
offset *int
unique *bool
order []OrderFunc
fields []string
predicates []predicate.Location
withParent *LocationQuery
withChildren *LocationQuery
withGroup *GroupQuery
withItems *ItemQuery
withFKs bool
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the LocationQuery builder.
func (lq *LocationQuery) Where(ps ...predicate.Location) *LocationQuery {
lq.predicates = append(lq.predicates, ps...)
return lq
}
// Limit adds a limit step to the query.
func (lq *LocationQuery) Limit(limit int) *LocationQuery {
lq.limit = &limit
return lq
}
// Offset adds an offset step to the query.
func (lq *LocationQuery) Offset(offset int) *LocationQuery {
lq.offset = &offset
return lq
}
// 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 (lq *LocationQuery) Unique(unique bool) *LocationQuery {
lq.unique = &unique
return lq
}
// Order adds an order step to the query.
func (lq *LocationQuery) Order(o ...OrderFunc) *LocationQuery {
lq.order = append(lq.order, o...)
return lq
}
// QueryParent chains the current query on the "parent" edge.
func (lq *LocationQuery) QueryParent() *LocationQuery {
query := &LocationQuery{config: lq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := lq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := lq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(location.Table, location.FieldID, selector),
sqlgraph.To(location.Table, location.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, location.ParentTable, location.ParentColumn),
)
fromU = sqlgraph.SetNeighbors(lq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryChildren chains the current query on the "children" edge.
func (lq *LocationQuery) QueryChildren() *LocationQuery {
query := &LocationQuery{config: lq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := lq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := lq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(location.Table, location.FieldID, selector),
sqlgraph.To(location.Table, location.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, location.ChildrenTable, location.ChildrenColumn),
)
fromU = sqlgraph.SetNeighbors(lq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryGroup chains the current query on the "group" edge.
func (lq *LocationQuery) QueryGroup() *GroupQuery {
query := &GroupQuery{config: lq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := lq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := lq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(location.Table, location.FieldID, selector),
sqlgraph.To(group.Table, group.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, location.GroupTable, location.GroupColumn),
)
fromU = sqlgraph.SetNeighbors(lq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryItems chains the current query on the "items" edge.
func (lq *LocationQuery) QueryItems() *ItemQuery {
query := &ItemQuery{config: lq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := lq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := lq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(location.Table, location.FieldID, selector),
sqlgraph.To(item.Table, item.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, location.ItemsTable, location.ItemsColumn),
)
fromU = sqlgraph.SetNeighbors(lq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Location entity from the query.
// Returns a *NotFoundError when no Location was found.
func (lq *LocationQuery) First(ctx context.Context) (*Location, error) {
nodes, err := lq.Limit(1).All(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{location.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (lq *LocationQuery) FirstX(ctx context.Context) *Location {
node, err := lq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Location ID from the query.
// Returns a *NotFoundError when no Location ID was found.
func (lq *LocationQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = lq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{location.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (lq *LocationQuery) FirstIDX(ctx context.Context) uuid.UUID {
id, err := lq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Location entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Location entity is found.
// Returns a *NotFoundError when no Location entities are found.
func (lq *LocationQuery) Only(ctx context.Context) (*Location, error) {
nodes, err := lq.Limit(2).All(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{location.Label}
default:
return nil, &NotSingularError{location.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (lq *LocationQuery) OnlyX(ctx context.Context) *Location {
node, err := lq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Location ID in the query.
// Returns a *NotSingularError when more than one Location ID is found.
// Returns a *NotFoundError when no entities are found.
func (lq *LocationQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) {
var ids []uuid.UUID
if ids, err = lq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{location.Label}
default:
err = &NotSingularError{location.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (lq *LocationQuery) OnlyIDX(ctx context.Context) uuid.UUID {
id, err := lq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Locations.
func (lq *LocationQuery) All(ctx context.Context) ([]*Location, error) {
if err := lq.prepareQuery(ctx); err != nil {
return nil, err
}
return lq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (lq *LocationQuery) AllX(ctx context.Context) []*Location {
nodes, err := lq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Location IDs.
func (lq *LocationQuery) IDs(ctx context.Context) ([]uuid.UUID, error) {
var ids []uuid.UUID
if err := lq.Select(location.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (lq *LocationQuery) IDsX(ctx context.Context) []uuid.UUID {
ids, err := lq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (lq *LocationQuery) Count(ctx context.Context) (int, error) {
if err := lq.prepareQuery(ctx); err != nil {
return 0, err
}
return lq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (lq *LocationQuery) CountX(ctx context.Context) int {
count, err := lq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (lq *LocationQuery) Exist(ctx context.Context) (bool, error) {
if err := lq.prepareQuery(ctx); err != nil {
return false, err
}
return lq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (lq *LocationQuery) ExistX(ctx context.Context) bool {
exist, err := lq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the LocationQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (lq *LocationQuery) Clone() *LocationQuery {
if lq == nil {
return nil
}
return &LocationQuery{
config: lq.config,
limit: lq.limit,
offset: lq.offset,
order: append([]OrderFunc{}, lq.order...),
predicates: append([]predicate.Location{}, lq.predicates...),
withParent: lq.withParent.Clone(),
withChildren: lq.withChildren.Clone(),
withGroup: lq.withGroup.Clone(),
withItems: lq.withItems.Clone(),
// clone intermediate query.
sql: lq.sql.Clone(),
path: lq.path,
unique: lq.unique,
}
}
// WithParent tells the query-builder to eager-load the nodes that are connected to
// the "parent" edge. The optional arguments are used to configure the query builder of the edge.
func (lq *LocationQuery) WithParent(opts ...func(*LocationQuery)) *LocationQuery {
query := &LocationQuery{config: lq.config}
for _, opt := range opts {
opt(query)
}
lq.withParent = query
return lq
}
// WithChildren tells the query-builder to eager-load the nodes that are connected to
// the "children" edge. The optional arguments are used to configure the query builder of the edge.
func (lq *LocationQuery) WithChildren(opts ...func(*LocationQuery)) *LocationQuery {
query := &LocationQuery{config: lq.config}
for _, opt := range opts {
opt(query)
}
lq.withChildren = query
return lq
}
// WithGroup tells the query-builder to eager-load the nodes that are connected to
// the "group" edge. The optional arguments are used to configure the query builder of the edge.
func (lq *LocationQuery) WithGroup(opts ...func(*GroupQuery)) *LocationQuery {
query := &GroupQuery{config: lq.config}
for _, opt := range opts {
opt(query)
}
lq.withGroup = query
return lq
}
// WithItems tells the query-builder to eager-load the nodes that are connected to
// the "items" edge. The optional arguments are used to configure the query builder of the edge.
func (lq *LocationQuery) WithItems(opts ...func(*ItemQuery)) *LocationQuery {
query := &ItemQuery{config: lq.config}
for _, opt := range opts {
opt(query)
}
lq.withItems = query
return lq
}
// 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.Location.Query().
// GroupBy(location.FieldCreatedAt).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (lq *LocationQuery) GroupBy(field string, fields ...string) *LocationGroupBy {
grbuild := &LocationGroupBy{config: lq.config}
grbuild.fields = append([]string{field}, fields...)
grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := lq.prepareQuery(ctx); err != nil {
return nil, err
}
return lq.sqlQuery(ctx), nil
}
grbuild.label = location.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.Location.Query().
// Select(location.FieldCreatedAt).
// Scan(ctx, &v)
func (lq *LocationQuery) Select(fields ...string) *LocationSelect {
lq.fields = append(lq.fields, fields...)
selbuild := &LocationSelect{LocationQuery: lq}
selbuild.label = location.Label
selbuild.flds, selbuild.scan = &lq.fields, selbuild.Scan
return selbuild
}
func (lq *LocationQuery) prepareQuery(ctx context.Context) error {
for _, f := range lq.fields {
if !location.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if lq.path != nil {
prev, err := lq.path(ctx)
if err != nil {
return err
}
lq.sql = prev
}
return nil
}
func (lq *LocationQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Location, error) {
var (
nodes = []*Location{}
withFKs = lq.withFKs
_spec = lq.querySpec()
loadedTypes = [4]bool{
lq.withParent != nil,
lq.withChildren != nil,
lq.withGroup != nil,
lq.withItems != nil,
}
)
if lq.withParent != nil || lq.withGroup != nil {
withFKs = true
}
if withFKs {
_spec.Node.Columns = append(_spec.Node.Columns, location.ForeignKeys...)
}
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Location).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Location{config: lq.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, lq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := lq.withParent; query != nil {
if err := lq.loadParent(ctx, query, nodes, nil,
func(n *Location, e *Location) { n.Edges.Parent = e }); err != nil {
return nil, err
}
}
if query := lq.withChildren; query != nil {
if err := lq.loadChildren(ctx, query, nodes,
func(n *Location) { n.Edges.Children = []*Location{} },
func(n *Location, e *Location) { n.Edges.Children = append(n.Edges.Children, e) }); err != nil {
return nil, err
}
}
if query := lq.withGroup; query != nil {
if err := lq.loadGroup(ctx, query, nodes, nil,
func(n *Location, e *Group) { n.Edges.Group = e }); err != nil {
return nil, err
}
}
if query := lq.withItems; query != nil {
if err := lq.loadItems(ctx, query, nodes,
func(n *Location) { n.Edges.Items = []*Item{} },
func(n *Location, e *Item) { n.Edges.Items = append(n.Edges.Items, e) }); err != nil {
return nil, err
}
}
return nodes, nil
}
func (lq *LocationQuery) loadParent(ctx context.Context, query *LocationQuery, nodes []*Location, init func(*Location), assign func(*Location, *Location)) error {
ids := make([]uuid.UUID, 0, len(nodes))
nodeids := make(map[uuid.UUID][]*Location)
for i := range nodes {
if nodes[i].location_children == nil {
continue
}
fk := *nodes[i].location_children
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
query.Where(location.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 "location_children" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (lq *LocationQuery) loadChildren(ctx context.Context, query *LocationQuery, nodes []*Location, init func(*Location), assign func(*Location, *Location)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[uuid.UUID]*Location)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
query.withFKs = true
query.Where(predicate.Location(func(s *sql.Selector) {
s.Where(sql.InValues(location.ChildrenColumn, fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.location_children
if fk == nil {
return fmt.Errorf(`foreign-key "location_children" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected foreign-key "location_children" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (lq *LocationQuery) loadGroup(ctx context.Context, query *GroupQuery, nodes []*Location, init func(*Location), assign func(*Location, *Group)) error {
ids := make([]uuid.UUID, 0, len(nodes))
nodeids := make(map[uuid.UUID][]*Location)
for i := range nodes {
if nodes[i].group_locations == nil {
continue
}
fk := *nodes[i].group_locations
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
query.Where(group.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 "group_locations" returned %v`, n.ID)
}
for i := range nodes {
assign(nodes[i], n)
}
}
return nil
}
func (lq *LocationQuery) loadItems(ctx context.Context, query *ItemQuery, nodes []*Location, init func(*Location), assign func(*Location, *Item)) error {
fks := make([]driver.Value, 0, len(nodes))
nodeids := make(map[uuid.UUID]*Location)
for i := range nodes {
fks = append(fks, nodes[i].ID)
nodeids[nodes[i].ID] = nodes[i]
if init != nil {
init(nodes[i])
}
}
query.withFKs = true
query.Where(predicate.Item(func(s *sql.Selector) {
s.Where(sql.InValues(location.ItemsColumn, fks...))
}))
neighbors, err := query.All(ctx)
if err != nil {
return err
}
for _, n := range neighbors {
fk := n.location_items
if fk == nil {
return fmt.Errorf(`foreign-key "location_items" is nil for node %v`, n.ID)
}
node, ok := nodeids[*fk]
if !ok {
return fmt.Errorf(`unexpected foreign-key "location_items" returned %v for node %v`, *fk, n.ID)
}
assign(node, n)
}
return nil
}
func (lq *LocationQuery) sqlCount(ctx context.Context) (int, error) {
_spec := lq.querySpec()
_spec.Node.Columns = lq.fields
if len(lq.fields) > 0 {
_spec.Unique = lq.unique != nil && *lq.unique
}
return sqlgraph.CountNodes(ctx, lq.driver, _spec)
}
func (lq *LocationQuery) sqlExist(ctx context.Context) (bool, error) {
switch _, err := lq.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 (lq *LocationQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: location.Table,
Columns: location.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeUUID,
Column: location.FieldID,
},
},
From: lq.sql,
Unique: true,
}
if unique := lq.unique; unique != nil {
_spec.Unique = *unique
}
if fields := lq.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, location.FieldID)
for i := range fields {
if fields[i] != location.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := lq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := lq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := lq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := lq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (lq *LocationQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(lq.driver.Dialect())
t1 := builder.Table(location.Table)
columns := lq.fields
if len(columns) == 0 {
columns = location.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if lq.sql != nil {
selector = lq.sql
selector.Select(selector.Columns(columns...)...)
}
if lq.unique != nil && *lq.unique {
selector.Distinct()
}
for _, p := range lq.predicates {
p(selector)
}
for _, p := range lq.order {
p(selector)
}
if offset := lq.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 := lq.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// LocationGroupBy is the group-by builder for Location entities.
type LocationGroupBy 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 (lgb *LocationGroupBy) Aggregate(fns ...AggregateFunc) *LocationGroupBy {
lgb.fns = append(lgb.fns, fns...)
return lgb
}
// Scan applies the group-by query and scans the result into the given value.
func (lgb *LocationGroupBy) Scan(ctx context.Context, v any) error {
query, err := lgb.path(ctx)
if err != nil {
return err
}
lgb.sql = query
return lgb.sqlScan(ctx, v)
}
func (lgb *LocationGroupBy) sqlScan(ctx context.Context, v any) error {
for _, f := range lgb.fields {
if !location.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := lgb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := lgb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (lgb *LocationGroupBy) sqlQuery() *sql.Selector {
selector := lgb.sql.Select()
aggregation := make([]string, 0, len(lgb.fns))
for _, fn := range lgb.fns {
aggregation = append(aggregation, fn(selector))
}
// If no columns were selected in a custom aggregation function, the default
// selection is the fields used for "group-by", and the aggregation functions.
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(lgb.fields)+len(lgb.fns))
for _, f := range lgb.fields {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
return selector.GroupBy(selector.Columns(lgb.fields...)...)
}
// LocationSelect is the builder for selecting fields of Location entities.
type LocationSelect struct {
*LocationQuery
selector
// intermediate query (i.e. traversal path).
sql *sql.Selector
}
// Scan applies the selector query and scans the result into the given value.
func (ls *LocationSelect) Scan(ctx context.Context, v any) error {
if err := ls.prepareQuery(ctx); err != nil {
return err
}
ls.sql = ls.LocationQuery.sqlQuery(ctx)
return ls.sqlScan(ctx, v)
}
func (ls *LocationSelect) sqlScan(ctx context.Context, v any) error {
rows := &sql.Rows{}
query, args := ls.sql.Query()
if err := ls.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,96 @@
// Code generated by ent, DO NOT EDIT.
package migrate
import (
"context"
"fmt"
"io"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql/schema"
)
var (
// WithGlobalUniqueID sets the universal ids options to the migration.
// If this option is enabled, ent migration will allocate a 1<<32 range
// for the ids of each entity (table).
// Note that this option cannot be applied on tables that already exist.
WithGlobalUniqueID = schema.WithGlobalUniqueID
// WithDropColumn sets the drop column option to the migration.
// If this option is enabled, ent migration will drop old columns
// that were used for both fields and edges. This defaults to false.
WithDropColumn = schema.WithDropColumn
// WithDropIndex sets the drop index option to the migration.
// If this option is enabled, ent migration will drop old indexes
// that were defined in the schema. This defaults to false.
// Note that unique constraints are defined using `UNIQUE INDEX`,
// and therefore, it's recommended to enable this option to get more
// flexibility in the schema changes.
WithDropIndex = schema.WithDropIndex
// WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true.
WithForeignKeys = schema.WithForeignKeys
)
// Schema is the API for creating, migrating and dropping a schema.
type Schema struct {
drv dialect.Driver
}
// NewSchema creates a new schema client.
func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} }
// Create creates all schema resources.
func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error {
return Create(ctx, s, Tables, opts...)
}
// Create creates all table resources using the given schema driver.
func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error {
migrate, err := schema.NewMigrate(s.drv, opts...)
if err != nil {
return fmt.Errorf("ent/migrate: %w", err)
}
return migrate.Create(ctx, tables...)
}
// Diff compares the state read from a database connection or migration directory with
// the state defined by the Ent schema. Changes will be written to new migration files.
func Diff(ctx context.Context, url string, opts ...schema.MigrateOption) error {
return NamedDiff(ctx, url, "changes", opts...)
}
// NamedDiff compares the state read from a database connection or migration directory with
// the state defined by the Ent schema. Changes will be written to new named migration files.
func NamedDiff(ctx context.Context, url, name string, opts ...schema.MigrateOption) error {
return schema.Diff(ctx, url, name, Tables, opts...)
}
// Diff creates a migration file containing the statements to resolve the diff
// between the Ent schema and the connected database.
func (s *Schema) Diff(ctx context.Context, opts ...schema.MigrateOption) error {
migrate, err := schema.NewMigrate(s.drv, opts...)
if err != nil {
return fmt.Errorf("ent/migrate: %w", err)
}
return migrate.Diff(ctx, Tables...)
}
// NamedDiff creates a named migration file containing the statements to resolve the diff
// between the Ent schema and the connected database.
func (s *Schema) NamedDiff(ctx context.Context, name string, opts ...schema.MigrateOption) error {
migrate, err := schema.NewMigrate(s.drv, opts...)
if err != nil {
return fmt.Errorf("ent/migrate: %w", err)
}
return migrate.NamedDiff(ctx, name, Tables...)
}
// WriteTo writes the schema changes to w instead of running them against the database.
//
// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil {
// log.Fatal(err)
// }
func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error {
return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...)
}

View file

@ -0,0 +1,407 @@
// Code generated by ent, DO NOT EDIT.
package migrate
import (
"entgo.io/ent/dialect/sql/schema"
"entgo.io/ent/schema/field"
)
var (
// AttachmentsColumns holds the columns for the "attachments" table.
AttachmentsColumns = []*schema.Column{
{Name: "id", Type: field.TypeUUID},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
{Name: "type", Type: field.TypeEnum, Enums: []string{"photo", "manual", "warranty", "attachment", "receipt"}, Default: "attachment"},
{Name: "document_attachments", Type: field.TypeUUID},
{Name: "item_attachments", Type: field.TypeUUID},
}
// AttachmentsTable holds the schema information for the "attachments" table.
AttachmentsTable = &schema.Table{
Name: "attachments",
Columns: AttachmentsColumns,
PrimaryKey: []*schema.Column{AttachmentsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "attachments_documents_attachments",
Columns: []*schema.Column{AttachmentsColumns[4]},
RefColumns: []*schema.Column{DocumentsColumns[0]},
OnDelete: schema.Cascade,
},
{
Symbol: "attachments_items_attachments",
Columns: []*schema.Column{AttachmentsColumns[5]},
RefColumns: []*schema.Column{ItemsColumns[0]},
OnDelete: schema.Cascade,
},
},
}
// AuthTokensColumns holds the columns for the "auth_tokens" table.
AuthTokensColumns = []*schema.Column{
{Name: "id", Type: field.TypeUUID},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
{Name: "token", Type: field.TypeBytes, Unique: true},
{Name: "expires_at", Type: field.TypeTime},
{Name: "user_auth_tokens", Type: field.TypeUUID, Nullable: true},
}
// AuthTokensTable holds the schema information for the "auth_tokens" table.
AuthTokensTable = &schema.Table{
Name: "auth_tokens",
Columns: AuthTokensColumns,
PrimaryKey: []*schema.Column{AuthTokensColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "auth_tokens_users_auth_tokens",
Columns: []*schema.Column{AuthTokensColumns[5]},
RefColumns: []*schema.Column{UsersColumns[0]},
OnDelete: schema.Cascade,
},
},
Indexes: []*schema.Index{
{
Name: "authtokens_token",
Unique: false,
Columns: []*schema.Column{AuthTokensColumns[3]},
},
},
}
// DocumentsColumns holds the columns for the "documents" table.
DocumentsColumns = []*schema.Column{
{Name: "id", Type: field.TypeUUID},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
{Name: "title", Type: field.TypeString, Size: 255},
{Name: "path", Type: field.TypeString, Size: 500},
{Name: "group_documents", Type: field.TypeUUID},
}
// DocumentsTable holds the schema information for the "documents" table.
DocumentsTable = &schema.Table{
Name: "documents",
Columns: DocumentsColumns,
PrimaryKey: []*schema.Column{DocumentsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "documents_groups_documents",
Columns: []*schema.Column{DocumentsColumns[5]},
RefColumns: []*schema.Column{GroupsColumns[0]},
OnDelete: schema.Cascade,
},
},
}
// DocumentTokensColumns holds the columns for the "document_tokens" table.
DocumentTokensColumns = []*schema.Column{
{Name: "id", Type: field.TypeUUID},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
{Name: "token", Type: field.TypeBytes, Unique: true},
{Name: "uses", Type: field.TypeInt, Default: 1},
{Name: "expires_at", Type: field.TypeTime},
{Name: "document_document_tokens", Type: field.TypeUUID, Nullable: true},
}
// DocumentTokensTable holds the schema information for the "document_tokens" table.
DocumentTokensTable = &schema.Table{
Name: "document_tokens",
Columns: DocumentTokensColumns,
PrimaryKey: []*schema.Column{DocumentTokensColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "document_tokens_documents_document_tokens",
Columns: []*schema.Column{DocumentTokensColumns[6]},
RefColumns: []*schema.Column{DocumentsColumns[0]},
OnDelete: schema.Cascade,
},
},
Indexes: []*schema.Index{
{
Name: "documenttoken_token",
Unique: false,
Columns: []*schema.Column{DocumentTokensColumns[3]},
},
},
}
// GroupsColumns holds the columns for the "groups" table.
GroupsColumns = []*schema.Column{
{Name: "id", Type: field.TypeUUID},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
{Name: "name", Type: field.TypeString, Size: 255},
{Name: "currency", Type: field.TypeEnum, Enums: []string{"usd", "eur", "gbp", "jpy"}, Default: "usd"},
}
// GroupsTable holds the schema information for the "groups" table.
GroupsTable = &schema.Table{
Name: "groups",
Columns: GroupsColumns,
PrimaryKey: []*schema.Column{GroupsColumns[0]},
}
// GroupInvitationTokensColumns holds the columns for the "group_invitation_tokens" table.
GroupInvitationTokensColumns = []*schema.Column{
{Name: "id", Type: field.TypeUUID},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
{Name: "token", Type: field.TypeBytes, Unique: true},
{Name: "expires_at", Type: field.TypeTime},
{Name: "uses", Type: field.TypeInt, Default: 0},
{Name: "group_invitation_tokens", Type: field.TypeUUID, Nullable: true},
}
// GroupInvitationTokensTable holds the schema information for the "group_invitation_tokens" table.
GroupInvitationTokensTable = &schema.Table{
Name: "group_invitation_tokens",
Columns: GroupInvitationTokensColumns,
PrimaryKey: []*schema.Column{GroupInvitationTokensColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "group_invitation_tokens_groups_invitation_tokens",
Columns: []*schema.Column{GroupInvitationTokensColumns[6]},
RefColumns: []*schema.Column{GroupsColumns[0]},
OnDelete: schema.Cascade,
},
},
}
// ItemsColumns holds the columns for the "items" table.
ItemsColumns = []*schema.Column{
{Name: "id", Type: field.TypeUUID},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
{Name: "name", Type: field.TypeString, Size: 255},
{Name: "description", Type: field.TypeString, Nullable: true, Size: 1000},
{Name: "import_ref", Type: field.TypeString, Nullable: true, Size: 100},
{Name: "notes", Type: field.TypeString, Nullable: true, Size: 1000},
{Name: "quantity", Type: field.TypeInt, Default: 1},
{Name: "insured", Type: field.TypeBool, Default: false},
{Name: "serial_number", Type: field.TypeString, Nullable: true, Size: 255},
{Name: "model_number", Type: field.TypeString, Nullable: true, Size: 255},
{Name: "manufacturer", Type: field.TypeString, Nullable: true, Size: 255},
{Name: "lifetime_warranty", Type: field.TypeBool, Default: false},
{Name: "warranty_expires", Type: field.TypeTime, Nullable: true},
{Name: "warranty_details", Type: field.TypeString, Nullable: true, Size: 1000},
{Name: "purchase_time", Type: field.TypeTime, Nullable: true},
{Name: "purchase_from", Type: field.TypeString, Nullable: true},
{Name: "purchase_price", Type: field.TypeFloat64, Default: 0},
{Name: "sold_time", Type: field.TypeTime, Nullable: true},
{Name: "sold_to", Type: field.TypeString, Nullable: true},
{Name: "sold_price", Type: field.TypeFloat64, Default: 0},
{Name: "sold_notes", Type: field.TypeString, Nullable: true, Size: 1000},
{Name: "group_items", Type: field.TypeUUID},
{Name: "item_children", Type: field.TypeUUID, Nullable: true},
{Name: "location_items", Type: field.TypeUUID, Nullable: true},
}
// ItemsTable holds the schema information for the "items" table.
ItemsTable = &schema.Table{
Name: "items",
Columns: ItemsColumns,
PrimaryKey: []*schema.Column{ItemsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "items_groups_items",
Columns: []*schema.Column{ItemsColumns[22]},
RefColumns: []*schema.Column{GroupsColumns[0]},
OnDelete: schema.Cascade,
},
{
Symbol: "items_items_children",
Columns: []*schema.Column{ItemsColumns[23]},
RefColumns: []*schema.Column{ItemsColumns[0]},
OnDelete: schema.SetNull,
},
{
Symbol: "items_locations_items",
Columns: []*schema.Column{ItemsColumns[24]},
RefColumns: []*schema.Column{LocationsColumns[0]},
OnDelete: schema.Cascade,
},
},
Indexes: []*schema.Index{
{
Name: "item_name",
Unique: false,
Columns: []*schema.Column{ItemsColumns[3]},
},
{
Name: "item_manufacturer",
Unique: false,
Columns: []*schema.Column{ItemsColumns[11]},
},
{
Name: "item_model_number",
Unique: false,
Columns: []*schema.Column{ItemsColumns[10]},
},
{
Name: "item_serial_number",
Unique: false,
Columns: []*schema.Column{ItemsColumns[9]},
},
},
}
// ItemFieldsColumns holds the columns for the "item_fields" table.
ItemFieldsColumns = []*schema.Column{
{Name: "id", Type: field.TypeUUID},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
{Name: "name", Type: field.TypeString, Size: 255},
{Name: "description", Type: field.TypeString, Nullable: true, Size: 1000},
{Name: "type", Type: field.TypeEnum, Enums: []string{"text", "number", "boolean", "time"}},
{Name: "text_value", Type: field.TypeString, Nullable: true, Size: 500},
{Name: "number_value", Type: field.TypeInt, Nullable: true},
{Name: "boolean_value", Type: field.TypeBool, Default: false},
{Name: "time_value", Type: field.TypeTime},
{Name: "item_fields", Type: field.TypeUUID, Nullable: true},
}
// ItemFieldsTable holds the schema information for the "item_fields" table.
ItemFieldsTable = &schema.Table{
Name: "item_fields",
Columns: ItemFieldsColumns,
PrimaryKey: []*schema.Column{ItemFieldsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "item_fields_items_fields",
Columns: []*schema.Column{ItemFieldsColumns[10]},
RefColumns: []*schema.Column{ItemsColumns[0]},
OnDelete: schema.Cascade,
},
},
}
// LabelsColumns holds the columns for the "labels" table.
LabelsColumns = []*schema.Column{
{Name: "id", Type: field.TypeUUID},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
{Name: "name", Type: field.TypeString, Size: 255},
{Name: "description", Type: field.TypeString, Nullable: true, Size: 1000},
{Name: "color", Type: field.TypeString, Nullable: true, Size: 255},
{Name: "group_labels", Type: field.TypeUUID},
}
// LabelsTable holds the schema information for the "labels" table.
LabelsTable = &schema.Table{
Name: "labels",
Columns: LabelsColumns,
PrimaryKey: []*schema.Column{LabelsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "labels_groups_labels",
Columns: []*schema.Column{LabelsColumns[6]},
RefColumns: []*schema.Column{GroupsColumns[0]},
OnDelete: schema.Cascade,
},
},
}
// LocationsColumns holds the columns for the "locations" table.
LocationsColumns = []*schema.Column{
{Name: "id", Type: field.TypeUUID},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
{Name: "name", Type: field.TypeString, Size: 255},
{Name: "description", Type: field.TypeString, Nullable: true, Size: 1000},
{Name: "group_locations", Type: field.TypeUUID},
{Name: "location_children", Type: field.TypeUUID, Nullable: true},
}
// LocationsTable holds the schema information for the "locations" table.
LocationsTable = &schema.Table{
Name: "locations",
Columns: LocationsColumns,
PrimaryKey: []*schema.Column{LocationsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "locations_groups_locations",
Columns: []*schema.Column{LocationsColumns[5]},
RefColumns: []*schema.Column{GroupsColumns[0]},
OnDelete: schema.Cascade,
},
{
Symbol: "locations_locations_children",
Columns: []*schema.Column{LocationsColumns[6]},
RefColumns: []*schema.Column{LocationsColumns[0]},
OnDelete: schema.SetNull,
},
},
}
// UsersColumns holds the columns for the "users" table.
UsersColumns = []*schema.Column{
{Name: "id", Type: field.TypeUUID},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
{Name: "name", Type: field.TypeString, Size: 255},
{Name: "email", Type: field.TypeString, Unique: true, Size: 255},
{Name: "password", Type: field.TypeString, Size: 255},
{Name: "is_superuser", Type: field.TypeBool, Default: false},
{Name: "role", Type: field.TypeEnum, Enums: []string{"user", "owner"}, Default: "user"},
{Name: "superuser", Type: field.TypeBool, Default: false},
{Name: "activated_on", Type: field.TypeTime, Nullable: true},
{Name: "group_users", Type: field.TypeUUID},
}
// UsersTable holds the schema information for the "users" table.
UsersTable = &schema.Table{
Name: "users",
Columns: UsersColumns,
PrimaryKey: []*schema.Column{UsersColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "users_groups_users",
Columns: []*schema.Column{UsersColumns[10]},
RefColumns: []*schema.Column{GroupsColumns[0]},
OnDelete: schema.Cascade,
},
},
}
// LabelItemsColumns holds the columns for the "label_items" table.
LabelItemsColumns = []*schema.Column{
{Name: "label_id", Type: field.TypeUUID},
{Name: "item_id", Type: field.TypeUUID},
}
// LabelItemsTable holds the schema information for the "label_items" table.
LabelItemsTable = &schema.Table{
Name: "label_items",
Columns: LabelItemsColumns,
PrimaryKey: []*schema.Column{LabelItemsColumns[0], LabelItemsColumns[1]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "label_items_label_id",
Columns: []*schema.Column{LabelItemsColumns[0]},
RefColumns: []*schema.Column{LabelsColumns[0]},
OnDelete: schema.Cascade,
},
{
Symbol: "label_items_item_id",
Columns: []*schema.Column{LabelItemsColumns[1]},
RefColumns: []*schema.Column{ItemsColumns[0]},
OnDelete: schema.Cascade,
},
},
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
AttachmentsTable,
AuthTokensTable,
DocumentsTable,
DocumentTokensTable,
GroupsTable,
GroupInvitationTokensTable,
ItemsTable,
ItemFieldsTable,
LabelsTable,
LocationsTable,
UsersTable,
LabelItemsTable,
}
)
func init() {
AttachmentsTable.ForeignKeys[0].RefTable = DocumentsTable
AttachmentsTable.ForeignKeys[1].RefTable = ItemsTable
AuthTokensTable.ForeignKeys[0].RefTable = UsersTable
DocumentsTable.ForeignKeys[0].RefTable = GroupsTable
DocumentTokensTable.ForeignKeys[0].RefTable = DocumentsTable
GroupInvitationTokensTable.ForeignKeys[0].RefTable = GroupsTable
ItemsTable.ForeignKeys[0].RefTable = GroupsTable
ItemsTable.ForeignKeys[1].RefTable = ItemsTable
ItemsTable.ForeignKeys[2].RefTable = LocationsTable
ItemFieldsTable.ForeignKeys[0].RefTable = ItemsTable
LabelsTable.ForeignKeys[0].RefTable = GroupsTable
LocationsTable.ForeignKeys[0].RefTable = GroupsTable
LocationsTable.ForeignKeys[1].RefTable = LocationsTable
UsersTable.ForeignKeys[0].RefTable = GroupsTable
LabelItemsTable.ForeignKeys[0].RefTable = LabelsTable
LabelItemsTable.ForeignKeys[1].RefTable = ItemsTable
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,40 @@
// Code generated by ent, DO NOT EDIT.
package predicate
import (
"entgo.io/ent/dialect/sql"
)
// Attachment is the predicate function for attachment builders.
type Attachment func(*sql.Selector)
// AuthTokens is the predicate function for authtokens builders.
type AuthTokens func(*sql.Selector)
// Document is the predicate function for document builders.
type Document func(*sql.Selector)
// DocumentToken is the predicate function for documenttoken builders.
type DocumentToken func(*sql.Selector)
// Group is the predicate function for group builders.
type Group func(*sql.Selector)
// GroupInvitationToken is the predicate function for groupinvitationtoken builders.
type GroupInvitationToken func(*sql.Selector)
// Item is the predicate function for item builders.
type Item func(*sql.Selector)
// ItemField is the predicate function for itemfield builders.
type ItemField func(*sql.Selector)
// Label is the predicate function for label builders.
type Label func(*sql.Selector)
// Location is the predicate function for location builders.
type Location func(*sql.Selector)
// User is the predicate function for user builders.
type User func(*sql.Selector)

View file

@ -0,0 +1,536 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"time"
"github.com/google/uuid"
"github.com/hay-kot/homebox/backend/internal/data/ent/attachment"
"github.com/hay-kot/homebox/backend/internal/data/ent/authtokens"
"github.com/hay-kot/homebox/backend/internal/data/ent/document"
"github.com/hay-kot/homebox/backend/internal/data/ent/documenttoken"
"github.com/hay-kot/homebox/backend/internal/data/ent/group"
"github.com/hay-kot/homebox/backend/internal/data/ent/groupinvitationtoken"
"github.com/hay-kot/homebox/backend/internal/data/ent/item"
"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/schema"
"github.com/hay-kot/homebox/backend/internal/data/ent/user"
)
// The init function reads all schema descriptors with runtime code
// (default values, validators, hooks and policies) and stitches it
// to their package variables.
func init() {
attachmentMixin := schema.Attachment{}.Mixin()
attachmentMixinFields0 := attachmentMixin[0].Fields()
_ = attachmentMixinFields0
attachmentFields := schema.Attachment{}.Fields()
_ = attachmentFields
// attachmentDescCreatedAt is the schema descriptor for created_at field.
attachmentDescCreatedAt := attachmentMixinFields0[1].Descriptor()
// attachment.DefaultCreatedAt holds the default value on creation for the created_at field.
attachment.DefaultCreatedAt = attachmentDescCreatedAt.Default.(func() time.Time)
// attachmentDescUpdatedAt is the schema descriptor for updated_at field.
attachmentDescUpdatedAt := attachmentMixinFields0[2].Descriptor()
// attachment.DefaultUpdatedAt holds the default value on creation for the updated_at field.
attachment.DefaultUpdatedAt = attachmentDescUpdatedAt.Default.(func() time.Time)
// attachment.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
attachment.UpdateDefaultUpdatedAt = attachmentDescUpdatedAt.UpdateDefault.(func() time.Time)
// attachmentDescID is the schema descriptor for id field.
attachmentDescID := attachmentMixinFields0[0].Descriptor()
// attachment.DefaultID holds the default value on creation for the id field.
attachment.DefaultID = attachmentDescID.Default.(func() uuid.UUID)
authtokensMixin := schema.AuthTokens{}.Mixin()
authtokensMixinFields0 := authtokensMixin[0].Fields()
_ = authtokensMixinFields0
authtokensFields := schema.AuthTokens{}.Fields()
_ = authtokensFields
// authtokensDescCreatedAt is the schema descriptor for created_at field.
authtokensDescCreatedAt := authtokensMixinFields0[1].Descriptor()
// authtokens.DefaultCreatedAt holds the default value on creation for the created_at field.
authtokens.DefaultCreatedAt = authtokensDescCreatedAt.Default.(func() time.Time)
// authtokensDescUpdatedAt is the schema descriptor for updated_at field.
authtokensDescUpdatedAt := authtokensMixinFields0[2].Descriptor()
// authtokens.DefaultUpdatedAt holds the default value on creation for the updated_at field.
authtokens.DefaultUpdatedAt = authtokensDescUpdatedAt.Default.(func() time.Time)
// authtokens.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
authtokens.UpdateDefaultUpdatedAt = authtokensDescUpdatedAt.UpdateDefault.(func() time.Time)
// authtokensDescExpiresAt is the schema descriptor for expires_at field.
authtokensDescExpiresAt := authtokensFields[1].Descriptor()
// authtokens.DefaultExpiresAt holds the default value on creation for the expires_at field.
authtokens.DefaultExpiresAt = authtokensDescExpiresAt.Default.(func() time.Time)
// authtokensDescID is the schema descriptor for id field.
authtokensDescID := authtokensMixinFields0[0].Descriptor()
// authtokens.DefaultID holds the default value on creation for the id field.
authtokens.DefaultID = authtokensDescID.Default.(func() uuid.UUID)
documentMixin := schema.Document{}.Mixin()
documentMixinFields0 := documentMixin[0].Fields()
_ = documentMixinFields0
documentFields := schema.Document{}.Fields()
_ = documentFields
// documentDescCreatedAt is the schema descriptor for created_at field.
documentDescCreatedAt := documentMixinFields0[1].Descriptor()
// document.DefaultCreatedAt holds the default value on creation for the created_at field.
document.DefaultCreatedAt = documentDescCreatedAt.Default.(func() time.Time)
// documentDescUpdatedAt is the schema descriptor for updated_at field.
documentDescUpdatedAt := documentMixinFields0[2].Descriptor()
// document.DefaultUpdatedAt holds the default value on creation for the updated_at field.
document.DefaultUpdatedAt = documentDescUpdatedAt.Default.(func() time.Time)
// document.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
document.UpdateDefaultUpdatedAt = documentDescUpdatedAt.UpdateDefault.(func() time.Time)
// documentDescTitle is the schema descriptor for title field.
documentDescTitle := documentFields[0].Descriptor()
// document.TitleValidator is a validator for the "title" field. It is called by the builders before save.
document.TitleValidator = func() func(string) error {
validators := documentDescTitle.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(title string) error {
for _, fn := range fns {
if err := fn(title); err != nil {
return err
}
}
return nil
}
}()
// documentDescPath is the schema descriptor for path field.
documentDescPath := documentFields[1].Descriptor()
// document.PathValidator is a validator for the "path" field. It is called by the builders before save.
document.PathValidator = func() func(string) error {
validators := documentDescPath.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(_path string) error {
for _, fn := range fns {
if err := fn(_path); err != nil {
return err
}
}
return nil
}
}()
// documentDescID is the schema descriptor for id field.
documentDescID := documentMixinFields0[0].Descriptor()
// document.DefaultID holds the default value on creation for the id field.
document.DefaultID = documentDescID.Default.(func() uuid.UUID)
documenttokenMixin := schema.DocumentToken{}.Mixin()
documenttokenMixinFields0 := documenttokenMixin[0].Fields()
_ = documenttokenMixinFields0
documenttokenFields := schema.DocumentToken{}.Fields()
_ = documenttokenFields
// documenttokenDescCreatedAt is the schema descriptor for created_at field.
documenttokenDescCreatedAt := documenttokenMixinFields0[1].Descriptor()
// documenttoken.DefaultCreatedAt holds the default value on creation for the created_at field.
documenttoken.DefaultCreatedAt = documenttokenDescCreatedAt.Default.(func() time.Time)
// documenttokenDescUpdatedAt is the schema descriptor for updated_at field.
documenttokenDescUpdatedAt := documenttokenMixinFields0[2].Descriptor()
// documenttoken.DefaultUpdatedAt holds the default value on creation for the updated_at field.
documenttoken.DefaultUpdatedAt = documenttokenDescUpdatedAt.Default.(func() time.Time)
// documenttoken.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
documenttoken.UpdateDefaultUpdatedAt = documenttokenDescUpdatedAt.UpdateDefault.(func() time.Time)
// documenttokenDescToken is the schema descriptor for token field.
documenttokenDescToken := documenttokenFields[0].Descriptor()
// documenttoken.TokenValidator is a validator for the "token" field. It is called by the builders before save.
documenttoken.TokenValidator = documenttokenDescToken.Validators[0].(func([]byte) error)
// documenttokenDescUses is the schema descriptor for uses field.
documenttokenDescUses := documenttokenFields[1].Descriptor()
// documenttoken.DefaultUses holds the default value on creation for the uses field.
documenttoken.DefaultUses = documenttokenDescUses.Default.(int)
// documenttokenDescExpiresAt is the schema descriptor for expires_at field.
documenttokenDescExpiresAt := documenttokenFields[2].Descriptor()
// documenttoken.DefaultExpiresAt holds the default value on creation for the expires_at field.
documenttoken.DefaultExpiresAt = documenttokenDescExpiresAt.Default.(func() time.Time)
// documenttokenDescID is the schema descriptor for id field.
documenttokenDescID := documenttokenMixinFields0[0].Descriptor()
// documenttoken.DefaultID holds the default value on creation for the id field.
documenttoken.DefaultID = documenttokenDescID.Default.(func() uuid.UUID)
groupMixin := schema.Group{}.Mixin()
groupMixinFields0 := groupMixin[0].Fields()
_ = groupMixinFields0
groupFields := schema.Group{}.Fields()
_ = groupFields
// groupDescCreatedAt is the schema descriptor for created_at field.
groupDescCreatedAt := groupMixinFields0[1].Descriptor()
// group.DefaultCreatedAt holds the default value on creation for the created_at field.
group.DefaultCreatedAt = groupDescCreatedAt.Default.(func() time.Time)
// groupDescUpdatedAt is the schema descriptor for updated_at field.
groupDescUpdatedAt := groupMixinFields0[2].Descriptor()
// group.DefaultUpdatedAt holds the default value on creation for the updated_at field.
group.DefaultUpdatedAt = groupDescUpdatedAt.Default.(func() time.Time)
// group.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
group.UpdateDefaultUpdatedAt = groupDescUpdatedAt.UpdateDefault.(func() time.Time)
// groupDescName is the schema descriptor for name field.
groupDescName := groupFields[0].Descriptor()
// group.NameValidator is a validator for the "name" field. It is called by the builders before save.
group.NameValidator = func() func(string) error {
validators := groupDescName.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
}
}()
// groupDescID is the schema descriptor for id field.
groupDescID := groupMixinFields0[0].Descriptor()
// group.DefaultID holds the default value on creation for the id field.
group.DefaultID = groupDescID.Default.(func() uuid.UUID)
groupinvitationtokenMixin := schema.GroupInvitationToken{}.Mixin()
groupinvitationtokenMixinFields0 := groupinvitationtokenMixin[0].Fields()
_ = groupinvitationtokenMixinFields0
groupinvitationtokenFields := schema.GroupInvitationToken{}.Fields()
_ = groupinvitationtokenFields
// groupinvitationtokenDescCreatedAt is the schema descriptor for created_at field.
groupinvitationtokenDescCreatedAt := groupinvitationtokenMixinFields0[1].Descriptor()
// groupinvitationtoken.DefaultCreatedAt holds the default value on creation for the created_at field.
groupinvitationtoken.DefaultCreatedAt = groupinvitationtokenDescCreatedAt.Default.(func() time.Time)
// groupinvitationtokenDescUpdatedAt is the schema descriptor for updated_at field.
groupinvitationtokenDescUpdatedAt := groupinvitationtokenMixinFields0[2].Descriptor()
// groupinvitationtoken.DefaultUpdatedAt holds the default value on creation for the updated_at field.
groupinvitationtoken.DefaultUpdatedAt = groupinvitationtokenDescUpdatedAt.Default.(func() time.Time)
// groupinvitationtoken.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
groupinvitationtoken.UpdateDefaultUpdatedAt = groupinvitationtokenDescUpdatedAt.UpdateDefault.(func() time.Time)
// groupinvitationtokenDescExpiresAt is the schema descriptor for expires_at field.
groupinvitationtokenDescExpiresAt := groupinvitationtokenFields[1].Descriptor()
// groupinvitationtoken.DefaultExpiresAt holds the default value on creation for the expires_at field.
groupinvitationtoken.DefaultExpiresAt = groupinvitationtokenDescExpiresAt.Default.(func() time.Time)
// groupinvitationtokenDescUses is the schema descriptor for uses field.
groupinvitationtokenDescUses := groupinvitationtokenFields[2].Descriptor()
// groupinvitationtoken.DefaultUses holds the default value on creation for the uses field.
groupinvitationtoken.DefaultUses = groupinvitationtokenDescUses.Default.(int)
// groupinvitationtokenDescID is the schema descriptor for id field.
groupinvitationtokenDescID := groupinvitationtokenMixinFields0[0].Descriptor()
// groupinvitationtoken.DefaultID holds the default value on creation for the id field.
groupinvitationtoken.DefaultID = groupinvitationtokenDescID.Default.(func() uuid.UUID)
itemMixin := schema.Item{}.Mixin()
itemMixinFields0 := itemMixin[0].Fields()
_ = itemMixinFields0
itemMixinFields1 := itemMixin[1].Fields()
_ = itemMixinFields1
itemFields := schema.Item{}.Fields()
_ = itemFields
// itemDescCreatedAt is the schema descriptor for created_at field.
itemDescCreatedAt := itemMixinFields0[1].Descriptor()
// item.DefaultCreatedAt holds the default value on creation for the created_at field.
item.DefaultCreatedAt = itemDescCreatedAt.Default.(func() time.Time)
// itemDescUpdatedAt is the schema descriptor for updated_at field.
itemDescUpdatedAt := itemMixinFields0[2].Descriptor()
// item.DefaultUpdatedAt holds the default value on creation for the updated_at field.
item.DefaultUpdatedAt = itemDescUpdatedAt.Default.(func() time.Time)
// item.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
item.UpdateDefaultUpdatedAt = itemDescUpdatedAt.UpdateDefault.(func() time.Time)
// itemDescName is the schema descriptor for name field.
itemDescName := itemMixinFields1[0].Descriptor()
// item.NameValidator is a validator for the "name" field. It is called by the builders before save.
item.NameValidator = func() func(string) error {
validators := itemDescName.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
}
}()
// itemDescDescription is the schema descriptor for description field.
itemDescDescription := itemMixinFields1[1].Descriptor()
// item.DescriptionValidator is a validator for the "description" field. It is called by the builders before save.
item.DescriptionValidator = itemDescDescription.Validators[0].(func(string) error)
// itemDescImportRef is the schema descriptor for import_ref field.
itemDescImportRef := itemFields[0].Descriptor()
// item.ImportRefValidator is a validator for the "import_ref" field. It is called by the builders before save.
item.ImportRefValidator = itemDescImportRef.Validators[0].(func(string) error)
// itemDescNotes is the schema descriptor for notes field.
itemDescNotes := itemFields[1].Descriptor()
// item.NotesValidator is a validator for the "notes" field. It is called by the builders before save.
item.NotesValidator = itemDescNotes.Validators[0].(func(string) error)
// itemDescQuantity is the schema descriptor for quantity field.
itemDescQuantity := itemFields[2].Descriptor()
// item.DefaultQuantity holds the default value on creation for the quantity field.
item.DefaultQuantity = itemDescQuantity.Default.(int)
// itemDescInsured is the schema descriptor for insured field.
itemDescInsured := itemFields[3].Descriptor()
// item.DefaultInsured holds the default value on creation for the insured field.
item.DefaultInsured = itemDescInsured.Default.(bool)
// itemDescSerialNumber is the schema descriptor for serial_number field.
itemDescSerialNumber := itemFields[4].Descriptor()
// item.SerialNumberValidator is a validator for the "serial_number" field. It is called by the builders before save.
item.SerialNumberValidator = itemDescSerialNumber.Validators[0].(func(string) error)
// itemDescModelNumber is the schema descriptor for model_number field.
itemDescModelNumber := itemFields[5].Descriptor()
// item.ModelNumberValidator is a validator for the "model_number" field. It is called by the builders before save.
item.ModelNumberValidator = itemDescModelNumber.Validators[0].(func(string) error)
// itemDescManufacturer is the schema descriptor for manufacturer field.
itemDescManufacturer := itemFields[6].Descriptor()
// item.ManufacturerValidator is a validator for the "manufacturer" field. It is called by the builders before save.
item.ManufacturerValidator = itemDescManufacturer.Validators[0].(func(string) error)
// itemDescLifetimeWarranty is the schema descriptor for lifetime_warranty field.
itemDescLifetimeWarranty := itemFields[7].Descriptor()
// item.DefaultLifetimeWarranty holds the default value on creation for the lifetime_warranty field.
item.DefaultLifetimeWarranty = itemDescLifetimeWarranty.Default.(bool)
// itemDescWarrantyDetails is the schema descriptor for warranty_details field.
itemDescWarrantyDetails := itemFields[9].Descriptor()
// item.WarrantyDetailsValidator is a validator for the "warranty_details" field. It is called by the builders before save.
item.WarrantyDetailsValidator = itemDescWarrantyDetails.Validators[0].(func(string) error)
// itemDescPurchasePrice is the schema descriptor for purchase_price field.
itemDescPurchasePrice := itemFields[12].Descriptor()
// item.DefaultPurchasePrice holds the default value on creation for the purchase_price field.
item.DefaultPurchasePrice = itemDescPurchasePrice.Default.(float64)
// itemDescSoldPrice is the schema descriptor for sold_price field.
itemDescSoldPrice := itemFields[15].Descriptor()
// item.DefaultSoldPrice holds the default value on creation for the sold_price field.
item.DefaultSoldPrice = itemDescSoldPrice.Default.(float64)
// itemDescSoldNotes is the schema descriptor for sold_notes field.
itemDescSoldNotes := itemFields[16].Descriptor()
// item.SoldNotesValidator is a validator for the "sold_notes" field. It is called by the builders before save.
item.SoldNotesValidator = itemDescSoldNotes.Validators[0].(func(string) error)
// itemDescID is the schema descriptor for id field.
itemDescID := itemMixinFields0[0].Descriptor()
// item.DefaultID holds the default value on creation for the id field.
item.DefaultID = itemDescID.Default.(func() uuid.UUID)
itemfieldMixin := schema.ItemField{}.Mixin()
itemfieldMixinFields0 := itemfieldMixin[0].Fields()
_ = itemfieldMixinFields0
itemfieldMixinFields1 := itemfieldMixin[1].Fields()
_ = itemfieldMixinFields1
itemfieldFields := schema.ItemField{}.Fields()
_ = itemfieldFields
// itemfieldDescCreatedAt is the schema descriptor for created_at field.
itemfieldDescCreatedAt := itemfieldMixinFields0[1].Descriptor()
// itemfield.DefaultCreatedAt holds the default value on creation for the created_at field.
itemfield.DefaultCreatedAt = itemfieldDescCreatedAt.Default.(func() time.Time)
// itemfieldDescUpdatedAt is the schema descriptor for updated_at field.
itemfieldDescUpdatedAt := itemfieldMixinFields0[2].Descriptor()
// itemfield.DefaultUpdatedAt holds the default value on creation for the updated_at field.
itemfield.DefaultUpdatedAt = itemfieldDescUpdatedAt.Default.(func() time.Time)
// itemfield.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
itemfield.UpdateDefaultUpdatedAt = itemfieldDescUpdatedAt.UpdateDefault.(func() time.Time)
// itemfieldDescName is the schema descriptor for name field.
itemfieldDescName := itemfieldMixinFields1[0].Descriptor()
// itemfield.NameValidator is a validator for the "name" field. It is called by the builders before save.
itemfield.NameValidator = func() func(string) error {
validators := itemfieldDescName.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
}
}()
// itemfieldDescDescription is the schema descriptor for description field.
itemfieldDescDescription := itemfieldMixinFields1[1].Descriptor()
// itemfield.DescriptionValidator is a validator for the "description" field. It is called by the builders before save.
itemfield.DescriptionValidator = itemfieldDescDescription.Validators[0].(func(string) error)
// itemfieldDescTextValue is the schema descriptor for text_value field.
itemfieldDescTextValue := itemfieldFields[1].Descriptor()
// itemfield.TextValueValidator is a validator for the "text_value" field. It is called by the builders before save.
itemfield.TextValueValidator = itemfieldDescTextValue.Validators[0].(func(string) error)
// itemfieldDescBooleanValue is the schema descriptor for boolean_value field.
itemfieldDescBooleanValue := itemfieldFields[3].Descriptor()
// itemfield.DefaultBooleanValue holds the default value on creation for the boolean_value field.
itemfield.DefaultBooleanValue = itemfieldDescBooleanValue.Default.(bool)
// itemfieldDescTimeValue is the schema descriptor for time_value field.
itemfieldDescTimeValue := itemfieldFields[4].Descriptor()
// itemfield.DefaultTimeValue holds the default value on creation for the time_value field.
itemfield.DefaultTimeValue = itemfieldDescTimeValue.Default.(func() time.Time)
// itemfieldDescID is the schema descriptor for id field.
itemfieldDescID := itemfieldMixinFields0[0].Descriptor()
// itemfield.DefaultID holds the default value on creation for the id field.
itemfield.DefaultID = itemfieldDescID.Default.(func() uuid.UUID)
labelMixin := schema.Label{}.Mixin()
labelMixinFields0 := labelMixin[0].Fields()
_ = labelMixinFields0
labelMixinFields1 := labelMixin[1].Fields()
_ = labelMixinFields1
labelFields := schema.Label{}.Fields()
_ = labelFields
// labelDescCreatedAt is the schema descriptor for created_at field.
labelDescCreatedAt := labelMixinFields0[1].Descriptor()
// label.DefaultCreatedAt holds the default value on creation for the created_at field.
label.DefaultCreatedAt = labelDescCreatedAt.Default.(func() time.Time)
// labelDescUpdatedAt is the schema descriptor for updated_at field.
labelDescUpdatedAt := labelMixinFields0[2].Descriptor()
// label.DefaultUpdatedAt holds the default value on creation for the updated_at field.
label.DefaultUpdatedAt = labelDescUpdatedAt.Default.(func() time.Time)
// label.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
label.UpdateDefaultUpdatedAt = labelDescUpdatedAt.UpdateDefault.(func() time.Time)
// labelDescName is the schema descriptor for name field.
labelDescName := labelMixinFields1[0].Descriptor()
// label.NameValidator is a validator for the "name" field. It is called by the builders before save.
label.NameValidator = func() func(string) error {
validators := labelDescName.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
}
}()
// labelDescDescription is the schema descriptor for description field.
labelDescDescription := labelMixinFields1[1].Descriptor()
// label.DescriptionValidator is a validator for the "description" field. It is called by the builders before save.
label.DescriptionValidator = labelDescDescription.Validators[0].(func(string) error)
// labelDescColor is the schema descriptor for color field.
labelDescColor := labelFields[0].Descriptor()
// label.ColorValidator is a validator for the "color" field. It is called by the builders before save.
label.ColorValidator = labelDescColor.Validators[0].(func(string) error)
// labelDescID is the schema descriptor for id field.
labelDescID := labelMixinFields0[0].Descriptor()
// label.DefaultID holds the default value on creation for the id field.
label.DefaultID = labelDescID.Default.(func() uuid.UUID)
locationMixin := schema.Location{}.Mixin()
locationMixinFields0 := locationMixin[0].Fields()
_ = locationMixinFields0
locationMixinFields1 := locationMixin[1].Fields()
_ = locationMixinFields1
locationFields := schema.Location{}.Fields()
_ = locationFields
// locationDescCreatedAt is the schema descriptor for created_at field.
locationDescCreatedAt := locationMixinFields0[1].Descriptor()
// location.DefaultCreatedAt holds the default value on creation for the created_at field.
location.DefaultCreatedAt = locationDescCreatedAt.Default.(func() time.Time)
// locationDescUpdatedAt is the schema descriptor for updated_at field.
locationDescUpdatedAt := locationMixinFields0[2].Descriptor()
// location.DefaultUpdatedAt holds the default value on creation for the updated_at field.
location.DefaultUpdatedAt = locationDescUpdatedAt.Default.(func() time.Time)
// location.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
location.UpdateDefaultUpdatedAt = locationDescUpdatedAt.UpdateDefault.(func() time.Time)
// locationDescName is the schema descriptor for name field.
locationDescName := locationMixinFields1[0].Descriptor()
// location.NameValidator is a validator for the "name" field. It is called by the builders before save.
location.NameValidator = func() func(string) error {
validators := locationDescName.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
}
}()
// locationDescDescription is the schema descriptor for description field.
locationDescDescription := locationMixinFields1[1].Descriptor()
// location.DescriptionValidator is a validator for the "description" field. It is called by the builders before save.
location.DescriptionValidator = locationDescDescription.Validators[0].(func(string) error)
// locationDescID is the schema descriptor for id field.
locationDescID := locationMixinFields0[0].Descriptor()
// location.DefaultID holds the default value on creation for the id field.
location.DefaultID = locationDescID.Default.(func() uuid.UUID)
userMixin := schema.User{}.Mixin()
userMixinFields0 := userMixin[0].Fields()
_ = userMixinFields0
userFields := schema.User{}.Fields()
_ = userFields
// userDescCreatedAt is the schema descriptor for created_at field.
userDescCreatedAt := userMixinFields0[1].Descriptor()
// user.DefaultCreatedAt holds the default value on creation for the created_at field.
user.DefaultCreatedAt = userDescCreatedAt.Default.(func() time.Time)
// userDescUpdatedAt is the schema descriptor for updated_at field.
userDescUpdatedAt := userMixinFields0[2].Descriptor()
// user.DefaultUpdatedAt holds the default value on creation for the updated_at field.
user.DefaultUpdatedAt = userDescUpdatedAt.Default.(func() time.Time)
// user.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field.
user.UpdateDefaultUpdatedAt = userDescUpdatedAt.UpdateDefault.(func() time.Time)
// userDescName is the schema descriptor for name field.
userDescName := userFields[0].Descriptor()
// user.NameValidator is a validator for the "name" field. It is called by the builders before save.
user.NameValidator = func() func(string) error {
validators := userDescName.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
}
}()
// userDescEmail is the schema descriptor for email field.
userDescEmail := userFields[1].Descriptor()
// user.EmailValidator is a validator for the "email" field. It is called by the builders before save.
user.EmailValidator = func() func(string) error {
validators := userDescEmail.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(email string) error {
for _, fn := range fns {
if err := fn(email); err != nil {
return err
}
}
return nil
}
}()
// userDescPassword is the schema descriptor for password field.
userDescPassword := userFields[2].Descriptor()
// user.PasswordValidator is a validator for the "password" field. It is called by the builders before save.
user.PasswordValidator = func() func(string) error {
validators := userDescPassword.Validators
fns := [...]func(string) error{
validators[0].(func(string) error),
validators[1].(func(string) error),
}
return func(password string) error {
for _, fn := range fns {
if err := fn(password); err != nil {
return err
}
}
return nil
}
}()
// userDescIsSuperuser is the schema descriptor for is_superuser field.
userDescIsSuperuser := userFields[3].Descriptor()
// user.DefaultIsSuperuser holds the default value on creation for the is_superuser field.
user.DefaultIsSuperuser = userDescIsSuperuser.Default.(bool)
// userDescSuperuser is the schema descriptor for superuser field.
userDescSuperuser := userFields[5].Descriptor()
// user.DefaultSuperuser holds the default value on creation for the superuser field.
user.DefaultSuperuser = userDescSuperuser.Default.(bool)
// userDescID is the schema descriptor for id field.
userDescID := userMixinFields0[0].Descriptor()
// user.DefaultID holds the default value on creation for the id field.
user.DefaultID = userDescID.Default.(func() uuid.UUID)
}

View file

@ -0,0 +1,10 @@
// Code generated by ent, DO NOT EDIT.
package runtime
// The schema-stitching logic is generated in github.com/hay-kot/homebox/backend/internal/data/ent/runtime.go
const (
Version = "v0.11.3" // Version of ent codegen.
Sum = "h1:F5FBGAWiDCGder7YT+lqMnyzXl6d0xU3xMBM/SO3CMc=" // Sum of ent codegen.
)

View file

@ -0,0 +1,42 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"github.com/hay-kot/homebox/backend/internal/data/ent/schema/mixins"
)
// Attachment holds the schema definition for the Attachment entity.
type Attachment struct {
ent.Schema
}
func (Attachment) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.BaseMixin{},
}
}
// Fields of the Attachment.
func (Attachment) Fields() []ent.Field {
return []ent.Field{
field.Enum("type").
Values("photo", "manual", "warranty", "attachment", "receipt").
Default("attachment"),
}
}
// Edges of the Attachment.
func (Attachment) Edges() []ent.Edge {
return []ent.Edge{
edge.From("item", Item.Type).
Ref("attachments").
Required().
Unique(),
edge.From("document", Document.Type).
Ref("attachments").
Required().
Unique(),
}
}

View file

@ -0,0 +1,47 @@
package schema
import (
"time"
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
"github.com/hay-kot/homebox/backend/internal/data/ent/schema/mixins"
)
// AuthTokens holds the schema definition for the AuthTokens entity.
type AuthTokens struct {
ent.Schema
}
func (AuthTokens) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.BaseMixin{},
}
}
// Fields of the AuthTokens.
func (AuthTokens) Fields() []ent.Field {
return []ent.Field{
field.Bytes("token").
Unique(),
field.Time("expires_at").
Default(func() time.Time { return time.Now().Add(time.Hour * 24 * 7) }),
}
}
// Edges of the AuthTokens.
func (AuthTokens) Edges() []ent.Edge {
return []ent.Edge{
edge.From("user", User.Type).
Ref("auth_tokens").
Unique(),
}
}
func (AuthTokens) Indexes() []ent.Index {
return []ent.Index{
index.Fields("token"),
}
}

View file

@ -0,0 +1,50 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"github.com/hay-kot/homebox/backend/internal/data/ent/schema/mixins"
)
// Document holds the schema definition for the Document entity.
type Document struct {
ent.Schema
}
func (Document) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.BaseMixin{},
}
}
// Fields of the Document.
func (Document) Fields() []ent.Field {
return []ent.Field{
field.String("title").
MaxLen(255).
NotEmpty(),
field.String("path").
MaxLen(500).
NotEmpty(),
}
}
// Edges of the Document.
func (Document) Edges() []ent.Edge {
return []ent.Edge{
edge.From("group", Group.Type).
Ref("documents").
Required().
Unique(),
edge.To("document_tokens", DocumentToken.Type).
Annotations(entsql.Annotation{
OnDelete: entsql.Cascade,
}),
edge.To("attachments", Attachment.Type).
Annotations(entsql.Annotation{
OnDelete: entsql.Cascade,
}),
}
}

View file

@ -0,0 +1,50 @@
package schema
import (
"time"
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
"github.com/hay-kot/homebox/backend/internal/data/ent/schema/mixins"
)
// DocumentToken holds the schema definition for the DocumentToken entity.
type DocumentToken struct {
ent.Schema
}
func (DocumentToken) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.BaseMixin{},
}
}
// Fields of the DocumentToken.
func (DocumentToken) Fields() []ent.Field {
return []ent.Field{
field.Bytes("token").
NotEmpty().
Unique(),
field.Int("uses").
Default(1),
field.Time("expires_at").
Default(func() time.Time { return time.Now().Add(time.Minute * 10) }),
}
}
// Edges of the DocumentToken.
func (DocumentToken) Edges() []ent.Edge {
return []ent.Edge{
edge.From("document", Document.Type).
Ref("document_tokens").
Unique(),
}
}
func (DocumentToken) Indexes() []ent.Index {
return []ent.Index{
index.Fields("token"),
}
}

View file

@ -0,0 +1,62 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"github.com/hay-kot/homebox/backend/internal/data/ent/schema/mixins"
)
// Group holds the schema definition for the Group entity.
type Group struct {
ent.Schema
}
func (Group) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.BaseMixin{},
}
}
// Fields of the Home.
func (Group) Fields() []ent.Field {
return []ent.Field{
field.String("name").
MaxLen(255).
NotEmpty(),
field.Enum("currency").
Default("usd").
Values("usd", "eur", "gbp", "jpy"), // TODO: add more currencies
}
}
// Edges of the Home.
func (Group) Edges() []ent.Edge {
return []ent.Edge{
edge.To("users", User.Type).
Annotations(entsql.Annotation{
OnDelete: entsql.Cascade,
}),
edge.To("locations", Location.Type).
Annotations(entsql.Annotation{
OnDelete: entsql.Cascade,
}),
edge.To("items", Item.Type).
Annotations(entsql.Annotation{
OnDelete: entsql.Cascade,
}),
edge.To("labels", Label.Type).
Annotations(entsql.Annotation{
OnDelete: entsql.Cascade,
}),
edge.To("documents", Document.Type).
Annotations(entsql.Annotation{
OnDelete: entsql.Cascade,
}),
edge.To("invitation_tokens", GroupInvitationToken.Type).
Annotations(entsql.Annotation{
OnDelete: entsql.Cascade,
}),
}
}

View file

@ -0,0 +1,42 @@
package schema
import (
"time"
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"github.com/hay-kot/homebox/backend/internal/data/ent/schema/mixins"
)
// GroupInvitationToken holds the schema definition for the GroupInvitationToken entity.
type GroupInvitationToken struct {
ent.Schema
}
func (GroupInvitationToken) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.BaseMixin{},
}
}
// Fields of the GroupInvitationToken.
func (GroupInvitationToken) Fields() []ent.Field {
return []ent.Field{
field.Bytes("token").
Unique(),
field.Time("expires_at").
Default(func() time.Time { return time.Now().Add(time.Hour * 24 * 7) }),
field.Int("uses").
Default(0),
}
}
// Edges of the GroupInvitationToken.
func (GroupInvitationToken) Edges() []ent.Edge {
return []ent.Edge{
edge.From("group", Group.Type).
Ref("invitation_tokens").
Unique(),
}
}

View file

@ -0,0 +1,118 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
"github.com/hay-kot/homebox/backend/internal/data/ent/schema/mixins"
)
// Item holds the schema definition for the Item entity.
type Item struct {
ent.Schema
}
func (Item) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.BaseMixin{},
mixins.DetailsMixin{},
}
}
func (Item) Indexes() []ent.Index {
return []ent.Index{
// Unique index on the "title" field.
index.Fields("name"),
index.Fields("manufacturer"),
index.Fields("model_number"),
index.Fields("serial_number"),
}
}
// Fields of the Item.
func (Item) Fields() []ent.Field {
return []ent.Field{
field.String("import_ref").
Optional().
MaxLen(100).
Immutable(),
field.String("notes").
MaxLen(1000).
Optional(),
field.Int("quantity").
Default(1),
field.Bool("insured").
Default(false),
// ------------------------------------
// item identification
field.String("serial_number").
MaxLen(255).
Optional(),
field.String("model_number").
MaxLen(255).
Optional(),
field.String("manufacturer").
MaxLen(255).
Optional(),
// ------------------------------------
// Item Warranty
field.Bool("lifetime_warranty").
Default(false),
field.Time("warranty_expires").
Optional(),
field.Text("warranty_details").
MaxLen(1000).
Optional(),
// ------------------------------------
// item purchase
field.Time("purchase_time").
Optional(),
field.String("purchase_from").
Optional(),
field.Float("purchase_price").
Default(0),
// ------------------------------------
// Sold Details
field.Time("sold_time").
Optional(),
field.String("sold_to").
Optional(),
field.Float("sold_price").
Default(0),
field.String("sold_notes").
MaxLen(1000).
Optional(),
}
}
// Edges of the Item.
func (Item) Edges() []ent.Edge {
return []ent.Edge{
edge.To("children", Item.Type).
From("parent").
Unique(),
edge.From("group", Group.Type).
Ref("items").
Required().
Unique(),
edge.From("label", Label.Type).
Ref("items"),
edge.From("location", Location.Type).
Ref("items").
Unique(),
edge.To("fields", ItemField.Type).
Annotations(entsql.Annotation{
OnDelete: entsql.Cascade,
}),
edge.To("attachments", Attachment.Type).
Annotations(entsql.Annotation{
OnDelete: entsql.Cascade,
}),
}
}

View file

@ -0,0 +1,48 @@
package schema
import (
"time"
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"github.com/hay-kot/homebox/backend/internal/data/ent/schema/mixins"
)
// ItemField holds the schema definition for the ItemField entity.
type ItemField struct {
ent.Schema
}
func (ItemField) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.BaseMixin{},
mixins.DetailsMixin{},
}
}
// Fields of the ItemField.
func (ItemField) Fields() []ent.Field {
return []ent.Field{
field.Enum("type").
Values("text", "number", "boolean", "time"),
field.String("text_value").
MaxLen(500).
Optional(),
field.Int("number_value").
Optional(),
field.Bool("boolean_value").
Default(false),
field.Time("time_value").
Default(time.Now),
}
}
// Edges of the ItemField.
func (ItemField) Edges() []ent.Edge {
return []ent.Edge{
edge.From("item", Item.Type).
Ref("fields").
Unique(),
}
}

View file

@ -0,0 +1,40 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"github.com/hay-kot/homebox/backend/internal/data/ent/schema/mixins"
)
// Label holds the schema definition for the Label entity.
type Label struct {
ent.Schema
}
func (Label) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.BaseMixin{},
mixins.DetailsMixin{},
}
}
// Fields of the Label.
func (Label) Fields() []ent.Field {
return []ent.Field{
field.String("color").
MaxLen(255).
Optional(),
}
}
// Edges of the Label.
func (Label) Edges() []ent.Edge {
return []ent.Edge{
edge.From("group", Group.Type).
Ref("labels").
Required().
Unique(),
edge.To("items", Item.Type),
}
}

View file

@ -0,0 +1,42 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema/edge"
"github.com/hay-kot/homebox/backend/internal/data/ent/schema/mixins"
)
// Location holds the schema definition for the Location entity.
type Location struct {
ent.Schema
}
func (Location) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.BaseMixin{},
mixins.DetailsMixin{},
}
}
// Fields of the Location.
func (Location) Fields() []ent.Field {
return nil
}
// Edges of the Location.
func (Location) Edges() []ent.Edge {
return []ent.Edge{
edge.To("children", Location.Type).
From("parent").
Unique(),
edge.From("group", Group.Type).
Ref("locations").
Unique().
Required(),
edge.To("items", Item.Type).
Annotations(entsql.Annotation{
OnDelete: entsql.Cascade,
}),
}
}

View file

@ -0,0 +1,42 @@
package mixins
import (
"time"
"entgo.io/ent"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/mixin"
"github.com/google/uuid"
)
type BaseMixin struct {
mixin.Schema
}
func (BaseMixin) Fields() []ent.Field {
return []ent.Field{
field.UUID("id", uuid.UUID{}).
Default(uuid.New),
field.Time("created_at").
Immutable().
Default(time.Now),
field.Time("updated_at").
Default(time.Now).
UpdateDefault(time.Now),
}
}
type DetailsMixin struct {
mixin.Schema
}
func (DetailsMixin) Fields() []ent.Field {
return []ent.Field{
field.String("name").
MaxLen(255).
NotEmpty(),
field.String("description").
MaxLen(1000).
Optional(),
}
}

View file

@ -0,0 +1,18 @@
{{/* The line below tells Intellij/GoLand to enable the autocompletion based on the *gen.Graph type. */}}
{{/* gotype: entgo.io/ent/entc/gen.Graph */}}
{{ define "has_id" }}
{{/* Add the base header for the generated file */}}
{{ $pkg := base $.Config.Package }}
{{ template "header" $ }}
import "github.com/google/uuid"
{{/* Loop over all nodes and implement the "HasID" interface */}}
{{ range $n := $.Nodes }}
{{ $receiver := $n.Receiver }}
func ({{ $receiver }} *{{ $n.Name }}) GetID() uuid.UUID {
return {{ $receiver }}.ID
}
{{ end }}
{{ end }}

View file

@ -0,0 +1,60 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/dialect/entsql"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"github.com/hay-kot/homebox/backend/internal/data/ent/schema/mixins"
)
// User holds the schema definition for the User entity.
type User struct {
ent.Schema
}
func (User) Mixin() []ent.Mixin {
return []ent.Mixin{
mixins.BaseMixin{},
}
}
// Fields of the User.
func (User) Fields() []ent.Field {
return []ent.Field{
field.String("name").
MaxLen(255).
NotEmpty(),
field.String("email").
MaxLen(255).
NotEmpty().
Unique(),
field.String("password").
MaxLen(255).
NotEmpty().
Sensitive(),
field.Bool("is_superuser").
Default(false),
field.Enum("role").
Default("user").
Values("user", "owner"),
field.Bool("superuser").
Default(false),
field.Time("activated_on").
Optional(),
}
}
// Edges of the User.
func (User) Edges() []ent.Edge {
return []ent.Edge{
edge.From("group", Group.Type).
Ref("users").
Required().
Unique(),
edge.To("auth_tokens", AuthTokens.Type).
Annotations(entsql.Annotation{
OnDelete: entsql.Cascade,
}),
}
}

View file

@ -0,0 +1,240 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"sync"
"entgo.io/ent/dialect"
)
// Tx is a transactional client that is created by calling Client.Tx().
type Tx struct {
config
// Attachment is the client for interacting with the Attachment builders.
Attachment *AttachmentClient
// AuthTokens is the client for interacting with the AuthTokens builders.
AuthTokens *AuthTokensClient
// Document is the client for interacting with the Document builders.
Document *DocumentClient
// DocumentToken is the client for interacting with the DocumentToken builders.
DocumentToken *DocumentTokenClient
// Group is the client for interacting with the Group builders.
Group *GroupClient
// GroupInvitationToken is the client for interacting with the GroupInvitationToken builders.
GroupInvitationToken *GroupInvitationTokenClient
// Item is the client for interacting with the Item builders.
Item *ItemClient
// ItemField is the client for interacting with the ItemField builders.
ItemField *ItemFieldClient
// Label is the client for interacting with the Label builders.
Label *LabelClient
// Location is the client for interacting with the Location builders.
Location *LocationClient
// User is the client for interacting with the User builders.
User *UserClient
// lazily loaded.
client *Client
clientOnce sync.Once
// completion callbacks.
mu sync.Mutex
onCommit []CommitHook
onRollback []RollbackHook
// ctx lives for the life of the transaction. It is
// the same context used by the underlying connection.
ctx context.Context
}
type (
// Committer is the interface that wraps the Commit method.
Committer interface {
Commit(context.Context, *Tx) error
}
// The CommitFunc type is an adapter to allow the use of ordinary
// function as a Committer. If f is a function with the appropriate
// signature, CommitFunc(f) is a Committer that calls f.
CommitFunc func(context.Context, *Tx) error
// CommitHook defines the "commit middleware". A function that gets a Committer
// and returns a Committer. For example:
//
// hook := func(next ent.Committer) ent.Committer {
// return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error {
// // Do some stuff before.
// if err := next.Commit(ctx, tx); err != nil {
// return err
// }
// // Do some stuff after.
// return nil
// })
// }
//
CommitHook func(Committer) Committer
)
// Commit calls f(ctx, m).
func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error {
return f(ctx, tx)
}
// Commit commits the transaction.
func (tx *Tx) Commit() error {
txDriver := tx.config.driver.(*txDriver)
var fn Committer = CommitFunc(func(context.Context, *Tx) error {
return txDriver.tx.Commit()
})
tx.mu.Lock()
hooks := append([]CommitHook(nil), tx.onCommit...)
tx.mu.Unlock()
for i := len(hooks) - 1; i >= 0; i-- {
fn = hooks[i](fn)
}
return fn.Commit(tx.ctx, tx)
}
// OnCommit adds a hook to call on commit.
func (tx *Tx) OnCommit(f CommitHook) {
tx.mu.Lock()
defer tx.mu.Unlock()
tx.onCommit = append(tx.onCommit, f)
}
type (
// Rollbacker is the interface that wraps the Rollback method.
Rollbacker interface {
Rollback(context.Context, *Tx) error
}
// The RollbackFunc type is an adapter to allow the use of ordinary
// function as a Rollbacker. If f is a function with the appropriate
// signature, RollbackFunc(f) is a Rollbacker that calls f.
RollbackFunc func(context.Context, *Tx) error
// RollbackHook defines the "rollback middleware". A function that gets a Rollbacker
// and returns a Rollbacker. For example:
//
// hook := func(next ent.Rollbacker) ent.Rollbacker {
// return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error {
// // Do some stuff before.
// if err := next.Rollback(ctx, tx); err != nil {
// return err
// }
// // Do some stuff after.
// return nil
// })
// }
//
RollbackHook func(Rollbacker) Rollbacker
)
// Rollback calls f(ctx, m).
func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error {
return f(ctx, tx)
}
// Rollback rollbacks the transaction.
func (tx *Tx) Rollback() error {
txDriver := tx.config.driver.(*txDriver)
var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error {
return txDriver.tx.Rollback()
})
tx.mu.Lock()
hooks := append([]RollbackHook(nil), tx.onRollback...)
tx.mu.Unlock()
for i := len(hooks) - 1; i >= 0; i-- {
fn = hooks[i](fn)
}
return fn.Rollback(tx.ctx, tx)
}
// OnRollback adds a hook to call on rollback.
func (tx *Tx) OnRollback(f RollbackHook) {
tx.mu.Lock()
defer tx.mu.Unlock()
tx.onRollback = append(tx.onRollback, f)
}
// Client returns a Client that binds to current transaction.
func (tx *Tx) Client() *Client {
tx.clientOnce.Do(func() {
tx.client = &Client{config: tx.config}
tx.client.init()
})
return tx.client
}
func (tx *Tx) init() {
tx.Attachment = NewAttachmentClient(tx.config)
tx.AuthTokens = NewAuthTokensClient(tx.config)
tx.Document = NewDocumentClient(tx.config)
tx.DocumentToken = NewDocumentTokenClient(tx.config)
tx.Group = NewGroupClient(tx.config)
tx.GroupInvitationToken = NewGroupInvitationTokenClient(tx.config)
tx.Item = NewItemClient(tx.config)
tx.ItemField = NewItemFieldClient(tx.config)
tx.Label = NewLabelClient(tx.config)
tx.Location = NewLocationClient(tx.config)
tx.User = NewUserClient(tx.config)
}
// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation.
// The idea is to support transactions without adding any extra code to the builders.
// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance.
// Commit and Rollback are nop for the internal builders and the user must call one
// of them in order to commit or rollback the transaction.
//
// If a closed transaction is embedded in one of the generated entities, and the entity
// applies a query, for example: Attachment.QueryXXX(), the query will be executed
// through the driver which created this transaction.
//
// Note that txDriver is not goroutine safe.
type txDriver struct {
// the driver we started the transaction from.
drv dialect.Driver
// tx is the underlying transaction.
tx dialect.Tx
}
// newTx creates a new transactional driver.
func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) {
tx, err := drv.Tx(ctx)
if err != nil {
return nil, err
}
return &txDriver{tx: tx, drv: drv}, nil
}
// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls
// from the internal builders. Should be called only by the internal builders.
func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil }
// Dialect returns the dialect of the driver we started the transaction from.
func (tx *txDriver) Dialect() string { return tx.drv.Dialect() }
// Close is a nop close.
func (*txDriver) Close() error { return nil }
// Commit is a nop commit for the internal builders.
// User must call `Tx.Commit` in order to commit the transaction.
func (*txDriver) Commit() error { return nil }
// Rollback is a nop rollback for the internal builders.
// User must call `Tx.Rollback` in order to rollback the transaction.
func (*txDriver) Rollback() error { return nil }
// Exec calls tx.Exec.
func (tx *txDriver) Exec(ctx context.Context, query string, args, v any) error {
return tx.tx.Exec(ctx, query, args, v)
}
// Query calls tx.Query.
func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error {
return tx.tx.Query(ctx, query, args, v)
}
var _ dialect.Driver = (*txDriver)(nil)

View file

@ -0,0 +1,249 @@
// 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/group"
"github.com/hay-kot/homebox/backend/internal/data/ent/user"
)
// User is the model entity for the User schema.
type User 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"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// Email holds the value of the "email" field.
Email string `json:"email,omitempty"`
// Password holds the value of the "password" field.
Password string `json:"-"`
// IsSuperuser holds the value of the "is_superuser" field.
IsSuperuser bool `json:"is_superuser,omitempty"`
// Role holds the value of the "role" field.
Role user.Role `json:"role,omitempty"`
// Superuser holds the value of the "superuser" field.
Superuser bool `json:"superuser,omitempty"`
// ActivatedOn holds the value of the "activated_on" field.
ActivatedOn time.Time `json:"activated_on,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the UserQuery when eager-loading is set.
Edges UserEdges `json:"edges"`
group_users *uuid.UUID
}
// UserEdges holds the relations/edges for other nodes in the graph.
type UserEdges struct {
// Group holds the value of the group edge.
Group *Group `json:"group,omitempty"`
// AuthTokens holds the value of the auth_tokens edge.
AuthTokens []*AuthTokens `json:"auth_tokens,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
}
// GroupOrErr returns the Group value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e UserEdges) GroupOrErr() (*Group, error) {
if e.loadedTypes[0] {
if e.Group == nil {
// Edge was loaded but was not found.
return nil, &NotFoundError{label: group.Label}
}
return e.Group, nil
}
return nil, &NotLoadedError{edge: "group"}
}
// AuthTokensOrErr returns the AuthTokens value or an error if the edge
// was not loaded in eager-loading.
func (e UserEdges) AuthTokensOrErr() ([]*AuthTokens, error) {
if e.loadedTypes[1] {
return e.AuthTokens, nil
}
return nil, &NotLoadedError{edge: "auth_tokens"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*User) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case user.FieldIsSuperuser, user.FieldSuperuser:
values[i] = new(sql.NullBool)
case user.FieldName, user.FieldEmail, user.FieldPassword, user.FieldRole:
values[i] = new(sql.NullString)
case user.FieldCreatedAt, user.FieldUpdatedAt, user.FieldActivatedOn:
values[i] = new(sql.NullTime)
case user.FieldID:
values[i] = new(uuid.UUID)
case user.ForeignKeys[0]: // group_users
values[i] = &sql.NullScanner{S: new(uuid.UUID)}
default:
return nil, fmt.Errorf("unexpected column %q for type User", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the User fields.
func (u *User) 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 user.FieldID:
if value, ok := values[i].(*uuid.UUID); !ok {
return fmt.Errorf("unexpected type %T for field id", values[i])
} else if value != nil {
u.ID = *value
}
case user.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 {
u.CreatedAt = value.Time
}
case user.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 {
u.UpdatedAt = value.Time
}
case user.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
u.Name = value.String
}
case user.FieldEmail:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field email", values[i])
} else if value.Valid {
u.Email = value.String
}
case user.FieldPassword:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field password", values[i])
} else if value.Valid {
u.Password = value.String
}
case user.FieldIsSuperuser:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field is_superuser", values[i])
} else if value.Valid {
u.IsSuperuser = value.Bool
}
case user.FieldRole:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field role", values[i])
} else if value.Valid {
u.Role = user.Role(value.String)
}
case user.FieldSuperuser:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field superuser", values[i])
} else if value.Valid {
u.Superuser = value.Bool
}
case user.FieldActivatedOn:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field activated_on", values[i])
} else if value.Valid {
u.ActivatedOn = value.Time
}
case user.ForeignKeys[0]:
if value, ok := values[i].(*sql.NullScanner); !ok {
return fmt.Errorf("unexpected type %T for field group_users", values[i])
} else if value.Valid {
u.group_users = new(uuid.UUID)
*u.group_users = *value.S.(*uuid.UUID)
}
}
}
return nil
}
// QueryGroup queries the "group" edge of the User entity.
func (u *User) QueryGroup() *GroupQuery {
return (&UserClient{config: u.config}).QueryGroup(u)
}
// QueryAuthTokens queries the "auth_tokens" edge of the User entity.
func (u *User) QueryAuthTokens() *AuthTokensQuery {
return (&UserClient{config: u.config}).QueryAuthTokens(u)
}
// Update returns a builder for updating this User.
// Note that you need to call User.Unwrap() before calling this method if this User
// was returned from a transaction, and the transaction was committed or rolled back.
func (u *User) Update() *UserUpdateOne {
return (&UserClient{config: u.config}).UpdateOne(u)
}
// Unwrap unwraps the User 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 (u *User) Unwrap() *User {
_tx, ok := u.config.driver.(*txDriver)
if !ok {
panic("ent: User is not a transactional entity")
}
u.config.driver = _tx.drv
return u
}
// String implements the fmt.Stringer.
func (u *User) String() string {
var builder strings.Builder
builder.WriteString("User(")
builder.WriteString(fmt.Sprintf("id=%v, ", u.ID))
builder.WriteString("created_at=")
builder.WriteString(u.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(u.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("name=")
builder.WriteString(u.Name)
builder.WriteString(", ")
builder.WriteString("email=")
builder.WriteString(u.Email)
builder.WriteString(", ")
builder.WriteString("password=<sensitive>")
builder.WriteString(", ")
builder.WriteString("is_superuser=")
builder.WriteString(fmt.Sprintf("%v", u.IsSuperuser))
builder.WriteString(", ")
builder.WriteString("role=")
builder.WriteString(fmt.Sprintf("%v", u.Role))
builder.WriteString(", ")
builder.WriteString("superuser=")
builder.WriteString(fmt.Sprintf("%v", u.Superuser))
builder.WriteString(", ")
builder.WriteString("activated_on=")
builder.WriteString(u.ActivatedOn.Format(time.ANSIC))
builder.WriteByte(')')
return builder.String()
}
// Users is a parsable slice of User.
type Users []*User
func (u Users) config(cfg config) {
for _i := range u {
u[_i].config = cfg
}
}

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