(wip) init token APIs

This commit is contained in:
Hayden 2022-10-01 14:02:14 -08:00
parent c4916ea762
commit 245591cb23
37 changed files with 4286 additions and 131 deletions

View file

@ -21,6 +21,41 @@ const docTemplate = `{
"host": "{{.Host}}", "host": "{{.Host}}",
"basePath": "{{.BasePath}}", "basePath": "{{.BasePath}}",
"paths": { "paths": {
"/v1/groups/invitations": {
"post": {
"security": [
{
"Bearer": []
}
],
"produces": [
"application/json"
],
"tags": [
"User"
],
"summary": "Get the current user",
"parameters": [
{
"description": "User Data",
"name": "payload",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/v1.GroupTokenPayload"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/v1.GroupTokenResponse"
}
}
}
}
},
"/v1/items": { "/v1/items": {
"get": { "get": {
"security": [ "security": [
@ -1504,6 +1539,9 @@ const docTemplate = `{
}, },
"password": { "password": {
"type": "string" "type": "string"
},
"token": {
"type": "string"
} }
} }
}, },
@ -1544,6 +1582,31 @@ const docTemplate = `{
} }
} }
}, },
"v1.GroupTokenPayload": {
"type": "object",
"properties": {
"expiresAt": {
"type": "string"
},
"uses": {
"type": "integer"
}
}
},
"v1.GroupTokenResponse": {
"type": "object",
"properties": {
"expiresAt": {
"type": "string"
},
"token": {
"type": "string"
},
"uses": {
"type": "integer"
}
}
},
"v1.ItemAttachmentToken": { "v1.ItemAttachmentToken": {
"type": "object", "type": "object",
"properties": { "properties": {

View file

@ -13,6 +13,41 @@
}, },
"basePath": "/api", "basePath": "/api",
"paths": { "paths": {
"/v1/groups/invitations": {
"post": {
"security": [
{
"Bearer": []
}
],
"produces": [
"application/json"
],
"tags": [
"User"
],
"summary": "Get the current user",
"parameters": [
{
"description": "User Data",
"name": "payload",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/v1.GroupTokenPayload"
}
}
],
"responses": {
"200": {
"description": "OK",
"schema": {
"$ref": "#/definitions/v1.GroupTokenResponse"
}
}
}
}
},
"/v1/items": { "/v1/items": {
"get": { "get": {
"security": [ "security": [
@ -1496,6 +1531,9 @@
}, },
"password": { "password": {
"type": "string" "type": "string"
},
"token": {
"type": "string"
} }
} }
}, },
@ -1536,6 +1574,31 @@
} }
} }
}, },
"v1.GroupTokenPayload": {
"type": "object",
"properties": {
"expiresAt": {
"type": "string"
},
"uses": {
"type": "integer"
}
}
},
"v1.GroupTokenResponse": {
"type": "object",
"properties": {
"expiresAt": {
"type": "string"
},
"token": {
"type": "string"
},
"uses": {
"type": "integer"
}
}
},
"v1.ItemAttachmentToken": { "v1.ItemAttachmentToken": {
"type": "object", "type": "object",
"properties": { "properties": {

View file

@ -328,6 +328,8 @@ definitions:
type: string type: string
password: password:
type: string type: string
token:
type: string
type: object type: object
v1.ApiSummary: v1.ApiSummary:
properties: properties:
@ -353,6 +355,22 @@ definitions:
version: version:
type: string type: string
type: object type: object
v1.GroupTokenPayload:
properties:
expiresAt:
type: string
uses:
type: integer
type: object
v1.GroupTokenResponse:
properties:
expiresAt:
type: string
token:
type: string
uses:
type: integer
type: object
v1.ItemAttachmentToken: v1.ItemAttachmentToken:
properties: properties:
token: token:
@ -376,6 +394,27 @@ info:
title: Go API Templates title: Go API Templates
version: "1.0" version: "1.0"
paths: paths:
/v1/groups/invitations:
post:
parameters:
- description: User Data
in: body
name: payload
required: true
schema:
$ref: '#/definitions/v1.GroupTokenPayload'
produces:
- application/json
responses:
"200":
description: OK
schema:
$ref: '#/definitions/v1.GroupTokenResponse'
security:
- Bearer: []
summary: Get the current user
tags:
- User
/v1/items: /v1/items:
get: get:
produces: produces:

View file

@ -66,6 +66,8 @@ func (a *app) newRouter(repos *repo.AllRepos) *chi.Mux {
r.Post(v1Base("/users/logout"), v1Ctrl.HandleAuthLogout()) r.Post(v1Base("/users/logout"), v1Ctrl.HandleAuthLogout())
r.Get(v1Base("/users/refresh"), v1Ctrl.HandleAuthRefresh()) r.Get(v1Base("/users/refresh"), v1Ctrl.HandleAuthRefresh())
r.Post(v1Base("/groups/invitations"), v1Ctrl.HandleGroupInvitationsCreate())
r.Get(v1Base("/locations"), v1Ctrl.HandleLocationGetAll()) r.Get(v1Base("/locations"), v1Ctrl.HandleLocationGetAll())
r.Post(v1Base("/locations"), v1Ctrl.HandleLocationCreate()) r.Post(v1Base("/locations"), v1Ctrl.HandleLocationCreate())
r.Get(v1Base("/locations/{id}"), v1Ctrl.HandleLocationGet()) r.Get(v1Base("/locations/{id}"), v1Ctrl.HandleLocationGet())

View file

@ -0,0 +1,62 @@
package v1
import (
"net/http"
"time"
"github.com/hay-kot/homebox/backend/internal/services"
"github.com/hay-kot/homebox/backend/pkgs/server"
"github.com/rs/zerolog/log"
)
type (
GroupTokenPayload struct {
Uses int `json:"uses"`
ExpiresAt time.Time `json:"expiresAt"`
}
GroupTokenResponse struct {
Token string `json:"token"`
ExpiresAt time.Time `json:"expiresAt"`
Uses int `json:"uses"`
}
)
// HandleUserSelf godoc
// @Summary Get the current user
// @Tags User
// @Produce json
// @Param payload body GroupTokenPayload true "User Data"
// @Success 200 {object} GroupTokenResponse
// @Router /v1/groups/invitations [Post]
// @Security Bearer
func (ctrl *V1Controller) HandleGroupInvitationsCreate() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
data := GroupTokenPayload{}
if err := server.Decode(r, &data); err != nil {
log.Err(err).Msg("failed to decode user registration data")
server.RespondError(w, http.StatusInternalServerError, err)
return
}
if data.ExpiresAt.IsZero() {
data.ExpiresAt = time.Now().Add(time.Hour * 24)
}
ctx := services.NewContext(r.Context())
token, err := ctrl.svc.User.NewInvitation(ctx, data.Uses, data.ExpiresAt)
if err != nil {
log.Err(err).Msg("failed to create new token")
server.RespondError(w, http.StatusInternalServerError, err)
return
}
server.Respond(w, http.StatusCreated, server.Wrap(GroupTokenResponse{
Token: token,
ExpiresAt: data.ExpiresAt,
Uses: data.Uses,
}))
}
}

View file

@ -16,6 +16,7 @@ import (
"github.com/hay-kot/homebox/backend/ent/document" "github.com/hay-kot/homebox/backend/ent/document"
"github.com/hay-kot/homebox/backend/ent/documenttoken" "github.com/hay-kot/homebox/backend/ent/documenttoken"
"github.com/hay-kot/homebox/backend/ent/group" "github.com/hay-kot/homebox/backend/ent/group"
"github.com/hay-kot/homebox/backend/ent/groupinvitationtoken"
"github.com/hay-kot/homebox/backend/ent/item" "github.com/hay-kot/homebox/backend/ent/item"
"github.com/hay-kot/homebox/backend/ent/itemfield" "github.com/hay-kot/homebox/backend/ent/itemfield"
"github.com/hay-kot/homebox/backend/ent/label" "github.com/hay-kot/homebox/backend/ent/label"
@ -42,6 +43,8 @@ type Client struct {
DocumentToken *DocumentTokenClient DocumentToken *DocumentTokenClient
// Group is the client for interacting with the Group builders. // Group is the client for interacting with the Group builders.
Group *GroupClient 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 is the client for interacting with the Item builders.
Item *ItemClient Item *ItemClient
// ItemField is the client for interacting with the ItemField builders. // ItemField is the client for interacting with the ItemField builders.
@ -70,6 +73,7 @@ func (c *Client) init() {
c.Document = NewDocumentClient(c.config) c.Document = NewDocumentClient(c.config)
c.DocumentToken = NewDocumentTokenClient(c.config) c.DocumentToken = NewDocumentTokenClient(c.config)
c.Group = NewGroupClient(c.config) c.Group = NewGroupClient(c.config)
c.GroupInvitationToken = NewGroupInvitationTokenClient(c.config)
c.Item = NewItemClient(c.config) c.Item = NewItemClient(c.config)
c.ItemField = NewItemFieldClient(c.config) c.ItemField = NewItemFieldClient(c.config)
c.Label = NewLabelClient(c.config) c.Label = NewLabelClient(c.config)
@ -106,18 +110,19 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) {
cfg := c.config cfg := c.config
cfg.driver = tx cfg.driver = tx
return &Tx{ return &Tx{
ctx: ctx, ctx: ctx,
config: cfg, config: cfg,
Attachment: NewAttachmentClient(cfg), Attachment: NewAttachmentClient(cfg),
AuthTokens: NewAuthTokensClient(cfg), AuthTokens: NewAuthTokensClient(cfg),
Document: NewDocumentClient(cfg), Document: NewDocumentClient(cfg),
DocumentToken: NewDocumentTokenClient(cfg), DocumentToken: NewDocumentTokenClient(cfg),
Group: NewGroupClient(cfg), Group: NewGroupClient(cfg),
Item: NewItemClient(cfg), GroupInvitationToken: NewGroupInvitationTokenClient(cfg),
ItemField: NewItemFieldClient(cfg), Item: NewItemClient(cfg),
Label: NewLabelClient(cfg), ItemField: NewItemFieldClient(cfg),
Location: NewLocationClient(cfg), Label: NewLabelClient(cfg),
User: NewUserClient(cfg), Location: NewLocationClient(cfg),
User: NewUserClient(cfg),
}, nil }, nil
} }
@ -135,18 +140,19 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
cfg := c.config cfg := c.config
cfg.driver = &txDriver{tx: tx, drv: c.driver} cfg.driver = &txDriver{tx: tx, drv: c.driver}
return &Tx{ return &Tx{
ctx: ctx, ctx: ctx,
config: cfg, config: cfg,
Attachment: NewAttachmentClient(cfg), Attachment: NewAttachmentClient(cfg),
AuthTokens: NewAuthTokensClient(cfg), AuthTokens: NewAuthTokensClient(cfg),
Document: NewDocumentClient(cfg), Document: NewDocumentClient(cfg),
DocumentToken: NewDocumentTokenClient(cfg), DocumentToken: NewDocumentTokenClient(cfg),
Group: NewGroupClient(cfg), Group: NewGroupClient(cfg),
Item: NewItemClient(cfg), GroupInvitationToken: NewGroupInvitationTokenClient(cfg),
ItemField: NewItemFieldClient(cfg), Item: NewItemClient(cfg),
Label: NewLabelClient(cfg), ItemField: NewItemFieldClient(cfg),
Location: NewLocationClient(cfg), Label: NewLabelClient(cfg),
User: NewUserClient(cfg), Location: NewLocationClient(cfg),
User: NewUserClient(cfg),
}, nil }, nil
} }
@ -180,6 +186,7 @@ func (c *Client) Use(hooks ...Hook) {
c.Document.Use(hooks...) c.Document.Use(hooks...)
c.DocumentToken.Use(hooks...) c.DocumentToken.Use(hooks...)
c.Group.Use(hooks...) c.Group.Use(hooks...)
c.GroupInvitationToken.Use(hooks...)
c.Item.Use(hooks...) c.Item.Use(hooks...)
c.ItemField.Use(hooks...) c.ItemField.Use(hooks...)
c.Label.Use(hooks...) c.Label.Use(hooks...)
@ -824,11 +831,133 @@ func (c *GroupClient) QueryDocuments(gr *Group) *DocumentQuery {
return query return query
} }
// QueryInvitationTokens queries the invitation_tokens edge of a Group.
func (c *GroupClient) QueryInvitationTokens(gr *Group) *GroupInvitationTokenQuery {
query := &GroupInvitationTokenQuery{config: c.config}
query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {
id := gr.ID
step := sqlgraph.NewStep(
sqlgraph.From(group.Table, group.FieldID, id),
sqlgraph.To(groupinvitationtoken.Table, groupinvitationtoken.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, group.InvitationTokensTable, group.InvitationTokensColumn),
)
fromV = sqlgraph.Neighbors(gr.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks. // Hooks returns the client hooks.
func (c *GroupClient) Hooks() []Hook { func (c *GroupClient) Hooks() []Hook {
return c.hooks.Group return c.hooks.Group
} }
// GroupInvitationTokenClient is a client for the GroupInvitationToken schema.
type GroupInvitationTokenClient struct {
config
}
// NewGroupInvitationTokenClient returns a client for the GroupInvitationToken from the given config.
func NewGroupInvitationTokenClient(c config) *GroupInvitationTokenClient {
return &GroupInvitationTokenClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `groupinvitationtoken.Hooks(f(g(h())))`.
func (c *GroupInvitationTokenClient) Use(hooks ...Hook) {
c.hooks.GroupInvitationToken = append(c.hooks.GroupInvitationToken, hooks...)
}
// Create returns a builder for creating a GroupInvitationToken entity.
func (c *GroupInvitationTokenClient) Create() *GroupInvitationTokenCreate {
mutation := newGroupInvitationTokenMutation(c.config, OpCreate)
return &GroupInvitationTokenCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of GroupInvitationToken entities.
func (c *GroupInvitationTokenClient) CreateBulk(builders ...*GroupInvitationTokenCreate) *GroupInvitationTokenCreateBulk {
return &GroupInvitationTokenCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for GroupInvitationToken.
func (c *GroupInvitationTokenClient) Update() *GroupInvitationTokenUpdate {
mutation := newGroupInvitationTokenMutation(c.config, OpUpdate)
return &GroupInvitationTokenUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *GroupInvitationTokenClient) UpdateOne(git *GroupInvitationToken) *GroupInvitationTokenUpdateOne {
mutation := newGroupInvitationTokenMutation(c.config, OpUpdateOne, withGroupInvitationToken(git))
return &GroupInvitationTokenUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *GroupInvitationTokenClient) UpdateOneID(id uuid.UUID) *GroupInvitationTokenUpdateOne {
mutation := newGroupInvitationTokenMutation(c.config, OpUpdateOne, withGroupInvitationTokenID(id))
return &GroupInvitationTokenUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for GroupInvitationToken.
func (c *GroupInvitationTokenClient) Delete() *GroupInvitationTokenDelete {
mutation := newGroupInvitationTokenMutation(c.config, OpDelete)
return &GroupInvitationTokenDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *GroupInvitationTokenClient) DeleteOne(git *GroupInvitationToken) *GroupInvitationTokenDeleteOne {
return c.DeleteOneID(git.ID)
}
// DeleteOne returns a builder for deleting the given entity by its id.
func (c *GroupInvitationTokenClient) DeleteOneID(id uuid.UUID) *GroupInvitationTokenDeleteOne {
builder := c.Delete().Where(groupinvitationtoken.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &GroupInvitationTokenDeleteOne{builder}
}
// Query returns a query builder for GroupInvitationToken.
func (c *GroupInvitationTokenClient) Query() *GroupInvitationTokenQuery {
return &GroupInvitationTokenQuery{
config: c.config,
}
}
// Get returns a GroupInvitationToken entity by its id.
func (c *GroupInvitationTokenClient) Get(ctx context.Context, id uuid.UUID) (*GroupInvitationToken, error) {
return c.Query().Where(groupinvitationtoken.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *GroupInvitationTokenClient) GetX(ctx context.Context, id uuid.UUID) *GroupInvitationToken {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryGroup queries the group edge of a GroupInvitationToken.
func (c *GroupInvitationTokenClient) QueryGroup(git *GroupInvitationToken) *GroupQuery {
query := &GroupQuery{config: c.config}
query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {
id := git.ID
step := sqlgraph.NewStep(
sqlgraph.From(groupinvitationtoken.Table, groupinvitationtoken.FieldID, id),
sqlgraph.To(group.Table, group.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, groupinvitationtoken.GroupTable, groupinvitationtoken.GroupColumn),
)
fromV = sqlgraph.Neighbors(git.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *GroupInvitationTokenClient) Hooks() []Hook {
return c.hooks.GroupInvitationToken
}
// ItemClient is a client for the Item schema. // ItemClient is a client for the Item schema.
type ItemClient struct { type ItemClient struct {
config config

View file

@ -24,16 +24,17 @@ type config struct {
// hooks per client, for fast access. // hooks per client, for fast access.
type hooks struct { type hooks struct {
Attachment []ent.Hook Attachment []ent.Hook
AuthTokens []ent.Hook AuthTokens []ent.Hook
Document []ent.Hook Document []ent.Hook
DocumentToken []ent.Hook DocumentToken []ent.Hook
Group []ent.Hook Group []ent.Hook
Item []ent.Hook GroupInvitationToken []ent.Hook
ItemField []ent.Hook Item []ent.Hook
Label []ent.Hook ItemField []ent.Hook
Location []ent.Hook Label []ent.Hook
User []ent.Hook Location []ent.Hook
User []ent.Hook
} }
// Options applies the options on the config object. // Options applies the options on the config object.

View file

@ -15,6 +15,7 @@ import (
"github.com/hay-kot/homebox/backend/ent/document" "github.com/hay-kot/homebox/backend/ent/document"
"github.com/hay-kot/homebox/backend/ent/documenttoken" "github.com/hay-kot/homebox/backend/ent/documenttoken"
"github.com/hay-kot/homebox/backend/ent/group" "github.com/hay-kot/homebox/backend/ent/group"
"github.com/hay-kot/homebox/backend/ent/groupinvitationtoken"
"github.com/hay-kot/homebox/backend/ent/item" "github.com/hay-kot/homebox/backend/ent/item"
"github.com/hay-kot/homebox/backend/ent/itemfield" "github.com/hay-kot/homebox/backend/ent/itemfield"
"github.com/hay-kot/homebox/backend/ent/label" "github.com/hay-kot/homebox/backend/ent/label"
@ -40,16 +41,17 @@ type OrderFunc func(*sql.Selector)
// columnChecker returns a function indicates if the column exists in the given column. // columnChecker returns a function indicates if the column exists in the given column.
func columnChecker(table string) func(string) error { func columnChecker(table string) func(string) error {
checks := map[string]func(string) bool{ checks := map[string]func(string) bool{
attachment.Table: attachment.ValidColumn, attachment.Table: attachment.ValidColumn,
authtokens.Table: authtokens.ValidColumn, authtokens.Table: authtokens.ValidColumn,
document.Table: document.ValidColumn, document.Table: document.ValidColumn,
documenttoken.Table: documenttoken.ValidColumn, documenttoken.Table: documenttoken.ValidColumn,
group.Table: group.ValidColumn, group.Table: group.ValidColumn,
item.Table: item.ValidColumn, groupinvitationtoken.Table: groupinvitationtoken.ValidColumn,
itemfield.Table: itemfield.ValidColumn, item.Table: item.ValidColumn,
label.Table: label.ValidColumn, itemfield.Table: itemfield.ValidColumn,
location.Table: location.ValidColumn, label.Table: label.ValidColumn,
user.Table: user.ValidColumn, location.Table: location.ValidColumn,
user.Table: user.ValidColumn,
} }
check, ok := checks[table] check, ok := checks[table]
if !ok { if !ok {

View file

@ -42,9 +42,11 @@ type GroupEdges struct {
Labels []*Label `json:"labels,omitempty"` Labels []*Label `json:"labels,omitempty"`
// Documents holds the value of the documents edge. // Documents holds the value of the documents edge.
Documents []*Document `json:"documents,omitempty"` 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 // loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not. // type was loaded (or requested) in eager-loading or not.
loadedTypes [5]bool loadedTypes [6]bool
} }
// UsersOrErr returns the Users value or an error if the edge // UsersOrErr returns the Users value or an error if the edge
@ -92,6 +94,15 @@ func (e GroupEdges) DocumentsOrErr() ([]*Document, error) {
return nil, &NotLoadedError{edge: "documents"} 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. // scanValues returns the types for scanning values from sql.Rows.
func (*Group) scanValues(columns []string) ([]any, error) { func (*Group) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns)) values := make([]any, len(columns))
@ -178,6 +189,11 @@ func (gr *Group) QueryDocuments() *DocumentQuery {
return (&GroupClient{config: gr.config}).QueryDocuments(gr) 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. // Update returns a builder for updating this Group.
// Note that you need to call Group.Unwrap() before calling this method if 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. // was returned from a transaction, and the transaction was committed or rolled back.

View file

@ -32,6 +32,8 @@ const (
EdgeLabels = "labels" EdgeLabels = "labels"
// EdgeDocuments holds the string denoting the documents edge name in mutations. // EdgeDocuments holds the string denoting the documents edge name in mutations.
EdgeDocuments = "documents" 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 holds the table name of the group in the database.
Table = "groups" Table = "groups"
// UsersTable is the table that holds the users relation/edge. // UsersTable is the table that holds the users relation/edge.
@ -69,6 +71,13 @@ const (
DocumentsInverseTable = "documents" DocumentsInverseTable = "documents"
// DocumentsColumn is the table column denoting the documents relation/edge. // DocumentsColumn is the table column denoting the documents relation/edge.
DocumentsColumn = "group_documents" 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. // Columns holds all SQL columns for group fields.

View file

@ -506,6 +506,34 @@ func HasDocumentsWith(preds ...predicate.Document) predicate.Group {
}) })
} }
// 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. // And groups predicates with the AND operator between them.
func And(predicates ...predicate.Group) predicate.Group { func And(predicates ...predicate.Group) predicate.Group {
return predicate.Group(func(s *sql.Selector) { return predicate.Group(func(s *sql.Selector) {

View file

@ -13,6 +13,7 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"github.com/hay-kot/homebox/backend/ent/document" "github.com/hay-kot/homebox/backend/ent/document"
"github.com/hay-kot/homebox/backend/ent/group" "github.com/hay-kot/homebox/backend/ent/group"
"github.com/hay-kot/homebox/backend/ent/groupinvitationtoken"
"github.com/hay-kot/homebox/backend/ent/item" "github.com/hay-kot/homebox/backend/ent/item"
"github.com/hay-kot/homebox/backend/ent/label" "github.com/hay-kot/homebox/backend/ent/label"
"github.com/hay-kot/homebox/backend/ent/location" "github.com/hay-kot/homebox/backend/ent/location"
@ -163,6 +164,21 @@ func (gc *GroupCreate) AddDocuments(d ...*Document) *GroupCreate {
return gc.AddDocumentIDs(ids...) 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. // Mutation returns the GroupMutation object of the builder.
func (gc *GroupCreate) Mutation() *GroupMutation { func (gc *GroupCreate) Mutation() *GroupMutation {
return gc.mutation return gc.mutation
@ -445,6 +461,25 @@ func (gc *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) {
} }
_spec.Edges = append(_spec.Edges, edge) _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 return _node, _spec
} }

View file

@ -14,6 +14,7 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"github.com/hay-kot/homebox/backend/ent/document" "github.com/hay-kot/homebox/backend/ent/document"
"github.com/hay-kot/homebox/backend/ent/group" "github.com/hay-kot/homebox/backend/ent/group"
"github.com/hay-kot/homebox/backend/ent/groupinvitationtoken"
"github.com/hay-kot/homebox/backend/ent/item" "github.com/hay-kot/homebox/backend/ent/item"
"github.com/hay-kot/homebox/backend/ent/label" "github.com/hay-kot/homebox/backend/ent/label"
"github.com/hay-kot/homebox/backend/ent/location" "github.com/hay-kot/homebox/backend/ent/location"
@ -24,17 +25,18 @@ import (
// GroupQuery is the builder for querying Group entities. // GroupQuery is the builder for querying Group entities.
type GroupQuery struct { type GroupQuery struct {
config config
limit *int limit *int
offset *int offset *int
unique *bool unique *bool
order []OrderFunc order []OrderFunc
fields []string fields []string
predicates []predicate.Group predicates []predicate.Group
withUsers *UserQuery withUsers *UserQuery
withLocations *LocationQuery withLocations *LocationQuery
withItems *ItemQuery withItems *ItemQuery
withLabels *LabelQuery withLabels *LabelQuery
withDocuments *DocumentQuery withDocuments *DocumentQuery
withInvitationTokens *GroupInvitationTokenQuery
// intermediate query (i.e. traversal path). // intermediate query (i.e. traversal path).
sql *sql.Selector sql *sql.Selector
path func(context.Context) (*sql.Selector, error) path func(context.Context) (*sql.Selector, error)
@ -181,6 +183,28 @@ func (gq *GroupQuery) QueryDocuments() *DocumentQuery {
return query 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. // First returns the first Group entity from the query.
// Returns a *NotFoundError when no Group was found. // Returns a *NotFoundError when no Group was found.
func (gq *GroupQuery) First(ctx context.Context) (*Group, error) { func (gq *GroupQuery) First(ctx context.Context) (*Group, error) {
@ -357,16 +381,17 @@ func (gq *GroupQuery) Clone() *GroupQuery {
return nil return nil
} }
return &GroupQuery{ return &GroupQuery{
config: gq.config, config: gq.config,
limit: gq.limit, limit: gq.limit,
offset: gq.offset, offset: gq.offset,
order: append([]OrderFunc{}, gq.order...), order: append([]OrderFunc{}, gq.order...),
predicates: append([]predicate.Group{}, gq.predicates...), predicates: append([]predicate.Group{}, gq.predicates...),
withUsers: gq.withUsers.Clone(), withUsers: gq.withUsers.Clone(),
withLocations: gq.withLocations.Clone(), withLocations: gq.withLocations.Clone(),
withItems: gq.withItems.Clone(), withItems: gq.withItems.Clone(),
withLabels: gq.withLabels.Clone(), withLabels: gq.withLabels.Clone(),
withDocuments: gq.withDocuments.Clone(), withDocuments: gq.withDocuments.Clone(),
withInvitationTokens: gq.withInvitationTokens.Clone(),
// clone intermediate query. // clone intermediate query.
sql: gq.sql.Clone(), sql: gq.sql.Clone(),
path: gq.path, path: gq.path,
@ -429,6 +454,17 @@ func (gq *GroupQuery) WithDocuments(opts ...func(*DocumentQuery)) *GroupQuery {
return gq 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. // 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. // It is often used with aggregate functions, like: count, max, mean, min, sum.
// //
@ -497,12 +533,13 @@ func (gq *GroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Group,
var ( var (
nodes = []*Group{} nodes = []*Group{}
_spec = gq.querySpec() _spec = gq.querySpec()
loadedTypes = [5]bool{ loadedTypes = [6]bool{
gq.withUsers != nil, gq.withUsers != nil,
gq.withLocations != nil, gq.withLocations != nil,
gq.withItems != nil, gq.withItems != nil,
gq.withLabels != nil, gq.withLabels != nil,
gq.withDocuments != nil, gq.withDocuments != nil,
gq.withInvitationTokens != nil,
} }
) )
_spec.ScanValues = func(columns []string) ([]any, error) { _spec.ScanValues = func(columns []string) ([]any, error) {
@ -558,6 +595,15 @@ func (gq *GroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Group,
return nil, err 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 return nodes, nil
} }
@ -716,6 +762,37 @@ func (gq *GroupQuery) loadDocuments(ctx context.Context, query *DocumentQuery, n
} }
return nil 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) { func (gq *GroupQuery) sqlCount(ctx context.Context) (int, error) {
_spec := gq.querySpec() _spec := gq.querySpec()

View file

@ -14,6 +14,7 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"github.com/hay-kot/homebox/backend/ent/document" "github.com/hay-kot/homebox/backend/ent/document"
"github.com/hay-kot/homebox/backend/ent/group" "github.com/hay-kot/homebox/backend/ent/group"
"github.com/hay-kot/homebox/backend/ent/groupinvitationtoken"
"github.com/hay-kot/homebox/backend/ent/item" "github.com/hay-kot/homebox/backend/ent/item"
"github.com/hay-kot/homebox/backend/ent/label" "github.com/hay-kot/homebox/backend/ent/label"
"github.com/hay-kot/homebox/backend/ent/location" "github.com/hay-kot/homebox/backend/ent/location"
@ -135,6 +136,21 @@ func (gu *GroupUpdate) AddDocuments(d ...*Document) *GroupUpdate {
return gu.AddDocumentIDs(ids...) return gu.AddDocumentIDs(ids...)
} }
// AddInvitationTokenIDs adds the "invitation_tokens" edge to the GroupInvitationToken entity by IDs.
func (gu *GroupUpdate) AddInvitationTokenIDs(ids ...uuid.UUID) *GroupUpdate {
gu.mutation.AddInvitationTokenIDs(ids...)
return gu
}
// AddInvitationTokens adds the "invitation_tokens" edges to the GroupInvitationToken entity.
func (gu *GroupUpdate) AddInvitationTokens(g ...*GroupInvitationToken) *GroupUpdate {
ids := make([]uuid.UUID, len(g))
for i := range g {
ids[i] = g[i].ID
}
return gu.AddInvitationTokenIDs(ids...)
}
// Mutation returns the GroupMutation object of the builder. // Mutation returns the GroupMutation object of the builder.
func (gu *GroupUpdate) Mutation() *GroupMutation { func (gu *GroupUpdate) Mutation() *GroupMutation {
return gu.mutation return gu.mutation
@ -245,6 +261,27 @@ func (gu *GroupUpdate) RemoveDocuments(d ...*Document) *GroupUpdate {
return gu.RemoveDocumentIDs(ids...) return gu.RemoveDocumentIDs(ids...)
} }
// ClearInvitationTokens clears all "invitation_tokens" edges to the GroupInvitationToken entity.
func (gu *GroupUpdate) ClearInvitationTokens() *GroupUpdate {
gu.mutation.ClearInvitationTokens()
return gu
}
// RemoveInvitationTokenIDs removes the "invitation_tokens" edge to GroupInvitationToken entities by IDs.
func (gu *GroupUpdate) RemoveInvitationTokenIDs(ids ...uuid.UUID) *GroupUpdate {
gu.mutation.RemoveInvitationTokenIDs(ids...)
return gu
}
// RemoveInvitationTokens removes "invitation_tokens" edges to GroupInvitationToken entities.
func (gu *GroupUpdate) RemoveInvitationTokens(g ...*GroupInvitationToken) *GroupUpdate {
ids := make([]uuid.UUID, len(g))
for i := range g {
ids[i] = g[i].ID
}
return gu.RemoveInvitationTokenIDs(ids...)
}
// Save executes the query and returns the number of nodes affected by the update operation. // Save executes the query and returns the number of nodes affected by the update operation.
func (gu *GroupUpdate) Save(ctx context.Context) (int, error) { func (gu *GroupUpdate) Save(ctx context.Context) (int, error) {
var ( var (
@ -638,6 +675,60 @@ func (gu *GroupUpdate) sqlSave(ctx context.Context) (n int, err error) {
} }
_spec.Edges.Add = append(_spec.Edges.Add, edge) _spec.Edges.Add = append(_spec.Edges.Add, edge)
} }
if gu.mutation.InvitationTokensCleared() {
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,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := gu.mutation.RemovedInvitationTokensIDs(); len(nodes) > 0 && !gu.mutation.InvitationTokensCleared() {
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.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := gu.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.Add = append(_spec.Edges.Add, edge)
}
if n, err = sqlgraph.UpdateNodes(ctx, gu.driver, _spec); err != nil { if n, err = sqlgraph.UpdateNodes(ctx, gu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok { if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{group.Label} err = &NotFoundError{group.Label}
@ -758,6 +849,21 @@ func (guo *GroupUpdateOne) AddDocuments(d ...*Document) *GroupUpdateOne {
return guo.AddDocumentIDs(ids...) return guo.AddDocumentIDs(ids...)
} }
// AddInvitationTokenIDs adds the "invitation_tokens" edge to the GroupInvitationToken entity by IDs.
func (guo *GroupUpdateOne) AddInvitationTokenIDs(ids ...uuid.UUID) *GroupUpdateOne {
guo.mutation.AddInvitationTokenIDs(ids...)
return guo
}
// AddInvitationTokens adds the "invitation_tokens" edges to the GroupInvitationToken entity.
func (guo *GroupUpdateOne) AddInvitationTokens(g ...*GroupInvitationToken) *GroupUpdateOne {
ids := make([]uuid.UUID, len(g))
for i := range g {
ids[i] = g[i].ID
}
return guo.AddInvitationTokenIDs(ids...)
}
// Mutation returns the GroupMutation object of the builder. // Mutation returns the GroupMutation object of the builder.
func (guo *GroupUpdateOne) Mutation() *GroupMutation { func (guo *GroupUpdateOne) Mutation() *GroupMutation {
return guo.mutation return guo.mutation
@ -868,6 +974,27 @@ func (guo *GroupUpdateOne) RemoveDocuments(d ...*Document) *GroupUpdateOne {
return guo.RemoveDocumentIDs(ids...) return guo.RemoveDocumentIDs(ids...)
} }
// ClearInvitationTokens clears all "invitation_tokens" edges to the GroupInvitationToken entity.
func (guo *GroupUpdateOne) ClearInvitationTokens() *GroupUpdateOne {
guo.mutation.ClearInvitationTokens()
return guo
}
// RemoveInvitationTokenIDs removes the "invitation_tokens" edge to GroupInvitationToken entities by IDs.
func (guo *GroupUpdateOne) RemoveInvitationTokenIDs(ids ...uuid.UUID) *GroupUpdateOne {
guo.mutation.RemoveInvitationTokenIDs(ids...)
return guo
}
// RemoveInvitationTokens removes "invitation_tokens" edges to GroupInvitationToken entities.
func (guo *GroupUpdateOne) RemoveInvitationTokens(g ...*GroupInvitationToken) *GroupUpdateOne {
ids := make([]uuid.UUID, len(g))
for i := range g {
ids[i] = g[i].ID
}
return guo.RemoveInvitationTokenIDs(ids...)
}
// Select allows selecting one or more fields (columns) of the returned entity. // Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema. // The default is selecting all fields defined in the entity schema.
func (guo *GroupUpdateOne) Select(field string, fields ...string) *GroupUpdateOne { func (guo *GroupUpdateOne) Select(field string, fields ...string) *GroupUpdateOne {
@ -1291,6 +1418,60 @@ func (guo *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error
} }
_spec.Edges.Add = append(_spec.Edges.Add, edge) _spec.Edges.Add = append(_spec.Edges.Add, edge)
} }
if guo.mutation.InvitationTokensCleared() {
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,
},
},
}
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := guo.mutation.RemovedInvitationTokensIDs(); len(nodes) > 0 && !guo.mutation.InvitationTokensCleared() {
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.Clear = append(_spec.Edges.Clear, edge)
}
if nodes := guo.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.Add = append(_spec.Edges.Add, edge)
}
_node = &Group{config: guo.config} _node = &Group{config: guo.config}
_spec.Assign = _node.assignValues _spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues _spec.ScanValues = _node.scanValues

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/ent/group"
"github.com/hay-kot/homebox/backend/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/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/ent/group"
"github.com/hay-kot/homebox/backend/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/ent/groupinvitationtoken"
"github.com/hay-kot/homebox/backend/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/ent/group"
"github.com/hay-kot/homebox/backend/ent/groupinvitationtoken"
"github.com/hay-kot/homebox/backend/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/ent/group"
"github.com/hay-kot/homebox/backend/ent/groupinvitationtoken"
"github.com/hay-kot/homebox/backend/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

@ -74,6 +74,19 @@ func (f GroupFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error
return f(ctx, mv) 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 // The ItemFunc type is an adapter to allow the use of ordinary
// function as Item mutator. // function as Item mutator.
type ItemFunc func(context.Context, *ent.ItemMutation) (ent.Value, error) type ItemFunc func(context.Context, *ent.ItemMutation) (ent.Value, error)

View file

@ -135,6 +135,30 @@ var (
Columns: GroupsColumns, Columns: GroupsColumns,
PrimaryKey: []*schema.Column{GroupsColumns[0]}, 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 holds the columns for the "items" table.
ItemsColumns = []*schema.Column{ ItemsColumns = []*schema.Column{
{Name: "id", Type: field.TypeUUID}, {Name: "id", Type: field.TypeUUID},
@ -336,6 +360,7 @@ var (
DocumentsTable, DocumentsTable,
DocumentTokensTable, DocumentTokensTable,
GroupsTable, GroupsTable,
GroupInvitationTokensTable,
ItemsTable, ItemsTable,
ItemFieldsTable, ItemFieldsTable,
LabelsTable, LabelsTable,
@ -351,6 +376,7 @@ func init() {
AuthTokensTable.ForeignKeys[0].RefTable = UsersTable AuthTokensTable.ForeignKeys[0].RefTable = UsersTable
DocumentsTable.ForeignKeys[0].RefTable = GroupsTable DocumentsTable.ForeignKeys[0].RefTable = GroupsTable
DocumentTokensTable.ForeignKeys[0].RefTable = DocumentsTable DocumentTokensTable.ForeignKeys[0].RefTable = DocumentsTable
GroupInvitationTokensTable.ForeignKeys[0].RefTable = GroupsTable
ItemsTable.ForeignKeys[0].RefTable = GroupsTable ItemsTable.ForeignKeys[0].RefTable = GroupsTable
ItemsTable.ForeignKeys[1].RefTable = LocationsTable ItemsTable.ForeignKeys[1].RefTable = LocationsTable
ItemFieldsTable.ForeignKeys[0].RefTable = ItemsTable ItemFieldsTable.ForeignKeys[0].RefTable = ItemsTable

View file

@ -15,6 +15,7 @@ import (
"github.com/hay-kot/homebox/backend/ent/document" "github.com/hay-kot/homebox/backend/ent/document"
"github.com/hay-kot/homebox/backend/ent/documenttoken" "github.com/hay-kot/homebox/backend/ent/documenttoken"
"github.com/hay-kot/homebox/backend/ent/group" "github.com/hay-kot/homebox/backend/ent/group"
"github.com/hay-kot/homebox/backend/ent/groupinvitationtoken"
"github.com/hay-kot/homebox/backend/ent/item" "github.com/hay-kot/homebox/backend/ent/item"
"github.com/hay-kot/homebox/backend/ent/itemfield" "github.com/hay-kot/homebox/backend/ent/itemfield"
"github.com/hay-kot/homebox/backend/ent/label" "github.com/hay-kot/homebox/backend/ent/label"
@ -34,16 +35,17 @@ const (
OpUpdateOne = ent.OpUpdateOne OpUpdateOne = ent.OpUpdateOne
// Node types. // Node types.
TypeAttachment = "Attachment" TypeAttachment = "Attachment"
TypeAuthTokens = "AuthTokens" TypeAuthTokens = "AuthTokens"
TypeDocument = "Document" TypeDocument = "Document"
TypeDocumentToken = "DocumentToken" TypeDocumentToken = "DocumentToken"
TypeGroup = "Group" TypeGroup = "Group"
TypeItem = "Item" TypeGroupInvitationToken = "GroupInvitationToken"
TypeItemField = "ItemField" TypeItem = "Item"
TypeLabel = "Label" TypeItemField = "ItemField"
TypeLocation = "Location" TypeLabel = "Label"
TypeUser = "User" TypeLocation = "Location"
TypeUser = "User"
) )
// AttachmentMutation represents an operation that mutates the Attachment nodes in the graph. // AttachmentMutation represents an operation that mutates the Attachment nodes in the graph.
@ -2496,32 +2498,35 @@ func (m *DocumentTokenMutation) ResetEdge(name string) error {
// GroupMutation represents an operation that mutates the Group nodes in the graph. // GroupMutation represents an operation that mutates the Group nodes in the graph.
type GroupMutation struct { type GroupMutation struct {
config config
op Op op Op
typ string typ string
id *uuid.UUID id *uuid.UUID
created_at *time.Time created_at *time.Time
updated_at *time.Time updated_at *time.Time
name *string name *string
currency *group.Currency currency *group.Currency
clearedFields map[string]struct{} clearedFields map[string]struct{}
users map[uuid.UUID]struct{} users map[uuid.UUID]struct{}
removedusers map[uuid.UUID]struct{} removedusers map[uuid.UUID]struct{}
clearedusers bool clearedusers bool
locations map[uuid.UUID]struct{} locations map[uuid.UUID]struct{}
removedlocations map[uuid.UUID]struct{} removedlocations map[uuid.UUID]struct{}
clearedlocations bool clearedlocations bool
items map[uuid.UUID]struct{} items map[uuid.UUID]struct{}
removeditems map[uuid.UUID]struct{} removeditems map[uuid.UUID]struct{}
cleareditems bool cleareditems bool
labels map[uuid.UUID]struct{} labels map[uuid.UUID]struct{}
removedlabels map[uuid.UUID]struct{} removedlabels map[uuid.UUID]struct{}
clearedlabels bool clearedlabels bool
documents map[uuid.UUID]struct{} documents map[uuid.UUID]struct{}
removeddocuments map[uuid.UUID]struct{} removeddocuments map[uuid.UUID]struct{}
cleareddocuments bool cleareddocuments bool
done bool invitation_tokens map[uuid.UUID]struct{}
oldValue func(context.Context) (*Group, error) removedinvitation_tokens map[uuid.UUID]struct{}
predicates []predicate.Group clearedinvitation_tokens bool
done bool
oldValue func(context.Context) (*Group, error)
predicates []predicate.Group
} }
var _ ent.Mutation = (*GroupMutation)(nil) var _ ent.Mutation = (*GroupMutation)(nil)
@ -3042,6 +3047,60 @@ func (m *GroupMutation) ResetDocuments() {
m.removeddocuments = nil m.removeddocuments = nil
} }
// AddInvitationTokenIDs adds the "invitation_tokens" edge to the GroupInvitationToken entity by ids.
func (m *GroupMutation) AddInvitationTokenIDs(ids ...uuid.UUID) {
if m.invitation_tokens == nil {
m.invitation_tokens = make(map[uuid.UUID]struct{})
}
for i := range ids {
m.invitation_tokens[ids[i]] = struct{}{}
}
}
// ClearInvitationTokens clears the "invitation_tokens" edge to the GroupInvitationToken entity.
func (m *GroupMutation) ClearInvitationTokens() {
m.clearedinvitation_tokens = true
}
// InvitationTokensCleared reports if the "invitation_tokens" edge to the GroupInvitationToken entity was cleared.
func (m *GroupMutation) InvitationTokensCleared() bool {
return m.clearedinvitation_tokens
}
// RemoveInvitationTokenIDs removes the "invitation_tokens" edge to the GroupInvitationToken entity by IDs.
func (m *GroupMutation) RemoveInvitationTokenIDs(ids ...uuid.UUID) {
if m.removedinvitation_tokens == nil {
m.removedinvitation_tokens = make(map[uuid.UUID]struct{})
}
for i := range ids {
delete(m.invitation_tokens, ids[i])
m.removedinvitation_tokens[ids[i]] = struct{}{}
}
}
// RemovedInvitationTokens returns the removed IDs of the "invitation_tokens" edge to the GroupInvitationToken entity.
func (m *GroupMutation) RemovedInvitationTokensIDs() (ids []uuid.UUID) {
for id := range m.removedinvitation_tokens {
ids = append(ids, id)
}
return
}
// InvitationTokensIDs returns the "invitation_tokens" edge IDs in the mutation.
func (m *GroupMutation) InvitationTokensIDs() (ids []uuid.UUID) {
for id := range m.invitation_tokens {
ids = append(ids, id)
}
return
}
// ResetInvitationTokens resets all changes to the "invitation_tokens" edge.
func (m *GroupMutation) ResetInvitationTokens() {
m.invitation_tokens = nil
m.clearedinvitation_tokens = false
m.removedinvitation_tokens = nil
}
// Where appends a list predicates to the GroupMutation builder. // Where appends a list predicates to the GroupMutation builder.
func (m *GroupMutation) Where(ps ...predicate.Group) { func (m *GroupMutation) Where(ps ...predicate.Group) {
m.predicates = append(m.predicates, ps...) m.predicates = append(m.predicates, ps...)
@ -3211,7 +3270,7 @@ func (m *GroupMutation) ResetField(name string) error {
// AddedEdges returns all edge names that were set/added in this mutation. // AddedEdges returns all edge names that were set/added in this mutation.
func (m *GroupMutation) AddedEdges() []string { func (m *GroupMutation) AddedEdges() []string {
edges := make([]string, 0, 5) edges := make([]string, 0, 6)
if m.users != nil { if m.users != nil {
edges = append(edges, group.EdgeUsers) edges = append(edges, group.EdgeUsers)
} }
@ -3227,6 +3286,9 @@ func (m *GroupMutation) AddedEdges() []string {
if m.documents != nil { if m.documents != nil {
edges = append(edges, group.EdgeDocuments) edges = append(edges, group.EdgeDocuments)
} }
if m.invitation_tokens != nil {
edges = append(edges, group.EdgeInvitationTokens)
}
return edges return edges
} }
@ -3264,13 +3326,19 @@ func (m *GroupMutation) AddedIDs(name string) []ent.Value {
ids = append(ids, id) ids = append(ids, id)
} }
return ids return ids
case group.EdgeInvitationTokens:
ids := make([]ent.Value, 0, len(m.invitation_tokens))
for id := range m.invitation_tokens {
ids = append(ids, id)
}
return ids
} }
return nil return nil
} }
// RemovedEdges returns all edge names that were removed in this mutation. // RemovedEdges returns all edge names that were removed in this mutation.
func (m *GroupMutation) RemovedEdges() []string { func (m *GroupMutation) RemovedEdges() []string {
edges := make([]string, 0, 5) edges := make([]string, 0, 6)
if m.removedusers != nil { if m.removedusers != nil {
edges = append(edges, group.EdgeUsers) edges = append(edges, group.EdgeUsers)
} }
@ -3286,6 +3354,9 @@ func (m *GroupMutation) RemovedEdges() []string {
if m.removeddocuments != nil { if m.removeddocuments != nil {
edges = append(edges, group.EdgeDocuments) edges = append(edges, group.EdgeDocuments)
} }
if m.removedinvitation_tokens != nil {
edges = append(edges, group.EdgeInvitationTokens)
}
return edges return edges
} }
@ -3323,13 +3394,19 @@ func (m *GroupMutation) RemovedIDs(name string) []ent.Value {
ids = append(ids, id) ids = append(ids, id)
} }
return ids return ids
case group.EdgeInvitationTokens:
ids := make([]ent.Value, 0, len(m.removedinvitation_tokens))
for id := range m.removedinvitation_tokens {
ids = append(ids, id)
}
return ids
} }
return nil return nil
} }
// ClearedEdges returns all edge names that were cleared in this mutation. // ClearedEdges returns all edge names that were cleared in this mutation.
func (m *GroupMutation) ClearedEdges() []string { func (m *GroupMutation) ClearedEdges() []string {
edges := make([]string, 0, 5) edges := make([]string, 0, 6)
if m.clearedusers { if m.clearedusers {
edges = append(edges, group.EdgeUsers) edges = append(edges, group.EdgeUsers)
} }
@ -3345,6 +3422,9 @@ func (m *GroupMutation) ClearedEdges() []string {
if m.cleareddocuments { if m.cleareddocuments {
edges = append(edges, group.EdgeDocuments) edges = append(edges, group.EdgeDocuments)
} }
if m.clearedinvitation_tokens {
edges = append(edges, group.EdgeInvitationTokens)
}
return edges return edges
} }
@ -3362,6 +3442,8 @@ func (m *GroupMutation) EdgeCleared(name string) bool {
return m.clearedlabels return m.clearedlabels
case group.EdgeDocuments: case group.EdgeDocuments:
return m.cleareddocuments return m.cleareddocuments
case group.EdgeInvitationTokens:
return m.clearedinvitation_tokens
} }
return false return false
} }
@ -3393,10 +3475,649 @@ func (m *GroupMutation) ResetEdge(name string) error {
case group.EdgeDocuments: case group.EdgeDocuments:
m.ResetDocuments() m.ResetDocuments()
return nil return nil
case group.EdgeInvitationTokens:
m.ResetInvitationTokens()
return nil
} }
return fmt.Errorf("unknown Group edge %s", name) return fmt.Errorf("unknown Group edge %s", name)
} }
// GroupInvitationTokenMutation represents an operation that mutates the GroupInvitationToken nodes in the graph.
type GroupInvitationTokenMutation struct {
config
op Op
typ string
id *uuid.UUID
created_at *time.Time
updated_at *time.Time
token *[]byte
expires_at *time.Time
uses *int
adduses *int
clearedFields map[string]struct{}
group *uuid.UUID
clearedgroup bool
done bool
oldValue func(context.Context) (*GroupInvitationToken, error)
predicates []predicate.GroupInvitationToken
}
var _ ent.Mutation = (*GroupInvitationTokenMutation)(nil)
// groupinvitationtokenOption allows management of the mutation configuration using functional options.
type groupinvitationtokenOption func(*GroupInvitationTokenMutation)
// newGroupInvitationTokenMutation creates new mutation for the GroupInvitationToken entity.
func newGroupInvitationTokenMutation(c config, op Op, opts ...groupinvitationtokenOption) *GroupInvitationTokenMutation {
m := &GroupInvitationTokenMutation{
config: c,
op: op,
typ: TypeGroupInvitationToken,
clearedFields: make(map[string]struct{}),
}
for _, opt := range opts {
opt(m)
}
return m
}
// withGroupInvitationTokenID sets the ID field of the mutation.
func withGroupInvitationTokenID(id uuid.UUID) groupinvitationtokenOption {
return func(m *GroupInvitationTokenMutation) {
var (
err error
once sync.Once
value *GroupInvitationToken
)
m.oldValue = func(ctx context.Context) (*GroupInvitationToken, error) {
once.Do(func() {
if m.done {
err = errors.New("querying old values post mutation is not allowed")
} else {
value, err = m.Client().GroupInvitationToken.Get(ctx, id)
}
})
return value, err
}
m.id = &id
}
}
// withGroupInvitationToken sets the old GroupInvitationToken of the mutation.
func withGroupInvitationToken(node *GroupInvitationToken) groupinvitationtokenOption {
return func(m *GroupInvitationTokenMutation) {
m.oldValue = func(context.Context) (*GroupInvitationToken, error) {
return node, nil
}
m.id = &node.ID
}
}
// Client returns a new `ent.Client` from the mutation. If the mutation was
// executed in a transaction (ent.Tx), a transactional client is returned.
func (m GroupInvitationTokenMutation) Client() *Client {
client := &Client{config: m.config}
client.init()
return client
}
// Tx returns an `ent.Tx` for mutations that were executed in transactions;
// it returns an error otherwise.
func (m GroupInvitationTokenMutation) Tx() (*Tx, error) {
if _, ok := m.driver.(*txDriver); !ok {
return nil, errors.New("ent: mutation is not running in a transaction")
}
tx := &Tx{config: m.config}
tx.init()
return tx, nil
}
// SetID sets the value of the id field. Note that this
// operation is only accepted on creation of GroupInvitationToken entities.
func (m *GroupInvitationTokenMutation) SetID(id uuid.UUID) {
m.id = &id
}
// ID returns the ID value in the mutation. Note that the ID is only available
// if it was provided to the builder or after it was returned from the database.
func (m *GroupInvitationTokenMutation) ID() (id uuid.UUID, exists bool) {
if m.id == nil {
return
}
return *m.id, true
}
// IDs queries the database and returns the entity ids that match the mutation's predicate.
// That means, if the mutation is applied within a transaction with an isolation level such
// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated
// or updated by the mutation.
func (m *GroupInvitationTokenMutation) IDs(ctx context.Context) ([]uuid.UUID, error) {
switch {
case m.op.Is(OpUpdateOne | OpDeleteOne):
id, exists := m.ID()
if exists {
return []uuid.UUID{id}, nil
}
fallthrough
case m.op.Is(OpUpdate | OpDelete):
return m.Client().GroupInvitationToken.Query().Where(m.predicates...).IDs(ctx)
default:
return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op)
}
}
// SetCreatedAt sets the "created_at" field.
func (m *GroupInvitationTokenMutation) SetCreatedAt(t time.Time) {
m.created_at = &t
}
// CreatedAt returns the value of the "created_at" field in the mutation.
func (m *GroupInvitationTokenMutation) CreatedAt() (r time.Time, exists bool) {
v := m.created_at
if v == nil {
return
}
return *v, true
}
// OldCreatedAt returns the old "created_at" field's value of the GroupInvitationToken entity.
// If the GroupInvitationToken object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *GroupInvitationTokenMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldCreatedAt requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err)
}
return oldValue.CreatedAt, nil
}
// ResetCreatedAt resets all changes to the "created_at" field.
func (m *GroupInvitationTokenMutation) ResetCreatedAt() {
m.created_at = nil
}
// SetUpdatedAt sets the "updated_at" field.
func (m *GroupInvitationTokenMutation) SetUpdatedAt(t time.Time) {
m.updated_at = &t
}
// UpdatedAt returns the value of the "updated_at" field in the mutation.
func (m *GroupInvitationTokenMutation) UpdatedAt() (r time.Time, exists bool) {
v := m.updated_at
if v == nil {
return
}
return *v, true
}
// OldUpdatedAt returns the old "updated_at" field's value of the GroupInvitationToken entity.
// If the GroupInvitationToken object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *GroupInvitationTokenMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldUpdatedAt requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err)
}
return oldValue.UpdatedAt, nil
}
// ResetUpdatedAt resets all changes to the "updated_at" field.
func (m *GroupInvitationTokenMutation) ResetUpdatedAt() {
m.updated_at = nil
}
// SetToken sets the "token" field.
func (m *GroupInvitationTokenMutation) SetToken(b []byte) {
m.token = &b
}
// Token returns the value of the "token" field in the mutation.
func (m *GroupInvitationTokenMutation) Token() (r []byte, exists bool) {
v := m.token
if v == nil {
return
}
return *v, true
}
// OldToken returns the old "token" field's value of the GroupInvitationToken entity.
// If the GroupInvitationToken object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *GroupInvitationTokenMutation) OldToken(ctx context.Context) (v []byte, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldToken is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldToken requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldToken: %w", err)
}
return oldValue.Token, nil
}
// ResetToken resets all changes to the "token" field.
func (m *GroupInvitationTokenMutation) ResetToken() {
m.token = nil
}
// SetExpiresAt sets the "expires_at" field.
func (m *GroupInvitationTokenMutation) SetExpiresAt(t time.Time) {
m.expires_at = &t
}
// ExpiresAt returns the value of the "expires_at" field in the mutation.
func (m *GroupInvitationTokenMutation) ExpiresAt() (r time.Time, exists bool) {
v := m.expires_at
if v == nil {
return
}
return *v, true
}
// OldExpiresAt returns the old "expires_at" field's value of the GroupInvitationToken entity.
// If the GroupInvitationToken object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *GroupInvitationTokenMutation) OldExpiresAt(ctx context.Context) (v time.Time, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldExpiresAt is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldExpiresAt requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldExpiresAt: %w", err)
}
return oldValue.ExpiresAt, nil
}
// ResetExpiresAt resets all changes to the "expires_at" field.
func (m *GroupInvitationTokenMutation) ResetExpiresAt() {
m.expires_at = nil
}
// SetUses sets the "uses" field.
func (m *GroupInvitationTokenMutation) SetUses(i int) {
m.uses = &i
m.adduses = nil
}
// Uses returns the value of the "uses" field in the mutation.
func (m *GroupInvitationTokenMutation) Uses() (r int, exists bool) {
v := m.uses
if v == nil {
return
}
return *v, true
}
// OldUses returns the old "uses" field's value of the GroupInvitationToken entity.
// If the GroupInvitationToken object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *GroupInvitationTokenMutation) OldUses(ctx context.Context) (v int, err error) {
if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldUses is only allowed on UpdateOne operations")
}
if m.id == nil || m.oldValue == nil {
return v, errors.New("OldUses requires an ID field in the mutation")
}
oldValue, err := m.oldValue(ctx)
if err != nil {
return v, fmt.Errorf("querying old value for OldUses: %w", err)
}
return oldValue.Uses, nil
}
// AddUses adds i to the "uses" field.
func (m *GroupInvitationTokenMutation) AddUses(i int) {
if m.adduses != nil {
*m.adduses += i
} else {
m.adduses = &i
}
}
// AddedUses returns the value that was added to the "uses" field in this mutation.
func (m *GroupInvitationTokenMutation) AddedUses() (r int, exists bool) {
v := m.adduses
if v == nil {
return
}
return *v, true
}
// ResetUses resets all changes to the "uses" field.
func (m *GroupInvitationTokenMutation) ResetUses() {
m.uses = nil
m.adduses = nil
}
// SetGroupID sets the "group" edge to the Group entity by id.
func (m *GroupInvitationTokenMutation) SetGroupID(id uuid.UUID) {
m.group = &id
}
// ClearGroup clears the "group" edge to the Group entity.
func (m *GroupInvitationTokenMutation) ClearGroup() {
m.clearedgroup = true
}
// GroupCleared reports if the "group" edge to the Group entity was cleared.
func (m *GroupInvitationTokenMutation) GroupCleared() bool {
return m.clearedgroup
}
// GroupID returns the "group" edge ID in the mutation.
func (m *GroupInvitationTokenMutation) GroupID() (id uuid.UUID, exists bool) {
if m.group != nil {
return *m.group, true
}
return
}
// GroupIDs returns the "group" edge IDs in the mutation.
// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use
// GroupID instead. It exists only for internal usage by the builders.
func (m *GroupInvitationTokenMutation) GroupIDs() (ids []uuid.UUID) {
if id := m.group; id != nil {
ids = append(ids, *id)
}
return
}
// ResetGroup resets all changes to the "group" edge.
func (m *GroupInvitationTokenMutation) ResetGroup() {
m.group = nil
m.clearedgroup = false
}
// Where appends a list predicates to the GroupInvitationTokenMutation builder.
func (m *GroupInvitationTokenMutation) Where(ps ...predicate.GroupInvitationToken) {
m.predicates = append(m.predicates, ps...)
}
// Op returns the operation name.
func (m *GroupInvitationTokenMutation) Op() Op {
return m.op
}
// Type returns the node type of this mutation (GroupInvitationToken).
func (m *GroupInvitationTokenMutation) Type() string {
return m.typ
}
// Fields returns all fields that were changed during this mutation. Note that in
// order to get all numeric fields that were incremented/decremented, call
// AddedFields().
func (m *GroupInvitationTokenMutation) Fields() []string {
fields := make([]string, 0, 5)
if m.created_at != nil {
fields = append(fields, groupinvitationtoken.FieldCreatedAt)
}
if m.updated_at != nil {
fields = append(fields, groupinvitationtoken.FieldUpdatedAt)
}
if m.token != nil {
fields = append(fields, groupinvitationtoken.FieldToken)
}
if m.expires_at != nil {
fields = append(fields, groupinvitationtoken.FieldExpiresAt)
}
if m.uses != nil {
fields = append(fields, groupinvitationtoken.FieldUses)
}
return fields
}
// Field returns the value of a field with the given name. The second boolean
// return value indicates that this field was not set, or was not defined in the
// schema.
func (m *GroupInvitationTokenMutation) Field(name string) (ent.Value, bool) {
switch name {
case groupinvitationtoken.FieldCreatedAt:
return m.CreatedAt()
case groupinvitationtoken.FieldUpdatedAt:
return m.UpdatedAt()
case groupinvitationtoken.FieldToken:
return m.Token()
case groupinvitationtoken.FieldExpiresAt:
return m.ExpiresAt()
case groupinvitationtoken.FieldUses:
return m.Uses()
}
return nil, false
}
// OldField returns the old value of the field from the database. An error is
// returned if the mutation operation is not UpdateOne, or the query to the
// database failed.
func (m *GroupInvitationTokenMutation) OldField(ctx context.Context, name string) (ent.Value, error) {
switch name {
case groupinvitationtoken.FieldCreatedAt:
return m.OldCreatedAt(ctx)
case groupinvitationtoken.FieldUpdatedAt:
return m.OldUpdatedAt(ctx)
case groupinvitationtoken.FieldToken:
return m.OldToken(ctx)
case groupinvitationtoken.FieldExpiresAt:
return m.OldExpiresAt(ctx)
case groupinvitationtoken.FieldUses:
return m.OldUses(ctx)
}
return nil, fmt.Errorf("unknown GroupInvitationToken field %s", name)
}
// SetField sets the value of a field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *GroupInvitationTokenMutation) SetField(name string, value ent.Value) error {
switch name {
case groupinvitationtoken.FieldCreatedAt:
v, ok := value.(time.Time)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetCreatedAt(v)
return nil
case groupinvitationtoken.FieldUpdatedAt:
v, ok := value.(time.Time)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetUpdatedAt(v)
return nil
case groupinvitationtoken.FieldToken:
v, ok := value.([]byte)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetToken(v)
return nil
case groupinvitationtoken.FieldExpiresAt:
v, ok := value.(time.Time)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetExpiresAt(v)
return nil
case groupinvitationtoken.FieldUses:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.SetUses(v)
return nil
}
return fmt.Errorf("unknown GroupInvitationToken field %s", name)
}
// AddedFields returns all numeric fields that were incremented/decremented during
// this mutation.
func (m *GroupInvitationTokenMutation) AddedFields() []string {
var fields []string
if m.adduses != nil {
fields = append(fields, groupinvitationtoken.FieldUses)
}
return fields
}
// AddedField returns the numeric value that was incremented/decremented on a field
// with the given name. The second boolean return value indicates that this field
// was not set, or was not defined in the schema.
func (m *GroupInvitationTokenMutation) AddedField(name string) (ent.Value, bool) {
switch name {
case groupinvitationtoken.FieldUses:
return m.AddedUses()
}
return nil, false
}
// AddField adds the value to the field with the given name. It returns an error if
// the field is not defined in the schema, or if the type mismatched the field
// type.
func (m *GroupInvitationTokenMutation) AddField(name string, value ent.Value) error {
switch name {
case groupinvitationtoken.FieldUses:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.AddUses(v)
return nil
}
return fmt.Errorf("unknown GroupInvitationToken numeric field %s", name)
}
// ClearedFields returns all nullable fields that were cleared during this
// mutation.
func (m *GroupInvitationTokenMutation) ClearedFields() []string {
return nil
}
// FieldCleared returns a boolean indicating if a field with the given name was
// cleared in this mutation.
func (m *GroupInvitationTokenMutation) FieldCleared(name string) bool {
_, ok := m.clearedFields[name]
return ok
}
// ClearField clears the value of the field with the given name. It returns an
// error if the field is not defined in the schema.
func (m *GroupInvitationTokenMutation) ClearField(name string) error {
return fmt.Errorf("unknown GroupInvitationToken nullable field %s", name)
}
// ResetField resets all changes in the mutation for the field with the given name.
// It returns an error if the field is not defined in the schema.
func (m *GroupInvitationTokenMutation) ResetField(name string) error {
switch name {
case groupinvitationtoken.FieldCreatedAt:
m.ResetCreatedAt()
return nil
case groupinvitationtoken.FieldUpdatedAt:
m.ResetUpdatedAt()
return nil
case groupinvitationtoken.FieldToken:
m.ResetToken()
return nil
case groupinvitationtoken.FieldExpiresAt:
m.ResetExpiresAt()
return nil
case groupinvitationtoken.FieldUses:
m.ResetUses()
return nil
}
return fmt.Errorf("unknown GroupInvitationToken field %s", name)
}
// AddedEdges returns all edge names that were set/added in this mutation.
func (m *GroupInvitationTokenMutation) AddedEdges() []string {
edges := make([]string, 0, 1)
if m.group != nil {
edges = append(edges, groupinvitationtoken.EdgeGroup)
}
return edges
}
// AddedIDs returns all IDs (to other nodes) that were added for the given edge
// name in this mutation.
func (m *GroupInvitationTokenMutation) AddedIDs(name string) []ent.Value {
switch name {
case groupinvitationtoken.EdgeGroup:
if id := m.group; id != nil {
return []ent.Value{*id}
}
}
return nil
}
// RemovedEdges returns all edge names that were removed in this mutation.
func (m *GroupInvitationTokenMutation) RemovedEdges() []string {
edges := make([]string, 0, 1)
return edges
}
// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with
// the given name in this mutation.
func (m *GroupInvitationTokenMutation) RemovedIDs(name string) []ent.Value {
return nil
}
// ClearedEdges returns all edge names that were cleared in this mutation.
func (m *GroupInvitationTokenMutation) ClearedEdges() []string {
edges := make([]string, 0, 1)
if m.clearedgroup {
edges = append(edges, groupinvitationtoken.EdgeGroup)
}
return edges
}
// EdgeCleared returns a boolean which indicates if the edge with the given name
// was cleared in this mutation.
func (m *GroupInvitationTokenMutation) EdgeCleared(name string) bool {
switch name {
case groupinvitationtoken.EdgeGroup:
return m.clearedgroup
}
return false
}
// ClearEdge clears the value of the edge with the given name. It returns an error
// if that edge is not defined in the schema.
func (m *GroupInvitationTokenMutation) ClearEdge(name string) error {
switch name {
case groupinvitationtoken.EdgeGroup:
m.ClearGroup()
return nil
}
return fmt.Errorf("unknown GroupInvitationToken unique edge %s", name)
}
// ResetEdge resets all changes to the edge with the given name in this mutation.
// It returns an error if the edge is not defined in the schema.
func (m *GroupInvitationTokenMutation) ResetEdge(name string) error {
switch name {
case groupinvitationtoken.EdgeGroup:
m.ResetGroup()
return nil
}
return fmt.Errorf("unknown GroupInvitationToken edge %s", name)
}
// ItemMutation represents an operation that mutates the Item nodes in the graph. // ItemMutation represents an operation that mutates the Item nodes in the graph.
type ItemMutation struct { type ItemMutation struct {
config config

View file

@ -21,6 +21,9 @@ type DocumentToken func(*sql.Selector)
// Group is the predicate function for group builders. // Group is the predicate function for group builders.
type Group func(*sql.Selector) 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. // Item is the predicate function for item builders.
type Item func(*sql.Selector) type Item func(*sql.Selector)

View file

@ -11,6 +11,7 @@ import (
"github.com/hay-kot/homebox/backend/ent/document" "github.com/hay-kot/homebox/backend/ent/document"
"github.com/hay-kot/homebox/backend/ent/documenttoken" "github.com/hay-kot/homebox/backend/ent/documenttoken"
"github.com/hay-kot/homebox/backend/ent/group" "github.com/hay-kot/homebox/backend/ent/group"
"github.com/hay-kot/homebox/backend/ent/groupinvitationtoken"
"github.com/hay-kot/homebox/backend/ent/item" "github.com/hay-kot/homebox/backend/ent/item"
"github.com/hay-kot/homebox/backend/ent/itemfield" "github.com/hay-kot/homebox/backend/ent/itemfield"
"github.com/hay-kot/homebox/backend/ent/label" "github.com/hay-kot/homebox/backend/ent/label"
@ -188,6 +189,33 @@ func init() {
groupDescID := groupMixinFields0[0].Descriptor() groupDescID := groupMixinFields0[0].Descriptor()
// group.DefaultID holds the default value on creation for the id field. // group.DefaultID holds the default value on creation for the id field.
group.DefaultID = groupDescID.Default.(func() uuid.UUID) 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() itemMixin := schema.Item{}.Mixin()
itemMixinFields0 := itemMixin[0].Fields() itemMixinFields0 := itemMixin[0].Fields()
_ = itemMixinFields0 _ = itemMixinFields0

View file

@ -54,5 +54,9 @@ func (Group) Edges() []ent.Edge {
Annotations(entsql.Annotation{ Annotations(entsql.Annotation{
OnDelete: entsql.Cascade, 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/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

@ -22,6 +22,8 @@ type Tx struct {
DocumentToken *DocumentTokenClient DocumentToken *DocumentTokenClient
// Group is the client for interacting with the Group builders. // Group is the client for interacting with the Group builders.
Group *GroupClient 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 is the client for interacting with the Item builders.
Item *ItemClient Item *ItemClient
// ItemField is the client for interacting with the ItemField builders. // ItemField is the client for interacting with the ItemField builders.
@ -172,6 +174,7 @@ func (tx *Tx) init() {
tx.Document = NewDocumentClient(tx.config) tx.Document = NewDocumentClient(tx.config)
tx.DocumentToken = NewDocumentTokenClient(tx.config) tx.DocumentToken = NewDocumentTokenClient(tx.config)
tx.Group = NewGroupClient(tx.config) tx.Group = NewGroupClient(tx.config)
tx.GroupInvitationToken = NewGroupInvitationTokenClient(tx.config)
tx.Item = NewItemClient(tx.config) tx.Item = NewItemClient(tx.config)
tx.ItemField = NewItemFieldClient(tx.config) tx.ItemField = NewItemFieldClient(tx.config)
tx.Label = NewLabelClient(tx.config) tx.Label = NewLabelClient(tx.config)

View file

@ -0,0 +1,4 @@
-- create "group_invitation_tokens" table
CREATE TABLE `group_invitation_tokens` (`id` uuid NOT NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, `token` blob NOT NULL, `expires_at` datetime NOT NULL, `uses` integer NOT NULL DEFAULT 0, `group_invitation_tokens` uuid NULL, PRIMARY KEY (`id`), CONSTRAINT `group_invitation_tokens_groups_invitation_tokens` FOREIGN KEY (`group_invitation_tokens`) REFERENCES `groups` (`id`) ON DELETE CASCADE);
-- create index "group_invitation_tokens_token_key" to table: "group_invitation_tokens"
CREATE UNIQUE INDEX `group_invitation_tokens_token_key` ON `group_invitation_tokens` (`token`);

View file

@ -1,2 +1,3 @@
h1:ihsTwGsfNb8b/1qt+jw0OPKM8I/Bcw1J3Ise0ZFu5co= h1:JE1IHs4N6SqydqXavjqcO40KuPMZ4uA9q9eQmqeYI/o=
20220929052825_init.sql h1:ZlCqm1wzjDmofeAcSX3jE4h4VcdTNGpRg2eabztDy9Q= 20220929052825_init.sql h1:ZlCqm1wzjDmofeAcSX3jE4h4VcdTNGpRg2eabztDy9Q=
20221001210956_group_invitations.sql h1:YQKJFtE39wFOcRNbZQ/d+ZlHwrcfcsZlcv/pLEYdpjw=

View file

@ -19,7 +19,7 @@ var (
tClient *ent.Client tClient *ent.Client
tRepos *AllRepos tRepos *AllRepos
tUser UserOut tUser UserOut
tGroup *ent.Group tGroup Group
) )
func bootstrap() { func bootstrap() {
@ -28,7 +28,7 @@ func bootstrap() {
ctx = context.Background() ctx = context.Background()
) )
tGroup, err = tRepos.Groups.Create(ctx, "test-group") tGroup, err = tRepos.Groups.GroupCreate(ctx, "test-group")
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }

View file

@ -2,21 +2,112 @@ package repo
import ( import (
"context" "context"
"time"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/hay-kot/homebox/backend/ent" "github.com/hay-kot/homebox/backend/ent"
"github.com/hay-kot/homebox/backend/ent/groupinvitationtoken"
) )
type GroupRepository struct { type GroupRepository struct {
db *ent.Client db *ent.Client
} }
func (r *GroupRepository) Create(ctx context.Context, name string) (*ent.Group, error) { type (
return r.db.Group.Create(). Group struct {
SetName(name). ID uuid.UUID
Save(ctx) Name string
CreatedAt time.Time
UpdatedAt time.Time
Currency string
}
GroupInvitationCreate struct {
Token []byte `json:"-"`
ExpiresAt time.Time `json:"expiresAt"`
Uses int `json:"uses"`
}
GroupInvitation struct {
ID uuid.UUID `json:"id"`
ExpiresAt time.Time `json:"expiresAt"`
Uses int `json:"uses"`
Group Group `json:"group"`
}
)
var (
mapToGroupErr = mapTErrFunc(mapToGroup)
)
func mapToGroup(g *ent.Group) Group {
return Group{
ID: g.ID,
Name: g.Name,
CreatedAt: g.CreatedAt,
UpdatedAt: g.UpdatedAt,
Currency: g.Currency.String(),
}
} }
func (r *GroupRepository) GetOneId(ctx context.Context, id uuid.UUID) (*ent.Group, error) { var (
return r.db.Group.Get(ctx, id) mapToGroupInvitationErr = mapTErrFunc(mapToGroupInvitation)
)
func mapToGroupInvitation(g *ent.GroupInvitationToken) GroupInvitation {
return GroupInvitation{
ID: g.ID,
ExpiresAt: g.ExpiresAt,
Uses: g.Uses,
Group: mapToGroup(g.Edges.Group),
}
}
func (r *GroupRepository) GroupCreate(ctx context.Context, name string) (Group, error) {
return mapToGroupErr(r.db.Group.Create().
SetName(name).
Save(ctx))
}
func (r *GroupRepository) GroupByID(ctx context.Context, id uuid.UUID) (Group, error) {
return mapToGroupErr(r.db.Group.Get(ctx, id))
}
func (r *GroupRepository) InvitationGet(ctx context.Context, token []byte) (GroupInvitation, error) {
return mapToGroupInvitationErr(r.db.GroupInvitationToken.Query().
Where(groupinvitationtoken.Token(token)).
WithGroup().
Only(ctx))
}
func (r *GroupRepository) InvitationCreate(ctx context.Context, groupID uuid.UUID, invite GroupInvitationCreate) (GroupInvitation, error) {
entity, err := r.db.GroupInvitationToken.Create().
SetGroupID(groupID).
SetToken(invite.Token).
SetExpiresAt(invite.ExpiresAt).
SetUses(invite.Uses).
Save(ctx)
if err != nil {
return GroupInvitation{}, err
}
return r.InvitationGet(ctx, entity.Token)
}
func (r *GroupRepository) InvitationUpdate(ctx context.Context, id uuid.UUID, uses int) error {
_, err := r.db.GroupInvitationToken.UpdateOneID(id).SetUses(uses).Save(ctx)
return err
}
// InvitationPurge removes all expired invitations or those that have been used up.
// It returns the number of deleted invitations.
func (r *GroupRepository) InvitationPurge(ctx context.Context) (amount int, err error) {
q := r.db.GroupInvitationToken.Delete()
q.Where(groupinvitationtoken.Or(
groupinvitationtoken.ExpiresAtLT(time.Now()),
groupinvitationtoken.UsesLTE(0),
))
return q.Exec(ctx)
} }

View file

@ -8,13 +8,13 @@ import (
) )
func Test_Group_Create(t *testing.T) { func Test_Group_Create(t *testing.T) {
g, err := tRepos.Groups.Create(context.Background(), "test") g, err := tRepos.Groups.GroupCreate(context.Background(), "test")
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, "test", g.Name) assert.Equal(t, "test", g.Name)
// Get by ID // Get by ID
foundGroup, err := tRepos.Groups.GetOneId(context.Background(), g.ID) foundGroup, err := tRepos.Groups.GroupByID(context.Background(), g.ID)
assert.NoError(t, err) assert.NoError(t, err)
assert.Equal(t, g.ID, foundGroup.ID) assert.Equal(t, g.ID, foundGroup.ID)
} }

View file

@ -21,7 +21,7 @@ var (
tClient *ent.Client tClient *ent.Client
tRepos *repo.AllRepos tRepos *repo.AllRepos
tUser repo.UserOut tUser repo.UserOut
tGroup *ent.Group tGroup repo.Group
tSvc *AllServices tSvc *AllServices
) )
@ -31,7 +31,7 @@ func bootstrap() {
ctx = context.Background() ctx = context.Background()
) )
tGroup, err = tRepos.Groups.Create(ctx, "test-group") tGroup, err = tRepos.Groups.GroupCreate(ctx, "test-group")
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }

View file

@ -24,20 +24,16 @@ type UserService struct {
type ( type (
UserRegistration struct { UserRegistration struct {
Name string `json:"name"` GroupToken string `json:"token"`
Email string `json:"email"` Name string `json:"name"`
Password string `json:"password"` Email string `json:"email"`
GroupName string `json:"groupName"` Password string `json:"password"`
GroupName string `json:"groupName"`
} }
UserAuthTokenDetail struct { UserAuthTokenDetail struct {
Raw string `json:"raw"` Raw string `json:"raw"`
ExpiresAt time.Time `json:"expiresAt"` ExpiresAt time.Time `json:"expiresAt"`
} }
UserAuthTokenCreate struct {
TokenHash []byte `json:"token"`
UserID uuid.UUID `json:"userId"`
ExpiresAt time.Time `json:"expiresAt"`
}
LoginForm struct { LoginForm struct {
Username string `json:"username"` Username string `json:"username"`
Password string `json:"password"` Password string `json:"password"`
@ -51,11 +47,28 @@ func (svc *UserService) RegisterUser(ctx context.Context, data UserRegistration)
Str("name", data.Name). Str("name", data.Name).
Str("email", data.Email). Str("email", data.Email).
Str("groupName", data.GroupName). Str("groupName", data.GroupName).
Str("groupToken", data.GroupToken).
Msg("Registering new user") Msg("Registering new user")
group, err := svc.repos.Groups.Create(ctx, data.GroupName) var (
if err != nil { err error
return repo.UserOut{}, err group repo.Group
token repo.GroupInvitation
)
if data.GroupToken == "" {
group, err = svc.repos.Groups.GroupCreate(ctx, data.GroupName)
if err != nil {
log.Err(err).Msg("Failed to create group")
return repo.UserOut{}, err
}
} else {
token, err = svc.repos.Groups.InvitationGet(ctx, hasher.HashToken(data.GroupToken))
if err != nil {
log.Err(err).Msg("Failed to get invitation token")
return repo.UserOut{}, err
}
group = token.Group
} }
hashed, _ := hasher.HashPassword(data.Password) hashed, _ := hasher.HashPassword(data.Password)
@ -86,6 +99,15 @@ func (svc *UserService) RegisterUser(ctx context.Context, data UserRegistration)
} }
} }
// Decrement the invitation token if it was used
if token.ID != uuid.Nil {
err = svc.repos.Groups.InvitationUpdate(ctx, token.ID, token.Uses-1)
if err != nil {
log.Err(err).Msg("Failed to update invitation token")
return repo.UserOut{}, err
}
}
return usr, nil return usr, nil
} }
@ -155,3 +177,18 @@ func (svc *UserService) RenewToken(ctx context.Context, token string) (UserAuthT
func (svc *UserService) DeleteSelf(ctx context.Context, ID uuid.UUID) error { func (svc *UserService) DeleteSelf(ctx context.Context, ID uuid.UUID) error {
return svc.repos.Users.Delete(ctx, ID) return svc.repos.Users.Delete(ctx, ID)
} }
func (svc *UserService) NewInvitation(ctx Context, uses int, expiresAt time.Time) (string, error) {
token := hasher.GenerateToken()
_, err := svc.repos.Groups.InvitationCreate(ctx, ctx.GID, repo.GroupInvitationCreate{
Token: token.Hash,
Uses: uses,
ExpiresAt: expiresAt,
})
if err != nil {
return "", err
}
return token.Raw, nil
}

View file

@ -222,6 +222,7 @@ export interface UserRegistration {
groupName: string; groupName: string;
name: string; name: string;
password: string; password: string;
token: string;
} }
export interface ApiSummary { export interface ApiSummary {
@ -238,6 +239,17 @@ export interface Build {
version: string; version: string;
} }
export interface GroupTokenPayload {
expiresAt: string;
uses: number;
}
export interface GroupTokenResponse {
expiresAt: string;
token: string;
uses: number;
}
export interface ItemAttachmentToken { export interface ItemAttachmentToken {
token: string; token: string;
} }