From 48f60f77edca3f5c7ba2ab8de6f3d11679ca6025 Mon Sep 17 00:00:00 2001 From: yokowu <18836617@qq.com> Date: Tue, 17 Mar 2026 11:16:23 +0800 Subject: [PATCH 1/5] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=20taskflow=20?= =?UTF-8?q?=E5=AE=A2=E6=88=B7=E7=AB=AF=E3=80=81Host/VM=20=E5=B8=B8?= =?UTF-8?q?=E9=87=8F=E5=92=8C=20ent=20=E7=B1=BB=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - consts/host.go: Host/VM/Terminal 相关常量 - pkg/taskflow/: 完整的 taskflow HTTP+WebSocket 客户端实现 - ent/types/virtualmachine.go: VM Condition 类型定义 - pkg/request: 函数签名添加 context.Context 参数 --- backend/biz/setting/usecase/model.go | 8 +- backend/consts/host.go | 62 +++++++ backend/ent/types/virtualmachine.go | 72 ++++++++ backend/go.mod | 1 + backend/go.sum | 2 + backend/pkg/request/request.go | 28 ++- backend/pkg/taskflow/client.go | 123 +++++++++++++ backend/pkg/taskflow/host.go | 33 ++++ backend/pkg/taskflow/portforward.go | 46 +++++ backend/pkg/taskflow/shell.go | 198 ++++++++++++++++++++ backend/pkg/taskflow/types.go | 262 +++++++++++++++++++++++++++ backend/pkg/taskflow/vm.go | 105 +++++++++++ 12 files changed, 930 insertions(+), 10 deletions(-) create mode 100644 backend/consts/host.go create mode 100644 backend/ent/types/virtualmachine.go create mode 100644 backend/pkg/taskflow/client.go create mode 100644 backend/pkg/taskflow/host.go create mode 100644 backend/pkg/taskflow/portforward.go create mode 100644 backend/pkg/taskflow/shell.go create mode 100644 backend/pkg/taskflow/types.go create mode 100644 backend/pkg/taskflow/vm.go diff --git a/backend/biz/setting/usecase/model.go b/backend/biz/setting/usecase/model.go index d92159cd..4b25c352 100644 --- a/backend/biz/setting/usecase/model.go +++ b/backend/biz/setting/usecase/model.go @@ -198,7 +198,7 @@ func (u *modelUsecase) GetProviderModelList(ctx context.Context, req *domain.Get client := request.NewClient(m.Scheme, m.Host, u.client.Timeout, request.WithClient(u.client)) resp, err := request.Get[domain.OpenAIResp]( - client, m.Path, + client, ctx, m.Path, request.WithHeader( request.Header{ "Authorization": fmt.Sprintf("Bearer %s", req.APIKey), @@ -236,7 +236,7 @@ func (u *modelUsecase) GetProviderModelList(ctx context.Context, req *domain.Get maps.Copy(h, headers) } - resp, err := request.Get[domain.GetProviderModelListResp](client, m.Path, request.WithHeader(h)) + resp, err := request.Get[domain.GetProviderModelListResp](client, ctx, m.Path, request.WithHeader(h)) if err != nil { return nil, err } @@ -272,7 +272,7 @@ func (u *modelUsecase) getModelsWithProxyRetry( u.logger.DebugContext(ctx, "trying direct connection (no proxy)", "provider", req.Provider, "url", m.String()) client := request.NewClient(m.Scheme, m.Host, u.client.Timeout, request.WithClient(u.client)) resp, err := request.Get[domain.OpenAIResp]( - client, m.Path, + client, ctx, m.Path, request.WithHeader(header), request.WithQuery(query), ) @@ -329,7 +329,7 @@ func (u *modelUsecase) getModelsWithProxyRetry( client := request.NewClient(m.Scheme, m.Host, u.client.Timeout, request.WithClient(proxyClient)) resp, err := request.Get[domain.OpenAIResp]( - client, m.Path, + client, ctx, m.Path, request.WithHeader(header), request.WithQuery(query), ) diff --git a/backend/consts/host.go b/backend/consts/host.go new file mode 100644 index 00000000..ebdaaae6 --- /dev/null +++ b/backend/consts/host.go @@ -0,0 +1,62 @@ +package consts + +const ( + PUBLIC_HOST_ID = "public_host" +) + +type VirtualmachineTTLKind string + +const ( + CountDown VirtualmachineTTLKind = "countdown" + Forever VirtualmachineTTLKind = "forever" +) + +type HostStatus string + +const ( + HostStatusOnline HostStatus = "online" + HostStatusOffline HostStatus = "offline" +) + +// ProxyProtocol represents the protocol used for proxy connections. +type ProxyProtocol string + +const ( + ProxyProtocolHTTP ProxyProtocol = "http" + ProxyProtocolHTTPS ProxyProtocol = "https" + ProxyProtocolSOCKS5 ProxyProtocol = "socks5" +) + +// TerminalMode 终端模式 +type TerminalMode string + +const ( + TerminalModeReadOnly TerminalMode = "read_only" + TerminalModeReadWrite TerminalMode = "read_write" +) + +// TerminalType 终端类型 +type TerminalType string + +const ( + TerminalTypeReadOnly TerminalType = "terminal_readonly" + TerminalTypeInteractive TerminalType = "terminal_interactive" +) + +const ( + VM_EXPIRE_QUEUE_KEY = "vmexpire:queue" +) + +type VM_PORT_PROTOCOL string + +const ( + VM_PORT_PROTOCOL_HTTP VM_PORT_PROTOCOL = "http" + VM_PORT_PROTOCOL_HTTPS VM_PORT_PROTOCOL = "https" +) + +type PortStatus string + +const ( + PortStatusReversed PortStatus = "reserved" + PortStatusConnected PortStatus = "connected" +) diff --git a/backend/ent/types/virtualmachine.go b/backend/ent/types/virtualmachine.go new file mode 100644 index 00000000..f9e11c94 --- /dev/null +++ b/backend/ent/types/virtualmachine.go @@ -0,0 +1,72 @@ +package types + +import ( + "github.com/chaitin/MonkeyCode/backend/pkg/cvt" + "github.com/chaitin/MonkeyCode/backend/pkg/taskflow" +) + +// ConditionStatus 条件状态 +type ConditionStatus int32 + +const ( + ConditionStatus_CONDITION_STATUS_UNKNOWN ConditionStatus = 0 + ConditionStatus_CONDITION_STATUS_IN_PROGRESS ConditionStatus = 1 + ConditionStatus_CONDITION_STATUS_TRUE ConditionStatus = 2 + ConditionStatus_CONDITION_STATUS_FALSE ConditionStatus = 3 +) + +// ConditionType 条件类型 +type ConditionType string + +const ( + ConditionTypeScheduled ConditionType = "Scheduled" + ConditionTypeImagePulled ConditionType = "ImagePulled" + ConditionTypeProjectCloned ConditionType = "ProjectCloned" + ConditionTypeImageBuilt ConditionType = "ImageBuilt" + ConditionTypeContainerCreated ConditionType = "ContainerCreated" + ConditionTypeContainerStarted ConditionType = "ContainerStarted" + ConditionTypeReady ConditionType = "Ready" + ConditionTypeFailed ConditionType = "Failed" +) + +// Condition 细粒度状态条件 +type Condition struct { + Type ConditionType `json:"type,omitempty"` + Status ConditionStatus `json:"status,omitempty"` + Reason string `json:"reason,omitempty"` + Message string `json:"message,omitempty"` + LastTransitionTime int64 `json:"last_transition_time,omitempty"` + Progress *int32 `json:"progress,omitempty"` +} + +// From 从 taskflow 类型转换 +func (c *Condition) From(src *taskflow.Condition) *Condition { + if src == nil { + return c + } + c.Type = ConditionType(src.Type) + c.Status = ConditionStatus(src.Status) + c.Reason = src.Reason + c.Message = src.Message + c.LastTransitionTime = src.LastTransitionTime + c.Progress = src.Progress + return c +} + +// VirtualMachineCondition 虚拟机条件集合 +type VirtualMachineCondition struct { + EnvID string `json:"env_id"` + Conditions []*Condition `json:"conditions,omitempty"` +} + +// From 从 taskflow 类型转换 +func (v *VirtualMachineCondition) From(src *taskflow.VirtualMachineCondition) *VirtualMachineCondition { + if src == nil { + return v + } + v.EnvID = src.EnvID + v.Conditions = cvt.Iter(src.Conditions, func(_ int, c *taskflow.Condition) *Condition { + return cvt.From(c, &Condition{}) + }) + return v +} diff --git a/backend/go.mod b/backend/go.mod index 84059a26..3762062a 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -24,6 +24,7 @@ require ( github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect github.com/bmatcuk/doublestar v1.3.4 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/coder/websocket v1.8.14 // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect github.com/gabriel-vasile/mimetype v1.4.13 // indirect diff --git a/backend/go.sum b/backend/go.sum index db88ac94..003a177a 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -26,6 +26,8 @@ github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/coder/websocket v1.8.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9g= +github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg= github.com/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI= github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M= github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE= diff --git a/backend/pkg/request/request.go b/backend/pkg/request/request.go index ee0475c8..e3bfd198 100644 --- a/backend/pkg/request/request.go +++ b/backend/pkg/request/request.go @@ -7,6 +7,7 @@ import ( "fmt" "io" "log" + "log/slog" "net/http" "net/url" "strings" @@ -22,8 +23,21 @@ type Client struct { client *http.Client tr *http.Transport debug bool + logger *slog.Logger } +// SetLogger 设置日志 +func (c *Client) SetLogger(logger *slog.Logger) { c.logger = logger } + +// SetDebug 设置调试模式 +func (c *Client) SetDebug(debug bool) { c.debug = debug } + +// GetScheme 获取协议 +func (c *Client) GetScheme() string { return c.scheme } + +// GetHost 获取主机地址 +func (c *Client) GetHost() string { return c.host } + // NewClient 创建 HTTP 客户端 func NewClient(scheme string, host string, timeout time.Duration, opts ...ReqOpt) *Client { req := &Client{ @@ -141,24 +155,26 @@ func sendRequest[T any](c *Client, method, path string, opts ...Opt) (*T, error) } // Get 发送 GET 请求 -func Get[T any](c *Client, path string, opts ...Opt) (*T, error) { +func Get[T any](c *Client, ctx context.Context, path string, opts ...Opt) (*T, error) { + opts = append(opts, WithContext(ctx)) return sendRequest[T](c, http.MethodGet, path, opts...) } // Post 发送 POST 请求 -func Post[T any](c *Client, path string, body any, opts ...Opt) (*T, error) { - opts = append(opts, WithBody(body)) +func Post[T any](c *Client, ctx context.Context, path string, body any, opts ...Opt) (*T, error) { + opts = append(opts, WithBody(body), WithContext(ctx)) return sendRequest[T](c, http.MethodPost, path, opts...) } // Put 发送 PUT 请求 -func Put[T any](c *Client, path string, body any, opts ...Opt) (*T, error) { - opts = append(opts, WithBody(body)) +func Put[T any](c *Client, ctx context.Context, path string, body any, opts ...Opt) (*T, error) { + opts = append(opts, WithBody(body), WithContext(ctx)) return sendRequest[T](c, http.MethodPut, path, opts...) } // Delete 发送 DELETE 请求 -func Delete[T any](c *Client, path string, opts ...Opt) (*T, error) { +func Delete[T any](c *Client, ctx context.Context, path string, opts ...Opt) (*T, error) { + opts = append(opts, WithContext(ctx)) return sendRequest[T](c, http.MethodDelete, path, opts...) } diff --git a/backend/pkg/taskflow/client.go b/backend/pkg/taskflow/client.go new file mode 100644 index 00000000..d8df16de --- /dev/null +++ b/backend/pkg/taskflow/client.go @@ -0,0 +1,123 @@ +package taskflow + +import ( + "context" + "fmt" + "log/slog" + "net/http" + "net/url" + "os" + "time" + + "github.com/chaitin/MonkeyCode/backend/pkg/request" +) + +// ==================== 接口定义 ==================== + +// Clienter taskflow 客户端接口 +type Clienter interface { + VirtualMachiner() VirtualMachiner + Host() Hoster + PortForwarder() PortForwarder +} + +// Sheller 终端 shell 接口 +type Sheller interface { + Write(TerminalData) error + Stop() + BlockRead(fn func(TerminalData)) error +} + +// Hoster 宿主机管理接口 +type Hoster interface { + List(ctx context.Context, userID string) (map[string]*Host, error) + IsOnline(ctx context.Context, req *IsOnlineReq[string]) (*IsOnlineResp, error) +} + +// VirtualMachiner 虚拟机管理接口 +type VirtualMachiner interface { + Create(ctx context.Context, req *CreateVirtualMachineReq) (*VirtualMachine, error) + Delete(ctx context.Context, req *DeleteVirtualMachineReq) error + Terminal(ctx context.Context, req *TerminalReq) (Sheller, error) + TerminalList(ctx context.Context, id string) ([]*Terminal, error) + CloseTerminal(ctx context.Context, req *CloseTerminalReq) error + IsOnline(ctx context.Context, req *IsOnlineReq[string]) (*IsOnlineResp, error) +} + +// PortForwarder 端口转发管理接口 +type PortForwarder interface { + List(ctx context.Context, id string) ([]*PortForwardInfo, error) + Create(ctx context.Context, req CreatePortForward) (*PortForwardInfo, error) + Close(ctx context.Context, req ClosePortForward) error + Update(ctx context.Context, req UpdatePortForward) (*PortForwardInfo, error) +} + +// ==================== 客户端实现 ==================== + +// Client taskflow 客户端 +type Client struct { + client *request.Client + hostclient Hoster + vmclient VirtualMachiner + portForwardClient PortForwarder + logger *slog.Logger +} + +// Opt 客户端选项 +type Opt func(*Client) + +// WithLogger 设置日志 +func WithLogger(logger *slog.Logger) Opt { + return func(c *Client) { + c.logger = logger + } +} + +// WithDebug 开启调试模式 +func WithDebug(debug bool) Opt { + return func(c *Client) { + c.client.SetDebug(debug) + } +} + +// NewClient 创建 taskflow 客户端 +func NewClient(opts ...Opt) Clienter { + server := os.Getenv("TASKFLOW_SERVER") + if server == "" { + panic(fmt.Errorf("TASKFLOW_SERVER must be set")) + } + + u, err := url.Parse(server) + if err != nil { + panic(fmt.Errorf("TASKFLOW_SERVER is not a valid URL: %v", err)) + } + + httpclient := &http.Client{ + Timeout: time.Second * 30, + Transport: &http.Transport{ + MaxIdleConns: 100, + MaxIdleConnsPerHost: 100, + MaxConnsPerHost: 100, + IdleConnTimeout: time.Second * 30, + }, + } + + client := request.NewClient(u.Scheme, u.Host, 15*time.Second, request.WithClient(httpclient)) + c := &Client{ + client: client, + logger: slog.Default(), + } + for _, opt := range opts { + opt(c) + } + c.client.SetLogger(c.logger) + c.vmclient = newVirtualMachineClient(c.client) + c.hostclient = newHostClient(c.client) + c.portForwardClient = newPortForwardClient(c.client) + + return c +} + +func (c *Client) VirtualMachiner() VirtualMachiner { return c.vmclient } +func (c *Client) Host() Hoster { return c.hostclient } +func (c *Client) PortForwarder() PortForwarder { return c.portForwardClient } diff --git a/backend/pkg/taskflow/host.go b/backend/pkg/taskflow/host.go new file mode 100644 index 00000000..9e9b3811 --- /dev/null +++ b/backend/pkg/taskflow/host.go @@ -0,0 +1,33 @@ +package taskflow + +import ( + "context" + + "github.com/chaitin/MonkeyCode/backend/pkg/request" +) + +type hostClient struct { + client *request.Client +} + +func newHostClient(client *request.Client) Hoster { + return &hostClient{client: client} +} + +func (h *hostClient) List(ctx context.Context, userID string) (map[string]*Host, error) { + resp, err := request.Get[Resp[map[string]*Host]](h.client, ctx, "/internal/host/list", request.WithQuery(request.Query{ + "user_id": userID, + })) + if err != nil { + return nil, err + } + return resp.Data, nil +} + +func (h *hostClient) IsOnline(ctx context.Context, req *IsOnlineReq[string]) (*IsOnlineResp, error) { + resp, err := request.Post[Resp[*IsOnlineResp]](h.client, ctx, "/internal/host/is-online", req) + if err != nil { + return nil, err + } + return resp.Data, nil +} diff --git a/backend/pkg/taskflow/portforward.go b/backend/pkg/taskflow/portforward.go new file mode 100644 index 00000000..26d56b44 --- /dev/null +++ b/backend/pkg/taskflow/portforward.go @@ -0,0 +1,46 @@ +package taskflow + +import ( + "context" + + "github.com/chaitin/MonkeyCode/backend/pkg/request" +) + +type portForwardClient struct { + client *request.Client +} + +func newPortForwardClient(client *request.Client) PortForwarder { + return &portForwardClient{client: client} +} + +func (p *portForwardClient) List(ctx context.Context, id string) ([]*PortForwardInfo, error) { + resp, err := request.Get[Resp[[]*PortForwardInfo]](p.client, ctx, "/internal/port-forward", request.WithQuery(request.Query{ + "id": id, + })) + if err != nil { + return nil, err + } + return resp.Data, nil +} + +func (p *portForwardClient) Create(ctx context.Context, req CreatePortForward) (*PortForwardInfo, error) { + resp, err := request.Post[Resp[*PortForwardInfo]](p.client, ctx, "/internal/port-forward", req) + if err != nil { + return nil, err + } + return resp.Data, nil +} + +func (p *portForwardClient) Close(ctx context.Context, req ClosePortForward) error { + _, err := request.Post[Resp[any]](p.client, ctx, "/internal/port-forward/close", req) + return err +} + +func (p *portForwardClient) Update(ctx context.Context, req UpdatePortForward) (*PortForwardInfo, error) { + resp, err := request.Put[Resp[*PortForwardInfo]](p.client, ctx, "/internal/port-forward", req) + if err != nil { + return nil, err + } + return resp.Data, nil +} diff --git a/backend/pkg/taskflow/shell.go b/backend/pkg/taskflow/shell.go new file mode 100644 index 00000000..84f63e69 --- /dev/null +++ b/backend/pkg/taskflow/shell.go @@ -0,0 +1,198 @@ +package taskflow + +import ( + "context" + "encoding/json" + "fmt" + "log/slog" + "sync" + "time" + + "github.com/coder/websocket" +) + +// Shell WebSocket 终端 shell 实现,支持自动重连和 keepalive +type Shell struct { + ctx context.Context + cancel context.CancelCauseFunc + conn *websocket.Conn + dial func(context.Context) (*websocket.Conn, error) + mu sync.Mutex + pingTicker *time.Ticker +} + +var _ Sheller = &Shell{} + +func (s *Shell) startPing() { + s.mu.Lock() + if s.pingTicker != nil { + s.mu.Unlock() + return + } + s.pingTicker = time.NewTicker(15 * time.Second) + s.mu.Unlock() + + go func() { + for { + select { + case <-s.ctx.Done(): + return + case <-s.pingTicker.C: + s.mu.Lock() + conn := s.conn + s.mu.Unlock() + + if conn == nil { + _ = s.reconnect(s.ctx) + continue + } + + pctx, cancel := context.WithTimeout(s.ctx, 5*time.Second) + if err := conn.Ping(pctx); err != nil { + cancel() + _ = s.reconnect(s.ctx) + continue + } + cancel() + } + } + }() +} + +func (s *Shell) reconnect(ctx context.Context) error { + backoff := 1 * time.Second + for { + select { + case <-ctx.Done(): + return ctx.Err() + default: + } + + nc, err := s.dial(ctx) + if err == nil { + s.mu.Lock() + old := s.conn + s.conn = nc + s.mu.Unlock() + if old != nil { + _ = old.Close(websocket.StatusNormalClosure, "reconnect") + } + return nil + } + + time.Sleep(backoff) + if backoff < 30*time.Second { + backoff *= 2 + if backoff > 30*time.Second { + backoff = 30 * time.Second + } + } + } +} + +// BlockRead 阻塞读取终端数据,支持自动重连 +func (s *Shell) BlockRead(fn func(TerminalData)) error { + for { + select { + case <-s.ctx.Done(): + return s.ctx.Err() + default: + } + + s.mu.Lock() + conn := s.conn + s.mu.Unlock() + if conn == nil { + if err := s.reconnect(s.ctx); err != nil { + return err + } + continue + } + + tp, data, err := conn.Read(s.ctx) + if err != nil { + if rerr := s.reconnect(s.ctx); rerr != nil { + return rerr + } + continue + } + + switch tp { + case websocket.MessageBinary: + fn(TerminalData{Data: data}) + case websocket.MessageText: + var tdata TerminalData + if err := json.Unmarshal(data, &tdata); err != nil { + slog.With("error", err).ErrorContext(context.Background(), "failed to unmarshal terminal text message") + continue + } + fn(tdata) + } + } +} + +// Stop 停止终端连接 +func (s *Shell) Stop() { + s.mu.Lock() + if s.pingTicker != nil { + s.pingTicker.Stop() + s.pingTicker = nil + } + conn := s.conn + s.conn = nil + s.mu.Unlock() + + if conn != nil { + _ = conn.Close(websocket.StatusNormalClosure, "stop by user") + } + s.cancel(fmt.Errorf("stop by user")) +} + +// Write 向终端写入数据,支持超时和自动重连 +func (s *Shell) Write(data TerminalData) error { + writeOnce := func(conn *websocket.Conn) error { + wctx, cancel := context.WithTimeout(s.ctx, 10*time.Second) + defer cancel() + + if len(data.Data) > 0 { + if err := conn.Write(wctx, websocket.MessageBinary, data.Data); err != nil { + return err + } + } + if data.Resize != nil { + b, err := json.Marshal(data.Resize) + if err != nil { + return err + } + if err := conn.Write(wctx, websocket.MessageText, b); err != nil { + return err + } + } + return nil + } + + s.mu.Lock() + conn := s.conn + s.mu.Unlock() + + if conn == nil { + if err := s.reconnect(s.ctx); err != nil { + return err + } + s.mu.Lock() + conn = s.conn + s.mu.Unlock() + } + + if err := writeOnce(conn); err != nil { + if rerr := s.reconnect(s.ctx); rerr != nil { + return rerr + } + s.mu.Lock() + conn = s.conn + s.mu.Unlock() + return writeOnce(conn) + } + + return nil +} diff --git a/backend/pkg/taskflow/types.go b/backend/pkg/taskflow/types.go new file mode 100644 index 00000000..0c6b5741 --- /dev/null +++ b/backend/pkg/taskflow/types.go @@ -0,0 +1,262 @@ +// Package taskflow 提供 taskflow 服务的客户端实现 +package taskflow + +import "github.com/google/uuid" + +// ==================== 通用响应 ==================== + +// Resp 通用 API 响应包装 +type Resp[T any] struct { + Code int `json:"code"` + Message string `json:"message"` + Data T `json:"data,omitempty"` +} + +// ==================== Host 类型 ==================== + +// Host 宿主机信息 +type Host struct { + ID string `json:"id"` + UserID string `json:"user_id"` + Hostname string `json:"hostname"` + Arch string `json:"arch"` + OS string `json:"os"` + Name string `json:"name"` + Cores int32 `json:"cores"` + Memory uint64 `json:"memory"` + Disk uint64 `json:"disk"` + PublicIP string `json:"public_ip"` + InternalIP string `json:"internal_ip"` + TTL TTL `json:"ttl"` + CreatedAt int64 `json:"created_at"` + Version string `json:"version"` +} + +// IsOnlineReq 在线状态查询请求 +type IsOnlineReq[T any] struct { + IDs []T `json:"ids"` +} + +// IsOnlineResp 在线状态查询响应 +type IsOnlineResp struct { + OnlineMap map[string]bool `json:"online_map"` +} + +// ==================== VirtualMachine 类型 ==================== + +// VirtualMachineStatus 虚拟机状态 +type VirtualMachineStatus string + +const ( + VirtualMachineStatusUnknown VirtualMachineStatus = "unknown" + VirtualMachineStatusPending VirtualMachineStatus = "pending" + VirtualMachineStatusOnline VirtualMachineStatus = "online" + VirtualMachineStatusOffline VirtualMachineStatus = "offline" +) + +// TTLKind TTL 类型 +type TTLKind uint8 + +const ( + TTLForever TTLKind = iota + 1 // 永不过期 + TTLCountDown // 计时器过期 +) + +// TTL 生命周期 +type TTL struct { + Kind TTLKind `json:"kind"` + Seconds int64 `json:"seconds"` +} + +// VirtualMachine 虚拟机信息 +type VirtualMachine struct { + ID string `json:"id"` + EnvironmentID string `json:"environment_id"` + HostID string `json:"host_id"` + Hostname string `json:"hostname"` + Arch string `json:"arch"` + OS string `json:"os"` + Name string `json:"name"` + Repository string `json:"repository"` + Status VirtualMachineStatus `json:"status"` + StatusMessage string `json:"status_message"` + Cores int32 `json:"cores"` + Memory uint64 `json:"memory"` + Disk uint64 `json:"disk"` + TTL TTL `json:"ttl"` + ExternalIP string `json:"external_ip"` + CreatedAt int64 `json:"created_at"` + Version string `json:"version"` +} + +// ConditionStatus 条件状态 +type ConditionStatus int32 + +const ( + ConditionStatusUnknown ConditionStatus = 0 + ConditionStatusInProgress ConditionStatus = 1 + ConditionStatusTrue ConditionStatus = 2 + ConditionStatusFalse ConditionStatus = 3 +) + +// Condition 细粒度状态条件 +type Condition struct { + Type string `json:"type,omitempty"` + Status ConditionStatus `json:"status,omitempty"` + Reason string `json:"reason,omitempty"` + Message string `json:"message,omitempty"` + LastTransitionTime int64 `json:"last_transition_time,omitempty"` + Progress *int32 `json:"progress,omitempty"` +} + +// VirtualMachineCondition 虚拟机条件集合 +type VirtualMachineCondition struct { + EnvID string `json:"env_id"` + Conditions []*Condition `json:"conditions,omitempty"` +} + +// ==================== 创建/删除 VM 请求 ==================== + +// CreateVirtualMachineReq 创建虚拟机请求 +type CreateVirtualMachineReq struct { + UserID string `json:"user_id" validate:"required"` + HostID string `json:"host_id" validate:"required"` + HostName string `json:"hostname"` + Git Git `json:"git"` + ZipUrl string `json:"zip_url"` + ImageURL string `json:"image_url"` + ProxyURL string `json:"proxy_url"` + TTL TTL `json:"ttl" validate:"required"` + TaskID uuid.UUID `json:"task_id"` + LLM LLMProviderReq `json:"llm"` + Cores string `json:"cores"` + Memory uint64 `json:"memory"` + InstallCodingAgents bool `json:"install_coding_agents"` +} + +// Git 仓库信息 +type Git struct { + URL string `json:"url"` + Token string `json:"token"` + ProxyURL string `json:"proxy_url"` + Branch string `json:"branch,omitempty"` + Username string `json:"username,omitempty"` + Email string `json:"email,omitempty"` +} + +// LLMProvider 模型提供商 +type LLMProvider string + +const ( + LlmProviderOpenAI LLMProvider = "openai" +) + +// LLMProviderReq 模型提供商配置 +type LLMProviderReq struct { + Provider LLMProvider `json:"provider"` + ApiKey string `json:"api_key"` + BaseURL string `json:"base_url"` + Model string `json:"model"` + Temperature *float32 `json:"temperature,omitempty"` +} + +// DeleteVirtualMachineReq 删除虚拟机请求 +type DeleteVirtualMachineReq struct { + HostID string `json:"host_id" query:"host_id" validate:"required"` + UserID string `json:"user_id" query:"user_id" validate:"required"` + ID string `json:"id" query:"id" validate:"required"` +} + +// ==================== Terminal 类型 ==================== + +// TerminalMode 终端模式 +type TerminalMode uint8 + +const ( + TerminalModeReadWrite TerminalMode = iota + TerminalModeReadOnly +) + +// TerminalSize 终端尺寸 +type TerminalSize struct { + Col uint32 `json:"col" query:"col"` + Row uint32 `json:"row" query:"row"` +} + +// TerminalReq 终端连接请求 +type TerminalReq struct { + ID string `json:"id" query:"id"` + Mode TerminalMode `json:"mode" query:"mode"` + TerminalID string `json:"terminal_id" query:"terminal_id" validate:"required"` + Exec string `json:"exec" query:"exec"` + TerminalSize +} + +// TerminalData 终端数据 +type TerminalData struct { + Data []byte `json:"data,omitempty"` + Connected bool `json:"connected"` + Resize *TerminalSize `json:"resize,omitempty"` + Error *string `json:"error,omitempty"` +} + +// CloseTerminalReq 关闭终端请求 +type CloseTerminalReq struct { + ID string `json:"id" query:"id"` + TerminalID string `json:"terminal_id" query:"terminal_id"` +} + +// Terminal 终端信息 +type Terminal struct { + ID string `json:"id"` + Title string `json:"title"` + ConnectedCount uint32 `json:"connected_count"` + CreatedAt int64 `json:"created_at"` +} + +// ==================== PortForward 类型 ==================== + +// PortForwardInfo 端口转发信息 +type PortForwardInfo struct { + Port int32 `json:"port"` + Status string `json:"status"` + Process string `json:"process"` + ForwardID *string `json:"forward_id"` + AccessURL *string `json:"access_url"` + CreatedAt int64 `json:"created_at"` + Success bool `json:"success"` + ErrorMessage string `json:"error_message,omitempty"` + WhitelistIPs []string `json:"whitelist_ips"` +} + +// CreatePortForward 创建端口转发请求 +type CreatePortForward struct { + ID string `json:"id" query:"id" validate:"required"` + UserID string `json:"user_id"` + LocalPort int32 `json:"local_port"` + WhitelistIPs []string `json:"whitelist_ips"` +} + +// UpdatePortForward 更新端口转发请求 +type UpdatePortForward struct { + ID string `json:"id" query:"id" validate:"required"` + ForwardID string `json:"forward_id"` + WhitelistIPs []string `json:"whitelist_ips"` +} + +// ClosePortForward 关闭端口转发请求 +type ClosePortForward struct { + ID string `json:"id" query:"id" validate:"required"` + ForwardID string `json:"forward_id"` +} + +// ==================== Stats 类型 ==================== + +// Stats 统计信息 +type Stats struct { + OnlineHostCount int `json:"online_host_count"` + OnlineTaskCount int `json:"online_task_count"` + OnlineVMCount int `json:"online_vm_count"` + OnlineTerminalCount int `json:"online_terminal_count"` + UsingTerminalUserCount int `json:"using_terminal_user_count"` +} diff --git a/backend/pkg/taskflow/vm.go b/backend/pkg/taskflow/vm.go new file mode 100644 index 00000000..d4bc84d0 --- /dev/null +++ b/backend/pkg/taskflow/vm.go @@ -0,0 +1,105 @@ +package taskflow + +import ( + "context" + "fmt" + "net/url" + + "github.com/coder/websocket" + + "github.com/chaitin/MonkeyCode/backend/pkg/request" +) + +type virtualMachineClient struct { + client *request.Client +} + +func newVirtualMachineClient(client *request.Client) VirtualMachiner { + return &virtualMachineClient{client: client} +} + +func (v *virtualMachineClient) Create(ctx context.Context, req *CreateVirtualMachineReq) (*VirtualMachine, error) { + resp, err := request.Post[Resp[*VirtualMachine]](v.client, ctx, "/internal/vm", req) + if err != nil { + return nil, err + } + return resp.Data, nil +} + +func (v *virtualMachineClient) Delete(ctx context.Context, req *DeleteVirtualMachineReq) error { + q := request.Query{ + "id": req.ID, + "host_id": req.HostID, + "user_id": req.UserID, + } + _, err := request.Delete[any](v.client, ctx, "/internal/vm", request.WithQuery(q)) + return err +} + +func (v *virtualMachineClient) IsOnline(ctx context.Context, req *IsOnlineReq[string]) (*IsOnlineResp, error) { + resp, err := request.Post[Resp[*IsOnlineResp]](v.client, ctx, "/internal/vm/is-online", req) + if err != nil { + return nil, err + } + return resp.Data, nil +} + +func (v *virtualMachineClient) Terminal(ctx context.Context, req *TerminalReq) (Sheller, error) { + wsScheme := "ws" + if v.client.GetScheme() == "https" { + wsScheme = "wss" + } + + dial := func(ctx context.Context) (*websocket.Conn, error) { + u := &url.URL{ + Scheme: wsScheme, + Host: v.client.GetHost(), + Path: "/internal/ws/terminal", + } + values := url.Values{} + values.Add("id", req.ID) + values.Add("col", fmt.Sprintf("%d", req.Col)) + values.Add("row", fmt.Sprintf("%d", req.Row)) + values.Add("terminal_id", req.TerminalID) + values.Add("exec", req.Exec) + values.Add("mode", fmt.Sprintf("%d", req.Mode)) + u.RawQuery = values.Encode() + + conn, _, err := websocket.Dial(ctx, u.String(), &websocket.DialOptions{}) + if err != nil { + return nil, err + } + return conn, nil + } + + conn, err := dial(ctx) + if err != nil { + return nil, err + } + + ctx, cancel := context.WithCancelCause(ctx) + shell := &Shell{ + ctx: ctx, + cancel: cancel, + conn: conn, + dial: dial, + } + shell.startPing() + + return shell, nil +} + +func (v *virtualMachineClient) TerminalList(ctx context.Context, id string) ([]*Terminal, error) { + resp, err := request.Get[Resp[[]*Terminal]](v.client, ctx, "/internal/terminal", request.WithQuery( + request.Query{"id": id}, + )) + if err != nil { + return nil, err + } + return resp.Data, nil +} + +func (v *virtualMachineClient) CloseTerminal(ctx context.Context, req *CloseTerminalReq) error { + _, err := request.Delete[any](v.client, ctx, "/internal/terminal", request.WithBody(req)) + return err +} From c30c73aa93e7650e104fd125b4f1da9fa3670a1d Mon Sep 17 00:00:00 2001 From: yokowu <18836617@qq.com> Date: Tue, 17 Mar 2026 11:22:25 +0800 Subject: [PATCH 2/5] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=20Host/VM=20ent?= =?UTF-8?q?=20schema=20=E5=92=8C=E6=95=B0=E6=8D=AE=E5=BA=93=E8=BF=81?= =?UTF-8?q?=E7=A7=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - ent/schema: host, virtualmachine, teamhost, teamgrouphost - 修改 user/team/teamgroup/model schema 添加 host/vm edges - migration/000003: hosts, virtualmachines, team_hosts, team_group_hosts 建表 --- backend/db/client.go | 847 +- backend/db/cursor.go | 92 + backend/db/ent.go | 8 + backend/db/hook/hook.go | 48 + backend/db/host.go | 351 + backend/db/host/host.go | 306 + backend/db/host/where.go | 1194 ++ backend/db/host_create.go | 1839 ++ backend/db/host_delete.go | 88 + backend/db/host_query.go | 911 + backend/db/host_update.go | 1657 ++ backend/db/intercept/intercept.go | 120 + backend/db/migrate/schema.go | 173 + backend/db/model.go | 22 +- backend/db/model/model.go | 30 + backend/db/model/where.go | 23 + backend/db/model_create.go | 32 + backend/db/model_query.go | 76 +- backend/db/model_update.go | 163 + backend/db/mutation.go | 18994 +++++++++++------- backend/db/page.go | 56 + backend/db/predicate/predicate.go | 12 + backend/db/runtime/runtime.go | 52 + backend/db/teamgroup.go | 40 +- backend/db/teamgroup/teamgroup.go | 61 + backend/db/teamgroup/where.go | 46 + backend/db/teamgroup_create.go | 68 + backend/db/teamgroup_query.go | 181 +- backend/db/teamgroup_update.go | 350 + backend/db/teamgrouphost.go | 177 + backend/db/teamgrouphost/teamgrouphost.go | 117 + backend/db/teamgrouphost/where.go | 258 + backend/db/teamgrouphost_create.go | 659 + backend/db/teamgrouphost_delete.go | 88 + backend/db/teamgrouphost_query.go | 732 + backend/db/teamgrouphost_update.go | 473 + backend/db/teamhost.go | 177 + backend/db/teamhost/teamhost.go | 117 + backend/db/teamhost/where.go | 258 + backend/db/teamhost_create.go | 659 + backend/db/teamhost_delete.go | 88 + backend/db/teamhost_query.go | 732 + backend/db/teamhost_update.go | 473 + backend/db/tx.go | 12 + backend/db/user.go | 38 +- backend/db/user/user.go | 60 + backend/db/user/where.go | 46 + backend/db/user_create.go | 64 + backend/db/user_query.go | 150 +- backend/db/user_update.go | 326 + backend/db/virtualmachine.go | 438 + backend/db/virtualmachine/virtualmachine.go | 313 + backend/db/virtualmachine/where.go | 1687 ++ backend/db/virtualmachine_create.go | 2363 +++ backend/db/virtualmachine_delete.go | 88 + backend/db/virtualmachine_query.go | 807 + backend/db/virtualmachine_update.go | 1650 ++ backend/ent/schema/host.go | 63 + backend/ent/schema/model.go | 1 + backend/ent/schema/teamgroup.go | 1 + backend/ent/schema/teamgrouphost.go | 44 + backend/ent/schema/teamhost.go | 41 + backend/ent/schema/user.go | 2 + backend/ent/schema/virtualmachine.go | 72 + backend/migration/000003_host_vm.down.sql | 4 + backend/migration/000003_host_vm.up.sql | 78 + 66 files changed, 34439 insertions(+), 6757 deletions(-) create mode 100644 backend/db/host.go create mode 100644 backend/db/host/host.go create mode 100644 backend/db/host/where.go create mode 100644 backend/db/host_create.go create mode 100644 backend/db/host_delete.go create mode 100644 backend/db/host_query.go create mode 100644 backend/db/host_update.go create mode 100644 backend/db/teamgrouphost.go create mode 100644 backend/db/teamgrouphost/teamgrouphost.go create mode 100644 backend/db/teamgrouphost/where.go create mode 100644 backend/db/teamgrouphost_create.go create mode 100644 backend/db/teamgrouphost_delete.go create mode 100644 backend/db/teamgrouphost_query.go create mode 100644 backend/db/teamgrouphost_update.go create mode 100644 backend/db/teamhost.go create mode 100644 backend/db/teamhost/teamhost.go create mode 100644 backend/db/teamhost/where.go create mode 100644 backend/db/teamhost_create.go create mode 100644 backend/db/teamhost_delete.go create mode 100644 backend/db/teamhost_query.go create mode 100644 backend/db/teamhost_update.go create mode 100644 backend/db/virtualmachine.go create mode 100644 backend/db/virtualmachine/virtualmachine.go create mode 100644 backend/db/virtualmachine/where.go create mode 100644 backend/db/virtualmachine_create.go create mode 100644 backend/db/virtualmachine_delete.go create mode 100644 backend/db/virtualmachine_query.go create mode 100644 backend/db/virtualmachine_update.go create mode 100644 backend/ent/schema/host.go create mode 100644 backend/ent/schema/teamgrouphost.go create mode 100644 backend/ent/schema/teamhost.go create mode 100644 backend/ent/schema/virtualmachine.go create mode 100644 backend/migration/000003_host_vm.down.sql create mode 100644 backend/migration/000003_host_vm.up.sql diff --git a/backend/db/client.go b/backend/db/client.go index ac6ce89d..c9c86448 100644 --- a/backend/db/client.go +++ b/backend/db/client.go @@ -17,18 +17,22 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "github.com/chaitin/MonkeyCode/backend/db/audit" + "github.com/chaitin/MonkeyCode/backend/db/host" "github.com/chaitin/MonkeyCode/backend/db/image" "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/team" "github.com/chaitin/MonkeyCode/backend/db/teamgroup" + "github.com/chaitin/MonkeyCode/backend/db/teamgrouphost" "github.com/chaitin/MonkeyCode/backend/db/teamgroupimage" "github.com/chaitin/MonkeyCode/backend/db/teamgroupmember" "github.com/chaitin/MonkeyCode/backend/db/teamgroupmodel" + "github.com/chaitin/MonkeyCode/backend/db/teamhost" "github.com/chaitin/MonkeyCode/backend/db/teamimage" "github.com/chaitin/MonkeyCode/backend/db/teammember" "github.com/chaitin/MonkeyCode/backend/db/teammodel" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/chaitin/MonkeyCode/backend/db/useridentity" + "github.com/chaitin/MonkeyCode/backend/db/virtualmachine" stdsql "database/sql" ) @@ -40,6 +44,8 @@ type Client struct { Schema *migrate.Schema // Audit is the client for interacting with the Audit builders. Audit *AuditClient + // Host is the client for interacting with the Host builders. + Host *HostClient // Image is the client for interacting with the Image builders. Image *ImageClient // Model is the client for interacting with the Model builders. @@ -48,12 +54,16 @@ type Client struct { Team *TeamClient // TeamGroup is the client for interacting with the TeamGroup builders. TeamGroup *TeamGroupClient + // TeamGroupHost is the client for interacting with the TeamGroupHost builders. + TeamGroupHost *TeamGroupHostClient // TeamGroupImage is the client for interacting with the TeamGroupImage builders. TeamGroupImage *TeamGroupImageClient // TeamGroupMember is the client for interacting with the TeamGroupMember builders. TeamGroupMember *TeamGroupMemberClient // TeamGroupModel is the client for interacting with the TeamGroupModel builders. TeamGroupModel *TeamGroupModelClient + // TeamHost is the client for interacting with the TeamHost builders. + TeamHost *TeamHostClient // TeamImage is the client for interacting with the TeamImage builders. TeamImage *TeamImageClient // TeamMember is the client for interacting with the TeamMember builders. @@ -64,6 +74,8 @@ type Client struct { User *UserClient // UserIdentity is the client for interacting with the UserIdentity builders. UserIdentity *UserIdentityClient + // VirtualMachine is the client for interacting with the VirtualMachine builders. + VirtualMachine *VirtualMachineClient } // NewClient creates a new client configured with the given options. @@ -76,18 +88,22 @@ func NewClient(opts ...Option) *Client { func (c *Client) init() { c.Schema = migrate.NewSchema(c.driver) c.Audit = NewAuditClient(c.config) + c.Host = NewHostClient(c.config) c.Image = NewImageClient(c.config) c.Model = NewModelClient(c.config) c.Team = NewTeamClient(c.config) c.TeamGroup = NewTeamGroupClient(c.config) + c.TeamGroupHost = NewTeamGroupHostClient(c.config) c.TeamGroupImage = NewTeamGroupImageClient(c.config) c.TeamGroupMember = NewTeamGroupMemberClient(c.config) c.TeamGroupModel = NewTeamGroupModelClient(c.config) + c.TeamHost = NewTeamHostClient(c.config) c.TeamImage = NewTeamImageClient(c.config) c.TeamMember = NewTeamMemberClient(c.config) c.TeamModel = NewTeamModelClient(c.config) c.User = NewUserClient(c.config) c.UserIdentity = NewUserIdentityClient(c.config) + c.VirtualMachine = NewVirtualMachineClient(c.config) } type ( @@ -181,18 +197,22 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { ctx: ctx, config: cfg, Audit: NewAuditClient(cfg), + Host: NewHostClient(cfg), Image: NewImageClient(cfg), Model: NewModelClient(cfg), Team: NewTeamClient(cfg), TeamGroup: NewTeamGroupClient(cfg), + TeamGroupHost: NewTeamGroupHostClient(cfg), TeamGroupImage: NewTeamGroupImageClient(cfg), TeamGroupMember: NewTeamGroupMemberClient(cfg), TeamGroupModel: NewTeamGroupModelClient(cfg), + TeamHost: NewTeamHostClient(cfg), TeamImage: NewTeamImageClient(cfg), TeamMember: NewTeamMemberClient(cfg), TeamModel: NewTeamModelClient(cfg), User: NewUserClient(cfg), UserIdentity: NewUserIdentityClient(cfg), + VirtualMachine: NewVirtualMachineClient(cfg), }, nil } @@ -213,18 +233,22 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) ctx: ctx, config: cfg, Audit: NewAuditClient(cfg), + Host: NewHostClient(cfg), Image: NewImageClient(cfg), Model: NewModelClient(cfg), Team: NewTeamClient(cfg), TeamGroup: NewTeamGroupClient(cfg), + TeamGroupHost: NewTeamGroupHostClient(cfg), TeamGroupImage: NewTeamGroupImageClient(cfg), TeamGroupMember: NewTeamGroupMemberClient(cfg), TeamGroupModel: NewTeamGroupModelClient(cfg), + TeamHost: NewTeamHostClient(cfg), TeamImage: NewTeamImageClient(cfg), TeamMember: NewTeamMemberClient(cfg), TeamModel: NewTeamModelClient(cfg), User: NewUserClient(cfg), UserIdentity: NewUserIdentityClient(cfg), + VirtualMachine: NewVirtualMachineClient(cfg), }, nil } @@ -254,9 +278,9 @@ func (c *Client) Close() error { // In order to add hooks to a specific client, call: `client.Node.Use(...)`. func (c *Client) Use(hooks ...Hook) { for _, n := range []interface{ Use(...Hook) }{ - c.Audit, c.Image, c.Model, c.Team, c.TeamGroup, c.TeamGroupImage, - c.TeamGroupMember, c.TeamGroupModel, c.TeamImage, c.TeamMember, c.TeamModel, - c.User, c.UserIdentity, + c.Audit, c.Host, c.Image, c.Model, c.Team, c.TeamGroup, c.TeamGroupHost, + c.TeamGroupImage, c.TeamGroupMember, c.TeamGroupModel, c.TeamHost, c.TeamImage, + c.TeamMember, c.TeamModel, c.User, c.UserIdentity, c.VirtualMachine, } { n.Use(hooks...) } @@ -266,9 +290,9 @@ func (c *Client) Use(hooks ...Hook) { // In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. func (c *Client) Intercept(interceptors ...Interceptor) { for _, n := range []interface{ Intercept(...Interceptor) }{ - c.Audit, c.Image, c.Model, c.Team, c.TeamGroup, c.TeamGroupImage, - c.TeamGroupMember, c.TeamGroupModel, c.TeamImage, c.TeamMember, c.TeamModel, - c.User, c.UserIdentity, + c.Audit, c.Host, c.Image, c.Model, c.Team, c.TeamGroup, c.TeamGroupHost, + c.TeamGroupImage, c.TeamGroupMember, c.TeamGroupModel, c.TeamHost, c.TeamImage, + c.TeamMember, c.TeamModel, c.User, c.UserIdentity, c.VirtualMachine, } { n.Intercept(interceptors...) } @@ -279,6 +303,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { switch m := m.(type) { case *AuditMutation: return c.Audit.mutate(ctx, m) + case *HostMutation: + return c.Host.mutate(ctx, m) case *ImageMutation: return c.Image.mutate(ctx, m) case *ModelMutation: @@ -287,12 +313,16 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.Team.mutate(ctx, m) case *TeamGroupMutation: return c.TeamGroup.mutate(ctx, m) + case *TeamGroupHostMutation: + return c.TeamGroupHost.mutate(ctx, m) case *TeamGroupImageMutation: return c.TeamGroupImage.mutate(ctx, m) case *TeamGroupMemberMutation: return c.TeamGroupMember.mutate(ctx, m) case *TeamGroupModelMutation: return c.TeamGroupModel.mutate(ctx, m) + case *TeamHostMutation: + return c.TeamHost.mutate(ctx, m) case *TeamImageMutation: return c.TeamImage.mutate(ctx, m) case *TeamMemberMutation: @@ -303,6 +333,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { return c.User.mutate(ctx, m) case *UserIdentityMutation: return c.UserIdentity.mutate(ctx, m) + case *VirtualMachineMutation: + return c.VirtualMachine.mutate(ctx, m) default: return nil, fmt.Errorf("db: unknown mutation type %T", m) } @@ -457,6 +489,205 @@ func (c *AuditClient) mutate(ctx context.Context, m *AuditMutation) (Value, erro } } +// HostClient is a client for the Host schema. +type HostClient struct { + config +} + +// NewHostClient returns a client for the Host from the given config. +func NewHostClient(c config) *HostClient { + return &HostClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `host.Hooks(f(g(h())))`. +func (c *HostClient) Use(hooks ...Hook) { + c.hooks.Host = append(c.hooks.Host, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `host.Intercept(f(g(h())))`. +func (c *HostClient) Intercept(interceptors ...Interceptor) { + c.inters.Host = append(c.inters.Host, interceptors...) +} + +// Create returns a builder for creating a Host entity. +func (c *HostClient) Create() *HostCreate { + mutation := newHostMutation(c.config, OpCreate) + return &HostCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Host entities. +func (c *HostClient) CreateBulk(builders ...*HostCreate) *HostCreateBulk { + return &HostCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *HostClient) MapCreateBulk(slice any, setFunc func(*HostCreate, int)) *HostCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &HostCreateBulk{err: fmt.Errorf("calling to HostClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*HostCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &HostCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Host. +func (c *HostClient) Update() *HostUpdate { + mutation := newHostMutation(c.config, OpUpdate) + return &HostUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *HostClient) UpdateOne(_m *Host) *HostUpdateOne { + mutation := newHostMutation(c.config, OpUpdateOne, withHost(_m)) + return &HostUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *HostClient) UpdateOneID(id string) *HostUpdateOne { + mutation := newHostMutation(c.config, OpUpdateOne, withHostID(id)) + return &HostUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Host. +func (c *HostClient) Delete() *HostDelete { + mutation := newHostMutation(c.config, OpDelete) + return &HostDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *HostClient) DeleteOne(_m *Host) *HostDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *HostClient) DeleteOneID(id string) *HostDeleteOne { + builder := c.Delete().Where(host.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &HostDeleteOne{builder} +} + +// Query returns a query builder for Host. +func (c *HostClient) Query() *HostQuery { + return &HostQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeHost}, + inters: c.Interceptors(), + } +} + +// Get returns a Host entity by its id. +func (c *HostClient) Get(ctx context.Context, id string) (*Host, error) { + return c.Query().Where(host.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *HostClient) GetX(ctx context.Context, id string) *Host { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryVms queries the vms edge of a Host. +func (c *HostClient) QueryVms(_m *Host) *VirtualMachineQuery { + query := (&VirtualMachineClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(host.Table, host.FieldID, id), + sqlgraph.To(virtualmachine.Table, virtualmachine.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, host.VmsTable, host.VmsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryUser queries the user edge of a Host. +func (c *HostClient) QueryUser(_m *Host) *UserQuery { + query := (&UserClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(host.Table, host.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, host.UserTable, host.UserColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryGroups queries the groups edge of a Host. +func (c *HostClient) QueryGroups(_m *Host) *TeamGroupQuery { + query := (&TeamGroupClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(host.Table, host.FieldID, id), + sqlgraph.To(teamgroup.Table, teamgroup.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, host.GroupsTable, host.GroupsPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryTeamGroupHosts queries the team_group_hosts edge of a Host. +func (c *HostClient) QueryTeamGroupHosts(_m *Host) *TeamGroupHostQuery { + query := (&TeamGroupHostClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(host.Table, host.FieldID, id), + sqlgraph.To(teamgrouphost.Table, teamgrouphost.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, host.TeamGroupHostsTable, host.TeamGroupHostsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *HostClient) Hooks() []Hook { + hooks := c.hooks.Host + return append(hooks[:len(hooks):len(hooks)], host.Hooks[:]...) +} + +// Interceptors returns the client interceptors. +func (c *HostClient) Interceptors() []Interceptor { + inters := c.inters.Host + return append(inters[:len(inters):len(inters)], host.Interceptors[:]...) +} + +func (c *HostClient) mutate(ctx context.Context, m *HostMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&HostCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&HostUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&HostUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&HostDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown Host mutation op: %q", m.Op()) + } +} + // ImageClient is a client for the Image schema. type ImageClient struct { config @@ -828,6 +1059,22 @@ func (c *ModelClient) QueryGroups(_m *Model) *TeamGroupQuery { return query } +// QueryVms queries the vms edge of a Model. +func (c *ModelClient) QueryVms(_m *Model) *VirtualMachineQuery { + query := (&VirtualMachineClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(model.Table, model.FieldID, id), + sqlgraph.To(virtualmachine.Table, virtualmachine.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, model.VmsTable, model.VmsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + // QueryTeamModels queries the team_models edge of a Model. func (c *ModelClient) QueryTeamModels(_m *Model) *TeamModelQuery { query := (&TeamModelClient{config: c.config}).Query() @@ -1306,6 +1553,22 @@ func (c *TeamGroupClient) QueryImages(_m *TeamGroup) *ImageQuery { return query } +// QueryHosts queries the hosts edge of a TeamGroup. +func (c *TeamGroupClient) QueryHosts(_m *TeamGroup) *HostQuery { + query := (&HostClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(teamgroup.Table, teamgroup.FieldID, id), + sqlgraph.To(host.Table, host.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, teamgroup.HostsTable, teamgroup.HostsPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + // QueryTeamGroupMembers queries the team_group_members edge of a TeamGroup. func (c *TeamGroupClient) QueryTeamGroupMembers(_m *TeamGroup) *TeamGroupMemberQuery { query := (&TeamGroupMemberClient{config: c.config}).Query() @@ -1354,6 +1617,22 @@ func (c *TeamGroupClient) QueryTeamGroupImages(_m *TeamGroup) *TeamGroupImageQue return query } +// QueryTeamGroupHosts queries the team_group_hosts edge of a TeamGroup. +func (c *TeamGroupClient) QueryTeamGroupHosts(_m *TeamGroup) *TeamGroupHostQuery { + query := (&TeamGroupHostClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(teamgroup.Table, teamgroup.FieldID, id), + sqlgraph.To(teamgrouphost.Table, teamgrouphost.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, teamgroup.TeamGroupHostsTable, teamgroup.TeamGroupHostsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + // Hooks returns the client hooks. func (c *TeamGroupClient) Hooks() []Hook { hooks := c.hooks.TeamGroup @@ -1381,6 +1660,171 @@ func (c *TeamGroupClient) mutate(ctx context.Context, m *TeamGroupMutation) (Val } } +// TeamGroupHostClient is a client for the TeamGroupHost schema. +type TeamGroupHostClient struct { + config +} + +// NewTeamGroupHostClient returns a client for the TeamGroupHost from the given config. +func NewTeamGroupHostClient(c config) *TeamGroupHostClient { + return &TeamGroupHostClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `teamgrouphost.Hooks(f(g(h())))`. +func (c *TeamGroupHostClient) Use(hooks ...Hook) { + c.hooks.TeamGroupHost = append(c.hooks.TeamGroupHost, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `teamgrouphost.Intercept(f(g(h())))`. +func (c *TeamGroupHostClient) Intercept(interceptors ...Interceptor) { + c.inters.TeamGroupHost = append(c.inters.TeamGroupHost, interceptors...) +} + +// Create returns a builder for creating a TeamGroupHost entity. +func (c *TeamGroupHostClient) Create() *TeamGroupHostCreate { + mutation := newTeamGroupHostMutation(c.config, OpCreate) + return &TeamGroupHostCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of TeamGroupHost entities. +func (c *TeamGroupHostClient) CreateBulk(builders ...*TeamGroupHostCreate) *TeamGroupHostCreateBulk { + return &TeamGroupHostCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *TeamGroupHostClient) MapCreateBulk(slice any, setFunc func(*TeamGroupHostCreate, int)) *TeamGroupHostCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &TeamGroupHostCreateBulk{err: fmt.Errorf("calling to TeamGroupHostClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*TeamGroupHostCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &TeamGroupHostCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for TeamGroupHost. +func (c *TeamGroupHostClient) Update() *TeamGroupHostUpdate { + mutation := newTeamGroupHostMutation(c.config, OpUpdate) + return &TeamGroupHostUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *TeamGroupHostClient) UpdateOne(_m *TeamGroupHost) *TeamGroupHostUpdateOne { + mutation := newTeamGroupHostMutation(c.config, OpUpdateOne, withTeamGroupHost(_m)) + return &TeamGroupHostUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *TeamGroupHostClient) UpdateOneID(id uuid.UUID) *TeamGroupHostUpdateOne { + mutation := newTeamGroupHostMutation(c.config, OpUpdateOne, withTeamGroupHostID(id)) + return &TeamGroupHostUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for TeamGroupHost. +func (c *TeamGroupHostClient) Delete() *TeamGroupHostDelete { + mutation := newTeamGroupHostMutation(c.config, OpDelete) + return &TeamGroupHostDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *TeamGroupHostClient) DeleteOne(_m *TeamGroupHost) *TeamGroupHostDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *TeamGroupHostClient) DeleteOneID(id uuid.UUID) *TeamGroupHostDeleteOne { + builder := c.Delete().Where(teamgrouphost.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &TeamGroupHostDeleteOne{builder} +} + +// Query returns a query builder for TeamGroupHost. +func (c *TeamGroupHostClient) Query() *TeamGroupHostQuery { + return &TeamGroupHostQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeTeamGroupHost}, + inters: c.Interceptors(), + } +} + +// Get returns a TeamGroupHost entity by its id. +func (c *TeamGroupHostClient) Get(ctx context.Context, id uuid.UUID) (*TeamGroupHost, error) { + return c.Query().Where(teamgrouphost.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *TeamGroupHostClient) GetX(ctx context.Context, id uuid.UUID) *TeamGroupHost { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryGroup queries the group edge of a TeamGroupHost. +func (c *TeamGroupHostClient) QueryGroup(_m *TeamGroupHost) *TeamGroupQuery { + query := (&TeamGroupClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(teamgrouphost.Table, teamgrouphost.FieldID, id), + sqlgraph.To(teamgroup.Table, teamgroup.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, teamgrouphost.GroupTable, teamgrouphost.GroupColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryHost queries the host edge of a TeamGroupHost. +func (c *TeamGroupHostClient) QueryHost(_m *TeamGroupHost) *HostQuery { + query := (&HostClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(teamgrouphost.Table, teamgrouphost.FieldID, id), + sqlgraph.To(host.Table, host.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, teamgrouphost.HostTable, teamgrouphost.HostColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *TeamGroupHostClient) Hooks() []Hook { + return c.hooks.TeamGroupHost +} + +// Interceptors returns the client interceptors. +func (c *TeamGroupHostClient) Interceptors() []Interceptor { + return c.inters.TeamGroupHost +} + +func (c *TeamGroupHostClient) mutate(ctx context.Context, m *TeamGroupHostMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&TeamGroupHostCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&TeamGroupHostUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&TeamGroupHostUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&TeamGroupHostDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown TeamGroupHost mutation op: %q", m.Op()) + } +} + // TeamGroupImageClient is a client for the TeamGroupImage schema. type TeamGroupImageClient struct { config @@ -1876,6 +2320,171 @@ func (c *TeamGroupModelClient) mutate(ctx context.Context, m *TeamGroupModelMuta } } +// TeamHostClient is a client for the TeamHost schema. +type TeamHostClient struct { + config +} + +// NewTeamHostClient returns a client for the TeamHost from the given config. +func NewTeamHostClient(c config) *TeamHostClient { + return &TeamHostClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `teamhost.Hooks(f(g(h())))`. +func (c *TeamHostClient) Use(hooks ...Hook) { + c.hooks.TeamHost = append(c.hooks.TeamHost, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `teamhost.Intercept(f(g(h())))`. +func (c *TeamHostClient) Intercept(interceptors ...Interceptor) { + c.inters.TeamHost = append(c.inters.TeamHost, interceptors...) +} + +// Create returns a builder for creating a TeamHost entity. +func (c *TeamHostClient) Create() *TeamHostCreate { + mutation := newTeamHostMutation(c.config, OpCreate) + return &TeamHostCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of TeamHost entities. +func (c *TeamHostClient) CreateBulk(builders ...*TeamHostCreate) *TeamHostCreateBulk { + return &TeamHostCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *TeamHostClient) MapCreateBulk(slice any, setFunc func(*TeamHostCreate, int)) *TeamHostCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &TeamHostCreateBulk{err: fmt.Errorf("calling to TeamHostClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*TeamHostCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &TeamHostCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for TeamHost. +func (c *TeamHostClient) Update() *TeamHostUpdate { + mutation := newTeamHostMutation(c.config, OpUpdate) + return &TeamHostUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *TeamHostClient) UpdateOne(_m *TeamHost) *TeamHostUpdateOne { + mutation := newTeamHostMutation(c.config, OpUpdateOne, withTeamHost(_m)) + return &TeamHostUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *TeamHostClient) UpdateOneID(id uuid.UUID) *TeamHostUpdateOne { + mutation := newTeamHostMutation(c.config, OpUpdateOne, withTeamHostID(id)) + return &TeamHostUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for TeamHost. +func (c *TeamHostClient) Delete() *TeamHostDelete { + mutation := newTeamHostMutation(c.config, OpDelete) + return &TeamHostDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *TeamHostClient) DeleteOne(_m *TeamHost) *TeamHostDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *TeamHostClient) DeleteOneID(id uuid.UUID) *TeamHostDeleteOne { + builder := c.Delete().Where(teamhost.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &TeamHostDeleteOne{builder} +} + +// Query returns a query builder for TeamHost. +func (c *TeamHostClient) Query() *TeamHostQuery { + return &TeamHostQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeTeamHost}, + inters: c.Interceptors(), + } +} + +// Get returns a TeamHost entity by its id. +func (c *TeamHostClient) Get(ctx context.Context, id uuid.UUID) (*TeamHost, error) { + return c.Query().Where(teamhost.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *TeamHostClient) GetX(ctx context.Context, id uuid.UUID) *TeamHost { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryTeam queries the team edge of a TeamHost. +func (c *TeamHostClient) QueryTeam(_m *TeamHost) *TeamQuery { + query := (&TeamClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(teamhost.Table, teamhost.FieldID, id), + sqlgraph.To(team.Table, team.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, teamhost.TeamTable, teamhost.TeamColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryHost queries the host edge of a TeamHost. +func (c *TeamHostClient) QueryHost(_m *TeamHost) *HostQuery { + query := (&HostClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(teamhost.Table, teamhost.FieldID, id), + sqlgraph.To(host.Table, host.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, teamhost.HostTable, teamhost.HostColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *TeamHostClient) Hooks() []Hook { + return c.hooks.TeamHost +} + +// Interceptors returns the client interceptors. +func (c *TeamHostClient) Interceptors() []Interceptor { + return c.inters.TeamHost +} + +func (c *TeamHostClient) mutate(ctx context.Context, m *TeamHostMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&TeamHostCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&TeamHostUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&TeamHostUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&TeamHostDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown TeamHost mutation op: %q", m.Op()) + } +} + // TeamImageClient is a client for the TeamImage schema. type TeamImageClient struct { config @@ -2575,6 +3184,38 @@ func (c *UserClient) QueryImages(_m *User) *ImageQuery { return query } +// QueryHosts queries the hosts edge of a User. +func (c *UserClient) QueryHosts(_m *User) *HostQuery { + query := (&HostClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, id), + sqlgraph.To(host.Table, host.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, user.HostsTable, user.HostsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryVms queries the vms edge of a User. +func (c *UserClient) QueryVms(_m *User) *VirtualMachineQuery { + query := (&VirtualMachineClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, id), + sqlgraph.To(virtualmachine.Table, virtualmachine.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, user.VmsTable, user.VmsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + // QueryTeamMembers queries the team_members edge of a User. func (c *UserClient) QueryTeamMembers(_m *User) *TeamMemberQuery { query := (&TeamMemberClient{config: c.config}).Query() @@ -2785,16 +3426,200 @@ func (c *UserIdentityClient) mutate(ctx context.Context, m *UserIdentityMutation } } +// VirtualMachineClient is a client for the VirtualMachine schema. +type VirtualMachineClient struct { + config +} + +// NewVirtualMachineClient returns a client for the VirtualMachine from the given config. +func NewVirtualMachineClient(c config) *VirtualMachineClient { + return &VirtualMachineClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `virtualmachine.Hooks(f(g(h())))`. +func (c *VirtualMachineClient) Use(hooks ...Hook) { + c.hooks.VirtualMachine = append(c.hooks.VirtualMachine, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `virtualmachine.Intercept(f(g(h())))`. +func (c *VirtualMachineClient) Intercept(interceptors ...Interceptor) { + c.inters.VirtualMachine = append(c.inters.VirtualMachine, interceptors...) +} + +// Create returns a builder for creating a VirtualMachine entity. +func (c *VirtualMachineClient) Create() *VirtualMachineCreate { + mutation := newVirtualMachineMutation(c.config, OpCreate) + return &VirtualMachineCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of VirtualMachine entities. +func (c *VirtualMachineClient) CreateBulk(builders ...*VirtualMachineCreate) *VirtualMachineCreateBulk { + return &VirtualMachineCreateBulk{config: c.config, builders: builders} +} + +// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates +// a builder and applies setFunc on it. +func (c *VirtualMachineClient) MapCreateBulk(slice any, setFunc func(*VirtualMachineCreate, int)) *VirtualMachineCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &VirtualMachineCreateBulk{err: fmt.Errorf("calling to VirtualMachineClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*VirtualMachineCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &VirtualMachineCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for VirtualMachine. +func (c *VirtualMachineClient) Update() *VirtualMachineUpdate { + mutation := newVirtualMachineMutation(c.config, OpUpdate) + return &VirtualMachineUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *VirtualMachineClient) UpdateOne(_m *VirtualMachine) *VirtualMachineUpdateOne { + mutation := newVirtualMachineMutation(c.config, OpUpdateOne, withVirtualMachine(_m)) + return &VirtualMachineUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *VirtualMachineClient) UpdateOneID(id string) *VirtualMachineUpdateOne { + mutation := newVirtualMachineMutation(c.config, OpUpdateOne, withVirtualMachineID(id)) + return &VirtualMachineUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for VirtualMachine. +func (c *VirtualMachineClient) Delete() *VirtualMachineDelete { + mutation := newVirtualMachineMutation(c.config, OpDelete) + return &VirtualMachineDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *VirtualMachineClient) DeleteOne(_m *VirtualMachine) *VirtualMachineDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *VirtualMachineClient) DeleteOneID(id string) *VirtualMachineDeleteOne { + builder := c.Delete().Where(virtualmachine.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &VirtualMachineDeleteOne{builder} +} + +// Query returns a query builder for VirtualMachine. +func (c *VirtualMachineClient) Query() *VirtualMachineQuery { + return &VirtualMachineQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeVirtualMachine}, + inters: c.Interceptors(), + } +} + +// Get returns a VirtualMachine entity by its id. +func (c *VirtualMachineClient) Get(ctx context.Context, id string) (*VirtualMachine, error) { + return c.Query().Where(virtualmachine.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *VirtualMachineClient) GetX(ctx context.Context, id string) *VirtualMachine { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryHost queries the host edge of a VirtualMachine. +func (c *VirtualMachineClient) QueryHost(_m *VirtualMachine) *HostQuery { + query := (&HostClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(virtualmachine.Table, virtualmachine.FieldID, id), + sqlgraph.To(host.Table, host.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, virtualmachine.HostTable, virtualmachine.HostColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryModel queries the model edge of a VirtualMachine. +func (c *VirtualMachineClient) QueryModel(_m *VirtualMachine) *ModelQuery { + query := (&ModelClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(virtualmachine.Table, virtualmachine.FieldID, id), + sqlgraph.To(model.Table, model.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, virtualmachine.ModelTable, virtualmachine.ModelColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryUser queries the user edge of a VirtualMachine. +func (c *VirtualMachineClient) QueryUser(_m *VirtualMachine) *UserQuery { + query := (&UserClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(virtualmachine.Table, virtualmachine.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, virtualmachine.UserTable, virtualmachine.UserColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *VirtualMachineClient) Hooks() []Hook { + hooks := c.hooks.VirtualMachine + return append(hooks[:len(hooks):len(hooks)], virtualmachine.Hooks[:]...) +} + +// Interceptors returns the client interceptors. +func (c *VirtualMachineClient) Interceptors() []Interceptor { + inters := c.inters.VirtualMachine + return append(inters[:len(inters):len(inters)], virtualmachine.Interceptors[:]...) +} + +func (c *VirtualMachineClient) mutate(ctx context.Context, m *VirtualMachineMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&VirtualMachineCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&VirtualMachineUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&VirtualMachineUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&VirtualMachineDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("db: unknown VirtualMachine mutation op: %q", m.Op()) + } +} + // hooks and interceptors per client, for fast access. type ( hooks struct { - Audit, Image, Model, Team, TeamGroup, TeamGroupImage, TeamGroupMember, - TeamGroupModel, TeamImage, TeamMember, TeamModel, User, UserIdentity []ent.Hook + Audit, Host, Image, Model, Team, TeamGroup, TeamGroupHost, TeamGroupImage, + TeamGroupMember, TeamGroupModel, TeamHost, TeamImage, TeamMember, TeamModel, + User, UserIdentity, VirtualMachine []ent.Hook } inters struct { - Audit, Image, Model, Team, TeamGroup, TeamGroupImage, TeamGroupMember, - TeamGroupModel, TeamImage, TeamMember, TeamModel, User, - UserIdentity []ent.Interceptor + Audit, Host, Image, Model, Team, TeamGroup, TeamGroupHost, TeamGroupImage, + TeamGroupMember, TeamGroupModel, TeamHost, TeamImage, TeamMember, TeamModel, + User, UserIdentity, VirtualMachine []ent.Interceptor } ) diff --git a/backend/db/cursor.go b/backend/db/cursor.go index 8ccf03e3..a8a2c351 100644 --- a/backend/db/cursor.go +++ b/backend/db/cursor.go @@ -13,9 +13,11 @@ import ( "entgo.io/ent/dialect/sql" "github.com/chaitin/MonkeyCode/backend/db/audit" + "github.com/chaitin/MonkeyCode/backend/db/host" "github.com/chaitin/MonkeyCode/backend/db/image" "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/teamgroup" + "github.com/chaitin/MonkeyCode/backend/db/teamgrouphost" "github.com/chaitin/MonkeyCode/backend/db/teamgroupmodel" "github.com/google/uuid" ) @@ -204,6 +206,51 @@ func (q *AuditQuery) After(ctx context.Context, cursor string, limit int) ([]*Au return nodes, res, nil } +func (q *HostQuery) After(ctx context.Context, cursor string, limit int) ([]*Host, *Cursor, error) { + i, err := unmarshalCreatedAt(cursor) + if err != nil { + return nil, nil, err + } + q.Order(host.ByCreatedAt(sql.OrderDesc()), host.ByID(sql.OrderDesc())) + q.Limit(limit + 1) + + if i != nil { + q.Where(func(s *sql.Selector) { + s.Where(sql.Or( + sql.LT(s.C("created_at"), i.CreatedAt), + sql.And( + sql.EQ(s.C("created_at"), i.CreatedAt), + sql.LT(s.C("id"), i.ID), + ), + )) + }) + } + nodes, err := q.All(ctx) + if err != nil { + return nil, nil, err + } + + res := &Cursor{} + if len(nodes) > limit { + res.HasNextPage = true + nodes = nodes[:limit] + } + + if len(nodes) > 0 { + last := nodes[len(nodes)-1] + i := &createdAtCursor{ + CreatedAt: last.CreatedAt, + ID: last.ID, + } + cursor, err := i.marshal() + if err != nil { + return nil, nil, err + } + res.Cursor = cursor + } + return nodes, res, nil +} + func (q *ImageQuery) After(ctx context.Context, cursor string, limit int) ([]*Image, *Cursor, error) { i, err := unmarshalCreatedAt(cursor) if err != nil { @@ -339,6 +386,51 @@ func (q *TeamGroupQuery) After(ctx context.Context, cursor string, limit int) ([ return nodes, res, nil } +func (q *TeamGroupHostQuery) After(ctx context.Context, cursor string, limit int) ([]*TeamGroupHost, *Cursor, error) { + i, err := unmarshalCreatedAt(cursor) + if err != nil { + return nil, nil, err + } + q.Order(teamgrouphost.ByCreatedAt(sql.OrderDesc()), teamgrouphost.ByID(sql.OrderDesc())) + q.Limit(limit + 1) + + if i != nil { + q.Where(func(s *sql.Selector) { + s.Where(sql.Or( + sql.LT(s.C("created_at"), i.CreatedAt), + sql.And( + sql.EQ(s.C("created_at"), i.CreatedAt), + sql.LT(s.C("id"), i.ID), + ), + )) + }) + } + nodes, err := q.All(ctx) + if err != nil { + return nil, nil, err + } + + res := &Cursor{} + if len(nodes) > limit { + res.HasNextPage = true + nodes = nodes[:limit] + } + + if len(nodes) > 0 { + last := nodes[len(nodes)-1] + i := &createdAtCursor{ + CreatedAt: last.CreatedAt, + ID: last.ID, + } + cursor, err := i.marshal() + if err != nil { + return nil, nil, err + } + res.Cursor = cursor + } + return nodes, res, nil +} + func (q *TeamGroupModelQuery) After(ctx context.Context, cursor string, limit int) ([]*TeamGroupModel, *Cursor, error) { i, err := unmarshalCreatedAt(cursor) if err != nil { diff --git a/backend/db/ent.go b/backend/db/ent.go index 9f14e961..0eff6511 100644 --- a/backend/db/ent.go +++ b/backend/db/ent.go @@ -13,18 +13,22 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "github.com/chaitin/MonkeyCode/backend/db/audit" + "github.com/chaitin/MonkeyCode/backend/db/host" "github.com/chaitin/MonkeyCode/backend/db/image" "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/team" "github.com/chaitin/MonkeyCode/backend/db/teamgroup" + "github.com/chaitin/MonkeyCode/backend/db/teamgrouphost" "github.com/chaitin/MonkeyCode/backend/db/teamgroupimage" "github.com/chaitin/MonkeyCode/backend/db/teamgroupmember" "github.com/chaitin/MonkeyCode/backend/db/teamgroupmodel" + "github.com/chaitin/MonkeyCode/backend/db/teamhost" "github.com/chaitin/MonkeyCode/backend/db/teamimage" "github.com/chaitin/MonkeyCode/backend/db/teammember" "github.com/chaitin/MonkeyCode/backend/db/teammodel" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/chaitin/MonkeyCode/backend/db/useridentity" + "github.com/chaitin/MonkeyCode/backend/db/virtualmachine" ) // ent aliases to avoid import conflicts in user's code. @@ -86,18 +90,22 @@ func checkColumn(t, c string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ audit.Table: audit.ValidColumn, + host.Table: host.ValidColumn, image.Table: image.ValidColumn, model.Table: model.ValidColumn, team.Table: team.ValidColumn, teamgroup.Table: teamgroup.ValidColumn, + teamgrouphost.Table: teamgrouphost.ValidColumn, teamgroupimage.Table: teamgroupimage.ValidColumn, teamgroupmember.Table: teamgroupmember.ValidColumn, teamgroupmodel.Table: teamgroupmodel.ValidColumn, + teamhost.Table: teamhost.ValidColumn, teamimage.Table: teamimage.ValidColumn, teammember.Table: teammember.ValidColumn, teammodel.Table: teammodel.ValidColumn, user.Table: user.ValidColumn, useridentity.Table: useridentity.ValidColumn, + virtualmachine.Table: virtualmachine.ValidColumn, }) }) return columnCheck(t, c) diff --git a/backend/db/hook/hook.go b/backend/db/hook/hook.go index 21763443..ac8ce8dd 100644 --- a/backend/db/hook/hook.go +++ b/backend/db/hook/hook.go @@ -21,6 +21,18 @@ func (f AuditFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) return nil, fmt.Errorf("unexpected mutation type %T. expect *db.AuditMutation", m) } +// The HostFunc type is an adapter to allow the use of ordinary +// function as Host mutator. +type HostFunc func(context.Context, *db.HostMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f HostFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.HostMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.HostMutation", m) +} + // The ImageFunc type is an adapter to allow the use of ordinary // function as Image mutator. type ImageFunc func(context.Context, *db.ImageMutation) (db.Value, error) @@ -69,6 +81,18 @@ func (f TeamGroupFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, err return nil, fmt.Errorf("unexpected mutation type %T. expect *db.TeamGroupMutation", m) } +// The TeamGroupHostFunc type is an adapter to allow the use of ordinary +// function as TeamGroupHost mutator. +type TeamGroupHostFunc func(context.Context, *db.TeamGroupHostMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f TeamGroupHostFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.TeamGroupHostMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.TeamGroupHostMutation", m) +} + // The TeamGroupImageFunc type is an adapter to allow the use of ordinary // function as TeamGroupImage mutator. type TeamGroupImageFunc func(context.Context, *db.TeamGroupImageMutation) (db.Value, error) @@ -105,6 +129,18 @@ func (f TeamGroupModelFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value return nil, fmt.Errorf("unexpected mutation type %T. expect *db.TeamGroupModelMutation", m) } +// The TeamHostFunc type is an adapter to allow the use of ordinary +// function as TeamHost mutator. +type TeamHostFunc func(context.Context, *db.TeamHostMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f TeamHostFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.TeamHostMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.TeamHostMutation", m) +} + // The TeamImageFunc type is an adapter to allow the use of ordinary // function as TeamImage mutator. type TeamImageFunc func(context.Context, *db.TeamImageMutation) (db.Value, error) @@ -165,6 +201,18 @@ func (f UserIdentityFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, return nil, fmt.Errorf("unexpected mutation type %T. expect *db.UserIdentityMutation", m) } +// The VirtualMachineFunc type is an adapter to allow the use of ordinary +// function as VirtualMachine mutator. +type VirtualMachineFunc func(context.Context, *db.VirtualMachineMutation) (db.Value, error) + +// Mutate calls f(ctx, m). +func (f VirtualMachineFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) { + if mv, ok := m.(*db.VirtualMachineMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *db.VirtualMachineMutation", m) +} + // Condition is a hook condition function. type Condition func(context.Context, db.Mutation) bool diff --git a/backend/db/host.go b/backend/db/host.go new file mode 100644 index 00000000..32df2c24 --- /dev/null +++ b/backend/db/host.go @@ -0,0 +1,351 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/chaitin/MonkeyCode/backend/db/host" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/google/uuid" +) + +// Host is the model entity for the Host schema. +type Host struct { + config `json:"-"` + // ID of the ent. + ID string `json:"id,omitempty"` + // DeletedAt holds the value of the "deleted_at" field. + DeletedAt time.Time `json:"deleted_at,omitempty"` + // UserID holds the value of the "user_id" field. + UserID uuid.UUID `json:"user_id,omitempty"` + // Hostname holds the value of the "hostname" field. + Hostname string `json:"hostname,omitempty"` + // Arch holds the value of the "arch" field. + Arch string `json:"arch,omitempty"` + // Cores holds the value of the "cores" field. + Cores int `json:"cores,omitempty"` + // Weight holds the value of the "weight" field. + Weight int `json:"weight,omitempty"` + // Memory holds the value of the "memory" field. + Memory int64 `json:"memory,omitempty"` + // Disk holds the value of the "disk" field. + Disk int64 `json:"disk,omitempty"` + // Os holds the value of the "os" field. + Os string `json:"os,omitempty"` + // ExternalIP holds the value of the "external_ip" field. + ExternalIP string `json:"external_ip,omitempty"` + // InternalIP holds the value of the "internal_ip" field. + InternalIP string `json:"internal_ip,omitempty"` + // Version holds the value of the "version" field. + Version string `json:"version,omitempty"` + // MachineID holds the value of the "machine_id" field. + MachineID string `json:"machine_id,omitempty"` + // Remark holds the value of the "remark" field. + Remark string `json:"remark,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"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the HostQuery when eager-loading is set. + Edges HostEdges `json:"edges"` + selectValues sql.SelectValues +} + +// HostEdges holds the relations/edges for other nodes in the graph. +type HostEdges struct { + // Vms holds the value of the vms edge. + Vms []*VirtualMachine `json:"vms,omitempty"` + // User holds the value of the user edge. + User *User `json:"user,omitempty"` + // Groups holds the value of the groups edge. + Groups []*TeamGroup `json:"groups,omitempty"` + // TeamGroupHosts holds the value of the team_group_hosts edge. + TeamGroupHosts []*TeamGroupHost `json:"team_group_hosts,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [4]bool +} + +// VmsOrErr returns the Vms value or an error if the edge +// was not loaded in eager-loading. +func (e HostEdges) VmsOrErr() ([]*VirtualMachine, error) { + if e.loadedTypes[0] { + return e.Vms, nil + } + return nil, &NotLoadedError{edge: "vms"} +} + +// UserOrErr returns the User value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e HostEdges) UserOrErr() (*User, error) { + if e.User != nil { + return e.User, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: user.Label} + } + return nil, &NotLoadedError{edge: "user"} +} + +// GroupsOrErr returns the Groups value or an error if the edge +// was not loaded in eager-loading. +func (e HostEdges) GroupsOrErr() ([]*TeamGroup, error) { + if e.loadedTypes[2] { + return e.Groups, nil + } + return nil, &NotLoadedError{edge: "groups"} +} + +// TeamGroupHostsOrErr returns the TeamGroupHosts value or an error if the edge +// was not loaded in eager-loading. +func (e HostEdges) TeamGroupHostsOrErr() ([]*TeamGroupHost, error) { + if e.loadedTypes[3] { + return e.TeamGroupHosts, nil + } + return nil, &NotLoadedError{edge: "team_group_hosts"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Host) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case host.FieldCores, host.FieldWeight, host.FieldMemory, host.FieldDisk: + values[i] = new(sql.NullInt64) + case host.FieldID, host.FieldHostname, host.FieldArch, host.FieldOs, host.FieldExternalIP, host.FieldInternalIP, host.FieldVersion, host.FieldMachineID, host.FieldRemark: + values[i] = new(sql.NullString) + case host.FieldDeletedAt, host.FieldCreatedAt, host.FieldUpdatedAt: + values[i] = new(sql.NullTime) + case host.FieldUserID: + values[i] = new(uuid.UUID) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the Host fields. +func (_m *Host) 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 host.FieldID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value.Valid { + _m.ID = value.String + } + case host.FieldDeletedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field deleted_at", values[i]) + } else if value.Valid { + _m.DeletedAt = value.Time + } + case host.FieldUserID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field user_id", values[i]) + } else if value != nil { + _m.UserID = *value + } + case host.FieldHostname: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field hostname", values[i]) + } else if value.Valid { + _m.Hostname = value.String + } + case host.FieldArch: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field arch", values[i]) + } else if value.Valid { + _m.Arch = value.String + } + case host.FieldCores: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field cores", values[i]) + } else if value.Valid { + _m.Cores = int(value.Int64) + } + case host.FieldWeight: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field weight", values[i]) + } else if value.Valid { + _m.Weight = int(value.Int64) + } + case host.FieldMemory: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field memory", values[i]) + } else if value.Valid { + _m.Memory = value.Int64 + } + case host.FieldDisk: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field disk", values[i]) + } else if value.Valid { + _m.Disk = value.Int64 + } + case host.FieldOs: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field os", values[i]) + } else if value.Valid { + _m.Os = value.String + } + case host.FieldExternalIP: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field external_ip", values[i]) + } else if value.Valid { + _m.ExternalIP = value.String + } + case host.FieldInternalIP: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field internal_ip", values[i]) + } else if value.Valid { + _m.InternalIP = value.String + } + case host.FieldVersion: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field version", values[i]) + } else if value.Valid { + _m.Version = value.String + } + case host.FieldMachineID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field machine_id", values[i]) + } else if value.Valid { + _m.MachineID = value.String + } + case host.FieldRemark: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field remark", values[i]) + } else if value.Valid { + _m.Remark = value.String + } + case host.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + case host.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 { + _m.UpdatedAt = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Host. +// This includes values selected through modifiers, order, etc. +func (_m *Host) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryVms queries the "vms" edge of the Host entity. +func (_m *Host) QueryVms() *VirtualMachineQuery { + return NewHostClient(_m.config).QueryVms(_m) +} + +// QueryUser queries the "user" edge of the Host entity. +func (_m *Host) QueryUser() *UserQuery { + return NewHostClient(_m.config).QueryUser(_m) +} + +// QueryGroups queries the "groups" edge of the Host entity. +func (_m *Host) QueryGroups() *TeamGroupQuery { + return NewHostClient(_m.config).QueryGroups(_m) +} + +// QueryTeamGroupHosts queries the "team_group_hosts" edge of the Host entity. +func (_m *Host) QueryTeamGroupHosts() *TeamGroupHostQuery { + return NewHostClient(_m.config).QueryTeamGroupHosts(_m) +} + +// Update returns a builder for updating this Host. +// Note that you need to call Host.Unwrap() before calling this method if this Host +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *Host) Update() *HostUpdateOne { + return NewHostClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the Host entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *Host) Unwrap() *Host { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: Host is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *Host) String() string { + var builder strings.Builder + builder.WriteString("Host(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("deleted_at=") + builder.WriteString(_m.DeletedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("user_id=") + builder.WriteString(fmt.Sprintf("%v", _m.UserID)) + builder.WriteString(", ") + builder.WriteString("hostname=") + builder.WriteString(_m.Hostname) + builder.WriteString(", ") + builder.WriteString("arch=") + builder.WriteString(_m.Arch) + builder.WriteString(", ") + builder.WriteString("cores=") + builder.WriteString(fmt.Sprintf("%v", _m.Cores)) + builder.WriteString(", ") + builder.WriteString("weight=") + builder.WriteString(fmt.Sprintf("%v", _m.Weight)) + builder.WriteString(", ") + builder.WriteString("memory=") + builder.WriteString(fmt.Sprintf("%v", _m.Memory)) + builder.WriteString(", ") + builder.WriteString("disk=") + builder.WriteString(fmt.Sprintf("%v", _m.Disk)) + builder.WriteString(", ") + builder.WriteString("os=") + builder.WriteString(_m.Os) + builder.WriteString(", ") + builder.WriteString("external_ip=") + builder.WriteString(_m.ExternalIP) + builder.WriteString(", ") + builder.WriteString("internal_ip=") + builder.WriteString(_m.InternalIP) + builder.WriteString(", ") + builder.WriteString("version=") + builder.WriteString(_m.Version) + builder.WriteString(", ") + builder.WriteString("machine_id=") + builder.WriteString(_m.MachineID) + builder.WriteString(", ") + builder.WriteString("remark=") + builder.WriteString(_m.Remark) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("updated_at=") + builder.WriteString(_m.UpdatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// Hosts is a parsable slice of Host. +type Hosts []*Host diff --git a/backend/db/host/host.go b/backend/db/host/host.go new file mode 100644 index 00000000..b8dc026f --- /dev/null +++ b/backend/db/host/host.go @@ -0,0 +1,306 @@ +// Code generated by ent, DO NOT EDIT. + +package host + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the host type in the database. + Label = "host" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldDeletedAt holds the string denoting the deleted_at field in the database. + FieldDeletedAt = "deleted_at" + // FieldUserID holds the string denoting the user_id field in the database. + FieldUserID = "user_id" + // FieldHostname holds the string denoting the hostname field in the database. + FieldHostname = "hostname" + // FieldArch holds the string denoting the arch field in the database. + FieldArch = "arch" + // FieldCores holds the string denoting the cores field in the database. + FieldCores = "cores" + // FieldWeight holds the string denoting the weight field in the database. + FieldWeight = "weight" + // FieldMemory holds the string denoting the memory field in the database. + FieldMemory = "memory" + // FieldDisk holds the string denoting the disk field in the database. + FieldDisk = "disk" + // FieldOs holds the string denoting the os field in the database. + FieldOs = "os" + // FieldExternalIP holds the string denoting the external_ip field in the database. + FieldExternalIP = "external_ip" + // FieldInternalIP holds the string denoting the internal_ip field in the database. + FieldInternalIP = "internal_ip" + // FieldVersion holds the string denoting the version field in the database. + FieldVersion = "version" + // FieldMachineID holds the string denoting the machine_id field in the database. + FieldMachineID = "machine_id" + // FieldRemark holds the string denoting the remark field in the database. + FieldRemark = "remark" + // 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" + // EdgeVms holds the string denoting the vms edge name in mutations. + EdgeVms = "vms" + // EdgeUser holds the string denoting the user edge name in mutations. + EdgeUser = "user" + // EdgeGroups holds the string denoting the groups edge name in mutations. + EdgeGroups = "groups" + // EdgeTeamGroupHosts holds the string denoting the team_group_hosts edge name in mutations. + EdgeTeamGroupHosts = "team_group_hosts" + // Table holds the table name of the host in the database. + Table = "hosts" + // VmsTable is the table that holds the vms relation/edge. + VmsTable = "virtualmachines" + // VmsInverseTable is the table name for the VirtualMachine entity. + // It exists in this package in order to avoid circular dependency with the "virtualmachine" package. + VmsInverseTable = "virtualmachines" + // VmsColumn is the table column denoting the vms relation/edge. + VmsColumn = "host_id" + // UserTable is the table that holds the user relation/edge. + UserTable = "hosts" + // UserInverseTable is the table name for the User entity. + // It exists in this package in order to avoid circular dependency with the "user" package. + UserInverseTable = "users" + // UserColumn is the table column denoting the user relation/edge. + UserColumn = "user_id" + // GroupsTable is the table that holds the groups relation/edge. The primary key declared below. + GroupsTable = "team_group_hosts" + // GroupsInverseTable is the table name for the TeamGroup entity. + // It exists in this package in order to avoid circular dependency with the "teamgroup" package. + GroupsInverseTable = "team_groups" + // TeamGroupHostsTable is the table that holds the team_group_hosts relation/edge. + TeamGroupHostsTable = "team_group_hosts" + // TeamGroupHostsInverseTable is the table name for the TeamGroupHost entity. + // It exists in this package in order to avoid circular dependency with the "teamgrouphost" package. + TeamGroupHostsInverseTable = "team_group_hosts" + // TeamGroupHostsColumn is the table column denoting the team_group_hosts relation/edge. + TeamGroupHostsColumn = "host_id" +) + +// Columns holds all SQL columns for host fields. +var Columns = []string{ + FieldID, + FieldDeletedAt, + FieldUserID, + FieldHostname, + FieldArch, + FieldCores, + FieldWeight, + FieldMemory, + FieldDisk, + FieldOs, + FieldExternalIP, + FieldInternalIP, + FieldVersion, + FieldMachineID, + FieldRemark, + FieldCreatedAt, + FieldUpdatedAt, +} + +var ( + // GroupsPrimaryKey and GroupsColumn2 are the table columns denoting the + // primary key for the groups relation (M2M). + GroupsPrimaryKey = []string{"group_id", "host_id"} +) + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +// Note that the variables below are initialized by the runtime +// package on the initialization of the application. Therefore, +// it should be imported in the main as follows: +// +// import _ "github.com/chaitin/MonkeyCode/backend/db/runtime" +var ( + Hooks [1]ent.Hook + Interceptors [1]ent.Interceptor + // DefaultWeight holds the default value on creation for the "weight" field. + DefaultWeight int + // 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 +) + +// OrderOption defines the ordering options for the Host queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByDeletedAt orders the results by the deleted_at field. +func ByDeletedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDeletedAt, opts...).ToFunc() +} + +// ByUserID orders the results by the user_id field. +func ByUserID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUserID, opts...).ToFunc() +} + +// ByHostname orders the results by the hostname field. +func ByHostname(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldHostname, opts...).ToFunc() +} + +// ByArch orders the results by the arch field. +func ByArch(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldArch, opts...).ToFunc() +} + +// ByCores orders the results by the cores field. +func ByCores(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCores, opts...).ToFunc() +} + +// ByWeight orders the results by the weight field. +func ByWeight(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldWeight, opts...).ToFunc() +} + +// ByMemory orders the results by the memory field. +func ByMemory(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMemory, opts...).ToFunc() +} + +// ByDisk orders the results by the disk field. +func ByDisk(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDisk, opts...).ToFunc() +} + +// ByOs orders the results by the os field. +func ByOs(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldOs, opts...).ToFunc() +} + +// ByExternalIP orders the results by the external_ip field. +func ByExternalIP(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldExternalIP, opts...).ToFunc() +} + +// ByInternalIP orders the results by the internal_ip field. +func ByInternalIP(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInternalIP, opts...).ToFunc() +} + +// ByVersion orders the results by the version field. +func ByVersion(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldVersion, opts...).ToFunc() +} + +// ByMachineID orders the results by the machine_id field. +func ByMachineID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMachineID, opts...).ToFunc() +} + +// ByRemark orders the results by the remark field. +func ByRemark(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRemark, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByUpdatedAt orders the results by the updated_at field. +func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() +} + +// ByVmsCount orders the results by vms count. +func ByVmsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newVmsStep(), opts...) + } +} + +// ByVms orders the results by vms terms. +func ByVms(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newVmsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByUserField orders the results by user field. +func ByUserField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newUserStep(), sql.OrderByField(field, opts...)) + } +} + +// ByGroupsCount orders the results by groups count. +func ByGroupsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newGroupsStep(), opts...) + } +} + +// ByGroups orders the results by groups terms. +func ByGroups(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newGroupsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByTeamGroupHostsCount orders the results by team_group_hosts count. +func ByTeamGroupHostsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newTeamGroupHostsStep(), opts...) + } +} + +// ByTeamGroupHosts orders the results by team_group_hosts terms. +func ByTeamGroupHosts(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newTeamGroupHostsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newVmsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(VmsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, VmsTable, VmsColumn), + ) +} +func newUserStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UserInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn), + ) +} +func newGroupsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(GroupsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, GroupsTable, GroupsPrimaryKey...), + ) +} +func newTeamGroupHostsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TeamGroupHostsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, TeamGroupHostsTable, TeamGroupHostsColumn), + ) +} diff --git a/backend/db/host/where.go b/backend/db/host/where.go new file mode 100644 index 00000000..04f3f980 --- /dev/null +++ b/backend/db/host/where.go @@ -0,0 +1,1194 @@ +// Code generated by ent, DO NOT EDIT. + +package host + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.Host { + return predicate.Host(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.Host { + return predicate.Host(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.Host { + return predicate.Host(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.Host { + return predicate.Host(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.Host { + return predicate.Host(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.Host { + return predicate.Host(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.Host { + return predicate.Host(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.Host { + return predicate.Host(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.Host { + return predicate.Host(sql.FieldContainsFold(FieldID, id)) +} + +// DeletedAt applies equality check predicate on the "deleted_at" field. It's identical to DeletedAtEQ. +func DeletedAt(v time.Time) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldDeletedAt, v)) +} + +// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. +func UserID(v uuid.UUID) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldUserID, v)) +} + +// Hostname applies equality check predicate on the "hostname" field. It's identical to HostnameEQ. +func Hostname(v string) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldHostname, v)) +} + +// Arch applies equality check predicate on the "arch" field. It's identical to ArchEQ. +func Arch(v string) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldArch, v)) +} + +// Cores applies equality check predicate on the "cores" field. It's identical to CoresEQ. +func Cores(v int) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldCores, v)) +} + +// Weight applies equality check predicate on the "weight" field. It's identical to WeightEQ. +func Weight(v int) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldWeight, v)) +} + +// Memory applies equality check predicate on the "memory" field. It's identical to MemoryEQ. +func Memory(v int64) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldMemory, v)) +} + +// Disk applies equality check predicate on the "disk" field. It's identical to DiskEQ. +func Disk(v int64) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldDisk, v)) +} + +// Os applies equality check predicate on the "os" field. It's identical to OsEQ. +func Os(v string) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldOs, v)) +} + +// ExternalIP applies equality check predicate on the "external_ip" field. It's identical to ExternalIPEQ. +func ExternalIP(v string) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldExternalIP, v)) +} + +// InternalIP applies equality check predicate on the "internal_ip" field. It's identical to InternalIPEQ. +func InternalIP(v string) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldInternalIP, v)) +} + +// Version applies equality check predicate on the "version" field. It's identical to VersionEQ. +func Version(v string) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldVersion, v)) +} + +// MachineID applies equality check predicate on the "machine_id" field. It's identical to MachineIDEQ. +func MachineID(v string) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldMachineID, v)) +} + +// Remark applies equality check predicate on the "remark" field. It's identical to RemarkEQ. +func Remark(v string) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldRemark, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldCreatedAt, v)) +} + +// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. +func UpdatedAt(v time.Time) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.Host { + return predicate.Host(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.Host { + return predicate.Host(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.Host { + return predicate.Host(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.Host { + return predicate.Host(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.Host { + return predicate.Host(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.Host { + return predicate.Host(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.Host { + return predicate.Host(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.Host { + return predicate.Host(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.Host { + return predicate.Host(sql.FieldNotNull(FieldDeletedAt)) +} + +// UserIDEQ applies the EQ predicate on the "user_id" field. +func UserIDEQ(v uuid.UUID) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldUserID, v)) +} + +// UserIDNEQ applies the NEQ predicate on the "user_id" field. +func UserIDNEQ(v uuid.UUID) predicate.Host { + return predicate.Host(sql.FieldNEQ(FieldUserID, v)) +} + +// UserIDIn applies the In predicate on the "user_id" field. +func UserIDIn(vs ...uuid.UUID) predicate.Host { + return predicate.Host(sql.FieldIn(FieldUserID, vs...)) +} + +// UserIDNotIn applies the NotIn predicate on the "user_id" field. +func UserIDNotIn(vs ...uuid.UUID) predicate.Host { + return predicate.Host(sql.FieldNotIn(FieldUserID, vs...)) +} + +// HostnameEQ applies the EQ predicate on the "hostname" field. +func HostnameEQ(v string) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldHostname, v)) +} + +// HostnameNEQ applies the NEQ predicate on the "hostname" field. +func HostnameNEQ(v string) predicate.Host { + return predicate.Host(sql.FieldNEQ(FieldHostname, v)) +} + +// HostnameIn applies the In predicate on the "hostname" field. +func HostnameIn(vs ...string) predicate.Host { + return predicate.Host(sql.FieldIn(FieldHostname, vs...)) +} + +// HostnameNotIn applies the NotIn predicate on the "hostname" field. +func HostnameNotIn(vs ...string) predicate.Host { + return predicate.Host(sql.FieldNotIn(FieldHostname, vs...)) +} + +// HostnameGT applies the GT predicate on the "hostname" field. +func HostnameGT(v string) predicate.Host { + return predicate.Host(sql.FieldGT(FieldHostname, v)) +} + +// HostnameGTE applies the GTE predicate on the "hostname" field. +func HostnameGTE(v string) predicate.Host { + return predicate.Host(sql.FieldGTE(FieldHostname, v)) +} + +// HostnameLT applies the LT predicate on the "hostname" field. +func HostnameLT(v string) predicate.Host { + return predicate.Host(sql.FieldLT(FieldHostname, v)) +} + +// HostnameLTE applies the LTE predicate on the "hostname" field. +func HostnameLTE(v string) predicate.Host { + return predicate.Host(sql.FieldLTE(FieldHostname, v)) +} + +// HostnameContains applies the Contains predicate on the "hostname" field. +func HostnameContains(v string) predicate.Host { + return predicate.Host(sql.FieldContains(FieldHostname, v)) +} + +// HostnameHasPrefix applies the HasPrefix predicate on the "hostname" field. +func HostnameHasPrefix(v string) predicate.Host { + return predicate.Host(sql.FieldHasPrefix(FieldHostname, v)) +} + +// HostnameHasSuffix applies the HasSuffix predicate on the "hostname" field. +func HostnameHasSuffix(v string) predicate.Host { + return predicate.Host(sql.FieldHasSuffix(FieldHostname, v)) +} + +// HostnameIsNil applies the IsNil predicate on the "hostname" field. +func HostnameIsNil() predicate.Host { + return predicate.Host(sql.FieldIsNull(FieldHostname)) +} + +// HostnameNotNil applies the NotNil predicate on the "hostname" field. +func HostnameNotNil() predicate.Host { + return predicate.Host(sql.FieldNotNull(FieldHostname)) +} + +// HostnameEqualFold applies the EqualFold predicate on the "hostname" field. +func HostnameEqualFold(v string) predicate.Host { + return predicate.Host(sql.FieldEqualFold(FieldHostname, v)) +} + +// HostnameContainsFold applies the ContainsFold predicate on the "hostname" field. +func HostnameContainsFold(v string) predicate.Host { + return predicate.Host(sql.FieldContainsFold(FieldHostname, v)) +} + +// ArchEQ applies the EQ predicate on the "arch" field. +func ArchEQ(v string) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldArch, v)) +} + +// ArchNEQ applies the NEQ predicate on the "arch" field. +func ArchNEQ(v string) predicate.Host { + return predicate.Host(sql.FieldNEQ(FieldArch, v)) +} + +// ArchIn applies the In predicate on the "arch" field. +func ArchIn(vs ...string) predicate.Host { + return predicate.Host(sql.FieldIn(FieldArch, vs...)) +} + +// ArchNotIn applies the NotIn predicate on the "arch" field. +func ArchNotIn(vs ...string) predicate.Host { + return predicate.Host(sql.FieldNotIn(FieldArch, vs...)) +} + +// ArchGT applies the GT predicate on the "arch" field. +func ArchGT(v string) predicate.Host { + return predicate.Host(sql.FieldGT(FieldArch, v)) +} + +// ArchGTE applies the GTE predicate on the "arch" field. +func ArchGTE(v string) predicate.Host { + return predicate.Host(sql.FieldGTE(FieldArch, v)) +} + +// ArchLT applies the LT predicate on the "arch" field. +func ArchLT(v string) predicate.Host { + return predicate.Host(sql.FieldLT(FieldArch, v)) +} + +// ArchLTE applies the LTE predicate on the "arch" field. +func ArchLTE(v string) predicate.Host { + return predicate.Host(sql.FieldLTE(FieldArch, v)) +} + +// ArchContains applies the Contains predicate on the "arch" field. +func ArchContains(v string) predicate.Host { + return predicate.Host(sql.FieldContains(FieldArch, v)) +} + +// ArchHasPrefix applies the HasPrefix predicate on the "arch" field. +func ArchHasPrefix(v string) predicate.Host { + return predicate.Host(sql.FieldHasPrefix(FieldArch, v)) +} + +// ArchHasSuffix applies the HasSuffix predicate on the "arch" field. +func ArchHasSuffix(v string) predicate.Host { + return predicate.Host(sql.FieldHasSuffix(FieldArch, v)) +} + +// ArchIsNil applies the IsNil predicate on the "arch" field. +func ArchIsNil() predicate.Host { + return predicate.Host(sql.FieldIsNull(FieldArch)) +} + +// ArchNotNil applies the NotNil predicate on the "arch" field. +func ArchNotNil() predicate.Host { + return predicate.Host(sql.FieldNotNull(FieldArch)) +} + +// ArchEqualFold applies the EqualFold predicate on the "arch" field. +func ArchEqualFold(v string) predicate.Host { + return predicate.Host(sql.FieldEqualFold(FieldArch, v)) +} + +// ArchContainsFold applies the ContainsFold predicate on the "arch" field. +func ArchContainsFold(v string) predicate.Host { + return predicate.Host(sql.FieldContainsFold(FieldArch, v)) +} + +// CoresEQ applies the EQ predicate on the "cores" field. +func CoresEQ(v int) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldCores, v)) +} + +// CoresNEQ applies the NEQ predicate on the "cores" field. +func CoresNEQ(v int) predicate.Host { + return predicate.Host(sql.FieldNEQ(FieldCores, v)) +} + +// CoresIn applies the In predicate on the "cores" field. +func CoresIn(vs ...int) predicate.Host { + return predicate.Host(sql.FieldIn(FieldCores, vs...)) +} + +// CoresNotIn applies the NotIn predicate on the "cores" field. +func CoresNotIn(vs ...int) predicate.Host { + return predicate.Host(sql.FieldNotIn(FieldCores, vs...)) +} + +// CoresGT applies the GT predicate on the "cores" field. +func CoresGT(v int) predicate.Host { + return predicate.Host(sql.FieldGT(FieldCores, v)) +} + +// CoresGTE applies the GTE predicate on the "cores" field. +func CoresGTE(v int) predicate.Host { + return predicate.Host(sql.FieldGTE(FieldCores, v)) +} + +// CoresLT applies the LT predicate on the "cores" field. +func CoresLT(v int) predicate.Host { + return predicate.Host(sql.FieldLT(FieldCores, v)) +} + +// CoresLTE applies the LTE predicate on the "cores" field. +func CoresLTE(v int) predicate.Host { + return predicate.Host(sql.FieldLTE(FieldCores, v)) +} + +// CoresIsNil applies the IsNil predicate on the "cores" field. +func CoresIsNil() predicate.Host { + return predicate.Host(sql.FieldIsNull(FieldCores)) +} + +// CoresNotNil applies the NotNil predicate on the "cores" field. +func CoresNotNil() predicate.Host { + return predicate.Host(sql.FieldNotNull(FieldCores)) +} + +// WeightEQ applies the EQ predicate on the "weight" field. +func WeightEQ(v int) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldWeight, v)) +} + +// WeightNEQ applies the NEQ predicate on the "weight" field. +func WeightNEQ(v int) predicate.Host { + return predicate.Host(sql.FieldNEQ(FieldWeight, v)) +} + +// WeightIn applies the In predicate on the "weight" field. +func WeightIn(vs ...int) predicate.Host { + return predicate.Host(sql.FieldIn(FieldWeight, vs...)) +} + +// WeightNotIn applies the NotIn predicate on the "weight" field. +func WeightNotIn(vs ...int) predicate.Host { + return predicate.Host(sql.FieldNotIn(FieldWeight, vs...)) +} + +// WeightGT applies the GT predicate on the "weight" field. +func WeightGT(v int) predicate.Host { + return predicate.Host(sql.FieldGT(FieldWeight, v)) +} + +// WeightGTE applies the GTE predicate on the "weight" field. +func WeightGTE(v int) predicate.Host { + return predicate.Host(sql.FieldGTE(FieldWeight, v)) +} + +// WeightLT applies the LT predicate on the "weight" field. +func WeightLT(v int) predicate.Host { + return predicate.Host(sql.FieldLT(FieldWeight, v)) +} + +// WeightLTE applies the LTE predicate on the "weight" field. +func WeightLTE(v int) predicate.Host { + return predicate.Host(sql.FieldLTE(FieldWeight, v)) +} + +// MemoryEQ applies the EQ predicate on the "memory" field. +func MemoryEQ(v int64) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldMemory, v)) +} + +// MemoryNEQ applies the NEQ predicate on the "memory" field. +func MemoryNEQ(v int64) predicate.Host { + return predicate.Host(sql.FieldNEQ(FieldMemory, v)) +} + +// MemoryIn applies the In predicate on the "memory" field. +func MemoryIn(vs ...int64) predicate.Host { + return predicate.Host(sql.FieldIn(FieldMemory, vs...)) +} + +// MemoryNotIn applies the NotIn predicate on the "memory" field. +func MemoryNotIn(vs ...int64) predicate.Host { + return predicate.Host(sql.FieldNotIn(FieldMemory, vs...)) +} + +// MemoryGT applies the GT predicate on the "memory" field. +func MemoryGT(v int64) predicate.Host { + return predicate.Host(sql.FieldGT(FieldMemory, v)) +} + +// MemoryGTE applies the GTE predicate on the "memory" field. +func MemoryGTE(v int64) predicate.Host { + return predicate.Host(sql.FieldGTE(FieldMemory, v)) +} + +// MemoryLT applies the LT predicate on the "memory" field. +func MemoryLT(v int64) predicate.Host { + return predicate.Host(sql.FieldLT(FieldMemory, v)) +} + +// MemoryLTE applies the LTE predicate on the "memory" field. +func MemoryLTE(v int64) predicate.Host { + return predicate.Host(sql.FieldLTE(FieldMemory, v)) +} + +// MemoryIsNil applies the IsNil predicate on the "memory" field. +func MemoryIsNil() predicate.Host { + return predicate.Host(sql.FieldIsNull(FieldMemory)) +} + +// MemoryNotNil applies the NotNil predicate on the "memory" field. +func MemoryNotNil() predicate.Host { + return predicate.Host(sql.FieldNotNull(FieldMemory)) +} + +// DiskEQ applies the EQ predicate on the "disk" field. +func DiskEQ(v int64) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldDisk, v)) +} + +// DiskNEQ applies the NEQ predicate on the "disk" field. +func DiskNEQ(v int64) predicate.Host { + return predicate.Host(sql.FieldNEQ(FieldDisk, v)) +} + +// DiskIn applies the In predicate on the "disk" field. +func DiskIn(vs ...int64) predicate.Host { + return predicate.Host(sql.FieldIn(FieldDisk, vs...)) +} + +// DiskNotIn applies the NotIn predicate on the "disk" field. +func DiskNotIn(vs ...int64) predicate.Host { + return predicate.Host(sql.FieldNotIn(FieldDisk, vs...)) +} + +// DiskGT applies the GT predicate on the "disk" field. +func DiskGT(v int64) predicate.Host { + return predicate.Host(sql.FieldGT(FieldDisk, v)) +} + +// DiskGTE applies the GTE predicate on the "disk" field. +func DiskGTE(v int64) predicate.Host { + return predicate.Host(sql.FieldGTE(FieldDisk, v)) +} + +// DiskLT applies the LT predicate on the "disk" field. +func DiskLT(v int64) predicate.Host { + return predicate.Host(sql.FieldLT(FieldDisk, v)) +} + +// DiskLTE applies the LTE predicate on the "disk" field. +func DiskLTE(v int64) predicate.Host { + return predicate.Host(sql.FieldLTE(FieldDisk, v)) +} + +// DiskIsNil applies the IsNil predicate on the "disk" field. +func DiskIsNil() predicate.Host { + return predicate.Host(sql.FieldIsNull(FieldDisk)) +} + +// DiskNotNil applies the NotNil predicate on the "disk" field. +func DiskNotNil() predicate.Host { + return predicate.Host(sql.FieldNotNull(FieldDisk)) +} + +// OsEQ applies the EQ predicate on the "os" field. +func OsEQ(v string) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldOs, v)) +} + +// OsNEQ applies the NEQ predicate on the "os" field. +func OsNEQ(v string) predicate.Host { + return predicate.Host(sql.FieldNEQ(FieldOs, v)) +} + +// OsIn applies the In predicate on the "os" field. +func OsIn(vs ...string) predicate.Host { + return predicate.Host(sql.FieldIn(FieldOs, vs...)) +} + +// OsNotIn applies the NotIn predicate on the "os" field. +func OsNotIn(vs ...string) predicate.Host { + return predicate.Host(sql.FieldNotIn(FieldOs, vs...)) +} + +// OsGT applies the GT predicate on the "os" field. +func OsGT(v string) predicate.Host { + return predicate.Host(sql.FieldGT(FieldOs, v)) +} + +// OsGTE applies the GTE predicate on the "os" field. +func OsGTE(v string) predicate.Host { + return predicate.Host(sql.FieldGTE(FieldOs, v)) +} + +// OsLT applies the LT predicate on the "os" field. +func OsLT(v string) predicate.Host { + return predicate.Host(sql.FieldLT(FieldOs, v)) +} + +// OsLTE applies the LTE predicate on the "os" field. +func OsLTE(v string) predicate.Host { + return predicate.Host(sql.FieldLTE(FieldOs, v)) +} + +// OsContains applies the Contains predicate on the "os" field. +func OsContains(v string) predicate.Host { + return predicate.Host(sql.FieldContains(FieldOs, v)) +} + +// OsHasPrefix applies the HasPrefix predicate on the "os" field. +func OsHasPrefix(v string) predicate.Host { + return predicate.Host(sql.FieldHasPrefix(FieldOs, v)) +} + +// OsHasSuffix applies the HasSuffix predicate on the "os" field. +func OsHasSuffix(v string) predicate.Host { + return predicate.Host(sql.FieldHasSuffix(FieldOs, v)) +} + +// OsIsNil applies the IsNil predicate on the "os" field. +func OsIsNil() predicate.Host { + return predicate.Host(sql.FieldIsNull(FieldOs)) +} + +// OsNotNil applies the NotNil predicate on the "os" field. +func OsNotNil() predicate.Host { + return predicate.Host(sql.FieldNotNull(FieldOs)) +} + +// OsEqualFold applies the EqualFold predicate on the "os" field. +func OsEqualFold(v string) predicate.Host { + return predicate.Host(sql.FieldEqualFold(FieldOs, v)) +} + +// OsContainsFold applies the ContainsFold predicate on the "os" field. +func OsContainsFold(v string) predicate.Host { + return predicate.Host(sql.FieldContainsFold(FieldOs, v)) +} + +// ExternalIPEQ applies the EQ predicate on the "external_ip" field. +func ExternalIPEQ(v string) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldExternalIP, v)) +} + +// ExternalIPNEQ applies the NEQ predicate on the "external_ip" field. +func ExternalIPNEQ(v string) predicate.Host { + return predicate.Host(sql.FieldNEQ(FieldExternalIP, v)) +} + +// ExternalIPIn applies the In predicate on the "external_ip" field. +func ExternalIPIn(vs ...string) predicate.Host { + return predicate.Host(sql.FieldIn(FieldExternalIP, vs...)) +} + +// ExternalIPNotIn applies the NotIn predicate on the "external_ip" field. +func ExternalIPNotIn(vs ...string) predicate.Host { + return predicate.Host(sql.FieldNotIn(FieldExternalIP, vs...)) +} + +// ExternalIPGT applies the GT predicate on the "external_ip" field. +func ExternalIPGT(v string) predicate.Host { + return predicate.Host(sql.FieldGT(FieldExternalIP, v)) +} + +// ExternalIPGTE applies the GTE predicate on the "external_ip" field. +func ExternalIPGTE(v string) predicate.Host { + return predicate.Host(sql.FieldGTE(FieldExternalIP, v)) +} + +// ExternalIPLT applies the LT predicate on the "external_ip" field. +func ExternalIPLT(v string) predicate.Host { + return predicate.Host(sql.FieldLT(FieldExternalIP, v)) +} + +// ExternalIPLTE applies the LTE predicate on the "external_ip" field. +func ExternalIPLTE(v string) predicate.Host { + return predicate.Host(sql.FieldLTE(FieldExternalIP, v)) +} + +// ExternalIPContains applies the Contains predicate on the "external_ip" field. +func ExternalIPContains(v string) predicate.Host { + return predicate.Host(sql.FieldContains(FieldExternalIP, v)) +} + +// ExternalIPHasPrefix applies the HasPrefix predicate on the "external_ip" field. +func ExternalIPHasPrefix(v string) predicate.Host { + return predicate.Host(sql.FieldHasPrefix(FieldExternalIP, v)) +} + +// ExternalIPHasSuffix applies the HasSuffix predicate on the "external_ip" field. +func ExternalIPHasSuffix(v string) predicate.Host { + return predicate.Host(sql.FieldHasSuffix(FieldExternalIP, v)) +} + +// ExternalIPIsNil applies the IsNil predicate on the "external_ip" field. +func ExternalIPIsNil() predicate.Host { + return predicate.Host(sql.FieldIsNull(FieldExternalIP)) +} + +// ExternalIPNotNil applies the NotNil predicate on the "external_ip" field. +func ExternalIPNotNil() predicate.Host { + return predicate.Host(sql.FieldNotNull(FieldExternalIP)) +} + +// ExternalIPEqualFold applies the EqualFold predicate on the "external_ip" field. +func ExternalIPEqualFold(v string) predicate.Host { + return predicate.Host(sql.FieldEqualFold(FieldExternalIP, v)) +} + +// ExternalIPContainsFold applies the ContainsFold predicate on the "external_ip" field. +func ExternalIPContainsFold(v string) predicate.Host { + return predicate.Host(sql.FieldContainsFold(FieldExternalIP, v)) +} + +// InternalIPEQ applies the EQ predicate on the "internal_ip" field. +func InternalIPEQ(v string) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldInternalIP, v)) +} + +// InternalIPNEQ applies the NEQ predicate on the "internal_ip" field. +func InternalIPNEQ(v string) predicate.Host { + return predicate.Host(sql.FieldNEQ(FieldInternalIP, v)) +} + +// InternalIPIn applies the In predicate on the "internal_ip" field. +func InternalIPIn(vs ...string) predicate.Host { + return predicate.Host(sql.FieldIn(FieldInternalIP, vs...)) +} + +// InternalIPNotIn applies the NotIn predicate on the "internal_ip" field. +func InternalIPNotIn(vs ...string) predicate.Host { + return predicate.Host(sql.FieldNotIn(FieldInternalIP, vs...)) +} + +// InternalIPGT applies the GT predicate on the "internal_ip" field. +func InternalIPGT(v string) predicate.Host { + return predicate.Host(sql.FieldGT(FieldInternalIP, v)) +} + +// InternalIPGTE applies the GTE predicate on the "internal_ip" field. +func InternalIPGTE(v string) predicate.Host { + return predicate.Host(sql.FieldGTE(FieldInternalIP, v)) +} + +// InternalIPLT applies the LT predicate on the "internal_ip" field. +func InternalIPLT(v string) predicate.Host { + return predicate.Host(sql.FieldLT(FieldInternalIP, v)) +} + +// InternalIPLTE applies the LTE predicate on the "internal_ip" field. +func InternalIPLTE(v string) predicate.Host { + return predicate.Host(sql.FieldLTE(FieldInternalIP, v)) +} + +// InternalIPContains applies the Contains predicate on the "internal_ip" field. +func InternalIPContains(v string) predicate.Host { + return predicate.Host(sql.FieldContains(FieldInternalIP, v)) +} + +// InternalIPHasPrefix applies the HasPrefix predicate on the "internal_ip" field. +func InternalIPHasPrefix(v string) predicate.Host { + return predicate.Host(sql.FieldHasPrefix(FieldInternalIP, v)) +} + +// InternalIPHasSuffix applies the HasSuffix predicate on the "internal_ip" field. +func InternalIPHasSuffix(v string) predicate.Host { + return predicate.Host(sql.FieldHasSuffix(FieldInternalIP, v)) +} + +// InternalIPIsNil applies the IsNil predicate on the "internal_ip" field. +func InternalIPIsNil() predicate.Host { + return predicate.Host(sql.FieldIsNull(FieldInternalIP)) +} + +// InternalIPNotNil applies the NotNil predicate on the "internal_ip" field. +func InternalIPNotNil() predicate.Host { + return predicate.Host(sql.FieldNotNull(FieldInternalIP)) +} + +// InternalIPEqualFold applies the EqualFold predicate on the "internal_ip" field. +func InternalIPEqualFold(v string) predicate.Host { + return predicate.Host(sql.FieldEqualFold(FieldInternalIP, v)) +} + +// InternalIPContainsFold applies the ContainsFold predicate on the "internal_ip" field. +func InternalIPContainsFold(v string) predicate.Host { + return predicate.Host(sql.FieldContainsFold(FieldInternalIP, v)) +} + +// VersionEQ applies the EQ predicate on the "version" field. +func VersionEQ(v string) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldVersion, v)) +} + +// VersionNEQ applies the NEQ predicate on the "version" field. +func VersionNEQ(v string) predicate.Host { + return predicate.Host(sql.FieldNEQ(FieldVersion, v)) +} + +// VersionIn applies the In predicate on the "version" field. +func VersionIn(vs ...string) predicate.Host { + return predicate.Host(sql.FieldIn(FieldVersion, vs...)) +} + +// VersionNotIn applies the NotIn predicate on the "version" field. +func VersionNotIn(vs ...string) predicate.Host { + return predicate.Host(sql.FieldNotIn(FieldVersion, vs...)) +} + +// VersionGT applies the GT predicate on the "version" field. +func VersionGT(v string) predicate.Host { + return predicate.Host(sql.FieldGT(FieldVersion, v)) +} + +// VersionGTE applies the GTE predicate on the "version" field. +func VersionGTE(v string) predicate.Host { + return predicate.Host(sql.FieldGTE(FieldVersion, v)) +} + +// VersionLT applies the LT predicate on the "version" field. +func VersionLT(v string) predicate.Host { + return predicate.Host(sql.FieldLT(FieldVersion, v)) +} + +// VersionLTE applies the LTE predicate on the "version" field. +func VersionLTE(v string) predicate.Host { + return predicate.Host(sql.FieldLTE(FieldVersion, v)) +} + +// VersionContains applies the Contains predicate on the "version" field. +func VersionContains(v string) predicate.Host { + return predicate.Host(sql.FieldContains(FieldVersion, v)) +} + +// VersionHasPrefix applies the HasPrefix predicate on the "version" field. +func VersionHasPrefix(v string) predicate.Host { + return predicate.Host(sql.FieldHasPrefix(FieldVersion, v)) +} + +// VersionHasSuffix applies the HasSuffix predicate on the "version" field. +func VersionHasSuffix(v string) predicate.Host { + return predicate.Host(sql.FieldHasSuffix(FieldVersion, v)) +} + +// VersionIsNil applies the IsNil predicate on the "version" field. +func VersionIsNil() predicate.Host { + return predicate.Host(sql.FieldIsNull(FieldVersion)) +} + +// VersionNotNil applies the NotNil predicate on the "version" field. +func VersionNotNil() predicate.Host { + return predicate.Host(sql.FieldNotNull(FieldVersion)) +} + +// VersionEqualFold applies the EqualFold predicate on the "version" field. +func VersionEqualFold(v string) predicate.Host { + return predicate.Host(sql.FieldEqualFold(FieldVersion, v)) +} + +// VersionContainsFold applies the ContainsFold predicate on the "version" field. +func VersionContainsFold(v string) predicate.Host { + return predicate.Host(sql.FieldContainsFold(FieldVersion, v)) +} + +// MachineIDEQ applies the EQ predicate on the "machine_id" field. +func MachineIDEQ(v string) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldMachineID, v)) +} + +// MachineIDNEQ applies the NEQ predicate on the "machine_id" field. +func MachineIDNEQ(v string) predicate.Host { + return predicate.Host(sql.FieldNEQ(FieldMachineID, v)) +} + +// MachineIDIn applies the In predicate on the "machine_id" field. +func MachineIDIn(vs ...string) predicate.Host { + return predicate.Host(sql.FieldIn(FieldMachineID, vs...)) +} + +// MachineIDNotIn applies the NotIn predicate on the "machine_id" field. +func MachineIDNotIn(vs ...string) predicate.Host { + return predicate.Host(sql.FieldNotIn(FieldMachineID, vs...)) +} + +// MachineIDGT applies the GT predicate on the "machine_id" field. +func MachineIDGT(v string) predicate.Host { + return predicate.Host(sql.FieldGT(FieldMachineID, v)) +} + +// MachineIDGTE applies the GTE predicate on the "machine_id" field. +func MachineIDGTE(v string) predicate.Host { + return predicate.Host(sql.FieldGTE(FieldMachineID, v)) +} + +// MachineIDLT applies the LT predicate on the "machine_id" field. +func MachineIDLT(v string) predicate.Host { + return predicate.Host(sql.FieldLT(FieldMachineID, v)) +} + +// MachineIDLTE applies the LTE predicate on the "machine_id" field. +func MachineIDLTE(v string) predicate.Host { + return predicate.Host(sql.FieldLTE(FieldMachineID, v)) +} + +// MachineIDContains applies the Contains predicate on the "machine_id" field. +func MachineIDContains(v string) predicate.Host { + return predicate.Host(sql.FieldContains(FieldMachineID, v)) +} + +// MachineIDHasPrefix applies the HasPrefix predicate on the "machine_id" field. +func MachineIDHasPrefix(v string) predicate.Host { + return predicate.Host(sql.FieldHasPrefix(FieldMachineID, v)) +} + +// MachineIDHasSuffix applies the HasSuffix predicate on the "machine_id" field. +func MachineIDHasSuffix(v string) predicate.Host { + return predicate.Host(sql.FieldHasSuffix(FieldMachineID, v)) +} + +// MachineIDIsNil applies the IsNil predicate on the "machine_id" field. +func MachineIDIsNil() predicate.Host { + return predicate.Host(sql.FieldIsNull(FieldMachineID)) +} + +// MachineIDNotNil applies the NotNil predicate on the "machine_id" field. +func MachineIDNotNil() predicate.Host { + return predicate.Host(sql.FieldNotNull(FieldMachineID)) +} + +// MachineIDEqualFold applies the EqualFold predicate on the "machine_id" field. +func MachineIDEqualFold(v string) predicate.Host { + return predicate.Host(sql.FieldEqualFold(FieldMachineID, v)) +} + +// MachineIDContainsFold applies the ContainsFold predicate on the "machine_id" field. +func MachineIDContainsFold(v string) predicate.Host { + return predicate.Host(sql.FieldContainsFold(FieldMachineID, v)) +} + +// RemarkEQ applies the EQ predicate on the "remark" field. +func RemarkEQ(v string) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldRemark, v)) +} + +// RemarkNEQ applies the NEQ predicate on the "remark" field. +func RemarkNEQ(v string) predicate.Host { + return predicate.Host(sql.FieldNEQ(FieldRemark, v)) +} + +// RemarkIn applies the In predicate on the "remark" field. +func RemarkIn(vs ...string) predicate.Host { + return predicate.Host(sql.FieldIn(FieldRemark, vs...)) +} + +// RemarkNotIn applies the NotIn predicate on the "remark" field. +func RemarkNotIn(vs ...string) predicate.Host { + return predicate.Host(sql.FieldNotIn(FieldRemark, vs...)) +} + +// RemarkGT applies the GT predicate on the "remark" field. +func RemarkGT(v string) predicate.Host { + return predicate.Host(sql.FieldGT(FieldRemark, v)) +} + +// RemarkGTE applies the GTE predicate on the "remark" field. +func RemarkGTE(v string) predicate.Host { + return predicate.Host(sql.FieldGTE(FieldRemark, v)) +} + +// RemarkLT applies the LT predicate on the "remark" field. +func RemarkLT(v string) predicate.Host { + return predicate.Host(sql.FieldLT(FieldRemark, v)) +} + +// RemarkLTE applies the LTE predicate on the "remark" field. +func RemarkLTE(v string) predicate.Host { + return predicate.Host(sql.FieldLTE(FieldRemark, v)) +} + +// RemarkContains applies the Contains predicate on the "remark" field. +func RemarkContains(v string) predicate.Host { + return predicate.Host(sql.FieldContains(FieldRemark, v)) +} + +// RemarkHasPrefix applies the HasPrefix predicate on the "remark" field. +func RemarkHasPrefix(v string) predicate.Host { + return predicate.Host(sql.FieldHasPrefix(FieldRemark, v)) +} + +// RemarkHasSuffix applies the HasSuffix predicate on the "remark" field. +func RemarkHasSuffix(v string) predicate.Host { + return predicate.Host(sql.FieldHasSuffix(FieldRemark, v)) +} + +// RemarkIsNil applies the IsNil predicate on the "remark" field. +func RemarkIsNil() predicate.Host { + return predicate.Host(sql.FieldIsNull(FieldRemark)) +} + +// RemarkNotNil applies the NotNil predicate on the "remark" field. +func RemarkNotNil() predicate.Host { + return predicate.Host(sql.FieldNotNull(FieldRemark)) +} + +// RemarkEqualFold applies the EqualFold predicate on the "remark" field. +func RemarkEqualFold(v string) predicate.Host { + return predicate.Host(sql.FieldEqualFold(FieldRemark, v)) +} + +// RemarkContainsFold applies the ContainsFold predicate on the "remark" field. +func RemarkContainsFold(v string) predicate.Host { + return predicate.Host(sql.FieldContainsFold(FieldRemark, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.Host { + return predicate.Host(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.Host { + return predicate.Host(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.Host { + return predicate.Host(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.Host { + return predicate.Host(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.Host { + return predicate.Host(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.Host { + return predicate.Host(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.Host { + return predicate.Host(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.Host { + return predicate.Host(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.Host { + return predicate.Host(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.Host { + return predicate.Host(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.Host { + return predicate.Host(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.Host { + return predicate.Host(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.Host { + return predicate.Host(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.Host { + return predicate.Host(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.Host { + return predicate.Host(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// HasVms applies the HasEdge predicate on the "vms" edge. +func HasVms() predicate.Host { + return predicate.Host(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, VmsTable, VmsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasVmsWith applies the HasEdge predicate on the "vms" edge with a given conditions (other predicates). +func HasVmsWith(preds ...predicate.VirtualMachine) predicate.Host { + return predicate.Host(func(s *sql.Selector) { + step := newVmsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasUser applies the HasEdge predicate on the "user" edge. +func HasUser() predicate.Host { + return predicate.Host(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates). +func HasUserWith(preds ...predicate.User) predicate.Host { + return predicate.Host(func(s *sql.Selector) { + step := newUserStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasGroups applies the HasEdge predicate on the "groups" edge. +func HasGroups() predicate.Host { + return predicate.Host(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, GroupsTable, GroupsPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasGroupsWith applies the HasEdge predicate on the "groups" edge with a given conditions (other predicates). +func HasGroupsWith(preds ...predicate.TeamGroup) predicate.Host { + return predicate.Host(func(s *sql.Selector) { + step := newGroupsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasTeamGroupHosts applies the HasEdge predicate on the "team_group_hosts" edge. +func HasTeamGroupHosts() predicate.Host { + return predicate.Host(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, TeamGroupHostsTable, TeamGroupHostsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasTeamGroupHostsWith applies the HasEdge predicate on the "team_group_hosts" edge with a given conditions (other predicates). +func HasTeamGroupHostsWith(preds ...predicate.TeamGroupHost) predicate.Host { + return predicate.Host(func(s *sql.Selector) { + step := newTeamGroupHostsStep() + 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.Host) predicate.Host { + return predicate.Host(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Host) predicate.Host { + return predicate.Host(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Host) predicate.Host { + return predicate.Host(sql.NotPredicates(p)) +} diff --git a/backend/db/host_create.go b/backend/db/host_create.go new file mode 100644 index 00000000..3e973963 --- /dev/null +++ b/backend/db/host_create.go @@ -0,0 +1,1839 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/host" + "github.com/chaitin/MonkeyCode/backend/db/teamgroup" + "github.com/chaitin/MonkeyCode/backend/db/teamgrouphost" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/virtualmachine" + "github.com/google/uuid" +) + +// HostCreate is the builder for creating a Host entity. +type HostCreate struct { + config + mutation *HostMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *HostCreate) SetDeletedAt(v time.Time) *HostCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *HostCreate) SetNillableDeletedAt(v *time.Time) *HostCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetUserID sets the "user_id" field. +func (_c *HostCreate) SetUserID(v uuid.UUID) *HostCreate { + _c.mutation.SetUserID(v) + return _c +} + +// SetHostname sets the "hostname" field. +func (_c *HostCreate) SetHostname(v string) *HostCreate { + _c.mutation.SetHostname(v) + return _c +} + +// SetNillableHostname sets the "hostname" field if the given value is not nil. +func (_c *HostCreate) SetNillableHostname(v *string) *HostCreate { + if v != nil { + _c.SetHostname(*v) + } + return _c +} + +// SetArch sets the "arch" field. +func (_c *HostCreate) SetArch(v string) *HostCreate { + _c.mutation.SetArch(v) + return _c +} + +// SetNillableArch sets the "arch" field if the given value is not nil. +func (_c *HostCreate) SetNillableArch(v *string) *HostCreate { + if v != nil { + _c.SetArch(*v) + } + return _c +} + +// SetCores sets the "cores" field. +func (_c *HostCreate) SetCores(v int) *HostCreate { + _c.mutation.SetCores(v) + return _c +} + +// SetNillableCores sets the "cores" field if the given value is not nil. +func (_c *HostCreate) SetNillableCores(v *int) *HostCreate { + if v != nil { + _c.SetCores(*v) + } + return _c +} + +// SetWeight sets the "weight" field. +func (_c *HostCreate) SetWeight(v int) *HostCreate { + _c.mutation.SetWeight(v) + return _c +} + +// SetNillableWeight sets the "weight" field if the given value is not nil. +func (_c *HostCreate) SetNillableWeight(v *int) *HostCreate { + if v != nil { + _c.SetWeight(*v) + } + return _c +} + +// SetMemory sets the "memory" field. +func (_c *HostCreate) SetMemory(v int64) *HostCreate { + _c.mutation.SetMemory(v) + return _c +} + +// SetNillableMemory sets the "memory" field if the given value is not nil. +func (_c *HostCreate) SetNillableMemory(v *int64) *HostCreate { + if v != nil { + _c.SetMemory(*v) + } + return _c +} + +// SetDisk sets the "disk" field. +func (_c *HostCreate) SetDisk(v int64) *HostCreate { + _c.mutation.SetDisk(v) + return _c +} + +// SetNillableDisk sets the "disk" field if the given value is not nil. +func (_c *HostCreate) SetNillableDisk(v *int64) *HostCreate { + if v != nil { + _c.SetDisk(*v) + } + return _c +} + +// SetOs sets the "os" field. +func (_c *HostCreate) SetOs(v string) *HostCreate { + _c.mutation.SetOs(v) + return _c +} + +// SetNillableOs sets the "os" field if the given value is not nil. +func (_c *HostCreate) SetNillableOs(v *string) *HostCreate { + if v != nil { + _c.SetOs(*v) + } + return _c +} + +// SetExternalIP sets the "external_ip" field. +func (_c *HostCreate) SetExternalIP(v string) *HostCreate { + _c.mutation.SetExternalIP(v) + return _c +} + +// SetNillableExternalIP sets the "external_ip" field if the given value is not nil. +func (_c *HostCreate) SetNillableExternalIP(v *string) *HostCreate { + if v != nil { + _c.SetExternalIP(*v) + } + return _c +} + +// SetInternalIP sets the "internal_ip" field. +func (_c *HostCreate) SetInternalIP(v string) *HostCreate { + _c.mutation.SetInternalIP(v) + return _c +} + +// SetNillableInternalIP sets the "internal_ip" field if the given value is not nil. +func (_c *HostCreate) SetNillableInternalIP(v *string) *HostCreate { + if v != nil { + _c.SetInternalIP(*v) + } + return _c +} + +// SetVersion sets the "version" field. +func (_c *HostCreate) SetVersion(v string) *HostCreate { + _c.mutation.SetVersion(v) + return _c +} + +// SetNillableVersion sets the "version" field if the given value is not nil. +func (_c *HostCreate) SetNillableVersion(v *string) *HostCreate { + if v != nil { + _c.SetVersion(*v) + } + return _c +} + +// SetMachineID sets the "machine_id" field. +func (_c *HostCreate) SetMachineID(v string) *HostCreate { + _c.mutation.SetMachineID(v) + return _c +} + +// SetNillableMachineID sets the "machine_id" field if the given value is not nil. +func (_c *HostCreate) SetNillableMachineID(v *string) *HostCreate { + if v != nil { + _c.SetMachineID(*v) + } + return _c +} + +// SetRemark sets the "remark" field. +func (_c *HostCreate) SetRemark(v string) *HostCreate { + _c.mutation.SetRemark(v) + return _c +} + +// SetNillableRemark sets the "remark" field if the given value is not nil. +func (_c *HostCreate) SetNillableRemark(v *string) *HostCreate { + if v != nil { + _c.SetRemark(*v) + } + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *HostCreate) SetCreatedAt(v time.Time) *HostCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *HostCreate) SetNillableCreatedAt(v *time.Time) *HostCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *HostCreate) SetUpdatedAt(v time.Time) *HostCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *HostCreate) SetNillableUpdatedAt(v *time.Time) *HostCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *HostCreate) SetID(v string) *HostCreate { + _c.mutation.SetID(v) + return _c +} + +// AddVMIDs adds the "vms" edge to the VirtualMachine entity by IDs. +func (_c *HostCreate) AddVMIDs(ids ...string) *HostCreate { + _c.mutation.AddVMIDs(ids...) + return _c +} + +// AddVms adds the "vms" edges to the VirtualMachine entity. +func (_c *HostCreate) AddVms(v ...*VirtualMachine) *HostCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddVMIDs(ids...) +} + +// SetUser sets the "user" edge to the User entity. +func (_c *HostCreate) SetUser(v *User) *HostCreate { + return _c.SetUserID(v.ID) +} + +// AddGroupIDs adds the "groups" edge to the TeamGroup entity by IDs. +func (_c *HostCreate) AddGroupIDs(ids ...uuid.UUID) *HostCreate { + _c.mutation.AddGroupIDs(ids...) + return _c +} + +// AddGroups adds the "groups" edges to the TeamGroup entity. +func (_c *HostCreate) AddGroups(v ...*TeamGroup) *HostCreate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddGroupIDs(ids...) +} + +// AddTeamGroupHostIDs adds the "team_group_hosts" edge to the TeamGroupHost entity by IDs. +func (_c *HostCreate) AddTeamGroupHostIDs(ids ...uuid.UUID) *HostCreate { + _c.mutation.AddTeamGroupHostIDs(ids...) + return _c +} + +// AddTeamGroupHosts adds the "team_group_hosts" edges to the TeamGroupHost entity. +func (_c *HostCreate) AddTeamGroupHosts(v ...*TeamGroupHost) *HostCreate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddTeamGroupHostIDs(ids...) +} + +// Mutation returns the HostMutation object of the builder. +func (_c *HostCreate) Mutation() *HostMutation { + return _c.mutation +} + +// Save creates the Host in the database. +func (_c *HostCreate) Save(ctx context.Context) (*Host, error) { + if err := _c.defaults(); err != nil { + return nil, err + } + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *HostCreate) SaveX(ctx context.Context) *Host { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *HostCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *HostCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *HostCreate) defaults() error { + if _, ok := _c.mutation.Weight(); !ok { + v := host.DefaultWeight + _c.mutation.SetWeight(v) + } + if _, ok := _c.mutation.CreatedAt(); !ok { + if host.DefaultCreatedAt == nil { + return fmt.Errorf("db: uninitialized host.DefaultCreatedAt (forgotten import db/runtime?)") + } + v := host.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + if host.DefaultUpdatedAt == nil { + return fmt.Errorf("db: uninitialized host.DefaultUpdatedAt (forgotten import db/runtime?)") + } + v := host.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + return nil +} + +// check runs all checks and user-defined validators on the builder. +func (_c *HostCreate) check() error { + if _, ok := _c.mutation.UserID(); !ok { + return &ValidationError{Name: "user_id", err: errors.New(`db: missing required field "Host.user_id"`)} + } + if _, ok := _c.mutation.Weight(); !ok { + return &ValidationError{Name: "weight", err: errors.New(`db: missing required field "Host.weight"`)} + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "Host.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "Host.updated_at"`)} + } + if len(_c.mutation.UserIDs()) == 0 { + return &ValidationError{Name: "user", err: errors.New(`db: missing required edge "Host.user"`)} + } + return nil +} + +func (_c *HostCreate) sqlSave(ctx context.Context) (*Host, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != nil { + if id, ok := _spec.ID.Value.(string); ok { + _node.ID = id + } else { + return nil, fmt.Errorf("unexpected Host.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *HostCreate) createSpec() (*Host, *sqlgraph.CreateSpec) { + var ( + _node = &Host{config: _c.config} + _spec = sqlgraph.NewCreateSpec(host.Table, sqlgraph.NewFieldSpec(host.FieldID, field.TypeString)) + ) + _spec.OnConflict = _c.conflict + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(host.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = value + } + if value, ok := _c.mutation.Hostname(); ok { + _spec.SetField(host.FieldHostname, field.TypeString, value) + _node.Hostname = value + } + if value, ok := _c.mutation.Arch(); ok { + _spec.SetField(host.FieldArch, field.TypeString, value) + _node.Arch = value + } + if value, ok := _c.mutation.Cores(); ok { + _spec.SetField(host.FieldCores, field.TypeInt, value) + _node.Cores = value + } + if value, ok := _c.mutation.Weight(); ok { + _spec.SetField(host.FieldWeight, field.TypeInt, value) + _node.Weight = value + } + if value, ok := _c.mutation.Memory(); ok { + _spec.SetField(host.FieldMemory, field.TypeInt64, value) + _node.Memory = value + } + if value, ok := _c.mutation.Disk(); ok { + _spec.SetField(host.FieldDisk, field.TypeInt64, value) + _node.Disk = value + } + if value, ok := _c.mutation.Os(); ok { + _spec.SetField(host.FieldOs, field.TypeString, value) + _node.Os = value + } + if value, ok := _c.mutation.ExternalIP(); ok { + _spec.SetField(host.FieldExternalIP, field.TypeString, value) + _node.ExternalIP = value + } + if value, ok := _c.mutation.InternalIP(); ok { + _spec.SetField(host.FieldInternalIP, field.TypeString, value) + _node.InternalIP = value + } + if value, ok := _c.mutation.Version(); ok { + _spec.SetField(host.FieldVersion, field.TypeString, value) + _node.Version = value + } + if value, ok := _c.mutation.MachineID(); ok { + _spec.SetField(host.FieldMachineID, field.TypeString, value) + _node.MachineID = value + } + if value, ok := _c.mutation.Remark(); ok { + _spec.SetField(host.FieldRemark, field.TypeString, value) + _node.Remark = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(host.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(host.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if nodes := _c.mutation.VmsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: host.VmsTable, + Columns: []string{host.VmsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(virtualmachine.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: host.UserTable, + Columns: []string{host.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.UserID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.GroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: host.GroupsTable, + Columns: host.GroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(teamgroup.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &TeamGroupHostCreate{config: _c.config, mutation: newTeamGroupHostMutation(_c.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.TeamGroupHostsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: host.TeamGroupHostsTable, + Columns: []string{host.TeamGroupHostsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(teamgrouphost.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.Host.Create(). +// SetDeletedAt(v). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.HostUpsert) { +// SetDeletedAt(v+v). +// }). +// Exec(ctx) +func (_c *HostCreate) OnConflict(opts ...sql.ConflictOption) *HostUpsertOne { + _c.conflict = opts + return &HostUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Host.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *HostCreate) OnConflictColumns(columns ...string) *HostUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &HostUpsertOne{ + create: _c, + } +} + +type ( + // HostUpsertOne is the builder for "upsert"-ing + // one Host node. + HostUpsertOne struct { + create *HostCreate + } + + // HostUpsert is the "OnConflict" setter. + HostUpsert struct { + *sql.UpdateSet + } +) + +// SetDeletedAt sets the "deleted_at" field. +func (u *HostUpsert) SetDeletedAt(v time.Time) *HostUpsert { + u.Set(host.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *HostUpsert) UpdateDeletedAt() *HostUpsert { + u.SetExcluded(host.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *HostUpsert) ClearDeletedAt() *HostUpsert { + u.SetNull(host.FieldDeletedAt) + return u +} + +// SetUserID sets the "user_id" field. +func (u *HostUpsert) SetUserID(v uuid.UUID) *HostUpsert { + u.Set(host.FieldUserID, v) + return u +} + +// UpdateUserID sets the "user_id" field to the value that was provided on create. +func (u *HostUpsert) UpdateUserID() *HostUpsert { + u.SetExcluded(host.FieldUserID) + return u +} + +// SetHostname sets the "hostname" field. +func (u *HostUpsert) SetHostname(v string) *HostUpsert { + u.Set(host.FieldHostname, v) + return u +} + +// UpdateHostname sets the "hostname" field to the value that was provided on create. +func (u *HostUpsert) UpdateHostname() *HostUpsert { + u.SetExcluded(host.FieldHostname) + return u +} + +// ClearHostname clears the value of the "hostname" field. +func (u *HostUpsert) ClearHostname() *HostUpsert { + u.SetNull(host.FieldHostname) + return u +} + +// SetArch sets the "arch" field. +func (u *HostUpsert) SetArch(v string) *HostUpsert { + u.Set(host.FieldArch, v) + return u +} + +// UpdateArch sets the "arch" field to the value that was provided on create. +func (u *HostUpsert) UpdateArch() *HostUpsert { + u.SetExcluded(host.FieldArch) + return u +} + +// ClearArch clears the value of the "arch" field. +func (u *HostUpsert) ClearArch() *HostUpsert { + u.SetNull(host.FieldArch) + return u +} + +// SetCores sets the "cores" field. +func (u *HostUpsert) SetCores(v int) *HostUpsert { + u.Set(host.FieldCores, v) + return u +} + +// UpdateCores sets the "cores" field to the value that was provided on create. +func (u *HostUpsert) UpdateCores() *HostUpsert { + u.SetExcluded(host.FieldCores) + return u +} + +// AddCores adds v to the "cores" field. +func (u *HostUpsert) AddCores(v int) *HostUpsert { + u.Add(host.FieldCores, v) + return u +} + +// ClearCores clears the value of the "cores" field. +func (u *HostUpsert) ClearCores() *HostUpsert { + u.SetNull(host.FieldCores) + return u +} + +// SetWeight sets the "weight" field. +func (u *HostUpsert) SetWeight(v int) *HostUpsert { + u.Set(host.FieldWeight, v) + return u +} + +// UpdateWeight sets the "weight" field to the value that was provided on create. +func (u *HostUpsert) UpdateWeight() *HostUpsert { + u.SetExcluded(host.FieldWeight) + return u +} + +// AddWeight adds v to the "weight" field. +func (u *HostUpsert) AddWeight(v int) *HostUpsert { + u.Add(host.FieldWeight, v) + return u +} + +// SetMemory sets the "memory" field. +func (u *HostUpsert) SetMemory(v int64) *HostUpsert { + u.Set(host.FieldMemory, v) + return u +} + +// UpdateMemory sets the "memory" field to the value that was provided on create. +func (u *HostUpsert) UpdateMemory() *HostUpsert { + u.SetExcluded(host.FieldMemory) + return u +} + +// AddMemory adds v to the "memory" field. +func (u *HostUpsert) AddMemory(v int64) *HostUpsert { + u.Add(host.FieldMemory, v) + return u +} + +// ClearMemory clears the value of the "memory" field. +func (u *HostUpsert) ClearMemory() *HostUpsert { + u.SetNull(host.FieldMemory) + return u +} + +// SetDisk sets the "disk" field. +func (u *HostUpsert) SetDisk(v int64) *HostUpsert { + u.Set(host.FieldDisk, v) + return u +} + +// UpdateDisk sets the "disk" field to the value that was provided on create. +func (u *HostUpsert) UpdateDisk() *HostUpsert { + u.SetExcluded(host.FieldDisk) + return u +} + +// AddDisk adds v to the "disk" field. +func (u *HostUpsert) AddDisk(v int64) *HostUpsert { + u.Add(host.FieldDisk, v) + return u +} + +// ClearDisk clears the value of the "disk" field. +func (u *HostUpsert) ClearDisk() *HostUpsert { + u.SetNull(host.FieldDisk) + return u +} + +// SetOs sets the "os" field. +func (u *HostUpsert) SetOs(v string) *HostUpsert { + u.Set(host.FieldOs, v) + return u +} + +// UpdateOs sets the "os" field to the value that was provided on create. +func (u *HostUpsert) UpdateOs() *HostUpsert { + u.SetExcluded(host.FieldOs) + return u +} + +// ClearOs clears the value of the "os" field. +func (u *HostUpsert) ClearOs() *HostUpsert { + u.SetNull(host.FieldOs) + return u +} + +// SetExternalIP sets the "external_ip" field. +func (u *HostUpsert) SetExternalIP(v string) *HostUpsert { + u.Set(host.FieldExternalIP, v) + return u +} + +// UpdateExternalIP sets the "external_ip" field to the value that was provided on create. +func (u *HostUpsert) UpdateExternalIP() *HostUpsert { + u.SetExcluded(host.FieldExternalIP) + return u +} + +// ClearExternalIP clears the value of the "external_ip" field. +func (u *HostUpsert) ClearExternalIP() *HostUpsert { + u.SetNull(host.FieldExternalIP) + return u +} + +// SetInternalIP sets the "internal_ip" field. +func (u *HostUpsert) SetInternalIP(v string) *HostUpsert { + u.Set(host.FieldInternalIP, v) + return u +} + +// UpdateInternalIP sets the "internal_ip" field to the value that was provided on create. +func (u *HostUpsert) UpdateInternalIP() *HostUpsert { + u.SetExcluded(host.FieldInternalIP) + return u +} + +// ClearInternalIP clears the value of the "internal_ip" field. +func (u *HostUpsert) ClearInternalIP() *HostUpsert { + u.SetNull(host.FieldInternalIP) + return u +} + +// SetVersion sets the "version" field. +func (u *HostUpsert) SetVersion(v string) *HostUpsert { + u.Set(host.FieldVersion, v) + return u +} + +// UpdateVersion sets the "version" field to the value that was provided on create. +func (u *HostUpsert) UpdateVersion() *HostUpsert { + u.SetExcluded(host.FieldVersion) + return u +} + +// ClearVersion clears the value of the "version" field. +func (u *HostUpsert) ClearVersion() *HostUpsert { + u.SetNull(host.FieldVersion) + return u +} + +// SetMachineID sets the "machine_id" field. +func (u *HostUpsert) SetMachineID(v string) *HostUpsert { + u.Set(host.FieldMachineID, v) + return u +} + +// UpdateMachineID sets the "machine_id" field to the value that was provided on create. +func (u *HostUpsert) UpdateMachineID() *HostUpsert { + u.SetExcluded(host.FieldMachineID) + return u +} + +// ClearMachineID clears the value of the "machine_id" field. +func (u *HostUpsert) ClearMachineID() *HostUpsert { + u.SetNull(host.FieldMachineID) + return u +} + +// SetRemark sets the "remark" field. +func (u *HostUpsert) SetRemark(v string) *HostUpsert { + u.Set(host.FieldRemark, v) + return u +} + +// UpdateRemark sets the "remark" field to the value that was provided on create. +func (u *HostUpsert) UpdateRemark() *HostUpsert { + u.SetExcluded(host.FieldRemark) + return u +} + +// ClearRemark clears the value of the "remark" field. +func (u *HostUpsert) ClearRemark() *HostUpsert { + u.SetNull(host.FieldRemark) + return u +} + +// SetCreatedAt sets the "created_at" field. +func (u *HostUpsert) SetCreatedAt(v time.Time) *HostUpsert { + u.Set(host.FieldCreatedAt, v) + return u +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *HostUpsert) UpdateCreatedAt() *HostUpsert { + u.SetExcluded(host.FieldCreatedAt) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *HostUpsert) SetUpdatedAt(v time.Time) *HostUpsert { + u.Set(host.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *HostUpsert) UpdateUpdatedAt() *HostUpsert { + u.SetExcluded(host.FieldUpdatedAt) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.Host.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(host.FieldID) +// }), +// ). +// Exec(ctx) +func (u *HostUpsertOne) UpdateNewValues() *HostUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + if _, exists := u.create.mutation.ID(); exists { + s.SetIgnore(host.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Host.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *HostUpsertOne) Ignore() *HostUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *HostUpsertOne) DoNothing() *HostUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the HostCreate.OnConflict +// documentation for more info. +func (u *HostUpsertOne) Update(set func(*HostUpsert)) *HostUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&HostUpsert{UpdateSet: update}) + })) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *HostUpsertOne) SetDeletedAt(v time.Time) *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *HostUpsertOne) UpdateDeletedAt() *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *HostUpsertOne) ClearDeletedAt() *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.ClearDeletedAt() + }) +} + +// SetUserID sets the "user_id" field. +func (u *HostUpsertOne) SetUserID(v uuid.UUID) *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.SetUserID(v) + }) +} + +// UpdateUserID sets the "user_id" field to the value that was provided on create. +func (u *HostUpsertOne) UpdateUserID() *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.UpdateUserID() + }) +} + +// SetHostname sets the "hostname" field. +func (u *HostUpsertOne) SetHostname(v string) *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.SetHostname(v) + }) +} + +// UpdateHostname sets the "hostname" field to the value that was provided on create. +func (u *HostUpsertOne) UpdateHostname() *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.UpdateHostname() + }) +} + +// ClearHostname clears the value of the "hostname" field. +func (u *HostUpsertOne) ClearHostname() *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.ClearHostname() + }) +} + +// SetArch sets the "arch" field. +func (u *HostUpsertOne) SetArch(v string) *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.SetArch(v) + }) +} + +// UpdateArch sets the "arch" field to the value that was provided on create. +func (u *HostUpsertOne) UpdateArch() *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.UpdateArch() + }) +} + +// ClearArch clears the value of the "arch" field. +func (u *HostUpsertOne) ClearArch() *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.ClearArch() + }) +} + +// SetCores sets the "cores" field. +func (u *HostUpsertOne) SetCores(v int) *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.SetCores(v) + }) +} + +// AddCores adds v to the "cores" field. +func (u *HostUpsertOne) AddCores(v int) *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.AddCores(v) + }) +} + +// UpdateCores sets the "cores" field to the value that was provided on create. +func (u *HostUpsertOne) UpdateCores() *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.UpdateCores() + }) +} + +// ClearCores clears the value of the "cores" field. +func (u *HostUpsertOne) ClearCores() *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.ClearCores() + }) +} + +// SetWeight sets the "weight" field. +func (u *HostUpsertOne) SetWeight(v int) *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.SetWeight(v) + }) +} + +// AddWeight adds v to the "weight" field. +func (u *HostUpsertOne) AddWeight(v int) *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.AddWeight(v) + }) +} + +// UpdateWeight sets the "weight" field to the value that was provided on create. +func (u *HostUpsertOne) UpdateWeight() *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.UpdateWeight() + }) +} + +// SetMemory sets the "memory" field. +func (u *HostUpsertOne) SetMemory(v int64) *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.SetMemory(v) + }) +} + +// AddMemory adds v to the "memory" field. +func (u *HostUpsertOne) AddMemory(v int64) *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.AddMemory(v) + }) +} + +// UpdateMemory sets the "memory" field to the value that was provided on create. +func (u *HostUpsertOne) UpdateMemory() *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.UpdateMemory() + }) +} + +// ClearMemory clears the value of the "memory" field. +func (u *HostUpsertOne) ClearMemory() *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.ClearMemory() + }) +} + +// SetDisk sets the "disk" field. +func (u *HostUpsertOne) SetDisk(v int64) *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.SetDisk(v) + }) +} + +// AddDisk adds v to the "disk" field. +func (u *HostUpsertOne) AddDisk(v int64) *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.AddDisk(v) + }) +} + +// UpdateDisk sets the "disk" field to the value that was provided on create. +func (u *HostUpsertOne) UpdateDisk() *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.UpdateDisk() + }) +} + +// ClearDisk clears the value of the "disk" field. +func (u *HostUpsertOne) ClearDisk() *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.ClearDisk() + }) +} + +// SetOs sets the "os" field. +func (u *HostUpsertOne) SetOs(v string) *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.SetOs(v) + }) +} + +// UpdateOs sets the "os" field to the value that was provided on create. +func (u *HostUpsertOne) UpdateOs() *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.UpdateOs() + }) +} + +// ClearOs clears the value of the "os" field. +func (u *HostUpsertOne) ClearOs() *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.ClearOs() + }) +} + +// SetExternalIP sets the "external_ip" field. +func (u *HostUpsertOne) SetExternalIP(v string) *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.SetExternalIP(v) + }) +} + +// UpdateExternalIP sets the "external_ip" field to the value that was provided on create. +func (u *HostUpsertOne) UpdateExternalIP() *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.UpdateExternalIP() + }) +} + +// ClearExternalIP clears the value of the "external_ip" field. +func (u *HostUpsertOne) ClearExternalIP() *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.ClearExternalIP() + }) +} + +// SetInternalIP sets the "internal_ip" field. +func (u *HostUpsertOne) SetInternalIP(v string) *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.SetInternalIP(v) + }) +} + +// UpdateInternalIP sets the "internal_ip" field to the value that was provided on create. +func (u *HostUpsertOne) UpdateInternalIP() *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.UpdateInternalIP() + }) +} + +// ClearInternalIP clears the value of the "internal_ip" field. +func (u *HostUpsertOne) ClearInternalIP() *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.ClearInternalIP() + }) +} + +// SetVersion sets the "version" field. +func (u *HostUpsertOne) SetVersion(v string) *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.SetVersion(v) + }) +} + +// UpdateVersion sets the "version" field to the value that was provided on create. +func (u *HostUpsertOne) UpdateVersion() *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.UpdateVersion() + }) +} + +// ClearVersion clears the value of the "version" field. +func (u *HostUpsertOne) ClearVersion() *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.ClearVersion() + }) +} + +// SetMachineID sets the "machine_id" field. +func (u *HostUpsertOne) SetMachineID(v string) *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.SetMachineID(v) + }) +} + +// UpdateMachineID sets the "machine_id" field to the value that was provided on create. +func (u *HostUpsertOne) UpdateMachineID() *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.UpdateMachineID() + }) +} + +// ClearMachineID clears the value of the "machine_id" field. +func (u *HostUpsertOne) ClearMachineID() *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.ClearMachineID() + }) +} + +// SetRemark sets the "remark" field. +func (u *HostUpsertOne) SetRemark(v string) *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.SetRemark(v) + }) +} + +// UpdateRemark sets the "remark" field to the value that was provided on create. +func (u *HostUpsertOne) UpdateRemark() *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.UpdateRemark() + }) +} + +// ClearRemark clears the value of the "remark" field. +func (u *HostUpsertOne) ClearRemark() *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.ClearRemark() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *HostUpsertOne) SetCreatedAt(v time.Time) *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *HostUpsertOne) UpdateCreatedAt() *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.UpdateCreatedAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *HostUpsertOne) SetUpdatedAt(v time.Time) *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *HostUpsertOne) UpdateUpdatedAt() *HostUpsertOne { + return u.Update(func(s *HostUpsert) { + s.UpdateUpdatedAt() + }) +} + +// Exec executes the query. +func (u *HostUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for HostCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *HostUpsertOne) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} + +// Exec executes the UPSERT query and returns the inserted/updated ID. +func (u *HostUpsertOne) ID(ctx context.Context) (id string, err error) { + if u.create.driver.Dialect() == dialect.MySQL { + // In case of "ON CONFLICT", there is no way to get back non-numeric ID + // fields from the database since MySQL does not support the RETURNING clause. + return id, errors.New("db: HostUpsertOne.ID is not supported by MySQL driver. Use HostUpsertOne.Exec instead") + } + node, err := u.create.Save(ctx) + if err != nil { + return id, err + } + return node.ID, nil +} + +// IDX is like ID, but panics if an error occurs. +func (u *HostUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// HostCreateBulk is the builder for creating many Host entities in bulk. +type HostCreateBulk struct { + config + err error + builders []*HostCreate + conflict []sql.ConflictOption +} + +// Save creates the Host entities in the database. +func (_c *HostCreateBulk) Save(ctx context.Context) ([]*Host, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Host, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*HostMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.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, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *HostCreateBulk) SaveX(ctx context.Context) []*Host { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *HostCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *HostCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.Host.CreateBulk(builders...). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.HostUpsert) { +// SetDeletedAt(v+v). +// }). +// Exec(ctx) +func (_c *HostCreateBulk) OnConflict(opts ...sql.ConflictOption) *HostUpsertBulk { + _c.conflict = opts + return &HostUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.Host.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *HostCreateBulk) OnConflictColumns(columns ...string) *HostUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &HostUpsertBulk{ + create: _c, + } +} + +// HostUpsertBulk is the builder for "upsert"-ing +// a bulk of Host nodes. +type HostUpsertBulk struct { + create *HostCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.Host.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(host.FieldID) +// }), +// ). +// Exec(ctx) +func (u *HostUpsertBulk) UpdateNewValues() *HostUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + for _, b := range u.create.builders { + if _, exists := b.mutation.ID(); exists { + s.SetIgnore(host.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.Host.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *HostUpsertBulk) Ignore() *HostUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *HostUpsertBulk) DoNothing() *HostUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the HostCreateBulk.OnConflict +// documentation for more info. +func (u *HostUpsertBulk) Update(set func(*HostUpsert)) *HostUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&HostUpsert{UpdateSet: update}) + })) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *HostUpsertBulk) SetDeletedAt(v time.Time) *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *HostUpsertBulk) UpdateDeletedAt() *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *HostUpsertBulk) ClearDeletedAt() *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.ClearDeletedAt() + }) +} + +// SetUserID sets the "user_id" field. +func (u *HostUpsertBulk) SetUserID(v uuid.UUID) *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.SetUserID(v) + }) +} + +// UpdateUserID sets the "user_id" field to the value that was provided on create. +func (u *HostUpsertBulk) UpdateUserID() *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.UpdateUserID() + }) +} + +// SetHostname sets the "hostname" field. +func (u *HostUpsertBulk) SetHostname(v string) *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.SetHostname(v) + }) +} + +// UpdateHostname sets the "hostname" field to the value that was provided on create. +func (u *HostUpsertBulk) UpdateHostname() *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.UpdateHostname() + }) +} + +// ClearHostname clears the value of the "hostname" field. +func (u *HostUpsertBulk) ClearHostname() *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.ClearHostname() + }) +} + +// SetArch sets the "arch" field. +func (u *HostUpsertBulk) SetArch(v string) *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.SetArch(v) + }) +} + +// UpdateArch sets the "arch" field to the value that was provided on create. +func (u *HostUpsertBulk) UpdateArch() *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.UpdateArch() + }) +} + +// ClearArch clears the value of the "arch" field. +func (u *HostUpsertBulk) ClearArch() *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.ClearArch() + }) +} + +// SetCores sets the "cores" field. +func (u *HostUpsertBulk) SetCores(v int) *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.SetCores(v) + }) +} + +// AddCores adds v to the "cores" field. +func (u *HostUpsertBulk) AddCores(v int) *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.AddCores(v) + }) +} + +// UpdateCores sets the "cores" field to the value that was provided on create. +func (u *HostUpsertBulk) UpdateCores() *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.UpdateCores() + }) +} + +// ClearCores clears the value of the "cores" field. +func (u *HostUpsertBulk) ClearCores() *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.ClearCores() + }) +} + +// SetWeight sets the "weight" field. +func (u *HostUpsertBulk) SetWeight(v int) *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.SetWeight(v) + }) +} + +// AddWeight adds v to the "weight" field. +func (u *HostUpsertBulk) AddWeight(v int) *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.AddWeight(v) + }) +} + +// UpdateWeight sets the "weight" field to the value that was provided on create. +func (u *HostUpsertBulk) UpdateWeight() *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.UpdateWeight() + }) +} + +// SetMemory sets the "memory" field. +func (u *HostUpsertBulk) SetMemory(v int64) *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.SetMemory(v) + }) +} + +// AddMemory adds v to the "memory" field. +func (u *HostUpsertBulk) AddMemory(v int64) *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.AddMemory(v) + }) +} + +// UpdateMemory sets the "memory" field to the value that was provided on create. +func (u *HostUpsertBulk) UpdateMemory() *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.UpdateMemory() + }) +} + +// ClearMemory clears the value of the "memory" field. +func (u *HostUpsertBulk) ClearMemory() *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.ClearMemory() + }) +} + +// SetDisk sets the "disk" field. +func (u *HostUpsertBulk) SetDisk(v int64) *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.SetDisk(v) + }) +} + +// AddDisk adds v to the "disk" field. +func (u *HostUpsertBulk) AddDisk(v int64) *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.AddDisk(v) + }) +} + +// UpdateDisk sets the "disk" field to the value that was provided on create. +func (u *HostUpsertBulk) UpdateDisk() *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.UpdateDisk() + }) +} + +// ClearDisk clears the value of the "disk" field. +func (u *HostUpsertBulk) ClearDisk() *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.ClearDisk() + }) +} + +// SetOs sets the "os" field. +func (u *HostUpsertBulk) SetOs(v string) *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.SetOs(v) + }) +} + +// UpdateOs sets the "os" field to the value that was provided on create. +func (u *HostUpsertBulk) UpdateOs() *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.UpdateOs() + }) +} + +// ClearOs clears the value of the "os" field. +func (u *HostUpsertBulk) ClearOs() *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.ClearOs() + }) +} + +// SetExternalIP sets the "external_ip" field. +func (u *HostUpsertBulk) SetExternalIP(v string) *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.SetExternalIP(v) + }) +} + +// UpdateExternalIP sets the "external_ip" field to the value that was provided on create. +func (u *HostUpsertBulk) UpdateExternalIP() *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.UpdateExternalIP() + }) +} + +// ClearExternalIP clears the value of the "external_ip" field. +func (u *HostUpsertBulk) ClearExternalIP() *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.ClearExternalIP() + }) +} + +// SetInternalIP sets the "internal_ip" field. +func (u *HostUpsertBulk) SetInternalIP(v string) *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.SetInternalIP(v) + }) +} + +// UpdateInternalIP sets the "internal_ip" field to the value that was provided on create. +func (u *HostUpsertBulk) UpdateInternalIP() *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.UpdateInternalIP() + }) +} + +// ClearInternalIP clears the value of the "internal_ip" field. +func (u *HostUpsertBulk) ClearInternalIP() *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.ClearInternalIP() + }) +} + +// SetVersion sets the "version" field. +func (u *HostUpsertBulk) SetVersion(v string) *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.SetVersion(v) + }) +} + +// UpdateVersion sets the "version" field to the value that was provided on create. +func (u *HostUpsertBulk) UpdateVersion() *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.UpdateVersion() + }) +} + +// ClearVersion clears the value of the "version" field. +func (u *HostUpsertBulk) ClearVersion() *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.ClearVersion() + }) +} + +// SetMachineID sets the "machine_id" field. +func (u *HostUpsertBulk) SetMachineID(v string) *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.SetMachineID(v) + }) +} + +// UpdateMachineID sets the "machine_id" field to the value that was provided on create. +func (u *HostUpsertBulk) UpdateMachineID() *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.UpdateMachineID() + }) +} + +// ClearMachineID clears the value of the "machine_id" field. +func (u *HostUpsertBulk) ClearMachineID() *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.ClearMachineID() + }) +} + +// SetRemark sets the "remark" field. +func (u *HostUpsertBulk) SetRemark(v string) *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.SetRemark(v) + }) +} + +// UpdateRemark sets the "remark" field to the value that was provided on create. +func (u *HostUpsertBulk) UpdateRemark() *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.UpdateRemark() + }) +} + +// ClearRemark clears the value of the "remark" field. +func (u *HostUpsertBulk) ClearRemark() *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.ClearRemark() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *HostUpsertBulk) SetCreatedAt(v time.Time) *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *HostUpsertBulk) UpdateCreatedAt() *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.UpdateCreatedAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *HostUpsertBulk) SetUpdatedAt(v time.Time) *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *HostUpsertBulk) UpdateUpdatedAt() *HostUpsertBulk { + return u.Update(func(s *HostUpsert) { + s.UpdateUpdatedAt() + }) +} + +// Exec executes the query. +func (u *HostUpsertBulk) Exec(ctx context.Context) error { + if u.create.err != nil { + return u.create.err + } + for i, b := range u.create.builders { + if len(b.conflict) != 0 { + return fmt.Errorf("db: OnConflict was set for builder %d. Set it on the HostCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for HostCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *HostUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/host_delete.go b/backend/db/host_delete.go new file mode 100644 index 00000000..9a58b9f1 --- /dev/null +++ b/backend/db/host_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/host" + "github.com/chaitin/MonkeyCode/backend/db/predicate" +) + +// HostDelete is the builder for deleting a Host entity. +type HostDelete struct { + config + hooks []Hook + mutation *HostMutation +} + +// Where appends a list predicates to the HostDelete builder. +func (_d *HostDelete) Where(ps ...predicate.Host) *HostDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *HostDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *HostDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *HostDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(host.Table, sqlgraph.NewFieldSpec(host.FieldID, field.TypeString)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// HostDeleteOne is the builder for deleting a single Host entity. +type HostDeleteOne struct { + _d *HostDelete +} + +// Where appends a list predicates to the HostDelete builder. +func (_d *HostDeleteOne) Where(ps ...predicate.Host) *HostDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *HostDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{host.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *HostDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/host_query.go b/backend/db/host_query.go new file mode 100644 index 00000000..063a5dd3 --- /dev/null +++ b/backend/db/host_query.go @@ -0,0 +1,911 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "database/sql/driver" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/host" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/teamgroup" + "github.com/chaitin/MonkeyCode/backend/db/teamgrouphost" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/virtualmachine" + "github.com/google/uuid" +) + +// HostQuery is the builder for querying Host entities. +type HostQuery struct { + config + ctx *QueryContext + order []host.OrderOption + inters []Interceptor + predicates []predicate.Host + withVms *VirtualMachineQuery + withUser *UserQuery + withGroups *TeamGroupQuery + withTeamGroupHosts *TeamGroupHostQuery + modifiers []func(*sql.Selector) + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the HostQuery builder. +func (_q *HostQuery) Where(ps ...predicate.Host) *HostQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *HostQuery) Limit(limit int) *HostQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *HostQuery) Offset(offset int) *HostQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *HostQuery) Unique(unique bool) *HostQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *HostQuery) Order(o ...host.OrderOption) *HostQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryVms chains the current query on the "vms" edge. +func (_q *HostQuery) QueryVms() *VirtualMachineQuery { + query := (&VirtualMachineClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(host.Table, host.FieldID, selector), + sqlgraph.To(virtualmachine.Table, virtualmachine.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, host.VmsTable, host.VmsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryUser chains the current query on the "user" edge. +func (_q *HostQuery) QueryUser() *UserQuery { + query := (&UserClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(host.Table, host.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, host.UserTable, host.UserColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryGroups chains the current query on the "groups" edge. +func (_q *HostQuery) QueryGroups() *TeamGroupQuery { + query := (&TeamGroupClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(host.Table, host.FieldID, selector), + sqlgraph.To(teamgroup.Table, teamgroup.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, host.GroupsTable, host.GroupsPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryTeamGroupHosts chains the current query on the "team_group_hosts" edge. +func (_q *HostQuery) QueryTeamGroupHosts() *TeamGroupHostQuery { + query := (&TeamGroupHostClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(host.Table, host.FieldID, selector), + sqlgraph.To(teamgrouphost.Table, teamgrouphost.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, host.TeamGroupHostsTable, host.TeamGroupHostsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Host entity from the query. +// Returns a *NotFoundError when no Host was found. +func (_q *HostQuery) First(ctx context.Context) (*Host, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{host.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *HostQuery) FirstX(ctx context.Context) *Host { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Host ID from the query. +// Returns a *NotFoundError when no Host ID was found. +func (_q *HostQuery) FirstID(ctx context.Context) (id string, err error) { + var ids []string + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{host.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *HostQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Host entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Host entity is found. +// Returns a *NotFoundError when no Host entities are found. +func (_q *HostQuery) Only(ctx context.Context) (*Host, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{host.Label} + default: + return nil, &NotSingularError{host.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *HostQuery) OnlyX(ctx context.Context) *Host { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Host ID in the query. +// Returns a *NotSingularError when more than one Host ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *HostQuery) OnlyID(ctx context.Context) (id string, err error) { + var ids []string + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{host.Label} + default: + err = &NotSingularError{host.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *HostQuery) OnlyIDX(ctx context.Context) string { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Hosts. +func (_q *HostQuery) All(ctx context.Context) ([]*Host, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Host, *HostQuery]() + return withInterceptors[[]*Host](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *HostQuery) AllX(ctx context.Context) []*Host { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Host IDs. +func (_q *HostQuery) IDs(ctx context.Context) (ids []string, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(host.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *HostQuery) IDsX(ctx context.Context) []string { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *HostQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*HostQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *HostQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *HostQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("db: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *HostQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the HostQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *HostQuery) Clone() *HostQuery { + if _q == nil { + return nil + } + return &HostQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]host.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Host{}, _q.predicates...), + withVms: _q.withVms.Clone(), + withUser: _q.withUser.Clone(), + withGroups: _q.withGroups.Clone(), + withTeamGroupHosts: _q.withTeamGroupHosts.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + modifiers: append([]func(*sql.Selector){}, _q.modifiers...), + } +} + +// WithVms tells the query-builder to eager-load the nodes that are connected to +// the "vms" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *HostQuery) WithVms(opts ...func(*VirtualMachineQuery)) *HostQuery { + query := (&VirtualMachineClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withVms = query + return _q +} + +// WithUser tells the query-builder to eager-load the nodes that are connected to +// the "user" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *HostQuery) WithUser(opts ...func(*UserQuery)) *HostQuery { + query := (&UserClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withUser = query + return _q +} + +// WithGroups tells the query-builder to eager-load the nodes that are connected to +// the "groups" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *HostQuery) WithGroups(opts ...func(*TeamGroupQuery)) *HostQuery { + query := (&TeamGroupClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withGroups = query + return _q +} + +// WithTeamGroupHosts tells the query-builder to eager-load the nodes that are connected to +// the "team_group_hosts" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *HostQuery) WithTeamGroupHosts(opts ...func(*TeamGroupHostQuery)) *HostQuery { + query := (&TeamGroupHostClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withTeamGroupHosts = query + return _q +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// DeletedAt time.Time `json:"deleted_at,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Host.Query(). +// GroupBy(host.FieldDeletedAt). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *HostQuery) GroupBy(field string, fields ...string) *HostGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &HostGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = host.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// DeletedAt time.Time `json:"deleted_at,omitempty"` +// } +// +// client.Host.Query(). +// Select(host.FieldDeletedAt). +// Scan(ctx, &v) +func (_q *HostQuery) Select(fields ...string) *HostSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &HostSelect{HostQuery: _q} + sbuild.label = host.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a HostSelect configured with the given aggregations. +func (_q *HostQuery) Aggregate(fns ...AggregateFunc) *HostSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *HostQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !host.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *HostQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Host, error) { + var ( + nodes = []*Host{} + _spec = _q.querySpec() + loadedTypes = [4]bool{ + _q.withVms != nil, + _q.withUser != nil, + _q.withGroups != nil, + _q.withTeamGroupHosts != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Host).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Host{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withVms; query != nil { + if err := _q.loadVms(ctx, query, nodes, + func(n *Host) { n.Edges.Vms = []*VirtualMachine{} }, + func(n *Host, e *VirtualMachine) { n.Edges.Vms = append(n.Edges.Vms, e) }); err != nil { + return nil, err + } + } + if query := _q.withUser; query != nil { + if err := _q.loadUser(ctx, query, nodes, nil, + func(n *Host, e *User) { n.Edges.User = e }); err != nil { + return nil, err + } + } + if query := _q.withGroups; query != nil { + if err := _q.loadGroups(ctx, query, nodes, + func(n *Host) { n.Edges.Groups = []*TeamGroup{} }, + func(n *Host, e *TeamGroup) { n.Edges.Groups = append(n.Edges.Groups, e) }); err != nil { + return nil, err + } + } + if query := _q.withTeamGroupHosts; query != nil { + if err := _q.loadTeamGroupHosts(ctx, query, nodes, + func(n *Host) { n.Edges.TeamGroupHosts = []*TeamGroupHost{} }, + func(n *Host, e *TeamGroupHost) { n.Edges.TeamGroupHosts = append(n.Edges.TeamGroupHosts, e) }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *HostQuery) loadVms(ctx context.Context, query *VirtualMachineQuery, nodes []*Host, init func(*Host), assign func(*Host, *VirtualMachine)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*Host) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(virtualmachine.FieldHostID) + } + query.Where(predicate.VirtualMachine(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(host.VmsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.HostID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "host_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *HostQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*Host, init func(*Host), assign func(*Host, *User)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*Host) + for i := range nodes { + fk := nodes[i].UserID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(user.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "user_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *HostQuery) loadGroups(ctx context.Context, query *TeamGroupQuery, nodes []*Host, init func(*Host), assign func(*Host, *TeamGroup)) error { + edgeIDs := make([]driver.Value, len(nodes)) + byID := make(map[string]*Host) + nids := make(map[uuid.UUID]map[*Host]struct{}) + for i, node := range nodes { + edgeIDs[i] = node.ID + byID[node.ID] = node + if init != nil { + init(node) + } + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(host.GroupsTable) + s.Join(joinT).On(s.C(teamgroup.FieldID), joinT.C(host.GroupsPrimaryKey[0])) + s.Where(sql.InValues(joinT.C(host.GroupsPrimaryKey[1]), edgeIDs...)) + columns := s.SelectedColumns() + s.Select(joinT.C(host.GroupsPrimaryKey[1])) + s.AppendSelect(columns...) + s.SetDistinct(false) + }) + if err := query.prepareQuery(ctx); err != nil { + return err + } + qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) { + assign := spec.Assign + values := spec.ScanValues + spec.ScanValues = func(columns []string) ([]any, error) { + values, err := values(columns[1:]) + if err != nil { + return nil, err + } + return append([]any{new(sql.NullString)}, values...), nil + } + spec.Assign = func(columns []string, values []any) error { + outValue := values[0].(*sql.NullString).String + inValue := *values[1].(*uuid.UUID) + if nids[inValue] == nil { + nids[inValue] = map[*Host]struct{}{byID[outValue]: {}} + return assign(columns[1:], values[1:]) + } + nids[inValue][byID[outValue]] = struct{}{} + return nil + } + }) + }) + neighbors, err := withInterceptors[[]*TeamGroup](ctx, query, qr, query.inters) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nids[n.ID] + if !ok { + return fmt.Errorf(`unexpected "groups" node returned %v`, n.ID) + } + for kn := range nodes { + assign(kn, n) + } + } + return nil +} +func (_q *HostQuery) loadTeamGroupHosts(ctx context.Context, query *TeamGroupHostQuery, nodes []*Host, init func(*Host), assign func(*Host, *TeamGroupHost)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*Host) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(teamgrouphost.FieldHostID) + } + query.Where(predicate.TeamGroupHost(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(host.TeamGroupHostsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.HostID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "host_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (_q *HostQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *HostQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(host.Table, host.Columns, sqlgraph.NewFieldSpec(host.FieldID, field.TypeString)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, host.FieldID) + for i := range fields { + if fields[i] != host.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withUser != nil { + _spec.Node.AddColumnOnce(host.FieldUserID) + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *HostQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(host.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = host.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, m := range _q.modifiers { + m(selector) + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// ForUpdate locks the selected rows against concurrent updates, and prevent them from being +// updated, deleted or "selected ... for update" by other sessions, until the transaction is +// either committed or rolled-back. +func (_q *HostQuery) ForUpdate(opts ...sql.LockOption) *HostQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return _q +} + +// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock +// on any rows that are read. Other sessions can read the rows, but cannot modify them +// until your transaction commits. +func (_q *HostQuery) ForShare(opts ...sql.LockOption) *HostQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (_q *HostQuery) Modify(modifiers ...func(s *sql.Selector)) *HostSelect { + _q.modifiers = append(_q.modifiers, modifiers...) + return _q.Select() +} + +// HostGroupBy is the group-by builder for Host entities. +type HostGroupBy struct { + selector + build *HostQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *HostGroupBy) Aggregate(fns ...AggregateFunc) *HostGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *HostGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*HostQuery, *HostGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *HostGroupBy) sqlScan(ctx context.Context, root *HostQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// HostSelect is the builder for selecting fields of Host entities. +type HostSelect struct { + *HostQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *HostSelect) Aggregate(fns ...AggregateFunc) *HostSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *HostSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*HostQuery, *HostSelect](ctx, _s.HostQuery, _s, _s.inters, v) +} + +func (_s *HostSelect) sqlScan(ctx context.Context, root *HostQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (_s *HostSelect) Modify(modifiers ...func(s *sql.Selector)) *HostSelect { + _s.modifiers = append(_s.modifiers, modifiers...) + return _s +} diff --git a/backend/db/host_update.go b/backend/db/host_update.go new file mode 100644 index 00000000..706cb3a8 --- /dev/null +++ b/backend/db/host_update.go @@ -0,0 +1,1657 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/host" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/teamgroup" + "github.com/chaitin/MonkeyCode/backend/db/teamgrouphost" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/virtualmachine" + "github.com/google/uuid" +) + +// HostUpdate is the builder for updating Host entities. +type HostUpdate struct { + config + hooks []Hook + mutation *HostMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the HostUpdate builder. +func (_u *HostUpdate) Where(ps ...predicate.Host) *HostUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *HostUpdate) SetDeletedAt(v time.Time) *HostUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *HostUpdate) SetNillableDeletedAt(v *time.Time) *HostUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *HostUpdate) ClearDeletedAt() *HostUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetUserID sets the "user_id" field. +func (_u *HostUpdate) SetUserID(v uuid.UUID) *HostUpdate { + _u.mutation.SetUserID(v) + return _u +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (_u *HostUpdate) SetNillableUserID(v *uuid.UUID) *HostUpdate { + if v != nil { + _u.SetUserID(*v) + } + return _u +} + +// SetHostname sets the "hostname" field. +func (_u *HostUpdate) SetHostname(v string) *HostUpdate { + _u.mutation.SetHostname(v) + return _u +} + +// SetNillableHostname sets the "hostname" field if the given value is not nil. +func (_u *HostUpdate) SetNillableHostname(v *string) *HostUpdate { + if v != nil { + _u.SetHostname(*v) + } + return _u +} + +// ClearHostname clears the value of the "hostname" field. +func (_u *HostUpdate) ClearHostname() *HostUpdate { + _u.mutation.ClearHostname() + return _u +} + +// SetArch sets the "arch" field. +func (_u *HostUpdate) SetArch(v string) *HostUpdate { + _u.mutation.SetArch(v) + return _u +} + +// SetNillableArch sets the "arch" field if the given value is not nil. +func (_u *HostUpdate) SetNillableArch(v *string) *HostUpdate { + if v != nil { + _u.SetArch(*v) + } + return _u +} + +// ClearArch clears the value of the "arch" field. +func (_u *HostUpdate) ClearArch() *HostUpdate { + _u.mutation.ClearArch() + return _u +} + +// SetCores sets the "cores" field. +func (_u *HostUpdate) SetCores(v int) *HostUpdate { + _u.mutation.ResetCores() + _u.mutation.SetCores(v) + return _u +} + +// SetNillableCores sets the "cores" field if the given value is not nil. +func (_u *HostUpdate) SetNillableCores(v *int) *HostUpdate { + if v != nil { + _u.SetCores(*v) + } + return _u +} + +// AddCores adds value to the "cores" field. +func (_u *HostUpdate) AddCores(v int) *HostUpdate { + _u.mutation.AddCores(v) + return _u +} + +// ClearCores clears the value of the "cores" field. +func (_u *HostUpdate) ClearCores() *HostUpdate { + _u.mutation.ClearCores() + return _u +} + +// SetWeight sets the "weight" field. +func (_u *HostUpdate) SetWeight(v int) *HostUpdate { + _u.mutation.ResetWeight() + _u.mutation.SetWeight(v) + return _u +} + +// SetNillableWeight sets the "weight" field if the given value is not nil. +func (_u *HostUpdate) SetNillableWeight(v *int) *HostUpdate { + if v != nil { + _u.SetWeight(*v) + } + return _u +} + +// AddWeight adds value to the "weight" field. +func (_u *HostUpdate) AddWeight(v int) *HostUpdate { + _u.mutation.AddWeight(v) + return _u +} + +// SetMemory sets the "memory" field. +func (_u *HostUpdate) SetMemory(v int64) *HostUpdate { + _u.mutation.ResetMemory() + _u.mutation.SetMemory(v) + return _u +} + +// SetNillableMemory sets the "memory" field if the given value is not nil. +func (_u *HostUpdate) SetNillableMemory(v *int64) *HostUpdate { + if v != nil { + _u.SetMemory(*v) + } + return _u +} + +// AddMemory adds value to the "memory" field. +func (_u *HostUpdate) AddMemory(v int64) *HostUpdate { + _u.mutation.AddMemory(v) + return _u +} + +// ClearMemory clears the value of the "memory" field. +func (_u *HostUpdate) ClearMemory() *HostUpdate { + _u.mutation.ClearMemory() + return _u +} + +// SetDisk sets the "disk" field. +func (_u *HostUpdate) SetDisk(v int64) *HostUpdate { + _u.mutation.ResetDisk() + _u.mutation.SetDisk(v) + return _u +} + +// SetNillableDisk sets the "disk" field if the given value is not nil. +func (_u *HostUpdate) SetNillableDisk(v *int64) *HostUpdate { + if v != nil { + _u.SetDisk(*v) + } + return _u +} + +// AddDisk adds value to the "disk" field. +func (_u *HostUpdate) AddDisk(v int64) *HostUpdate { + _u.mutation.AddDisk(v) + return _u +} + +// ClearDisk clears the value of the "disk" field. +func (_u *HostUpdate) ClearDisk() *HostUpdate { + _u.mutation.ClearDisk() + return _u +} + +// SetOs sets the "os" field. +func (_u *HostUpdate) SetOs(v string) *HostUpdate { + _u.mutation.SetOs(v) + return _u +} + +// SetNillableOs sets the "os" field if the given value is not nil. +func (_u *HostUpdate) SetNillableOs(v *string) *HostUpdate { + if v != nil { + _u.SetOs(*v) + } + return _u +} + +// ClearOs clears the value of the "os" field. +func (_u *HostUpdate) ClearOs() *HostUpdate { + _u.mutation.ClearOs() + return _u +} + +// SetExternalIP sets the "external_ip" field. +func (_u *HostUpdate) SetExternalIP(v string) *HostUpdate { + _u.mutation.SetExternalIP(v) + return _u +} + +// SetNillableExternalIP sets the "external_ip" field if the given value is not nil. +func (_u *HostUpdate) SetNillableExternalIP(v *string) *HostUpdate { + if v != nil { + _u.SetExternalIP(*v) + } + return _u +} + +// ClearExternalIP clears the value of the "external_ip" field. +func (_u *HostUpdate) ClearExternalIP() *HostUpdate { + _u.mutation.ClearExternalIP() + return _u +} + +// SetInternalIP sets the "internal_ip" field. +func (_u *HostUpdate) SetInternalIP(v string) *HostUpdate { + _u.mutation.SetInternalIP(v) + return _u +} + +// SetNillableInternalIP sets the "internal_ip" field if the given value is not nil. +func (_u *HostUpdate) SetNillableInternalIP(v *string) *HostUpdate { + if v != nil { + _u.SetInternalIP(*v) + } + return _u +} + +// ClearInternalIP clears the value of the "internal_ip" field. +func (_u *HostUpdate) ClearInternalIP() *HostUpdate { + _u.mutation.ClearInternalIP() + return _u +} + +// SetVersion sets the "version" field. +func (_u *HostUpdate) SetVersion(v string) *HostUpdate { + _u.mutation.SetVersion(v) + return _u +} + +// SetNillableVersion sets the "version" field if the given value is not nil. +func (_u *HostUpdate) SetNillableVersion(v *string) *HostUpdate { + if v != nil { + _u.SetVersion(*v) + } + return _u +} + +// ClearVersion clears the value of the "version" field. +func (_u *HostUpdate) ClearVersion() *HostUpdate { + _u.mutation.ClearVersion() + return _u +} + +// SetMachineID sets the "machine_id" field. +func (_u *HostUpdate) SetMachineID(v string) *HostUpdate { + _u.mutation.SetMachineID(v) + return _u +} + +// SetNillableMachineID sets the "machine_id" field if the given value is not nil. +func (_u *HostUpdate) SetNillableMachineID(v *string) *HostUpdate { + if v != nil { + _u.SetMachineID(*v) + } + return _u +} + +// ClearMachineID clears the value of the "machine_id" field. +func (_u *HostUpdate) ClearMachineID() *HostUpdate { + _u.mutation.ClearMachineID() + return _u +} + +// SetRemark sets the "remark" field. +func (_u *HostUpdate) SetRemark(v string) *HostUpdate { + _u.mutation.SetRemark(v) + return _u +} + +// SetNillableRemark sets the "remark" field if the given value is not nil. +func (_u *HostUpdate) SetNillableRemark(v *string) *HostUpdate { + if v != nil { + _u.SetRemark(*v) + } + return _u +} + +// ClearRemark clears the value of the "remark" field. +func (_u *HostUpdate) ClearRemark() *HostUpdate { + _u.mutation.ClearRemark() + return _u +} + +// SetCreatedAt sets the "created_at" field. +func (_u *HostUpdate) SetCreatedAt(v time.Time) *HostUpdate { + _u.mutation.SetCreatedAt(v) + return _u +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_u *HostUpdate) SetNillableCreatedAt(v *time.Time) *HostUpdate { + if v != nil { + _u.SetCreatedAt(*v) + } + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *HostUpdate) SetUpdatedAt(v time.Time) *HostUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// AddVMIDs adds the "vms" edge to the VirtualMachine entity by IDs. +func (_u *HostUpdate) AddVMIDs(ids ...string) *HostUpdate { + _u.mutation.AddVMIDs(ids...) + return _u +} + +// AddVms adds the "vms" edges to the VirtualMachine entity. +func (_u *HostUpdate) AddVms(v ...*VirtualMachine) *HostUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddVMIDs(ids...) +} + +// SetUser sets the "user" edge to the User entity. +func (_u *HostUpdate) SetUser(v *User) *HostUpdate { + return _u.SetUserID(v.ID) +} + +// AddGroupIDs adds the "groups" edge to the TeamGroup entity by IDs. +func (_u *HostUpdate) AddGroupIDs(ids ...uuid.UUID) *HostUpdate { + _u.mutation.AddGroupIDs(ids...) + return _u +} + +// AddGroups adds the "groups" edges to the TeamGroup entity. +func (_u *HostUpdate) AddGroups(v ...*TeamGroup) *HostUpdate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddGroupIDs(ids...) +} + +// AddTeamGroupHostIDs adds the "team_group_hosts" edge to the TeamGroupHost entity by IDs. +func (_u *HostUpdate) AddTeamGroupHostIDs(ids ...uuid.UUID) *HostUpdate { + _u.mutation.AddTeamGroupHostIDs(ids...) + return _u +} + +// AddTeamGroupHosts adds the "team_group_hosts" edges to the TeamGroupHost entity. +func (_u *HostUpdate) AddTeamGroupHosts(v ...*TeamGroupHost) *HostUpdate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddTeamGroupHostIDs(ids...) +} + +// Mutation returns the HostMutation object of the builder. +func (_u *HostUpdate) Mutation() *HostMutation { + return _u.mutation +} + +// ClearVms clears all "vms" edges to the VirtualMachine entity. +func (_u *HostUpdate) ClearVms() *HostUpdate { + _u.mutation.ClearVms() + return _u +} + +// RemoveVMIDs removes the "vms" edge to VirtualMachine entities by IDs. +func (_u *HostUpdate) RemoveVMIDs(ids ...string) *HostUpdate { + _u.mutation.RemoveVMIDs(ids...) + return _u +} + +// RemoveVms removes "vms" edges to VirtualMachine entities. +func (_u *HostUpdate) RemoveVms(v ...*VirtualMachine) *HostUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveVMIDs(ids...) +} + +// ClearUser clears the "user" edge to the User entity. +func (_u *HostUpdate) ClearUser() *HostUpdate { + _u.mutation.ClearUser() + return _u +} + +// ClearGroups clears all "groups" edges to the TeamGroup entity. +func (_u *HostUpdate) ClearGroups() *HostUpdate { + _u.mutation.ClearGroups() + return _u +} + +// RemoveGroupIDs removes the "groups" edge to TeamGroup entities by IDs. +func (_u *HostUpdate) RemoveGroupIDs(ids ...uuid.UUID) *HostUpdate { + _u.mutation.RemoveGroupIDs(ids...) + return _u +} + +// RemoveGroups removes "groups" edges to TeamGroup entities. +func (_u *HostUpdate) RemoveGroups(v ...*TeamGroup) *HostUpdate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveGroupIDs(ids...) +} + +// ClearTeamGroupHosts clears all "team_group_hosts" edges to the TeamGroupHost entity. +func (_u *HostUpdate) ClearTeamGroupHosts() *HostUpdate { + _u.mutation.ClearTeamGroupHosts() + return _u +} + +// RemoveTeamGroupHostIDs removes the "team_group_hosts" edge to TeamGroupHost entities by IDs. +func (_u *HostUpdate) RemoveTeamGroupHostIDs(ids ...uuid.UUID) *HostUpdate { + _u.mutation.RemoveTeamGroupHostIDs(ids...) + return _u +} + +// RemoveTeamGroupHosts removes "team_group_hosts" edges to TeamGroupHost entities. +func (_u *HostUpdate) RemoveTeamGroupHosts(v ...*TeamGroupHost) *HostUpdate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveTeamGroupHostIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *HostUpdate) Save(ctx context.Context) (int, error) { + if err := _u.defaults(); err != nil { + return 0, err + } + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *HostUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *HostUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *HostUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *HostUpdate) defaults() error { + if _, ok := _u.mutation.UpdatedAt(); !ok { + if host.UpdateDefaultUpdatedAt == nil { + return fmt.Errorf("db: uninitialized host.UpdateDefaultUpdatedAt (forgotten import db/runtime?)") + } + v := host.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } + return nil +} + +// check runs all checks and user-defined validators on the builder. +func (_u *HostUpdate) check() error { + if _u.mutation.UserCleared() && len(_u.mutation.UserIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "Host.user"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *HostUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *HostUpdate { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *HostUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(host.Table, host.Columns, sqlgraph.NewFieldSpec(host.FieldID, field.TypeString)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(host.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(host.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Hostname(); ok { + _spec.SetField(host.FieldHostname, field.TypeString, value) + } + if _u.mutation.HostnameCleared() { + _spec.ClearField(host.FieldHostname, field.TypeString) + } + if value, ok := _u.mutation.Arch(); ok { + _spec.SetField(host.FieldArch, field.TypeString, value) + } + if _u.mutation.ArchCleared() { + _spec.ClearField(host.FieldArch, field.TypeString) + } + if value, ok := _u.mutation.Cores(); ok { + _spec.SetField(host.FieldCores, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedCores(); ok { + _spec.AddField(host.FieldCores, field.TypeInt, value) + } + if _u.mutation.CoresCleared() { + _spec.ClearField(host.FieldCores, field.TypeInt) + } + if value, ok := _u.mutation.Weight(); ok { + _spec.SetField(host.FieldWeight, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedWeight(); ok { + _spec.AddField(host.FieldWeight, field.TypeInt, value) + } + if value, ok := _u.mutation.Memory(); ok { + _spec.SetField(host.FieldMemory, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedMemory(); ok { + _spec.AddField(host.FieldMemory, field.TypeInt64, value) + } + if _u.mutation.MemoryCleared() { + _spec.ClearField(host.FieldMemory, field.TypeInt64) + } + if value, ok := _u.mutation.Disk(); ok { + _spec.SetField(host.FieldDisk, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedDisk(); ok { + _spec.AddField(host.FieldDisk, field.TypeInt64, value) + } + if _u.mutation.DiskCleared() { + _spec.ClearField(host.FieldDisk, field.TypeInt64) + } + if value, ok := _u.mutation.Os(); ok { + _spec.SetField(host.FieldOs, field.TypeString, value) + } + if _u.mutation.OsCleared() { + _spec.ClearField(host.FieldOs, field.TypeString) + } + if value, ok := _u.mutation.ExternalIP(); ok { + _spec.SetField(host.FieldExternalIP, field.TypeString, value) + } + if _u.mutation.ExternalIPCleared() { + _spec.ClearField(host.FieldExternalIP, field.TypeString) + } + if value, ok := _u.mutation.InternalIP(); ok { + _spec.SetField(host.FieldInternalIP, field.TypeString, value) + } + if _u.mutation.InternalIPCleared() { + _spec.ClearField(host.FieldInternalIP, field.TypeString) + } + if value, ok := _u.mutation.Version(); ok { + _spec.SetField(host.FieldVersion, field.TypeString, value) + } + if _u.mutation.VersionCleared() { + _spec.ClearField(host.FieldVersion, field.TypeString) + } + if value, ok := _u.mutation.MachineID(); ok { + _spec.SetField(host.FieldMachineID, field.TypeString, value) + } + if _u.mutation.MachineIDCleared() { + _spec.ClearField(host.FieldMachineID, field.TypeString) + } + if value, ok := _u.mutation.Remark(); ok { + _spec.SetField(host.FieldRemark, field.TypeString, value) + } + if _u.mutation.RemarkCleared() { + _spec.ClearField(host.FieldRemark, field.TypeString) + } + if value, ok := _u.mutation.CreatedAt(); ok { + _spec.SetField(host.FieldCreatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(host.FieldUpdatedAt, field.TypeTime, value) + } + if _u.mutation.VmsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: host.VmsTable, + Columns: []string{host.VmsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(virtualmachine.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedVmsIDs(); len(nodes) > 0 && !_u.mutation.VmsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: host.VmsTable, + Columns: []string{host.VmsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(virtualmachine.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.VmsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: host.VmsTable, + Columns: []string{host.VmsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(virtualmachine.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: host.UserTable, + Columns: []string{host.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: host.UserTable, + Columns: []string{host.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.GroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: host.GroupsTable, + Columns: host.GroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(teamgroup.FieldID, field.TypeUUID), + }, + } + createE := &TeamGroupHostCreate{config: _u.config, mutation: newTeamGroupHostMutation(_u.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedGroupsIDs(); len(nodes) > 0 && !_u.mutation.GroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: host.GroupsTable, + Columns: host.GroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(teamgroup.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &TeamGroupHostCreate{config: _u.config, mutation: newTeamGroupHostMutation(_u.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.GroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: host.GroupsTable, + Columns: host.GroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(teamgroup.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &TeamGroupHostCreate{config: _u.config, mutation: newTeamGroupHostMutation(_u.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.TeamGroupHostsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: host.TeamGroupHostsTable, + Columns: []string{host.TeamGroupHostsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(teamgrouphost.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedTeamGroupHostsIDs(); len(nodes) > 0 && !_u.mutation.TeamGroupHostsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: host.TeamGroupHostsTable, + Columns: []string{host.TeamGroupHostsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(teamgrouphost.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.TeamGroupHostsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: host.TeamGroupHostsTable, + Columns: []string{host.TeamGroupHostsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(teamgrouphost.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(_u.modifiers...) + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{host.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// HostUpdateOne is the builder for updating a single Host entity. +type HostUpdateOne struct { + config + fields []string + hooks []Hook + mutation *HostMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *HostUpdateOne) SetDeletedAt(v time.Time) *HostUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *HostUpdateOne) SetNillableDeletedAt(v *time.Time) *HostUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *HostUpdateOne) ClearDeletedAt() *HostUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetUserID sets the "user_id" field. +func (_u *HostUpdateOne) SetUserID(v uuid.UUID) *HostUpdateOne { + _u.mutation.SetUserID(v) + return _u +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (_u *HostUpdateOne) SetNillableUserID(v *uuid.UUID) *HostUpdateOne { + if v != nil { + _u.SetUserID(*v) + } + return _u +} + +// SetHostname sets the "hostname" field. +func (_u *HostUpdateOne) SetHostname(v string) *HostUpdateOne { + _u.mutation.SetHostname(v) + return _u +} + +// SetNillableHostname sets the "hostname" field if the given value is not nil. +func (_u *HostUpdateOne) SetNillableHostname(v *string) *HostUpdateOne { + if v != nil { + _u.SetHostname(*v) + } + return _u +} + +// ClearHostname clears the value of the "hostname" field. +func (_u *HostUpdateOne) ClearHostname() *HostUpdateOne { + _u.mutation.ClearHostname() + return _u +} + +// SetArch sets the "arch" field. +func (_u *HostUpdateOne) SetArch(v string) *HostUpdateOne { + _u.mutation.SetArch(v) + return _u +} + +// SetNillableArch sets the "arch" field if the given value is not nil. +func (_u *HostUpdateOne) SetNillableArch(v *string) *HostUpdateOne { + if v != nil { + _u.SetArch(*v) + } + return _u +} + +// ClearArch clears the value of the "arch" field. +func (_u *HostUpdateOne) ClearArch() *HostUpdateOne { + _u.mutation.ClearArch() + return _u +} + +// SetCores sets the "cores" field. +func (_u *HostUpdateOne) SetCores(v int) *HostUpdateOne { + _u.mutation.ResetCores() + _u.mutation.SetCores(v) + return _u +} + +// SetNillableCores sets the "cores" field if the given value is not nil. +func (_u *HostUpdateOne) SetNillableCores(v *int) *HostUpdateOne { + if v != nil { + _u.SetCores(*v) + } + return _u +} + +// AddCores adds value to the "cores" field. +func (_u *HostUpdateOne) AddCores(v int) *HostUpdateOne { + _u.mutation.AddCores(v) + return _u +} + +// ClearCores clears the value of the "cores" field. +func (_u *HostUpdateOne) ClearCores() *HostUpdateOne { + _u.mutation.ClearCores() + return _u +} + +// SetWeight sets the "weight" field. +func (_u *HostUpdateOne) SetWeight(v int) *HostUpdateOne { + _u.mutation.ResetWeight() + _u.mutation.SetWeight(v) + return _u +} + +// SetNillableWeight sets the "weight" field if the given value is not nil. +func (_u *HostUpdateOne) SetNillableWeight(v *int) *HostUpdateOne { + if v != nil { + _u.SetWeight(*v) + } + return _u +} + +// AddWeight adds value to the "weight" field. +func (_u *HostUpdateOne) AddWeight(v int) *HostUpdateOne { + _u.mutation.AddWeight(v) + return _u +} + +// SetMemory sets the "memory" field. +func (_u *HostUpdateOne) SetMemory(v int64) *HostUpdateOne { + _u.mutation.ResetMemory() + _u.mutation.SetMemory(v) + return _u +} + +// SetNillableMemory sets the "memory" field if the given value is not nil. +func (_u *HostUpdateOne) SetNillableMemory(v *int64) *HostUpdateOne { + if v != nil { + _u.SetMemory(*v) + } + return _u +} + +// AddMemory adds value to the "memory" field. +func (_u *HostUpdateOne) AddMemory(v int64) *HostUpdateOne { + _u.mutation.AddMemory(v) + return _u +} + +// ClearMemory clears the value of the "memory" field. +func (_u *HostUpdateOne) ClearMemory() *HostUpdateOne { + _u.mutation.ClearMemory() + return _u +} + +// SetDisk sets the "disk" field. +func (_u *HostUpdateOne) SetDisk(v int64) *HostUpdateOne { + _u.mutation.ResetDisk() + _u.mutation.SetDisk(v) + return _u +} + +// SetNillableDisk sets the "disk" field if the given value is not nil. +func (_u *HostUpdateOne) SetNillableDisk(v *int64) *HostUpdateOne { + if v != nil { + _u.SetDisk(*v) + } + return _u +} + +// AddDisk adds value to the "disk" field. +func (_u *HostUpdateOne) AddDisk(v int64) *HostUpdateOne { + _u.mutation.AddDisk(v) + return _u +} + +// ClearDisk clears the value of the "disk" field. +func (_u *HostUpdateOne) ClearDisk() *HostUpdateOne { + _u.mutation.ClearDisk() + return _u +} + +// SetOs sets the "os" field. +func (_u *HostUpdateOne) SetOs(v string) *HostUpdateOne { + _u.mutation.SetOs(v) + return _u +} + +// SetNillableOs sets the "os" field if the given value is not nil. +func (_u *HostUpdateOne) SetNillableOs(v *string) *HostUpdateOne { + if v != nil { + _u.SetOs(*v) + } + return _u +} + +// ClearOs clears the value of the "os" field. +func (_u *HostUpdateOne) ClearOs() *HostUpdateOne { + _u.mutation.ClearOs() + return _u +} + +// SetExternalIP sets the "external_ip" field. +func (_u *HostUpdateOne) SetExternalIP(v string) *HostUpdateOne { + _u.mutation.SetExternalIP(v) + return _u +} + +// SetNillableExternalIP sets the "external_ip" field if the given value is not nil. +func (_u *HostUpdateOne) SetNillableExternalIP(v *string) *HostUpdateOne { + if v != nil { + _u.SetExternalIP(*v) + } + return _u +} + +// ClearExternalIP clears the value of the "external_ip" field. +func (_u *HostUpdateOne) ClearExternalIP() *HostUpdateOne { + _u.mutation.ClearExternalIP() + return _u +} + +// SetInternalIP sets the "internal_ip" field. +func (_u *HostUpdateOne) SetInternalIP(v string) *HostUpdateOne { + _u.mutation.SetInternalIP(v) + return _u +} + +// SetNillableInternalIP sets the "internal_ip" field if the given value is not nil. +func (_u *HostUpdateOne) SetNillableInternalIP(v *string) *HostUpdateOne { + if v != nil { + _u.SetInternalIP(*v) + } + return _u +} + +// ClearInternalIP clears the value of the "internal_ip" field. +func (_u *HostUpdateOne) ClearInternalIP() *HostUpdateOne { + _u.mutation.ClearInternalIP() + return _u +} + +// SetVersion sets the "version" field. +func (_u *HostUpdateOne) SetVersion(v string) *HostUpdateOne { + _u.mutation.SetVersion(v) + return _u +} + +// SetNillableVersion sets the "version" field if the given value is not nil. +func (_u *HostUpdateOne) SetNillableVersion(v *string) *HostUpdateOne { + if v != nil { + _u.SetVersion(*v) + } + return _u +} + +// ClearVersion clears the value of the "version" field. +func (_u *HostUpdateOne) ClearVersion() *HostUpdateOne { + _u.mutation.ClearVersion() + return _u +} + +// SetMachineID sets the "machine_id" field. +func (_u *HostUpdateOne) SetMachineID(v string) *HostUpdateOne { + _u.mutation.SetMachineID(v) + return _u +} + +// SetNillableMachineID sets the "machine_id" field if the given value is not nil. +func (_u *HostUpdateOne) SetNillableMachineID(v *string) *HostUpdateOne { + if v != nil { + _u.SetMachineID(*v) + } + return _u +} + +// ClearMachineID clears the value of the "machine_id" field. +func (_u *HostUpdateOne) ClearMachineID() *HostUpdateOne { + _u.mutation.ClearMachineID() + return _u +} + +// SetRemark sets the "remark" field. +func (_u *HostUpdateOne) SetRemark(v string) *HostUpdateOne { + _u.mutation.SetRemark(v) + return _u +} + +// SetNillableRemark sets the "remark" field if the given value is not nil. +func (_u *HostUpdateOne) SetNillableRemark(v *string) *HostUpdateOne { + if v != nil { + _u.SetRemark(*v) + } + return _u +} + +// ClearRemark clears the value of the "remark" field. +func (_u *HostUpdateOne) ClearRemark() *HostUpdateOne { + _u.mutation.ClearRemark() + return _u +} + +// SetCreatedAt sets the "created_at" field. +func (_u *HostUpdateOne) SetCreatedAt(v time.Time) *HostUpdateOne { + _u.mutation.SetCreatedAt(v) + return _u +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_u *HostUpdateOne) SetNillableCreatedAt(v *time.Time) *HostUpdateOne { + if v != nil { + _u.SetCreatedAt(*v) + } + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *HostUpdateOne) SetUpdatedAt(v time.Time) *HostUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// AddVMIDs adds the "vms" edge to the VirtualMachine entity by IDs. +func (_u *HostUpdateOne) AddVMIDs(ids ...string) *HostUpdateOne { + _u.mutation.AddVMIDs(ids...) + return _u +} + +// AddVms adds the "vms" edges to the VirtualMachine entity. +func (_u *HostUpdateOne) AddVms(v ...*VirtualMachine) *HostUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddVMIDs(ids...) +} + +// SetUser sets the "user" edge to the User entity. +func (_u *HostUpdateOne) SetUser(v *User) *HostUpdateOne { + return _u.SetUserID(v.ID) +} + +// AddGroupIDs adds the "groups" edge to the TeamGroup entity by IDs. +func (_u *HostUpdateOne) AddGroupIDs(ids ...uuid.UUID) *HostUpdateOne { + _u.mutation.AddGroupIDs(ids...) + return _u +} + +// AddGroups adds the "groups" edges to the TeamGroup entity. +func (_u *HostUpdateOne) AddGroups(v ...*TeamGroup) *HostUpdateOne { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddGroupIDs(ids...) +} + +// AddTeamGroupHostIDs adds the "team_group_hosts" edge to the TeamGroupHost entity by IDs. +func (_u *HostUpdateOne) AddTeamGroupHostIDs(ids ...uuid.UUID) *HostUpdateOne { + _u.mutation.AddTeamGroupHostIDs(ids...) + return _u +} + +// AddTeamGroupHosts adds the "team_group_hosts" edges to the TeamGroupHost entity. +func (_u *HostUpdateOne) AddTeamGroupHosts(v ...*TeamGroupHost) *HostUpdateOne { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddTeamGroupHostIDs(ids...) +} + +// Mutation returns the HostMutation object of the builder. +func (_u *HostUpdateOne) Mutation() *HostMutation { + return _u.mutation +} + +// ClearVms clears all "vms" edges to the VirtualMachine entity. +func (_u *HostUpdateOne) ClearVms() *HostUpdateOne { + _u.mutation.ClearVms() + return _u +} + +// RemoveVMIDs removes the "vms" edge to VirtualMachine entities by IDs. +func (_u *HostUpdateOne) RemoveVMIDs(ids ...string) *HostUpdateOne { + _u.mutation.RemoveVMIDs(ids...) + return _u +} + +// RemoveVms removes "vms" edges to VirtualMachine entities. +func (_u *HostUpdateOne) RemoveVms(v ...*VirtualMachine) *HostUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveVMIDs(ids...) +} + +// ClearUser clears the "user" edge to the User entity. +func (_u *HostUpdateOne) ClearUser() *HostUpdateOne { + _u.mutation.ClearUser() + return _u +} + +// ClearGroups clears all "groups" edges to the TeamGroup entity. +func (_u *HostUpdateOne) ClearGroups() *HostUpdateOne { + _u.mutation.ClearGroups() + return _u +} + +// RemoveGroupIDs removes the "groups" edge to TeamGroup entities by IDs. +func (_u *HostUpdateOne) RemoveGroupIDs(ids ...uuid.UUID) *HostUpdateOne { + _u.mutation.RemoveGroupIDs(ids...) + return _u +} + +// RemoveGroups removes "groups" edges to TeamGroup entities. +func (_u *HostUpdateOne) RemoveGroups(v ...*TeamGroup) *HostUpdateOne { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveGroupIDs(ids...) +} + +// ClearTeamGroupHosts clears all "team_group_hosts" edges to the TeamGroupHost entity. +func (_u *HostUpdateOne) ClearTeamGroupHosts() *HostUpdateOne { + _u.mutation.ClearTeamGroupHosts() + return _u +} + +// RemoveTeamGroupHostIDs removes the "team_group_hosts" edge to TeamGroupHost entities by IDs. +func (_u *HostUpdateOne) RemoveTeamGroupHostIDs(ids ...uuid.UUID) *HostUpdateOne { + _u.mutation.RemoveTeamGroupHostIDs(ids...) + return _u +} + +// RemoveTeamGroupHosts removes "team_group_hosts" edges to TeamGroupHost entities. +func (_u *HostUpdateOne) RemoveTeamGroupHosts(v ...*TeamGroupHost) *HostUpdateOne { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveTeamGroupHostIDs(ids...) +} + +// Where appends a list predicates to the HostUpdate builder. +func (_u *HostUpdateOne) Where(ps ...predicate.Host) *HostUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *HostUpdateOne) Select(field string, fields ...string) *HostUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated Host entity. +func (_u *HostUpdateOne) Save(ctx context.Context) (*Host, error) { + if err := _u.defaults(); err != nil { + return nil, err + } + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *HostUpdateOne) SaveX(ctx context.Context) *Host { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *HostUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *HostUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_u *HostUpdateOne) defaults() error { + if _, ok := _u.mutation.UpdatedAt(); !ok { + if host.UpdateDefaultUpdatedAt == nil { + return fmt.Errorf("db: uninitialized host.UpdateDefaultUpdatedAt (forgotten import db/runtime?)") + } + v := host.UpdateDefaultUpdatedAt() + _u.mutation.SetUpdatedAt(v) + } + return nil +} + +// check runs all checks and user-defined validators on the builder. +func (_u *HostUpdateOne) check() error { + if _u.mutation.UserCleared() && len(_u.mutation.UserIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "Host.user"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *HostUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *HostUpdateOne { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *HostUpdateOne) sqlSave(ctx context.Context) (_node *Host, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(host.Table, host.Columns, sqlgraph.NewFieldSpec(host.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "Host.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, host.FieldID) + for _, f := range fields { + if !host.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != host.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(host.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(host.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.Hostname(); ok { + _spec.SetField(host.FieldHostname, field.TypeString, value) + } + if _u.mutation.HostnameCleared() { + _spec.ClearField(host.FieldHostname, field.TypeString) + } + if value, ok := _u.mutation.Arch(); ok { + _spec.SetField(host.FieldArch, field.TypeString, value) + } + if _u.mutation.ArchCleared() { + _spec.ClearField(host.FieldArch, field.TypeString) + } + if value, ok := _u.mutation.Cores(); ok { + _spec.SetField(host.FieldCores, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedCores(); ok { + _spec.AddField(host.FieldCores, field.TypeInt, value) + } + if _u.mutation.CoresCleared() { + _spec.ClearField(host.FieldCores, field.TypeInt) + } + if value, ok := _u.mutation.Weight(); ok { + _spec.SetField(host.FieldWeight, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedWeight(); ok { + _spec.AddField(host.FieldWeight, field.TypeInt, value) + } + if value, ok := _u.mutation.Memory(); ok { + _spec.SetField(host.FieldMemory, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedMemory(); ok { + _spec.AddField(host.FieldMemory, field.TypeInt64, value) + } + if _u.mutation.MemoryCleared() { + _spec.ClearField(host.FieldMemory, field.TypeInt64) + } + if value, ok := _u.mutation.Disk(); ok { + _spec.SetField(host.FieldDisk, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedDisk(); ok { + _spec.AddField(host.FieldDisk, field.TypeInt64, value) + } + if _u.mutation.DiskCleared() { + _spec.ClearField(host.FieldDisk, field.TypeInt64) + } + if value, ok := _u.mutation.Os(); ok { + _spec.SetField(host.FieldOs, field.TypeString, value) + } + if _u.mutation.OsCleared() { + _spec.ClearField(host.FieldOs, field.TypeString) + } + if value, ok := _u.mutation.ExternalIP(); ok { + _spec.SetField(host.FieldExternalIP, field.TypeString, value) + } + if _u.mutation.ExternalIPCleared() { + _spec.ClearField(host.FieldExternalIP, field.TypeString) + } + if value, ok := _u.mutation.InternalIP(); ok { + _spec.SetField(host.FieldInternalIP, field.TypeString, value) + } + if _u.mutation.InternalIPCleared() { + _spec.ClearField(host.FieldInternalIP, field.TypeString) + } + if value, ok := _u.mutation.Version(); ok { + _spec.SetField(host.FieldVersion, field.TypeString, value) + } + if _u.mutation.VersionCleared() { + _spec.ClearField(host.FieldVersion, field.TypeString) + } + if value, ok := _u.mutation.MachineID(); ok { + _spec.SetField(host.FieldMachineID, field.TypeString, value) + } + if _u.mutation.MachineIDCleared() { + _spec.ClearField(host.FieldMachineID, field.TypeString) + } + if value, ok := _u.mutation.Remark(); ok { + _spec.SetField(host.FieldRemark, field.TypeString, value) + } + if _u.mutation.RemarkCleared() { + _spec.ClearField(host.FieldRemark, field.TypeString) + } + if value, ok := _u.mutation.CreatedAt(); ok { + _spec.SetField(host.FieldCreatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(host.FieldUpdatedAt, field.TypeTime, value) + } + if _u.mutation.VmsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: host.VmsTable, + Columns: []string{host.VmsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(virtualmachine.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedVmsIDs(); len(nodes) > 0 && !_u.mutation.VmsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: host.VmsTable, + Columns: []string{host.VmsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(virtualmachine.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.VmsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: host.VmsTable, + Columns: []string{host.VmsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(virtualmachine.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: host.UserTable, + Columns: []string{host.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: host.UserTable, + Columns: []string{host.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.GroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: host.GroupsTable, + Columns: host.GroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(teamgroup.FieldID, field.TypeUUID), + }, + } + createE := &TeamGroupHostCreate{config: _u.config, mutation: newTeamGroupHostMutation(_u.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedGroupsIDs(); len(nodes) > 0 && !_u.mutation.GroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: host.GroupsTable, + Columns: host.GroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(teamgroup.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &TeamGroupHostCreate{config: _u.config, mutation: newTeamGroupHostMutation(_u.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.GroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: host.GroupsTable, + Columns: host.GroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(teamgroup.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &TeamGroupHostCreate{config: _u.config, mutation: newTeamGroupHostMutation(_u.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.TeamGroupHostsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: host.TeamGroupHostsTable, + Columns: []string{host.TeamGroupHostsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(teamgrouphost.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedTeamGroupHostsIDs(); len(nodes) > 0 && !_u.mutation.TeamGroupHostsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: host.TeamGroupHostsTable, + Columns: []string{host.TeamGroupHostsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(teamgrouphost.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.TeamGroupHostsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: host.TeamGroupHostsTable, + Columns: []string{host.TeamGroupHostsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(teamgrouphost.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(_u.modifiers...) + _node = &Host{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{host.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/backend/db/intercept/intercept.go b/backend/db/intercept/intercept.go index f41be519..afbc3c12 100644 --- a/backend/db/intercept/intercept.go +++ b/backend/db/intercept/intercept.go @@ -9,19 +9,23 @@ import ( "entgo.io/ent/dialect/sql" "github.com/chaitin/MonkeyCode/backend/db" "github.com/chaitin/MonkeyCode/backend/db/audit" + "github.com/chaitin/MonkeyCode/backend/db/host" "github.com/chaitin/MonkeyCode/backend/db/image" "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/predicate" "github.com/chaitin/MonkeyCode/backend/db/team" "github.com/chaitin/MonkeyCode/backend/db/teamgroup" + "github.com/chaitin/MonkeyCode/backend/db/teamgrouphost" "github.com/chaitin/MonkeyCode/backend/db/teamgroupimage" "github.com/chaitin/MonkeyCode/backend/db/teamgroupmember" "github.com/chaitin/MonkeyCode/backend/db/teamgroupmodel" + "github.com/chaitin/MonkeyCode/backend/db/teamhost" "github.com/chaitin/MonkeyCode/backend/db/teamimage" "github.com/chaitin/MonkeyCode/backend/db/teammember" "github.com/chaitin/MonkeyCode/backend/db/teammodel" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/chaitin/MonkeyCode/backend/db/useridentity" + "github.com/chaitin/MonkeyCode/backend/db/virtualmachine" ) // The Query interface represents an operation that queries a graph. @@ -107,6 +111,33 @@ func (f TraverseAudit) Traverse(ctx context.Context, q db.Query) error { return fmt.Errorf("unexpected query type %T. expect *db.AuditQuery", q) } +// The HostFunc type is an adapter to allow the use of ordinary function as a Querier. +type HostFunc func(context.Context, *db.HostQuery) (db.Value, error) + +// Query calls f(ctx, q). +func (f HostFunc) Query(ctx context.Context, q db.Query) (db.Value, error) { + if q, ok := q.(*db.HostQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *db.HostQuery", q) +} + +// The TraverseHost type is an adapter to allow the use of ordinary function as Traverser. +type TraverseHost func(context.Context, *db.HostQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseHost) Intercept(next db.Querier) db.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseHost) Traverse(ctx context.Context, q db.Query) error { + if q, ok := q.(*db.HostQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *db.HostQuery", q) +} + // The ImageFunc type is an adapter to allow the use of ordinary function as a Querier. type ImageFunc func(context.Context, *db.ImageQuery) (db.Value, error) @@ -215,6 +246,33 @@ func (f TraverseTeamGroup) Traverse(ctx context.Context, q db.Query) error { return fmt.Errorf("unexpected query type %T. expect *db.TeamGroupQuery", q) } +// The TeamGroupHostFunc type is an adapter to allow the use of ordinary function as a Querier. +type TeamGroupHostFunc func(context.Context, *db.TeamGroupHostQuery) (db.Value, error) + +// Query calls f(ctx, q). +func (f TeamGroupHostFunc) Query(ctx context.Context, q db.Query) (db.Value, error) { + if q, ok := q.(*db.TeamGroupHostQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *db.TeamGroupHostQuery", q) +} + +// The TraverseTeamGroupHost type is an adapter to allow the use of ordinary function as Traverser. +type TraverseTeamGroupHost func(context.Context, *db.TeamGroupHostQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseTeamGroupHost) Intercept(next db.Querier) db.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseTeamGroupHost) Traverse(ctx context.Context, q db.Query) error { + if q, ok := q.(*db.TeamGroupHostQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *db.TeamGroupHostQuery", q) +} + // The TeamGroupImageFunc type is an adapter to allow the use of ordinary function as a Querier. type TeamGroupImageFunc func(context.Context, *db.TeamGroupImageQuery) (db.Value, error) @@ -296,6 +354,33 @@ func (f TraverseTeamGroupModel) Traverse(ctx context.Context, q db.Query) error return fmt.Errorf("unexpected query type %T. expect *db.TeamGroupModelQuery", q) } +// The TeamHostFunc type is an adapter to allow the use of ordinary function as a Querier. +type TeamHostFunc func(context.Context, *db.TeamHostQuery) (db.Value, error) + +// Query calls f(ctx, q). +func (f TeamHostFunc) Query(ctx context.Context, q db.Query) (db.Value, error) { + if q, ok := q.(*db.TeamHostQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *db.TeamHostQuery", q) +} + +// The TraverseTeamHost type is an adapter to allow the use of ordinary function as Traverser. +type TraverseTeamHost func(context.Context, *db.TeamHostQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseTeamHost) Intercept(next db.Querier) db.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseTeamHost) Traverse(ctx context.Context, q db.Query) error { + if q, ok := q.(*db.TeamHostQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *db.TeamHostQuery", q) +} + // The TeamImageFunc type is an adapter to allow the use of ordinary function as a Querier. type TeamImageFunc func(context.Context, *db.TeamImageQuery) (db.Value, error) @@ -431,11 +516,40 @@ func (f TraverseUserIdentity) Traverse(ctx context.Context, q db.Query) error { return fmt.Errorf("unexpected query type %T. expect *db.UserIdentityQuery", q) } +// The VirtualMachineFunc type is an adapter to allow the use of ordinary function as a Querier. +type VirtualMachineFunc func(context.Context, *db.VirtualMachineQuery) (db.Value, error) + +// Query calls f(ctx, q). +func (f VirtualMachineFunc) Query(ctx context.Context, q db.Query) (db.Value, error) { + if q, ok := q.(*db.VirtualMachineQuery); ok { + return f(ctx, q) + } + return nil, fmt.Errorf("unexpected query type %T. expect *db.VirtualMachineQuery", q) +} + +// The TraverseVirtualMachine type is an adapter to allow the use of ordinary function as Traverser. +type TraverseVirtualMachine func(context.Context, *db.VirtualMachineQuery) error + +// Intercept is a dummy implementation of Intercept that returns the next Querier in the pipeline. +func (f TraverseVirtualMachine) Intercept(next db.Querier) db.Querier { + return next +} + +// Traverse calls f(ctx, q). +func (f TraverseVirtualMachine) Traverse(ctx context.Context, q db.Query) error { + if q, ok := q.(*db.VirtualMachineQuery); ok { + return f(ctx, q) + } + return fmt.Errorf("unexpected query type %T. expect *db.VirtualMachineQuery", q) +} + // NewQuery returns the generic Query interface for the given typed query. func NewQuery(q db.Query) (Query, error) { switch q := q.(type) { case *db.AuditQuery: return &query[*db.AuditQuery, predicate.Audit, audit.OrderOption]{typ: db.TypeAudit, tq: q}, nil + case *db.HostQuery: + return &query[*db.HostQuery, predicate.Host, host.OrderOption]{typ: db.TypeHost, tq: q}, nil case *db.ImageQuery: return &query[*db.ImageQuery, predicate.Image, image.OrderOption]{typ: db.TypeImage, tq: q}, nil case *db.ModelQuery: @@ -444,12 +558,16 @@ func NewQuery(q db.Query) (Query, error) { return &query[*db.TeamQuery, predicate.Team, team.OrderOption]{typ: db.TypeTeam, tq: q}, nil case *db.TeamGroupQuery: return &query[*db.TeamGroupQuery, predicate.TeamGroup, teamgroup.OrderOption]{typ: db.TypeTeamGroup, tq: q}, nil + case *db.TeamGroupHostQuery: + return &query[*db.TeamGroupHostQuery, predicate.TeamGroupHost, teamgrouphost.OrderOption]{typ: db.TypeTeamGroupHost, tq: q}, nil case *db.TeamGroupImageQuery: return &query[*db.TeamGroupImageQuery, predicate.TeamGroupImage, teamgroupimage.OrderOption]{typ: db.TypeTeamGroupImage, tq: q}, nil case *db.TeamGroupMemberQuery: return &query[*db.TeamGroupMemberQuery, predicate.TeamGroupMember, teamgroupmember.OrderOption]{typ: db.TypeTeamGroupMember, tq: q}, nil case *db.TeamGroupModelQuery: return &query[*db.TeamGroupModelQuery, predicate.TeamGroupModel, teamgroupmodel.OrderOption]{typ: db.TypeTeamGroupModel, tq: q}, nil + case *db.TeamHostQuery: + return &query[*db.TeamHostQuery, predicate.TeamHost, teamhost.OrderOption]{typ: db.TypeTeamHost, tq: q}, nil case *db.TeamImageQuery: return &query[*db.TeamImageQuery, predicate.TeamImage, teamimage.OrderOption]{typ: db.TypeTeamImage, tq: q}, nil case *db.TeamMemberQuery: @@ -460,6 +578,8 @@ func NewQuery(q db.Query) (Query, error) { return &query[*db.UserQuery, predicate.User, user.OrderOption]{typ: db.TypeUser, tq: q}, nil case *db.UserIdentityQuery: return &query[*db.UserIdentityQuery, predicate.UserIdentity, useridentity.OrderOption]{typ: db.TypeUserIdentity, tq: q}, nil + case *db.VirtualMachineQuery: + return &query[*db.VirtualMachineQuery, predicate.VirtualMachine, virtualmachine.OrderOption]{typ: db.TypeVirtualMachine, tq: q}, nil default: return nil, fmt.Errorf("unknown query type %T", q) } diff --git a/backend/db/migrate/schema.go b/backend/db/migrate/schema.go index b78b0f7b..feadfd4b 100644 --- a/backend/db/migrate/schema.go +++ b/backend/db/migrate/schema.go @@ -34,6 +34,40 @@ var ( }, }, } + // HostsColumns holds the columns for the "hosts" table. + HostsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "hostname", Type: field.TypeString, Nullable: true}, + {Name: "arch", Type: field.TypeString, Nullable: true}, + {Name: "cores", Type: field.TypeInt, Nullable: true}, + {Name: "weight", Type: field.TypeInt, Default: 1}, + {Name: "memory", Type: field.TypeInt64, Nullable: true}, + {Name: "disk", Type: field.TypeInt64, Nullable: true}, + {Name: "os", Type: field.TypeString, Nullable: true}, + {Name: "external_ip", Type: field.TypeString, Nullable: true}, + {Name: "internal_ip", Type: field.TypeString, Nullable: true}, + {Name: "version", Type: field.TypeString, Nullable: true}, + {Name: "machine_id", Type: field.TypeString, Nullable: true}, + {Name: "remark", Type: field.TypeString, Nullable: true}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "user_id", Type: field.TypeUUID}, + } + // HostsTable holds the schema information for the "hosts" table. + HostsTable = &schema.Table{ + Name: "hosts", + Columns: HostsColumns, + PrimaryKey: []*schema.Column{HostsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "hosts_users_hosts", + Columns: []*schema.Column{HostsColumns[16]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + } // ImagesColumns holds the columns for the "images" table. ImagesColumns = []*schema.Column{ {Name: "id", Type: field.TypeUUID, Unique: true}, @@ -129,6 +163,40 @@ var ( }, }, } + // TeamGroupHostsColumns holds the columns for the "team_group_hosts" table. + TeamGroupHostsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID, Unique: true}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "group_id", Type: field.TypeUUID}, + {Name: "host_id", Type: field.TypeString}, + } + // TeamGroupHostsTable holds the schema information for the "team_group_hosts" table. + TeamGroupHostsTable = &schema.Table{ + Name: "team_group_hosts", + Columns: TeamGroupHostsColumns, + PrimaryKey: []*schema.Column{TeamGroupHostsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "team_group_hosts_team_groups_group", + Columns: []*schema.Column{TeamGroupHostsColumns[2]}, + RefColumns: []*schema.Column{TeamGroupsColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "team_group_hosts_hosts_host", + Columns: []*schema.Column{TeamGroupHostsColumns[3]}, + RefColumns: []*schema.Column{HostsColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "teamgrouphost_group_id_host_id", + Unique: true, + Columns: []*schema.Column{TeamGroupHostsColumns[2], TeamGroupHostsColumns[3]}, + }, + }, + } // TeamGroupImagesColumns holds the columns for the "team_group_images" table. TeamGroupImagesColumns = []*schema.Column{ {Name: "id", Type: field.TypeUUID, Unique: true}, @@ -231,6 +299,33 @@ var ( }, }, } + // TeamHostsColumns holds the columns for the "team_hosts" table. + TeamHostsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeUUID, Unique: true}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "team_id", Type: field.TypeUUID}, + {Name: "host_id", Type: field.TypeString}, + } + // TeamHostsTable holds the schema information for the "team_hosts" table. + TeamHostsTable = &schema.Table{ + Name: "team_hosts", + Columns: TeamHostsColumns, + PrimaryKey: []*schema.Column{TeamHostsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "team_hosts_teams_team", + Columns: []*schema.Column{TeamHostsColumns[2]}, + RefColumns: []*schema.Column{TeamsColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "team_hosts_hosts_host", + Columns: []*schema.Column{TeamHostsColumns[3]}, + RefColumns: []*schema.Column{HostsColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + } // TeamImagesColumns holds the columns for the "team_images" table. TeamImagesColumns = []*schema.Column{ {Name: "id", Type: field.TypeUUID}, @@ -382,21 +477,79 @@ var ( }, }, } + // VirtualmachinesColumns holds the columns for the "virtualmachines" table. + VirtualmachinesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true}, + {Name: "deleted_at", Type: field.TypeTime, Nullable: true}, + {Name: "environment_id", Type: field.TypeString, Nullable: true}, + {Name: "name", Type: field.TypeString}, + {Name: "hostname", Type: field.TypeString, Nullable: true}, + {Name: "arch", Type: field.TypeString, Nullable: true}, + {Name: "cores", Type: field.TypeInt, Nullable: true}, + {Name: "memory", Type: field.TypeInt64, Nullable: true}, + {Name: "os", Type: field.TypeString, Nullable: true}, + {Name: "external_ip", Type: field.TypeString, Nullable: true}, + {Name: "internal_ip", Type: field.TypeString, Nullable: true}, + {Name: "ttl_kind", Type: field.TypeString, Nullable: true}, + {Name: "ttl", Type: field.TypeInt64, Nullable: true}, + {Name: "version", Type: field.TypeString, Nullable: true}, + {Name: "machine_id", Type: field.TypeString, Nullable: true}, + {Name: "repo_url", Type: field.TypeString, Nullable: true}, + {Name: "repo_filename", Type: field.TypeString, Nullable: true}, + {Name: "branch", Type: field.TypeString, Nullable: true}, + {Name: "is_recycled", Type: field.TypeBool, Nullable: true}, + {Name: "conditions", Type: field.TypeJSON, Nullable: true}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "updated_at", Type: field.TypeTime}, + {Name: "host_id", Type: field.TypeString}, + {Name: "model_id", Type: field.TypeUUID, Nullable: true}, + {Name: "user_id", Type: field.TypeUUID, Nullable: true}, + } + // VirtualmachinesTable holds the schema information for the "virtualmachines" table. + VirtualmachinesTable = &schema.Table{ + Name: "virtualmachines", + Columns: VirtualmachinesColumns, + PrimaryKey: []*schema.Column{VirtualmachinesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "virtualmachines_hosts_vms", + Columns: []*schema.Column{VirtualmachinesColumns[22]}, + RefColumns: []*schema.Column{HostsColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "virtualmachines_models_vms", + Columns: []*schema.Column{VirtualmachinesColumns[23]}, + RefColumns: []*schema.Column{ModelsColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "virtualmachines_users_vms", + Columns: []*schema.Column{VirtualmachinesColumns[24]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + } // Tables holds all the tables in the schema. Tables = []*schema.Table{ AuditsTable, + HostsTable, ImagesTable, ModelsTable, TeamsTable, TeamGroupsTable, + TeamGroupHostsTable, TeamGroupImagesTable, TeamGroupMembersTable, TeamGroupModelsTable, + TeamHostsTable, TeamImagesTable, TeamMembersTable, TeamModelsTable, UsersTable, UserIdentitiesTable, + VirtualmachinesTable, } ) @@ -405,6 +558,10 @@ func init() { AuditsTable.Annotation = &entsql.Annotation{ Table: "audits", } + HostsTable.ForeignKeys[0].RefTable = UsersTable + HostsTable.Annotation = &entsql.Annotation{ + Table: "hosts", + } ImagesTable.ForeignKeys[0].RefTable = UsersTable ImagesTable.Annotation = &entsql.Annotation{ Table: "images", @@ -420,6 +577,11 @@ func init() { TeamGroupsTable.Annotation = &entsql.Annotation{ Table: "team_groups", } + TeamGroupHostsTable.ForeignKeys[0].RefTable = TeamGroupsTable + TeamGroupHostsTable.ForeignKeys[1].RefTable = HostsTable + TeamGroupHostsTable.Annotation = &entsql.Annotation{ + Table: "team_group_hosts", + } TeamGroupImagesTable.ForeignKeys[0].RefTable = TeamGroupsTable TeamGroupImagesTable.ForeignKeys[1].RefTable = ImagesTable TeamGroupImagesTable.Annotation = &entsql.Annotation{ @@ -435,6 +597,11 @@ func init() { TeamGroupModelsTable.Annotation = &entsql.Annotation{ Table: "team_group_models", } + TeamHostsTable.ForeignKeys[0].RefTable = TeamsTable + TeamHostsTable.ForeignKeys[1].RefTable = HostsTable + TeamHostsTable.Annotation = &entsql.Annotation{ + Table: "team_hosts", + } TeamImagesTable.ForeignKeys[0].RefTable = TeamsTable TeamImagesTable.ForeignKeys[1].RefTable = ImagesTable TeamImagesTable.Annotation = &entsql.Annotation{ @@ -457,4 +624,10 @@ func init() { UserIdentitiesTable.Annotation = &entsql.Annotation{ Table: "user_identities", } + VirtualmachinesTable.ForeignKeys[0].RefTable = HostsTable + VirtualmachinesTable.ForeignKeys[1].RefTable = ModelsTable + VirtualmachinesTable.ForeignKeys[2].RefTable = UsersTable + VirtualmachinesTable.Annotation = &entsql.Annotation{ + Table: "virtualmachines", + } } diff --git a/backend/db/model.go b/backend/db/model.go index 43df0a49..9c0a070e 100644 --- a/backend/db/model.go +++ b/backend/db/model.go @@ -63,13 +63,15 @@ type ModelEdges struct { Teams []*Team `json:"teams,omitempty"` // Groups holds the value of the groups edge. Groups []*TeamGroup `json:"groups,omitempty"` + // Vms holds the value of the vms edge. + Vms []*VirtualMachine `json:"vms,omitempty"` // TeamModels holds the value of the team_models edge. TeamModels []*TeamModel `json:"team_models,omitempty"` // TeamGroupModels holds the value of the team_group_models edge. TeamGroupModels []*TeamGroupModel `json:"team_group_models,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [5]bool + loadedTypes [6]bool } // UserOrErr returns the User value or an error if the edge @@ -101,10 +103,19 @@ func (e ModelEdges) GroupsOrErr() ([]*TeamGroup, error) { return nil, &NotLoadedError{edge: "groups"} } +// VmsOrErr returns the Vms value or an error if the edge +// was not loaded in eager-loading. +func (e ModelEdges) VmsOrErr() ([]*VirtualMachine, error) { + if e.loadedTypes[3] { + return e.Vms, nil + } + return nil, &NotLoadedError{edge: "vms"} +} + // TeamModelsOrErr returns the TeamModels value or an error if the edge // was not loaded in eager-loading. func (e ModelEdges) TeamModelsOrErr() ([]*TeamModel, error) { - if e.loadedTypes[3] { + if e.loadedTypes[4] { return e.TeamModels, nil } return nil, &NotLoadedError{edge: "team_models"} @@ -113,7 +124,7 @@ func (e ModelEdges) TeamModelsOrErr() ([]*TeamModel, error) { // TeamGroupModelsOrErr returns the TeamGroupModels value or an error if the edge // was not loaded in eager-loading. func (e ModelEdges) TeamGroupModelsOrErr() ([]*TeamGroupModel, error) { - if e.loadedTypes[4] { + if e.loadedTypes[5] { return e.TeamGroupModels, nil } return nil, &NotLoadedError{edge: "team_group_models"} @@ -275,6 +286,11 @@ func (_m *Model) QueryGroups() *TeamGroupQuery { return NewModelClient(_m.config).QueryGroups(_m) } +// QueryVms queries the "vms" edge of the Model entity. +func (_m *Model) QueryVms() *VirtualMachineQuery { + return NewModelClient(_m.config).QueryVms(_m) +} + // QueryTeamModels queries the "team_models" edge of the Model entity. func (_m *Model) QueryTeamModels() *TeamModelQuery { return NewModelClient(_m.config).QueryTeamModels(_m) diff --git a/backend/db/model/model.go b/backend/db/model/model.go index da994d08..35deaac7 100644 --- a/backend/db/model/model.go +++ b/backend/db/model/model.go @@ -51,6 +51,8 @@ const ( EdgeTeams = "teams" // EdgeGroups holds the string denoting the groups edge name in mutations. EdgeGroups = "groups" + // EdgeVms holds the string denoting the vms edge name in mutations. + EdgeVms = "vms" // EdgeTeamModels holds the string denoting the team_models edge name in mutations. EdgeTeamModels = "team_models" // EdgeTeamGroupModels holds the string denoting the team_group_models edge name in mutations. @@ -74,6 +76,13 @@ const ( // GroupsInverseTable is the table name for the TeamGroup entity. // It exists in this package in order to avoid circular dependency with the "teamgroup" package. GroupsInverseTable = "team_groups" + // VmsTable is the table that holds the vms relation/edge. + VmsTable = "virtualmachines" + // VmsInverseTable is the table name for the VirtualMachine entity. + // It exists in this package in order to avoid circular dependency with the "virtualmachine" package. + VmsInverseTable = "virtualmachines" + // VmsColumn is the table column denoting the vms relation/edge. + VmsColumn = "model_id" // TeamModelsTable is the table that holds the team_models relation/edge. TeamModelsTable = "team_models" // TeamModelsInverseTable is the table name for the TeamModel entity. @@ -273,6 +282,20 @@ func ByGroups(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { } } +// ByVmsCount orders the results by vms count. +func ByVmsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newVmsStep(), opts...) + } +} + +// ByVms orders the results by vms terms. +func ByVms(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newVmsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + // ByTeamModelsCount orders the results by team_models count. func ByTeamModelsCount(opts ...sql.OrderTermOption) OrderOption { return func(s *sql.Selector) { @@ -321,6 +344,13 @@ func newGroupsStep() *sqlgraph.Step { sqlgraph.Edge(sqlgraph.M2M, true, GroupsTable, GroupsPrimaryKey...), ) } +func newVmsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(VmsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, VmsTable, VmsColumn), + ) +} func newTeamModelsStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), diff --git a/backend/db/model/where.go b/backend/db/model/where.go index c59ce3fd..2ef7840f 100644 --- a/backend/db/model/where.go +++ b/backend/db/model/where.go @@ -995,6 +995,29 @@ func HasGroupsWith(preds ...predicate.TeamGroup) predicate.Model { }) } +// HasVms applies the HasEdge predicate on the "vms" edge. +func HasVms() predicate.Model { + return predicate.Model(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, VmsTable, VmsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasVmsWith applies the HasEdge predicate on the "vms" edge with a given conditions (other predicates). +func HasVmsWith(preds ...predicate.VirtualMachine) predicate.Model { + return predicate.Model(func(s *sql.Selector) { + step := newVmsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + // HasTeamModels applies the HasEdge predicate on the "team_models" edge. func HasTeamModels() predicate.Model { return predicate.Model(func(s *sql.Selector) { diff --git a/backend/db/model_create.go b/backend/db/model_create.go index efe18709..ac004337 100644 --- a/backend/db/model_create.go +++ b/backend/db/model_create.go @@ -18,6 +18,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/teamgroupmodel" "github.com/chaitin/MonkeyCode/backend/db/teammodel" "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/virtualmachine" "github.com/google/uuid" ) @@ -240,6 +241,21 @@ func (_c *ModelCreate) AddGroups(v ...*TeamGroup) *ModelCreate { return _c.AddGroupIDs(ids...) } +// AddVMIDs adds the "vms" edge to the VirtualMachine entity by IDs. +func (_c *ModelCreate) AddVMIDs(ids ...string) *ModelCreate { + _c.mutation.AddVMIDs(ids...) + return _c +} + +// AddVms adds the "vms" edges to the VirtualMachine entity. +func (_c *ModelCreate) AddVms(v ...*VirtualMachine) *ModelCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddVMIDs(ids...) +} + // AddTeamModelIDs adds the "team_models" edge to the TeamModel entity by IDs. func (_c *ModelCreate) AddTeamModelIDs(ids ...uuid.UUID) *ModelCreate { _c.mutation.AddTeamModelIDs(ids...) @@ -526,6 +542,22 @@ func (_c *ModelCreate) createSpec() (*Model, *sqlgraph.CreateSpec) { edge.Target.Fields = specE.Fields _spec.Edges = append(_spec.Edges, edge) } + if nodes := _c.mutation.VmsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: model.VmsTable, + Columns: []string{model.VmsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(virtualmachine.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } if nodes := _c.mutation.TeamModelsIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, diff --git a/backend/db/model_query.go b/backend/db/model_query.go index 0dad27e9..074e3219 100644 --- a/backend/db/model_query.go +++ b/backend/db/model_query.go @@ -20,6 +20,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/teamgroupmodel" "github.com/chaitin/MonkeyCode/backend/db/teammodel" "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/virtualmachine" "github.com/google/uuid" ) @@ -33,6 +34,7 @@ type ModelQuery struct { withUser *UserQuery withTeams *TeamQuery withGroups *TeamGroupQuery + withVms *VirtualMachineQuery withTeamModels *TeamModelQuery withTeamGroupModels *TeamGroupModelQuery modifiers []func(*sql.Selector) @@ -138,6 +140,28 @@ func (_q *ModelQuery) QueryGroups() *TeamGroupQuery { return query } +// QueryVms chains the current query on the "vms" edge. +func (_q *ModelQuery) QueryVms() *VirtualMachineQuery { + query := (&VirtualMachineClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(model.Table, model.FieldID, selector), + sqlgraph.To(virtualmachine.Table, virtualmachine.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, model.VmsTable, model.VmsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + // QueryTeamModels chains the current query on the "team_models" edge. func (_q *ModelQuery) QueryTeamModels() *TeamModelQuery { query := (&TeamModelClient{config: _q.config}).Query() @@ -377,6 +401,7 @@ func (_q *ModelQuery) Clone() *ModelQuery { withUser: _q.withUser.Clone(), withTeams: _q.withTeams.Clone(), withGroups: _q.withGroups.Clone(), + withVms: _q.withVms.Clone(), withTeamModels: _q.withTeamModels.Clone(), withTeamGroupModels: _q.withTeamGroupModels.Clone(), // clone intermediate query. @@ -419,6 +444,17 @@ func (_q *ModelQuery) WithGroups(opts ...func(*TeamGroupQuery)) *ModelQuery { return _q } +// WithVms tells the query-builder to eager-load the nodes that are connected to +// the "vms" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *ModelQuery) WithVms(opts ...func(*VirtualMachineQuery)) *ModelQuery { + query := (&VirtualMachineClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withVms = query + return _q +} + // WithTeamModels tells the query-builder to eager-load the nodes that are connected to // the "team_models" edge. The optional arguments are used to configure the query builder of the edge. func (_q *ModelQuery) WithTeamModels(opts ...func(*TeamModelQuery)) *ModelQuery { @@ -519,10 +555,11 @@ func (_q *ModelQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Model, var ( nodes = []*Model{} _spec = _q.querySpec() - loadedTypes = [5]bool{ + loadedTypes = [6]bool{ _q.withUser != nil, _q.withTeams != nil, _q.withGroups != nil, + _q.withVms != nil, _q.withTeamModels != nil, _q.withTeamGroupModels != nil, } @@ -568,6 +605,13 @@ func (_q *ModelQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Model, return nil, err } } + if query := _q.withVms; query != nil { + if err := _q.loadVms(ctx, query, nodes, + func(n *Model) { n.Edges.Vms = []*VirtualMachine{} }, + func(n *Model, e *VirtualMachine) { n.Edges.Vms = append(n.Edges.Vms, e) }); err != nil { + return nil, err + } + } if query := _q.withTeamModels; query != nil { if err := _q.loadTeamModels(ctx, query, nodes, func(n *Model) { n.Edges.TeamModels = []*TeamModel{} }, @@ -736,6 +780,36 @@ func (_q *ModelQuery) loadGroups(ctx context.Context, query *TeamGroupQuery, nod } return nil } +func (_q *ModelQuery) loadVms(ctx context.Context, query *VirtualMachineQuery, nodes []*Model, init func(*Model), assign func(*Model, *VirtualMachine)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[uuid.UUID]*Model) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(virtualmachine.FieldModelID) + } + query.Where(predicate.VirtualMachine(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(model.VmsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.ModelID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "model_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} func (_q *ModelQuery) loadTeamModels(ctx context.Context, query *TeamModelQuery, nodes []*Model, init func(*Model), assign func(*Model, *TeamModel)) error { fks := make([]driver.Value, 0, len(nodes)) nodeids := make(map[uuid.UUID]*Model) diff --git a/backend/db/model_update.go b/backend/db/model_update.go index 336cff33..9ca3fbba 100644 --- a/backend/db/model_update.go +++ b/backend/db/model_update.go @@ -18,6 +18,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/teamgroupmodel" "github.com/chaitin/MonkeyCode/backend/db/teammodel" "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/virtualmachine" "github.com/google/uuid" ) @@ -328,6 +329,21 @@ func (_u *ModelUpdate) AddGroups(v ...*TeamGroup) *ModelUpdate { return _u.AddGroupIDs(ids...) } +// AddVMIDs adds the "vms" edge to the VirtualMachine entity by IDs. +func (_u *ModelUpdate) AddVMIDs(ids ...string) *ModelUpdate { + _u.mutation.AddVMIDs(ids...) + return _u +} + +// AddVms adds the "vms" edges to the VirtualMachine entity. +func (_u *ModelUpdate) AddVms(v ...*VirtualMachine) *ModelUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddVMIDs(ids...) +} + // AddTeamModelIDs adds the "team_models" edge to the TeamModel entity by IDs. func (_u *ModelUpdate) AddTeamModelIDs(ids ...uuid.UUID) *ModelUpdate { _u.mutation.AddTeamModelIDs(ids...) @@ -411,6 +427,27 @@ func (_u *ModelUpdate) RemoveGroups(v ...*TeamGroup) *ModelUpdate { return _u.RemoveGroupIDs(ids...) } +// ClearVms clears all "vms" edges to the VirtualMachine entity. +func (_u *ModelUpdate) ClearVms() *ModelUpdate { + _u.mutation.ClearVms() + return _u +} + +// RemoveVMIDs removes the "vms" edge to VirtualMachine entities by IDs. +func (_u *ModelUpdate) RemoveVMIDs(ids ...string) *ModelUpdate { + _u.mutation.RemoveVMIDs(ids...) + return _u +} + +// RemoveVms removes "vms" edges to VirtualMachine entities. +func (_u *ModelUpdate) RemoveVms(v ...*VirtualMachine) *ModelUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveVMIDs(ids...) +} + // ClearTeamModels clears all "team_models" edges to the TeamModel entity. func (_u *ModelUpdate) ClearTeamModels() *ModelUpdate { _u.mutation.ClearTeamModels() @@ -753,6 +790,51 @@ func (_u *ModelUpdate) sqlSave(ctx context.Context) (_node int, err error) { edge.Target.Fields = specE.Fields _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if _u.mutation.VmsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: model.VmsTable, + Columns: []string{model.VmsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(virtualmachine.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedVmsIDs(); len(nodes) > 0 && !_u.mutation.VmsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: model.VmsTable, + Columns: []string{model.VmsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(virtualmachine.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.VmsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: model.VmsTable, + Columns: []string{model.VmsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(virtualmachine.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if _u.mutation.TeamModelsCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, @@ -1158,6 +1240,21 @@ func (_u *ModelUpdateOne) AddGroups(v ...*TeamGroup) *ModelUpdateOne { return _u.AddGroupIDs(ids...) } +// AddVMIDs adds the "vms" edge to the VirtualMachine entity by IDs. +func (_u *ModelUpdateOne) AddVMIDs(ids ...string) *ModelUpdateOne { + _u.mutation.AddVMIDs(ids...) + return _u +} + +// AddVms adds the "vms" edges to the VirtualMachine entity. +func (_u *ModelUpdateOne) AddVms(v ...*VirtualMachine) *ModelUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddVMIDs(ids...) +} + // AddTeamModelIDs adds the "team_models" edge to the TeamModel entity by IDs. func (_u *ModelUpdateOne) AddTeamModelIDs(ids ...uuid.UUID) *ModelUpdateOne { _u.mutation.AddTeamModelIDs(ids...) @@ -1241,6 +1338,27 @@ func (_u *ModelUpdateOne) RemoveGroups(v ...*TeamGroup) *ModelUpdateOne { return _u.RemoveGroupIDs(ids...) } +// ClearVms clears all "vms" edges to the VirtualMachine entity. +func (_u *ModelUpdateOne) ClearVms() *ModelUpdateOne { + _u.mutation.ClearVms() + return _u +} + +// RemoveVMIDs removes the "vms" edge to VirtualMachine entities by IDs. +func (_u *ModelUpdateOne) RemoveVMIDs(ids ...string) *ModelUpdateOne { + _u.mutation.RemoveVMIDs(ids...) + return _u +} + +// RemoveVms removes "vms" edges to VirtualMachine entities. +func (_u *ModelUpdateOne) RemoveVms(v ...*VirtualMachine) *ModelUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveVMIDs(ids...) +} + // ClearTeamModels clears all "team_models" edges to the TeamModel entity. func (_u *ModelUpdateOne) ClearTeamModels() *ModelUpdateOne { _u.mutation.ClearTeamModels() @@ -1613,6 +1731,51 @@ func (_u *ModelUpdateOne) sqlSave(ctx context.Context) (_node *Model, err error) edge.Target.Fields = specE.Fields _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if _u.mutation.VmsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: model.VmsTable, + Columns: []string{model.VmsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(virtualmachine.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedVmsIDs(); len(nodes) > 0 && !_u.mutation.VmsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: model.VmsTable, + Columns: []string{model.VmsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(virtualmachine.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.VmsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: model.VmsTable, + Columns: []string{model.VmsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(virtualmachine.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if _u.mutation.TeamModelsCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, diff --git a/backend/db/mutation.go b/backend/db/mutation.go index 0f567dfe..521e4060 100644 --- a/backend/db/mutation.go +++ b/backend/db/mutation.go @@ -13,19 +13,24 @@ import ( "entgo.io/ent/dialect/sql" "github.com/chaitin/MonkeyCode/backend/consts" "github.com/chaitin/MonkeyCode/backend/db/audit" + "github.com/chaitin/MonkeyCode/backend/db/host" "github.com/chaitin/MonkeyCode/backend/db/image" "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/predicate" "github.com/chaitin/MonkeyCode/backend/db/team" "github.com/chaitin/MonkeyCode/backend/db/teamgroup" + "github.com/chaitin/MonkeyCode/backend/db/teamgrouphost" "github.com/chaitin/MonkeyCode/backend/db/teamgroupimage" "github.com/chaitin/MonkeyCode/backend/db/teamgroupmember" "github.com/chaitin/MonkeyCode/backend/db/teamgroupmodel" + "github.com/chaitin/MonkeyCode/backend/db/teamhost" "github.com/chaitin/MonkeyCode/backend/db/teamimage" "github.com/chaitin/MonkeyCode/backend/db/teammember" "github.com/chaitin/MonkeyCode/backend/db/teammodel" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/chaitin/MonkeyCode/backend/db/useridentity" + "github.com/chaitin/MonkeyCode/backend/db/virtualmachine" + "github.com/chaitin/MonkeyCode/backend/ent/types" "github.com/google/uuid" ) @@ -39,18 +44,22 @@ const ( // Node types. TypeAudit = "Audit" + TypeHost = "Host" TypeImage = "Image" TypeModel = "Model" TypeTeam = "Team" TypeTeamGroup = "TeamGroup" + TypeTeamGroupHost = "TeamGroupHost" TypeTeamGroupImage = "TeamGroupImage" TypeTeamGroupMember = "TeamGroupMember" TypeTeamGroupModel = "TeamGroupModel" + TypeTeamHost = "TeamHost" TypeTeamImage = "TeamImage" TypeTeamMember = "TeamMember" TypeTeamModel = "TeamModel" TypeUser = "User" TypeUserIdentity = "UserIdentity" + TypeVirtualMachine = "VirtualMachine" ) // AuditMutation represents an operation that mutates the Audit nodes in the graph. @@ -785,48 +794,59 @@ func (m *AuditMutation) ResetEdge(name string) error { return fmt.Errorf("unknown Audit edge %s", name) } -// ImageMutation represents an operation that mutates the Image nodes in the graph. -type ImageMutation struct { +// HostMutation represents an operation that mutates the Host nodes in the graph. +type HostMutation struct { config - op Op - typ string - id *uuid.UUID - deleted_at *time.Time - name *string - remark *string - created_at *time.Time - updated_at *time.Time - clearedFields map[string]struct{} - user *uuid.UUID - cleareduser bool - teams map[uuid.UUID]struct{} - removedteams map[uuid.UUID]struct{} - clearedteams bool - groups map[uuid.UUID]struct{} - removedgroups map[uuid.UUID]struct{} - clearedgroups bool - team_images map[uuid.UUID]struct{} - removedteam_images map[uuid.UUID]struct{} - clearedteam_images bool - team_group_images map[uuid.UUID]struct{} - removedteam_group_images map[uuid.UUID]struct{} - clearedteam_group_images bool - done bool - oldValue func(context.Context) (*Image, error) - predicates []predicate.Image -} - -var _ ent.Mutation = (*ImageMutation)(nil) - -// imageOption allows management of the mutation configuration using functional options. -type imageOption func(*ImageMutation) - -// newImageMutation creates new mutation for the Image entity. -func newImageMutation(c config, op Op, opts ...imageOption) *ImageMutation { - m := &ImageMutation{ + op Op + typ string + id *string + deleted_at *time.Time + hostname *string + arch *string + cores *int + addcores *int + weight *int + addweight *int + memory *int64 + addmemory *int64 + disk *int64 + adddisk *int64 + os *string + external_ip *string + internal_ip *string + version *string + machine_id *string + remark *string + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + vms map[string]struct{} + removedvms map[string]struct{} + clearedvms bool + user *uuid.UUID + cleareduser bool + groups map[uuid.UUID]struct{} + removedgroups map[uuid.UUID]struct{} + clearedgroups bool + team_group_hosts map[uuid.UUID]struct{} + removedteam_group_hosts map[uuid.UUID]struct{} + clearedteam_group_hosts bool + done bool + oldValue func(context.Context) (*Host, error) + predicates []predicate.Host +} + +var _ ent.Mutation = (*HostMutation)(nil) + +// hostOption allows management of the mutation configuration using functional options. +type hostOption func(*HostMutation) + +// newHostMutation creates new mutation for the Host entity. +func newHostMutation(c config, op Op, opts ...hostOption) *HostMutation { + m := &HostMutation{ config: c, op: op, - typ: TypeImage, + typ: TypeHost, clearedFields: make(map[string]struct{}), } for _, opt := range opts { @@ -835,20 +855,20 @@ func newImageMutation(c config, op Op, opts ...imageOption) *ImageMutation { return m } -// withImageID sets the ID field of the mutation. -func withImageID(id uuid.UUID) imageOption { - return func(m *ImageMutation) { +// withHostID sets the ID field of the mutation. +func withHostID(id string) hostOption { + return func(m *HostMutation) { var ( err error once sync.Once - value *Image + value *Host ) - m.oldValue = func(ctx context.Context) (*Image, error) { + m.oldValue = func(ctx context.Context) (*Host, error) { once.Do(func() { if m.done { err = errors.New("querying old values post mutation is not allowed") } else { - value, err = m.Client().Image.Get(ctx, id) + value, err = m.Client().Host.Get(ctx, id) } }) return value, err @@ -857,10 +877,10 @@ func withImageID(id uuid.UUID) imageOption { } } -// withImage sets the old Image of the mutation. -func withImage(node *Image) imageOption { - return func(m *ImageMutation) { - m.oldValue = func(context.Context) (*Image, error) { +// withHost sets the old Host of the mutation. +func withHost(node *Host) hostOption { + return func(m *HostMutation) { + m.oldValue = func(context.Context) (*Host, error) { return node, nil } m.id = &node.ID @@ -869,7 +889,7 @@ func withImage(node *Image) imageOption { // 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 ImageMutation) Client() *Client { +func (m HostMutation) Client() *Client { client := &Client{config: m.config} client.init() return client @@ -877,7 +897,7 @@ func (m ImageMutation) Client() *Client { // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. -func (m ImageMutation) Tx() (*Tx, error) { +func (m HostMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { return nil, errors.New("db: mutation is not running in a transaction") } @@ -887,14 +907,14 @@ func (m ImageMutation) Tx() (*Tx, error) { } // SetID sets the value of the id field. Note that this -// operation is only accepted on creation of Image entities. -func (m *ImageMutation) SetID(id uuid.UUID) { +// operation is only accepted on creation of Host entities. +func (m *HostMutation) SetID(id string) { 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 *ImageMutation) ID() (id uuid.UUID, exists bool) { +func (m *HostMutation) ID() (id string, exists bool) { if m.id == nil { return } @@ -905,28 +925,28 @@ func (m *ImageMutation) ID() (id uuid.UUID, exists bool) { // 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 *ImageMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { +func (m *HostMutation) IDs(ctx context.Context) ([]string, error) { switch { case m.op.Is(OpUpdateOne | OpDeleteOne): id, exists := m.ID() if exists { - return []uuid.UUID{id}, nil + return []string{id}, nil } fallthrough case m.op.Is(OpUpdate | OpDelete): - return m.Client().Image.Query().Where(m.predicates...).IDs(ctx) + return m.Client().Host.Query().Where(m.predicates...).IDs(ctx) default: return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } } // SetDeletedAt sets the "deleted_at" field. -func (m *ImageMutation) SetDeletedAt(t time.Time) { +func (m *HostMutation) SetDeletedAt(t time.Time) { m.deleted_at = &t } // DeletedAt returns the value of the "deleted_at" field in the mutation. -func (m *ImageMutation) DeletedAt() (r time.Time, exists bool) { +func (m *HostMutation) DeletedAt() (r time.Time, exists bool) { v := m.deleted_at if v == nil { return @@ -934,10 +954,10 @@ func (m *ImageMutation) DeletedAt() (r time.Time, exists bool) { return *v, true } -// OldDeletedAt returns the old "deleted_at" field's value of the Image entity. -// If the Image object wasn't provided to the builder, the object is fetched from the database. +// OldDeletedAt returns the old "deleted_at" field's value of the Host entity. +// If the Host 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 *ImageMutation) OldDeletedAt(ctx context.Context) (v time.Time, err error) { +func (m *HostMutation) OldDeletedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") } @@ -952,30 +972,30 @@ func (m *ImageMutation) OldDeletedAt(ctx context.Context) (v time.Time, err erro } // ClearDeletedAt clears the value of the "deleted_at" field. -func (m *ImageMutation) ClearDeletedAt() { +func (m *HostMutation) ClearDeletedAt() { m.deleted_at = nil - m.clearedFields[image.FieldDeletedAt] = struct{}{} + m.clearedFields[host.FieldDeletedAt] = struct{}{} } // DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. -func (m *ImageMutation) DeletedAtCleared() bool { - _, ok := m.clearedFields[image.FieldDeletedAt] +func (m *HostMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[host.FieldDeletedAt] return ok } // ResetDeletedAt resets all changes to the "deleted_at" field. -func (m *ImageMutation) ResetDeletedAt() { +func (m *HostMutation) ResetDeletedAt() { m.deleted_at = nil - delete(m.clearedFields, image.FieldDeletedAt) + delete(m.clearedFields, host.FieldDeletedAt) } // SetUserID sets the "user_id" field. -func (m *ImageMutation) SetUserID(u uuid.UUID) { +func (m *HostMutation) SetUserID(u uuid.UUID) { m.user = &u } // UserID returns the value of the "user_id" field in the mutation. -func (m *ImageMutation) UserID() (r uuid.UUID, exists bool) { +func (m *HostMutation) UserID() (r uuid.UUID, exists bool) { v := m.user if v == nil { return @@ -983,10 +1003,10 @@ func (m *ImageMutation) UserID() (r uuid.UUID, exists bool) { return *v, true } -// OldUserID returns the old "user_id" field's value of the Image entity. -// If the Image object wasn't provided to the builder, the object is fetched from the database. +// OldUserID returns the old "user_id" field's value of the Host entity. +// If the Host 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 *ImageMutation) OldUserID(ctx context.Context) (v uuid.UUID, err error) { +func (m *HostMutation) OldUserID(ctx context.Context) (v uuid.UUID, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldUserID is only allowed on UpdateOne operations") } @@ -1001,1574 +1021,1907 @@ func (m *ImageMutation) OldUserID(ctx context.Context) (v uuid.UUID, err error) } // ResetUserID resets all changes to the "user_id" field. -func (m *ImageMutation) ResetUserID() { +func (m *HostMutation) ResetUserID() { m.user = nil } -// SetName sets the "name" field. -func (m *ImageMutation) SetName(s string) { - m.name = &s +// SetHostname sets the "hostname" field. +func (m *HostMutation) SetHostname(s string) { + m.hostname = &s } -// Name returns the value of the "name" field in the mutation. -func (m *ImageMutation) Name() (r string, exists bool) { - v := m.name +// Hostname returns the value of the "hostname" field in the mutation. +func (m *HostMutation) Hostname() (r string, exists bool) { + v := m.hostname if v == nil { return } return *v, true } -// OldName returns the old "name" field's value of the Image entity. -// If the Image object wasn't provided to the builder, the object is fetched from the database. +// OldHostname returns the old "hostname" field's value of the Host entity. +// If the Host 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 *ImageMutation) OldName(ctx context.Context) (v string, err error) { +func (m *HostMutation) OldHostname(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldName is only allowed on UpdateOne operations") + return v, errors.New("OldHostname is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldName requires an ID field in the mutation") + return v, errors.New("OldHostname requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldName: %w", err) + return v, fmt.Errorf("querying old value for OldHostname: %w", err) } - return oldValue.Name, nil + return oldValue.Hostname, nil } -// ResetName resets all changes to the "name" field. -func (m *ImageMutation) ResetName() { - m.name = nil +// ClearHostname clears the value of the "hostname" field. +func (m *HostMutation) ClearHostname() { + m.hostname = nil + m.clearedFields[host.FieldHostname] = struct{}{} } -// SetRemark sets the "remark" field. -func (m *ImageMutation) SetRemark(s string) { - m.remark = &s +// HostnameCleared returns if the "hostname" field was cleared in this mutation. +func (m *HostMutation) HostnameCleared() bool { + _, ok := m.clearedFields[host.FieldHostname] + return ok } -// Remark returns the value of the "remark" field in the mutation. -func (m *ImageMutation) Remark() (r string, exists bool) { - v := m.remark +// ResetHostname resets all changes to the "hostname" field. +func (m *HostMutation) ResetHostname() { + m.hostname = nil + delete(m.clearedFields, host.FieldHostname) +} + +// SetArch sets the "arch" field. +func (m *HostMutation) SetArch(s string) { + m.arch = &s +} + +// Arch returns the value of the "arch" field in the mutation. +func (m *HostMutation) Arch() (r string, exists bool) { + v := m.arch if v == nil { return } return *v, true } -// OldRemark returns the old "remark" field's value of the Image entity. -// If the Image object wasn't provided to the builder, the object is fetched from the database. +// OldArch returns the old "arch" field's value of the Host entity. +// If the Host 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 *ImageMutation) OldRemark(ctx context.Context) (v string, err error) { +func (m *HostMutation) OldArch(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldRemark is only allowed on UpdateOne operations") + return v, errors.New("OldArch is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldRemark requires an ID field in the mutation") + return v, errors.New("OldArch requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldRemark: %w", err) + return v, fmt.Errorf("querying old value for OldArch: %w", err) } - return oldValue.Remark, nil + return oldValue.Arch, nil } -// ClearRemark clears the value of the "remark" field. -func (m *ImageMutation) ClearRemark() { - m.remark = nil - m.clearedFields[image.FieldRemark] = struct{}{} +// ClearArch clears the value of the "arch" field. +func (m *HostMutation) ClearArch() { + m.arch = nil + m.clearedFields[host.FieldArch] = struct{}{} } -// RemarkCleared returns if the "remark" field was cleared in this mutation. -func (m *ImageMutation) RemarkCleared() bool { - _, ok := m.clearedFields[image.FieldRemark] +// ArchCleared returns if the "arch" field was cleared in this mutation. +func (m *HostMutation) ArchCleared() bool { + _, ok := m.clearedFields[host.FieldArch] return ok } -// ResetRemark resets all changes to the "remark" field. -func (m *ImageMutation) ResetRemark() { - m.remark = nil - delete(m.clearedFields, image.FieldRemark) +// ResetArch resets all changes to the "arch" field. +func (m *HostMutation) ResetArch() { + m.arch = nil + delete(m.clearedFields, host.FieldArch) } -// SetCreatedAt sets the "created_at" field. -func (m *ImageMutation) SetCreatedAt(t time.Time) { - m.created_at = &t +// SetCores sets the "cores" field. +func (m *HostMutation) SetCores(i int) { + m.cores = &i + m.addcores = nil } -// CreatedAt returns the value of the "created_at" field in the mutation. -func (m *ImageMutation) CreatedAt() (r time.Time, exists bool) { - v := m.created_at +// Cores returns the value of the "cores" field in the mutation. +func (m *HostMutation) Cores() (r int, exists bool) { + v := m.cores if v == nil { return } return *v, true } -// OldCreatedAt returns the old "created_at" field's value of the Image entity. -// If the Image object wasn't provided to the builder, the object is fetched from the database. +// OldCores returns the old "cores" field's value of the Host entity. +// If the Host 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 *ImageMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { +func (m *HostMutation) OldCores(ctx context.Context) (v int, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") + return v, errors.New("OldCores 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") + return v, errors.New("OldCores 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 v, fmt.Errorf("querying old value for OldCores: %w", err) } - return oldValue.CreatedAt, nil + return oldValue.Cores, nil } -// ResetCreatedAt resets all changes to the "created_at" field. -func (m *ImageMutation) ResetCreatedAt() { - m.created_at = nil +// AddCores adds i to the "cores" field. +func (m *HostMutation) AddCores(i int) { + if m.addcores != nil { + *m.addcores += i + } else { + m.addcores = &i + } } -// SetUpdatedAt sets the "updated_at" field. -func (m *ImageMutation) SetUpdatedAt(t time.Time) { - m.updated_at = &t +// AddedCores returns the value that was added to the "cores" field in this mutation. +func (m *HostMutation) AddedCores() (r int, exists bool) { + v := m.addcores + if v == nil { + return + } + return *v, true } -// UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *ImageMutation) UpdatedAt() (r time.Time, exists bool) { - v := m.updated_at +// ClearCores clears the value of the "cores" field. +func (m *HostMutation) ClearCores() { + m.cores = nil + m.addcores = nil + m.clearedFields[host.FieldCores] = struct{}{} +} + +// CoresCleared returns if the "cores" field was cleared in this mutation. +func (m *HostMutation) CoresCleared() bool { + _, ok := m.clearedFields[host.FieldCores] + return ok +} + +// ResetCores resets all changes to the "cores" field. +func (m *HostMutation) ResetCores() { + m.cores = nil + m.addcores = nil + delete(m.clearedFields, host.FieldCores) +} + +// SetWeight sets the "weight" field. +func (m *HostMutation) SetWeight(i int) { + m.weight = &i + m.addweight = nil +} + +// Weight returns the value of the "weight" field in the mutation. +func (m *HostMutation) Weight() (r int, exists bool) { + v := m.weight if v == nil { return } return *v, true } -// OldUpdatedAt returns the old "updated_at" field's value of the Image entity. -// If the Image object wasn't provided to the builder, the object is fetched from the database. +// OldWeight returns the old "weight" field's value of the Host entity. +// If the Host 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 *ImageMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { +func (m *HostMutation) OldWeight(ctx context.Context) (v int, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") + return v, errors.New("OldWeight 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") + return v, errors.New("OldWeight 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 v, fmt.Errorf("querying old value for OldWeight: %w", err) } - return oldValue.UpdatedAt, nil + return oldValue.Weight, nil } -// ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *ImageMutation) ResetUpdatedAt() { - m.updated_at = nil +// AddWeight adds i to the "weight" field. +func (m *HostMutation) AddWeight(i int) { + if m.addweight != nil { + *m.addweight += i + } else { + m.addweight = &i + } } -// ClearUser clears the "user" edge to the User entity. -func (m *ImageMutation) ClearUser() { - m.cleareduser = true - m.clearedFields[image.FieldUserID] = struct{}{} +// AddedWeight returns the value that was added to the "weight" field in this mutation. +func (m *HostMutation) AddedWeight() (r int, exists bool) { + v := m.addweight + if v == nil { + return + } + return *v, true } -// UserCleared reports if the "user" edge to the User entity was cleared. -func (m *ImageMutation) UserCleared() bool { - return m.cleareduser +// ResetWeight resets all changes to the "weight" field. +func (m *HostMutation) ResetWeight() { + m.weight = nil + m.addweight = nil } -// UserIDs returns the "user" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// UserID instead. It exists only for internal usage by the builders. -func (m *ImageMutation) UserIDs() (ids []uuid.UUID) { - if id := m.user; id != nil { - ids = append(ids, *id) +// SetMemory sets the "memory" field. +func (m *HostMutation) SetMemory(i int64) { + m.memory = &i + m.addmemory = nil +} + +// Memory returns the value of the "memory" field in the mutation. +func (m *HostMutation) Memory() (r int64, exists bool) { + v := m.memory + if v == nil { + return } - return + return *v, true } -// ResetUser resets all changes to the "user" edge. -func (m *ImageMutation) ResetUser() { - m.user = nil - m.cleareduser = false +// OldMemory returns the old "memory" field's value of the Host entity. +// If the Host 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 *HostMutation) OldMemory(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMemory is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMemory requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMemory: %w", err) + } + return oldValue.Memory, nil } -// AddTeamIDs adds the "teams" edge to the Team entity by ids. -func (m *ImageMutation) AddTeamIDs(ids ...uuid.UUID) { - if m.teams == nil { - m.teams = make(map[uuid.UUID]struct{}) +// AddMemory adds i to the "memory" field. +func (m *HostMutation) AddMemory(i int64) { + if m.addmemory != nil { + *m.addmemory += i + } else { + m.addmemory = &i } - for i := range ids { - m.teams[ids[i]] = struct{}{} +} + +// AddedMemory returns the value that was added to the "memory" field in this mutation. +func (m *HostMutation) AddedMemory() (r int64, exists bool) { + v := m.addmemory + if v == nil { + return } + return *v, true } -// ClearTeams clears the "teams" edge to the Team entity. -func (m *ImageMutation) ClearTeams() { - m.clearedteams = true +// ClearMemory clears the value of the "memory" field. +func (m *HostMutation) ClearMemory() { + m.memory = nil + m.addmemory = nil + m.clearedFields[host.FieldMemory] = struct{}{} } -// TeamsCleared reports if the "teams" edge to the Team entity was cleared. -func (m *ImageMutation) TeamsCleared() bool { - return m.clearedteams +// MemoryCleared returns if the "memory" field was cleared in this mutation. +func (m *HostMutation) MemoryCleared() bool { + _, ok := m.clearedFields[host.FieldMemory] + return ok } -// RemoveTeamIDs removes the "teams" edge to the Team entity by IDs. -func (m *ImageMutation) RemoveTeamIDs(ids ...uuid.UUID) { - if m.removedteams == nil { - m.removedteams = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.teams, ids[i]) - m.removedteams[ids[i]] = struct{}{} - } +// ResetMemory resets all changes to the "memory" field. +func (m *HostMutation) ResetMemory() { + m.memory = nil + m.addmemory = nil + delete(m.clearedFields, host.FieldMemory) } -// RemovedTeams returns the removed IDs of the "teams" edge to the Team entity. -func (m *ImageMutation) RemovedTeamsIDs() (ids []uuid.UUID) { - for id := range m.removedteams { - ids = append(ids, id) - } - return +// SetDisk sets the "disk" field. +func (m *HostMutation) SetDisk(i int64) { + m.disk = &i + m.adddisk = nil } -// TeamsIDs returns the "teams" edge IDs in the mutation. -func (m *ImageMutation) TeamsIDs() (ids []uuid.UUID) { - for id := range m.teams { - ids = append(ids, id) +// Disk returns the value of the "disk" field in the mutation. +func (m *HostMutation) Disk() (r int64, exists bool) { + v := m.disk + if v == nil { + return } - return + return *v, true } -// ResetTeams resets all changes to the "teams" edge. -func (m *ImageMutation) ResetTeams() { - m.teams = nil - m.clearedteams = false - m.removedteams = nil +// OldDisk returns the old "disk" field's value of the Host entity. +// If the Host 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 *HostMutation) OldDisk(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDisk is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDisk requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDisk: %w", err) + } + return oldValue.Disk, nil } -// AddGroupIDs adds the "groups" edge to the TeamGroup entity by ids. -func (m *ImageMutation) AddGroupIDs(ids ...uuid.UUID) { - if m.groups == nil { - m.groups = make(map[uuid.UUID]struct{}) +// AddDisk adds i to the "disk" field. +func (m *HostMutation) AddDisk(i int64) { + if m.adddisk != nil { + *m.adddisk += i + } else { + m.adddisk = &i } - for i := range ids { - m.groups[ids[i]] = struct{}{} +} + +// AddedDisk returns the value that was added to the "disk" field in this mutation. +func (m *HostMutation) AddedDisk() (r int64, exists bool) { + v := m.adddisk + if v == nil { + return } + return *v, true } -// ClearGroups clears the "groups" edge to the TeamGroup entity. -func (m *ImageMutation) ClearGroups() { - m.clearedgroups = true +// ClearDisk clears the value of the "disk" field. +func (m *HostMutation) ClearDisk() { + m.disk = nil + m.adddisk = nil + m.clearedFields[host.FieldDisk] = struct{}{} } -// GroupsCleared reports if the "groups" edge to the TeamGroup entity was cleared. -func (m *ImageMutation) GroupsCleared() bool { - return m.clearedgroups +// DiskCleared returns if the "disk" field was cleared in this mutation. +func (m *HostMutation) DiskCleared() bool { + _, ok := m.clearedFields[host.FieldDisk] + return ok } -// RemoveGroupIDs removes the "groups" edge to the TeamGroup entity by IDs. -func (m *ImageMutation) RemoveGroupIDs(ids ...uuid.UUID) { - if m.removedgroups == nil { - m.removedgroups = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.groups, ids[i]) - m.removedgroups[ids[i]] = struct{}{} - } +// ResetDisk resets all changes to the "disk" field. +func (m *HostMutation) ResetDisk() { + m.disk = nil + m.adddisk = nil + delete(m.clearedFields, host.FieldDisk) } -// RemovedGroups returns the removed IDs of the "groups" edge to the TeamGroup entity. -func (m *ImageMutation) RemovedGroupsIDs() (ids []uuid.UUID) { - for id := range m.removedgroups { - ids = append(ids, id) +// SetOs sets the "os" field. +func (m *HostMutation) SetOs(s string) { + m.os = &s +} + +// Os returns the value of the "os" field in the mutation. +func (m *HostMutation) Os() (r string, exists bool) { + v := m.os + if v == nil { + return } - return + return *v, true } -// GroupsIDs returns the "groups" edge IDs in the mutation. -func (m *ImageMutation) GroupsIDs() (ids []uuid.UUID) { - for id := range m.groups { - ids = append(ids, id) +// OldOs returns the old "os" field's value of the Host entity. +// If the Host 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 *HostMutation) OldOs(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldOs is only allowed on UpdateOne operations") } - return + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldOs requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldOs: %w", err) + } + return oldValue.Os, nil } -// ResetGroups resets all changes to the "groups" edge. -func (m *ImageMutation) ResetGroups() { - m.groups = nil - m.clearedgroups = false - m.removedgroups = nil +// ClearOs clears the value of the "os" field. +func (m *HostMutation) ClearOs() { + m.os = nil + m.clearedFields[host.FieldOs] = struct{}{} } -// AddTeamImageIDs adds the "team_images" edge to the TeamImage entity by ids. -func (m *ImageMutation) AddTeamImageIDs(ids ...uuid.UUID) { - if m.team_images == nil { - m.team_images = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.team_images[ids[i]] = struct{}{} - } +// OsCleared returns if the "os" field was cleared in this mutation. +func (m *HostMutation) OsCleared() bool { + _, ok := m.clearedFields[host.FieldOs] + return ok } -// ClearTeamImages clears the "team_images" edge to the TeamImage entity. -func (m *ImageMutation) ClearTeamImages() { - m.clearedteam_images = true +// ResetOs resets all changes to the "os" field. +func (m *HostMutation) ResetOs() { + m.os = nil + delete(m.clearedFields, host.FieldOs) } -// TeamImagesCleared reports if the "team_images" edge to the TeamImage entity was cleared. -func (m *ImageMutation) TeamImagesCleared() bool { - return m.clearedteam_images +// SetExternalIP sets the "external_ip" field. +func (m *HostMutation) SetExternalIP(s string) { + m.external_ip = &s } -// RemoveTeamImageIDs removes the "team_images" edge to the TeamImage entity by IDs. -func (m *ImageMutation) RemoveTeamImageIDs(ids ...uuid.UUID) { - if m.removedteam_images == nil { - m.removedteam_images = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.team_images, ids[i]) - m.removedteam_images[ids[i]] = struct{}{} +// ExternalIP returns the value of the "external_ip" field in the mutation. +func (m *HostMutation) ExternalIP() (r string, exists bool) { + v := m.external_ip + if v == nil { + return } + return *v, true } -// RemovedTeamImages returns the removed IDs of the "team_images" edge to the TeamImage entity. -func (m *ImageMutation) RemovedTeamImagesIDs() (ids []uuid.UUID) { - for id := range m.removedteam_images { - ids = append(ids, id) +// OldExternalIP returns the old "external_ip" field's value of the Host entity. +// If the Host 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 *HostMutation) OldExternalIP(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldExternalIP is only allowed on UpdateOne operations") } - return + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldExternalIP requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldExternalIP: %w", err) + } + return oldValue.ExternalIP, nil } -// TeamImagesIDs returns the "team_images" edge IDs in the mutation. -func (m *ImageMutation) TeamImagesIDs() (ids []uuid.UUID) { - for id := range m.team_images { - ids = append(ids, id) - } - return +// ClearExternalIP clears the value of the "external_ip" field. +func (m *HostMutation) ClearExternalIP() { + m.external_ip = nil + m.clearedFields[host.FieldExternalIP] = struct{}{} } -// ResetTeamImages resets all changes to the "team_images" edge. -func (m *ImageMutation) ResetTeamImages() { - m.team_images = nil - m.clearedteam_images = false - m.removedteam_images = nil +// ExternalIPCleared returns if the "external_ip" field was cleared in this mutation. +func (m *HostMutation) ExternalIPCleared() bool { + _, ok := m.clearedFields[host.FieldExternalIP] + return ok } -// AddTeamGroupImageIDs adds the "team_group_images" edge to the TeamGroupImage entity by ids. -func (m *ImageMutation) AddTeamGroupImageIDs(ids ...uuid.UUID) { - if m.team_group_images == nil { - m.team_group_images = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.team_group_images[ids[i]] = struct{}{} - } +// ResetExternalIP resets all changes to the "external_ip" field. +func (m *HostMutation) ResetExternalIP() { + m.external_ip = nil + delete(m.clearedFields, host.FieldExternalIP) } -// ClearTeamGroupImages clears the "team_group_images" edge to the TeamGroupImage entity. -func (m *ImageMutation) ClearTeamGroupImages() { - m.clearedteam_group_images = true +// SetInternalIP sets the "internal_ip" field. +func (m *HostMutation) SetInternalIP(s string) { + m.internal_ip = &s } -// TeamGroupImagesCleared reports if the "team_group_images" edge to the TeamGroupImage entity was cleared. -func (m *ImageMutation) TeamGroupImagesCleared() bool { - return m.clearedteam_group_images +// InternalIP returns the value of the "internal_ip" field in the mutation. +func (m *HostMutation) InternalIP() (r string, exists bool) { + v := m.internal_ip + if v == nil { + return + } + return *v, true } -// RemoveTeamGroupImageIDs removes the "team_group_images" edge to the TeamGroupImage entity by IDs. -func (m *ImageMutation) RemoveTeamGroupImageIDs(ids ...uuid.UUID) { - if m.removedteam_group_images == nil { - m.removedteam_group_images = make(map[uuid.UUID]struct{}) +// OldInternalIP returns the old "internal_ip" field's value of the Host entity. +// If the Host 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 *HostMutation) OldInternalIP(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInternalIP is only allowed on UpdateOne operations") } - for i := range ids { - delete(m.team_group_images, ids[i]) - m.removedteam_group_images[ids[i]] = struct{}{} + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInternalIP requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInternalIP: %w", err) } + return oldValue.InternalIP, nil } -// RemovedTeamGroupImages returns the removed IDs of the "team_group_images" edge to the TeamGroupImage entity. -func (m *ImageMutation) RemovedTeamGroupImagesIDs() (ids []uuid.UUID) { - for id := range m.removedteam_group_images { - ids = append(ids, id) - } - return +// ClearInternalIP clears the value of the "internal_ip" field. +func (m *HostMutation) ClearInternalIP() { + m.internal_ip = nil + m.clearedFields[host.FieldInternalIP] = struct{}{} } -// TeamGroupImagesIDs returns the "team_group_images" edge IDs in the mutation. -func (m *ImageMutation) TeamGroupImagesIDs() (ids []uuid.UUID) { - for id := range m.team_group_images { - ids = append(ids, id) - } - return +// InternalIPCleared returns if the "internal_ip" field was cleared in this mutation. +func (m *HostMutation) InternalIPCleared() bool { + _, ok := m.clearedFields[host.FieldInternalIP] + return ok } -// ResetTeamGroupImages resets all changes to the "team_group_images" edge. -func (m *ImageMutation) ResetTeamGroupImages() { - m.team_group_images = nil - m.clearedteam_group_images = false - m.removedteam_group_images = nil +// ResetInternalIP resets all changes to the "internal_ip" field. +func (m *HostMutation) ResetInternalIP() { + m.internal_ip = nil + delete(m.clearedFields, host.FieldInternalIP) } -// Where appends a list predicates to the ImageMutation builder. -func (m *ImageMutation) Where(ps ...predicate.Image) { - m.predicates = append(m.predicates, ps...) +// SetVersion sets the "version" field. +func (m *HostMutation) SetVersion(s string) { + m.version = &s } -// WhereP appends storage-level predicates to the ImageMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *ImageMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.Image, len(ps)) - for i := range ps { - p[i] = ps[i] +// Version returns the value of the "version" field in the mutation. +func (m *HostMutation) Version() (r string, exists bool) { + v := m.version + if v == nil { + return } - m.Where(p...) + return *v, true } -// Op returns the operation name. -func (m *ImageMutation) Op() Op { - return m.op +// OldVersion returns the old "version" field's value of the Host entity. +// If the Host 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 *HostMutation) OldVersion(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldVersion is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldVersion requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldVersion: %w", err) + } + return oldValue.Version, nil } -// SetOp allows setting the mutation operation. -func (m *ImageMutation) SetOp(op Op) { - m.op = op +// ClearVersion clears the value of the "version" field. +func (m *HostMutation) ClearVersion() { + m.version = nil + m.clearedFields[host.FieldVersion] = struct{}{} } -// Type returns the node type of this mutation (Image). -func (m *ImageMutation) Type() string { - return m.typ +// VersionCleared returns if the "version" field was cleared in this mutation. +func (m *HostMutation) VersionCleared() bool { + _, ok := m.clearedFields[host.FieldVersion] + return ok } -// 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 *ImageMutation) Fields() []string { - fields := make([]string, 0, 6) - if m.deleted_at != nil { - fields = append(fields, image.FieldDeletedAt) - } - if m.user != nil { - fields = append(fields, image.FieldUserID) +// ResetVersion resets all changes to the "version" field. +func (m *HostMutation) ResetVersion() { + m.version = nil + delete(m.clearedFields, host.FieldVersion) +} + +// SetMachineID sets the "machine_id" field. +func (m *HostMutation) SetMachineID(s string) { + m.machine_id = &s +} + +// MachineID returns the value of the "machine_id" field in the mutation. +func (m *HostMutation) MachineID() (r string, exists bool) { + v := m.machine_id + if v == nil { + return } - if m.name != nil { - fields = append(fields, image.FieldName) + return *v, true +} + +// OldMachineID returns the old "machine_id" field's value of the Host entity. +// If the Host 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 *HostMutation) OldMachineID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMachineID is only allowed on UpdateOne operations") } - if m.remark != nil { - fields = append(fields, image.FieldRemark) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMachineID requires an ID field in the mutation") } - if m.created_at != nil { - fields = append(fields, image.FieldCreatedAt) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMachineID: %w", err) } - if m.updated_at != nil { - fields = append(fields, image.FieldUpdatedAt) + return oldValue.MachineID, nil +} + +// ClearMachineID clears the value of the "machine_id" field. +func (m *HostMutation) ClearMachineID() { + m.machine_id = nil + m.clearedFields[host.FieldMachineID] = struct{}{} +} + +// MachineIDCleared returns if the "machine_id" field was cleared in this mutation. +func (m *HostMutation) MachineIDCleared() bool { + _, ok := m.clearedFields[host.FieldMachineID] + return ok +} + +// ResetMachineID resets all changes to the "machine_id" field. +func (m *HostMutation) ResetMachineID() { + m.machine_id = nil + delete(m.clearedFields, host.FieldMachineID) +} + +// SetRemark sets the "remark" field. +func (m *HostMutation) SetRemark(s string) { + m.remark = &s +} + +// Remark returns the value of the "remark" field in the mutation. +func (m *HostMutation) Remark() (r string, exists bool) { + v := m.remark + if v == nil { + return } - return fields + return *v, true } -// 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 *ImageMutation) Field(name string) (ent.Value, bool) { - switch name { - case image.FieldDeletedAt: - return m.DeletedAt() - case image.FieldUserID: - return m.UserID() - case image.FieldName: - return m.Name() - case image.FieldRemark: - return m.Remark() - case image.FieldCreatedAt: - return m.CreatedAt() - case image.FieldUpdatedAt: - return m.UpdatedAt() +// OldRemark returns the old "remark" field's value of the Host entity. +// If the Host 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 *HostMutation) OldRemark(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRemark is only allowed on UpdateOne operations") } - return nil, false + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRemark requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRemark: %w", err) + } + return oldValue.Remark, nil } -// 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 *ImageMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case image.FieldDeletedAt: - return m.OldDeletedAt(ctx) - case image.FieldUserID: - return m.OldUserID(ctx) - case image.FieldName: - return m.OldName(ctx) - case image.FieldRemark: - return m.OldRemark(ctx) - case image.FieldCreatedAt: - return m.OldCreatedAt(ctx) - case image.FieldUpdatedAt: - return m.OldUpdatedAt(ctx) - } - return nil, fmt.Errorf("unknown Image field %s", name) +// ClearRemark clears the value of the "remark" field. +func (m *HostMutation) ClearRemark() { + m.remark = nil + m.clearedFields[host.FieldRemark] = struct{}{} } -// 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 *ImageMutation) SetField(name string, value ent.Value) error { - switch name { - case image.FieldDeletedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetDeletedAt(v) - return nil - case image.FieldUserID: - v, ok := value.(uuid.UUID) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUserID(v) - return nil - case image.FieldName: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetName(v) - return nil - case image.FieldRemark: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetRemark(v) - return nil - case image.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 image.FieldUpdatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUpdatedAt(v) - return nil - } - return fmt.Errorf("unknown Image field %s", name) +// RemarkCleared returns if the "remark" field was cleared in this mutation. +func (m *HostMutation) RemarkCleared() bool { + _, ok := m.clearedFields[host.FieldRemark] + return ok } -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *ImageMutation) AddedFields() []string { - return nil +// ResetRemark resets all changes to the "remark" field. +func (m *HostMutation) ResetRemark() { + m.remark = nil + delete(m.clearedFields, host.FieldRemark) } -// 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 *ImageMutation) AddedField(name string) (ent.Value, bool) { - return nil, false +// SetCreatedAt sets the "created_at" field. +func (m *HostMutation) SetCreatedAt(t time.Time) { + m.created_at = &t } -// 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 *ImageMutation) AddField(name string, value ent.Value) error { - switch name { +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *HostMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return } - return fmt.Errorf("unknown Image numeric field %s", name) + return *v, true } -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *ImageMutation) ClearedFields() []string { - var fields []string - if m.FieldCleared(image.FieldDeletedAt) { - fields = append(fields, image.FieldDeletedAt) +// OldCreatedAt returns the old "created_at" field's value of the Host entity. +// If the Host 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 *HostMutation) 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.FieldCleared(image.FieldRemark) { - fields = append(fields, image.FieldRemark) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") } - return fields + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil } -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *ImageMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *HostMutation) ResetCreatedAt() { + m.created_at = nil } -// 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 *ImageMutation) ClearField(name string) error { - switch name { - case image.FieldDeletedAt: - m.ClearDeletedAt() - return nil - case image.FieldRemark: - m.ClearRemark() - return nil +// SetUpdatedAt sets the "updated_at" field. +func (m *HostMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *HostMutation) UpdatedAt() (r time.Time, exists bool) { + v := m.updated_at + if v == nil { + return } - return fmt.Errorf("unknown Image nullable field %s", name) + return *v, true } -// 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 *ImageMutation) ResetField(name string) error { - switch name { - case image.FieldDeletedAt: - m.ResetDeletedAt() - return nil - case image.FieldUserID: - m.ResetUserID() - return nil - case image.FieldName: - m.ResetName() - return nil - case image.FieldRemark: - m.ResetRemark() - return nil - case image.FieldCreatedAt: - m.ResetCreatedAt() - return nil - case image.FieldUpdatedAt: - m.ResetUpdatedAt() - return nil +// OldUpdatedAt returns the old "updated_at" field's value of the Host entity. +// If the Host 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 *HostMutation) 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") } - return fmt.Errorf("unknown Image field %s", name) + 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 } -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *ImageMutation) AddedEdges() []string { - edges := make([]string, 0, 5) - if m.user != nil { - edges = append(edges, image.EdgeUser) +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *HostMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// AddVMIDs adds the "vms" edge to the VirtualMachine entity by ids. +func (m *HostMutation) AddVMIDs(ids ...string) { + if m.vms == nil { + m.vms = make(map[string]struct{}) } - if m.teams != nil { - edges = append(edges, image.EdgeTeams) + for i := range ids { + m.vms[ids[i]] = struct{}{} } - if m.groups != nil { - edges = append(edges, image.EdgeGroups) +} + +// ClearVms clears the "vms" edge to the VirtualMachine entity. +func (m *HostMutation) ClearVms() { + m.clearedvms = true +} + +// VmsCleared reports if the "vms" edge to the VirtualMachine entity was cleared. +func (m *HostMutation) VmsCleared() bool { + return m.clearedvms +} + +// RemoveVMIDs removes the "vms" edge to the VirtualMachine entity by IDs. +func (m *HostMutation) RemoveVMIDs(ids ...string) { + if m.removedvms == nil { + m.removedvms = make(map[string]struct{}) } - if m.team_images != nil { - edges = append(edges, image.EdgeTeamImages) + for i := range ids { + delete(m.vms, ids[i]) + m.removedvms[ids[i]] = struct{}{} } - if m.team_group_images != nil { - edges = append(edges, image.EdgeTeamGroupImages) +} + +// RemovedVms returns the removed IDs of the "vms" edge to the VirtualMachine entity. +func (m *HostMutation) RemovedVmsIDs() (ids []string) { + for id := range m.removedvms { + ids = append(ids, id) } - return edges + return } -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *ImageMutation) AddedIDs(name string) []ent.Value { - switch name { - case image.EdgeUser: - if id := m.user; id != nil { - return []ent.Value{*id} - } - case image.EdgeTeams: - ids := make([]ent.Value, 0, len(m.teams)) - for id := range m.teams { - ids = append(ids, id) - } - return ids - case image.EdgeGroups: - ids := make([]ent.Value, 0, len(m.groups)) - for id := range m.groups { - ids = append(ids, id) - } - return ids - case image.EdgeTeamImages: - ids := make([]ent.Value, 0, len(m.team_images)) - for id := range m.team_images { - ids = append(ids, id) - } - return ids - case image.EdgeTeamGroupImages: - ids := make([]ent.Value, 0, len(m.team_group_images)) - for id := range m.team_group_images { - ids = append(ids, id) - } - return ids +// VmsIDs returns the "vms" edge IDs in the mutation. +func (m *HostMutation) VmsIDs() (ids []string) { + for id := range m.vms { + ids = append(ids, id) } - return nil + return } -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *ImageMutation) RemovedEdges() []string { - edges := make([]string, 0, 5) - if m.removedteams != nil { - edges = append(edges, image.EdgeTeams) - } - if m.removedgroups != nil { - edges = append(edges, image.EdgeGroups) - } - if m.removedteam_images != nil { - edges = append(edges, image.EdgeTeamImages) - } - if m.removedteam_group_images != nil { - edges = append(edges, image.EdgeTeamGroupImages) - } - return edges +// ResetVms resets all changes to the "vms" edge. +func (m *HostMutation) ResetVms() { + m.vms = nil + m.clearedvms = false + m.removedvms = nil } -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *ImageMutation) RemovedIDs(name string) []ent.Value { - switch name { - case image.EdgeTeams: - ids := make([]ent.Value, 0, len(m.removedteams)) - for id := range m.removedteams { - ids = append(ids, id) - } - return ids - case image.EdgeGroups: - ids := make([]ent.Value, 0, len(m.removedgroups)) - for id := range m.removedgroups { - ids = append(ids, id) - } - return ids - case image.EdgeTeamImages: - ids := make([]ent.Value, 0, len(m.removedteam_images)) - for id := range m.removedteam_images { - ids = append(ids, id) - } - return ids - case image.EdgeTeamGroupImages: - ids := make([]ent.Value, 0, len(m.removedteam_group_images)) - for id := range m.removedteam_group_images { - ids = append(ids, id) - } - return ids - } - return nil +// ClearUser clears the "user" edge to the User entity. +func (m *HostMutation) ClearUser() { + m.cleareduser = true + m.clearedFields[host.FieldUserID] = struct{}{} } -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *ImageMutation) ClearedEdges() []string { - edges := make([]string, 0, 5) - if m.cleareduser { - edges = append(edges, image.EdgeUser) - } - if m.clearedteams { - edges = append(edges, image.EdgeTeams) - } - if m.clearedgroups { - edges = append(edges, image.EdgeGroups) - } - if m.clearedteam_images { - edges = append(edges, image.EdgeTeamImages) - } - if m.clearedteam_group_images { - edges = append(edges, image.EdgeTeamGroupImages) - } - return edges +// UserCleared reports if the "user" edge to the User entity was cleared. +func (m *HostMutation) UserCleared() bool { + return m.cleareduser } -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *ImageMutation) EdgeCleared(name string) bool { - switch name { - case image.EdgeUser: - return m.cleareduser - case image.EdgeTeams: - return m.clearedteams - case image.EdgeGroups: - return m.clearedgroups - case image.EdgeTeamImages: - return m.clearedteam_images - case image.EdgeTeamGroupImages: - return m.clearedteam_group_images +// UserIDs returns the "user" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UserID instead. It exists only for internal usage by the builders. +func (m *HostMutation) UserIDs() (ids []uuid.UUID) { + if id := m.user; id != nil { + ids = append(ids, *id) } - return false + return } -// 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 *ImageMutation) ClearEdge(name string) error { - switch name { - case image.EdgeUser: - m.ClearUser() - return nil - } - return fmt.Errorf("unknown Image unique edge %s", name) +// ResetUser resets all changes to the "user" edge. +func (m *HostMutation) ResetUser() { + m.user = nil + m.cleareduser = false } -// 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 *ImageMutation) ResetEdge(name string) error { - switch name { - case image.EdgeUser: - m.ResetUser() - return nil - case image.EdgeTeams: - m.ResetTeams() - return nil - case image.EdgeGroups: - m.ResetGroups() - return nil - case image.EdgeTeamImages: - m.ResetTeamImages() - return nil - case image.EdgeTeamGroupImages: - m.ResetTeamGroupImages() - return nil +// AddGroupIDs adds the "groups" edge to the TeamGroup entity by ids. +func (m *HostMutation) AddGroupIDs(ids ...uuid.UUID) { + if m.groups == nil { + m.groups = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.groups[ids[i]] = struct{}{} } - return fmt.Errorf("unknown Image edge %s", name) } -// ModelMutation represents an operation that mutates the Model nodes in the graph. -type ModelMutation struct { - config - op Op - typ string - id *uuid.UUID - deleted_at *time.Time - provider *string - api_key *string - base_url *string - model *string - remark *string - temperature *float64 - addtemperature *float64 - interface_type *string - weight *int - addweight *int - last_check_at *time.Time - last_check_success *bool - last_check_error *string - created_at *time.Time - updated_at *time.Time - clearedFields map[string]struct{} - user *uuid.UUID - cleareduser bool - teams map[uuid.UUID]struct{} - removedteams map[uuid.UUID]struct{} - clearedteams bool - groups map[uuid.UUID]struct{} - removedgroups map[uuid.UUID]struct{} - clearedgroups bool - team_models map[uuid.UUID]struct{} - removedteam_models map[uuid.UUID]struct{} - clearedteam_models bool - team_group_models map[uuid.UUID]struct{} - removedteam_group_models map[uuid.UUID]struct{} - clearedteam_group_models bool - done bool - oldValue func(context.Context) (*Model, error) - predicates []predicate.Model +// ClearGroups clears the "groups" edge to the TeamGroup entity. +func (m *HostMutation) ClearGroups() { + m.clearedgroups = true } -var _ ent.Mutation = (*ModelMutation)(nil) - -// modelOption allows management of the mutation configuration using functional options. -type modelOption func(*ModelMutation) +// GroupsCleared reports if the "groups" edge to the TeamGroup entity was cleared. +func (m *HostMutation) GroupsCleared() bool { + return m.clearedgroups +} -// newModelMutation creates new mutation for the Model entity. -func newModelMutation(c config, op Op, opts ...modelOption) *ModelMutation { - m := &ModelMutation{ - config: c, - op: op, - typ: TypeModel, - clearedFields: make(map[string]struct{}), +// RemoveGroupIDs removes the "groups" edge to the TeamGroup entity by IDs. +func (m *HostMutation) RemoveGroupIDs(ids ...uuid.UUID) { + if m.removedgroups == nil { + m.removedgroups = make(map[uuid.UUID]struct{}) } - for _, opt := range opts { - opt(m) + for i := range ids { + delete(m.groups, ids[i]) + m.removedgroups[ids[i]] = struct{}{} } - return m } -// withModelID sets the ID field of the mutation. -func withModelID(id uuid.UUID) modelOption { - return func(m *ModelMutation) { - var ( - err error - once sync.Once - value *Model - ) - m.oldValue = func(ctx context.Context) (*Model, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().Model.Get(ctx, id) - } - }) - return value, err - } - m.id = &id +// RemovedGroups returns the removed IDs of the "groups" edge to the TeamGroup entity. +func (m *HostMutation) RemovedGroupsIDs() (ids []uuid.UUID) { + for id := range m.removedgroups { + ids = append(ids, id) } + return } -// withModel sets the old Model of the mutation. -func withModel(node *Model) modelOption { - return func(m *ModelMutation) { - m.oldValue = func(context.Context) (*Model, error) { - return node, nil - } - m.id = &node.ID +// GroupsIDs returns the "groups" edge IDs in the mutation. +func (m *HostMutation) GroupsIDs() (ids []uuid.UUID) { + for id := range m.groups { + ids = append(ids, id) } + return } -// 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 ModelMutation) Client() *Client { - client := &Client{config: m.config} - client.init() - return client +// ResetGroups resets all changes to the "groups" edge. +func (m *HostMutation) ResetGroups() { + m.groups = nil + m.clearedgroups = false + m.removedgroups = nil } -// Tx returns an `ent.Tx` for mutations that were executed in transactions; -// it returns an error otherwise. -func (m ModelMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("db: mutation is not running in a transaction") +// AddTeamGroupHostIDs adds the "team_group_hosts" edge to the TeamGroupHost entity by ids. +func (m *HostMutation) AddTeamGroupHostIDs(ids ...uuid.UUID) { + if m.team_group_hosts == nil { + m.team_group_hosts = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.team_group_hosts[ids[i]] = struct{}{} } - 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 Model entities. -func (m *ModelMutation) SetID(id uuid.UUID) { - m.id = &id +// ClearTeamGroupHosts clears the "team_group_hosts" edge to the TeamGroupHost entity. +func (m *HostMutation) ClearTeamGroupHosts() { + m.clearedteam_group_hosts = true } -// 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 *ModelMutation) ID() (id uuid.UUID, exists bool) { - if m.id == nil { - return - } - return *m.id, true +// TeamGroupHostsCleared reports if the "team_group_hosts" edge to the TeamGroupHost entity was cleared. +func (m *HostMutation) TeamGroupHostsCleared() bool { + return m.clearedteam_group_hosts } -// 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 *ModelMutation) 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().Model.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) +// RemoveTeamGroupHostIDs removes the "team_group_hosts" edge to the TeamGroupHost entity by IDs. +func (m *HostMutation) RemoveTeamGroupHostIDs(ids ...uuid.UUID) { + if m.removedteam_group_hosts == nil { + m.removedteam_group_hosts = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.team_group_hosts, ids[i]) + m.removedteam_group_hosts[ids[i]] = struct{}{} } } -// SetDeletedAt sets the "deleted_at" field. -func (m *ModelMutation) SetDeletedAt(t time.Time) { - m.deleted_at = &t +// RemovedTeamGroupHosts returns the removed IDs of the "team_group_hosts" edge to the TeamGroupHost entity. +func (m *HostMutation) RemovedTeamGroupHostsIDs() (ids []uuid.UUID) { + for id := range m.removedteam_group_hosts { + ids = append(ids, id) + } + return } -// DeletedAt returns the value of the "deleted_at" field in the mutation. -func (m *ModelMutation) DeletedAt() (r time.Time, exists bool) { - v := m.deleted_at - if v == nil { - return +// TeamGroupHostsIDs returns the "team_group_hosts" edge IDs in the mutation. +func (m *HostMutation) TeamGroupHostsIDs() (ids []uuid.UUID) { + for id := range m.team_group_hosts { + ids = append(ids, id) } - return *v, true + return } -// OldDeletedAt returns the old "deleted_at" field's value of the Model entity. -// If the Model 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 *ModelMutation) OldDeletedAt(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldDeletedAt requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldDeletedAt: %w", err) - } - return oldValue.DeletedAt, nil +// ResetTeamGroupHosts resets all changes to the "team_group_hosts" edge. +func (m *HostMutation) ResetTeamGroupHosts() { + m.team_group_hosts = nil + m.clearedteam_group_hosts = false + m.removedteam_group_hosts = nil } -// ClearDeletedAt clears the value of the "deleted_at" field. -func (m *ModelMutation) ClearDeletedAt() { - m.deleted_at = nil - m.clearedFields[model.FieldDeletedAt] = struct{}{} +// Where appends a list predicates to the HostMutation builder. +func (m *HostMutation) Where(ps ...predicate.Host) { + m.predicates = append(m.predicates, ps...) } -// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. -func (m *ModelMutation) DeletedAtCleared() bool { - _, ok := m.clearedFields[model.FieldDeletedAt] - return ok +// WhereP appends storage-level predicates to the HostMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *HostMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Host, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) } -// ResetDeletedAt resets all changes to the "deleted_at" field. -func (m *ModelMutation) ResetDeletedAt() { - m.deleted_at = nil - delete(m.clearedFields, model.FieldDeletedAt) +// Op returns the operation name. +func (m *HostMutation) Op() Op { + return m.op } -// SetUserID sets the "user_id" field. -func (m *ModelMutation) SetUserID(u uuid.UUID) { - m.user = &u +// SetOp allows setting the mutation operation. +func (m *HostMutation) SetOp(op Op) { + m.op = op } -// UserID returns the value of the "user_id" field in the mutation. -func (m *ModelMutation) UserID() (r uuid.UUID, exists bool) { - v := m.user - if v == nil { - return - } - return *v, true +// Type returns the node type of this mutation (Host). +func (m *HostMutation) Type() string { + return m.typ } -// OldUserID returns the old "user_id" field's value of the Model entity. -// If the Model 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 *ModelMutation) OldUserID(ctx context.Context) (v uuid.UUID, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUserID is only allowed on UpdateOne operations") +// 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 *HostMutation) Fields() []string { + fields := make([]string, 0, 16) + if m.deleted_at != nil { + fields = append(fields, host.FieldDeletedAt) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUserID requires an ID field in the mutation") + if m.user != nil { + fields = append(fields, host.FieldUserID) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldUserID: %w", err) + if m.hostname != nil { + fields = append(fields, host.FieldHostname) } - return oldValue.UserID, nil -} - -// ResetUserID resets all changes to the "user_id" field. -func (m *ModelMutation) ResetUserID() { - m.user = nil -} - -// SetProvider sets the "provider" field. -func (m *ModelMutation) SetProvider(s string) { - m.provider = &s -} - -// Provider returns the value of the "provider" field in the mutation. -func (m *ModelMutation) Provider() (r string, exists bool) { - v := m.provider - if v == nil { - return + if m.arch != nil { + fields = append(fields, host.FieldArch) } - return *v, true -} - -// OldProvider returns the old "provider" field's value of the Model entity. -// If the Model 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 *ModelMutation) OldProvider(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldProvider is only allowed on UpdateOne operations") + if m.cores != nil { + fields = append(fields, host.FieldCores) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldProvider requires an ID field in the mutation") + if m.weight != nil { + fields = append(fields, host.FieldWeight) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldProvider: %w", err) + if m.memory != nil { + fields = append(fields, host.FieldMemory) } - return oldValue.Provider, nil -} - -// ResetProvider resets all changes to the "provider" field. -func (m *ModelMutation) ResetProvider() { - m.provider = nil -} - -// SetAPIKey sets the "api_key" field. -func (m *ModelMutation) SetAPIKey(s string) { - m.api_key = &s -} - -// APIKey returns the value of the "api_key" field in the mutation. -func (m *ModelMutation) APIKey() (r string, exists bool) { - v := m.api_key - if v == nil { - return + if m.disk != nil { + fields = append(fields, host.FieldDisk) } - return *v, true -} - -// OldAPIKey returns the old "api_key" field's value of the Model entity. -// If the Model 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 *ModelMutation) OldAPIKey(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldAPIKey is only allowed on UpdateOne operations") + if m.os != nil { + fields = append(fields, host.FieldOs) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldAPIKey requires an ID field in the mutation") + if m.external_ip != nil { + fields = append(fields, host.FieldExternalIP) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldAPIKey: %w", err) + if m.internal_ip != nil { + fields = append(fields, host.FieldInternalIP) } - return oldValue.APIKey, nil -} - -// ResetAPIKey resets all changes to the "api_key" field. -func (m *ModelMutation) ResetAPIKey() { - m.api_key = nil -} - -// SetBaseURL sets the "base_url" field. -func (m *ModelMutation) SetBaseURL(s string) { - m.base_url = &s -} - -// BaseURL returns the value of the "base_url" field in the mutation. -func (m *ModelMutation) BaseURL() (r string, exists bool) { - v := m.base_url - if v == nil { - return + if m.version != nil { + fields = append(fields, host.FieldVersion) } - return *v, true -} - -// OldBaseURL returns the old "base_url" field's value of the Model entity. -// If the Model 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 *ModelMutation) OldBaseURL(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldBaseURL is only allowed on UpdateOne operations") + if m.machine_id != nil { + fields = append(fields, host.FieldMachineID) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldBaseURL requires an ID field in the mutation") + if m.remark != nil { + fields = append(fields, host.FieldRemark) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldBaseURL: %w", err) + if m.created_at != nil { + fields = append(fields, host.FieldCreatedAt) } - return oldValue.BaseURL, nil -} - -// ResetBaseURL resets all changes to the "base_url" field. -func (m *ModelMutation) ResetBaseURL() { - m.base_url = nil + if m.updated_at != nil { + fields = append(fields, host.FieldUpdatedAt) + } + return fields } -// SetModel sets the "model" field. -func (m *ModelMutation) SetModel(s string) { - m.model = &s +// 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 *HostMutation) Field(name string) (ent.Value, bool) { + switch name { + case host.FieldDeletedAt: + return m.DeletedAt() + case host.FieldUserID: + return m.UserID() + case host.FieldHostname: + return m.Hostname() + case host.FieldArch: + return m.Arch() + case host.FieldCores: + return m.Cores() + case host.FieldWeight: + return m.Weight() + case host.FieldMemory: + return m.Memory() + case host.FieldDisk: + return m.Disk() + case host.FieldOs: + return m.Os() + case host.FieldExternalIP: + return m.ExternalIP() + case host.FieldInternalIP: + return m.InternalIP() + case host.FieldVersion: + return m.Version() + case host.FieldMachineID: + return m.MachineID() + case host.FieldRemark: + return m.Remark() + case host.FieldCreatedAt: + return m.CreatedAt() + case host.FieldUpdatedAt: + return m.UpdatedAt() + } + return nil, false } -// Model returns the value of the "model" field in the mutation. -func (m *ModelMutation) Model() (r string, exists bool) { - v := m.model - if v == nil { - return +// 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 *HostMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case host.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case host.FieldUserID: + return m.OldUserID(ctx) + case host.FieldHostname: + return m.OldHostname(ctx) + case host.FieldArch: + return m.OldArch(ctx) + case host.FieldCores: + return m.OldCores(ctx) + case host.FieldWeight: + return m.OldWeight(ctx) + case host.FieldMemory: + return m.OldMemory(ctx) + case host.FieldDisk: + return m.OldDisk(ctx) + case host.FieldOs: + return m.OldOs(ctx) + case host.FieldExternalIP: + return m.OldExternalIP(ctx) + case host.FieldInternalIP: + return m.OldInternalIP(ctx) + case host.FieldVersion: + return m.OldVersion(ctx) + case host.FieldMachineID: + return m.OldMachineID(ctx) + case host.FieldRemark: + return m.OldRemark(ctx) + case host.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case host.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) } - return *v, true + return nil, fmt.Errorf("unknown Host field %s", name) } -// OldModel returns the old "model" field's value of the Model entity. -// If the Model 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 *ModelMutation) OldModel(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldModel is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldModel requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldModel: %w", err) +// 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 *HostMutation) SetField(name string, value ent.Value) error { + switch name { + case host.FieldDeletedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeletedAt(v) + return nil + case host.FieldUserID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil + case host.FieldHostname: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetHostname(v) + return nil + case host.FieldArch: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetArch(v) + return nil + case host.FieldCores: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCores(v) + return nil + case host.FieldWeight: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetWeight(v) + return nil + case host.FieldMemory: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMemory(v) + return nil + case host.FieldDisk: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDisk(v) + return nil + case host.FieldOs: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOs(v) + return nil + case host.FieldExternalIP: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetExternalIP(v) + return nil + case host.FieldInternalIP: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInternalIP(v) + return nil + case host.FieldVersion: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetVersion(v) + return nil + case host.FieldMachineID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMachineID(v) + return nil + case host.FieldRemark: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRemark(v) + return nil + case host.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 host.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil } - return oldValue.Model, nil + return fmt.Errorf("unknown Host field %s", name) } -// ResetModel resets all changes to the "model" field. -func (m *ModelMutation) ResetModel() { - m.model = nil +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *HostMutation) AddedFields() []string { + var fields []string + if m.addcores != nil { + fields = append(fields, host.FieldCores) + } + if m.addweight != nil { + fields = append(fields, host.FieldWeight) + } + if m.addmemory != nil { + fields = append(fields, host.FieldMemory) + } + if m.adddisk != nil { + fields = append(fields, host.FieldDisk) + } + return fields } -// SetRemark sets the "remark" field. -func (m *ModelMutation) SetRemark(s string) { - m.remark = &s +// 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 *HostMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case host.FieldCores: + return m.AddedCores() + case host.FieldWeight: + return m.AddedWeight() + case host.FieldMemory: + return m.AddedMemory() + case host.FieldDisk: + return m.AddedDisk() + } + return nil, false } -// Remark returns the value of the "remark" field in the mutation. -func (m *ModelMutation) Remark() (r string, exists bool) { - v := m.remark - if v == nil { - return +// 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 *HostMutation) AddField(name string, value ent.Value) error { + switch name { + case host.FieldCores: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddCores(v) + return nil + case host.FieldWeight: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddWeight(v) + return nil + case host.FieldMemory: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddMemory(v) + return nil + case host.FieldDisk: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddDisk(v) + return nil } - return *v, true + return fmt.Errorf("unknown Host numeric field %s", name) } -// OldRemark returns the old "remark" field's value of the Model entity. -// If the Model 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 *ModelMutation) OldRemark(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldRemark is only allowed on UpdateOne operations") +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *HostMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(host.FieldDeletedAt) { + fields = append(fields, host.FieldDeletedAt) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldRemark requires an ID field in the mutation") + if m.FieldCleared(host.FieldHostname) { + fields = append(fields, host.FieldHostname) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldRemark: %w", err) + if m.FieldCleared(host.FieldArch) { + fields = append(fields, host.FieldArch) } - return oldValue.Remark, nil -} - -// ClearRemark clears the value of the "remark" field. -func (m *ModelMutation) ClearRemark() { - m.remark = nil - m.clearedFields[model.FieldRemark] = struct{}{} + if m.FieldCleared(host.FieldCores) { + fields = append(fields, host.FieldCores) + } + if m.FieldCleared(host.FieldMemory) { + fields = append(fields, host.FieldMemory) + } + if m.FieldCleared(host.FieldDisk) { + fields = append(fields, host.FieldDisk) + } + if m.FieldCleared(host.FieldOs) { + fields = append(fields, host.FieldOs) + } + if m.FieldCleared(host.FieldExternalIP) { + fields = append(fields, host.FieldExternalIP) + } + if m.FieldCleared(host.FieldInternalIP) { + fields = append(fields, host.FieldInternalIP) + } + if m.FieldCleared(host.FieldVersion) { + fields = append(fields, host.FieldVersion) + } + if m.FieldCleared(host.FieldMachineID) { + fields = append(fields, host.FieldMachineID) + } + if m.FieldCleared(host.FieldRemark) { + fields = append(fields, host.FieldRemark) + } + return fields } -// RemarkCleared returns if the "remark" field was cleared in this mutation. -func (m *ModelMutation) RemarkCleared() bool { - _, ok := m.clearedFields[model.FieldRemark] +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *HostMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] return ok } -// ResetRemark resets all changes to the "remark" field. -func (m *ModelMutation) ResetRemark() { - m.remark = nil - delete(m.clearedFields, model.FieldRemark) -} - -// SetTemperature sets the "temperature" field. -func (m *ModelMutation) SetTemperature(f float64) { - m.temperature = &f - m.addtemperature = nil +// 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 *HostMutation) ClearField(name string) error { + switch name { + case host.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case host.FieldHostname: + m.ClearHostname() + return nil + case host.FieldArch: + m.ClearArch() + return nil + case host.FieldCores: + m.ClearCores() + return nil + case host.FieldMemory: + m.ClearMemory() + return nil + case host.FieldDisk: + m.ClearDisk() + return nil + case host.FieldOs: + m.ClearOs() + return nil + case host.FieldExternalIP: + m.ClearExternalIP() + return nil + case host.FieldInternalIP: + m.ClearInternalIP() + return nil + case host.FieldVersion: + m.ClearVersion() + return nil + case host.FieldMachineID: + m.ClearMachineID() + return nil + case host.FieldRemark: + m.ClearRemark() + return nil + } + return fmt.Errorf("unknown Host nullable field %s", name) } -// Temperature returns the value of the "temperature" field in the mutation. -func (m *ModelMutation) Temperature() (r float64, exists bool) { - v := m.temperature - if v == nil { - return +// 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 *HostMutation) ResetField(name string) error { + switch name { + case host.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case host.FieldUserID: + m.ResetUserID() + return nil + case host.FieldHostname: + m.ResetHostname() + return nil + case host.FieldArch: + m.ResetArch() + return nil + case host.FieldCores: + m.ResetCores() + return nil + case host.FieldWeight: + m.ResetWeight() + return nil + case host.FieldMemory: + m.ResetMemory() + return nil + case host.FieldDisk: + m.ResetDisk() + return nil + case host.FieldOs: + m.ResetOs() + return nil + case host.FieldExternalIP: + m.ResetExternalIP() + return nil + case host.FieldInternalIP: + m.ResetInternalIP() + return nil + case host.FieldVersion: + m.ResetVersion() + return nil + case host.FieldMachineID: + m.ResetMachineID() + return nil + case host.FieldRemark: + m.ResetRemark() + return nil + case host.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case host.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil } - return *v, true + return fmt.Errorf("unknown Host field %s", name) } -// OldTemperature returns the old "temperature" field's value of the Model entity. -// If the Model 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 *ModelMutation) OldTemperature(ctx context.Context) (v float64, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldTemperature is only allowed on UpdateOne operations") +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *HostMutation) AddedEdges() []string { + edges := make([]string, 0, 4) + if m.vms != nil { + edges = append(edges, host.EdgeVms) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldTemperature requires an ID field in the mutation") + if m.user != nil { + edges = append(edges, host.EdgeUser) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldTemperature: %w", err) + if m.groups != nil { + edges = append(edges, host.EdgeGroups) } - return oldValue.Temperature, nil -} - -// AddTemperature adds f to the "temperature" field. -func (m *ModelMutation) AddTemperature(f float64) { - if m.addtemperature != nil { - *m.addtemperature += f - } else { - m.addtemperature = &f + if m.team_group_hosts != nil { + edges = append(edges, host.EdgeTeamGroupHosts) } + return edges } -// AddedTemperature returns the value that was added to the "temperature" field in this mutation. -func (m *ModelMutation) AddedTemperature() (r float64, exists bool) { - v := m.addtemperature - if v == nil { - return +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *HostMutation) AddedIDs(name string) []ent.Value { + switch name { + case host.EdgeVms: + ids := make([]ent.Value, 0, len(m.vms)) + for id := range m.vms { + ids = append(ids, id) + } + return ids + case host.EdgeUser: + if id := m.user; id != nil { + return []ent.Value{*id} + } + case host.EdgeGroups: + ids := make([]ent.Value, 0, len(m.groups)) + for id := range m.groups { + ids = append(ids, id) + } + return ids + case host.EdgeTeamGroupHosts: + ids := make([]ent.Value, 0, len(m.team_group_hosts)) + for id := range m.team_group_hosts { + ids = append(ids, id) + } + return ids } - return *v, true -} - -// ClearTemperature clears the value of the "temperature" field. -func (m *ModelMutation) ClearTemperature() { - m.temperature = nil - m.addtemperature = nil - m.clearedFields[model.FieldTemperature] = struct{}{} -} - -// TemperatureCleared returns if the "temperature" field was cleared in this mutation. -func (m *ModelMutation) TemperatureCleared() bool { - _, ok := m.clearedFields[model.FieldTemperature] - return ok -} - -// ResetTemperature resets all changes to the "temperature" field. -func (m *ModelMutation) ResetTemperature() { - m.temperature = nil - m.addtemperature = nil - delete(m.clearedFields, model.FieldTemperature) + return nil } -// SetInterfaceType sets the "interface_type" field. -func (m *ModelMutation) SetInterfaceType(s string) { - m.interface_type = &s +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *HostMutation) RemovedEdges() []string { + edges := make([]string, 0, 4) + if m.removedvms != nil { + edges = append(edges, host.EdgeVms) + } + if m.removedgroups != nil { + edges = append(edges, host.EdgeGroups) + } + if m.removedteam_group_hosts != nil { + edges = append(edges, host.EdgeTeamGroupHosts) + } + return edges } -// InterfaceType returns the value of the "interface_type" field in the mutation. -func (m *ModelMutation) InterfaceType() (r string, exists bool) { - v := m.interface_type - if v == nil { - return +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *HostMutation) RemovedIDs(name string) []ent.Value { + switch name { + case host.EdgeVms: + ids := make([]ent.Value, 0, len(m.removedvms)) + for id := range m.removedvms { + ids = append(ids, id) + } + return ids + case host.EdgeGroups: + ids := make([]ent.Value, 0, len(m.removedgroups)) + for id := range m.removedgroups { + ids = append(ids, id) + } + return ids + case host.EdgeTeamGroupHosts: + ids := make([]ent.Value, 0, len(m.removedteam_group_hosts)) + for id := range m.removedteam_group_hosts { + ids = append(ids, id) + } + return ids } - return *v, true + return nil } -// OldInterfaceType returns the old "interface_type" field's value of the Model entity. -// If the Model 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 *ModelMutation) OldInterfaceType(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldInterfaceType is only allowed on UpdateOne operations") +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *HostMutation) ClearedEdges() []string { + edges := make([]string, 0, 4) + if m.clearedvms { + edges = append(edges, host.EdgeVms) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldInterfaceType requires an ID field in the mutation") + if m.cleareduser { + edges = append(edges, host.EdgeUser) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldInterfaceType: %w", err) + if m.clearedgroups { + edges = append(edges, host.EdgeGroups) } - return oldValue.InterfaceType, nil + if m.clearedteam_group_hosts { + edges = append(edges, host.EdgeTeamGroupHosts) + } + return edges } -// ClearInterfaceType clears the value of the "interface_type" field. -func (m *ModelMutation) ClearInterfaceType() { - m.interface_type = nil - m.clearedFields[model.FieldInterfaceType] = struct{}{} +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *HostMutation) EdgeCleared(name string) bool { + switch name { + case host.EdgeVms: + return m.clearedvms + case host.EdgeUser: + return m.cleareduser + case host.EdgeGroups: + return m.clearedgroups + case host.EdgeTeamGroupHosts: + return m.clearedteam_group_hosts + } + return false } -// InterfaceTypeCleared returns if the "interface_type" field was cleared in this mutation. -func (m *ModelMutation) InterfaceTypeCleared() bool { - _, ok := m.clearedFields[model.FieldInterfaceType] - return ok +// 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 *HostMutation) ClearEdge(name string) error { + switch name { + case host.EdgeUser: + m.ClearUser() + return nil + } + return fmt.Errorf("unknown Host unique edge %s", name) } -// ResetInterfaceType resets all changes to the "interface_type" field. -func (m *ModelMutation) ResetInterfaceType() { - m.interface_type = nil - delete(m.clearedFields, model.FieldInterfaceType) +// 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 *HostMutation) ResetEdge(name string) error { + switch name { + case host.EdgeVms: + m.ResetVms() + return nil + case host.EdgeUser: + m.ResetUser() + return nil + case host.EdgeGroups: + m.ResetGroups() + return nil + case host.EdgeTeamGroupHosts: + m.ResetTeamGroupHosts() + return nil + } + return fmt.Errorf("unknown Host edge %s", name) } -// SetWeight sets the "weight" field. -func (m *ModelMutation) SetWeight(i int) { - m.weight = &i - m.addweight = nil +// ImageMutation represents an operation that mutates the Image nodes in the graph. +type ImageMutation struct { + config + op Op + typ string + id *uuid.UUID + deleted_at *time.Time + name *string + remark *string + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + user *uuid.UUID + cleareduser bool + teams map[uuid.UUID]struct{} + removedteams map[uuid.UUID]struct{} + clearedteams bool + groups map[uuid.UUID]struct{} + removedgroups map[uuid.UUID]struct{} + clearedgroups bool + team_images map[uuid.UUID]struct{} + removedteam_images map[uuid.UUID]struct{} + clearedteam_images bool + team_group_images map[uuid.UUID]struct{} + removedteam_group_images map[uuid.UUID]struct{} + clearedteam_group_images bool + done bool + oldValue func(context.Context) (*Image, error) + predicates []predicate.Image } -// Weight returns the value of the "weight" field in the mutation. -func (m *ModelMutation) Weight() (r int, exists bool) { - v := m.weight - if v == nil { - return - } - return *v, true -} +var _ ent.Mutation = (*ImageMutation)(nil) -// OldWeight returns the old "weight" field's value of the Model entity. -// If the Model 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 *ModelMutation) OldWeight(ctx context.Context) (v int, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldWeight is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldWeight requires an ID field in the mutation") +// imageOption allows management of the mutation configuration using functional options. +type imageOption func(*ImageMutation) + +// newImageMutation creates new mutation for the Image entity. +func newImageMutation(c config, op Op, opts ...imageOption) *ImageMutation { + m := &ImageMutation{ + config: c, + op: op, + typ: TypeImage, + clearedFields: make(map[string]struct{}), } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldWeight: %w", err) + for _, opt := range opts { + opt(m) } - return oldValue.Weight, nil + return m } -// AddWeight adds i to the "weight" field. -func (m *ModelMutation) AddWeight(i int) { - if m.addweight != nil { - *m.addweight += i - } else { - m.addweight = &i +// withImageID sets the ID field of the mutation. +func withImageID(id uuid.UUID) imageOption { + return func(m *ImageMutation) { + var ( + err error + once sync.Once + value *Image + ) + m.oldValue = func(ctx context.Context) (*Image, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Image.Get(ctx, id) + } + }) + return value, err + } + m.id = &id } } -// AddedWeight returns the value that was added to the "weight" field in this mutation. -func (m *ModelMutation) AddedWeight() (r int, exists bool) { - v := m.addweight - if v == nil { - return +// withImage sets the old Image of the mutation. +func withImage(node *Image) imageOption { + return func(m *ImageMutation) { + m.oldValue = func(context.Context) (*Image, error) { + return node, nil + } + m.id = &node.ID } - return *v, true } -// ResetWeight resets all changes to the "weight" field. -func (m *ModelMutation) ResetWeight() { - m.weight = nil - m.addweight = nil +// 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 ImageMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client } -// SetLastCheckAt sets the "last_check_at" field. -func (m *ModelMutation) SetLastCheckAt(t time.Time) { - m.last_check_at = &t +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m ImageMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("db: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil } -// LastCheckAt returns the value of the "last_check_at" field in the mutation. -func (m *ModelMutation) LastCheckAt() (r time.Time, exists bool) { - v := m.last_check_at +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of Image entities. +func (m *ImageMutation) 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 *ImageMutation) 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 *ImageMutation) 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().Image.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *ImageMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *ImageMutation) DeletedAt() (r time.Time, exists bool) { + v := m.deleted_at if v == nil { return } return *v, true } -// OldLastCheckAt returns the old "last_check_at" field's value of the Model entity. -// If the Model object wasn't provided to the builder, the object is fetched from the database. +// OldDeletedAt returns the old "deleted_at" field's value of the Image entity. +// If the Image 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 *ModelMutation) OldLastCheckAt(ctx context.Context) (v time.Time, err error) { +func (m *ImageMutation) OldDeletedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldLastCheckAt is only allowed on UpdateOne operations") + return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldLastCheckAt requires an ID field in the mutation") + return v, errors.New("OldDeletedAt requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldLastCheckAt: %w", err) + return v, fmt.Errorf("querying old value for OldDeletedAt: %w", err) } - return oldValue.LastCheckAt, nil + return oldValue.DeletedAt, nil } -// ClearLastCheckAt clears the value of the "last_check_at" field. -func (m *ModelMutation) ClearLastCheckAt() { - m.last_check_at = nil - m.clearedFields[model.FieldLastCheckAt] = struct{}{} +// ClearDeletedAt clears the value of the "deleted_at" field. +func (m *ImageMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[image.FieldDeletedAt] = struct{}{} } -// LastCheckAtCleared returns if the "last_check_at" field was cleared in this mutation. -func (m *ModelMutation) LastCheckAtCleared() bool { - _, ok := m.clearedFields[model.FieldLastCheckAt] +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *ImageMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[image.FieldDeletedAt] return ok } -// ResetLastCheckAt resets all changes to the "last_check_at" field. -func (m *ModelMutation) ResetLastCheckAt() { - m.last_check_at = nil - delete(m.clearedFields, model.FieldLastCheckAt) +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *ImageMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, image.FieldDeletedAt) } -// SetLastCheckSuccess sets the "last_check_success" field. -func (m *ModelMutation) SetLastCheckSuccess(b bool) { - m.last_check_success = &b +// SetUserID sets the "user_id" field. +func (m *ImageMutation) SetUserID(u uuid.UUID) { + m.user = &u } -// LastCheckSuccess returns the value of the "last_check_success" field in the mutation. -func (m *ModelMutation) LastCheckSuccess() (r bool, exists bool) { - v := m.last_check_success +// UserID returns the value of the "user_id" field in the mutation. +func (m *ImageMutation) UserID() (r uuid.UUID, exists bool) { + v := m.user if v == nil { return } return *v, true } -// OldLastCheckSuccess returns the old "last_check_success" field's value of the Model entity. -// If the Model object wasn't provided to the builder, the object is fetched from the database. +// OldUserID returns the old "user_id" field's value of the Image entity. +// If the Image 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 *ModelMutation) OldLastCheckSuccess(ctx context.Context) (v bool, err error) { +func (m *ImageMutation) OldUserID(ctx context.Context) (v uuid.UUID, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldLastCheckSuccess is only allowed on UpdateOne operations") + return v, errors.New("OldUserID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldLastCheckSuccess requires an ID field in the mutation") + return v, errors.New("OldUserID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldLastCheckSuccess: %w", err) + return v, fmt.Errorf("querying old value for OldUserID: %w", err) } - return oldValue.LastCheckSuccess, nil + return oldValue.UserID, nil } -// ClearLastCheckSuccess clears the value of the "last_check_success" field. -func (m *ModelMutation) ClearLastCheckSuccess() { - m.last_check_success = nil - m.clearedFields[model.FieldLastCheckSuccess] = struct{}{} +// ResetUserID resets all changes to the "user_id" field. +func (m *ImageMutation) ResetUserID() { + m.user = nil } -// LastCheckSuccessCleared returns if the "last_check_success" field was cleared in this mutation. -func (m *ModelMutation) LastCheckSuccessCleared() bool { - _, ok := m.clearedFields[model.FieldLastCheckSuccess] - return ok +// SetName sets the "name" field. +func (m *ImageMutation) SetName(s string) { + m.name = &s } -// ResetLastCheckSuccess resets all changes to the "last_check_success" field. -func (m *ModelMutation) ResetLastCheckSuccess() { - m.last_check_success = nil - delete(m.clearedFields, model.FieldLastCheckSuccess) +// Name returns the value of the "name" field in the mutation. +func (m *ImageMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true } -// SetLastCheckError sets the "last_check_error" field. -func (m *ModelMutation) SetLastCheckError(s string) { - m.last_check_error = &s +// OldName returns the old "name" field's value of the Image entity. +// If the Image 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 *ImageMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil } -// LastCheckError returns the value of the "last_check_error" field in the mutation. -func (m *ModelMutation) LastCheckError() (r string, exists bool) { - v := m.last_check_error +// ResetName resets all changes to the "name" field. +func (m *ImageMutation) ResetName() { + m.name = nil +} + +// SetRemark sets the "remark" field. +func (m *ImageMutation) SetRemark(s string) { + m.remark = &s +} + +// Remark returns the value of the "remark" field in the mutation. +func (m *ImageMutation) Remark() (r string, exists bool) { + v := m.remark if v == nil { return } return *v, true } -// OldLastCheckError returns the old "last_check_error" field's value of the Model entity. -// If the Model object wasn't provided to the builder, the object is fetched from the database. +// OldRemark returns the old "remark" field's value of the Image entity. +// If the Image 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 *ModelMutation) OldLastCheckError(ctx context.Context) (v string, err error) { +func (m *ImageMutation) OldRemark(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldLastCheckError is only allowed on UpdateOne operations") + return v, errors.New("OldRemark is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldLastCheckError requires an ID field in the mutation") + return v, errors.New("OldRemark requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldLastCheckError: %w", err) + return v, fmt.Errorf("querying old value for OldRemark: %w", err) } - return oldValue.LastCheckError, nil + return oldValue.Remark, nil } -// ClearLastCheckError clears the value of the "last_check_error" field. -func (m *ModelMutation) ClearLastCheckError() { - m.last_check_error = nil - m.clearedFields[model.FieldLastCheckError] = struct{}{} +// ClearRemark clears the value of the "remark" field. +func (m *ImageMutation) ClearRemark() { + m.remark = nil + m.clearedFields[image.FieldRemark] = struct{}{} } -// LastCheckErrorCleared returns if the "last_check_error" field was cleared in this mutation. -func (m *ModelMutation) LastCheckErrorCleared() bool { - _, ok := m.clearedFields[model.FieldLastCheckError] +// RemarkCleared returns if the "remark" field was cleared in this mutation. +func (m *ImageMutation) RemarkCleared() bool { + _, ok := m.clearedFields[image.FieldRemark] return ok } -// ResetLastCheckError resets all changes to the "last_check_error" field. -func (m *ModelMutation) ResetLastCheckError() { - m.last_check_error = nil - delete(m.clearedFields, model.FieldLastCheckError) +// ResetRemark resets all changes to the "remark" field. +func (m *ImageMutation) ResetRemark() { + m.remark = nil + delete(m.clearedFields, image.FieldRemark) } // SetCreatedAt sets the "created_at" field. -func (m *ModelMutation) SetCreatedAt(t time.Time) { +func (m *ImageMutation) SetCreatedAt(t time.Time) { m.created_at = &t } // CreatedAt returns the value of the "created_at" field in the mutation. -func (m *ModelMutation) CreatedAt() (r time.Time, exists bool) { +func (m *ImageMutation) CreatedAt() (r time.Time, exists bool) { v := m.created_at if v == nil { return @@ -2576,10 +2929,10 @@ func (m *ModelMutation) CreatedAt() (r time.Time, exists bool) { return *v, true } -// OldCreatedAt returns the old "created_at" field's value of the Model entity. -// If the Model object wasn't provided to the builder, the object is fetched from the database. +// OldCreatedAt returns the old "created_at" field's value of the Image entity. +// If the Image 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 *ModelMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { +func (m *ImageMutation) 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") } @@ -2594,17 +2947,17 @@ func (m *ModelMutation) OldCreatedAt(ctx context.Context) (v time.Time, err erro } // ResetCreatedAt resets all changes to the "created_at" field. -func (m *ModelMutation) ResetCreatedAt() { +func (m *ImageMutation) ResetCreatedAt() { m.created_at = nil } // SetUpdatedAt sets the "updated_at" field. -func (m *ModelMutation) SetUpdatedAt(t time.Time) { +func (m *ImageMutation) SetUpdatedAt(t time.Time) { m.updated_at = &t } // UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *ModelMutation) UpdatedAt() (r time.Time, exists bool) { +func (m *ImageMutation) UpdatedAt() (r time.Time, exists bool) { v := m.updated_at if v == nil { return @@ -2612,10 +2965,10 @@ func (m *ModelMutation) UpdatedAt() (r time.Time, exists bool) { return *v, true } -// OldUpdatedAt returns the old "updated_at" field's value of the Model entity. -// If the Model object wasn't provided to the builder, the object is fetched from the database. +// OldUpdatedAt returns the old "updated_at" field's value of the Image entity. +// If the Image 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 *ModelMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { +func (m *ImageMutation) 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") } @@ -2630,25 +2983,25 @@ func (m *ModelMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err erro } // ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *ModelMutation) ResetUpdatedAt() { +func (m *ImageMutation) ResetUpdatedAt() { m.updated_at = nil } // ClearUser clears the "user" edge to the User entity. -func (m *ModelMutation) ClearUser() { +func (m *ImageMutation) ClearUser() { m.cleareduser = true - m.clearedFields[model.FieldUserID] = struct{}{} + m.clearedFields[image.FieldUserID] = struct{}{} } // UserCleared reports if the "user" edge to the User entity was cleared. -func (m *ModelMutation) UserCleared() bool { +func (m *ImageMutation) UserCleared() bool { return m.cleareduser } // UserIDs returns the "user" edge IDs in the mutation. // Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use // UserID instead. It exists only for internal usage by the builders. -func (m *ModelMutation) UserIDs() (ids []uuid.UUID) { +func (m *ImageMutation) UserIDs() (ids []uuid.UUID) { if id := m.user; id != nil { ids = append(ids, *id) } @@ -2656,13 +3009,13 @@ func (m *ModelMutation) UserIDs() (ids []uuid.UUID) { } // ResetUser resets all changes to the "user" edge. -func (m *ModelMutation) ResetUser() { +func (m *ImageMutation) ResetUser() { m.user = nil m.cleareduser = false } // AddTeamIDs adds the "teams" edge to the Team entity by ids. -func (m *ModelMutation) AddTeamIDs(ids ...uuid.UUID) { +func (m *ImageMutation) AddTeamIDs(ids ...uuid.UUID) { if m.teams == nil { m.teams = make(map[uuid.UUID]struct{}) } @@ -2671,221 +3024,5167 @@ func (m *ModelMutation) AddTeamIDs(ids ...uuid.UUID) { } } -// ClearTeams clears the "teams" edge to the Team entity. -func (m *ModelMutation) ClearTeams() { - m.clearedteams = true +// ClearTeams clears the "teams" edge to the Team entity. +func (m *ImageMutation) ClearTeams() { + m.clearedteams = true +} + +// TeamsCleared reports if the "teams" edge to the Team entity was cleared. +func (m *ImageMutation) TeamsCleared() bool { + return m.clearedteams +} + +// RemoveTeamIDs removes the "teams" edge to the Team entity by IDs. +func (m *ImageMutation) RemoveTeamIDs(ids ...uuid.UUID) { + if m.removedteams == nil { + m.removedteams = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.teams, ids[i]) + m.removedteams[ids[i]] = struct{}{} + } +} + +// RemovedTeams returns the removed IDs of the "teams" edge to the Team entity. +func (m *ImageMutation) RemovedTeamsIDs() (ids []uuid.UUID) { + for id := range m.removedteams { + ids = append(ids, id) + } + return +} + +// TeamsIDs returns the "teams" edge IDs in the mutation. +func (m *ImageMutation) TeamsIDs() (ids []uuid.UUID) { + for id := range m.teams { + ids = append(ids, id) + } + return +} + +// ResetTeams resets all changes to the "teams" edge. +func (m *ImageMutation) ResetTeams() { + m.teams = nil + m.clearedteams = false + m.removedteams = nil +} + +// AddGroupIDs adds the "groups" edge to the TeamGroup entity by ids. +func (m *ImageMutation) AddGroupIDs(ids ...uuid.UUID) { + if m.groups == nil { + m.groups = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.groups[ids[i]] = struct{}{} + } +} + +// ClearGroups clears the "groups" edge to the TeamGroup entity. +func (m *ImageMutation) ClearGroups() { + m.clearedgroups = true +} + +// GroupsCleared reports if the "groups" edge to the TeamGroup entity was cleared. +func (m *ImageMutation) GroupsCleared() bool { + return m.clearedgroups +} + +// RemoveGroupIDs removes the "groups" edge to the TeamGroup entity by IDs. +func (m *ImageMutation) RemoveGroupIDs(ids ...uuid.UUID) { + if m.removedgroups == nil { + m.removedgroups = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.groups, ids[i]) + m.removedgroups[ids[i]] = struct{}{} + } +} + +// RemovedGroups returns the removed IDs of the "groups" edge to the TeamGroup entity. +func (m *ImageMutation) RemovedGroupsIDs() (ids []uuid.UUID) { + for id := range m.removedgroups { + ids = append(ids, id) + } + return +} + +// GroupsIDs returns the "groups" edge IDs in the mutation. +func (m *ImageMutation) GroupsIDs() (ids []uuid.UUID) { + for id := range m.groups { + ids = append(ids, id) + } + return +} + +// ResetGroups resets all changes to the "groups" edge. +func (m *ImageMutation) ResetGroups() { + m.groups = nil + m.clearedgroups = false + m.removedgroups = nil +} + +// AddTeamImageIDs adds the "team_images" edge to the TeamImage entity by ids. +func (m *ImageMutation) AddTeamImageIDs(ids ...uuid.UUID) { + if m.team_images == nil { + m.team_images = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.team_images[ids[i]] = struct{}{} + } +} + +// ClearTeamImages clears the "team_images" edge to the TeamImage entity. +func (m *ImageMutation) ClearTeamImages() { + m.clearedteam_images = true +} + +// TeamImagesCleared reports if the "team_images" edge to the TeamImage entity was cleared. +func (m *ImageMutation) TeamImagesCleared() bool { + return m.clearedteam_images +} + +// RemoveTeamImageIDs removes the "team_images" edge to the TeamImage entity by IDs. +func (m *ImageMutation) RemoveTeamImageIDs(ids ...uuid.UUID) { + if m.removedteam_images == nil { + m.removedteam_images = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.team_images, ids[i]) + m.removedteam_images[ids[i]] = struct{}{} + } +} + +// RemovedTeamImages returns the removed IDs of the "team_images" edge to the TeamImage entity. +func (m *ImageMutation) RemovedTeamImagesIDs() (ids []uuid.UUID) { + for id := range m.removedteam_images { + ids = append(ids, id) + } + return +} + +// TeamImagesIDs returns the "team_images" edge IDs in the mutation. +func (m *ImageMutation) TeamImagesIDs() (ids []uuid.UUID) { + for id := range m.team_images { + ids = append(ids, id) + } + return +} + +// ResetTeamImages resets all changes to the "team_images" edge. +func (m *ImageMutation) ResetTeamImages() { + m.team_images = nil + m.clearedteam_images = false + m.removedteam_images = nil +} + +// AddTeamGroupImageIDs adds the "team_group_images" edge to the TeamGroupImage entity by ids. +func (m *ImageMutation) AddTeamGroupImageIDs(ids ...uuid.UUID) { + if m.team_group_images == nil { + m.team_group_images = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.team_group_images[ids[i]] = struct{}{} + } +} + +// ClearTeamGroupImages clears the "team_group_images" edge to the TeamGroupImage entity. +func (m *ImageMutation) ClearTeamGroupImages() { + m.clearedteam_group_images = true +} + +// TeamGroupImagesCleared reports if the "team_group_images" edge to the TeamGroupImage entity was cleared. +func (m *ImageMutation) TeamGroupImagesCleared() bool { + return m.clearedteam_group_images +} + +// RemoveTeamGroupImageIDs removes the "team_group_images" edge to the TeamGroupImage entity by IDs. +func (m *ImageMutation) RemoveTeamGroupImageIDs(ids ...uuid.UUID) { + if m.removedteam_group_images == nil { + m.removedteam_group_images = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.team_group_images, ids[i]) + m.removedteam_group_images[ids[i]] = struct{}{} + } +} + +// RemovedTeamGroupImages returns the removed IDs of the "team_group_images" edge to the TeamGroupImage entity. +func (m *ImageMutation) RemovedTeamGroupImagesIDs() (ids []uuid.UUID) { + for id := range m.removedteam_group_images { + ids = append(ids, id) + } + return +} + +// TeamGroupImagesIDs returns the "team_group_images" edge IDs in the mutation. +func (m *ImageMutation) TeamGroupImagesIDs() (ids []uuid.UUID) { + for id := range m.team_group_images { + ids = append(ids, id) + } + return +} + +// ResetTeamGroupImages resets all changes to the "team_group_images" edge. +func (m *ImageMutation) ResetTeamGroupImages() { + m.team_group_images = nil + m.clearedteam_group_images = false + m.removedteam_group_images = nil +} + +// Where appends a list predicates to the ImageMutation builder. +func (m *ImageMutation) Where(ps ...predicate.Image) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ImageMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ImageMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Image, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ImageMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ImageMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Image). +func (m *ImageMutation) 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 *ImageMutation) Fields() []string { + fields := make([]string, 0, 6) + if m.deleted_at != nil { + fields = append(fields, image.FieldDeletedAt) + } + if m.user != nil { + fields = append(fields, image.FieldUserID) + } + if m.name != nil { + fields = append(fields, image.FieldName) + } + if m.remark != nil { + fields = append(fields, image.FieldRemark) + } + if m.created_at != nil { + fields = append(fields, image.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, image.FieldUpdatedAt) + } + 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 *ImageMutation) Field(name string) (ent.Value, bool) { + switch name { + case image.FieldDeletedAt: + return m.DeletedAt() + case image.FieldUserID: + return m.UserID() + case image.FieldName: + return m.Name() + case image.FieldRemark: + return m.Remark() + case image.FieldCreatedAt: + return m.CreatedAt() + case image.FieldUpdatedAt: + return m.UpdatedAt() + } + 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 *ImageMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case image.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case image.FieldUserID: + return m.OldUserID(ctx) + case image.FieldName: + return m.OldName(ctx) + case image.FieldRemark: + return m.OldRemark(ctx) + case image.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case image.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + } + return nil, fmt.Errorf("unknown Image 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 *ImageMutation) SetField(name string, value ent.Value) error { + switch name { + case image.FieldDeletedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeletedAt(v) + return nil + case image.FieldUserID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil + case image.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case image.FieldRemark: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRemark(v) + return nil + case image.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 image.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + } + return fmt.Errorf("unknown Image field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ImageMutation) AddedFields() []string { + return nil +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *ImageMutation) AddedField(name string) (ent.Value, bool) { + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *ImageMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Image numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ImageMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(image.FieldDeletedAt) { + fields = append(fields, image.FieldDeletedAt) + } + if m.FieldCleared(image.FieldRemark) { + fields = append(fields, image.FieldRemark) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ImageMutation) 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 *ImageMutation) ClearField(name string) error { + switch name { + case image.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case image.FieldRemark: + m.ClearRemark() + return nil + } + return fmt.Errorf("unknown Image 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 *ImageMutation) ResetField(name string) error { + switch name { + case image.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case image.FieldUserID: + m.ResetUserID() + return nil + case image.FieldName: + m.ResetName() + return nil + case image.FieldRemark: + m.ResetRemark() + return nil + case image.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case image.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + } + return fmt.Errorf("unknown Image field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ImageMutation) AddedEdges() []string { + edges := make([]string, 0, 5) + if m.user != nil { + edges = append(edges, image.EdgeUser) + } + if m.teams != nil { + edges = append(edges, image.EdgeTeams) + } + if m.groups != nil { + edges = append(edges, image.EdgeGroups) + } + if m.team_images != nil { + edges = append(edges, image.EdgeTeamImages) + } + if m.team_group_images != nil { + edges = append(edges, image.EdgeTeamGroupImages) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ImageMutation) AddedIDs(name string) []ent.Value { + switch name { + case image.EdgeUser: + if id := m.user; id != nil { + return []ent.Value{*id} + } + case image.EdgeTeams: + ids := make([]ent.Value, 0, len(m.teams)) + for id := range m.teams { + ids = append(ids, id) + } + return ids + case image.EdgeGroups: + ids := make([]ent.Value, 0, len(m.groups)) + for id := range m.groups { + ids = append(ids, id) + } + return ids + case image.EdgeTeamImages: + ids := make([]ent.Value, 0, len(m.team_images)) + for id := range m.team_images { + ids = append(ids, id) + } + return ids + case image.EdgeTeamGroupImages: + ids := make([]ent.Value, 0, len(m.team_group_images)) + for id := range m.team_group_images { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *ImageMutation) RemovedEdges() []string { + edges := make([]string, 0, 5) + if m.removedteams != nil { + edges = append(edges, image.EdgeTeams) + } + if m.removedgroups != nil { + edges = append(edges, image.EdgeGroups) + } + if m.removedteam_images != nil { + edges = append(edges, image.EdgeTeamImages) + } + if m.removedteam_group_images != nil { + edges = append(edges, image.EdgeTeamGroupImages) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *ImageMutation) RemovedIDs(name string) []ent.Value { + switch name { + case image.EdgeTeams: + ids := make([]ent.Value, 0, len(m.removedteams)) + for id := range m.removedteams { + ids = append(ids, id) + } + return ids + case image.EdgeGroups: + ids := make([]ent.Value, 0, len(m.removedgroups)) + for id := range m.removedgroups { + ids = append(ids, id) + } + return ids + case image.EdgeTeamImages: + ids := make([]ent.Value, 0, len(m.removedteam_images)) + for id := range m.removedteam_images { + ids = append(ids, id) + } + return ids + case image.EdgeTeamGroupImages: + ids := make([]ent.Value, 0, len(m.removedteam_group_images)) + for id := range m.removedteam_group_images { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ImageMutation) ClearedEdges() []string { + edges := make([]string, 0, 5) + if m.cleareduser { + edges = append(edges, image.EdgeUser) + } + if m.clearedteams { + edges = append(edges, image.EdgeTeams) + } + if m.clearedgroups { + edges = append(edges, image.EdgeGroups) + } + if m.clearedteam_images { + edges = append(edges, image.EdgeTeamImages) + } + if m.clearedteam_group_images { + edges = append(edges, image.EdgeTeamGroupImages) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ImageMutation) EdgeCleared(name string) bool { + switch name { + case image.EdgeUser: + return m.cleareduser + case image.EdgeTeams: + return m.clearedteams + case image.EdgeGroups: + return m.clearedgroups + case image.EdgeTeamImages: + return m.clearedteam_images + case image.EdgeTeamGroupImages: + return m.clearedteam_group_images + } + 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 *ImageMutation) ClearEdge(name string) error { + switch name { + case image.EdgeUser: + m.ClearUser() + return nil + } + return fmt.Errorf("unknown Image 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 *ImageMutation) ResetEdge(name string) error { + switch name { + case image.EdgeUser: + m.ResetUser() + return nil + case image.EdgeTeams: + m.ResetTeams() + return nil + case image.EdgeGroups: + m.ResetGroups() + return nil + case image.EdgeTeamImages: + m.ResetTeamImages() + return nil + case image.EdgeTeamGroupImages: + m.ResetTeamGroupImages() + return nil + } + return fmt.Errorf("unknown Image edge %s", name) +} + +// ModelMutation represents an operation that mutates the Model nodes in the graph. +type ModelMutation struct { + config + op Op + typ string + id *uuid.UUID + deleted_at *time.Time + provider *string + api_key *string + base_url *string + model *string + remark *string + temperature *float64 + addtemperature *float64 + interface_type *string + weight *int + addweight *int + last_check_at *time.Time + last_check_success *bool + last_check_error *string + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + user *uuid.UUID + cleareduser bool + teams map[uuid.UUID]struct{} + removedteams map[uuid.UUID]struct{} + clearedteams bool + groups map[uuid.UUID]struct{} + removedgroups map[uuid.UUID]struct{} + clearedgroups bool + vms map[string]struct{} + removedvms map[string]struct{} + clearedvms bool + team_models map[uuid.UUID]struct{} + removedteam_models map[uuid.UUID]struct{} + clearedteam_models bool + team_group_models map[uuid.UUID]struct{} + removedteam_group_models map[uuid.UUID]struct{} + clearedteam_group_models bool + done bool + oldValue func(context.Context) (*Model, error) + predicates []predicate.Model +} + +var _ ent.Mutation = (*ModelMutation)(nil) + +// modelOption allows management of the mutation configuration using functional options. +type modelOption func(*ModelMutation) + +// newModelMutation creates new mutation for the Model entity. +func newModelMutation(c config, op Op, opts ...modelOption) *ModelMutation { + m := &ModelMutation{ + config: c, + op: op, + typ: TypeModel, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withModelID sets the ID field of the mutation. +func withModelID(id uuid.UUID) modelOption { + return func(m *ModelMutation) { + var ( + err error + once sync.Once + value *Model + ) + m.oldValue = func(ctx context.Context) (*Model, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Model.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withModel sets the old Model of the mutation. +func withModel(node *Model) modelOption { + return func(m *ModelMutation) { + m.oldValue = func(context.Context) (*Model, 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 ModelMutation) 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 ModelMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("db: 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 Model entities. +func (m *ModelMutation) 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 *ModelMutation) 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 *ModelMutation) 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().Model.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *ModelMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *ModelMutation) DeletedAt() (r time.Time, exists bool) { + v := m.deleted_at + if v == nil { + return + } + return *v, true +} + +// OldDeletedAt returns the old "deleted_at" field's value of the Model entity. +// If the Model 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 *ModelMutation) OldDeletedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDeletedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDeletedAt: %w", err) + } + return oldValue.DeletedAt, nil +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (m *ModelMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[model.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *ModelMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[model.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *ModelMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, model.FieldDeletedAt) +} + +// SetUserID sets the "user_id" field. +func (m *ModelMutation) SetUserID(u uuid.UUID) { + m.user = &u +} + +// UserID returns the value of the "user_id" field in the mutation. +func (m *ModelMutation) UserID() (r uuid.UUID, exists bool) { + v := m.user + if v == nil { + return + } + return *v, true +} + +// OldUserID returns the old "user_id" field's value of the Model entity. +// If the Model 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 *ModelMutation) OldUserID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUserID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUserID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUserID: %w", err) + } + return oldValue.UserID, nil +} + +// ResetUserID resets all changes to the "user_id" field. +func (m *ModelMutation) ResetUserID() { + m.user = nil +} + +// SetProvider sets the "provider" field. +func (m *ModelMutation) SetProvider(s string) { + m.provider = &s +} + +// Provider returns the value of the "provider" field in the mutation. +func (m *ModelMutation) Provider() (r string, exists bool) { + v := m.provider + if v == nil { + return + } + return *v, true +} + +// OldProvider returns the old "provider" field's value of the Model entity. +// If the Model 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 *ModelMutation) OldProvider(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldProvider is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldProvider requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldProvider: %w", err) + } + return oldValue.Provider, nil +} + +// ResetProvider resets all changes to the "provider" field. +func (m *ModelMutation) ResetProvider() { + m.provider = nil +} + +// SetAPIKey sets the "api_key" field. +func (m *ModelMutation) SetAPIKey(s string) { + m.api_key = &s +} + +// APIKey returns the value of the "api_key" field in the mutation. +func (m *ModelMutation) APIKey() (r string, exists bool) { + v := m.api_key + if v == nil { + return + } + return *v, true +} + +// OldAPIKey returns the old "api_key" field's value of the Model entity. +// If the Model 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 *ModelMutation) OldAPIKey(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAPIKey is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAPIKey requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAPIKey: %w", err) + } + return oldValue.APIKey, nil +} + +// ResetAPIKey resets all changes to the "api_key" field. +func (m *ModelMutation) ResetAPIKey() { + m.api_key = nil +} + +// SetBaseURL sets the "base_url" field. +func (m *ModelMutation) SetBaseURL(s string) { + m.base_url = &s +} + +// BaseURL returns the value of the "base_url" field in the mutation. +func (m *ModelMutation) BaseURL() (r string, exists bool) { + v := m.base_url + if v == nil { + return + } + return *v, true +} + +// OldBaseURL returns the old "base_url" field's value of the Model entity. +// If the Model 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 *ModelMutation) OldBaseURL(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBaseURL is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBaseURL requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBaseURL: %w", err) + } + return oldValue.BaseURL, nil +} + +// ResetBaseURL resets all changes to the "base_url" field. +func (m *ModelMutation) ResetBaseURL() { + m.base_url = nil +} + +// SetModel sets the "model" field. +func (m *ModelMutation) SetModel(s string) { + m.model = &s +} + +// Model returns the value of the "model" field in the mutation. +func (m *ModelMutation) Model() (r string, exists bool) { + v := m.model + if v == nil { + return + } + return *v, true +} + +// OldModel returns the old "model" field's value of the Model entity. +// If the Model 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 *ModelMutation) OldModel(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldModel is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldModel requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldModel: %w", err) + } + return oldValue.Model, nil +} + +// ResetModel resets all changes to the "model" field. +func (m *ModelMutation) ResetModel() { + m.model = nil +} + +// SetRemark sets the "remark" field. +func (m *ModelMutation) SetRemark(s string) { + m.remark = &s +} + +// Remark returns the value of the "remark" field in the mutation. +func (m *ModelMutation) Remark() (r string, exists bool) { + v := m.remark + if v == nil { + return + } + return *v, true +} + +// OldRemark returns the old "remark" field's value of the Model entity. +// If the Model 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 *ModelMutation) OldRemark(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRemark is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRemark requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRemark: %w", err) + } + return oldValue.Remark, nil +} + +// ClearRemark clears the value of the "remark" field. +func (m *ModelMutation) ClearRemark() { + m.remark = nil + m.clearedFields[model.FieldRemark] = struct{}{} +} + +// RemarkCleared returns if the "remark" field was cleared in this mutation. +func (m *ModelMutation) RemarkCleared() bool { + _, ok := m.clearedFields[model.FieldRemark] + return ok +} + +// ResetRemark resets all changes to the "remark" field. +func (m *ModelMutation) ResetRemark() { + m.remark = nil + delete(m.clearedFields, model.FieldRemark) +} + +// SetTemperature sets the "temperature" field. +func (m *ModelMutation) SetTemperature(f float64) { + m.temperature = &f + m.addtemperature = nil +} + +// Temperature returns the value of the "temperature" field in the mutation. +func (m *ModelMutation) Temperature() (r float64, exists bool) { + v := m.temperature + if v == nil { + return + } + return *v, true +} + +// OldTemperature returns the old "temperature" field's value of the Model entity. +// If the Model 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 *ModelMutation) OldTemperature(ctx context.Context) (v float64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTemperature is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTemperature requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTemperature: %w", err) + } + return oldValue.Temperature, nil +} + +// AddTemperature adds f to the "temperature" field. +func (m *ModelMutation) AddTemperature(f float64) { + if m.addtemperature != nil { + *m.addtemperature += f + } else { + m.addtemperature = &f + } +} + +// AddedTemperature returns the value that was added to the "temperature" field in this mutation. +func (m *ModelMutation) AddedTemperature() (r float64, exists bool) { + v := m.addtemperature + if v == nil { + return + } + return *v, true +} + +// ClearTemperature clears the value of the "temperature" field. +func (m *ModelMutation) ClearTemperature() { + m.temperature = nil + m.addtemperature = nil + m.clearedFields[model.FieldTemperature] = struct{}{} +} + +// TemperatureCleared returns if the "temperature" field was cleared in this mutation. +func (m *ModelMutation) TemperatureCleared() bool { + _, ok := m.clearedFields[model.FieldTemperature] + return ok +} + +// ResetTemperature resets all changes to the "temperature" field. +func (m *ModelMutation) ResetTemperature() { + m.temperature = nil + m.addtemperature = nil + delete(m.clearedFields, model.FieldTemperature) +} + +// SetInterfaceType sets the "interface_type" field. +func (m *ModelMutation) SetInterfaceType(s string) { + m.interface_type = &s +} + +// InterfaceType returns the value of the "interface_type" field in the mutation. +func (m *ModelMutation) InterfaceType() (r string, exists bool) { + v := m.interface_type + if v == nil { + return + } + return *v, true +} + +// OldInterfaceType returns the old "interface_type" field's value of the Model entity. +// If the Model 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 *ModelMutation) OldInterfaceType(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInterfaceType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInterfaceType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInterfaceType: %w", err) + } + return oldValue.InterfaceType, nil +} + +// ClearInterfaceType clears the value of the "interface_type" field. +func (m *ModelMutation) ClearInterfaceType() { + m.interface_type = nil + m.clearedFields[model.FieldInterfaceType] = struct{}{} +} + +// InterfaceTypeCleared returns if the "interface_type" field was cleared in this mutation. +func (m *ModelMutation) InterfaceTypeCleared() bool { + _, ok := m.clearedFields[model.FieldInterfaceType] + return ok +} + +// ResetInterfaceType resets all changes to the "interface_type" field. +func (m *ModelMutation) ResetInterfaceType() { + m.interface_type = nil + delete(m.clearedFields, model.FieldInterfaceType) +} + +// SetWeight sets the "weight" field. +func (m *ModelMutation) SetWeight(i int) { + m.weight = &i + m.addweight = nil +} + +// Weight returns the value of the "weight" field in the mutation. +func (m *ModelMutation) Weight() (r int, exists bool) { + v := m.weight + if v == nil { + return + } + return *v, true +} + +// OldWeight returns the old "weight" field's value of the Model entity. +// If the Model 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 *ModelMutation) OldWeight(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldWeight is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldWeight requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldWeight: %w", err) + } + return oldValue.Weight, nil +} + +// AddWeight adds i to the "weight" field. +func (m *ModelMutation) AddWeight(i int) { + if m.addweight != nil { + *m.addweight += i + } else { + m.addweight = &i + } +} + +// AddedWeight returns the value that was added to the "weight" field in this mutation. +func (m *ModelMutation) AddedWeight() (r int, exists bool) { + v := m.addweight + if v == nil { + return + } + return *v, true +} + +// ResetWeight resets all changes to the "weight" field. +func (m *ModelMutation) ResetWeight() { + m.weight = nil + m.addweight = nil +} + +// SetLastCheckAt sets the "last_check_at" field. +func (m *ModelMutation) SetLastCheckAt(t time.Time) { + m.last_check_at = &t +} + +// LastCheckAt returns the value of the "last_check_at" field in the mutation. +func (m *ModelMutation) LastCheckAt() (r time.Time, exists bool) { + v := m.last_check_at + if v == nil { + return + } + return *v, true +} + +// OldLastCheckAt returns the old "last_check_at" field's value of the Model entity. +// If the Model 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 *ModelMutation) OldLastCheckAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLastCheckAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLastCheckAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLastCheckAt: %w", err) + } + return oldValue.LastCheckAt, nil +} + +// ClearLastCheckAt clears the value of the "last_check_at" field. +func (m *ModelMutation) ClearLastCheckAt() { + m.last_check_at = nil + m.clearedFields[model.FieldLastCheckAt] = struct{}{} +} + +// LastCheckAtCleared returns if the "last_check_at" field was cleared in this mutation. +func (m *ModelMutation) LastCheckAtCleared() bool { + _, ok := m.clearedFields[model.FieldLastCheckAt] + return ok +} + +// ResetLastCheckAt resets all changes to the "last_check_at" field. +func (m *ModelMutation) ResetLastCheckAt() { + m.last_check_at = nil + delete(m.clearedFields, model.FieldLastCheckAt) +} + +// SetLastCheckSuccess sets the "last_check_success" field. +func (m *ModelMutation) SetLastCheckSuccess(b bool) { + m.last_check_success = &b +} + +// LastCheckSuccess returns the value of the "last_check_success" field in the mutation. +func (m *ModelMutation) LastCheckSuccess() (r bool, exists bool) { + v := m.last_check_success + if v == nil { + return + } + return *v, true +} + +// OldLastCheckSuccess returns the old "last_check_success" field's value of the Model entity. +// If the Model 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 *ModelMutation) OldLastCheckSuccess(ctx context.Context) (v bool, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLastCheckSuccess is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLastCheckSuccess requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLastCheckSuccess: %w", err) + } + return oldValue.LastCheckSuccess, nil +} + +// ClearLastCheckSuccess clears the value of the "last_check_success" field. +func (m *ModelMutation) ClearLastCheckSuccess() { + m.last_check_success = nil + m.clearedFields[model.FieldLastCheckSuccess] = struct{}{} +} + +// LastCheckSuccessCleared returns if the "last_check_success" field was cleared in this mutation. +func (m *ModelMutation) LastCheckSuccessCleared() bool { + _, ok := m.clearedFields[model.FieldLastCheckSuccess] + return ok +} + +// ResetLastCheckSuccess resets all changes to the "last_check_success" field. +func (m *ModelMutation) ResetLastCheckSuccess() { + m.last_check_success = nil + delete(m.clearedFields, model.FieldLastCheckSuccess) +} + +// SetLastCheckError sets the "last_check_error" field. +func (m *ModelMutation) SetLastCheckError(s string) { + m.last_check_error = &s +} + +// LastCheckError returns the value of the "last_check_error" field in the mutation. +func (m *ModelMutation) LastCheckError() (r string, exists bool) { + v := m.last_check_error + if v == nil { + return + } + return *v, true +} + +// OldLastCheckError returns the old "last_check_error" field's value of the Model entity. +// If the Model 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 *ModelMutation) OldLastCheckError(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldLastCheckError is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldLastCheckError requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldLastCheckError: %w", err) + } + return oldValue.LastCheckError, nil +} + +// ClearLastCheckError clears the value of the "last_check_error" field. +func (m *ModelMutation) ClearLastCheckError() { + m.last_check_error = nil + m.clearedFields[model.FieldLastCheckError] = struct{}{} +} + +// LastCheckErrorCleared returns if the "last_check_error" field was cleared in this mutation. +func (m *ModelMutation) LastCheckErrorCleared() bool { + _, ok := m.clearedFields[model.FieldLastCheckError] + return ok +} + +// ResetLastCheckError resets all changes to the "last_check_error" field. +func (m *ModelMutation) ResetLastCheckError() { + m.last_check_error = nil + delete(m.clearedFields, model.FieldLastCheckError) +} + +// SetCreatedAt sets the "created_at" field. +func (m *ModelMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *ModelMutation) 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 Model entity. +// If the Model 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 *ModelMutation) 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 *ModelMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *ModelMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *ModelMutation) 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 Model entity. +// If the Model 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 *ModelMutation) 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 *ModelMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// ClearUser clears the "user" edge to the User entity. +func (m *ModelMutation) ClearUser() { + m.cleareduser = true + m.clearedFields[model.FieldUserID] = struct{}{} +} + +// UserCleared reports if the "user" edge to the User entity was cleared. +func (m *ModelMutation) UserCleared() bool { + return m.cleareduser +} + +// UserIDs returns the "user" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UserID instead. It exists only for internal usage by the builders. +func (m *ModelMutation) UserIDs() (ids []uuid.UUID) { + if id := m.user; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetUser resets all changes to the "user" edge. +func (m *ModelMutation) ResetUser() { + m.user = nil + m.cleareduser = false +} + +// AddTeamIDs adds the "teams" edge to the Team entity by ids. +func (m *ModelMutation) AddTeamIDs(ids ...uuid.UUID) { + if m.teams == nil { + m.teams = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.teams[ids[i]] = struct{}{} + } +} + +// ClearTeams clears the "teams" edge to the Team entity. +func (m *ModelMutation) ClearTeams() { + m.clearedteams = true +} + +// TeamsCleared reports if the "teams" edge to the Team entity was cleared. +func (m *ModelMutation) TeamsCleared() bool { + return m.clearedteams +} + +// RemoveTeamIDs removes the "teams" edge to the Team entity by IDs. +func (m *ModelMutation) RemoveTeamIDs(ids ...uuid.UUID) { + if m.removedteams == nil { + m.removedteams = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.teams, ids[i]) + m.removedteams[ids[i]] = struct{}{} + } +} + +// RemovedTeams returns the removed IDs of the "teams" edge to the Team entity. +func (m *ModelMutation) RemovedTeamsIDs() (ids []uuid.UUID) { + for id := range m.removedteams { + ids = append(ids, id) + } + return +} + +// TeamsIDs returns the "teams" edge IDs in the mutation. +func (m *ModelMutation) TeamsIDs() (ids []uuid.UUID) { + for id := range m.teams { + ids = append(ids, id) + } + return +} + +// ResetTeams resets all changes to the "teams" edge. +func (m *ModelMutation) ResetTeams() { + m.teams = nil + m.clearedteams = false + m.removedteams = nil +} + +// AddGroupIDs adds the "groups" edge to the TeamGroup entity by ids. +func (m *ModelMutation) AddGroupIDs(ids ...uuid.UUID) { + if m.groups == nil { + m.groups = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.groups[ids[i]] = struct{}{} + } +} + +// ClearGroups clears the "groups" edge to the TeamGroup entity. +func (m *ModelMutation) ClearGroups() { + m.clearedgroups = true +} + +// GroupsCleared reports if the "groups" edge to the TeamGroup entity was cleared. +func (m *ModelMutation) GroupsCleared() bool { + return m.clearedgroups +} + +// RemoveGroupIDs removes the "groups" edge to the TeamGroup entity by IDs. +func (m *ModelMutation) RemoveGroupIDs(ids ...uuid.UUID) { + if m.removedgroups == nil { + m.removedgroups = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.groups, ids[i]) + m.removedgroups[ids[i]] = struct{}{} + } +} + +// RemovedGroups returns the removed IDs of the "groups" edge to the TeamGroup entity. +func (m *ModelMutation) RemovedGroupsIDs() (ids []uuid.UUID) { + for id := range m.removedgroups { + ids = append(ids, id) + } + return +} + +// GroupsIDs returns the "groups" edge IDs in the mutation. +func (m *ModelMutation) GroupsIDs() (ids []uuid.UUID) { + for id := range m.groups { + ids = append(ids, id) + } + return +} + +// ResetGroups resets all changes to the "groups" edge. +func (m *ModelMutation) ResetGroups() { + m.groups = nil + m.clearedgroups = false + m.removedgroups = nil +} + +// AddVMIDs adds the "vms" edge to the VirtualMachine entity by ids. +func (m *ModelMutation) AddVMIDs(ids ...string) { + if m.vms == nil { + m.vms = make(map[string]struct{}) + } + for i := range ids { + m.vms[ids[i]] = struct{}{} + } +} + +// ClearVms clears the "vms" edge to the VirtualMachine entity. +func (m *ModelMutation) ClearVms() { + m.clearedvms = true +} + +// VmsCleared reports if the "vms" edge to the VirtualMachine entity was cleared. +func (m *ModelMutation) VmsCleared() bool { + return m.clearedvms +} + +// RemoveVMIDs removes the "vms" edge to the VirtualMachine entity by IDs. +func (m *ModelMutation) RemoveVMIDs(ids ...string) { + if m.removedvms == nil { + m.removedvms = make(map[string]struct{}) + } + for i := range ids { + delete(m.vms, ids[i]) + m.removedvms[ids[i]] = struct{}{} + } +} + +// RemovedVms returns the removed IDs of the "vms" edge to the VirtualMachine entity. +func (m *ModelMutation) RemovedVmsIDs() (ids []string) { + for id := range m.removedvms { + ids = append(ids, id) + } + return +} + +// VmsIDs returns the "vms" edge IDs in the mutation. +func (m *ModelMutation) VmsIDs() (ids []string) { + for id := range m.vms { + ids = append(ids, id) + } + return +} + +// ResetVms resets all changes to the "vms" edge. +func (m *ModelMutation) ResetVms() { + m.vms = nil + m.clearedvms = false + m.removedvms = nil +} + +// AddTeamModelIDs adds the "team_models" edge to the TeamModel entity by ids. +func (m *ModelMutation) AddTeamModelIDs(ids ...uuid.UUID) { + if m.team_models == nil { + m.team_models = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.team_models[ids[i]] = struct{}{} + } +} + +// ClearTeamModels clears the "team_models" edge to the TeamModel entity. +func (m *ModelMutation) ClearTeamModels() { + m.clearedteam_models = true +} + +// TeamModelsCleared reports if the "team_models" edge to the TeamModel entity was cleared. +func (m *ModelMutation) TeamModelsCleared() bool { + return m.clearedteam_models +} + +// RemoveTeamModelIDs removes the "team_models" edge to the TeamModel entity by IDs. +func (m *ModelMutation) RemoveTeamModelIDs(ids ...uuid.UUID) { + if m.removedteam_models == nil { + m.removedteam_models = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.team_models, ids[i]) + m.removedteam_models[ids[i]] = struct{}{} + } +} + +// RemovedTeamModels returns the removed IDs of the "team_models" edge to the TeamModel entity. +func (m *ModelMutation) RemovedTeamModelsIDs() (ids []uuid.UUID) { + for id := range m.removedteam_models { + ids = append(ids, id) + } + return +} + +// TeamModelsIDs returns the "team_models" edge IDs in the mutation. +func (m *ModelMutation) TeamModelsIDs() (ids []uuid.UUID) { + for id := range m.team_models { + ids = append(ids, id) + } + return +} + +// ResetTeamModels resets all changes to the "team_models" edge. +func (m *ModelMutation) ResetTeamModels() { + m.team_models = nil + m.clearedteam_models = false + m.removedteam_models = nil +} + +// AddTeamGroupModelIDs adds the "team_group_models" edge to the TeamGroupModel entity by ids. +func (m *ModelMutation) AddTeamGroupModelIDs(ids ...uuid.UUID) { + if m.team_group_models == nil { + m.team_group_models = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.team_group_models[ids[i]] = struct{}{} + } +} + +// ClearTeamGroupModels clears the "team_group_models" edge to the TeamGroupModel entity. +func (m *ModelMutation) ClearTeamGroupModels() { + m.clearedteam_group_models = true +} + +// TeamGroupModelsCleared reports if the "team_group_models" edge to the TeamGroupModel entity was cleared. +func (m *ModelMutation) TeamGroupModelsCleared() bool { + return m.clearedteam_group_models +} + +// RemoveTeamGroupModelIDs removes the "team_group_models" edge to the TeamGroupModel entity by IDs. +func (m *ModelMutation) RemoveTeamGroupModelIDs(ids ...uuid.UUID) { + if m.removedteam_group_models == nil { + m.removedteam_group_models = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.team_group_models, ids[i]) + m.removedteam_group_models[ids[i]] = struct{}{} + } +} + +// RemovedTeamGroupModels returns the removed IDs of the "team_group_models" edge to the TeamGroupModel entity. +func (m *ModelMutation) RemovedTeamGroupModelsIDs() (ids []uuid.UUID) { + for id := range m.removedteam_group_models { + ids = append(ids, id) + } + return +} + +// TeamGroupModelsIDs returns the "team_group_models" edge IDs in the mutation. +func (m *ModelMutation) TeamGroupModelsIDs() (ids []uuid.UUID) { + for id := range m.team_group_models { + ids = append(ids, id) + } + return +} + +// ResetTeamGroupModels resets all changes to the "team_group_models" edge. +func (m *ModelMutation) ResetTeamGroupModels() { + m.team_group_models = nil + m.clearedteam_group_models = false + m.removedteam_group_models = nil +} + +// Where appends a list predicates to the ModelMutation builder. +func (m *ModelMutation) Where(ps ...predicate.Model) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ModelMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ModelMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Model, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ModelMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ModelMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Model). +func (m *ModelMutation) 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 *ModelMutation) Fields() []string { + fields := make([]string, 0, 15) + if m.deleted_at != nil { + fields = append(fields, model.FieldDeletedAt) + } + if m.user != nil { + fields = append(fields, model.FieldUserID) + } + if m.provider != nil { + fields = append(fields, model.FieldProvider) + } + if m.api_key != nil { + fields = append(fields, model.FieldAPIKey) + } + if m.base_url != nil { + fields = append(fields, model.FieldBaseURL) + } + if m.model != nil { + fields = append(fields, model.FieldModel) + } + if m.remark != nil { + fields = append(fields, model.FieldRemark) + } + if m.temperature != nil { + fields = append(fields, model.FieldTemperature) + } + if m.interface_type != nil { + fields = append(fields, model.FieldInterfaceType) + } + if m.weight != nil { + fields = append(fields, model.FieldWeight) + } + if m.last_check_at != nil { + fields = append(fields, model.FieldLastCheckAt) + } + if m.last_check_success != nil { + fields = append(fields, model.FieldLastCheckSuccess) + } + if m.last_check_error != nil { + fields = append(fields, model.FieldLastCheckError) + } + if m.created_at != nil { + fields = append(fields, model.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, model.FieldUpdatedAt) + } + 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 *ModelMutation) Field(name string) (ent.Value, bool) { + switch name { + case model.FieldDeletedAt: + return m.DeletedAt() + case model.FieldUserID: + return m.UserID() + case model.FieldProvider: + return m.Provider() + case model.FieldAPIKey: + return m.APIKey() + case model.FieldBaseURL: + return m.BaseURL() + case model.FieldModel: + return m.Model() + case model.FieldRemark: + return m.Remark() + case model.FieldTemperature: + return m.Temperature() + case model.FieldInterfaceType: + return m.InterfaceType() + case model.FieldWeight: + return m.Weight() + case model.FieldLastCheckAt: + return m.LastCheckAt() + case model.FieldLastCheckSuccess: + return m.LastCheckSuccess() + case model.FieldLastCheckError: + return m.LastCheckError() + case model.FieldCreatedAt: + return m.CreatedAt() + case model.FieldUpdatedAt: + return m.UpdatedAt() + } + 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 *ModelMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case model.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case model.FieldUserID: + return m.OldUserID(ctx) + case model.FieldProvider: + return m.OldProvider(ctx) + case model.FieldAPIKey: + return m.OldAPIKey(ctx) + case model.FieldBaseURL: + return m.OldBaseURL(ctx) + case model.FieldModel: + return m.OldModel(ctx) + case model.FieldRemark: + return m.OldRemark(ctx) + case model.FieldTemperature: + return m.OldTemperature(ctx) + case model.FieldInterfaceType: + return m.OldInterfaceType(ctx) + case model.FieldWeight: + return m.OldWeight(ctx) + case model.FieldLastCheckAt: + return m.OldLastCheckAt(ctx) + case model.FieldLastCheckSuccess: + return m.OldLastCheckSuccess(ctx) + case model.FieldLastCheckError: + return m.OldLastCheckError(ctx) + case model.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case model.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + } + return nil, fmt.Errorf("unknown Model 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 *ModelMutation) SetField(name string, value ent.Value) error { + switch name { + case model.FieldDeletedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeletedAt(v) + return nil + case model.FieldUserID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil + case model.FieldProvider: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetProvider(v) + return nil + case model.FieldAPIKey: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAPIKey(v) + return nil + case model.FieldBaseURL: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBaseURL(v) + return nil + case model.FieldModel: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetModel(v) + return nil + case model.FieldRemark: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRemark(v) + return nil + case model.FieldTemperature: + v, ok := value.(float64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTemperature(v) + return nil + case model.FieldInterfaceType: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInterfaceType(v) + return nil + case model.FieldWeight: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetWeight(v) + return nil + case model.FieldLastCheckAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLastCheckAt(v) + return nil + case model.FieldLastCheckSuccess: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLastCheckSuccess(v) + return nil + case model.FieldLastCheckError: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetLastCheckError(v) + return nil + case model.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 model.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + } + return fmt.Errorf("unknown Model field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ModelMutation) AddedFields() []string { + var fields []string + if m.addtemperature != nil { + fields = append(fields, model.FieldTemperature) + } + if m.addweight != nil { + fields = append(fields, model.FieldWeight) + } + 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 *ModelMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case model.FieldTemperature: + return m.AddedTemperature() + case model.FieldWeight: + return m.AddedWeight() + } + 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 *ModelMutation) AddField(name string, value ent.Value) error { + switch name { + case model.FieldTemperature: + v, ok := value.(float64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddTemperature(v) + return nil + case model.FieldWeight: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddWeight(v) + return nil + } + return fmt.Errorf("unknown Model numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ModelMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(model.FieldDeletedAt) { + fields = append(fields, model.FieldDeletedAt) + } + if m.FieldCleared(model.FieldRemark) { + fields = append(fields, model.FieldRemark) + } + if m.FieldCleared(model.FieldTemperature) { + fields = append(fields, model.FieldTemperature) + } + if m.FieldCleared(model.FieldInterfaceType) { + fields = append(fields, model.FieldInterfaceType) + } + if m.FieldCleared(model.FieldLastCheckAt) { + fields = append(fields, model.FieldLastCheckAt) + } + if m.FieldCleared(model.FieldLastCheckSuccess) { + fields = append(fields, model.FieldLastCheckSuccess) + } + if m.FieldCleared(model.FieldLastCheckError) { + fields = append(fields, model.FieldLastCheckError) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ModelMutation) 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 *ModelMutation) ClearField(name string) error { + switch name { + case model.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case model.FieldRemark: + m.ClearRemark() + return nil + case model.FieldTemperature: + m.ClearTemperature() + return nil + case model.FieldInterfaceType: + m.ClearInterfaceType() + return nil + case model.FieldLastCheckAt: + m.ClearLastCheckAt() + return nil + case model.FieldLastCheckSuccess: + m.ClearLastCheckSuccess() + return nil + case model.FieldLastCheckError: + m.ClearLastCheckError() + return nil + } + return fmt.Errorf("unknown Model 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 *ModelMutation) ResetField(name string) error { + switch name { + case model.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case model.FieldUserID: + m.ResetUserID() + return nil + case model.FieldProvider: + m.ResetProvider() + return nil + case model.FieldAPIKey: + m.ResetAPIKey() + return nil + case model.FieldBaseURL: + m.ResetBaseURL() + return nil + case model.FieldModel: + m.ResetModel() + return nil + case model.FieldRemark: + m.ResetRemark() + return nil + case model.FieldTemperature: + m.ResetTemperature() + return nil + case model.FieldInterfaceType: + m.ResetInterfaceType() + return nil + case model.FieldWeight: + m.ResetWeight() + return nil + case model.FieldLastCheckAt: + m.ResetLastCheckAt() + return nil + case model.FieldLastCheckSuccess: + m.ResetLastCheckSuccess() + return nil + case model.FieldLastCheckError: + m.ResetLastCheckError() + return nil + case model.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case model.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + } + return fmt.Errorf("unknown Model field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ModelMutation) AddedEdges() []string { + edges := make([]string, 0, 6) + if m.user != nil { + edges = append(edges, model.EdgeUser) + } + if m.teams != nil { + edges = append(edges, model.EdgeTeams) + } + if m.groups != nil { + edges = append(edges, model.EdgeGroups) + } + if m.vms != nil { + edges = append(edges, model.EdgeVms) + } + if m.team_models != nil { + edges = append(edges, model.EdgeTeamModels) + } + if m.team_group_models != nil { + edges = append(edges, model.EdgeTeamGroupModels) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ModelMutation) AddedIDs(name string) []ent.Value { + switch name { + case model.EdgeUser: + if id := m.user; id != nil { + return []ent.Value{*id} + } + case model.EdgeTeams: + ids := make([]ent.Value, 0, len(m.teams)) + for id := range m.teams { + ids = append(ids, id) + } + return ids + case model.EdgeGroups: + ids := make([]ent.Value, 0, len(m.groups)) + for id := range m.groups { + ids = append(ids, id) + } + return ids + case model.EdgeVms: + ids := make([]ent.Value, 0, len(m.vms)) + for id := range m.vms { + ids = append(ids, id) + } + return ids + case model.EdgeTeamModels: + ids := make([]ent.Value, 0, len(m.team_models)) + for id := range m.team_models { + ids = append(ids, id) + } + return ids + case model.EdgeTeamGroupModels: + ids := make([]ent.Value, 0, len(m.team_group_models)) + for id := range m.team_group_models { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *ModelMutation) RemovedEdges() []string { + edges := make([]string, 0, 6) + if m.removedteams != nil { + edges = append(edges, model.EdgeTeams) + } + if m.removedgroups != nil { + edges = append(edges, model.EdgeGroups) + } + if m.removedvms != nil { + edges = append(edges, model.EdgeVms) + } + if m.removedteam_models != nil { + edges = append(edges, model.EdgeTeamModels) + } + if m.removedteam_group_models != nil { + edges = append(edges, model.EdgeTeamGroupModels) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *ModelMutation) RemovedIDs(name string) []ent.Value { + switch name { + case model.EdgeTeams: + ids := make([]ent.Value, 0, len(m.removedteams)) + for id := range m.removedteams { + ids = append(ids, id) + } + return ids + case model.EdgeGroups: + ids := make([]ent.Value, 0, len(m.removedgroups)) + for id := range m.removedgroups { + ids = append(ids, id) + } + return ids + case model.EdgeVms: + ids := make([]ent.Value, 0, len(m.removedvms)) + for id := range m.removedvms { + ids = append(ids, id) + } + return ids + case model.EdgeTeamModels: + ids := make([]ent.Value, 0, len(m.removedteam_models)) + for id := range m.removedteam_models { + ids = append(ids, id) + } + return ids + case model.EdgeTeamGroupModels: + ids := make([]ent.Value, 0, len(m.removedteam_group_models)) + for id := range m.removedteam_group_models { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ModelMutation) ClearedEdges() []string { + edges := make([]string, 0, 6) + if m.cleareduser { + edges = append(edges, model.EdgeUser) + } + if m.clearedteams { + edges = append(edges, model.EdgeTeams) + } + if m.clearedgroups { + edges = append(edges, model.EdgeGroups) + } + if m.clearedvms { + edges = append(edges, model.EdgeVms) + } + if m.clearedteam_models { + edges = append(edges, model.EdgeTeamModels) + } + if m.clearedteam_group_models { + edges = append(edges, model.EdgeTeamGroupModels) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ModelMutation) EdgeCleared(name string) bool { + switch name { + case model.EdgeUser: + return m.cleareduser + case model.EdgeTeams: + return m.clearedteams + case model.EdgeGroups: + return m.clearedgroups + case model.EdgeVms: + return m.clearedvms + case model.EdgeTeamModels: + return m.clearedteam_models + case model.EdgeTeamGroupModels: + return m.clearedteam_group_models + } + 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 *ModelMutation) ClearEdge(name string) error { + switch name { + case model.EdgeUser: + m.ClearUser() + return nil + } + return fmt.Errorf("unknown Model 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 *ModelMutation) ResetEdge(name string) error { + switch name { + case model.EdgeUser: + m.ResetUser() + return nil + case model.EdgeTeams: + m.ResetTeams() + return nil + case model.EdgeGroups: + m.ResetGroups() + return nil + case model.EdgeVms: + m.ResetVms() + return nil + case model.EdgeTeamModels: + m.ResetTeamModels() + return nil + case model.EdgeTeamGroupModels: + m.ResetTeamGroupModels() + return nil + } + return fmt.Errorf("unknown Model edge %s", name) +} + +// TeamMutation represents an operation that mutates the Team nodes in the graph. +type TeamMutation struct { + config + op Op + typ string + id *uuid.UUID + deleted_at *time.Time + name *string + member_limit *int + addmember_limit *int + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + groups map[uuid.UUID]struct{} + removedgroups map[uuid.UUID]struct{} + clearedgroups bool + members map[uuid.UUID]struct{} + removedmembers map[uuid.UUID]struct{} + clearedmembers bool + models map[uuid.UUID]struct{} + removedmodels map[uuid.UUID]struct{} + clearedmodels bool + images map[uuid.UUID]struct{} + removedimages map[uuid.UUID]struct{} + clearedimages bool + team_members map[uuid.UUID]struct{} + removedteam_members map[uuid.UUID]struct{} + clearedteam_members bool + team_models map[uuid.UUID]struct{} + removedteam_models map[uuid.UUID]struct{} + clearedteam_models bool + team_images map[uuid.UUID]struct{} + removedteam_images map[uuid.UUID]struct{} + clearedteam_images bool + done bool + oldValue func(context.Context) (*Team, error) + predicates []predicate.Team +} + +var _ ent.Mutation = (*TeamMutation)(nil) + +// teamOption allows management of the mutation configuration using functional options. +type teamOption func(*TeamMutation) + +// newTeamMutation creates new mutation for the Team entity. +func newTeamMutation(c config, op Op, opts ...teamOption) *TeamMutation { + m := &TeamMutation{ + config: c, + op: op, + typ: TypeTeam, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withTeamID sets the ID field of the mutation. +func withTeamID(id uuid.UUID) teamOption { + return func(m *TeamMutation) { + var ( + err error + once sync.Once + value *Team + ) + m.oldValue = func(ctx context.Context) (*Team, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Team.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withTeam sets the old Team of the mutation. +func withTeam(node *Team) teamOption { + return func(m *TeamMutation) { + m.oldValue = func(context.Context) (*Team, 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 TeamMutation) 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 TeamMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("db: 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 Team entities. +func (m *TeamMutation) 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 *TeamMutation) 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 *TeamMutation) 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().Team.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *TeamMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *TeamMutation) DeletedAt() (r time.Time, exists bool) { + v := m.deleted_at + if v == nil { + return + } + return *v, true +} + +// OldDeletedAt returns the old "deleted_at" field's value of the Team entity. +// If the Team 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 *TeamMutation) OldDeletedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDeletedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDeletedAt: %w", err) + } + return oldValue.DeletedAt, nil +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (m *TeamMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[team.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *TeamMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[team.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *TeamMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, team.FieldDeletedAt) +} + +// SetName sets the "name" field. +func (m *TeamMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *TeamMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the Team entity. +// If the Team 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 *TeamMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *TeamMutation) ResetName() { + m.name = nil +} + +// SetMemberLimit sets the "member_limit" field. +func (m *TeamMutation) SetMemberLimit(i int) { + m.member_limit = &i + m.addmember_limit = nil +} + +// MemberLimit returns the value of the "member_limit" field in the mutation. +func (m *TeamMutation) MemberLimit() (r int, exists bool) { + v := m.member_limit + if v == nil { + return + } + return *v, true +} + +// OldMemberLimit returns the old "member_limit" field's value of the Team entity. +// If the Team 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 *TeamMutation) OldMemberLimit(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMemberLimit is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMemberLimit requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMemberLimit: %w", err) + } + return oldValue.MemberLimit, nil +} + +// AddMemberLimit adds i to the "member_limit" field. +func (m *TeamMutation) AddMemberLimit(i int) { + if m.addmember_limit != nil { + *m.addmember_limit += i + } else { + m.addmember_limit = &i + } +} + +// AddedMemberLimit returns the value that was added to the "member_limit" field in this mutation. +func (m *TeamMutation) AddedMemberLimit() (r int, exists bool) { + v := m.addmember_limit + if v == nil { + return + } + return *v, true +} + +// ResetMemberLimit resets all changes to the "member_limit" field. +func (m *TeamMutation) ResetMemberLimit() { + m.member_limit = nil + m.addmember_limit = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *TeamMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *TeamMutation) 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 Team entity. +// If the Team 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 *TeamMutation) 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 *TeamMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *TeamMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *TeamMutation) 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 Team entity. +// If the Team 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 *TeamMutation) 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 *TeamMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// AddGroupIDs adds the "groups" edge to the TeamGroup entity by ids. +func (m *TeamMutation) AddGroupIDs(ids ...uuid.UUID) { + if m.groups == nil { + m.groups = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.groups[ids[i]] = struct{}{} + } +} + +// ClearGroups clears the "groups" edge to the TeamGroup entity. +func (m *TeamMutation) ClearGroups() { + m.clearedgroups = true +} + +// GroupsCleared reports if the "groups" edge to the TeamGroup entity was cleared. +func (m *TeamMutation) GroupsCleared() bool { + return m.clearedgroups +} + +// RemoveGroupIDs removes the "groups" edge to the TeamGroup entity by IDs. +func (m *TeamMutation) RemoveGroupIDs(ids ...uuid.UUID) { + if m.removedgroups == nil { + m.removedgroups = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.groups, ids[i]) + m.removedgroups[ids[i]] = struct{}{} + } +} + +// RemovedGroups returns the removed IDs of the "groups" edge to the TeamGroup entity. +func (m *TeamMutation) RemovedGroupsIDs() (ids []uuid.UUID) { + for id := range m.removedgroups { + ids = append(ids, id) + } + return +} + +// GroupsIDs returns the "groups" edge IDs in the mutation. +func (m *TeamMutation) GroupsIDs() (ids []uuid.UUID) { + for id := range m.groups { + ids = append(ids, id) + } + return +} + +// ResetGroups resets all changes to the "groups" edge. +func (m *TeamMutation) ResetGroups() { + m.groups = nil + m.clearedgroups = false + m.removedgroups = nil +} + +// AddMemberIDs adds the "members" edge to the User entity by ids. +func (m *TeamMutation) AddMemberIDs(ids ...uuid.UUID) { + if m.members == nil { + m.members = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.members[ids[i]] = struct{}{} + } +} + +// ClearMembers clears the "members" edge to the User entity. +func (m *TeamMutation) ClearMembers() { + m.clearedmembers = true +} + +// MembersCleared reports if the "members" edge to the User entity was cleared. +func (m *TeamMutation) MembersCleared() bool { + return m.clearedmembers +} + +// RemoveMemberIDs removes the "members" edge to the User entity by IDs. +func (m *TeamMutation) RemoveMemberIDs(ids ...uuid.UUID) { + if m.removedmembers == nil { + m.removedmembers = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.members, ids[i]) + m.removedmembers[ids[i]] = struct{}{} + } +} + +// RemovedMembers returns the removed IDs of the "members" edge to the User entity. +func (m *TeamMutation) RemovedMembersIDs() (ids []uuid.UUID) { + for id := range m.removedmembers { + ids = append(ids, id) + } + return +} + +// MembersIDs returns the "members" edge IDs in the mutation. +func (m *TeamMutation) MembersIDs() (ids []uuid.UUID) { + for id := range m.members { + ids = append(ids, id) + } + return +} + +// ResetMembers resets all changes to the "members" edge. +func (m *TeamMutation) ResetMembers() { + m.members = nil + m.clearedmembers = false + m.removedmembers = nil +} + +// AddModelIDs adds the "models" edge to the Model entity by ids. +func (m *TeamMutation) AddModelIDs(ids ...uuid.UUID) { + if m.models == nil { + m.models = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.models[ids[i]] = struct{}{} + } +} + +// ClearModels clears the "models" edge to the Model entity. +func (m *TeamMutation) ClearModels() { + m.clearedmodels = true +} + +// ModelsCleared reports if the "models" edge to the Model entity was cleared. +func (m *TeamMutation) ModelsCleared() bool { + return m.clearedmodels +} + +// RemoveModelIDs removes the "models" edge to the Model entity by IDs. +func (m *TeamMutation) RemoveModelIDs(ids ...uuid.UUID) { + if m.removedmodels == nil { + m.removedmodels = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.models, ids[i]) + m.removedmodels[ids[i]] = struct{}{} + } +} + +// RemovedModels returns the removed IDs of the "models" edge to the Model entity. +func (m *TeamMutation) RemovedModelsIDs() (ids []uuid.UUID) { + for id := range m.removedmodels { + ids = append(ids, id) + } + return +} + +// ModelsIDs returns the "models" edge IDs in the mutation. +func (m *TeamMutation) ModelsIDs() (ids []uuid.UUID) { + for id := range m.models { + ids = append(ids, id) + } + return +} + +// ResetModels resets all changes to the "models" edge. +func (m *TeamMutation) ResetModels() { + m.models = nil + m.clearedmodels = false + m.removedmodels = nil +} + +// AddImageIDs adds the "images" edge to the Image entity by ids. +func (m *TeamMutation) AddImageIDs(ids ...uuid.UUID) { + if m.images == nil { + m.images = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.images[ids[i]] = struct{}{} + } +} + +// ClearImages clears the "images" edge to the Image entity. +func (m *TeamMutation) ClearImages() { + m.clearedimages = true +} + +// ImagesCleared reports if the "images" edge to the Image entity was cleared. +func (m *TeamMutation) ImagesCleared() bool { + return m.clearedimages +} + +// RemoveImageIDs removes the "images" edge to the Image entity by IDs. +func (m *TeamMutation) RemoveImageIDs(ids ...uuid.UUID) { + if m.removedimages == nil { + m.removedimages = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.images, ids[i]) + m.removedimages[ids[i]] = struct{}{} + } +} + +// RemovedImages returns the removed IDs of the "images" edge to the Image entity. +func (m *TeamMutation) RemovedImagesIDs() (ids []uuid.UUID) { + for id := range m.removedimages { + ids = append(ids, id) + } + return +} + +// ImagesIDs returns the "images" edge IDs in the mutation. +func (m *TeamMutation) ImagesIDs() (ids []uuid.UUID) { + for id := range m.images { + ids = append(ids, id) + } + return +} + +// ResetImages resets all changes to the "images" edge. +func (m *TeamMutation) ResetImages() { + m.images = nil + m.clearedimages = false + m.removedimages = nil +} + +// AddTeamMemberIDs adds the "team_members" edge to the TeamMember entity by ids. +func (m *TeamMutation) AddTeamMemberIDs(ids ...uuid.UUID) { + if m.team_members == nil { + m.team_members = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.team_members[ids[i]] = struct{}{} + } +} + +// ClearTeamMembers clears the "team_members" edge to the TeamMember entity. +func (m *TeamMutation) ClearTeamMembers() { + m.clearedteam_members = true +} + +// TeamMembersCleared reports if the "team_members" edge to the TeamMember entity was cleared. +func (m *TeamMutation) TeamMembersCleared() bool { + return m.clearedteam_members +} + +// RemoveTeamMemberIDs removes the "team_members" edge to the TeamMember entity by IDs. +func (m *TeamMutation) RemoveTeamMemberIDs(ids ...uuid.UUID) { + if m.removedteam_members == nil { + m.removedteam_members = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.team_members, ids[i]) + m.removedteam_members[ids[i]] = struct{}{} + } +} + +// RemovedTeamMembers returns the removed IDs of the "team_members" edge to the TeamMember entity. +func (m *TeamMutation) RemovedTeamMembersIDs() (ids []uuid.UUID) { + for id := range m.removedteam_members { + ids = append(ids, id) + } + return +} + +// TeamMembersIDs returns the "team_members" edge IDs in the mutation. +func (m *TeamMutation) TeamMembersIDs() (ids []uuid.UUID) { + for id := range m.team_members { + ids = append(ids, id) + } + return +} + +// ResetTeamMembers resets all changes to the "team_members" edge. +func (m *TeamMutation) ResetTeamMembers() { + m.team_members = nil + m.clearedteam_members = false + m.removedteam_members = nil +} + +// AddTeamModelIDs adds the "team_models" edge to the TeamModel entity by ids. +func (m *TeamMutation) AddTeamModelIDs(ids ...uuid.UUID) { + if m.team_models == nil { + m.team_models = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.team_models[ids[i]] = struct{}{} + } +} + +// ClearTeamModels clears the "team_models" edge to the TeamModel entity. +func (m *TeamMutation) ClearTeamModels() { + m.clearedteam_models = true +} + +// TeamModelsCleared reports if the "team_models" edge to the TeamModel entity was cleared. +func (m *TeamMutation) TeamModelsCleared() bool { + return m.clearedteam_models +} + +// RemoveTeamModelIDs removes the "team_models" edge to the TeamModel entity by IDs. +func (m *TeamMutation) RemoveTeamModelIDs(ids ...uuid.UUID) { + if m.removedteam_models == nil { + m.removedteam_models = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.team_models, ids[i]) + m.removedteam_models[ids[i]] = struct{}{} + } +} + +// RemovedTeamModels returns the removed IDs of the "team_models" edge to the TeamModel entity. +func (m *TeamMutation) RemovedTeamModelsIDs() (ids []uuid.UUID) { + for id := range m.removedteam_models { + ids = append(ids, id) + } + return +} + +// TeamModelsIDs returns the "team_models" edge IDs in the mutation. +func (m *TeamMutation) TeamModelsIDs() (ids []uuid.UUID) { + for id := range m.team_models { + ids = append(ids, id) + } + return +} + +// ResetTeamModels resets all changes to the "team_models" edge. +func (m *TeamMutation) ResetTeamModels() { + m.team_models = nil + m.clearedteam_models = false + m.removedteam_models = nil +} + +// AddTeamImageIDs adds the "team_images" edge to the TeamImage entity by ids. +func (m *TeamMutation) AddTeamImageIDs(ids ...uuid.UUID) { + if m.team_images == nil { + m.team_images = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.team_images[ids[i]] = struct{}{} + } +} + +// ClearTeamImages clears the "team_images" edge to the TeamImage entity. +func (m *TeamMutation) ClearTeamImages() { + m.clearedteam_images = true +} + +// TeamImagesCleared reports if the "team_images" edge to the TeamImage entity was cleared. +func (m *TeamMutation) TeamImagesCleared() bool { + return m.clearedteam_images +} + +// RemoveTeamImageIDs removes the "team_images" edge to the TeamImage entity by IDs. +func (m *TeamMutation) RemoveTeamImageIDs(ids ...uuid.UUID) { + if m.removedteam_images == nil { + m.removedteam_images = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.team_images, ids[i]) + m.removedteam_images[ids[i]] = struct{}{} + } +} + +// RemovedTeamImages returns the removed IDs of the "team_images" edge to the TeamImage entity. +func (m *TeamMutation) RemovedTeamImagesIDs() (ids []uuid.UUID) { + for id := range m.removedteam_images { + ids = append(ids, id) + } + return +} + +// TeamImagesIDs returns the "team_images" edge IDs in the mutation. +func (m *TeamMutation) TeamImagesIDs() (ids []uuid.UUID) { + for id := range m.team_images { + ids = append(ids, id) + } + return +} + +// ResetTeamImages resets all changes to the "team_images" edge. +func (m *TeamMutation) ResetTeamImages() { + m.team_images = nil + m.clearedteam_images = false + m.removedteam_images = nil +} + +// Where appends a list predicates to the TeamMutation builder. +func (m *TeamMutation) Where(ps ...predicate.Team) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the TeamMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *TeamMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Team, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *TeamMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *TeamMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Team). +func (m *TeamMutation) 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 *TeamMutation) Fields() []string { + fields := make([]string, 0, 5) + if m.deleted_at != nil { + fields = append(fields, team.FieldDeletedAt) + } + if m.name != nil { + fields = append(fields, team.FieldName) + } + if m.member_limit != nil { + fields = append(fields, team.FieldMemberLimit) + } + if m.created_at != nil { + fields = append(fields, team.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, team.FieldUpdatedAt) + } + 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 *TeamMutation) Field(name string) (ent.Value, bool) { + switch name { + case team.FieldDeletedAt: + return m.DeletedAt() + case team.FieldName: + return m.Name() + case team.FieldMemberLimit: + return m.MemberLimit() + case team.FieldCreatedAt: + return m.CreatedAt() + case team.FieldUpdatedAt: + return m.UpdatedAt() + } + 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 *TeamMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case team.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case team.FieldName: + return m.OldName(ctx) + case team.FieldMemberLimit: + return m.OldMemberLimit(ctx) + case team.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case team.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + } + return nil, fmt.Errorf("unknown Team 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 *TeamMutation) SetField(name string, value ent.Value) error { + switch name { + case team.FieldDeletedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeletedAt(v) + return nil + case team.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case team.FieldMemberLimit: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMemberLimit(v) + return nil + case team.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 team.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + } + return fmt.Errorf("unknown Team field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *TeamMutation) AddedFields() []string { + var fields []string + if m.addmember_limit != nil { + fields = append(fields, team.FieldMemberLimit) + } + 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 *TeamMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case team.FieldMemberLimit: + return m.AddedMemberLimit() + } + 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 *TeamMutation) AddField(name string, value ent.Value) error { + switch name { + case team.FieldMemberLimit: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddMemberLimit(v) + return nil + } + return fmt.Errorf("unknown Team numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *TeamMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(team.FieldDeletedAt) { + fields = append(fields, team.FieldDeletedAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *TeamMutation) 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 *TeamMutation) ClearField(name string) error { + switch name { + case team.FieldDeletedAt: + m.ClearDeletedAt() + return nil + } + return fmt.Errorf("unknown Team 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 *TeamMutation) ResetField(name string) error { + switch name { + case team.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case team.FieldName: + m.ResetName() + return nil + case team.FieldMemberLimit: + m.ResetMemberLimit() + return nil + case team.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case team.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + } + return fmt.Errorf("unknown Team field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *TeamMutation) AddedEdges() []string { + edges := make([]string, 0, 7) + if m.groups != nil { + edges = append(edges, team.EdgeGroups) + } + if m.members != nil { + edges = append(edges, team.EdgeMembers) + } + if m.models != nil { + edges = append(edges, team.EdgeModels) + } + if m.images != nil { + edges = append(edges, team.EdgeImages) + } + if m.team_members != nil { + edges = append(edges, team.EdgeTeamMembers) + } + if m.team_models != nil { + edges = append(edges, team.EdgeTeamModels) + } + if m.team_images != nil { + edges = append(edges, team.EdgeTeamImages) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *TeamMutation) AddedIDs(name string) []ent.Value { + switch name { + case team.EdgeGroups: + ids := make([]ent.Value, 0, len(m.groups)) + for id := range m.groups { + ids = append(ids, id) + } + return ids + case team.EdgeMembers: + ids := make([]ent.Value, 0, len(m.members)) + for id := range m.members { + ids = append(ids, id) + } + return ids + case team.EdgeModels: + ids := make([]ent.Value, 0, len(m.models)) + for id := range m.models { + ids = append(ids, id) + } + return ids + case team.EdgeImages: + ids := make([]ent.Value, 0, len(m.images)) + for id := range m.images { + ids = append(ids, id) + } + return ids + case team.EdgeTeamMembers: + ids := make([]ent.Value, 0, len(m.team_members)) + for id := range m.team_members { + ids = append(ids, id) + } + return ids + case team.EdgeTeamModels: + ids := make([]ent.Value, 0, len(m.team_models)) + for id := range m.team_models { + ids = append(ids, id) + } + return ids + case team.EdgeTeamImages: + ids := make([]ent.Value, 0, len(m.team_images)) + for id := range m.team_images { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *TeamMutation) RemovedEdges() []string { + edges := make([]string, 0, 7) + if m.removedgroups != nil { + edges = append(edges, team.EdgeGroups) + } + if m.removedmembers != nil { + edges = append(edges, team.EdgeMembers) + } + if m.removedmodels != nil { + edges = append(edges, team.EdgeModels) + } + if m.removedimages != nil { + edges = append(edges, team.EdgeImages) + } + if m.removedteam_members != nil { + edges = append(edges, team.EdgeTeamMembers) + } + if m.removedteam_models != nil { + edges = append(edges, team.EdgeTeamModels) + } + if m.removedteam_images != nil { + edges = append(edges, team.EdgeTeamImages) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *TeamMutation) RemovedIDs(name string) []ent.Value { + switch name { + case team.EdgeGroups: + ids := make([]ent.Value, 0, len(m.removedgroups)) + for id := range m.removedgroups { + ids = append(ids, id) + } + return ids + case team.EdgeMembers: + ids := make([]ent.Value, 0, len(m.removedmembers)) + for id := range m.removedmembers { + ids = append(ids, id) + } + return ids + case team.EdgeModels: + ids := make([]ent.Value, 0, len(m.removedmodels)) + for id := range m.removedmodels { + ids = append(ids, id) + } + return ids + case team.EdgeImages: + ids := make([]ent.Value, 0, len(m.removedimages)) + for id := range m.removedimages { + ids = append(ids, id) + } + return ids + case team.EdgeTeamMembers: + ids := make([]ent.Value, 0, len(m.removedteam_members)) + for id := range m.removedteam_members { + ids = append(ids, id) + } + return ids + case team.EdgeTeamModels: + ids := make([]ent.Value, 0, len(m.removedteam_models)) + for id := range m.removedteam_models { + ids = append(ids, id) + } + return ids + case team.EdgeTeamImages: + ids := make([]ent.Value, 0, len(m.removedteam_images)) + for id := range m.removedteam_images { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *TeamMutation) ClearedEdges() []string { + edges := make([]string, 0, 7) + if m.clearedgroups { + edges = append(edges, team.EdgeGroups) + } + if m.clearedmembers { + edges = append(edges, team.EdgeMembers) + } + if m.clearedmodels { + edges = append(edges, team.EdgeModels) + } + if m.clearedimages { + edges = append(edges, team.EdgeImages) + } + if m.clearedteam_members { + edges = append(edges, team.EdgeTeamMembers) + } + if m.clearedteam_models { + edges = append(edges, team.EdgeTeamModels) + } + if m.clearedteam_images { + edges = append(edges, team.EdgeTeamImages) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *TeamMutation) EdgeCleared(name string) bool { + switch name { + case team.EdgeGroups: + return m.clearedgroups + case team.EdgeMembers: + return m.clearedmembers + case team.EdgeModels: + return m.clearedmodels + case team.EdgeImages: + return m.clearedimages + case team.EdgeTeamMembers: + return m.clearedteam_members + case team.EdgeTeamModels: + return m.clearedteam_models + case team.EdgeTeamImages: + return m.clearedteam_images + } + 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 *TeamMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown Team 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 *TeamMutation) ResetEdge(name string) error { + switch name { + case team.EdgeGroups: + m.ResetGroups() + return nil + case team.EdgeMembers: + m.ResetMembers() + return nil + case team.EdgeModels: + m.ResetModels() + return nil + case team.EdgeImages: + m.ResetImages() + return nil + case team.EdgeTeamMembers: + m.ResetTeamMembers() + return nil + case team.EdgeTeamModels: + m.ResetTeamModels() + return nil + case team.EdgeTeamImages: + m.ResetTeamImages() + return nil + } + return fmt.Errorf("unknown Team edge %s", name) +} + +// TeamGroupMutation represents an operation that mutates the TeamGroup nodes in the graph. +type TeamGroupMutation struct { + config + op Op + typ string + id *uuid.UUID + deleted_at *time.Time + name *string + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + members map[uuid.UUID]struct{} + removedmembers map[uuid.UUID]struct{} + clearedmembers bool + team *uuid.UUID + clearedteam bool + models map[uuid.UUID]struct{} + removedmodels map[uuid.UUID]struct{} + clearedmodels bool + images map[uuid.UUID]struct{} + removedimages map[uuid.UUID]struct{} + clearedimages bool + hosts map[string]struct{} + removedhosts map[string]struct{} + clearedhosts bool + team_group_members map[uuid.UUID]struct{} + removedteam_group_members map[uuid.UUID]struct{} + clearedteam_group_members bool + team_group_models map[uuid.UUID]struct{} + removedteam_group_models map[uuid.UUID]struct{} + clearedteam_group_models bool + team_group_images map[uuid.UUID]struct{} + removedteam_group_images map[uuid.UUID]struct{} + clearedteam_group_images bool + team_group_hosts map[uuid.UUID]struct{} + removedteam_group_hosts map[uuid.UUID]struct{} + clearedteam_group_hosts bool + done bool + oldValue func(context.Context) (*TeamGroup, error) + predicates []predicate.TeamGroup +} + +var _ ent.Mutation = (*TeamGroupMutation)(nil) + +// teamgroupOption allows management of the mutation configuration using functional options. +type teamgroupOption func(*TeamGroupMutation) + +// newTeamGroupMutation creates new mutation for the TeamGroup entity. +func newTeamGroupMutation(c config, op Op, opts ...teamgroupOption) *TeamGroupMutation { + m := &TeamGroupMutation{ + config: c, + op: op, + typ: TypeTeamGroup, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withTeamGroupID sets the ID field of the mutation. +func withTeamGroupID(id uuid.UUID) teamgroupOption { + return func(m *TeamGroupMutation) { + var ( + err error + once sync.Once + value *TeamGroup + ) + m.oldValue = func(ctx context.Context) (*TeamGroup, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().TeamGroup.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withTeamGroup sets the old TeamGroup of the mutation. +func withTeamGroup(node *TeamGroup) teamgroupOption { + return func(m *TeamGroupMutation) { + m.oldValue = func(context.Context) (*TeamGroup, 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 TeamGroupMutation) 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 TeamGroupMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("db: 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 TeamGroup entities. +func (m *TeamGroupMutation) 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 *TeamGroupMutation) 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 *TeamGroupMutation) 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().TeamGroup.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetDeletedAt sets the "deleted_at" field. +func (m *TeamGroupMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t +} + +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *TeamGroupMutation) DeletedAt() (r time.Time, exists bool) { + v := m.deleted_at + if v == nil { + return + } + return *v, true +} + +// OldDeletedAt returns the old "deleted_at" field's value of the TeamGroup entity. +// If the TeamGroup 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 *TeamGroupMutation) OldDeletedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDeletedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDeletedAt: %w", err) + } + return oldValue.DeletedAt, nil +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (m *TeamGroupMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[teamgroup.FieldDeletedAt] = struct{}{} +} + +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *TeamGroupMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[teamgroup.FieldDeletedAt] + return ok +} + +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *TeamGroupMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, teamgroup.FieldDeletedAt) +} + +// SetTeamID sets the "team_id" field. +func (m *TeamGroupMutation) SetTeamID(u uuid.UUID) { + m.team = &u +} + +// TeamID returns the value of the "team_id" field in the mutation. +func (m *TeamGroupMutation) TeamID() (r uuid.UUID, exists bool) { + v := m.team + if v == nil { + return + } + return *v, true +} + +// OldTeamID returns the old "team_id" field's value of the TeamGroup entity. +// If the TeamGroup 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 *TeamGroupMutation) OldTeamID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTeamID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTeamID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTeamID: %w", err) + } + return oldValue.TeamID, nil +} + +// ResetTeamID resets all changes to the "team_id" field. +func (m *TeamGroupMutation) ResetTeamID() { + m.team = nil +} + +// SetName sets the "name" field. +func (m *TeamGroupMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *TeamGroupMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the TeamGroup entity. +// If the TeamGroup 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 *TeamGroupMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *TeamGroupMutation) ResetName() { + m.name = nil +} + +// SetCreatedAt sets the "created_at" field. +func (m *TeamGroupMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *TeamGroupMutation) 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 TeamGroup entity. +// If the TeamGroup 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 *TeamGroupMutation) 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 *TeamGroupMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *TeamGroupMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *TeamGroupMutation) 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 TeamGroup entity. +// If the TeamGroup 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 *TeamGroupMutation) 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 *TeamGroupMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// AddMemberIDs adds the "members" edge to the User entity by ids. +func (m *TeamGroupMutation) AddMemberIDs(ids ...uuid.UUID) { + if m.members == nil { + m.members = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.members[ids[i]] = struct{}{} + } +} + +// ClearMembers clears the "members" edge to the User entity. +func (m *TeamGroupMutation) ClearMembers() { + m.clearedmembers = true +} + +// MembersCleared reports if the "members" edge to the User entity was cleared. +func (m *TeamGroupMutation) MembersCleared() bool { + return m.clearedmembers +} + +// RemoveMemberIDs removes the "members" edge to the User entity by IDs. +func (m *TeamGroupMutation) RemoveMemberIDs(ids ...uuid.UUID) { + if m.removedmembers == nil { + m.removedmembers = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.members, ids[i]) + m.removedmembers[ids[i]] = struct{}{} + } +} + +// RemovedMembers returns the removed IDs of the "members" edge to the User entity. +func (m *TeamGroupMutation) RemovedMembersIDs() (ids []uuid.UUID) { + for id := range m.removedmembers { + ids = append(ids, id) + } + return +} + +// MembersIDs returns the "members" edge IDs in the mutation. +func (m *TeamGroupMutation) MembersIDs() (ids []uuid.UUID) { + for id := range m.members { + ids = append(ids, id) + } + return +} + +// ResetMembers resets all changes to the "members" edge. +func (m *TeamGroupMutation) ResetMembers() { + m.members = nil + m.clearedmembers = false + m.removedmembers = nil +} + +// ClearTeam clears the "team" edge to the Team entity. +func (m *TeamGroupMutation) ClearTeam() { + m.clearedteam = true + m.clearedFields[teamgroup.FieldTeamID] = struct{}{} +} + +// TeamCleared reports if the "team" edge to the Team entity was cleared. +func (m *TeamGroupMutation) TeamCleared() bool { + return m.clearedteam +} + +// TeamIDs returns the "team" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// TeamID instead. It exists only for internal usage by the builders. +func (m *TeamGroupMutation) TeamIDs() (ids []uuid.UUID) { + if id := m.team; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetTeam resets all changes to the "team" edge. +func (m *TeamGroupMutation) ResetTeam() { + m.team = nil + m.clearedteam = false +} + +// AddModelIDs adds the "models" edge to the Model entity by ids. +func (m *TeamGroupMutation) AddModelIDs(ids ...uuid.UUID) { + if m.models == nil { + m.models = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.models[ids[i]] = struct{}{} + } +} + +// ClearModels clears the "models" edge to the Model entity. +func (m *TeamGroupMutation) ClearModels() { + m.clearedmodels = true +} + +// ModelsCleared reports if the "models" edge to the Model entity was cleared. +func (m *TeamGroupMutation) ModelsCleared() bool { + return m.clearedmodels +} + +// RemoveModelIDs removes the "models" edge to the Model entity by IDs. +func (m *TeamGroupMutation) RemoveModelIDs(ids ...uuid.UUID) { + if m.removedmodels == nil { + m.removedmodels = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.models, ids[i]) + m.removedmodels[ids[i]] = struct{}{} + } +} + +// RemovedModels returns the removed IDs of the "models" edge to the Model entity. +func (m *TeamGroupMutation) RemovedModelsIDs() (ids []uuid.UUID) { + for id := range m.removedmodels { + ids = append(ids, id) + } + return +} + +// ModelsIDs returns the "models" edge IDs in the mutation. +func (m *TeamGroupMutation) ModelsIDs() (ids []uuid.UUID) { + for id := range m.models { + ids = append(ids, id) + } + return +} + +// ResetModels resets all changes to the "models" edge. +func (m *TeamGroupMutation) ResetModels() { + m.models = nil + m.clearedmodels = false + m.removedmodels = nil +} + +// AddImageIDs adds the "images" edge to the Image entity by ids. +func (m *TeamGroupMutation) AddImageIDs(ids ...uuid.UUID) { + if m.images == nil { + m.images = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.images[ids[i]] = struct{}{} + } +} + +// ClearImages clears the "images" edge to the Image entity. +func (m *TeamGroupMutation) ClearImages() { + m.clearedimages = true +} + +// ImagesCleared reports if the "images" edge to the Image entity was cleared. +func (m *TeamGroupMutation) ImagesCleared() bool { + return m.clearedimages +} + +// RemoveImageIDs removes the "images" edge to the Image entity by IDs. +func (m *TeamGroupMutation) RemoveImageIDs(ids ...uuid.UUID) { + if m.removedimages == nil { + m.removedimages = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.images, ids[i]) + m.removedimages[ids[i]] = struct{}{} + } +} + +// RemovedImages returns the removed IDs of the "images" edge to the Image entity. +func (m *TeamGroupMutation) RemovedImagesIDs() (ids []uuid.UUID) { + for id := range m.removedimages { + ids = append(ids, id) + } + return +} + +// ImagesIDs returns the "images" edge IDs in the mutation. +func (m *TeamGroupMutation) ImagesIDs() (ids []uuid.UUID) { + for id := range m.images { + ids = append(ids, id) + } + return +} + +// ResetImages resets all changes to the "images" edge. +func (m *TeamGroupMutation) ResetImages() { + m.images = nil + m.clearedimages = false + m.removedimages = nil +} + +// AddHostIDs adds the "hosts" edge to the Host entity by ids. +func (m *TeamGroupMutation) AddHostIDs(ids ...string) { + if m.hosts == nil { + m.hosts = make(map[string]struct{}) + } + for i := range ids { + m.hosts[ids[i]] = struct{}{} + } +} + +// ClearHosts clears the "hosts" edge to the Host entity. +func (m *TeamGroupMutation) ClearHosts() { + m.clearedhosts = true +} + +// HostsCleared reports if the "hosts" edge to the Host entity was cleared. +func (m *TeamGroupMutation) HostsCleared() bool { + return m.clearedhosts +} + +// RemoveHostIDs removes the "hosts" edge to the Host entity by IDs. +func (m *TeamGroupMutation) RemoveHostIDs(ids ...string) { + if m.removedhosts == nil { + m.removedhosts = make(map[string]struct{}) + } + for i := range ids { + delete(m.hosts, ids[i]) + m.removedhosts[ids[i]] = struct{}{} + } +} + +// RemovedHosts returns the removed IDs of the "hosts" edge to the Host entity. +func (m *TeamGroupMutation) RemovedHostsIDs() (ids []string) { + for id := range m.removedhosts { + ids = append(ids, id) + } + return +} + +// HostsIDs returns the "hosts" edge IDs in the mutation. +func (m *TeamGroupMutation) HostsIDs() (ids []string) { + for id := range m.hosts { + ids = append(ids, id) + } + return +} + +// ResetHosts resets all changes to the "hosts" edge. +func (m *TeamGroupMutation) ResetHosts() { + m.hosts = nil + m.clearedhosts = false + m.removedhosts = nil +} + +// AddTeamGroupMemberIDs adds the "team_group_members" edge to the TeamGroupMember entity by ids. +func (m *TeamGroupMutation) AddTeamGroupMemberIDs(ids ...uuid.UUID) { + if m.team_group_members == nil { + m.team_group_members = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.team_group_members[ids[i]] = struct{}{} + } +} + +// ClearTeamGroupMembers clears the "team_group_members" edge to the TeamGroupMember entity. +func (m *TeamGroupMutation) ClearTeamGroupMembers() { + m.clearedteam_group_members = true +} + +// TeamGroupMembersCleared reports if the "team_group_members" edge to the TeamGroupMember entity was cleared. +func (m *TeamGroupMutation) TeamGroupMembersCleared() bool { + return m.clearedteam_group_members +} + +// RemoveTeamGroupMemberIDs removes the "team_group_members" edge to the TeamGroupMember entity by IDs. +func (m *TeamGroupMutation) RemoveTeamGroupMemberIDs(ids ...uuid.UUID) { + if m.removedteam_group_members == nil { + m.removedteam_group_members = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.team_group_members, ids[i]) + m.removedteam_group_members[ids[i]] = struct{}{} + } +} + +// RemovedTeamGroupMembers returns the removed IDs of the "team_group_members" edge to the TeamGroupMember entity. +func (m *TeamGroupMutation) RemovedTeamGroupMembersIDs() (ids []uuid.UUID) { + for id := range m.removedteam_group_members { + ids = append(ids, id) + } + return +} + +// TeamGroupMembersIDs returns the "team_group_members" edge IDs in the mutation. +func (m *TeamGroupMutation) TeamGroupMembersIDs() (ids []uuid.UUID) { + for id := range m.team_group_members { + ids = append(ids, id) + } + return +} + +// ResetTeamGroupMembers resets all changes to the "team_group_members" edge. +func (m *TeamGroupMutation) ResetTeamGroupMembers() { + m.team_group_members = nil + m.clearedteam_group_members = false + m.removedteam_group_members = nil +} + +// AddTeamGroupModelIDs adds the "team_group_models" edge to the TeamGroupModel entity by ids. +func (m *TeamGroupMutation) AddTeamGroupModelIDs(ids ...uuid.UUID) { + if m.team_group_models == nil { + m.team_group_models = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.team_group_models[ids[i]] = struct{}{} + } +} + +// ClearTeamGroupModels clears the "team_group_models" edge to the TeamGroupModel entity. +func (m *TeamGroupMutation) ClearTeamGroupModels() { + m.clearedteam_group_models = true +} + +// TeamGroupModelsCleared reports if the "team_group_models" edge to the TeamGroupModel entity was cleared. +func (m *TeamGroupMutation) TeamGroupModelsCleared() bool { + return m.clearedteam_group_models +} + +// RemoveTeamGroupModelIDs removes the "team_group_models" edge to the TeamGroupModel entity by IDs. +func (m *TeamGroupMutation) RemoveTeamGroupModelIDs(ids ...uuid.UUID) { + if m.removedteam_group_models == nil { + m.removedteam_group_models = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.team_group_models, ids[i]) + m.removedteam_group_models[ids[i]] = struct{}{} + } +} + +// RemovedTeamGroupModels returns the removed IDs of the "team_group_models" edge to the TeamGroupModel entity. +func (m *TeamGroupMutation) RemovedTeamGroupModelsIDs() (ids []uuid.UUID) { + for id := range m.removedteam_group_models { + ids = append(ids, id) + } + return +} + +// TeamGroupModelsIDs returns the "team_group_models" edge IDs in the mutation. +func (m *TeamGroupMutation) TeamGroupModelsIDs() (ids []uuid.UUID) { + for id := range m.team_group_models { + ids = append(ids, id) + } + return +} + +// ResetTeamGroupModels resets all changes to the "team_group_models" edge. +func (m *TeamGroupMutation) ResetTeamGroupModels() { + m.team_group_models = nil + m.clearedteam_group_models = false + m.removedteam_group_models = nil +} + +// AddTeamGroupImageIDs adds the "team_group_images" edge to the TeamGroupImage entity by ids. +func (m *TeamGroupMutation) AddTeamGroupImageIDs(ids ...uuid.UUID) { + if m.team_group_images == nil { + m.team_group_images = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.team_group_images[ids[i]] = struct{}{} + } +} + +// ClearTeamGroupImages clears the "team_group_images" edge to the TeamGroupImage entity. +func (m *TeamGroupMutation) ClearTeamGroupImages() { + m.clearedteam_group_images = true +} + +// TeamGroupImagesCleared reports if the "team_group_images" edge to the TeamGroupImage entity was cleared. +func (m *TeamGroupMutation) TeamGroupImagesCleared() bool { + return m.clearedteam_group_images +} + +// RemoveTeamGroupImageIDs removes the "team_group_images" edge to the TeamGroupImage entity by IDs. +func (m *TeamGroupMutation) RemoveTeamGroupImageIDs(ids ...uuid.UUID) { + if m.removedteam_group_images == nil { + m.removedteam_group_images = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.team_group_images, ids[i]) + m.removedteam_group_images[ids[i]] = struct{}{} + } +} + +// RemovedTeamGroupImages returns the removed IDs of the "team_group_images" edge to the TeamGroupImage entity. +func (m *TeamGroupMutation) RemovedTeamGroupImagesIDs() (ids []uuid.UUID) { + for id := range m.removedteam_group_images { + ids = append(ids, id) + } + return +} + +// TeamGroupImagesIDs returns the "team_group_images" edge IDs in the mutation. +func (m *TeamGroupMutation) TeamGroupImagesIDs() (ids []uuid.UUID) { + for id := range m.team_group_images { + ids = append(ids, id) + } + return +} + +// ResetTeamGroupImages resets all changes to the "team_group_images" edge. +func (m *TeamGroupMutation) ResetTeamGroupImages() { + m.team_group_images = nil + m.clearedteam_group_images = false + m.removedteam_group_images = nil +} + +// AddTeamGroupHostIDs adds the "team_group_hosts" edge to the TeamGroupHost entity by ids. +func (m *TeamGroupMutation) AddTeamGroupHostIDs(ids ...uuid.UUID) { + if m.team_group_hosts == nil { + m.team_group_hosts = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.team_group_hosts[ids[i]] = struct{}{} + } +} + +// ClearTeamGroupHosts clears the "team_group_hosts" edge to the TeamGroupHost entity. +func (m *TeamGroupMutation) ClearTeamGroupHosts() { + m.clearedteam_group_hosts = true +} + +// TeamGroupHostsCleared reports if the "team_group_hosts" edge to the TeamGroupHost entity was cleared. +func (m *TeamGroupMutation) TeamGroupHostsCleared() bool { + return m.clearedteam_group_hosts +} + +// RemoveTeamGroupHostIDs removes the "team_group_hosts" edge to the TeamGroupHost entity by IDs. +func (m *TeamGroupMutation) RemoveTeamGroupHostIDs(ids ...uuid.UUID) { + if m.removedteam_group_hosts == nil { + m.removedteam_group_hosts = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.team_group_hosts, ids[i]) + m.removedteam_group_hosts[ids[i]] = struct{}{} + } +} + +// RemovedTeamGroupHosts returns the removed IDs of the "team_group_hosts" edge to the TeamGroupHost entity. +func (m *TeamGroupMutation) RemovedTeamGroupHostsIDs() (ids []uuid.UUID) { + for id := range m.removedteam_group_hosts { + ids = append(ids, id) + } + return +} + +// TeamGroupHostsIDs returns the "team_group_hosts" edge IDs in the mutation. +func (m *TeamGroupMutation) TeamGroupHostsIDs() (ids []uuid.UUID) { + for id := range m.team_group_hosts { + ids = append(ids, id) + } + return +} + +// ResetTeamGroupHosts resets all changes to the "team_group_hosts" edge. +func (m *TeamGroupMutation) ResetTeamGroupHosts() { + m.team_group_hosts = nil + m.clearedteam_group_hosts = false + m.removedteam_group_hosts = nil +} + +// Where appends a list predicates to the TeamGroupMutation builder. +func (m *TeamGroupMutation) Where(ps ...predicate.TeamGroup) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the TeamGroupMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *TeamGroupMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.TeamGroup, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *TeamGroupMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *TeamGroupMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (TeamGroup). +func (m *TeamGroupMutation) 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 *TeamGroupMutation) Fields() []string { + fields := make([]string, 0, 5) + if m.deleted_at != nil { + fields = append(fields, teamgroup.FieldDeletedAt) + } + if m.team != nil { + fields = append(fields, teamgroup.FieldTeamID) + } + if m.name != nil { + fields = append(fields, teamgroup.FieldName) + } + if m.created_at != nil { + fields = append(fields, teamgroup.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, teamgroup.FieldUpdatedAt) + } + 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 *TeamGroupMutation) Field(name string) (ent.Value, bool) { + switch name { + case teamgroup.FieldDeletedAt: + return m.DeletedAt() + case teamgroup.FieldTeamID: + return m.TeamID() + case teamgroup.FieldName: + return m.Name() + case teamgroup.FieldCreatedAt: + return m.CreatedAt() + case teamgroup.FieldUpdatedAt: + return m.UpdatedAt() + } + 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 *TeamGroupMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case teamgroup.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case teamgroup.FieldTeamID: + return m.OldTeamID(ctx) + case teamgroup.FieldName: + return m.OldName(ctx) + case teamgroup.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case teamgroup.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) + } + return nil, fmt.Errorf("unknown TeamGroup 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 *TeamGroupMutation) SetField(name string, value ent.Value) error { + switch name { + case teamgroup.FieldDeletedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeletedAt(v) + return nil + case teamgroup.FieldTeamID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTeamID(v) + return nil + case teamgroup.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case teamgroup.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 teamgroup.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + } + return fmt.Errorf("unknown TeamGroup field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *TeamGroupMutation) AddedFields() []string { + return nil +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *TeamGroupMutation) AddedField(name string) (ent.Value, bool) { + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *TeamGroupMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown TeamGroup numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *TeamGroupMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(teamgroup.FieldDeletedAt) { + fields = append(fields, teamgroup.FieldDeletedAt) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *TeamGroupMutation) 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 *TeamGroupMutation) ClearField(name string) error { + switch name { + case teamgroup.FieldDeletedAt: + m.ClearDeletedAt() + return nil + } + return fmt.Errorf("unknown TeamGroup 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 *TeamGroupMutation) ResetField(name string) error { + switch name { + case teamgroup.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case teamgroup.FieldTeamID: + m.ResetTeamID() + return nil + case teamgroup.FieldName: + m.ResetName() + return nil + case teamgroup.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case teamgroup.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + } + return fmt.Errorf("unknown TeamGroup field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *TeamGroupMutation) AddedEdges() []string { + edges := make([]string, 0, 9) + if m.members != nil { + edges = append(edges, teamgroup.EdgeMembers) + } + if m.team != nil { + edges = append(edges, teamgroup.EdgeTeam) + } + if m.models != nil { + edges = append(edges, teamgroup.EdgeModels) + } + if m.images != nil { + edges = append(edges, teamgroup.EdgeImages) + } + if m.hosts != nil { + edges = append(edges, teamgroup.EdgeHosts) + } + if m.team_group_members != nil { + edges = append(edges, teamgroup.EdgeTeamGroupMembers) + } + if m.team_group_models != nil { + edges = append(edges, teamgroup.EdgeTeamGroupModels) + } + if m.team_group_images != nil { + edges = append(edges, teamgroup.EdgeTeamGroupImages) + } + if m.team_group_hosts != nil { + edges = append(edges, teamgroup.EdgeTeamGroupHosts) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *TeamGroupMutation) AddedIDs(name string) []ent.Value { + switch name { + case teamgroup.EdgeMembers: + ids := make([]ent.Value, 0, len(m.members)) + for id := range m.members { + ids = append(ids, id) + } + return ids + case teamgroup.EdgeTeam: + if id := m.team; id != nil { + return []ent.Value{*id} + } + case teamgroup.EdgeModels: + ids := make([]ent.Value, 0, len(m.models)) + for id := range m.models { + ids = append(ids, id) + } + return ids + case teamgroup.EdgeImages: + ids := make([]ent.Value, 0, len(m.images)) + for id := range m.images { + ids = append(ids, id) + } + return ids + case teamgroup.EdgeHosts: + ids := make([]ent.Value, 0, len(m.hosts)) + for id := range m.hosts { + ids = append(ids, id) + } + return ids + case teamgroup.EdgeTeamGroupMembers: + ids := make([]ent.Value, 0, len(m.team_group_members)) + for id := range m.team_group_members { + ids = append(ids, id) + } + return ids + case teamgroup.EdgeTeamGroupModels: + ids := make([]ent.Value, 0, len(m.team_group_models)) + for id := range m.team_group_models { + ids = append(ids, id) + } + return ids + case teamgroup.EdgeTeamGroupImages: + ids := make([]ent.Value, 0, len(m.team_group_images)) + for id := range m.team_group_images { + ids = append(ids, id) + } + return ids + case teamgroup.EdgeTeamGroupHosts: + ids := make([]ent.Value, 0, len(m.team_group_hosts)) + for id := range m.team_group_hosts { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *TeamGroupMutation) RemovedEdges() []string { + edges := make([]string, 0, 9) + if m.removedmembers != nil { + edges = append(edges, teamgroup.EdgeMembers) + } + if m.removedmodels != nil { + edges = append(edges, teamgroup.EdgeModels) + } + if m.removedimages != nil { + edges = append(edges, teamgroup.EdgeImages) + } + if m.removedhosts != nil { + edges = append(edges, teamgroup.EdgeHosts) + } + if m.removedteam_group_members != nil { + edges = append(edges, teamgroup.EdgeTeamGroupMembers) + } + if m.removedteam_group_models != nil { + edges = append(edges, teamgroup.EdgeTeamGroupModels) + } + if m.removedteam_group_images != nil { + edges = append(edges, teamgroup.EdgeTeamGroupImages) + } + if m.removedteam_group_hosts != nil { + edges = append(edges, teamgroup.EdgeTeamGroupHosts) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *TeamGroupMutation) RemovedIDs(name string) []ent.Value { + switch name { + case teamgroup.EdgeMembers: + ids := make([]ent.Value, 0, len(m.removedmembers)) + for id := range m.removedmembers { + ids = append(ids, id) + } + return ids + case teamgroup.EdgeModels: + ids := make([]ent.Value, 0, len(m.removedmodels)) + for id := range m.removedmodels { + ids = append(ids, id) + } + return ids + case teamgroup.EdgeImages: + ids := make([]ent.Value, 0, len(m.removedimages)) + for id := range m.removedimages { + ids = append(ids, id) + } + return ids + case teamgroup.EdgeHosts: + ids := make([]ent.Value, 0, len(m.removedhosts)) + for id := range m.removedhosts { + ids = append(ids, id) + } + return ids + case teamgroup.EdgeTeamGroupMembers: + ids := make([]ent.Value, 0, len(m.removedteam_group_members)) + for id := range m.removedteam_group_members { + ids = append(ids, id) + } + return ids + case teamgroup.EdgeTeamGroupModels: + ids := make([]ent.Value, 0, len(m.removedteam_group_models)) + for id := range m.removedteam_group_models { + ids = append(ids, id) + } + return ids + case teamgroup.EdgeTeamGroupImages: + ids := make([]ent.Value, 0, len(m.removedteam_group_images)) + for id := range m.removedteam_group_images { + ids = append(ids, id) + } + return ids + case teamgroup.EdgeTeamGroupHosts: + ids := make([]ent.Value, 0, len(m.removedteam_group_hosts)) + for id := range m.removedteam_group_hosts { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *TeamGroupMutation) ClearedEdges() []string { + edges := make([]string, 0, 9) + if m.clearedmembers { + edges = append(edges, teamgroup.EdgeMembers) + } + if m.clearedteam { + edges = append(edges, teamgroup.EdgeTeam) + } + if m.clearedmodels { + edges = append(edges, teamgroup.EdgeModels) + } + if m.clearedimages { + edges = append(edges, teamgroup.EdgeImages) + } + if m.clearedhosts { + edges = append(edges, teamgroup.EdgeHosts) + } + if m.clearedteam_group_members { + edges = append(edges, teamgroup.EdgeTeamGroupMembers) + } + if m.clearedteam_group_models { + edges = append(edges, teamgroup.EdgeTeamGroupModels) + } + if m.clearedteam_group_images { + edges = append(edges, teamgroup.EdgeTeamGroupImages) + } + if m.clearedteam_group_hosts { + edges = append(edges, teamgroup.EdgeTeamGroupHosts) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *TeamGroupMutation) EdgeCleared(name string) bool { + switch name { + case teamgroup.EdgeMembers: + return m.clearedmembers + case teamgroup.EdgeTeam: + return m.clearedteam + case teamgroup.EdgeModels: + return m.clearedmodels + case teamgroup.EdgeImages: + return m.clearedimages + case teamgroup.EdgeHosts: + return m.clearedhosts + case teamgroup.EdgeTeamGroupMembers: + return m.clearedteam_group_members + case teamgroup.EdgeTeamGroupModels: + return m.clearedteam_group_models + case teamgroup.EdgeTeamGroupImages: + return m.clearedteam_group_images + case teamgroup.EdgeTeamGroupHosts: + return m.clearedteam_group_hosts + } + 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 *TeamGroupMutation) ClearEdge(name string) error { + switch name { + case teamgroup.EdgeTeam: + m.ClearTeam() + return nil + } + return fmt.Errorf("unknown TeamGroup 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 *TeamGroupMutation) ResetEdge(name string) error { + switch name { + case teamgroup.EdgeMembers: + m.ResetMembers() + return nil + case teamgroup.EdgeTeam: + m.ResetTeam() + return nil + case teamgroup.EdgeModels: + m.ResetModels() + return nil + case teamgroup.EdgeImages: + m.ResetImages() + return nil + case teamgroup.EdgeHosts: + m.ResetHosts() + return nil + case teamgroup.EdgeTeamGroupMembers: + m.ResetTeamGroupMembers() + return nil + case teamgroup.EdgeTeamGroupModels: + m.ResetTeamGroupModels() + return nil + case teamgroup.EdgeTeamGroupImages: + m.ResetTeamGroupImages() + return nil + case teamgroup.EdgeTeamGroupHosts: + m.ResetTeamGroupHosts() + return nil + } + return fmt.Errorf("unknown TeamGroup edge %s", name) } -// TeamsCleared reports if the "teams" edge to the Team entity was cleared. -func (m *ModelMutation) TeamsCleared() bool { - return m.clearedteams +// TeamGroupHostMutation represents an operation that mutates the TeamGroupHost nodes in the graph. +type TeamGroupHostMutation struct { + config + op Op + typ string + id *uuid.UUID + created_at *time.Time + clearedFields map[string]struct{} + group *uuid.UUID + clearedgroup bool + host *string + clearedhost bool + done bool + oldValue func(context.Context) (*TeamGroupHost, error) + predicates []predicate.TeamGroupHost } -// RemoveTeamIDs removes the "teams" edge to the Team entity by IDs. -func (m *ModelMutation) RemoveTeamIDs(ids ...uuid.UUID) { - if m.removedteams == nil { - m.removedteams = make(map[uuid.UUID]struct{}) +var _ ent.Mutation = (*TeamGroupHostMutation)(nil) + +// teamgrouphostOption allows management of the mutation configuration using functional options. +type teamgrouphostOption func(*TeamGroupHostMutation) + +// newTeamGroupHostMutation creates new mutation for the TeamGroupHost entity. +func newTeamGroupHostMutation(c config, op Op, opts ...teamgrouphostOption) *TeamGroupHostMutation { + m := &TeamGroupHostMutation{ + config: c, + op: op, + typ: TypeTeamGroupHost, + clearedFields: make(map[string]struct{}), } - for i := range ids { - delete(m.teams, ids[i]) - m.removedteams[ids[i]] = struct{}{} + for _, opt := range opts { + opt(m) } + return m } -// RemovedTeams returns the removed IDs of the "teams" edge to the Team entity. -func (m *ModelMutation) RemovedTeamsIDs() (ids []uuid.UUID) { - for id := range m.removedteams { - ids = append(ids, id) +// withTeamGroupHostID sets the ID field of the mutation. +func withTeamGroupHostID(id uuid.UUID) teamgrouphostOption { + return func(m *TeamGroupHostMutation) { + var ( + err error + once sync.Once + value *TeamGroupHost + ) + m.oldValue = func(ctx context.Context) (*TeamGroupHost, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().TeamGroupHost.Get(ctx, id) + } + }) + return value, err + } + m.id = &id } - return } -// TeamsIDs returns the "teams" edge IDs in the mutation. -func (m *ModelMutation) TeamsIDs() (ids []uuid.UUID) { - for id := range m.teams { - ids = append(ids, id) +// withTeamGroupHost sets the old TeamGroupHost of the mutation. +func withTeamGroupHost(node *TeamGroupHost) teamgrouphostOption { + return func(m *TeamGroupHostMutation) { + m.oldValue = func(context.Context) (*TeamGroupHost, error) { + return node, nil + } + m.id = &node.ID } - return } -// ResetTeams resets all changes to the "teams" edge. -func (m *ModelMutation) ResetTeams() { - m.teams = nil - m.clearedteams = false - m.removedteams = nil +// 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 TeamGroupHostMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client } -// AddGroupIDs adds the "groups" edge to the TeamGroup entity by ids. -func (m *ModelMutation) AddGroupIDs(ids ...uuid.UUID) { - if m.groups == nil { - m.groups = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.groups[ids[i]] = struct{}{} +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m TeamGroupHostMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("db: mutation is not running in a transaction") } + tx := &Tx{config: m.config} + tx.init() + return tx, nil } -// ClearGroups clears the "groups" edge to the TeamGroup entity. -func (m *ModelMutation) ClearGroups() { - m.clearedgroups = true -} - -// GroupsCleared reports if the "groups" edge to the TeamGroup entity was cleared. -func (m *ModelMutation) GroupsCleared() bool { - return m.clearedgroups +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of TeamGroupHost entities. +func (m *TeamGroupHostMutation) SetID(id uuid.UUID) { + m.id = &id } -// RemoveGroupIDs removes the "groups" edge to the TeamGroup entity by IDs. -func (m *ModelMutation) RemoveGroupIDs(ids ...uuid.UUID) { - if m.removedgroups == nil { - m.removedgroups = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.groups, ids[i]) - m.removedgroups[ids[i]] = struct{}{} +// 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 *TeamGroupHostMutation) ID() (id uuid.UUID, exists bool) { + if m.id == nil { + return } + return *m.id, true } -// RemovedGroups returns the removed IDs of the "groups" edge to the TeamGroup entity. -func (m *ModelMutation) RemovedGroupsIDs() (ids []uuid.UUID) { - for id := range m.removedgroups { - ids = append(ids, id) +// 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 *TeamGroupHostMutation) 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().TeamGroupHost.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } - return } -// GroupsIDs returns the "groups" edge IDs in the mutation. -func (m *ModelMutation) GroupsIDs() (ids []uuid.UUID) { - for id := range m.groups { - ids = append(ids, id) - } - return +// SetGroupID sets the "group_id" field. +func (m *TeamGroupHostMutation) SetGroupID(u uuid.UUID) { + m.group = &u } -// ResetGroups resets all changes to the "groups" edge. -func (m *ModelMutation) ResetGroups() { - m.groups = nil - m.clearedgroups = false - m.removedgroups = nil +// GroupID returns the value of the "group_id" field in the mutation. +func (m *TeamGroupHostMutation) GroupID() (r uuid.UUID, exists bool) { + v := m.group + if v == nil { + return + } + return *v, true } -// AddTeamModelIDs adds the "team_models" edge to the TeamModel entity by ids. -func (m *ModelMutation) AddTeamModelIDs(ids ...uuid.UUID) { - if m.team_models == nil { - m.team_models = make(map[uuid.UUID]struct{}) +// OldGroupID returns the old "group_id" field's value of the TeamGroupHost entity. +// If the TeamGroupHost 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 *TeamGroupHostMutation) OldGroupID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldGroupID is only allowed on UpdateOne operations") } - for i := range ids { - m.team_models[ids[i]] = struct{}{} + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldGroupID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldGroupID: %w", err) } + return oldValue.GroupID, nil } -// ClearTeamModels clears the "team_models" edge to the TeamModel entity. -func (m *ModelMutation) ClearTeamModels() { - m.clearedteam_models = true +// ResetGroupID resets all changes to the "group_id" field. +func (m *TeamGroupHostMutation) ResetGroupID() { + m.group = nil } -// TeamModelsCleared reports if the "team_models" edge to the TeamModel entity was cleared. -func (m *ModelMutation) TeamModelsCleared() bool { - return m.clearedteam_models +// SetHostID sets the "host_id" field. +func (m *TeamGroupHostMutation) SetHostID(s string) { + m.host = &s } -// RemoveTeamModelIDs removes the "team_models" edge to the TeamModel entity by IDs. -func (m *ModelMutation) RemoveTeamModelIDs(ids ...uuid.UUID) { - if m.removedteam_models == nil { - m.removedteam_models = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.team_models, ids[i]) - m.removedteam_models[ids[i]] = struct{}{} +// HostID returns the value of the "host_id" field in the mutation. +func (m *TeamGroupHostMutation) HostID() (r string, exists bool) { + v := m.host + if v == nil { + return } + return *v, true } -// RemovedTeamModels returns the removed IDs of the "team_models" edge to the TeamModel entity. -func (m *ModelMutation) RemovedTeamModelsIDs() (ids []uuid.UUID) { - for id := range m.removedteam_models { - ids = append(ids, id) +// OldHostID returns the old "host_id" field's value of the TeamGroupHost entity. +// If the TeamGroupHost 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 *TeamGroupHostMutation) OldHostID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldHostID is only allowed on UpdateOne operations") } - return + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldHostID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldHostID: %w", err) + } + return oldValue.HostID, nil } -// TeamModelsIDs returns the "team_models" edge IDs in the mutation. -func (m *ModelMutation) TeamModelsIDs() (ids []uuid.UUID) { - for id := range m.team_models { - ids = append(ids, id) - } - return +// ResetHostID resets all changes to the "host_id" field. +func (m *TeamGroupHostMutation) ResetHostID() { + m.host = nil } -// ResetTeamModels resets all changes to the "team_models" edge. -func (m *ModelMutation) ResetTeamModels() { - m.team_models = nil - m.clearedteam_models = false - m.removedteam_models = nil +// SetCreatedAt sets the "created_at" field. +func (m *TeamGroupHostMutation) SetCreatedAt(t time.Time) { + m.created_at = &t } -// AddTeamGroupModelIDs adds the "team_group_models" edge to the TeamGroupModel entity by ids. -func (m *ModelMutation) AddTeamGroupModelIDs(ids ...uuid.UUID) { - if m.team_group_models == nil { - m.team_group_models = make(map[uuid.UUID]struct{}) +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *TeamGroupHostMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return } - for i := range ids { - m.team_group_models[ids[i]] = struct{}{} + return *v, true +} + +// OldCreatedAt returns the old "created_at" field's value of the TeamGroupHost entity. +// If the TeamGroupHost 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 *TeamGroupHostMutation) 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 } -// ClearTeamGroupModels clears the "team_group_models" edge to the TeamGroupModel entity. -func (m *ModelMutation) ClearTeamGroupModels() { - m.clearedteam_group_models = true +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *TeamGroupHostMutation) ResetCreatedAt() { + m.created_at = nil } -// TeamGroupModelsCleared reports if the "team_group_models" edge to the TeamGroupModel entity was cleared. -func (m *ModelMutation) TeamGroupModelsCleared() bool { - return m.clearedteam_group_models +// ClearGroup clears the "group" edge to the TeamGroup entity. +func (m *TeamGroupHostMutation) ClearGroup() { + m.clearedgroup = true + m.clearedFields[teamgrouphost.FieldGroupID] = struct{}{} } -// RemoveTeamGroupModelIDs removes the "team_group_models" edge to the TeamGroupModel entity by IDs. -func (m *ModelMutation) RemoveTeamGroupModelIDs(ids ...uuid.UUID) { - if m.removedteam_group_models == nil { - m.removedteam_group_models = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.team_group_models, ids[i]) - m.removedteam_group_models[ids[i]] = struct{}{} - } +// GroupCleared reports if the "group" edge to the TeamGroup entity was cleared. +func (m *TeamGroupHostMutation) GroupCleared() bool { + return m.clearedgroup } -// RemovedTeamGroupModels returns the removed IDs of the "team_group_models" edge to the TeamGroupModel entity. -func (m *ModelMutation) RemovedTeamGroupModelsIDs() (ids []uuid.UUID) { - for id := range m.removedteam_group_models { - ids = append(ids, id) +// 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 *TeamGroupHostMutation) GroupIDs() (ids []uuid.UUID) { + if id := m.group; id != nil { + ids = append(ids, *id) } return } -// TeamGroupModelsIDs returns the "team_group_models" edge IDs in the mutation. -func (m *ModelMutation) TeamGroupModelsIDs() (ids []uuid.UUID) { - for id := range m.team_group_models { - ids = append(ids, id) +// ResetGroup resets all changes to the "group" edge. +func (m *TeamGroupHostMutation) ResetGroup() { + m.group = nil + m.clearedgroup = false +} + +// ClearHost clears the "host" edge to the Host entity. +func (m *TeamGroupHostMutation) ClearHost() { + m.clearedhost = true + m.clearedFields[teamgrouphost.FieldHostID] = struct{}{} +} + +// HostCleared reports if the "host" edge to the Host entity was cleared. +func (m *TeamGroupHostMutation) HostCleared() bool { + return m.clearedhost +} + +// HostIDs returns the "host" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// HostID instead. It exists only for internal usage by the builders. +func (m *TeamGroupHostMutation) HostIDs() (ids []string) { + if id := m.host; id != nil { + ids = append(ids, *id) } return } -// ResetTeamGroupModels resets all changes to the "team_group_models" edge. -func (m *ModelMutation) ResetTeamGroupModels() { - m.team_group_models = nil - m.clearedteam_group_models = false - m.removedteam_group_models = nil +// ResetHost resets all changes to the "host" edge. +func (m *TeamGroupHostMutation) ResetHost() { + m.host = nil + m.clearedhost = false } -// Where appends a list predicates to the ModelMutation builder. -func (m *ModelMutation) Where(ps ...predicate.Model) { +// Where appends a list predicates to the TeamGroupHostMutation builder. +func (m *TeamGroupHostMutation) Where(ps ...predicate.TeamGroupHost) { m.predicates = append(m.predicates, ps...) } -// WhereP appends storage-level predicates to the ModelMutation builder. Using this method, +// WhereP appends storage-level predicates to the TeamGroupHostMutation builder. Using this method, // users can use type-assertion to append predicates that do not depend on any generated package. -func (m *ModelMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.Model, len(ps)) +func (m *TeamGroupHostMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.TeamGroupHost, len(ps)) for i := range ps { p[i] = ps[i] } @@ -2893,69 +8192,33 @@ func (m *ModelMutation) WhereP(ps ...func(*sql.Selector)) { } // Op returns the operation name. -func (m *ModelMutation) Op() Op { +func (m *TeamGroupHostMutation) Op() Op { return m.op } // SetOp allows setting the mutation operation. -func (m *ModelMutation) SetOp(op Op) { +func (m *TeamGroupHostMutation) SetOp(op Op) { m.op = op } -// Type returns the node type of this mutation (Model). -func (m *ModelMutation) Type() string { +// Type returns the node type of this mutation (TeamGroupHost). +func (m *TeamGroupHostMutation) 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 *ModelMutation) Fields() []string { - fields := make([]string, 0, 15) - if m.deleted_at != nil { - fields = append(fields, model.FieldDeletedAt) - } - if m.user != nil { - fields = append(fields, model.FieldUserID) - } - if m.provider != nil { - fields = append(fields, model.FieldProvider) - } - if m.api_key != nil { - fields = append(fields, model.FieldAPIKey) - } - if m.base_url != nil { - fields = append(fields, model.FieldBaseURL) - } - if m.model != nil { - fields = append(fields, model.FieldModel) - } - if m.remark != nil { - fields = append(fields, model.FieldRemark) - } - if m.temperature != nil { - fields = append(fields, model.FieldTemperature) - } - if m.interface_type != nil { - fields = append(fields, model.FieldInterfaceType) - } - if m.weight != nil { - fields = append(fields, model.FieldWeight) - } - if m.last_check_at != nil { - fields = append(fields, model.FieldLastCheckAt) - } - if m.last_check_success != nil { - fields = append(fields, model.FieldLastCheckSuccess) +func (m *TeamGroupHostMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.group != nil { + fields = append(fields, teamgrouphost.FieldGroupID) } - if m.last_check_error != nil { - fields = append(fields, model.FieldLastCheckError) + if m.host != nil { + fields = append(fields, teamgrouphost.FieldHostID) } if m.created_at != nil { - fields = append(fields, model.FieldCreatedAt) - } - if m.updated_at != nil { - fields = append(fields, model.FieldUpdatedAt) + fields = append(fields, teamgrouphost.FieldCreatedAt) } return fields } @@ -2963,38 +8226,14 @@ func (m *ModelMutation) Fields() []string { // 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 *ModelMutation) Field(name string) (ent.Value, bool) { +func (m *TeamGroupHostMutation) Field(name string) (ent.Value, bool) { switch name { - case model.FieldDeletedAt: - return m.DeletedAt() - case model.FieldUserID: - return m.UserID() - case model.FieldProvider: - return m.Provider() - case model.FieldAPIKey: - return m.APIKey() - case model.FieldBaseURL: - return m.BaseURL() - case model.FieldModel: - return m.Model() - case model.FieldRemark: - return m.Remark() - case model.FieldTemperature: - return m.Temperature() - case model.FieldInterfaceType: - return m.InterfaceType() - case model.FieldWeight: - return m.Weight() - case model.FieldLastCheckAt: - return m.LastCheckAt() - case model.FieldLastCheckSuccess: - return m.LastCheckSuccess() - case model.FieldLastCheckError: - return m.LastCheckError() - case model.FieldCreatedAt: + case teamgrouphost.FieldGroupID: + return m.GroupID() + case teamgrouphost.FieldHostID: + return m.HostID() + case teamgrouphost.FieldCreatedAt: return m.CreatedAt() - case model.FieldUpdatedAt: - return m.UpdatedAt() } return nil, false } @@ -3002,552 +8241,226 @@ func (m *ModelMutation) Field(name string) (ent.Value, bool) { // 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 *ModelMutation) OldField(ctx context.Context, name string) (ent.Value, error) { +func (m *TeamGroupHostMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { - case model.FieldDeletedAt: - return m.OldDeletedAt(ctx) - case model.FieldUserID: - return m.OldUserID(ctx) - case model.FieldProvider: - return m.OldProvider(ctx) - case model.FieldAPIKey: - return m.OldAPIKey(ctx) - case model.FieldBaseURL: - return m.OldBaseURL(ctx) - case model.FieldModel: - return m.OldModel(ctx) - case model.FieldRemark: - return m.OldRemark(ctx) - case model.FieldTemperature: - return m.OldTemperature(ctx) - case model.FieldInterfaceType: - return m.OldInterfaceType(ctx) - case model.FieldWeight: - return m.OldWeight(ctx) - case model.FieldLastCheckAt: - return m.OldLastCheckAt(ctx) - case model.FieldLastCheckSuccess: - return m.OldLastCheckSuccess(ctx) - case model.FieldLastCheckError: - return m.OldLastCheckError(ctx) - case model.FieldCreatedAt: + case teamgrouphost.FieldGroupID: + return m.OldGroupID(ctx) + case teamgrouphost.FieldHostID: + return m.OldHostID(ctx) + case teamgrouphost.FieldCreatedAt: return m.OldCreatedAt(ctx) - case model.FieldUpdatedAt: - return m.OldUpdatedAt(ctx) } - return nil, fmt.Errorf("unknown Model field %s", name) + return nil, fmt.Errorf("unknown TeamGroupHost 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 *ModelMutation) SetField(name string, value ent.Value) error { +func (m *TeamGroupHostMutation) SetField(name string, value ent.Value) error { switch name { - case model.FieldDeletedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetDeletedAt(v) - return nil - case model.FieldUserID: + case teamgrouphost.FieldGroupID: v, ok := value.(uuid.UUID) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetUserID(v) - return nil - case model.FieldProvider: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetProvider(v) - return nil - case model.FieldAPIKey: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetAPIKey(v) - return nil - case model.FieldBaseURL: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetBaseURL(v) - return nil - case model.FieldModel: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetModel(v) - return nil - case model.FieldRemark: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetRemark(v) - return nil - case model.FieldTemperature: - v, ok := value.(float64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetTemperature(v) - return nil - case model.FieldInterfaceType: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetInterfaceType(v) - return nil - case model.FieldWeight: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetWeight(v) - return nil - case model.FieldLastCheckAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetLastCheckAt(v) - return nil - case model.FieldLastCheckSuccess: - v, ok := value.(bool) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetLastCheckSuccess(v) - return nil - case model.FieldLastCheckError: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetLastCheckError(v) + m.SetGroupID(v) return nil - case model.FieldCreatedAt: - v, ok := value.(time.Time) + case teamgrouphost.FieldHostID: + v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetCreatedAt(v) + m.SetHostID(v) return nil - case model.FieldUpdatedAt: + case teamgrouphost.FieldCreatedAt: v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetUpdatedAt(v) + m.SetCreatedAt(v) return nil } - return fmt.Errorf("unknown Model field %s", name) + return fmt.Errorf("unknown TeamGroupHost field %s", name) } // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. -func (m *ModelMutation) AddedFields() []string { - var fields []string - if m.addtemperature != nil { - fields = append(fields, model.FieldTemperature) - } - if m.addweight != nil { - fields = append(fields, model.FieldWeight) - } - return fields +func (m *TeamGroupHostMutation) AddedFields() []string { + return nil } // AddedField returns the numeric value that was incremented/decremented on a field // with the given name. The second boolean return value indicates that this field // was not set, or was not defined in the schema. -func (m *ModelMutation) AddedField(name string) (ent.Value, bool) { - switch name { - case model.FieldTemperature: - return m.AddedTemperature() - case model.FieldWeight: - return m.AddedWeight() - } +func (m *TeamGroupHostMutation) AddedField(name string) (ent.Value, bool) { return nil, false } // AddField adds the value to the field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *ModelMutation) AddField(name string, value ent.Value) error { +func (m *TeamGroupHostMutation) AddField(name string, value ent.Value) error { switch name { - case model.FieldTemperature: - v, ok := value.(float64) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddTemperature(v) - return nil - case model.FieldWeight: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddWeight(v) - return nil } - return fmt.Errorf("unknown Model numeric field %s", name) + return fmt.Errorf("unknown TeamGroupHost numeric field %s", name) } // ClearedFields returns all nullable fields that were cleared during this // mutation. -func (m *ModelMutation) ClearedFields() []string { - var fields []string - if m.FieldCleared(model.FieldDeletedAt) { - fields = append(fields, model.FieldDeletedAt) - } - if m.FieldCleared(model.FieldRemark) { - fields = append(fields, model.FieldRemark) - } - if m.FieldCleared(model.FieldTemperature) { - fields = append(fields, model.FieldTemperature) - } - if m.FieldCleared(model.FieldInterfaceType) { - fields = append(fields, model.FieldInterfaceType) - } - if m.FieldCleared(model.FieldLastCheckAt) { - fields = append(fields, model.FieldLastCheckAt) - } - if m.FieldCleared(model.FieldLastCheckSuccess) { - fields = append(fields, model.FieldLastCheckSuccess) - } - if m.FieldCleared(model.FieldLastCheckError) { - fields = append(fields, model.FieldLastCheckError) - } - return fields +func (m *TeamGroupHostMutation) ClearedFields() []string { + return nil } // FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. -func (m *ModelMutation) FieldCleared(name string) bool { +func (m *TeamGroupHostMutation) 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 *ModelMutation) ClearField(name string) error { - switch name { - case model.FieldDeletedAt: - m.ClearDeletedAt() - return nil - case model.FieldRemark: - m.ClearRemark() - return nil - case model.FieldTemperature: - m.ClearTemperature() - return nil - case model.FieldInterfaceType: - m.ClearInterfaceType() - return nil - case model.FieldLastCheckAt: - m.ClearLastCheckAt() - return nil - case model.FieldLastCheckSuccess: - m.ClearLastCheckSuccess() - return nil - case model.FieldLastCheckError: - m.ClearLastCheckError() - return nil - } - return fmt.Errorf("unknown Model nullable field %s", name) +func (m *TeamGroupHostMutation) ClearField(name string) error { + return fmt.Errorf("unknown TeamGroupHost 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 *ModelMutation) ResetField(name string) error { +func (m *TeamGroupHostMutation) ResetField(name string) error { switch name { - case model.FieldDeletedAt: - m.ResetDeletedAt() - return nil - case model.FieldUserID: - m.ResetUserID() - return nil - case model.FieldProvider: - m.ResetProvider() - return nil - case model.FieldAPIKey: - m.ResetAPIKey() - return nil - case model.FieldBaseURL: - m.ResetBaseURL() - return nil - case model.FieldModel: - m.ResetModel() - return nil - case model.FieldRemark: - m.ResetRemark() - return nil - case model.FieldTemperature: - m.ResetTemperature() - return nil - case model.FieldInterfaceType: - m.ResetInterfaceType() - return nil - case model.FieldWeight: - m.ResetWeight() - return nil - case model.FieldLastCheckAt: - m.ResetLastCheckAt() - return nil - case model.FieldLastCheckSuccess: - m.ResetLastCheckSuccess() + case teamgrouphost.FieldGroupID: + m.ResetGroupID() return nil - case model.FieldLastCheckError: - m.ResetLastCheckError() + case teamgrouphost.FieldHostID: + m.ResetHostID() return nil - case model.FieldCreatedAt: + case teamgrouphost.FieldCreatedAt: m.ResetCreatedAt() return nil - case model.FieldUpdatedAt: - m.ResetUpdatedAt() - return nil } - return fmt.Errorf("unknown Model field %s", name) + return fmt.Errorf("unknown TeamGroupHost field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. -func (m *ModelMutation) AddedEdges() []string { - edges := make([]string, 0, 5) - if m.user != nil { - edges = append(edges, model.EdgeUser) - } - if m.teams != nil { - edges = append(edges, model.EdgeTeams) - } - if m.groups != nil { - edges = append(edges, model.EdgeGroups) - } - if m.team_models != nil { - edges = append(edges, model.EdgeTeamModels) +func (m *TeamGroupHostMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.group != nil { + edges = append(edges, teamgrouphost.EdgeGroup) } - if m.team_group_models != nil { - edges = append(edges, model.EdgeTeamGroupModels) + if m.host != nil { + edges = append(edges, teamgrouphost.EdgeHost) } return edges } // AddedIDs returns all IDs (to other nodes) that were added for the given edge // name in this mutation. -func (m *ModelMutation) AddedIDs(name string) []ent.Value { +func (m *TeamGroupHostMutation) AddedIDs(name string) []ent.Value { switch name { - case model.EdgeUser: - if id := m.user; id != nil { + case teamgrouphost.EdgeGroup: + if id := m.group; id != nil { return []ent.Value{*id} } - case model.EdgeTeams: - ids := make([]ent.Value, 0, len(m.teams)) - for id := range m.teams { - ids = append(ids, id) - } - return ids - case model.EdgeGroups: - ids := make([]ent.Value, 0, len(m.groups)) - for id := range m.groups { - ids = append(ids, id) - } - return ids - case model.EdgeTeamModels: - ids := make([]ent.Value, 0, len(m.team_models)) - for id := range m.team_models { - ids = append(ids, id) - } - return ids - case model.EdgeTeamGroupModels: - ids := make([]ent.Value, 0, len(m.team_group_models)) - for id := range m.team_group_models { - ids = append(ids, id) + case teamgrouphost.EdgeHost: + if id := m.host; id != nil { + return []ent.Value{*id} } - return ids } return nil } // RemovedEdges returns all edge names that were removed in this mutation. -func (m *ModelMutation) RemovedEdges() []string { - edges := make([]string, 0, 5) - if m.removedteams != nil { - edges = append(edges, model.EdgeTeams) - } - if m.removedgroups != nil { - edges = append(edges, model.EdgeGroups) - } - if m.removedteam_models != nil { - edges = append(edges, model.EdgeTeamModels) - } - if m.removedteam_group_models != nil { - edges = append(edges, model.EdgeTeamGroupModels) - } +func (m *TeamGroupHostMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) return edges } // RemovedIDs returns all IDs (to other nodes) that were removed for the edge with // the given name in this mutation. -func (m *ModelMutation) RemovedIDs(name string) []ent.Value { - switch name { - case model.EdgeTeams: - ids := make([]ent.Value, 0, len(m.removedteams)) - for id := range m.removedteams { - ids = append(ids, id) - } - return ids - case model.EdgeGroups: - ids := make([]ent.Value, 0, len(m.removedgroups)) - for id := range m.removedgroups { - ids = append(ids, id) - } - return ids - case model.EdgeTeamModels: - ids := make([]ent.Value, 0, len(m.removedteam_models)) - for id := range m.removedteam_models { - ids = append(ids, id) - } - return ids - case model.EdgeTeamGroupModels: - ids := make([]ent.Value, 0, len(m.removedteam_group_models)) - for id := range m.removedteam_group_models { - ids = append(ids, id) - } - return ids - } +func (m *TeamGroupHostMutation) RemovedIDs(name string) []ent.Value { return nil } // ClearedEdges returns all edge names that were cleared in this mutation. -func (m *ModelMutation) ClearedEdges() []string { - edges := make([]string, 0, 5) - if m.cleareduser { - edges = append(edges, model.EdgeUser) - } - if m.clearedteams { - edges = append(edges, model.EdgeTeams) - } - if m.clearedgroups { - edges = append(edges, model.EdgeGroups) - } - if m.clearedteam_models { - edges = append(edges, model.EdgeTeamModels) +func (m *TeamGroupHostMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedgroup { + edges = append(edges, teamgrouphost.EdgeGroup) } - if m.clearedteam_group_models { - edges = append(edges, model.EdgeTeamGroupModels) + if m.clearedhost { + edges = append(edges, teamgrouphost.EdgeHost) } return edges } // EdgeCleared returns a boolean which indicates if the edge with the given name // was cleared in this mutation. -func (m *ModelMutation) EdgeCleared(name string) bool { +func (m *TeamGroupHostMutation) EdgeCleared(name string) bool { switch name { - case model.EdgeUser: - return m.cleareduser - case model.EdgeTeams: - return m.clearedteams - case model.EdgeGroups: - return m.clearedgroups - case model.EdgeTeamModels: - return m.clearedteam_models - case model.EdgeTeamGroupModels: - return m.clearedteam_group_models + case teamgrouphost.EdgeGroup: + return m.clearedgroup + case teamgrouphost.EdgeHost: + return m.clearedhost } 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 *ModelMutation) ClearEdge(name string) error { +func (m *TeamGroupHostMutation) ClearEdge(name string) error { switch name { - case model.EdgeUser: - m.ClearUser() + case teamgrouphost.EdgeGroup: + m.ClearGroup() + return nil + case teamgrouphost.EdgeHost: + m.ClearHost() return nil } - return fmt.Errorf("unknown Model unique edge %s", name) + return fmt.Errorf("unknown TeamGroupHost 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 *ModelMutation) ResetEdge(name string) error { +func (m *TeamGroupHostMutation) ResetEdge(name string) error { switch name { - case model.EdgeUser: - m.ResetUser() - return nil - case model.EdgeTeams: - m.ResetTeams() - return nil - case model.EdgeGroups: - m.ResetGroups() - return nil - case model.EdgeTeamModels: - m.ResetTeamModels() + case teamgrouphost.EdgeGroup: + m.ResetGroup() return nil - case model.EdgeTeamGroupModels: - m.ResetTeamGroupModels() + case teamgrouphost.EdgeHost: + m.ResetHost() return nil } - return fmt.Errorf("unknown Model edge %s", name) + return fmt.Errorf("unknown TeamGroupHost edge %s", name) } -// TeamMutation represents an operation that mutates the Team nodes in the graph. -type TeamMutation struct { +// TeamGroupImageMutation represents an operation that mutates the TeamGroupImage nodes in the graph. +type TeamGroupImageMutation struct { config - op Op - typ string - id *uuid.UUID - deleted_at *time.Time - name *string - member_limit *int - addmember_limit *int - created_at *time.Time - updated_at *time.Time - clearedFields map[string]struct{} - groups map[uuid.UUID]struct{} - removedgroups map[uuid.UUID]struct{} - clearedgroups bool - members map[uuid.UUID]struct{} - removedmembers map[uuid.UUID]struct{} - clearedmembers bool - models map[uuid.UUID]struct{} - removedmodels map[uuid.UUID]struct{} - clearedmodels bool - images map[uuid.UUID]struct{} - removedimages map[uuid.UUID]struct{} - clearedimages bool - team_members map[uuid.UUID]struct{} - removedteam_members map[uuid.UUID]struct{} - clearedteam_members bool - team_models map[uuid.UUID]struct{} - removedteam_models map[uuid.UUID]struct{} - clearedteam_models bool - team_images map[uuid.UUID]struct{} - removedteam_images map[uuid.UUID]struct{} - clearedteam_images bool - done bool - oldValue func(context.Context) (*Team, error) - predicates []predicate.Team + op Op + typ string + id *uuid.UUID + created_at *time.Time + clearedFields map[string]struct{} + group *uuid.UUID + clearedgroup bool + image *uuid.UUID + clearedimage bool + done bool + oldValue func(context.Context) (*TeamGroupImage, error) + predicates []predicate.TeamGroupImage } -var _ ent.Mutation = (*TeamMutation)(nil) +var _ ent.Mutation = (*TeamGroupImageMutation)(nil) -// teamOption allows management of the mutation configuration using functional options. -type teamOption func(*TeamMutation) +// teamgroupimageOption allows management of the mutation configuration using functional options. +type teamgroupimageOption func(*TeamGroupImageMutation) -// newTeamMutation creates new mutation for the Team entity. -func newTeamMutation(c config, op Op, opts ...teamOption) *TeamMutation { - m := &TeamMutation{ +// newTeamGroupImageMutation creates new mutation for the TeamGroupImage entity. +func newTeamGroupImageMutation(c config, op Op, opts ...teamgroupimageOption) *TeamGroupImageMutation { + m := &TeamGroupImageMutation{ config: c, op: op, - typ: TypeTeam, + typ: TypeTeamGroupImage, clearedFields: make(map[string]struct{}), } for _, opt := range opts { @@ -3556,20 +8469,20 @@ func newTeamMutation(c config, op Op, opts ...teamOption) *TeamMutation { return m } -// withTeamID sets the ID field of the mutation. -func withTeamID(id uuid.UUID) teamOption { - return func(m *TeamMutation) { +// withTeamGroupImageID sets the ID field of the mutation. +func withTeamGroupImageID(id uuid.UUID) teamgroupimageOption { + return func(m *TeamGroupImageMutation) { var ( err error once sync.Once - value *Team + value *TeamGroupImage ) - m.oldValue = func(ctx context.Context) (*Team, error) { + m.oldValue = func(ctx context.Context) (*TeamGroupImage, error) { once.Do(func() { if m.done { err = errors.New("querying old values post mutation is not allowed") } else { - value, err = m.Client().Team.Get(ctx, id) + value, err = m.Client().TeamGroupImage.Get(ctx, id) } }) return value, err @@ -3578,10 +8491,10 @@ func withTeamID(id uuid.UUID) teamOption { } } -// withTeam sets the old Team of the mutation. -func withTeam(node *Team) teamOption { - return func(m *TeamMutation) { - m.oldValue = func(context.Context) (*Team, error) { +// withTeamGroupImage sets the old TeamGroupImage of the mutation. +func withTeamGroupImage(node *TeamGroupImage) teamgroupimageOption { + return func(m *TeamGroupImageMutation) { + m.oldValue = func(context.Context) (*TeamGroupImage, error) { return node, nil } m.id = &node.ID @@ -3590,7 +8503,7 @@ func withTeam(node *Team) teamOption { // 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 TeamMutation) Client() *Client { +func (m TeamGroupImageMutation) Client() *Client { client := &Client{config: m.config} client.init() return client @@ -3598,7 +8511,7 @@ func (m TeamMutation) Client() *Client { // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. -func (m TeamMutation) Tx() (*Tx, error) { +func (m TeamGroupImageMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { return nil, errors.New("db: mutation is not running in a transaction") } @@ -3608,14 +8521,14 @@ func (m TeamMutation) Tx() (*Tx, error) { } // SetID sets the value of the id field. Note that this -// operation is only accepted on creation of Team entities. -func (m *TeamMutation) SetID(id uuid.UUID) { +// operation is only accepted on creation of TeamGroupImage entities. +func (m *TeamGroupImageMutation) 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 *TeamMutation) ID() (id uuid.UUID, exists bool) { +func (m *TeamGroupImageMutation) ID() (id uuid.UUID, exists bool) { if m.id == nil { return } @@ -3626,7 +8539,7 @@ func (m *TeamMutation) ID() (id uuid.UUID, exists bool) { // 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 *TeamMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { +func (m *TeamGroupImageMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { switch { case m.op.Is(OpUpdateOne | OpDeleteOne): id, exists := m.ID() @@ -3635,160 +8548,91 @@ func (m *TeamMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { } fallthrough case m.op.Is(OpUpdate | OpDelete): - return m.Client().Team.Query().Where(m.predicates...).IDs(ctx) + return m.Client().TeamGroupImage.Query().Where(m.predicates...).IDs(ctx) default: return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } } -// SetDeletedAt sets the "deleted_at" field. -func (m *TeamMutation) SetDeletedAt(t time.Time) { - m.deleted_at = &t -} - -// DeletedAt returns the value of the "deleted_at" field in the mutation. -func (m *TeamMutation) DeletedAt() (r time.Time, exists bool) { - v := m.deleted_at - if v == nil { - return - } - return *v, true -} - -// OldDeletedAt returns the old "deleted_at" field's value of the Team entity. -// If the Team 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 *TeamMutation) OldDeletedAt(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldDeletedAt requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldDeletedAt: %w", err) - } - return oldValue.DeletedAt, nil -} - -// ClearDeletedAt clears the value of the "deleted_at" field. -func (m *TeamMutation) ClearDeletedAt() { - m.deleted_at = nil - m.clearedFields[team.FieldDeletedAt] = struct{}{} -} - -// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. -func (m *TeamMutation) DeletedAtCleared() bool { - _, ok := m.clearedFields[team.FieldDeletedAt] - return ok -} - -// ResetDeletedAt resets all changes to the "deleted_at" field. -func (m *TeamMutation) ResetDeletedAt() { - m.deleted_at = nil - delete(m.clearedFields, team.FieldDeletedAt) -} - -// SetName sets the "name" field. -func (m *TeamMutation) SetName(s string) { - m.name = &s +// SetGroupID sets the "group_id" field. +func (m *TeamGroupImageMutation) SetGroupID(u uuid.UUID) { + m.group = &u } -// Name returns the value of the "name" field in the mutation. -func (m *TeamMutation) Name() (r string, exists bool) { - v := m.name +// GroupID returns the value of the "group_id" field in the mutation. +func (m *TeamGroupImageMutation) GroupID() (r uuid.UUID, exists bool) { + v := m.group if v == nil { return } return *v, true } -// OldName returns the old "name" field's value of the Team entity. -// If the Team object wasn't provided to the builder, the object is fetched from the database. +// OldGroupID returns the old "group_id" field's value of the TeamGroupImage entity. +// If the TeamGroupImage 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 *TeamMutation) OldName(ctx context.Context) (v string, err error) { +func (m *TeamGroupImageMutation) OldGroupID(ctx context.Context) (v uuid.UUID, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldName is only allowed on UpdateOne operations") + return v, errors.New("OldGroupID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldName requires an ID field in the mutation") + return v, errors.New("OldGroupID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldName: %w", err) + return v, fmt.Errorf("querying old value for OldGroupID: %w", err) } - return oldValue.Name, nil + return oldValue.GroupID, nil } -// ResetName resets all changes to the "name" field. -func (m *TeamMutation) ResetName() { - m.name = nil +// ResetGroupID resets all changes to the "group_id" field. +func (m *TeamGroupImageMutation) ResetGroupID() { + m.group = nil } -// SetMemberLimit sets the "member_limit" field. -func (m *TeamMutation) SetMemberLimit(i int) { - m.member_limit = &i - m.addmember_limit = nil +// SetImageID sets the "image_id" field. +func (m *TeamGroupImageMutation) SetImageID(u uuid.UUID) { + m.image = &u } -// MemberLimit returns the value of the "member_limit" field in the mutation. -func (m *TeamMutation) MemberLimit() (r int, exists bool) { - v := m.member_limit +// ImageID returns the value of the "image_id" field in the mutation. +func (m *TeamGroupImageMutation) ImageID() (r uuid.UUID, exists bool) { + v := m.image if v == nil { return } return *v, true } -// OldMemberLimit returns the old "member_limit" field's value of the Team entity. -// If the Team object wasn't provided to the builder, the object is fetched from the database. +// OldImageID returns the old "image_id" field's value of the TeamGroupImage entity. +// If the TeamGroupImage 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 *TeamMutation) OldMemberLimit(ctx context.Context) (v int, err error) { +func (m *TeamGroupImageMutation) OldImageID(ctx context.Context) (v uuid.UUID, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldMemberLimit is only allowed on UpdateOne operations") + return v, errors.New("OldImageID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldMemberLimit requires an ID field in the mutation") + return v, errors.New("OldImageID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldMemberLimit: %w", err) - } - return oldValue.MemberLimit, nil -} - -// AddMemberLimit adds i to the "member_limit" field. -func (m *TeamMutation) AddMemberLimit(i int) { - if m.addmember_limit != nil { - *m.addmember_limit += i - } else { - m.addmember_limit = &i - } -} - -// AddedMemberLimit returns the value that was added to the "member_limit" field in this mutation. -func (m *TeamMutation) AddedMemberLimit() (r int, exists bool) { - v := m.addmember_limit - if v == nil { - return + return v, fmt.Errorf("querying old value for OldImageID: %w", err) } - return *v, true + return oldValue.ImageID, nil } -// ResetMemberLimit resets all changes to the "member_limit" field. -func (m *TeamMutation) ResetMemberLimit() { - m.member_limit = nil - m.addmember_limit = nil +// ResetImageID resets all changes to the "image_id" field. +func (m *TeamGroupImageMutation) ResetImageID() { + m.image = nil } // SetCreatedAt sets the "created_at" field. -func (m *TeamMutation) SetCreatedAt(t time.Time) { +func (m *TeamGroupImageMutation) SetCreatedAt(t time.Time) { m.created_at = &t } // CreatedAt returns the value of the "created_at" field in the mutation. -func (m *TeamMutation) CreatedAt() (r time.Time, exists bool) { +func (m *TeamGroupImageMutation) CreatedAt() (r time.Time, exists bool) { v := m.created_at if v == nil { return @@ -3796,10 +8640,10 @@ func (m *TeamMutation) CreatedAt() (r time.Time, exists bool) { return *v, true } -// OldCreatedAt returns the old "created_at" field's value of the Team entity. -// If the Team object wasn't provided to the builder, the object is fetched from the database. +// OldCreatedAt returns the old "created_at" field's value of the TeamGroupImage entity. +// If the TeamGroupImage 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 *TeamMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { +func (m *TeamGroupImageMutation) 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") } @@ -3814,433 +8658,613 @@ func (m *TeamMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error } // ResetCreatedAt resets all changes to the "created_at" field. -func (m *TeamMutation) ResetCreatedAt() { +func (m *TeamGroupImageMutation) ResetCreatedAt() { m.created_at = nil } -// SetUpdatedAt sets the "updated_at" field. -func (m *TeamMutation) SetUpdatedAt(t time.Time) { - m.updated_at = &t +// ClearGroup clears the "group" edge to the TeamGroup entity. +func (m *TeamGroupImageMutation) ClearGroup() { + m.clearedgroup = true + m.clearedFields[teamgroupimage.FieldGroupID] = struct{}{} } -// UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *TeamMutation) UpdatedAt() (r time.Time, exists bool) { - v := m.updated_at - if v == nil { - return - } - return *v, true +// GroupCleared reports if the "group" edge to the TeamGroup entity was cleared. +func (m *TeamGroupImageMutation) GroupCleared() bool { + return m.clearedgroup } -// OldUpdatedAt returns the old "updated_at" field's value of the Team entity. -// If the Team 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 *TeamMutation) 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) +// 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 *TeamGroupImageMutation) GroupIDs() (ids []uuid.UUID) { + if id := m.group; id != nil { + ids = append(ids, *id) } - return oldValue.UpdatedAt, nil + return } -// ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *TeamMutation) ResetUpdatedAt() { - m.updated_at = nil +// ResetGroup resets all changes to the "group" edge. +func (m *TeamGroupImageMutation) ResetGroup() { + m.group = nil + m.clearedgroup = false } -// AddGroupIDs adds the "groups" edge to the TeamGroup entity by ids. -func (m *TeamMutation) AddGroupIDs(ids ...uuid.UUID) { - if m.groups == nil { - m.groups = make(map[uuid.UUID]struct{}) +// ClearImage clears the "image" edge to the Image entity. +func (m *TeamGroupImageMutation) ClearImage() { + m.clearedimage = true + m.clearedFields[teamgroupimage.FieldImageID] = struct{}{} +} + +// ImageCleared reports if the "image" edge to the Image entity was cleared. +func (m *TeamGroupImageMutation) ImageCleared() bool { + return m.clearedimage +} + +// ImageIDs returns the "image" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// ImageID instead. It exists only for internal usage by the builders. +func (m *TeamGroupImageMutation) ImageIDs() (ids []uuid.UUID) { + if id := m.image; id != nil { + ids = append(ids, *id) } - for i := range ids { - m.groups[ids[i]] = struct{}{} + return +} + +// ResetImage resets all changes to the "image" edge. +func (m *TeamGroupImageMutation) ResetImage() { + m.image = nil + m.clearedimage = false +} + +// Where appends a list predicates to the TeamGroupImageMutation builder. +func (m *TeamGroupImageMutation) Where(ps ...predicate.TeamGroupImage) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the TeamGroupImageMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *TeamGroupImageMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.TeamGroupImage, len(ps)) + for i := range ps { + p[i] = ps[i] } + m.Where(p...) } -// ClearGroups clears the "groups" edge to the TeamGroup entity. -func (m *TeamMutation) ClearGroups() { - m.clearedgroups = true +// Op returns the operation name. +func (m *TeamGroupImageMutation) Op() Op { + return m.op } -// GroupsCleared reports if the "groups" edge to the TeamGroup entity was cleared. -func (m *TeamMutation) GroupsCleared() bool { - return m.clearedgroups +// SetOp allows setting the mutation operation. +func (m *TeamGroupImageMutation) SetOp(op Op) { + m.op = op } -// RemoveGroupIDs removes the "groups" edge to the TeamGroup entity by IDs. -func (m *TeamMutation) RemoveGroupIDs(ids ...uuid.UUID) { - if m.removedgroups == nil { - m.removedgroups = make(map[uuid.UUID]struct{}) +// Type returns the node type of this mutation (TeamGroupImage). +func (m *TeamGroupImageMutation) 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 *TeamGroupImageMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.group != nil { + fields = append(fields, teamgroupimage.FieldGroupID) } - for i := range ids { - delete(m.groups, ids[i]) - m.removedgroups[ids[i]] = struct{}{} + if m.image != nil { + fields = append(fields, teamgroupimage.FieldImageID) } + if m.created_at != nil { + fields = append(fields, teamgroupimage.FieldCreatedAt) + } + return fields } -// RemovedGroups returns the removed IDs of the "groups" edge to the TeamGroup entity. -func (m *TeamMutation) RemovedGroupsIDs() (ids []uuid.UUID) { - for id := range m.removedgroups { - ids = append(ids, id) +// 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 *TeamGroupImageMutation) Field(name string) (ent.Value, bool) { + switch name { + case teamgroupimage.FieldGroupID: + return m.GroupID() + case teamgroupimage.FieldImageID: + return m.ImageID() + case teamgroupimage.FieldCreatedAt: + return m.CreatedAt() } - return + return nil, false } -// GroupsIDs returns the "groups" edge IDs in the mutation. -func (m *TeamMutation) GroupsIDs() (ids []uuid.UUID) { - for id := range m.groups { - ids = append(ids, id) +// 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 *TeamGroupImageMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case teamgroupimage.FieldGroupID: + return m.OldGroupID(ctx) + case teamgroupimage.FieldImageID: + return m.OldImageID(ctx) + case teamgroupimage.FieldCreatedAt: + return m.OldCreatedAt(ctx) } - return + return nil, fmt.Errorf("unknown TeamGroupImage field %s", name) } -// ResetGroups resets all changes to the "groups" edge. -func (m *TeamMutation) ResetGroups() { - m.groups = nil - m.clearedgroups = false - m.removedgroups = nil +// 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 *TeamGroupImageMutation) SetField(name string, value ent.Value) error { + switch name { + case teamgroupimage.FieldGroupID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetGroupID(v) + return nil + case teamgroupimage.FieldImageID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetImageID(v) + return nil + case teamgroupimage.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + } + return fmt.Errorf("unknown TeamGroupImage field %s", name) } -// AddMemberIDs adds the "members" edge to the User entity by ids. -func (m *TeamMutation) AddMemberIDs(ids ...uuid.UUID) { - if m.members == nil { - m.members = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.members[ids[i]] = struct{}{} +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *TeamGroupImageMutation) AddedFields() []string { + return nil +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *TeamGroupImageMutation) AddedField(name string) (ent.Value, bool) { + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *TeamGroupImageMutation) AddField(name string, value ent.Value) error { + switch name { } + return fmt.Errorf("unknown TeamGroupImage numeric field %s", name) } -// ClearMembers clears the "members" edge to the User entity. -func (m *TeamMutation) ClearMembers() { - m.clearedmembers = true +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *TeamGroupImageMutation) ClearedFields() []string { + return nil } -// MembersCleared reports if the "members" edge to the User entity was cleared. -func (m *TeamMutation) MembersCleared() bool { - return m.clearedmembers +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *TeamGroupImageMutation) 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 *TeamGroupImageMutation) ClearField(name string) error { + return fmt.Errorf("unknown TeamGroupImage 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 *TeamGroupImageMutation) ResetField(name string) error { + switch name { + case teamgroupimage.FieldGroupID: + m.ResetGroupID() + return nil + case teamgroupimage.FieldImageID: + m.ResetImageID() + return nil + case teamgroupimage.FieldCreatedAt: + m.ResetCreatedAt() + return nil + } + return fmt.Errorf("unknown TeamGroupImage field %s", name) } -// RemoveMemberIDs removes the "members" edge to the User entity by IDs. -func (m *TeamMutation) RemoveMemberIDs(ids ...uuid.UUID) { - if m.removedmembers == nil { - m.removedmembers = make(map[uuid.UUID]struct{}) +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *TeamGroupImageMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.group != nil { + edges = append(edges, teamgroupimage.EdgeGroup) } - for i := range ids { - delete(m.members, ids[i]) - m.removedmembers[ids[i]] = struct{}{} + if m.image != nil { + edges = append(edges, teamgroupimage.EdgeImage) } + return edges } -// RemovedMembers returns the removed IDs of the "members" edge to the User entity. -func (m *TeamMutation) RemovedMembersIDs() (ids []uuid.UUID) { - for id := range m.removedmembers { - ids = append(ids, id) +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *TeamGroupImageMutation) AddedIDs(name string) []ent.Value { + switch name { + case teamgroupimage.EdgeGroup: + if id := m.group; id != nil { + return []ent.Value{*id} + } + case teamgroupimage.EdgeImage: + if id := m.image; id != nil { + return []ent.Value{*id} + } } - return + return nil } -// MembersIDs returns the "members" edge IDs in the mutation. -func (m *TeamMutation) MembersIDs() (ids []uuid.UUID) { - for id := range m.members { - ids = append(ids, id) - } - return +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *TeamGroupImageMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + return edges } -// ResetMembers resets all changes to the "members" edge. -func (m *TeamMutation) ResetMembers() { - m.members = nil - m.clearedmembers = false - m.removedmembers = nil +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *TeamGroupImageMutation) RemovedIDs(name string) []ent.Value { + return nil } -// AddModelIDs adds the "models" edge to the Model entity by ids. -func (m *TeamMutation) AddModelIDs(ids ...uuid.UUID) { - if m.models == nil { - m.models = make(map[uuid.UUID]struct{}) +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *TeamGroupImageMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedgroup { + edges = append(edges, teamgroupimage.EdgeGroup) } - for i := range ids { - m.models[ids[i]] = struct{}{} + if m.clearedimage { + edges = append(edges, teamgroupimage.EdgeImage) } + return edges } -// ClearModels clears the "models" edge to the Model entity. -func (m *TeamMutation) ClearModels() { - m.clearedmodels = true -} - -// ModelsCleared reports if the "models" edge to the Model entity was cleared. -func (m *TeamMutation) ModelsCleared() bool { - return m.clearedmodels -} - -// RemoveModelIDs removes the "models" edge to the Model entity by IDs. -func (m *TeamMutation) RemoveModelIDs(ids ...uuid.UUID) { - if m.removedmodels == nil { - m.removedmodels = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.models, ids[i]) - m.removedmodels[ids[i]] = struct{}{} +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *TeamGroupImageMutation) EdgeCleared(name string) bool { + switch name { + case teamgroupimage.EdgeGroup: + return m.clearedgroup + case teamgroupimage.EdgeImage: + return m.clearedimage } + return false } -// RemovedModels returns the removed IDs of the "models" edge to the Model entity. -func (m *TeamMutation) RemovedModelsIDs() (ids []uuid.UUID) { - for id := range m.removedmodels { - ids = append(ids, id) +// 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 *TeamGroupImageMutation) ClearEdge(name string) error { + switch name { + case teamgroupimage.EdgeGroup: + m.ClearGroup() + return nil + case teamgroupimage.EdgeImage: + m.ClearImage() + return nil } - return + return fmt.Errorf("unknown TeamGroupImage unique edge %s", name) } -// ModelsIDs returns the "models" edge IDs in the mutation. -func (m *TeamMutation) ModelsIDs() (ids []uuid.UUID) { - for id := range m.models { - ids = append(ids, id) +// 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 *TeamGroupImageMutation) ResetEdge(name string) error { + switch name { + case teamgroupimage.EdgeGroup: + m.ResetGroup() + return nil + case teamgroupimage.EdgeImage: + m.ResetImage() + return nil } - return + return fmt.Errorf("unknown TeamGroupImage edge %s", name) } -// ResetModels resets all changes to the "models" edge. -func (m *TeamMutation) ResetModels() { - m.models = nil - m.clearedmodels = false - m.removedmodels = nil +// TeamGroupMemberMutation represents an operation that mutates the TeamGroupMember nodes in the graph. +type TeamGroupMemberMutation struct { + config + op Op + typ string + id *uuid.UUID + created_at *time.Time + clearedFields map[string]struct{} + group *uuid.UUID + clearedgroup bool + user *uuid.UUID + cleareduser bool + done bool + oldValue func(context.Context) (*TeamGroupMember, error) + predicates []predicate.TeamGroupMember } -// AddImageIDs adds the "images" edge to the Image entity by ids. -func (m *TeamMutation) AddImageIDs(ids ...uuid.UUID) { - if m.images == nil { - m.images = make(map[uuid.UUID]struct{}) +var _ ent.Mutation = (*TeamGroupMemberMutation)(nil) + +// teamgroupmemberOption allows management of the mutation configuration using functional options. +type teamgroupmemberOption func(*TeamGroupMemberMutation) + +// newTeamGroupMemberMutation creates new mutation for the TeamGroupMember entity. +func newTeamGroupMemberMutation(c config, op Op, opts ...teamgroupmemberOption) *TeamGroupMemberMutation { + m := &TeamGroupMemberMutation{ + config: c, + op: op, + typ: TypeTeamGroupMember, + clearedFields: make(map[string]struct{}), } - for i := range ids { - m.images[ids[i]] = struct{}{} + for _, opt := range opts { + opt(m) } + return m } -// ClearImages clears the "images" edge to the Image entity. -func (m *TeamMutation) ClearImages() { - m.clearedimages = true +// withTeamGroupMemberID sets the ID field of the mutation. +func withTeamGroupMemberID(id uuid.UUID) teamgroupmemberOption { + return func(m *TeamGroupMemberMutation) { + var ( + err error + once sync.Once + value *TeamGroupMember + ) + m.oldValue = func(ctx context.Context) (*TeamGroupMember, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().TeamGroupMember.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } } -// ImagesCleared reports if the "images" edge to the Image entity was cleared. -func (m *TeamMutation) ImagesCleared() bool { - return m.clearedimages +// withTeamGroupMember sets the old TeamGroupMember of the mutation. +func withTeamGroupMember(node *TeamGroupMember) teamgroupmemberOption { + return func(m *TeamGroupMemberMutation) { + m.oldValue = func(context.Context) (*TeamGroupMember, error) { + return node, nil + } + m.id = &node.ID + } } -// RemoveImageIDs removes the "images" edge to the Image entity by IDs. -func (m *TeamMutation) RemoveImageIDs(ids ...uuid.UUID) { - if m.removedimages == nil { - m.removedimages = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.images, ids[i]) - m.removedimages[ids[i]] = struct{}{} - } +// 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 TeamGroupMemberMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client } -// RemovedImages returns the removed IDs of the "images" edge to the Image entity. -func (m *TeamMutation) RemovedImagesIDs() (ids []uuid.UUID) { - for id := range m.removedimages { - ids = append(ids, id) +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m TeamGroupMemberMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("db: mutation is not running in a transaction") } - return + tx := &Tx{config: m.config} + tx.init() + return tx, nil } -// ImagesIDs returns the "images" edge IDs in the mutation. -func (m *TeamMutation) ImagesIDs() (ids []uuid.UUID) { - for id := range m.images { - ids = append(ids, id) - } - return +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of TeamGroupMember entities. +func (m *TeamGroupMemberMutation) SetID(id uuid.UUID) { + m.id = &id } -// ResetImages resets all changes to the "images" edge. -func (m *TeamMutation) ResetImages() { - m.images = nil - m.clearedimages = false - m.removedimages = nil +// 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 *TeamGroupMemberMutation) ID() (id uuid.UUID, exists bool) { + if m.id == nil { + return + } + return *m.id, true } -// AddTeamMemberIDs adds the "team_members" edge to the TeamMember entity by ids. -func (m *TeamMutation) AddTeamMemberIDs(ids ...uuid.UUID) { - if m.team_members == nil { - m.team_members = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.team_members[ids[i]] = struct{}{} +// 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 *TeamGroupMemberMutation) 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().TeamGroupMember.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } } -// ClearTeamMembers clears the "team_members" edge to the TeamMember entity. -func (m *TeamMutation) ClearTeamMembers() { - m.clearedteam_members = true +// SetGroupID sets the "group_id" field. +func (m *TeamGroupMemberMutation) SetGroupID(u uuid.UUID) { + m.group = &u } -// TeamMembersCleared reports if the "team_members" edge to the TeamMember entity was cleared. -func (m *TeamMutation) TeamMembersCleared() bool { - return m.clearedteam_members +// GroupID returns the value of the "group_id" field in the mutation. +func (m *TeamGroupMemberMutation) GroupID() (r uuid.UUID, exists bool) { + v := m.group + if v == nil { + return + } + return *v, true } -// RemoveTeamMemberIDs removes the "team_members" edge to the TeamMember entity by IDs. -func (m *TeamMutation) RemoveTeamMemberIDs(ids ...uuid.UUID) { - if m.removedteam_members == nil { - m.removedteam_members = make(map[uuid.UUID]struct{}) +// OldGroupID returns the old "group_id" field's value of the TeamGroupMember entity. +// If the TeamGroupMember 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 *TeamGroupMemberMutation) OldGroupID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldGroupID is only allowed on UpdateOne operations") } - for i := range ids { - delete(m.team_members, ids[i]) - m.removedteam_members[ids[i]] = struct{}{} + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldGroupID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldGroupID: %w", err) } + return oldValue.GroupID, nil } -// RemovedTeamMembers returns the removed IDs of the "team_members" edge to the TeamMember entity. -func (m *TeamMutation) RemovedTeamMembersIDs() (ids []uuid.UUID) { - for id := range m.removedteam_members { - ids = append(ids, id) - } - return +// ResetGroupID resets all changes to the "group_id" field. +func (m *TeamGroupMemberMutation) ResetGroupID() { + m.group = nil } -// TeamMembersIDs returns the "team_members" edge IDs in the mutation. -func (m *TeamMutation) TeamMembersIDs() (ids []uuid.UUID) { - for id := range m.team_members { - ids = append(ids, id) - } - return +// SetUserID sets the "user_id" field. +func (m *TeamGroupMemberMutation) SetUserID(u uuid.UUID) { + m.user = &u } -// ResetTeamMembers resets all changes to the "team_members" edge. -func (m *TeamMutation) ResetTeamMembers() { - m.team_members = nil - m.clearedteam_members = false - m.removedteam_members = nil +// UserID returns the value of the "user_id" field in the mutation. +func (m *TeamGroupMemberMutation) UserID() (r uuid.UUID, exists bool) { + v := m.user + if v == nil { + return + } + return *v, true } -// AddTeamModelIDs adds the "team_models" edge to the TeamModel entity by ids. -func (m *TeamMutation) AddTeamModelIDs(ids ...uuid.UUID) { - if m.team_models == nil { - m.team_models = make(map[uuid.UUID]struct{}) +// OldUserID returns the old "user_id" field's value of the TeamGroupMember entity. +// If the TeamGroupMember 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 *TeamGroupMemberMutation) OldUserID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUserID is only allowed on UpdateOne operations") } - for i := range ids { - m.team_models[ids[i]] = struct{}{} + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUserID requires an ID field in the mutation") } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUserID: %w", err) + } + return oldValue.UserID, nil } -// ClearTeamModels clears the "team_models" edge to the TeamModel entity. -func (m *TeamMutation) ClearTeamModels() { - m.clearedteam_models = true +// ResetUserID resets all changes to the "user_id" field. +func (m *TeamGroupMemberMutation) ResetUserID() { + m.user = nil } -// TeamModelsCleared reports if the "team_models" edge to the TeamModel entity was cleared. -func (m *TeamMutation) TeamModelsCleared() bool { - return m.clearedteam_models +// SetCreatedAt sets the "created_at" field. +func (m *TeamGroupMemberMutation) SetCreatedAt(t time.Time) { + m.created_at = &t } -// RemoveTeamModelIDs removes the "team_models" edge to the TeamModel entity by IDs. -func (m *TeamMutation) RemoveTeamModelIDs(ids ...uuid.UUID) { - if m.removedteam_models == nil { - m.removedteam_models = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.team_models, ids[i]) - m.removedteam_models[ids[i]] = struct{}{} +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *TeamGroupMemberMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return } + return *v, true } -// RemovedTeamModels returns the removed IDs of the "team_models" edge to the TeamModel entity. -func (m *TeamMutation) RemovedTeamModelsIDs() (ids []uuid.UUID) { - for id := range m.removedteam_models { - ids = append(ids, id) +// OldCreatedAt returns the old "created_at" field's value of the TeamGroupMember entity. +// If the TeamGroupMember 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 *TeamGroupMemberMutation) 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") } - return + 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 } -// TeamModelsIDs returns the "team_models" edge IDs in the mutation. -func (m *TeamMutation) TeamModelsIDs() (ids []uuid.UUID) { - for id := range m.team_models { - ids = append(ids, id) - } - return +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *TeamGroupMemberMutation) ResetCreatedAt() { + m.created_at = nil } -// ResetTeamModels resets all changes to the "team_models" edge. -func (m *TeamMutation) ResetTeamModels() { - m.team_models = nil - m.clearedteam_models = false - m.removedteam_models = nil +// ClearGroup clears the "group" edge to the TeamGroup entity. +func (m *TeamGroupMemberMutation) ClearGroup() { + m.clearedgroup = true + m.clearedFields[teamgroupmember.FieldGroupID] = struct{}{} } -// AddTeamImageIDs adds the "team_images" edge to the TeamImage entity by ids. -func (m *TeamMutation) AddTeamImageIDs(ids ...uuid.UUID) { - if m.team_images == nil { - m.team_images = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.team_images[ids[i]] = struct{}{} - } +// GroupCleared reports if the "group" edge to the TeamGroup entity was cleared. +func (m *TeamGroupMemberMutation) GroupCleared() bool { + return m.clearedgroup } -// ClearTeamImages clears the "team_images" edge to the TeamImage entity. -func (m *TeamMutation) ClearTeamImages() { - m.clearedteam_images = true +// 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 *TeamGroupMemberMutation) GroupIDs() (ids []uuid.UUID) { + if id := m.group; id != nil { + ids = append(ids, *id) + } + return } -// TeamImagesCleared reports if the "team_images" edge to the TeamImage entity was cleared. -func (m *TeamMutation) TeamImagesCleared() bool { - return m.clearedteam_images +// ResetGroup resets all changes to the "group" edge. +func (m *TeamGroupMemberMutation) ResetGroup() { + m.group = nil + m.clearedgroup = false } -// RemoveTeamImageIDs removes the "team_images" edge to the TeamImage entity by IDs. -func (m *TeamMutation) RemoveTeamImageIDs(ids ...uuid.UUID) { - if m.removedteam_images == nil { - m.removedteam_images = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.team_images, ids[i]) - m.removedteam_images[ids[i]] = struct{}{} - } +// ClearUser clears the "user" edge to the User entity. +func (m *TeamGroupMemberMutation) ClearUser() { + m.cleareduser = true + m.clearedFields[teamgroupmember.FieldUserID] = struct{}{} } -// RemovedTeamImages returns the removed IDs of the "team_images" edge to the TeamImage entity. -func (m *TeamMutation) RemovedTeamImagesIDs() (ids []uuid.UUID) { - for id := range m.removedteam_images { - ids = append(ids, id) - } - return +// UserCleared reports if the "user" edge to the User entity was cleared. +func (m *TeamGroupMemberMutation) UserCleared() bool { + return m.cleareduser } -// TeamImagesIDs returns the "team_images" edge IDs in the mutation. -func (m *TeamMutation) TeamImagesIDs() (ids []uuid.UUID) { - for id := range m.team_images { - ids = append(ids, id) +// UserIDs returns the "user" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UserID instead. It exists only for internal usage by the builders. +func (m *TeamGroupMemberMutation) UserIDs() (ids []uuid.UUID) { + if id := m.user; id != nil { + ids = append(ids, *id) } return } -// ResetTeamImages resets all changes to the "team_images" edge. -func (m *TeamMutation) ResetTeamImages() { - m.team_images = nil - m.clearedteam_images = false - m.removedteam_images = nil +// ResetUser resets all changes to the "user" edge. +func (m *TeamGroupMemberMutation) ResetUser() { + m.user = nil + m.cleareduser = false } -// Where appends a list predicates to the TeamMutation builder. -func (m *TeamMutation) Where(ps ...predicate.Team) { +// Where appends a list predicates to the TeamGroupMemberMutation builder. +func (m *TeamGroupMemberMutation) Where(ps ...predicate.TeamGroupMember) { m.predicates = append(m.predicates, ps...) } -// WhereP appends storage-level predicates to the TeamMutation builder. Using this method, +// WhereP appends storage-level predicates to the TeamGroupMemberMutation builder. Using this method, // users can use type-assertion to append predicates that do not depend on any generated package. -func (m *TeamMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.Team, len(ps)) +func (m *TeamGroupMemberMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.TeamGroupMember, len(ps)) for i := range ps { p[i] = ps[i] } @@ -4248,39 +9272,33 @@ func (m *TeamMutation) WhereP(ps ...func(*sql.Selector)) { } // Op returns the operation name. -func (m *TeamMutation) Op() Op { +func (m *TeamGroupMemberMutation) Op() Op { return m.op } // SetOp allows setting the mutation operation. -func (m *TeamMutation) SetOp(op Op) { +func (m *TeamGroupMemberMutation) SetOp(op Op) { m.op = op } -// Type returns the node type of this mutation (Team). -func (m *TeamMutation) Type() string { +// Type returns the node type of this mutation (TeamGroupMember). +func (m *TeamGroupMemberMutation) 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 *TeamMutation) Fields() []string { - fields := make([]string, 0, 5) - if m.deleted_at != nil { - fields = append(fields, team.FieldDeletedAt) - } - if m.name != nil { - fields = append(fields, team.FieldName) +func (m *TeamGroupMemberMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.group != nil { + fields = append(fields, teamgroupmember.FieldGroupID) } - if m.member_limit != nil { - fields = append(fields, team.FieldMemberLimit) + if m.user != nil { + fields = append(fields, teamgroupmember.FieldUserID) } if m.created_at != nil { - fields = append(fields, team.FieldCreatedAt) - } - if m.updated_at != nil { - fields = append(fields, team.FieldUpdatedAt) + fields = append(fields, teamgroupmember.FieldCreatedAt) } return fields } @@ -4288,18 +9306,14 @@ func (m *TeamMutation) Fields() []string { // 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 *TeamMutation) Field(name string) (ent.Value, bool) { +func (m *TeamGroupMemberMutation) Field(name string) (ent.Value, bool) { switch name { - case team.FieldDeletedAt: - return m.DeletedAt() - case team.FieldName: - return m.Name() - case team.FieldMemberLimit: - return m.MemberLimit() - case team.FieldCreatedAt: + case teamgroupmember.FieldGroupID: + return m.GroupID() + case teamgroupmember.FieldUserID: + return m.UserID() + case teamgroupmember.FieldCreatedAt: return m.CreatedAt() - case team.FieldUpdatedAt: - return m.UpdatedAt() } return nil, false } @@ -4307,441 +9321,226 @@ func (m *TeamMutation) Field(name string) (ent.Value, bool) { // 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 *TeamMutation) OldField(ctx context.Context, name string) (ent.Value, error) { +func (m *TeamGroupMemberMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { - case team.FieldDeletedAt: - return m.OldDeletedAt(ctx) - case team.FieldName: - return m.OldName(ctx) - case team.FieldMemberLimit: - return m.OldMemberLimit(ctx) - case team.FieldCreatedAt: + case teamgroupmember.FieldGroupID: + return m.OldGroupID(ctx) + case teamgroupmember.FieldUserID: + return m.OldUserID(ctx) + case teamgroupmember.FieldCreatedAt: return m.OldCreatedAt(ctx) - case team.FieldUpdatedAt: - return m.OldUpdatedAt(ctx) } - return nil, fmt.Errorf("unknown Team field %s", name) + return nil, fmt.Errorf("unknown TeamGroupMember 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 *TeamMutation) SetField(name string, value ent.Value) error { +func (m *TeamGroupMemberMutation) SetField(name string, value ent.Value) error { switch name { - case team.FieldDeletedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetDeletedAt(v) - return nil - case team.FieldName: - v, ok := value.(string) + case teamgroupmember.FieldGroupID: + v, ok := value.(uuid.UUID) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetName(v) + m.SetGroupID(v) return nil - case team.FieldMemberLimit: - v, ok := value.(int) + case teamgroupmember.FieldUserID: + v, ok := value.(uuid.UUID) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetMemberLimit(v) + m.SetUserID(v) return nil - case team.FieldCreatedAt: + case teamgroupmember.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 team.FieldUpdatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUpdatedAt(v) - return nil } - return fmt.Errorf("unknown Team field %s", name) + return fmt.Errorf("unknown TeamGroupMember field %s", name) } // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. -func (m *TeamMutation) AddedFields() []string { - var fields []string - if m.addmember_limit != nil { - fields = append(fields, team.FieldMemberLimit) - } - return fields +func (m *TeamGroupMemberMutation) AddedFields() []string { + return nil } // AddedField returns the numeric value that was incremented/decremented on a field // with the given name. The second boolean return value indicates that this field // was not set, or was not defined in the schema. -func (m *TeamMutation) AddedField(name string) (ent.Value, bool) { - switch name { - case team.FieldMemberLimit: - return m.AddedMemberLimit() - } +func (m *TeamGroupMemberMutation) AddedField(name string) (ent.Value, bool) { return nil, false } // AddField adds the value to the field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *TeamMutation) AddField(name string, value ent.Value) error { +func (m *TeamGroupMemberMutation) AddField(name string, value ent.Value) error { switch name { - case team.FieldMemberLimit: - v, ok := value.(int) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.AddMemberLimit(v) - return nil } - return fmt.Errorf("unknown Team numeric field %s", name) + return fmt.Errorf("unknown TeamGroupMember numeric field %s", name) } // ClearedFields returns all nullable fields that were cleared during this // mutation. -func (m *TeamMutation) ClearedFields() []string { - var fields []string - if m.FieldCleared(team.FieldDeletedAt) { - fields = append(fields, team.FieldDeletedAt) - } - return fields +func (m *TeamGroupMemberMutation) ClearedFields() []string { + return nil } // FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. -func (m *TeamMutation) FieldCleared(name string) bool { +func (m *TeamGroupMemberMutation) 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 *TeamMutation) ClearField(name string) error { - switch name { - case team.FieldDeletedAt: - m.ClearDeletedAt() - return nil - } - return fmt.Errorf("unknown Team nullable field %s", name) +func (m *TeamGroupMemberMutation) ClearField(name string) error { + return fmt.Errorf("unknown TeamGroupMember 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 *TeamMutation) ResetField(name string) error { +func (m *TeamGroupMemberMutation) ResetField(name string) error { switch name { - case team.FieldDeletedAt: - m.ResetDeletedAt() - return nil - case team.FieldName: - m.ResetName() + case teamgroupmember.FieldGroupID: + m.ResetGroupID() return nil - case team.FieldMemberLimit: - m.ResetMemberLimit() + case teamgroupmember.FieldUserID: + m.ResetUserID() return nil - case team.FieldCreatedAt: + case teamgroupmember.FieldCreatedAt: m.ResetCreatedAt() return nil - case team.FieldUpdatedAt: - m.ResetUpdatedAt() - return nil } - return fmt.Errorf("unknown Team field %s", name) + return fmt.Errorf("unknown TeamGroupMember field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. -func (m *TeamMutation) AddedEdges() []string { - edges := make([]string, 0, 7) - if m.groups != nil { - edges = append(edges, team.EdgeGroups) - } - if m.members != nil { - edges = append(edges, team.EdgeMembers) - } - if m.models != nil { - edges = append(edges, team.EdgeModels) - } - if m.images != nil { - edges = append(edges, team.EdgeImages) - } - if m.team_members != nil { - edges = append(edges, team.EdgeTeamMembers) - } - if m.team_models != nil { - edges = append(edges, team.EdgeTeamModels) - } - if m.team_images != nil { - edges = append(edges, team.EdgeTeamImages) - } - return edges -} - -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *TeamMutation) AddedIDs(name string) []ent.Value { - switch name { - case team.EdgeGroups: - ids := make([]ent.Value, 0, len(m.groups)) - for id := range m.groups { - ids = append(ids, id) - } - return ids - case team.EdgeMembers: - ids := make([]ent.Value, 0, len(m.members)) - for id := range m.members { - ids = append(ids, id) - } - return ids - case team.EdgeModels: - ids := make([]ent.Value, 0, len(m.models)) - for id := range m.models { - ids = append(ids, id) - } - return ids - case team.EdgeImages: - ids := make([]ent.Value, 0, len(m.images)) - for id := range m.images { - ids = append(ids, id) - } - return ids - case team.EdgeTeamMembers: - ids := make([]ent.Value, 0, len(m.team_members)) - for id := range m.team_members { - ids = append(ids, id) - } - return ids - case team.EdgeTeamModels: - ids := make([]ent.Value, 0, len(m.team_models)) - for id := range m.team_models { - ids = append(ids, id) - } - return ids - case team.EdgeTeamImages: - ids := make([]ent.Value, 0, len(m.team_images)) - for id := range m.team_images { - ids = append(ids, id) - } - return ids - } - return nil -} - -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *TeamMutation) RemovedEdges() []string { - edges := make([]string, 0, 7) - if m.removedgroups != nil { - edges = append(edges, team.EdgeGroups) - } - if m.removedmembers != nil { - edges = append(edges, team.EdgeMembers) - } - if m.removedmodels != nil { - edges = append(edges, team.EdgeModels) - } - if m.removedimages != nil { - edges = append(edges, team.EdgeImages) - } - if m.removedteam_members != nil { - edges = append(edges, team.EdgeTeamMembers) - } - if m.removedteam_models != nil { - edges = append(edges, team.EdgeTeamModels) +func (m *TeamGroupMemberMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.group != nil { + edges = append(edges, teamgroupmember.EdgeGroup) } - if m.removedteam_images != nil { - edges = append(edges, team.EdgeTeamImages) + if m.user != nil { + edges = append(edges, teamgroupmember.EdgeUser) } return edges } -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *TeamMutation) RemovedIDs(name string) []ent.Value { +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *TeamGroupMemberMutation) AddedIDs(name string) []ent.Value { switch name { - case team.EdgeGroups: - ids := make([]ent.Value, 0, len(m.removedgroups)) - for id := range m.removedgroups { - ids = append(ids, id) - } - return ids - case team.EdgeMembers: - ids := make([]ent.Value, 0, len(m.removedmembers)) - for id := range m.removedmembers { - ids = append(ids, id) - } - return ids - case team.EdgeModels: - ids := make([]ent.Value, 0, len(m.removedmodels)) - for id := range m.removedmodels { - ids = append(ids, id) - } - return ids - case team.EdgeImages: - ids := make([]ent.Value, 0, len(m.removedimages)) - for id := range m.removedimages { - ids = append(ids, id) - } - return ids - case team.EdgeTeamMembers: - ids := make([]ent.Value, 0, len(m.removedteam_members)) - for id := range m.removedteam_members { - ids = append(ids, id) - } - return ids - case team.EdgeTeamModels: - ids := make([]ent.Value, 0, len(m.removedteam_models)) - for id := range m.removedteam_models { - ids = append(ids, id) + case teamgroupmember.EdgeGroup: + if id := m.group; id != nil { + return []ent.Value{*id} } - return ids - case team.EdgeTeamImages: - ids := make([]ent.Value, 0, len(m.removedteam_images)) - for id := range m.removedteam_images { - ids = append(ids, id) + case teamgroupmember.EdgeUser: + if id := m.user; id != nil { + return []ent.Value{*id} } - return ids } return nil } +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *TeamGroupMemberMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *TeamGroupMemberMutation) RemovedIDs(name string) []ent.Value { + return nil +} + // ClearedEdges returns all edge names that were cleared in this mutation. -func (m *TeamMutation) ClearedEdges() []string { - edges := make([]string, 0, 7) - if m.clearedgroups { - edges = append(edges, team.EdgeGroups) - } - if m.clearedmembers { - edges = append(edges, team.EdgeMembers) - } - if m.clearedmodels { - edges = append(edges, team.EdgeModels) - } - if m.clearedimages { - edges = append(edges, team.EdgeImages) - } - if m.clearedteam_members { - edges = append(edges, team.EdgeTeamMembers) - } - if m.clearedteam_models { - edges = append(edges, team.EdgeTeamModels) +func (m *TeamGroupMemberMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedgroup { + edges = append(edges, teamgroupmember.EdgeGroup) } - if m.clearedteam_images { - edges = append(edges, team.EdgeTeamImages) + if m.cleareduser { + edges = append(edges, teamgroupmember.EdgeUser) } return edges } // EdgeCleared returns a boolean which indicates if the edge with the given name // was cleared in this mutation. -func (m *TeamMutation) EdgeCleared(name string) bool { +func (m *TeamGroupMemberMutation) EdgeCleared(name string) bool { switch name { - case team.EdgeGroups: - return m.clearedgroups - case team.EdgeMembers: - return m.clearedmembers - case team.EdgeModels: - return m.clearedmodels - case team.EdgeImages: - return m.clearedimages - case team.EdgeTeamMembers: - return m.clearedteam_members - case team.EdgeTeamModels: - return m.clearedteam_models - case team.EdgeTeamImages: - return m.clearedteam_images + case teamgroupmember.EdgeGroup: + return m.clearedgroup + case teamgroupmember.EdgeUser: + return m.cleareduser } 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 *TeamMutation) ClearEdge(name string) error { +func (m *TeamGroupMemberMutation) ClearEdge(name string) error { switch name { + case teamgroupmember.EdgeGroup: + m.ClearGroup() + return nil + case teamgroupmember.EdgeUser: + m.ClearUser() + return nil } - return fmt.Errorf("unknown Team unique edge %s", name) + return fmt.Errorf("unknown TeamGroupMember 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 *TeamMutation) ResetEdge(name string) error { +func (m *TeamGroupMemberMutation) ResetEdge(name string) error { switch name { - case team.EdgeGroups: - m.ResetGroups() - return nil - case team.EdgeMembers: - m.ResetMembers() - return nil - case team.EdgeModels: - m.ResetModels() - return nil - case team.EdgeImages: - m.ResetImages() - return nil - case team.EdgeTeamMembers: - m.ResetTeamMembers() - return nil - case team.EdgeTeamModels: - m.ResetTeamModels() + case teamgroupmember.EdgeGroup: + m.ResetGroup() return nil - case team.EdgeTeamImages: - m.ResetTeamImages() + case teamgroupmember.EdgeUser: + m.ResetUser() return nil } - return fmt.Errorf("unknown Team edge %s", name) + return fmt.Errorf("unknown TeamGroupMember edge %s", name) } -// TeamGroupMutation represents an operation that mutates the TeamGroup nodes in the graph. -type TeamGroupMutation struct { +// TeamGroupModelMutation represents an operation that mutates the TeamGroupModel nodes in the graph. +type TeamGroupModelMutation struct { config - op Op - typ string - id *uuid.UUID - deleted_at *time.Time - name *string - created_at *time.Time - updated_at *time.Time - clearedFields map[string]struct{} - members map[uuid.UUID]struct{} - removedmembers map[uuid.UUID]struct{} - clearedmembers bool - team *uuid.UUID - clearedteam bool - models map[uuid.UUID]struct{} - removedmodels map[uuid.UUID]struct{} - clearedmodels bool - images map[uuid.UUID]struct{} - removedimages map[uuid.UUID]struct{} - clearedimages bool - team_group_members map[uuid.UUID]struct{} - removedteam_group_members map[uuid.UUID]struct{} - clearedteam_group_members bool - team_group_models map[uuid.UUID]struct{} - removedteam_group_models map[uuid.UUID]struct{} - clearedteam_group_models bool - team_group_images map[uuid.UUID]struct{} - removedteam_group_images map[uuid.UUID]struct{} - clearedteam_group_images bool - done bool - oldValue func(context.Context) (*TeamGroup, error) - predicates []predicate.TeamGroup + op Op + typ string + id *uuid.UUID + created_at *time.Time + clearedFields map[string]struct{} + group *uuid.UUID + clearedgroup bool + model *uuid.UUID + clearedmodel bool + done bool + oldValue func(context.Context) (*TeamGroupModel, error) + predicates []predicate.TeamGroupModel } -var _ ent.Mutation = (*TeamGroupMutation)(nil) +var _ ent.Mutation = (*TeamGroupModelMutation)(nil) -// teamgroupOption allows management of the mutation configuration using functional options. -type teamgroupOption func(*TeamGroupMutation) +// teamgroupmodelOption allows management of the mutation configuration using functional options. +type teamgroupmodelOption func(*TeamGroupModelMutation) -// newTeamGroupMutation creates new mutation for the TeamGroup entity. -func newTeamGroupMutation(c config, op Op, opts ...teamgroupOption) *TeamGroupMutation { - m := &TeamGroupMutation{ +// newTeamGroupModelMutation creates new mutation for the TeamGroupModel entity. +func newTeamGroupModelMutation(c config, op Op, opts ...teamgroupmodelOption) *TeamGroupModelMutation { + m := &TeamGroupModelMutation{ config: c, op: op, - typ: TypeTeamGroup, + typ: TypeTeamGroupModel, clearedFields: make(map[string]struct{}), } for _, opt := range opts { @@ -4750,20 +9549,20 @@ func newTeamGroupMutation(c config, op Op, opts ...teamgroupOption) *TeamGroupMu return m } -// withTeamGroupID sets the ID field of the mutation. -func withTeamGroupID(id uuid.UUID) teamgroupOption { - return func(m *TeamGroupMutation) { +// withTeamGroupModelID sets the ID field of the mutation. +func withTeamGroupModelID(id uuid.UUID) teamgroupmodelOption { + return func(m *TeamGroupModelMutation) { var ( err error once sync.Once - value *TeamGroup + value *TeamGroupModel ) - m.oldValue = func(ctx context.Context) (*TeamGroup, error) { + m.oldValue = func(ctx context.Context) (*TeamGroupModel, error) { once.Do(func() { if m.done { err = errors.New("querying old values post mutation is not allowed") } else { - value, err = m.Client().TeamGroup.Get(ctx, id) + value, err = m.Client().TeamGroupModel.Get(ctx, id) } }) return value, err @@ -4772,10 +9571,10 @@ func withTeamGroupID(id uuid.UUID) teamgroupOption { } } -// withTeamGroup sets the old TeamGroup of the mutation. -func withTeamGroup(node *TeamGroup) teamgroupOption { - return func(m *TeamGroupMutation) { - m.oldValue = func(context.Context) (*TeamGroup, error) { +// withTeamGroupModel sets the old TeamGroupModel of the mutation. +func withTeamGroupModel(node *TeamGroupModel) teamgroupmodelOption { + return func(m *TeamGroupModelMutation) { + m.oldValue = func(context.Context) (*TeamGroupModel, error) { return node, nil } m.id = &node.ID @@ -4784,7 +9583,7 @@ func withTeamGroup(node *TeamGroup) teamgroupOption { // 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 TeamGroupMutation) Client() *Client { +func (m TeamGroupModelMutation) Client() *Client { client := &Client{config: m.config} client.init() return client @@ -4792,7 +9591,7 @@ func (m TeamGroupMutation) Client() *Client { // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. -func (m TeamGroupMutation) Tx() (*Tx, error) { +func (m TeamGroupModelMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { return nil, errors.New("db: mutation is not running in a transaction") } @@ -4802,14 +9601,14 @@ func (m TeamGroupMutation) Tx() (*Tx, error) { } // SetID sets the value of the id field. Note that this -// operation is only accepted on creation of TeamGroup entities. -func (m *TeamGroupMutation) SetID(id uuid.UUID) { +// operation is only accepted on creation of TeamGroupModel entities. +func (m *TeamGroupModelMutation) 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 *TeamGroupMutation) ID() (id uuid.UUID, exists bool) { +func (m *TeamGroupModelMutation) ID() (id uuid.UUID, exists bool) { if m.id == nil { return } @@ -4820,7 +9619,7 @@ func (m *TeamGroupMutation) ID() (id uuid.UUID, exists bool) { // 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 *TeamGroupMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { +func (m *TeamGroupModelMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { switch { case m.op.Is(OpUpdateOne | OpDeleteOne): id, exists := m.ID() @@ -4829,565 +9628,723 @@ func (m *TeamGroupMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { } fallthrough case m.op.Is(OpUpdate | OpDelete): - return m.Client().TeamGroup.Query().Where(m.predicates...).IDs(ctx) + return m.Client().TeamGroupModel.Query().Where(m.predicates...).IDs(ctx) default: return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } } -// SetDeletedAt sets the "deleted_at" field. -func (m *TeamGroupMutation) SetDeletedAt(t time.Time) { - m.deleted_at = &t +// SetGroupID sets the "group_id" field. +func (m *TeamGroupModelMutation) SetGroupID(u uuid.UUID) { + m.group = &u } -// DeletedAt returns the value of the "deleted_at" field in the mutation. -func (m *TeamGroupMutation) DeletedAt() (r time.Time, exists bool) { - v := m.deleted_at +// GroupID returns the value of the "group_id" field in the mutation. +func (m *TeamGroupModelMutation) GroupID() (r uuid.UUID, exists bool) { + v := m.group if v == nil { return } return *v, true } -// OldDeletedAt returns the old "deleted_at" field's value of the TeamGroup entity. -// If the TeamGroup object wasn't provided to the builder, the object is fetched from the database. +// OldGroupID returns the old "group_id" field's value of the TeamGroupModel entity. +// If the TeamGroupModel 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 *TeamGroupMutation) OldDeletedAt(ctx context.Context) (v time.Time, err error) { +func (m *TeamGroupModelMutation) OldGroupID(ctx context.Context) (v uuid.UUID, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") + return v, errors.New("OldGroupID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldDeletedAt requires an ID field in the mutation") + return v, errors.New("OldGroupID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldDeletedAt: %w", err) + return v, fmt.Errorf("querying old value for OldGroupID: %w", err) } - return oldValue.DeletedAt, nil -} - -// ClearDeletedAt clears the value of the "deleted_at" field. -func (m *TeamGroupMutation) ClearDeletedAt() { - m.deleted_at = nil - m.clearedFields[teamgroup.FieldDeletedAt] = struct{}{} -} - -// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. -func (m *TeamGroupMutation) DeletedAtCleared() bool { - _, ok := m.clearedFields[teamgroup.FieldDeletedAt] - return ok + return oldValue.GroupID, nil } -// ResetDeletedAt resets all changes to the "deleted_at" field. -func (m *TeamGroupMutation) ResetDeletedAt() { - m.deleted_at = nil - delete(m.clearedFields, teamgroup.FieldDeletedAt) +// ResetGroupID resets all changes to the "group_id" field. +func (m *TeamGroupModelMutation) ResetGroupID() { + m.group = nil } -// SetTeamID sets the "team_id" field. -func (m *TeamGroupMutation) SetTeamID(u uuid.UUID) { - m.team = &u +// SetModelID sets the "model_id" field. +func (m *TeamGroupModelMutation) SetModelID(u uuid.UUID) { + m.model = &u } -// TeamID returns the value of the "team_id" field in the mutation. -func (m *TeamGroupMutation) TeamID() (r uuid.UUID, exists bool) { - v := m.team +// ModelID returns the value of the "model_id" field in the mutation. +func (m *TeamGroupModelMutation) ModelID() (r uuid.UUID, exists bool) { + v := m.model if v == nil { return } return *v, true } -// OldTeamID returns the old "team_id" field's value of the TeamGroup entity. -// If the TeamGroup object wasn't provided to the builder, the object is fetched from the database. +// OldModelID returns the old "model_id" field's value of the TeamGroupModel entity. +// If the TeamGroupModel 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 *TeamGroupMutation) OldTeamID(ctx context.Context) (v uuid.UUID, err error) { +func (m *TeamGroupModelMutation) OldModelID(ctx context.Context) (v uuid.UUID, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldTeamID is only allowed on UpdateOne operations") + return v, errors.New("OldModelID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldTeamID requires an ID field in the mutation") + return v, errors.New("OldModelID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldTeamID: %w", err) + return v, fmt.Errorf("querying old value for OldModelID: %w", err) } - return oldValue.TeamID, nil + return oldValue.ModelID, nil } -// ResetTeamID resets all changes to the "team_id" field. -func (m *TeamGroupMutation) ResetTeamID() { - m.team = nil +// ResetModelID resets all changes to the "model_id" field. +func (m *TeamGroupModelMutation) ResetModelID() { + m.model = nil } -// SetName sets the "name" field. -func (m *TeamGroupMutation) SetName(s string) { - m.name = &s +// SetCreatedAt sets the "created_at" field. +func (m *TeamGroupModelMutation) SetCreatedAt(t time.Time) { + m.created_at = &t } -// Name returns the value of the "name" field in the mutation. -func (m *TeamGroupMutation) Name() (r string, exists bool) { - v := m.name +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *TeamGroupModelMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at if v == nil { return } return *v, true } -// OldName returns the old "name" field's value of the TeamGroup entity. -// If the TeamGroup object wasn't provided to the builder, the object is fetched from the database. +// OldCreatedAt returns the old "created_at" field's value of the TeamGroupModel entity. +// If the TeamGroupModel 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 *TeamGroupMutation) OldName(ctx context.Context) (v string, err error) { +func (m *TeamGroupModelMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldName is only allowed on UpdateOne operations") + return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldName requires an ID field in the mutation") + 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 OldName: %w", err) + 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 *TeamGroupModelMutation) ResetCreatedAt() { + m.created_at = nil +} + +// ClearGroup clears the "group" edge to the TeamGroup entity. +func (m *TeamGroupModelMutation) ClearGroup() { + m.clearedgroup = true + m.clearedFields[teamgroupmodel.FieldGroupID] = struct{}{} +} + +// GroupCleared reports if the "group" edge to the TeamGroup entity was cleared. +func (m *TeamGroupModelMutation) GroupCleared() bool { + return m.clearedgroup +} + +// 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 *TeamGroupModelMutation) 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 *TeamGroupModelMutation) ResetGroup() { + m.group = nil + m.clearedgroup = false +} + +// ClearModel clears the "model" edge to the Model entity. +func (m *TeamGroupModelMutation) ClearModel() { + m.clearedmodel = true + m.clearedFields[teamgroupmodel.FieldModelID] = struct{}{} +} + +// ModelCleared reports if the "model" edge to the Model entity was cleared. +func (m *TeamGroupModelMutation) ModelCleared() bool { + return m.clearedmodel +} + +// ModelIDs returns the "model" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// ModelID instead. It exists only for internal usage by the builders. +func (m *TeamGroupModelMutation) ModelIDs() (ids []uuid.UUID) { + if id := m.model; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetModel resets all changes to the "model" edge. +func (m *TeamGroupModelMutation) ResetModel() { + m.model = nil + m.clearedmodel = false +} + +// Where appends a list predicates to the TeamGroupModelMutation builder. +func (m *TeamGroupModelMutation) Where(ps ...predicate.TeamGroupModel) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the TeamGroupModelMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *TeamGroupModelMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.TeamGroupModel, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *TeamGroupModelMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *TeamGroupModelMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (TeamGroupModel). +func (m *TeamGroupModelMutation) 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 *TeamGroupModelMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.group != nil { + fields = append(fields, teamgroupmodel.FieldGroupID) + } + if m.model != nil { + fields = append(fields, teamgroupmodel.FieldModelID) + } + if m.created_at != nil { + fields = append(fields, teamgroupmodel.FieldCreatedAt) + } + 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 *TeamGroupModelMutation) Field(name string) (ent.Value, bool) { + switch name { + case teamgroupmodel.FieldGroupID: + return m.GroupID() + case teamgroupmodel.FieldModelID: + return m.ModelID() + case teamgroupmodel.FieldCreatedAt: + return m.CreatedAt() + } + 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 *TeamGroupModelMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case teamgroupmodel.FieldGroupID: + return m.OldGroupID(ctx) + case teamgroupmodel.FieldModelID: + return m.OldModelID(ctx) + case teamgroupmodel.FieldCreatedAt: + return m.OldCreatedAt(ctx) + } + return nil, fmt.Errorf("unknown TeamGroupModel 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 *TeamGroupModelMutation) SetField(name string, value ent.Value) error { + switch name { + case teamgroupmodel.FieldGroupID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetGroupID(v) + return nil + case teamgroupmodel.FieldModelID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetModelID(v) + return nil + case teamgroupmodel.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil } - return oldValue.Name, nil + return fmt.Errorf("unknown TeamGroupModel field %s", name) } -// ResetName resets all changes to the "name" field. -func (m *TeamGroupMutation) ResetName() { - m.name = nil +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *TeamGroupModelMutation) AddedFields() []string { + return nil } -// SetCreatedAt sets the "created_at" field. -func (m *TeamGroupMutation) SetCreatedAt(t time.Time) { - m.created_at = &t +// 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 *TeamGroupModelMutation) AddedField(name string) (ent.Value, bool) { + return nil, false } -// CreatedAt returns the value of the "created_at" field in the mutation. -func (m *TeamGroupMutation) CreatedAt() (r time.Time, exists bool) { - v := m.created_at - if v == nil { - return +// 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 *TeamGroupModelMutation) AddField(name string, value ent.Value) error { + switch name { } - return *v, true + return fmt.Errorf("unknown TeamGroupModel numeric field %s", name) } -// OldCreatedAt returns the old "created_at" field's value of the TeamGroup entity. -// If the TeamGroup 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 *TeamGroupMutation) 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 +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *TeamGroupModelMutation) ClearedFields() []string { + return nil } -// ResetCreatedAt resets all changes to the "created_at" field. -func (m *TeamGroupMutation) ResetCreatedAt() { - m.created_at = nil +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *TeamGroupModelMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok } -// SetUpdatedAt sets the "updated_at" field. -func (m *TeamGroupMutation) SetUpdatedAt(t time.Time) { - m.updated_at = &t +// 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 *TeamGroupModelMutation) ClearField(name string) error { + return fmt.Errorf("unknown TeamGroupModel nullable field %s", name) } -// UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *TeamGroupMutation) UpdatedAt() (r time.Time, exists bool) { - v := m.updated_at - if v == nil { - return +// 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 *TeamGroupModelMutation) ResetField(name string) error { + switch name { + case teamgroupmodel.FieldGroupID: + m.ResetGroupID() + return nil + case teamgroupmodel.FieldModelID: + m.ResetModelID() + return nil + case teamgroupmodel.FieldCreatedAt: + m.ResetCreatedAt() + return nil } - return *v, true + return fmt.Errorf("unknown TeamGroupModel field %s", name) } -// OldUpdatedAt returns the old "updated_at" field's value of the TeamGroup entity. -// If the TeamGroup 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 *TeamGroupMutation) 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") +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *TeamGroupModelMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.group != nil { + edges = append(edges, teamgroupmodel.EdgeGroup) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) + if m.model != nil { + edges = append(edges, teamgroupmodel.EdgeModel) } - return oldValue.UpdatedAt, nil -} - -// ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *TeamGroupMutation) ResetUpdatedAt() { - m.updated_at = nil + return edges } -// AddMemberIDs adds the "members" edge to the User entity by ids. -func (m *TeamGroupMutation) AddMemberIDs(ids ...uuid.UUID) { - if m.members == nil { - m.members = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.members[ids[i]] = struct{}{} +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *TeamGroupModelMutation) AddedIDs(name string) []ent.Value { + switch name { + case teamgroupmodel.EdgeGroup: + if id := m.group; id != nil { + return []ent.Value{*id} + } + case teamgroupmodel.EdgeModel: + if id := m.model; id != nil { + return []ent.Value{*id} + } } + return nil } -// ClearMembers clears the "members" edge to the User entity. -func (m *TeamGroupMutation) ClearMembers() { - m.clearedmembers = true +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *TeamGroupModelMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + return edges } -// MembersCleared reports if the "members" edge to the User entity was cleared. -func (m *TeamGroupMutation) MembersCleared() bool { - return m.clearedmembers +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *TeamGroupModelMutation) RemovedIDs(name string) []ent.Value { + return nil } -// RemoveMemberIDs removes the "members" edge to the User entity by IDs. -func (m *TeamGroupMutation) RemoveMemberIDs(ids ...uuid.UUID) { - if m.removedmembers == nil { - m.removedmembers = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.members, ids[i]) - m.removedmembers[ids[i]] = struct{}{} +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *TeamGroupModelMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedgroup { + edges = append(edges, teamgroupmodel.EdgeGroup) } -} - -// RemovedMembers returns the removed IDs of the "members" edge to the User entity. -func (m *TeamGroupMutation) RemovedMembersIDs() (ids []uuid.UUID) { - for id := range m.removedmembers { - ids = append(ids, id) + if m.clearedmodel { + edges = append(edges, teamgroupmodel.EdgeModel) } - return + return edges } -// MembersIDs returns the "members" edge IDs in the mutation. -func (m *TeamGroupMutation) MembersIDs() (ids []uuid.UUID) { - for id := range m.members { - ids = append(ids, id) +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *TeamGroupModelMutation) EdgeCleared(name string) bool { + switch name { + case teamgroupmodel.EdgeGroup: + return m.clearedgroup + case teamgroupmodel.EdgeModel: + return m.clearedmodel } - return -} - -// ResetMembers resets all changes to the "members" edge. -func (m *TeamGroupMutation) ResetMembers() { - m.members = nil - m.clearedmembers = false - m.removedmembers = nil -} - -// ClearTeam clears the "team" edge to the Team entity. -func (m *TeamGroupMutation) ClearTeam() { - m.clearedteam = true - m.clearedFields[teamgroup.FieldTeamID] = struct{}{} -} - -// TeamCleared reports if the "team" edge to the Team entity was cleared. -func (m *TeamGroupMutation) TeamCleared() bool { - return m.clearedteam + return false } -// TeamIDs returns the "team" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// TeamID instead. It exists only for internal usage by the builders. -func (m *TeamGroupMutation) TeamIDs() (ids []uuid.UUID) { - if id := m.team; id != nil { - ids = append(ids, *id) +// 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 *TeamGroupModelMutation) ClearEdge(name string) error { + switch name { + case teamgroupmodel.EdgeGroup: + m.ClearGroup() + return nil + case teamgroupmodel.EdgeModel: + m.ClearModel() + return nil } - return -} - -// ResetTeam resets all changes to the "team" edge. -func (m *TeamGroupMutation) ResetTeam() { - m.team = nil - m.clearedteam = false + return fmt.Errorf("unknown TeamGroupModel unique edge %s", name) } -// AddModelIDs adds the "models" edge to the Model entity by ids. -func (m *TeamGroupMutation) AddModelIDs(ids ...uuid.UUID) { - if m.models == nil { - m.models = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.models[ids[i]] = struct{}{} +// 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 *TeamGroupModelMutation) ResetEdge(name string) error { + switch name { + case teamgroupmodel.EdgeGroup: + m.ResetGroup() + return nil + case teamgroupmodel.EdgeModel: + m.ResetModel() + return nil } + return fmt.Errorf("unknown TeamGroupModel edge %s", name) } -// ClearModels clears the "models" edge to the Model entity. -func (m *TeamGroupMutation) ClearModels() { - m.clearedmodels = true -} - -// ModelsCleared reports if the "models" edge to the Model entity was cleared. -func (m *TeamGroupMutation) ModelsCleared() bool { - return m.clearedmodels +// TeamHostMutation represents an operation that mutates the TeamHost nodes in the graph. +type TeamHostMutation struct { + config + op Op + typ string + id *uuid.UUID + created_at *time.Time + clearedFields map[string]struct{} + team *uuid.UUID + clearedteam bool + host *string + clearedhost bool + done bool + oldValue func(context.Context) (*TeamHost, error) + predicates []predicate.TeamHost } -// RemoveModelIDs removes the "models" edge to the Model entity by IDs. -func (m *TeamGroupMutation) RemoveModelIDs(ids ...uuid.UUID) { - if m.removedmodels == nil { - m.removedmodels = make(map[uuid.UUID]struct{}) +var _ ent.Mutation = (*TeamHostMutation)(nil) + +// teamhostOption allows management of the mutation configuration using functional options. +type teamhostOption func(*TeamHostMutation) + +// newTeamHostMutation creates new mutation for the TeamHost entity. +func newTeamHostMutation(c config, op Op, opts ...teamhostOption) *TeamHostMutation { + m := &TeamHostMutation{ + config: c, + op: op, + typ: TypeTeamHost, + clearedFields: make(map[string]struct{}), } - for i := range ids { - delete(m.models, ids[i]) - m.removedmodels[ids[i]] = struct{}{} + for _, opt := range opts { + opt(m) } + return m } -// RemovedModels returns the removed IDs of the "models" edge to the Model entity. -func (m *TeamGroupMutation) RemovedModelsIDs() (ids []uuid.UUID) { - for id := range m.removedmodels { - ids = append(ids, id) +// withTeamHostID sets the ID field of the mutation. +func withTeamHostID(id uuid.UUID) teamhostOption { + return func(m *TeamHostMutation) { + var ( + err error + once sync.Once + value *TeamHost + ) + m.oldValue = func(ctx context.Context) (*TeamHost, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().TeamHost.Get(ctx, id) + } + }) + return value, err + } + m.id = &id } - return } -// ModelsIDs returns the "models" edge IDs in the mutation. -func (m *TeamGroupMutation) ModelsIDs() (ids []uuid.UUID) { - for id := range m.models { - ids = append(ids, id) +// withTeamHost sets the old TeamHost of the mutation. +func withTeamHost(node *TeamHost) teamhostOption { + return func(m *TeamHostMutation) { + m.oldValue = func(context.Context) (*TeamHost, error) { + return node, nil + } + m.id = &node.ID } - return } -// ResetModels resets all changes to the "models" edge. -func (m *TeamGroupMutation) ResetModels() { - m.models = nil - m.clearedmodels = false - m.removedmodels = nil +// 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 TeamHostMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client } -// AddImageIDs adds the "images" edge to the Image entity by ids. -func (m *TeamGroupMutation) AddImageIDs(ids ...uuid.UUID) { - if m.images == nil { - m.images = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.images[ids[i]] = struct{}{} +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m TeamHostMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("db: mutation is not running in a transaction") } + tx := &Tx{config: m.config} + tx.init() + return tx, nil } -// ClearImages clears the "images" edge to the Image entity. -func (m *TeamGroupMutation) ClearImages() { - m.clearedimages = true -} - -// ImagesCleared reports if the "images" edge to the Image entity was cleared. -func (m *TeamGroupMutation) ImagesCleared() bool { - return m.clearedimages +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of TeamHost entities. +func (m *TeamHostMutation) SetID(id uuid.UUID) { + m.id = &id } -// RemoveImageIDs removes the "images" edge to the Image entity by IDs. -func (m *TeamGroupMutation) RemoveImageIDs(ids ...uuid.UUID) { - if m.removedimages == nil { - m.removedimages = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.images, ids[i]) - m.removedimages[ids[i]] = struct{}{} +// 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 *TeamHostMutation) ID() (id uuid.UUID, exists bool) { + if m.id == nil { + return } + return *m.id, true } -// RemovedImages returns the removed IDs of the "images" edge to the Image entity. -func (m *TeamGroupMutation) RemovedImagesIDs() (ids []uuid.UUID) { - for id := range m.removedimages { - ids = append(ids, id) +// 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 *TeamHostMutation) 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().TeamHost.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } - return } -// ImagesIDs returns the "images" edge IDs in the mutation. -func (m *TeamGroupMutation) ImagesIDs() (ids []uuid.UUID) { - for id := range m.images { - ids = append(ids, id) - } - return +// SetTeamID sets the "team_id" field. +func (m *TeamHostMutation) SetTeamID(u uuid.UUID) { + m.team = &u } -// ResetImages resets all changes to the "images" edge. -func (m *TeamGroupMutation) ResetImages() { - m.images = nil - m.clearedimages = false - m.removedimages = nil +// TeamID returns the value of the "team_id" field in the mutation. +func (m *TeamHostMutation) TeamID() (r uuid.UUID, exists bool) { + v := m.team + if v == nil { + return + } + return *v, true } -// AddTeamGroupMemberIDs adds the "team_group_members" edge to the TeamGroupMember entity by ids. -func (m *TeamGroupMutation) AddTeamGroupMemberIDs(ids ...uuid.UUID) { - if m.team_group_members == nil { - m.team_group_members = make(map[uuid.UUID]struct{}) +// OldTeamID returns the old "team_id" field's value of the TeamHost entity. +// If the TeamHost 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 *TeamHostMutation) OldTeamID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTeamID is only allowed on UpdateOne operations") } - for i := range ids { - m.team_group_members[ids[i]] = struct{}{} + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTeamID requires an ID field in the mutation") } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTeamID: %w", err) + } + return oldValue.TeamID, nil } -// ClearTeamGroupMembers clears the "team_group_members" edge to the TeamGroupMember entity. -func (m *TeamGroupMutation) ClearTeamGroupMembers() { - m.clearedteam_group_members = true -} - -// TeamGroupMembersCleared reports if the "team_group_members" edge to the TeamGroupMember entity was cleared. -func (m *TeamGroupMutation) TeamGroupMembersCleared() bool { - return m.clearedteam_group_members +// ResetTeamID resets all changes to the "team_id" field. +func (m *TeamHostMutation) ResetTeamID() { + m.team = nil } -// RemoveTeamGroupMemberIDs removes the "team_group_members" edge to the TeamGroupMember entity by IDs. -func (m *TeamGroupMutation) RemoveTeamGroupMemberIDs(ids ...uuid.UUID) { - if m.removedteam_group_members == nil { - m.removedteam_group_members = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.team_group_members, ids[i]) - m.removedteam_group_members[ids[i]] = struct{}{} - } +// SetHostID sets the "host_id" field. +func (m *TeamHostMutation) SetHostID(s string) { + m.host = &s } -// RemovedTeamGroupMembers returns the removed IDs of the "team_group_members" edge to the TeamGroupMember entity. -func (m *TeamGroupMutation) RemovedTeamGroupMembersIDs() (ids []uuid.UUID) { - for id := range m.removedteam_group_members { - ids = append(ids, id) +// HostID returns the value of the "host_id" field in the mutation. +func (m *TeamHostMutation) HostID() (r string, exists bool) { + v := m.host + if v == nil { + return } - return + return *v, true } -// TeamGroupMembersIDs returns the "team_group_members" edge IDs in the mutation. -func (m *TeamGroupMutation) TeamGroupMembersIDs() (ids []uuid.UUID) { - for id := range m.team_group_members { - ids = append(ids, id) +// OldHostID returns the old "host_id" field's value of the TeamHost entity. +// If the TeamHost 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 *TeamHostMutation) OldHostID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldHostID is only allowed on UpdateOne operations") } - return -} - -// ResetTeamGroupMembers resets all changes to the "team_group_members" edge. -func (m *TeamGroupMutation) ResetTeamGroupMembers() { - m.team_group_members = nil - m.clearedteam_group_members = false - m.removedteam_group_members = nil -} - -// AddTeamGroupModelIDs adds the "team_group_models" edge to the TeamGroupModel entity by ids. -func (m *TeamGroupMutation) AddTeamGroupModelIDs(ids ...uuid.UUID) { - if m.team_group_models == nil { - m.team_group_models = make(map[uuid.UUID]struct{}) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldHostID requires an ID field in the mutation") } - for i := range ids { - m.team_group_models[ids[i]] = struct{}{} + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldHostID: %w", err) } + return oldValue.HostID, nil } -// ClearTeamGroupModels clears the "team_group_models" edge to the TeamGroupModel entity. -func (m *TeamGroupMutation) ClearTeamGroupModels() { - m.clearedteam_group_models = true +// ResetHostID resets all changes to the "host_id" field. +func (m *TeamHostMutation) ResetHostID() { + m.host = nil } -// TeamGroupModelsCleared reports if the "team_group_models" edge to the TeamGroupModel entity was cleared. -func (m *TeamGroupMutation) TeamGroupModelsCleared() bool { - return m.clearedteam_group_models +// SetCreatedAt sets the "created_at" field. +func (m *TeamHostMutation) SetCreatedAt(t time.Time) { + m.created_at = &t } -// RemoveTeamGroupModelIDs removes the "team_group_models" edge to the TeamGroupModel entity by IDs. -func (m *TeamGroupMutation) RemoveTeamGroupModelIDs(ids ...uuid.UUID) { - if m.removedteam_group_models == nil { - m.removedteam_group_models = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.team_group_models, ids[i]) - m.removedteam_group_models[ids[i]] = struct{}{} +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *TeamHostMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return } + return *v, true } -// RemovedTeamGroupModels returns the removed IDs of the "team_group_models" edge to the TeamGroupModel entity. -func (m *TeamGroupMutation) RemovedTeamGroupModelsIDs() (ids []uuid.UUID) { - for id := range m.removedteam_group_models { - ids = append(ids, id) +// OldCreatedAt returns the old "created_at" field's value of the TeamHost entity. +// If the TeamHost 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 *TeamHostMutation) 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") } - return + 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 } -// TeamGroupModelsIDs returns the "team_group_models" edge IDs in the mutation. -func (m *TeamGroupMutation) TeamGroupModelsIDs() (ids []uuid.UUID) { - for id := range m.team_group_models { - ids = append(ids, id) - } - return +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *TeamHostMutation) ResetCreatedAt() { + m.created_at = nil } -// ResetTeamGroupModels resets all changes to the "team_group_models" edge. -func (m *TeamGroupMutation) ResetTeamGroupModels() { - m.team_group_models = nil - m.clearedteam_group_models = false - m.removedteam_group_models = nil +// ClearTeam clears the "team" edge to the Team entity. +func (m *TeamHostMutation) ClearTeam() { + m.clearedteam = true + m.clearedFields[teamhost.FieldTeamID] = struct{}{} } -// AddTeamGroupImageIDs adds the "team_group_images" edge to the TeamGroupImage entity by ids. -func (m *TeamGroupMutation) AddTeamGroupImageIDs(ids ...uuid.UUID) { - if m.team_group_images == nil { - m.team_group_images = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.team_group_images[ids[i]] = struct{}{} - } +// TeamCleared reports if the "team" edge to the Team entity was cleared. +func (m *TeamHostMutation) TeamCleared() bool { + return m.clearedteam } -// ClearTeamGroupImages clears the "team_group_images" edge to the TeamGroupImage entity. -func (m *TeamGroupMutation) ClearTeamGroupImages() { - m.clearedteam_group_images = true +// TeamIDs returns the "team" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// TeamID instead. It exists only for internal usage by the builders. +func (m *TeamHostMutation) TeamIDs() (ids []uuid.UUID) { + if id := m.team; id != nil { + ids = append(ids, *id) + } + return } -// TeamGroupImagesCleared reports if the "team_group_images" edge to the TeamGroupImage entity was cleared. -func (m *TeamGroupMutation) TeamGroupImagesCleared() bool { - return m.clearedteam_group_images +// ResetTeam resets all changes to the "team" edge. +func (m *TeamHostMutation) ResetTeam() { + m.team = nil + m.clearedteam = false } -// RemoveTeamGroupImageIDs removes the "team_group_images" edge to the TeamGroupImage entity by IDs. -func (m *TeamGroupMutation) RemoveTeamGroupImageIDs(ids ...uuid.UUID) { - if m.removedteam_group_images == nil { - m.removedteam_group_images = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.team_group_images, ids[i]) - m.removedteam_group_images[ids[i]] = struct{}{} - } +// ClearHost clears the "host" edge to the Host entity. +func (m *TeamHostMutation) ClearHost() { + m.clearedhost = true + m.clearedFields[teamhost.FieldHostID] = struct{}{} } -// RemovedTeamGroupImages returns the removed IDs of the "team_group_images" edge to the TeamGroupImage entity. -func (m *TeamGroupMutation) RemovedTeamGroupImagesIDs() (ids []uuid.UUID) { - for id := range m.removedteam_group_images { - ids = append(ids, id) - } - return +// HostCleared reports if the "host" edge to the Host entity was cleared. +func (m *TeamHostMutation) HostCleared() bool { + return m.clearedhost } -// TeamGroupImagesIDs returns the "team_group_images" edge IDs in the mutation. -func (m *TeamGroupMutation) TeamGroupImagesIDs() (ids []uuid.UUID) { - for id := range m.team_group_images { - ids = append(ids, id) +// HostIDs returns the "host" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// HostID instead. It exists only for internal usage by the builders. +func (m *TeamHostMutation) HostIDs() (ids []string) { + if id := m.host; id != nil { + ids = append(ids, *id) } return } -// ResetTeamGroupImages resets all changes to the "team_group_images" edge. -func (m *TeamGroupMutation) ResetTeamGroupImages() { - m.team_group_images = nil - m.clearedteam_group_images = false - m.removedteam_group_images = nil +// ResetHost resets all changes to the "host" edge. +func (m *TeamHostMutation) ResetHost() { + m.host = nil + m.clearedhost = false } -// Where appends a list predicates to the TeamGroupMutation builder. -func (m *TeamGroupMutation) Where(ps ...predicate.TeamGroup) { +// Where appends a list predicates to the TeamHostMutation builder. +func (m *TeamHostMutation) Where(ps ...predicate.TeamHost) { m.predicates = append(m.predicates, ps...) } -// WhereP appends storage-level predicates to the TeamGroupMutation builder. Using this method, +// WhereP appends storage-level predicates to the TeamHostMutation builder. Using this method, // users can use type-assertion to append predicates that do not depend on any generated package. -func (m *TeamGroupMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.TeamGroup, len(ps)) +func (m *TeamHostMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.TeamHost, len(ps)) for i := range ps { p[i] = ps[i] } @@ -5395,39 +10352,33 @@ func (m *TeamGroupMutation) WhereP(ps ...func(*sql.Selector)) { } // Op returns the operation name. -func (m *TeamGroupMutation) Op() Op { +func (m *TeamHostMutation) Op() Op { return m.op } // SetOp allows setting the mutation operation. -func (m *TeamGroupMutation) SetOp(op Op) { +func (m *TeamHostMutation) SetOp(op Op) { m.op = op } -// Type returns the node type of this mutation (TeamGroup). -func (m *TeamGroupMutation) Type() string { +// Type returns the node type of this mutation (TeamHost). +func (m *TeamHostMutation) 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 *TeamGroupMutation) Fields() []string { - fields := make([]string, 0, 5) - if m.deleted_at != nil { - fields = append(fields, teamgroup.FieldDeletedAt) - } +func (m *TeamHostMutation) Fields() []string { + fields := make([]string, 0, 3) if m.team != nil { - fields = append(fields, teamgroup.FieldTeamID) + fields = append(fields, teamhost.FieldTeamID) } - if m.name != nil { - fields = append(fields, teamgroup.FieldName) + if m.host != nil { + fields = append(fields, teamhost.FieldHostID) } if m.created_at != nil { - fields = append(fields, teamgroup.FieldCreatedAt) - } - if m.updated_at != nil { - fields = append(fields, teamgroup.FieldUpdatedAt) + fields = append(fields, teamhost.FieldCreatedAt) } return fields } @@ -5435,18 +10386,14 @@ func (m *TeamGroupMutation) Fields() []string { // 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 *TeamGroupMutation) Field(name string) (ent.Value, bool) { +func (m *TeamHostMutation) Field(name string) (ent.Value, bool) { switch name { - case teamgroup.FieldDeletedAt: - return m.DeletedAt() - case teamgroup.FieldTeamID: + case teamhost.FieldTeamID: return m.TeamID() - case teamgroup.FieldName: - return m.Name() - case teamgroup.FieldCreatedAt: + case teamhost.FieldHostID: + return m.HostID() + case teamhost.FieldCreatedAt: return m.CreatedAt() - case teamgroup.FieldUpdatedAt: - return m.UpdatedAt() } return nil, false } @@ -5454,399 +10401,226 @@ func (m *TeamGroupMutation) Field(name string) (ent.Value, bool) { // 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 *TeamGroupMutation) OldField(ctx context.Context, name string) (ent.Value, error) { +func (m *TeamHostMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { - case teamgroup.FieldDeletedAt: - return m.OldDeletedAt(ctx) - case teamgroup.FieldTeamID: + case teamhost.FieldTeamID: return m.OldTeamID(ctx) - case teamgroup.FieldName: - return m.OldName(ctx) - case teamgroup.FieldCreatedAt: + case teamhost.FieldHostID: + return m.OldHostID(ctx) + case teamhost.FieldCreatedAt: return m.OldCreatedAt(ctx) - case teamgroup.FieldUpdatedAt: - return m.OldUpdatedAt(ctx) } - return nil, fmt.Errorf("unknown TeamGroup field %s", name) + return nil, fmt.Errorf("unknown TeamHost 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 *TeamGroupMutation) SetField(name string, value ent.Value) error { +func (m *TeamHostMutation) SetField(name string, value ent.Value) error { switch name { - case teamgroup.FieldDeletedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetDeletedAt(v) - return nil - case teamgroup.FieldTeamID: + case teamhost.FieldTeamID: v, ok := value.(uuid.UUID) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetTeamID(v) return nil - case teamgroup.FieldName: + case teamhost.FieldHostID: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetName(v) + m.SetHostID(v) return nil - case teamgroup.FieldCreatedAt: + case teamhost.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 teamgroup.FieldUpdatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUpdatedAt(v) - return nil } - return fmt.Errorf("unknown TeamGroup field %s", name) + return fmt.Errorf("unknown TeamHost field %s", name) } // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. -func (m *TeamGroupMutation) AddedFields() []string { +func (m *TeamHostMutation) AddedFields() []string { return nil } // AddedField returns the numeric value that was incremented/decremented on a field // with the given name. The second boolean return value indicates that this field // was not set, or was not defined in the schema. -func (m *TeamGroupMutation) AddedField(name string) (ent.Value, bool) { +func (m *TeamHostMutation) AddedField(name string) (ent.Value, bool) { return nil, false } // AddField adds the value to the field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *TeamGroupMutation) AddField(name string, value ent.Value) error { +func (m *TeamHostMutation) AddField(name string, value ent.Value) error { switch name { } - return fmt.Errorf("unknown TeamGroup numeric field %s", name) + return fmt.Errorf("unknown TeamHost numeric field %s", name) } // ClearedFields returns all nullable fields that were cleared during this // mutation. -func (m *TeamGroupMutation) ClearedFields() []string { - var fields []string - if m.FieldCleared(teamgroup.FieldDeletedAt) { - fields = append(fields, teamgroup.FieldDeletedAt) - } - return fields +func (m *TeamHostMutation) ClearedFields() []string { + return nil } // FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. -func (m *TeamGroupMutation) FieldCleared(name string) bool { +func (m *TeamHostMutation) 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 *TeamGroupMutation) ClearField(name string) error { - switch name { - case teamgroup.FieldDeletedAt: - m.ClearDeletedAt() - return nil - } - return fmt.Errorf("unknown TeamGroup nullable field %s", name) +func (m *TeamHostMutation) ClearField(name string) error { + return fmt.Errorf("unknown TeamHost 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 *TeamGroupMutation) ResetField(name string) error { +func (m *TeamHostMutation) ResetField(name string) error { switch name { - case teamgroup.FieldDeletedAt: - m.ResetDeletedAt() - return nil - case teamgroup.FieldTeamID: + case teamhost.FieldTeamID: m.ResetTeamID() return nil - case teamgroup.FieldName: - m.ResetName() + case teamhost.FieldHostID: + m.ResetHostID() return nil - case teamgroup.FieldCreatedAt: + case teamhost.FieldCreatedAt: m.ResetCreatedAt() return nil - case teamgroup.FieldUpdatedAt: - m.ResetUpdatedAt() - return nil } - return fmt.Errorf("unknown TeamGroup field %s", name) + return fmt.Errorf("unknown TeamHost field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. -func (m *TeamGroupMutation) AddedEdges() []string { - edges := make([]string, 0, 7) - if m.members != nil { - edges = append(edges, teamgroup.EdgeMembers) - } +func (m *TeamHostMutation) AddedEdges() []string { + edges := make([]string, 0, 2) if m.team != nil { - edges = append(edges, teamgroup.EdgeTeam) - } - if m.models != nil { - edges = append(edges, teamgroup.EdgeModels) - } - if m.images != nil { - edges = append(edges, teamgroup.EdgeImages) - } - if m.team_group_members != nil { - edges = append(edges, teamgroup.EdgeTeamGroupMembers) - } - if m.team_group_models != nil { - edges = append(edges, teamgroup.EdgeTeamGroupModels) + edges = append(edges, teamhost.EdgeTeam) } - if m.team_group_images != nil { - edges = append(edges, teamgroup.EdgeTeamGroupImages) + if m.host != nil { + edges = append(edges, teamhost.EdgeHost) } return edges } // AddedIDs returns all IDs (to other nodes) that were added for the given edge // name in this mutation. -func (m *TeamGroupMutation) AddedIDs(name string) []ent.Value { +func (m *TeamHostMutation) AddedIDs(name string) []ent.Value { switch name { - case teamgroup.EdgeMembers: - ids := make([]ent.Value, 0, len(m.members)) - for id := range m.members { - ids = append(ids, id) - } - return ids - case teamgroup.EdgeTeam: + case teamhost.EdgeTeam: if id := m.team; id != nil { - return []ent.Value{*id} - } - case teamgroup.EdgeModels: - ids := make([]ent.Value, 0, len(m.models)) - for id := range m.models { - ids = append(ids, id) - } - return ids - case teamgroup.EdgeImages: - ids := make([]ent.Value, 0, len(m.images)) - for id := range m.images { - ids = append(ids, id) - } - return ids - case teamgroup.EdgeTeamGroupMembers: - ids := make([]ent.Value, 0, len(m.team_group_members)) - for id := range m.team_group_members { - ids = append(ids, id) - } - return ids - case teamgroup.EdgeTeamGroupModels: - ids := make([]ent.Value, 0, len(m.team_group_models)) - for id := range m.team_group_models { - ids = append(ids, id) - } - return ids - case teamgroup.EdgeTeamGroupImages: - ids := make([]ent.Value, 0, len(m.team_group_images)) - for id := range m.team_group_images { - ids = append(ids, id) - } - return ids - } - return nil -} - -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *TeamGroupMutation) RemovedEdges() []string { - edges := make([]string, 0, 7) - if m.removedmembers != nil { - edges = append(edges, teamgroup.EdgeMembers) - } - if m.removedmodels != nil { - edges = append(edges, teamgroup.EdgeModels) - } - if m.removedimages != nil { - edges = append(edges, teamgroup.EdgeImages) - } - if m.removedteam_group_members != nil { - edges = append(edges, teamgroup.EdgeTeamGroupMembers) - } - if m.removedteam_group_models != nil { - edges = append(edges, teamgroup.EdgeTeamGroupModels) - } - if m.removedteam_group_images != nil { - edges = append(edges, teamgroup.EdgeTeamGroupImages) - } - return edges -} - -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *TeamGroupMutation) RemovedIDs(name string) []ent.Value { - switch name { - case teamgroup.EdgeMembers: - ids := make([]ent.Value, 0, len(m.removedmembers)) - for id := range m.removedmembers { - ids = append(ids, id) - } - return ids - case teamgroup.EdgeModels: - ids := make([]ent.Value, 0, len(m.removedmodels)) - for id := range m.removedmodels { - ids = append(ids, id) - } - return ids - case teamgroup.EdgeImages: - ids := make([]ent.Value, 0, len(m.removedimages)) - for id := range m.removedimages { - ids = append(ids, id) - } - return ids - case teamgroup.EdgeTeamGroupMembers: - ids := make([]ent.Value, 0, len(m.removedteam_group_members)) - for id := range m.removedteam_group_members { - ids = append(ids, id) - } - return ids - case teamgroup.EdgeTeamGroupModels: - ids := make([]ent.Value, 0, len(m.removedteam_group_models)) - for id := range m.removedteam_group_models { - ids = append(ids, id) + return []ent.Value{*id} } - return ids - case teamgroup.EdgeTeamGroupImages: - ids := make([]ent.Value, 0, len(m.removedteam_group_images)) - for id := range m.removedteam_group_images { - ids = append(ids, id) + case teamhost.EdgeHost: + if id := m.host; id != nil { + return []ent.Value{*id} } - return ids } return nil } +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *TeamHostMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *TeamHostMutation) RemovedIDs(name string) []ent.Value { + return nil +} + // ClearedEdges returns all edge names that were cleared in this mutation. -func (m *TeamGroupMutation) ClearedEdges() []string { - edges := make([]string, 0, 7) - if m.clearedmembers { - edges = append(edges, teamgroup.EdgeMembers) - } +func (m *TeamHostMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) if m.clearedteam { - edges = append(edges, teamgroup.EdgeTeam) - } - if m.clearedmodels { - edges = append(edges, teamgroup.EdgeModels) - } - if m.clearedimages { - edges = append(edges, teamgroup.EdgeImages) - } - if m.clearedteam_group_members { - edges = append(edges, teamgroup.EdgeTeamGroupMembers) - } - if m.clearedteam_group_models { - edges = append(edges, teamgroup.EdgeTeamGroupModels) + edges = append(edges, teamhost.EdgeTeam) } - if m.clearedteam_group_images { - edges = append(edges, teamgroup.EdgeTeamGroupImages) + if m.clearedhost { + edges = append(edges, teamhost.EdgeHost) } return edges } // EdgeCleared returns a boolean which indicates if the edge with the given name // was cleared in this mutation. -func (m *TeamGroupMutation) EdgeCleared(name string) bool { +func (m *TeamHostMutation) EdgeCleared(name string) bool { switch name { - case teamgroup.EdgeMembers: - return m.clearedmembers - case teamgroup.EdgeTeam: + case teamhost.EdgeTeam: return m.clearedteam - case teamgroup.EdgeModels: - return m.clearedmodels - case teamgroup.EdgeImages: - return m.clearedimages - case teamgroup.EdgeTeamGroupMembers: - return m.clearedteam_group_members - case teamgroup.EdgeTeamGroupModels: - return m.clearedteam_group_models - case teamgroup.EdgeTeamGroupImages: - return m.clearedteam_group_images + case teamhost.EdgeHost: + return m.clearedhost } 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 *TeamGroupMutation) ClearEdge(name string) error { +func (m *TeamHostMutation) ClearEdge(name string) error { switch name { - case teamgroup.EdgeTeam: + case teamhost.EdgeTeam: m.ClearTeam() return nil + case teamhost.EdgeHost: + m.ClearHost() + return nil } - return fmt.Errorf("unknown TeamGroup unique edge %s", name) + return fmt.Errorf("unknown TeamHost 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 *TeamGroupMutation) ResetEdge(name string) error { +func (m *TeamHostMutation) ResetEdge(name string) error { switch name { - case teamgroup.EdgeMembers: - m.ResetMembers() - return nil - case teamgroup.EdgeTeam: + case teamhost.EdgeTeam: m.ResetTeam() return nil - case teamgroup.EdgeModels: - m.ResetModels() - return nil - case teamgroup.EdgeImages: - m.ResetImages() - return nil - case teamgroup.EdgeTeamGroupMembers: - m.ResetTeamGroupMembers() - return nil - case teamgroup.EdgeTeamGroupModels: - m.ResetTeamGroupModels() - return nil - case teamgroup.EdgeTeamGroupImages: - m.ResetTeamGroupImages() + case teamhost.EdgeHost: + m.ResetHost() return nil } - return fmt.Errorf("unknown TeamGroup edge %s", name) + return fmt.Errorf("unknown TeamHost edge %s", name) } -// TeamGroupImageMutation represents an operation that mutates the TeamGroupImage nodes in the graph. -type TeamGroupImageMutation struct { +// TeamImageMutation represents an operation that mutates the TeamImage nodes in the graph. +type TeamImageMutation struct { config op Op typ string id *uuid.UUID created_at *time.Time clearedFields map[string]struct{} - group *uuid.UUID - clearedgroup bool + team *uuid.UUID + clearedteam bool image *uuid.UUID clearedimage bool done bool - oldValue func(context.Context) (*TeamGroupImage, error) - predicates []predicate.TeamGroupImage + oldValue func(context.Context) (*TeamImage, error) + predicates []predicate.TeamImage } -var _ ent.Mutation = (*TeamGroupImageMutation)(nil) +var _ ent.Mutation = (*TeamImageMutation)(nil) -// teamgroupimageOption allows management of the mutation configuration using functional options. -type teamgroupimageOption func(*TeamGroupImageMutation) +// teamimageOption allows management of the mutation configuration using functional options. +type teamimageOption func(*TeamImageMutation) -// newTeamGroupImageMutation creates new mutation for the TeamGroupImage entity. -func newTeamGroupImageMutation(c config, op Op, opts ...teamgroupimageOption) *TeamGroupImageMutation { - m := &TeamGroupImageMutation{ +// newTeamImageMutation creates new mutation for the TeamImage entity. +func newTeamImageMutation(c config, op Op, opts ...teamimageOption) *TeamImageMutation { + m := &TeamImageMutation{ config: c, op: op, - typ: TypeTeamGroupImage, + typ: TypeTeamImage, clearedFields: make(map[string]struct{}), } for _, opt := range opts { @@ -5855,20 +10629,20 @@ func newTeamGroupImageMutation(c config, op Op, opts ...teamgroupimageOption) *T return m } -// withTeamGroupImageID sets the ID field of the mutation. -func withTeamGroupImageID(id uuid.UUID) teamgroupimageOption { - return func(m *TeamGroupImageMutation) { +// withTeamImageID sets the ID field of the mutation. +func withTeamImageID(id uuid.UUID) teamimageOption { + return func(m *TeamImageMutation) { var ( err error once sync.Once - value *TeamGroupImage + value *TeamImage ) - m.oldValue = func(ctx context.Context) (*TeamGroupImage, error) { + m.oldValue = func(ctx context.Context) (*TeamImage, error) { once.Do(func() { if m.done { err = errors.New("querying old values post mutation is not allowed") } else { - value, err = m.Client().TeamGroupImage.Get(ctx, id) + value, err = m.Client().TeamImage.Get(ctx, id) } }) return value, err @@ -5877,10 +10651,10 @@ func withTeamGroupImageID(id uuid.UUID) teamgroupimageOption { } } -// withTeamGroupImage sets the old TeamGroupImage of the mutation. -func withTeamGroupImage(node *TeamGroupImage) teamgroupimageOption { - return func(m *TeamGroupImageMutation) { - m.oldValue = func(context.Context) (*TeamGroupImage, error) { +// withTeamImage sets the old TeamImage of the mutation. +func withTeamImage(node *TeamImage) teamimageOption { + return func(m *TeamImageMutation) { + m.oldValue = func(context.Context) (*TeamImage, error) { return node, nil } m.id = &node.ID @@ -5889,7 +10663,7 @@ func withTeamGroupImage(node *TeamGroupImage) teamgroupimageOption { // 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 TeamGroupImageMutation) Client() *Client { +func (m TeamImageMutation) Client() *Client { client := &Client{config: m.config} client.init() return client @@ -5897,7 +10671,7 @@ func (m TeamGroupImageMutation) Client() *Client { // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. -func (m TeamGroupImageMutation) Tx() (*Tx, error) { +func (m TeamImageMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { return nil, errors.New("db: mutation is not running in a transaction") } @@ -5907,14 +10681,14 @@ func (m TeamGroupImageMutation) Tx() (*Tx, error) { } // SetID sets the value of the id field. Note that this -// operation is only accepted on creation of TeamGroupImage entities. -func (m *TeamGroupImageMutation) SetID(id uuid.UUID) { +// operation is only accepted on creation of TeamImage entities. +func (m *TeamImageMutation) 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 *TeamGroupImageMutation) ID() (id uuid.UUID, exists bool) { +func (m *TeamImageMutation) ID() (id uuid.UUID, exists bool) { if m.id == nil { return } @@ -5925,7 +10699,7 @@ func (m *TeamGroupImageMutation) ID() (id uuid.UUID, exists bool) { // 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 *TeamGroupImageMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { +func (m *TeamImageMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { switch { case m.op.Is(OpUpdateOne | OpDeleteOne): id, exists := m.ID() @@ -5934,55 +10708,55 @@ func (m *TeamGroupImageMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { } fallthrough case m.op.Is(OpUpdate | OpDelete): - return m.Client().TeamGroupImage.Query().Where(m.predicates...).IDs(ctx) + return m.Client().TeamImage.Query().Where(m.predicates...).IDs(ctx) default: return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } } -// SetGroupID sets the "group_id" field. -func (m *TeamGroupImageMutation) SetGroupID(u uuid.UUID) { - m.group = &u +// SetTeamID sets the "team_id" field. +func (m *TeamImageMutation) SetTeamID(u uuid.UUID) { + m.team = &u } -// GroupID returns the value of the "group_id" field in the mutation. -func (m *TeamGroupImageMutation) GroupID() (r uuid.UUID, exists bool) { - v := m.group +// TeamID returns the value of the "team_id" field in the mutation. +func (m *TeamImageMutation) TeamID() (r uuid.UUID, exists bool) { + v := m.team if v == nil { return } return *v, true } -// OldGroupID returns the old "group_id" field's value of the TeamGroupImage entity. -// If the TeamGroupImage object wasn't provided to the builder, the object is fetched from the database. +// OldTeamID returns the old "team_id" field's value of the TeamImage entity. +// If the TeamImage 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 *TeamGroupImageMutation) OldGroupID(ctx context.Context) (v uuid.UUID, err error) { +func (m *TeamImageMutation) OldTeamID(ctx context.Context) (v uuid.UUID, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldGroupID is only allowed on UpdateOne operations") + return v, errors.New("OldTeamID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldGroupID requires an ID field in the mutation") + return v, errors.New("OldTeamID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldGroupID: %w", err) + return v, fmt.Errorf("querying old value for OldTeamID: %w", err) } - return oldValue.GroupID, nil + return oldValue.TeamID, nil } -// ResetGroupID resets all changes to the "group_id" field. -func (m *TeamGroupImageMutation) ResetGroupID() { - m.group = nil +// ResetTeamID resets all changes to the "team_id" field. +func (m *TeamImageMutation) ResetTeamID() { + m.team = nil } // SetImageID sets the "image_id" field. -func (m *TeamGroupImageMutation) SetImageID(u uuid.UUID) { +func (m *TeamImageMutation) SetImageID(u uuid.UUID) { m.image = &u } // ImageID returns the value of the "image_id" field in the mutation. -func (m *TeamGroupImageMutation) ImageID() (r uuid.UUID, exists bool) { +func (m *TeamImageMutation) ImageID() (r uuid.UUID, exists bool) { v := m.image if v == nil { return @@ -5990,10 +10764,10 @@ func (m *TeamGroupImageMutation) ImageID() (r uuid.UUID, exists bool) { return *v, true } -// OldImageID returns the old "image_id" field's value of the TeamGroupImage entity. -// If the TeamGroupImage object wasn't provided to the builder, the object is fetched from the database. +// OldImageID returns the old "image_id" field's value of the TeamImage entity. +// If the TeamImage 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 *TeamGroupImageMutation) OldImageID(ctx context.Context) (v uuid.UUID, err error) { +func (m *TeamImageMutation) OldImageID(ctx context.Context) (v uuid.UUID, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldImageID is only allowed on UpdateOne operations") } @@ -6008,17 +10782,17 @@ func (m *TeamGroupImageMutation) OldImageID(ctx context.Context) (v uuid.UUID, e } // ResetImageID resets all changes to the "image_id" field. -func (m *TeamGroupImageMutation) ResetImageID() { +func (m *TeamImageMutation) ResetImageID() { m.image = nil } // SetCreatedAt sets the "created_at" field. -func (m *TeamGroupImageMutation) SetCreatedAt(t time.Time) { +func (m *TeamImageMutation) SetCreatedAt(t time.Time) { m.created_at = &t } // CreatedAt returns the value of the "created_at" field in the mutation. -func (m *TeamGroupImageMutation) CreatedAt() (r time.Time, exists bool) { +func (m *TeamImageMutation) CreatedAt() (r time.Time, exists bool) { v := m.created_at if v == nil { return @@ -6026,10 +10800,10 @@ func (m *TeamGroupImageMutation) CreatedAt() (r time.Time, exists bool) { return *v, true } -// OldCreatedAt returns the old "created_at" field's value of the TeamGroupImage entity. -// If the TeamGroupImage object wasn't provided to the builder, the object is fetched from the database. +// OldCreatedAt returns the old "created_at" field's value of the TeamImage entity. +// If the TeamImage 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 *TeamGroupImageMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { +func (m *TeamImageMutation) 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") } @@ -6044,52 +10818,52 @@ func (m *TeamGroupImageMutation) OldCreatedAt(ctx context.Context) (v time.Time, } // ResetCreatedAt resets all changes to the "created_at" field. -func (m *TeamGroupImageMutation) ResetCreatedAt() { +func (m *TeamImageMutation) ResetCreatedAt() { m.created_at = nil } -// ClearGroup clears the "group" edge to the TeamGroup entity. -func (m *TeamGroupImageMutation) ClearGroup() { - m.clearedgroup = true - m.clearedFields[teamgroupimage.FieldGroupID] = struct{}{} +// ClearTeam clears the "team" edge to the Team entity. +func (m *TeamImageMutation) ClearTeam() { + m.clearedteam = true + m.clearedFields[teamimage.FieldTeamID] = struct{}{} } -// GroupCleared reports if the "group" edge to the TeamGroup entity was cleared. -func (m *TeamGroupImageMutation) GroupCleared() bool { - return m.clearedgroup +// TeamCleared reports if the "team" edge to the Team entity was cleared. +func (m *TeamImageMutation) TeamCleared() bool { + return m.clearedteam } -// GroupIDs returns the "group" edge IDs in the mutation. +// TeamIDs returns the "team" 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 *TeamGroupImageMutation) GroupIDs() (ids []uuid.UUID) { - if id := m.group; id != nil { +// TeamID instead. It exists only for internal usage by the builders. +func (m *TeamImageMutation) TeamIDs() (ids []uuid.UUID) { + if id := m.team; id != nil { ids = append(ids, *id) } return } -// ResetGroup resets all changes to the "group" edge. -func (m *TeamGroupImageMutation) ResetGroup() { - m.group = nil - m.clearedgroup = false +// ResetTeam resets all changes to the "team" edge. +func (m *TeamImageMutation) ResetTeam() { + m.team = nil + m.clearedteam = false } // ClearImage clears the "image" edge to the Image entity. -func (m *TeamGroupImageMutation) ClearImage() { +func (m *TeamImageMutation) ClearImage() { m.clearedimage = true - m.clearedFields[teamgroupimage.FieldImageID] = struct{}{} + m.clearedFields[teamimage.FieldImageID] = struct{}{} } // ImageCleared reports if the "image" edge to the Image entity was cleared. -func (m *TeamGroupImageMutation) ImageCleared() bool { +func (m *TeamImageMutation) ImageCleared() bool { return m.clearedimage } // ImageIDs returns the "image" edge IDs in the mutation. // Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use // ImageID instead. It exists only for internal usage by the builders. -func (m *TeamGroupImageMutation) ImageIDs() (ids []uuid.UUID) { +func (m *TeamImageMutation) ImageIDs() (ids []uuid.UUID) { if id := m.image; id != nil { ids = append(ids, *id) } @@ -6097,20 +10871,20 @@ func (m *TeamGroupImageMutation) ImageIDs() (ids []uuid.UUID) { } // ResetImage resets all changes to the "image" edge. -func (m *TeamGroupImageMutation) ResetImage() { +func (m *TeamImageMutation) ResetImage() { m.image = nil m.clearedimage = false } -// Where appends a list predicates to the TeamGroupImageMutation builder. -func (m *TeamGroupImageMutation) Where(ps ...predicate.TeamGroupImage) { +// Where appends a list predicates to the TeamImageMutation builder. +func (m *TeamImageMutation) Where(ps ...predicate.TeamImage) { m.predicates = append(m.predicates, ps...) } -// WhereP appends storage-level predicates to the TeamGroupImageMutation builder. Using this method, +// WhereP appends storage-level predicates to the TeamImageMutation builder. Using this method, // users can use type-assertion to append predicates that do not depend on any generated package. -func (m *TeamGroupImageMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.TeamGroupImage, len(ps)) +func (m *TeamImageMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.TeamImage, len(ps)) for i := range ps { p[i] = ps[i] } @@ -6118,33 +10892,33 @@ func (m *TeamGroupImageMutation) WhereP(ps ...func(*sql.Selector)) { } // Op returns the operation name. -func (m *TeamGroupImageMutation) Op() Op { +func (m *TeamImageMutation) Op() Op { return m.op } // SetOp allows setting the mutation operation. -func (m *TeamGroupImageMutation) SetOp(op Op) { +func (m *TeamImageMutation) SetOp(op Op) { m.op = op } -// Type returns the node type of this mutation (TeamGroupImage). -func (m *TeamGroupImageMutation) Type() string { +// Type returns the node type of this mutation (TeamImage). +func (m *TeamImageMutation) 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 *TeamGroupImageMutation) Fields() []string { - fields := make([]string, 0, 3) - if m.group != nil { - fields = append(fields, teamgroupimage.FieldGroupID) +func (m *TeamImageMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.team != nil { + fields = append(fields, teamimage.FieldTeamID) } if m.image != nil { - fields = append(fields, teamgroupimage.FieldImageID) + fields = append(fields, teamimage.FieldImageID) } if m.created_at != nil { - fields = append(fields, teamgroupimage.FieldCreatedAt) + fields = append(fields, teamimage.FieldCreatedAt) } return fields } @@ -6152,13 +10926,13 @@ func (m *TeamGroupImageMutation) Fields() []string { // 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 *TeamGroupImageMutation) Field(name string) (ent.Value, bool) { +func (m *TeamImageMutation) Field(name string) (ent.Value, bool) { switch name { - case teamgroupimage.FieldGroupID: - return m.GroupID() - case teamgroupimage.FieldImageID: + case teamimage.FieldTeamID: + return m.TeamID() + case teamimage.FieldImageID: return m.ImageID() - case teamgroupimage.FieldCreatedAt: + case teamimage.FieldCreatedAt: return m.CreatedAt() } return nil, false @@ -6167,38 +10941,38 @@ func (m *TeamGroupImageMutation) Field(name string) (ent.Value, bool) { // 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 *TeamGroupImageMutation) OldField(ctx context.Context, name string) (ent.Value, error) { +func (m *TeamImageMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { - case teamgroupimage.FieldGroupID: - return m.OldGroupID(ctx) - case teamgroupimage.FieldImageID: + case teamimage.FieldTeamID: + return m.OldTeamID(ctx) + case teamimage.FieldImageID: return m.OldImageID(ctx) - case teamgroupimage.FieldCreatedAt: + case teamimage.FieldCreatedAt: return m.OldCreatedAt(ctx) } - return nil, fmt.Errorf("unknown TeamGroupImage field %s", name) + return nil, fmt.Errorf("unknown TeamImage 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 *TeamGroupImageMutation) SetField(name string, value ent.Value) error { +func (m *TeamImageMutation) SetField(name string, value ent.Value) error { switch name { - case teamgroupimage.FieldGroupID: + case teamimage.FieldTeamID: v, ok := value.(uuid.UUID) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetGroupID(v) + m.SetTeamID(v) return nil - case teamgroupimage.FieldImageID: + case teamimage.FieldImageID: v, ok := value.(uuid.UUID) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetImageID(v) return nil - case teamgroupimage.FieldCreatedAt: + case teamimage.FieldCreatedAt: v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) @@ -6206,88 +10980,88 @@ func (m *TeamGroupImageMutation) SetField(name string, value ent.Value) error { m.SetCreatedAt(v) return nil } - return fmt.Errorf("unknown TeamGroupImage field %s", name) + return fmt.Errorf("unknown TeamImage field %s", name) } // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. -func (m *TeamGroupImageMutation) AddedFields() []string { +func (m *TeamImageMutation) AddedFields() []string { return nil } // AddedField returns the numeric value that was incremented/decremented on a field // with the given name. The second boolean return value indicates that this field // was not set, or was not defined in the schema. -func (m *TeamGroupImageMutation) AddedField(name string) (ent.Value, bool) { +func (m *TeamImageMutation) AddedField(name string) (ent.Value, bool) { return nil, false } // AddField adds the value to the field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *TeamGroupImageMutation) AddField(name string, value ent.Value) error { +func (m *TeamImageMutation) AddField(name string, value ent.Value) error { switch name { } - return fmt.Errorf("unknown TeamGroupImage numeric field %s", name) + return fmt.Errorf("unknown TeamImage numeric field %s", name) } // ClearedFields returns all nullable fields that were cleared during this // mutation. -func (m *TeamGroupImageMutation) ClearedFields() []string { +func (m *TeamImageMutation) ClearedFields() []string { return nil } // FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. -func (m *TeamGroupImageMutation) FieldCleared(name string) bool { +func (m *TeamImageMutation) 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 *TeamGroupImageMutation) ClearField(name string) error { - return fmt.Errorf("unknown TeamGroupImage nullable field %s", name) +func (m *TeamImageMutation) ClearField(name string) error { + return fmt.Errorf("unknown TeamImage 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 *TeamGroupImageMutation) ResetField(name string) error { +func (m *TeamImageMutation) ResetField(name string) error { switch name { - case teamgroupimage.FieldGroupID: - m.ResetGroupID() + case teamimage.FieldTeamID: + m.ResetTeamID() return nil - case teamgroupimage.FieldImageID: + case teamimage.FieldImageID: m.ResetImageID() return nil - case teamgroupimage.FieldCreatedAt: + case teamimage.FieldCreatedAt: m.ResetCreatedAt() return nil } - return fmt.Errorf("unknown TeamGroupImage field %s", name) + return fmt.Errorf("unknown TeamImage field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. -func (m *TeamGroupImageMutation) AddedEdges() []string { +func (m *TeamImageMutation) AddedEdges() []string { edges := make([]string, 0, 2) - if m.group != nil { - edges = append(edges, teamgroupimage.EdgeGroup) + if m.team != nil { + edges = append(edges, teamimage.EdgeTeam) } if m.image != nil { - edges = append(edges, teamgroupimage.EdgeImage) + edges = append(edges, teamimage.EdgeImage) } return edges } // AddedIDs returns all IDs (to other nodes) that were added for the given edge // name in this mutation. -func (m *TeamGroupImageMutation) AddedIDs(name string) []ent.Value { +func (m *TeamImageMutation) AddedIDs(name string) []ent.Value { switch name { - case teamgroupimage.EdgeGroup: - if id := m.group; id != nil { + case teamimage.EdgeTeam: + if id := m.team; id != nil { return []ent.Value{*id} } - case teamgroupimage.EdgeImage: + case teamimage.EdgeImage: if id := m.image; id != nil { return []ent.Value{*id} } @@ -6296,36 +11070,36 @@ func (m *TeamGroupImageMutation) AddedIDs(name string) []ent.Value { } // RemovedEdges returns all edge names that were removed in this mutation. -func (m *TeamGroupImageMutation) RemovedEdges() []string { +func (m *TeamImageMutation) RemovedEdges() []string { edges := make([]string, 0, 2) return edges } // RemovedIDs returns all IDs (to other nodes) that were removed for the edge with // the given name in this mutation. -func (m *TeamGroupImageMutation) RemovedIDs(name string) []ent.Value { +func (m *TeamImageMutation) RemovedIDs(name string) []ent.Value { return nil } // ClearedEdges returns all edge names that were cleared in this mutation. -func (m *TeamGroupImageMutation) ClearedEdges() []string { +func (m *TeamImageMutation) ClearedEdges() []string { edges := make([]string, 0, 2) - if m.clearedgroup { - edges = append(edges, teamgroupimage.EdgeGroup) + if m.clearedteam { + edges = append(edges, teamimage.EdgeTeam) } if m.clearedimage { - edges = append(edges, teamgroupimage.EdgeImage) + edges = append(edges, teamimage.EdgeImage) } return edges } // EdgeCleared returns a boolean which indicates if the edge with the given name // was cleared in this mutation. -func (m *TeamGroupImageMutation) EdgeCleared(name string) bool { +func (m *TeamImageMutation) EdgeCleared(name string) bool { switch name { - case teamgroupimage.EdgeGroup: - return m.clearedgroup - case teamgroupimage.EdgeImage: + case teamimage.EdgeTeam: + return m.clearedteam + case teamimage.EdgeImage: return m.clearedimage } return false @@ -6333,60 +11107,61 @@ func (m *TeamGroupImageMutation) EdgeCleared(name string) bool { // 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 *TeamGroupImageMutation) ClearEdge(name string) error { +func (m *TeamImageMutation) ClearEdge(name string) error { switch name { - case teamgroupimage.EdgeGroup: - m.ClearGroup() + case teamimage.EdgeTeam: + m.ClearTeam() return nil - case teamgroupimage.EdgeImage: + case teamimage.EdgeImage: m.ClearImage() return nil } - return fmt.Errorf("unknown TeamGroupImage unique edge %s", name) + return fmt.Errorf("unknown TeamImage 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 *TeamGroupImageMutation) ResetEdge(name string) error { +func (m *TeamImageMutation) ResetEdge(name string) error { switch name { - case teamgroupimage.EdgeGroup: - m.ResetGroup() + case teamimage.EdgeTeam: + m.ResetTeam() return nil - case teamgroupimage.EdgeImage: + case teamimage.EdgeImage: m.ResetImage() return nil } - return fmt.Errorf("unknown TeamGroupImage edge %s", name) + return fmt.Errorf("unknown TeamImage edge %s", name) } -// TeamGroupMemberMutation represents an operation that mutates the TeamGroupMember nodes in the graph. -type TeamGroupMemberMutation struct { +// TeamMemberMutation represents an operation that mutates the TeamMember nodes in the graph. +type TeamMemberMutation struct { config op Op typ string id *uuid.UUID + role *consts.TeamMemberRole created_at *time.Time clearedFields map[string]struct{} - group *uuid.UUID - clearedgroup bool + team *uuid.UUID + clearedteam bool user *uuid.UUID cleareduser bool done bool - oldValue func(context.Context) (*TeamGroupMember, error) - predicates []predicate.TeamGroupMember + oldValue func(context.Context) (*TeamMember, error) + predicates []predicate.TeamMember } -var _ ent.Mutation = (*TeamGroupMemberMutation)(nil) +var _ ent.Mutation = (*TeamMemberMutation)(nil) -// teamgroupmemberOption allows management of the mutation configuration using functional options. -type teamgroupmemberOption func(*TeamGroupMemberMutation) +// teammemberOption allows management of the mutation configuration using functional options. +type teammemberOption func(*TeamMemberMutation) -// newTeamGroupMemberMutation creates new mutation for the TeamGroupMember entity. -func newTeamGroupMemberMutation(c config, op Op, opts ...teamgroupmemberOption) *TeamGroupMemberMutation { - m := &TeamGroupMemberMutation{ +// newTeamMemberMutation creates new mutation for the TeamMember entity. +func newTeamMemberMutation(c config, op Op, opts ...teammemberOption) *TeamMemberMutation { + m := &TeamMemberMutation{ config: c, op: op, - typ: TypeTeamGroupMember, + typ: TypeTeamMember, clearedFields: make(map[string]struct{}), } for _, opt := range opts { @@ -6395,20 +11170,20 @@ func newTeamGroupMemberMutation(c config, op Op, opts ...teamgroupmemberOption) return m } -// withTeamGroupMemberID sets the ID field of the mutation. -func withTeamGroupMemberID(id uuid.UUID) teamgroupmemberOption { - return func(m *TeamGroupMemberMutation) { +// withTeamMemberID sets the ID field of the mutation. +func withTeamMemberID(id uuid.UUID) teammemberOption { + return func(m *TeamMemberMutation) { var ( err error once sync.Once - value *TeamGroupMember + value *TeamMember ) - m.oldValue = func(ctx context.Context) (*TeamGroupMember, error) { + m.oldValue = func(ctx context.Context) (*TeamMember, error) { once.Do(func() { if m.done { err = errors.New("querying old values post mutation is not allowed") } else { - value, err = m.Client().TeamGroupMember.Get(ctx, id) + value, err = m.Client().TeamMember.Get(ctx, id) } }) return value, err @@ -6417,10 +11192,10 @@ func withTeamGroupMemberID(id uuid.UUID) teamgroupmemberOption { } } -// withTeamGroupMember sets the old TeamGroupMember of the mutation. -func withTeamGroupMember(node *TeamGroupMember) teamgroupmemberOption { - return func(m *TeamGroupMemberMutation) { - m.oldValue = func(context.Context) (*TeamGroupMember, error) { +// withTeamMember sets the old TeamMember of the mutation. +func withTeamMember(node *TeamMember) teammemberOption { + return func(m *TeamMemberMutation) { + m.oldValue = func(context.Context) (*TeamMember, error) { return node, nil } m.id = &node.ID @@ -6429,7 +11204,7 @@ func withTeamGroupMember(node *TeamGroupMember) teamgroupmemberOption { // 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 TeamGroupMemberMutation) Client() *Client { +func (m TeamMemberMutation) Client() *Client { client := &Client{config: m.config} client.init() return client @@ -6437,7 +11212,7 @@ func (m TeamGroupMemberMutation) Client() *Client { // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. -func (m TeamGroupMemberMutation) Tx() (*Tx, error) { +func (m TeamMemberMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { return nil, errors.New("db: mutation is not running in a transaction") } @@ -6447,14 +11222,14 @@ func (m TeamGroupMemberMutation) Tx() (*Tx, error) { } // SetID sets the value of the id field. Note that this -// operation is only accepted on creation of TeamGroupMember entities. -func (m *TeamGroupMemberMutation) SetID(id uuid.UUID) { +// operation is only accepted on creation of TeamMember entities. +func (m *TeamMemberMutation) 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 *TeamGroupMemberMutation) ID() (id uuid.UUID, exists bool) { +func (m *TeamMemberMutation) ID() (id uuid.UUID, exists bool) { if m.id == nil { return } @@ -6465,7 +11240,7 @@ func (m *TeamGroupMemberMutation) ID() (id uuid.UUID, exists bool) { // 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 *TeamGroupMemberMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { +func (m *TeamMemberMutation) IDs(ctx context.Context) ([]uuid.UUID, error) { switch { case m.op.Is(OpUpdateOne | OpDeleteOne): id, exists := m.ID() @@ -6474,55 +11249,55 @@ func (m *TeamGroupMemberMutation) IDs(ctx context.Context) ([]uuid.UUID, error) } fallthrough case m.op.Is(OpUpdate | OpDelete): - return m.Client().TeamGroupMember.Query().Where(m.predicates...).IDs(ctx) + return m.Client().TeamMember.Query().Where(m.predicates...).IDs(ctx) default: return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } } -// SetGroupID sets the "group_id" field. -func (m *TeamGroupMemberMutation) SetGroupID(u uuid.UUID) { - m.group = &u +// SetTeamID sets the "team_id" field. +func (m *TeamMemberMutation) SetTeamID(u uuid.UUID) { + m.team = &u } -// GroupID returns the value of the "group_id" field in the mutation. -func (m *TeamGroupMemberMutation) GroupID() (r uuid.UUID, exists bool) { - v := m.group +// TeamID returns the value of the "team_id" field in the mutation. +func (m *TeamMemberMutation) TeamID() (r uuid.UUID, exists bool) { + v := m.team if v == nil { return } return *v, true } -// OldGroupID returns the old "group_id" field's value of the TeamGroupMember entity. -// If the TeamGroupMember object wasn't provided to the builder, the object is fetched from the database. +// OldTeamID returns the old "team_id" field's value of the TeamMember entity. +// If the TeamMember 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 *TeamGroupMemberMutation) OldGroupID(ctx context.Context) (v uuid.UUID, err error) { +func (m *TeamMemberMutation) OldTeamID(ctx context.Context) (v uuid.UUID, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldGroupID is only allowed on UpdateOne operations") + return v, errors.New("OldTeamID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldGroupID requires an ID field in the mutation") + return v, errors.New("OldTeamID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldGroupID: %w", err) + return v, fmt.Errorf("querying old value for OldTeamID: %w", err) } - return oldValue.GroupID, nil + return oldValue.TeamID, nil } -// ResetGroupID resets all changes to the "group_id" field. -func (m *TeamGroupMemberMutation) ResetGroupID() { - m.group = nil +// ResetTeamID resets all changes to the "team_id" field. +func (m *TeamMemberMutation) ResetTeamID() { + m.team = nil } // SetUserID sets the "user_id" field. -func (m *TeamGroupMemberMutation) SetUserID(u uuid.UUID) { +func (m *TeamMemberMutation) SetUserID(u uuid.UUID) { m.user = &u } // UserID returns the value of the "user_id" field in the mutation. -func (m *TeamGroupMemberMutation) UserID() (r uuid.UUID, exists bool) { +func (m *TeamMemberMutation) UserID() (r uuid.UUID, exists bool) { v := m.user if v == nil { return @@ -6530,35 +11305,71 @@ func (m *TeamGroupMemberMutation) UserID() (r uuid.UUID, exists bool) { return *v, true } -// OldUserID returns the old "user_id" field's value of the TeamGroupMember entity. -// If the TeamGroupMember object wasn't provided to the builder, the object is fetched from the database. +// OldUserID returns the old "user_id" field's value of the TeamMember entity. +// If the TeamMember 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 *TeamMemberMutation) OldUserID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUserID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUserID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUserID: %w", err) + } + return oldValue.UserID, nil +} + +// ResetUserID resets all changes to the "user_id" field. +func (m *TeamMemberMutation) ResetUserID() { + m.user = nil +} + +// SetRole sets the "role" field. +func (m *TeamMemberMutation) SetRole(cmr consts.TeamMemberRole) { + m.role = &cmr +} + +// Role returns the value of the "role" field in the mutation. +func (m *TeamMemberMutation) Role() (r consts.TeamMemberRole, exists bool) { + v := m.role + if v == nil { + return + } + return *v, true +} + +// OldRole returns the old "role" field's value of the TeamMember entity. +// If the TeamMember 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 *TeamGroupMemberMutation) OldUserID(ctx context.Context) (v uuid.UUID, err error) { +func (m *TeamMemberMutation) OldRole(ctx context.Context) (v consts.TeamMemberRole, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUserID is only allowed on UpdateOne operations") + return v, errors.New("OldRole is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUserID requires an ID field in the mutation") + return v, errors.New("OldRole requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldUserID: %w", err) + return v, fmt.Errorf("querying old value for OldRole: %w", err) } - return oldValue.UserID, nil + return oldValue.Role, nil } -// ResetUserID resets all changes to the "user_id" field. -func (m *TeamGroupMemberMutation) ResetUserID() { - m.user = nil +// ResetRole resets all changes to the "role" field. +func (m *TeamMemberMutation) ResetRole() { + m.role = nil } // SetCreatedAt sets the "created_at" field. -func (m *TeamGroupMemberMutation) SetCreatedAt(t time.Time) { +func (m *TeamMemberMutation) SetCreatedAt(t time.Time) { m.created_at = &t } // CreatedAt returns the value of the "created_at" field in the mutation. -func (m *TeamGroupMemberMutation) CreatedAt() (r time.Time, exists bool) { +func (m *TeamMemberMutation) CreatedAt() (r time.Time, exists bool) { v := m.created_at if v == nil { return @@ -6566,10 +11377,10 @@ func (m *TeamGroupMemberMutation) CreatedAt() (r time.Time, exists bool) { return *v, true } -// OldCreatedAt returns the old "created_at" field's value of the TeamGroupMember entity. -// If the TeamGroupMember object wasn't provided to the builder, the object is fetched from the database. +// OldCreatedAt returns the old "created_at" field's value of the TeamMember entity. +// If the TeamMember 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 *TeamGroupMemberMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { +func (m *TeamMemberMutation) 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") } @@ -6584,52 +11395,52 @@ func (m *TeamGroupMemberMutation) OldCreatedAt(ctx context.Context) (v time.Time } // ResetCreatedAt resets all changes to the "created_at" field. -func (m *TeamGroupMemberMutation) ResetCreatedAt() { +func (m *TeamMemberMutation) ResetCreatedAt() { m.created_at = nil } -// ClearGroup clears the "group" edge to the TeamGroup entity. -func (m *TeamGroupMemberMutation) ClearGroup() { - m.clearedgroup = true - m.clearedFields[teamgroupmember.FieldGroupID] = struct{}{} +// ClearTeam clears the "team" edge to the Team entity. +func (m *TeamMemberMutation) ClearTeam() { + m.clearedteam = true + m.clearedFields[teammember.FieldTeamID] = struct{}{} } -// GroupCleared reports if the "group" edge to the TeamGroup entity was cleared. -func (m *TeamGroupMemberMutation) GroupCleared() bool { - return m.clearedgroup +// TeamCleared reports if the "team" edge to the Team entity was cleared. +func (m *TeamMemberMutation) TeamCleared() bool { + return m.clearedteam } -// GroupIDs returns the "group" edge IDs in the mutation. +// TeamIDs returns the "team" 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 *TeamGroupMemberMutation) GroupIDs() (ids []uuid.UUID) { - if id := m.group; id != nil { +// TeamID instead. It exists only for internal usage by the builders. +func (m *TeamMemberMutation) TeamIDs() (ids []uuid.UUID) { + if id := m.team; id != nil { ids = append(ids, *id) } return } -// ResetGroup resets all changes to the "group" edge. -func (m *TeamGroupMemberMutation) ResetGroup() { - m.group = nil - m.clearedgroup = false +// ResetTeam resets all changes to the "team" edge. +func (m *TeamMemberMutation) ResetTeam() { + m.team = nil + m.clearedteam = false } // ClearUser clears the "user" edge to the User entity. -func (m *TeamGroupMemberMutation) ClearUser() { +func (m *TeamMemberMutation) ClearUser() { m.cleareduser = true - m.clearedFields[teamgroupmember.FieldUserID] = struct{}{} + m.clearedFields[teammember.FieldUserID] = struct{}{} } // UserCleared reports if the "user" edge to the User entity was cleared. -func (m *TeamGroupMemberMutation) UserCleared() bool { +func (m *TeamMemberMutation) UserCleared() bool { return m.cleareduser } // UserIDs returns the "user" edge IDs in the mutation. // Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use // UserID instead. It exists only for internal usage by the builders. -func (m *TeamGroupMemberMutation) UserIDs() (ids []uuid.UUID) { +func (m *TeamMemberMutation) UserIDs() (ids []uuid.UUID) { if id := m.user; id != nil { ids = append(ids, *id) } @@ -6637,20 +11448,20 @@ func (m *TeamGroupMemberMutation) UserIDs() (ids []uuid.UUID) { } // ResetUser resets all changes to the "user" edge. -func (m *TeamGroupMemberMutation) ResetUser() { +func (m *TeamMemberMutation) ResetUser() { m.user = nil m.cleareduser = false } -// Where appends a list predicates to the TeamGroupMemberMutation builder. -func (m *TeamGroupMemberMutation) Where(ps ...predicate.TeamGroupMember) { +// Where appends a list predicates to the TeamMemberMutation builder. +func (m *TeamMemberMutation) Where(ps ...predicate.TeamMember) { m.predicates = append(m.predicates, ps...) } -// WhereP appends storage-level predicates to the TeamGroupMemberMutation builder. Using this method, +// WhereP appends storage-level predicates to the TeamMemberMutation builder. Using this method, // users can use type-assertion to append predicates that do not depend on any generated package. -func (m *TeamGroupMemberMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.TeamGroupMember, len(ps)) +func (m *TeamMemberMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.TeamMember, len(ps)) for i := range ps { p[i] = ps[i] } @@ -6658,33 +11469,36 @@ func (m *TeamGroupMemberMutation) WhereP(ps ...func(*sql.Selector)) { } // Op returns the operation name. -func (m *TeamGroupMemberMutation) Op() Op { +func (m *TeamMemberMutation) Op() Op { return m.op } // SetOp allows setting the mutation operation. -func (m *TeamGroupMemberMutation) SetOp(op Op) { +func (m *TeamMemberMutation) SetOp(op Op) { m.op = op } -// Type returns the node type of this mutation (TeamGroupMember). -func (m *TeamGroupMemberMutation) Type() string { +// Type returns the node type of this mutation (TeamMember). +func (m *TeamMemberMutation) 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 *TeamGroupMemberMutation) Fields() []string { - fields := make([]string, 0, 3) - if m.group != nil { - fields = append(fields, teamgroupmember.FieldGroupID) +func (m *TeamMemberMutation) Fields() []string { + fields := make([]string, 0, 4) + if m.team != nil { + fields = append(fields, teammember.FieldTeamID) } if m.user != nil { - fields = append(fields, teamgroupmember.FieldUserID) + fields = append(fields, teammember.FieldUserID) + } + if m.role != nil { + fields = append(fields, teammember.FieldRole) } if m.created_at != nil { - fields = append(fields, teamgroupmember.FieldCreatedAt) + fields = append(fields, teammember.FieldCreatedAt) } return fields } @@ -6692,13 +11506,15 @@ func (m *TeamGroupMemberMutation) Fields() []string { // 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 *TeamGroupMemberMutation) Field(name string) (ent.Value, bool) { +func (m *TeamMemberMutation) Field(name string) (ent.Value, bool) { switch name { - case teamgroupmember.FieldGroupID: - return m.GroupID() - case teamgroupmember.FieldUserID: + case teammember.FieldTeamID: + return m.TeamID() + case teammember.FieldUserID: return m.UserID() - case teamgroupmember.FieldCreatedAt: + case teammember.FieldRole: + return m.Role() + case teammember.FieldCreatedAt: return m.CreatedAt() } return nil, false @@ -6707,38 +11523,47 @@ func (m *TeamGroupMemberMutation) Field(name string) (ent.Value, bool) { // 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 *TeamGroupMemberMutation) OldField(ctx context.Context, name string) (ent.Value, error) { +func (m *TeamMemberMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { - case teamgroupmember.FieldGroupID: - return m.OldGroupID(ctx) - case teamgroupmember.FieldUserID: + case teammember.FieldTeamID: + return m.OldTeamID(ctx) + case teammember.FieldUserID: return m.OldUserID(ctx) - case teamgroupmember.FieldCreatedAt: + case teammember.FieldRole: + return m.OldRole(ctx) + case teammember.FieldCreatedAt: return m.OldCreatedAt(ctx) } - return nil, fmt.Errorf("unknown TeamGroupMember field %s", name) + return nil, fmt.Errorf("unknown TeamMember 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 *TeamGroupMemberMutation) SetField(name string, value ent.Value) error { +func (m *TeamMemberMutation) SetField(name string, value ent.Value) error { switch name { - case teamgroupmember.FieldGroupID: + case teammember.FieldTeamID: v, ok := value.(uuid.UUID) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetGroupID(v) + m.SetTeamID(v) return nil - case teamgroupmember.FieldUserID: + case teammember.FieldUserID: v, ok := value.(uuid.UUID) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetUserID(v) return nil - case teamgroupmember.FieldCreatedAt: + case teammember.FieldRole: + v, ok := value.(consts.TeamMemberRole) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRole(v) + return nil + case teammember.FieldCreatedAt: v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) @@ -6746,88 +11571,91 @@ func (m *TeamGroupMemberMutation) SetField(name string, value ent.Value) error { m.SetCreatedAt(v) return nil } - return fmt.Errorf("unknown TeamGroupMember field %s", name) + return fmt.Errorf("unknown TeamMember field %s", name) } // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. -func (m *TeamGroupMemberMutation) AddedFields() []string { +func (m *TeamMemberMutation) AddedFields() []string { return nil } // AddedField returns the numeric value that was incremented/decremented on a field // with the given name. The second boolean return value indicates that this field // was not set, or was not defined in the schema. -func (m *TeamGroupMemberMutation) AddedField(name string) (ent.Value, bool) { +func (m *TeamMemberMutation) AddedField(name string) (ent.Value, bool) { return nil, false } // AddField adds the value to the field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *TeamGroupMemberMutation) AddField(name string, value ent.Value) error { +func (m *TeamMemberMutation) AddField(name string, value ent.Value) error { switch name { } - return fmt.Errorf("unknown TeamGroupMember numeric field %s", name) + return fmt.Errorf("unknown TeamMember numeric field %s", name) } // ClearedFields returns all nullable fields that were cleared during this // mutation. -func (m *TeamGroupMemberMutation) ClearedFields() []string { +func (m *TeamMemberMutation) ClearedFields() []string { return nil } // FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. -func (m *TeamGroupMemberMutation) FieldCleared(name string) bool { +func (m *TeamMemberMutation) 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 *TeamGroupMemberMutation) ClearField(name string) error { - return fmt.Errorf("unknown TeamGroupMember nullable field %s", name) +func (m *TeamMemberMutation) ClearField(name string) error { + return fmt.Errorf("unknown TeamMember 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 *TeamGroupMemberMutation) ResetField(name string) error { +func (m *TeamMemberMutation) ResetField(name string) error { switch name { - case teamgroupmember.FieldGroupID: - m.ResetGroupID() + case teammember.FieldTeamID: + m.ResetTeamID() return nil - case teamgroupmember.FieldUserID: + case teammember.FieldUserID: m.ResetUserID() return nil - case teamgroupmember.FieldCreatedAt: + case teammember.FieldRole: + m.ResetRole() + return nil + case teammember.FieldCreatedAt: m.ResetCreatedAt() return nil } - return fmt.Errorf("unknown TeamGroupMember field %s", name) + return fmt.Errorf("unknown TeamMember field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. -func (m *TeamGroupMemberMutation) AddedEdges() []string { +func (m *TeamMemberMutation) AddedEdges() []string { edges := make([]string, 0, 2) - if m.group != nil { - edges = append(edges, teamgroupmember.EdgeGroup) + if m.team != nil { + edges = append(edges, teammember.EdgeTeam) } if m.user != nil { - edges = append(edges, teamgroupmember.EdgeUser) + edges = append(edges, teammember.EdgeUser) } return edges } // AddedIDs returns all IDs (to other nodes) that were added for the given edge // name in this mutation. -func (m *TeamGroupMemberMutation) AddedIDs(name string) []ent.Value { +func (m *TeamMemberMutation) AddedIDs(name string) []ent.Value { switch name { - case teamgroupmember.EdgeGroup: - if id := m.group; id != nil { + case teammember.EdgeTeam: + if id := m.team; id != nil { return []ent.Value{*id} } - case teamgroupmember.EdgeUser: + case teammember.EdgeUser: if id := m.user; id != nil { return []ent.Value{*id} } @@ -6836,36 +11664,36 @@ func (m *TeamGroupMemberMutation) AddedIDs(name string) []ent.Value { } // RemovedEdges returns all edge names that were removed in this mutation. -func (m *TeamGroupMemberMutation) RemovedEdges() []string { +func (m *TeamMemberMutation) RemovedEdges() []string { edges := make([]string, 0, 2) return edges } // RemovedIDs returns all IDs (to other nodes) that were removed for the edge with // the given name in this mutation. -func (m *TeamGroupMemberMutation) RemovedIDs(name string) []ent.Value { +func (m *TeamMemberMutation) RemovedIDs(name string) []ent.Value { return nil } // ClearedEdges returns all edge names that were cleared in this mutation. -func (m *TeamGroupMemberMutation) ClearedEdges() []string { +func (m *TeamMemberMutation) ClearedEdges() []string { edges := make([]string, 0, 2) - if m.clearedgroup { - edges = append(edges, teamgroupmember.EdgeGroup) + if m.clearedteam { + edges = append(edges, teammember.EdgeTeam) } if m.cleareduser { - edges = append(edges, teamgroupmember.EdgeUser) + edges = append(edges, teammember.EdgeUser) } return edges } // EdgeCleared returns a boolean which indicates if the edge with the given name // was cleared in this mutation. -func (m *TeamGroupMemberMutation) EdgeCleared(name string) bool { +func (m *TeamMemberMutation) EdgeCleared(name string) bool { switch name { - case teamgroupmember.EdgeGroup: - return m.clearedgroup - case teamgroupmember.EdgeUser: + case teammember.EdgeTeam: + return m.clearedteam + case teammember.EdgeUser: return m.cleareduser } return false @@ -6873,60 +11701,60 @@ func (m *TeamGroupMemberMutation) EdgeCleared(name string) bool { // 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 *TeamGroupMemberMutation) ClearEdge(name string) error { +func (m *TeamMemberMutation) ClearEdge(name string) error { switch name { - case teamgroupmember.EdgeGroup: - m.ClearGroup() + case teammember.EdgeTeam: + m.ClearTeam() return nil - case teamgroupmember.EdgeUser: + case teammember.EdgeUser: m.ClearUser() return nil } - return fmt.Errorf("unknown TeamGroupMember unique edge %s", name) + return fmt.Errorf("unknown TeamMember 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 *TeamGroupMemberMutation) ResetEdge(name string) error { +func (m *TeamMemberMutation) ResetEdge(name string) error { switch name { - case teamgroupmember.EdgeGroup: - m.ResetGroup() + case teammember.EdgeTeam: + m.ResetTeam() return nil - case teamgroupmember.EdgeUser: + case teammember.EdgeUser: m.ResetUser() return nil } - return fmt.Errorf("unknown TeamGroupMember edge %s", name) + return fmt.Errorf("unknown TeamMember edge %s", name) } -// TeamGroupModelMutation represents an operation that mutates the TeamGroupModel nodes in the graph. -type TeamGroupModelMutation struct { +// TeamModelMutation represents an operation that mutates the TeamModel nodes in the graph. +type TeamModelMutation struct { config op Op typ string id *uuid.UUID created_at *time.Time clearedFields map[string]struct{} - group *uuid.UUID - clearedgroup bool + team *uuid.UUID + clearedteam bool model *uuid.UUID clearedmodel bool done bool - oldValue func(context.Context) (*TeamGroupModel, error) - predicates []predicate.TeamGroupModel + oldValue func(context.Context) (*TeamModel, error) + predicates []predicate.TeamModel } -var _ ent.Mutation = (*TeamGroupModelMutation)(nil) - -// teamgroupmodelOption allows management of the mutation configuration using functional options. -type teamgroupmodelOption func(*TeamGroupModelMutation) +var _ ent.Mutation = (*TeamModelMutation)(nil) -// newTeamGroupModelMutation creates new mutation for the TeamGroupModel entity. -func newTeamGroupModelMutation(c config, op Op, opts ...teamgroupmodelOption) *TeamGroupModelMutation { - m := &TeamGroupModelMutation{ +// teammodelOption allows management of the mutation configuration using functional options. +type teammodelOption func(*TeamModelMutation) + +// newTeamModelMutation creates new mutation for the TeamModel entity. +func newTeamModelMutation(c config, op Op, opts ...teammodelOption) *TeamModelMutation { + m := &TeamModelMutation{ config: c, op: op, - typ: TypeTeamGroupModel, + typ: TypeTeamModel, clearedFields: make(map[string]struct{}), } for _, opt := range opts { @@ -6935,20 +11763,20 @@ func newTeamGroupModelMutation(c config, op Op, opts ...teamgroupmodelOption) *T return m } -// withTeamGroupModelID sets the ID field of the mutation. -func withTeamGroupModelID(id uuid.UUID) teamgroupmodelOption { - return func(m *TeamGroupModelMutation) { +// withTeamModelID sets the ID field of the mutation. +func withTeamModelID(id uuid.UUID) teammodelOption { + return func(m *TeamModelMutation) { var ( err error once sync.Once - value *TeamGroupModel + value *TeamModel ) - m.oldValue = func(ctx context.Context) (*TeamGroupModel, error) { + m.oldValue = func(ctx context.Context) (*TeamModel, error) { once.Do(func() { if m.done { err = errors.New("querying old values post mutation is not allowed") } else { - value, err = m.Client().TeamGroupModel.Get(ctx, id) + value, err = m.Client().TeamModel.Get(ctx, id) } }) return value, err @@ -6957,10 +11785,10 @@ func withTeamGroupModelID(id uuid.UUID) teamgroupmodelOption { } } -// withTeamGroupModel sets the old TeamGroupModel of the mutation. -func withTeamGroupModel(node *TeamGroupModel) teamgroupmodelOption { - return func(m *TeamGroupModelMutation) { - m.oldValue = func(context.Context) (*TeamGroupModel, error) { +// withTeamModel sets the old TeamModel of the mutation. +func withTeamModel(node *TeamModel) teammodelOption { + return func(m *TeamModelMutation) { + m.oldValue = func(context.Context) (*TeamModel, error) { return node, nil } m.id = &node.ID @@ -6969,7 +11797,7 @@ func withTeamGroupModel(node *TeamGroupModel) teamgroupmodelOption { // 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 TeamGroupModelMutation) Client() *Client { +func (m TeamModelMutation) Client() *Client { client := &Client{config: m.config} client.init() return client @@ -6977,1245 +11805,1021 @@ func (m TeamGroupModelMutation) Client() *Client { // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. -func (m TeamGroupModelMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("db: 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 TeamGroupModel entities. -func (m *TeamGroupModelMutation) 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 *TeamGroupModelMutation) 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 *TeamGroupModelMutation) 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().TeamGroupModel.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) - } -} - -// SetGroupID sets the "group_id" field. -func (m *TeamGroupModelMutation) SetGroupID(u uuid.UUID) { - m.group = &u -} - -// GroupID returns the value of the "group_id" field in the mutation. -func (m *TeamGroupModelMutation) GroupID() (r uuid.UUID, exists bool) { - v := m.group - if v == nil { - return - } - return *v, true -} - -// OldGroupID returns the old "group_id" field's value of the TeamGroupModel entity. -// If the TeamGroupModel 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 *TeamGroupModelMutation) OldGroupID(ctx context.Context) (v uuid.UUID, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldGroupID is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldGroupID requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldGroupID: %w", err) - } - return oldValue.GroupID, nil -} - -// ResetGroupID resets all changes to the "group_id" field. -func (m *TeamGroupModelMutation) ResetGroupID() { - m.group = nil -} - -// SetModelID sets the "model_id" field. -func (m *TeamGroupModelMutation) SetModelID(u uuid.UUID) { - m.model = &u -} - -// ModelID returns the value of the "model_id" field in the mutation. -func (m *TeamGroupModelMutation) ModelID() (r uuid.UUID, exists bool) { - v := m.model - if v == nil { - return - } - return *v, true -} - -// OldModelID returns the old "model_id" field's value of the TeamGroupModel entity. -// If the TeamGroupModel 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 *TeamGroupModelMutation) OldModelID(ctx context.Context) (v uuid.UUID, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldModelID is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldModelID requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldModelID: %w", err) - } - return oldValue.ModelID, nil -} - -// ResetModelID resets all changes to the "model_id" field. -func (m *TeamGroupModelMutation) ResetModelID() { - m.model = nil -} - -// SetCreatedAt sets the "created_at" field. -func (m *TeamGroupModelMutation) SetCreatedAt(t time.Time) { - m.created_at = &t -} - -// CreatedAt returns the value of the "created_at" field in the mutation. -func (m *TeamGroupModelMutation) 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 TeamGroupModel entity. -// If the TeamGroupModel 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 *TeamGroupModelMutation) 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 *TeamGroupModelMutation) ResetCreatedAt() { - m.created_at = nil -} - -// ClearGroup clears the "group" edge to the TeamGroup entity. -func (m *TeamGroupModelMutation) ClearGroup() { - m.clearedgroup = true - m.clearedFields[teamgroupmodel.FieldGroupID] = struct{}{} -} - -// GroupCleared reports if the "group" edge to the TeamGroup entity was cleared. -func (m *TeamGroupModelMutation) GroupCleared() bool { - return m.clearedgroup -} - -// 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 *TeamGroupModelMutation) 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 *TeamGroupModelMutation) ResetGroup() { - m.group = nil - m.clearedgroup = false -} - -// ClearModel clears the "model" edge to the Model entity. -func (m *TeamGroupModelMutation) ClearModel() { - m.clearedmodel = true - m.clearedFields[teamgroupmodel.FieldModelID] = struct{}{} -} - -// ModelCleared reports if the "model" edge to the Model entity was cleared. -func (m *TeamGroupModelMutation) ModelCleared() bool { - return m.clearedmodel -} - -// ModelIDs returns the "model" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// ModelID instead. It exists only for internal usage by the builders. -func (m *TeamGroupModelMutation) ModelIDs() (ids []uuid.UUID) { - if id := m.model; id != nil { - ids = append(ids, *id) - } - return -} - -// ResetModel resets all changes to the "model" edge. -func (m *TeamGroupModelMutation) ResetModel() { - m.model = nil - m.clearedmodel = false -} - -// Where appends a list predicates to the TeamGroupModelMutation builder. -func (m *TeamGroupModelMutation) Where(ps ...predicate.TeamGroupModel) { - m.predicates = append(m.predicates, ps...) -} - -// WhereP appends storage-level predicates to the TeamGroupModelMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *TeamGroupModelMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.TeamGroupModel, len(ps)) - for i := range ps { - p[i] = ps[i] - } - m.Where(p...) -} - -// Op returns the operation name. -func (m *TeamGroupModelMutation) Op() Op { - return m.op +func (m TeamModelMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("db: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil } -// SetOp allows setting the mutation operation. -func (m *TeamGroupModelMutation) SetOp(op Op) { - m.op = op +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of TeamModel entities. +func (m *TeamModelMutation) SetID(id uuid.UUID) { + m.id = &id } -// Type returns the node type of this mutation (TeamGroupModel). -func (m *TeamGroupModelMutation) Type() string { - return m.typ +// 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 *TeamModelMutation) ID() (id uuid.UUID, exists bool) { + if m.id == nil { + return + } + return *m.id, true } -// 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 *TeamGroupModelMutation) Fields() []string { - fields := make([]string, 0, 3) - if m.group != nil { - fields = append(fields, teamgroupmodel.FieldGroupID) - } - if m.model != nil { - fields = append(fields, teamgroupmodel.FieldModelID) - } - if m.created_at != nil { - fields = append(fields, teamgroupmodel.FieldCreatedAt) +// 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 *TeamModelMutation) 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().TeamModel.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } - 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 *TeamGroupModelMutation) Field(name string) (ent.Value, bool) { - switch name { - case teamgroupmodel.FieldGroupID: - return m.GroupID() - case teamgroupmodel.FieldModelID: - return m.ModelID() - case teamgroupmodel.FieldCreatedAt: - return m.CreatedAt() - } - return nil, false +// SetTeamID sets the "team_id" field. +func (m *TeamModelMutation) SetTeamID(u uuid.UUID) { + m.team = &u } -// 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 *TeamGroupModelMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case teamgroupmodel.FieldGroupID: - return m.OldGroupID(ctx) - case teamgroupmodel.FieldModelID: - return m.OldModelID(ctx) - case teamgroupmodel.FieldCreatedAt: - return m.OldCreatedAt(ctx) +// TeamID returns the value of the "team_id" field in the mutation. +func (m *TeamModelMutation) TeamID() (r uuid.UUID, exists bool) { + v := m.team + if v == nil { + return } - return nil, fmt.Errorf("unknown TeamGroupModel field %s", name) + return *v, true } -// 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 *TeamGroupModelMutation) SetField(name string, value ent.Value) error { - switch name { - case teamgroupmodel.FieldGroupID: - v, ok := value.(uuid.UUID) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetGroupID(v) - return nil - case teamgroupmodel.FieldModelID: - v, ok := value.(uuid.UUID) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetModelID(v) - return nil - case teamgroupmodel.FieldCreatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCreatedAt(v) - return nil +// OldTeamID returns the old "team_id" field's value of the TeamModel entity. +// If the TeamModel 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 *TeamModelMutation) OldTeamID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTeamID is only allowed on UpdateOne operations") } - return fmt.Errorf("unknown TeamGroupModel field %s", name) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTeamID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTeamID: %w", err) + } + return oldValue.TeamID, nil } -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *TeamGroupModelMutation) AddedFields() []string { - return nil +// ResetTeamID resets all changes to the "team_id" field. +func (m *TeamModelMutation) ResetTeamID() { + m.team = nil } -// AddedField returns the numeric value that was incremented/decremented on a field -// with the given name. The second boolean return value indicates that this field -// was not set, or was not defined in the schema. -func (m *TeamGroupModelMutation) AddedField(name string) (ent.Value, bool) { - return nil, false +// SetModelID sets the "model_id" field. +func (m *TeamModelMutation) SetModelID(u uuid.UUID) { + m.model = &u } -// 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 *TeamGroupModelMutation) AddField(name string, value ent.Value) error { - switch name { +// ModelID returns the value of the "model_id" field in the mutation. +func (m *TeamModelMutation) ModelID() (r uuid.UUID, exists bool) { + v := m.model + if v == nil { + return } - return fmt.Errorf("unknown TeamGroupModel numeric field %s", name) + return *v, true } -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *TeamGroupModelMutation) ClearedFields() []string { - return nil +// OldModelID returns the old "model_id" field's value of the TeamModel entity. +// If the TeamModel 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 *TeamModelMutation) OldModelID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldModelID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldModelID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldModelID: %w", err) + } + return oldValue.ModelID, nil } -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *TeamGroupModelMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok +// ResetModelID resets all changes to the "model_id" field. +func (m *TeamModelMutation) ResetModelID() { + m.model = nil } -// 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 *TeamGroupModelMutation) ClearField(name string) error { - return fmt.Errorf("unknown TeamGroupModel nullable field %s", name) +// SetCreatedAt sets the "created_at" field. +func (m *TeamModelMutation) SetCreatedAt(t time.Time) { + m.created_at = &t } -// 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 *TeamGroupModelMutation) ResetField(name string) error { - switch name { - case teamgroupmodel.FieldGroupID: - m.ResetGroupID() - return nil - case teamgroupmodel.FieldModelID: - m.ResetModelID() - return nil - case teamgroupmodel.FieldCreatedAt: - m.ResetCreatedAt() - return nil +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *TeamModelMutation) CreatedAt() (r time.Time, exists bool) { + v := m.created_at + if v == nil { + return } - return fmt.Errorf("unknown TeamGroupModel field %s", name) + return *v, true } -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *TeamGroupModelMutation) AddedEdges() []string { - edges := make([]string, 0, 2) - if m.group != nil { - edges = append(edges, teamgroupmodel.EdgeGroup) +// OldCreatedAt returns the old "created_at" field's value of the TeamModel entity. +// If the TeamModel 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 *TeamModelMutation) 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.model != nil { - edges = append(edges, teamgroupmodel.EdgeModel) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCreatedAt requires an ID field in the mutation") } - return edges + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + } + return oldValue.CreatedAt, nil } -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *TeamGroupModelMutation) AddedIDs(name string) []ent.Value { - switch name { - case teamgroupmodel.EdgeGroup: - if id := m.group; id != nil { - return []ent.Value{*id} - } - case teamgroupmodel.EdgeModel: - if id := m.model; id != nil { - return []ent.Value{*id} - } - } - return nil +// ResetCreatedAt resets all changes to the "created_at" field. +func (m *TeamModelMutation) ResetCreatedAt() { + m.created_at = nil } -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *TeamGroupModelMutation) RemovedEdges() []string { - edges := make([]string, 0, 2) - return edges +// ClearTeam clears the "team" edge to the Team entity. +func (m *TeamModelMutation) ClearTeam() { + m.clearedteam = true + m.clearedFields[teammodel.FieldTeamID] = struct{}{} } -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *TeamGroupModelMutation) RemovedIDs(name string) []ent.Value { - return nil +// TeamCleared reports if the "team" edge to the Team entity was cleared. +func (m *TeamModelMutation) TeamCleared() bool { + return m.clearedteam } -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *TeamGroupModelMutation) ClearedEdges() []string { - edges := make([]string, 0, 2) - if m.clearedgroup { - edges = append(edges, teamgroupmodel.EdgeGroup) - } - if m.clearedmodel { - edges = append(edges, teamgroupmodel.EdgeModel) +// TeamIDs returns the "team" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// TeamID instead. It exists only for internal usage by the builders. +func (m *TeamModelMutation) TeamIDs() (ids []uuid.UUID) { + if id := m.team; id != nil { + ids = append(ids, *id) } - return edges + return } -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *TeamGroupModelMutation) EdgeCleared(name string) bool { - switch name { - case teamgroupmodel.EdgeGroup: - return m.clearedgroup - case teamgroupmodel.EdgeModel: - return m.clearedmodel - } - return false +// ResetTeam resets all changes to the "team" edge. +func (m *TeamModelMutation) ResetTeam() { + m.team = nil + m.clearedteam = 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 *TeamGroupModelMutation) ClearEdge(name string) error { - switch name { - case teamgroupmodel.EdgeGroup: - m.ClearGroup() - return nil - case teamgroupmodel.EdgeModel: - m.ClearModel() - return nil - } - return fmt.Errorf("unknown TeamGroupModel unique edge %s", name) +// ClearModel clears the "model" edge to the Model entity. +func (m *TeamModelMutation) ClearModel() { + m.clearedmodel = true + m.clearedFields[teammodel.FieldModelID] = struct{}{} } -// 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 *TeamGroupModelMutation) ResetEdge(name string) error { - switch name { - case teamgroupmodel.EdgeGroup: - m.ResetGroup() - return nil - case teamgroupmodel.EdgeModel: - m.ResetModel() - return nil - } - return fmt.Errorf("unknown TeamGroupModel edge %s", name) +// ModelCleared reports if the "model" edge to the Model entity was cleared. +func (m *TeamModelMutation) ModelCleared() bool { + return m.clearedmodel } -// TeamImageMutation represents an operation that mutates the TeamImage nodes in the graph. -type TeamImageMutation struct { - config - op Op - typ string - id *uuid.UUID - created_at *time.Time - clearedFields map[string]struct{} - team *uuid.UUID - clearedteam bool - image *uuid.UUID - clearedimage bool - done bool - oldValue func(context.Context) (*TeamImage, error) - predicates []predicate.TeamImage +// ModelIDs returns the "model" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// ModelID instead. It exists only for internal usage by the builders. +func (m *TeamModelMutation) ModelIDs() (ids []uuid.UUID) { + if id := m.model; id != nil { + ids = append(ids, *id) + } + return } -var _ ent.Mutation = (*TeamImageMutation)(nil) +// ResetModel resets all changes to the "model" edge. +func (m *TeamModelMutation) ResetModel() { + m.model = nil + m.clearedmodel = false +} -// teamimageOption allows management of the mutation configuration using functional options. -type teamimageOption func(*TeamImageMutation) +// Where appends a list predicates to the TeamModelMutation builder. +func (m *TeamModelMutation) Where(ps ...predicate.TeamModel) { + m.predicates = append(m.predicates, ps...) +} -// newTeamImageMutation creates new mutation for the TeamImage entity. -func newTeamImageMutation(c config, op Op, opts ...teamimageOption) *TeamImageMutation { - m := &TeamImageMutation{ - config: c, - op: op, - typ: TypeTeamImage, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) +// WhereP appends storage-level predicates to the TeamModelMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *TeamModelMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.TeamModel, len(ps)) + for i := range ps { + p[i] = ps[i] } - return m + m.Where(p...) } -// withTeamImageID sets the ID field of the mutation. -func withTeamImageID(id uuid.UUID) teamimageOption { - return func(m *TeamImageMutation) { - var ( - err error - once sync.Once - value *TeamImage - ) - m.oldValue = func(ctx context.Context) (*TeamImage, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().TeamImage.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } +// Op returns the operation name. +func (m *TeamModelMutation) Op() Op { + return m.op } -// withTeamImage sets the old TeamImage of the mutation. -func withTeamImage(node *TeamImage) teamimageOption { - return func(m *TeamImageMutation) { - m.oldValue = func(context.Context) (*TeamImage, error) { - return node, nil - } - m.id = &node.ID - } +// SetOp allows setting the mutation operation. +func (m *TeamModelMutation) SetOp(op Op) { + m.op = op } -// 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 TeamImageMutation) Client() *Client { - client := &Client{config: m.config} - client.init() - return client +// Type returns the node type of this mutation (TeamModel). +func (m *TeamModelMutation) Type() string { + return m.typ } -// Tx returns an `ent.Tx` for mutations that were executed in transactions; -// it returns an error otherwise. -func (m TeamImageMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("db: mutation is not running in a transaction") +// 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 *TeamModelMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.team != nil { + fields = append(fields, teammodel.FieldTeamID) } - tx := &Tx{config: m.config} - tx.init() - return tx, nil + if m.model != nil { + fields = append(fields, teammodel.FieldModelID) + } + if m.created_at != nil { + fields = append(fields, teammodel.FieldCreatedAt) + } + return fields } -// SetID sets the value of the id field. Note that this -// operation is only accepted on creation of TeamImage entities. -func (m *TeamImageMutation) SetID(id uuid.UUID) { - m.id = &id +// 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 *TeamModelMutation) Field(name string) (ent.Value, bool) { + switch name { + case teammodel.FieldTeamID: + return m.TeamID() + case teammodel.FieldModelID: + return m.ModelID() + case teammodel.FieldCreatedAt: + return m.CreatedAt() + } + return nil, false } -// 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 *TeamImageMutation) ID() (id uuid.UUID, exists bool) { - if m.id == nil { - return +// 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 *TeamModelMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case teammodel.FieldTeamID: + return m.OldTeamID(ctx) + case teammodel.FieldModelID: + return m.OldModelID(ctx) + case teammodel.FieldCreatedAt: + return m.OldCreatedAt(ctx) } - return *m.id, true + return nil, fmt.Errorf("unknown TeamModel field %s", name) } -// 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 *TeamImageMutation) 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 +// 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 *TeamModelMutation) SetField(name string, value ent.Value) error { + switch name { + case teammodel.FieldTeamID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) } - fallthrough - case m.op.Is(OpUpdate | OpDelete): - return m.Client().TeamImage.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + m.SetTeamID(v) + return nil + case teammodel.FieldModelID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetModelID(v) + return nil + case teammodel.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil } + return fmt.Errorf("unknown TeamModel field %s", name) } -// SetTeamID sets the "team_id" field. -func (m *TeamImageMutation) SetTeamID(u uuid.UUID) { - m.team = &u +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *TeamModelMutation) AddedFields() []string { + return nil } -// TeamID returns the value of the "team_id" field in the mutation. -func (m *TeamImageMutation) TeamID() (r uuid.UUID, exists bool) { - v := m.team - if v == nil { - return - } - return *v, true +// 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 *TeamModelMutation) AddedField(name string) (ent.Value, bool) { + return nil, false } -// OldTeamID returns the old "team_id" field's value of the TeamImage entity. -// If the TeamImage 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 *TeamImageMutation) OldTeamID(ctx context.Context) (v uuid.UUID, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldTeamID is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldTeamID requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldTeamID: %w", err) +// 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 *TeamModelMutation) AddField(name string, value ent.Value) error { + switch name { } - return oldValue.TeamID, nil + return fmt.Errorf("unknown TeamModel numeric field %s", name) } -// ResetTeamID resets all changes to the "team_id" field. -func (m *TeamImageMutation) ResetTeamID() { - m.team = nil +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *TeamModelMutation) ClearedFields() []string { + return nil } -// SetImageID sets the "image_id" field. -func (m *TeamImageMutation) SetImageID(u uuid.UUID) { - m.image = &u +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *TeamModelMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok } -// ImageID returns the value of the "image_id" field in the mutation. -func (m *TeamImageMutation) ImageID() (r uuid.UUID, exists bool) { - v := m.image - if v == nil { - return - } - return *v, true +// 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 *TeamModelMutation) ClearField(name string) error { + return fmt.Errorf("unknown TeamModel nullable field %s", name) } -// OldImageID returns the old "image_id" field's value of the TeamImage entity. -// If the TeamImage 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 *TeamImageMutation) OldImageID(ctx context.Context) (v uuid.UUID, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldImageID is only allowed on UpdateOne operations") +// 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 *TeamModelMutation) ResetField(name string) error { + switch name { + case teammodel.FieldTeamID: + m.ResetTeamID() + return nil + case teammodel.FieldModelID: + m.ResetModelID() + return nil + case teammodel.FieldCreatedAt: + m.ResetCreatedAt() + return nil } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldImageID requires an ID field in the mutation") + return fmt.Errorf("unknown TeamModel field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *TeamModelMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.team != nil { + edges = append(edges, teammodel.EdgeTeam) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldImageID: %w", err) + if m.model != nil { + edges = append(edges, teammodel.EdgeModel) } - return oldValue.ImageID, nil + return edges } -// ResetImageID resets all changes to the "image_id" field. -func (m *TeamImageMutation) ResetImageID() { - m.image = nil +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *TeamModelMutation) AddedIDs(name string) []ent.Value { + switch name { + case teammodel.EdgeTeam: + if id := m.team; id != nil { + return []ent.Value{*id} + } + case teammodel.EdgeModel: + if id := m.model; id != nil { + return []ent.Value{*id} + } + } + return nil } -// SetCreatedAt sets the "created_at" field. -func (m *TeamImageMutation) SetCreatedAt(t time.Time) { - m.created_at = &t +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *TeamModelMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + return edges } -// CreatedAt returns the value of the "created_at" field in the mutation. -func (m *TeamImageMutation) CreatedAt() (r time.Time, exists bool) { - v := m.created_at - if v == nil { - return - } - return *v, true +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *TeamModelMutation) RemovedIDs(name string) []ent.Value { + return nil } -// OldCreatedAt returns the old "created_at" field's value of the TeamImage entity. -// If the TeamImage 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 *TeamImageMutation) 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") +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *TeamModelMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedteam { + edges = append(edges, teammodel.EdgeTeam) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCreatedAt requires an ID field in the mutation") + if m.clearedmodel { + edges = append(edges, teammodel.EdgeModel) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *TeamModelMutation) EdgeCleared(name string) bool { + switch name { + case teammodel.EdgeTeam: + return m.clearedteam + case teammodel.EdgeModel: + return m.clearedmodel } - return oldValue.CreatedAt, nil + return false } -// ResetCreatedAt resets all changes to the "created_at" field. -func (m *TeamImageMutation) ResetCreatedAt() { - m.created_at = nil +// 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 *TeamModelMutation) ClearEdge(name string) error { + switch name { + case teammodel.EdgeTeam: + m.ClearTeam() + return nil + case teammodel.EdgeModel: + m.ClearModel() + return nil + } + return fmt.Errorf("unknown TeamModel unique edge %s", name) } -// ClearTeam clears the "team" edge to the Team entity. -func (m *TeamImageMutation) ClearTeam() { - m.clearedteam = true - m.clearedFields[teamimage.FieldTeamID] = struct{}{} +// 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 *TeamModelMutation) ResetEdge(name string) error { + switch name { + case teammodel.EdgeTeam: + m.ResetTeam() + return nil + case teammodel.EdgeModel: + m.ResetModel() + return nil + } + return fmt.Errorf("unknown TeamModel edge %s", name) } -// TeamCleared reports if the "team" edge to the Team entity was cleared. -func (m *TeamImageMutation) TeamCleared() bool { - return m.clearedteam +// UserMutation represents an operation that mutates the User nodes in the graph. +type UserMutation struct { + config + op Op + typ string + id *uuid.UUID + deleted_at *time.Time + name *string + email *string + avatar_url *string + password *string + role *consts.UserRole + status *consts.UserStatus + is_blocked *bool + default_configs *map[consts.DefaultConfigType]uuid.UUID + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + identities map[uuid.UUID]struct{} + removedidentities map[uuid.UUID]struct{} + clearedidentities bool + audits map[uuid.UUID]struct{} + removedaudits map[uuid.UUID]struct{} + clearedaudits bool + teams map[uuid.UUID]struct{} + removedteams map[uuid.UUID]struct{} + clearedteams bool + groups map[uuid.UUID]struct{} + removedgroups map[uuid.UUID]struct{} + clearedgroups bool + models map[uuid.UUID]struct{} + removedmodels map[uuid.UUID]struct{} + clearedmodels bool + images map[uuid.UUID]struct{} + removedimages map[uuid.UUID]struct{} + clearedimages bool + hosts map[string]struct{} + removedhosts map[string]struct{} + clearedhosts bool + vms map[string]struct{} + removedvms map[string]struct{} + clearedvms bool + team_members map[uuid.UUID]struct{} + removedteam_members map[uuid.UUID]struct{} + clearedteam_members bool + team_group_members map[uuid.UUID]struct{} + removedteam_group_members map[uuid.UUID]struct{} + clearedteam_group_members bool + done bool + oldValue func(context.Context) (*User, error) + predicates []predicate.User } -// TeamIDs returns the "team" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// TeamID instead. It exists only for internal usage by the builders. -func (m *TeamImageMutation) TeamIDs() (ids []uuid.UUID) { - if id := m.team; id != nil { - ids = append(ids, *id) +var _ ent.Mutation = (*UserMutation)(nil) + +// userOption allows management of the mutation configuration using functional options. +type userOption func(*UserMutation) + +// newUserMutation creates new mutation for the User entity. +func newUserMutation(c config, op Op, opts ...userOption) *UserMutation { + m := &UserMutation{ + config: c, + op: op, + typ: TypeUser, + clearedFields: make(map[string]struct{}), } - return + for _, opt := range opts { + opt(m) + } + return m } -// ResetTeam resets all changes to the "team" edge. -func (m *TeamImageMutation) ResetTeam() { - m.team = nil - m.clearedteam = false +// withUserID sets the ID field of the mutation. +func withUserID(id uuid.UUID) userOption { + return func(m *UserMutation) { + var ( + err error + once sync.Once + value *User + ) + m.oldValue = func(ctx context.Context) (*User, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().User.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } } -// ClearImage clears the "image" edge to the Image entity. -func (m *TeamImageMutation) ClearImage() { - m.clearedimage = true - m.clearedFields[teamimage.FieldImageID] = struct{}{} +// withUser sets the old User of the mutation. +func withUser(node *User) userOption { + return func(m *UserMutation) { + m.oldValue = func(context.Context) (*User, error) { + return node, nil + } + m.id = &node.ID + } } -// ImageCleared reports if the "image" edge to the Image entity was cleared. -func (m *TeamImageMutation) ImageCleared() bool { - return m.clearedimage +// 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 UserMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client } -// ImageIDs returns the "image" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// ImageID instead. It exists only for internal usage by the builders. -func (m *TeamImageMutation) ImageIDs() (ids []uuid.UUID) { - if id := m.image; id != nil { - ids = append(ids, *id) +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m UserMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("db: mutation is not running in a transaction") } - return -} - -// ResetImage resets all changes to the "image" edge. -func (m *TeamImageMutation) ResetImage() { - m.image = nil - m.clearedimage = false + tx := &Tx{config: m.config} + tx.init() + return tx, nil } -// Where appends a list predicates to the TeamImageMutation builder. -func (m *TeamImageMutation) Where(ps ...predicate.TeamImage) { - m.predicates = append(m.predicates, ps...) +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of User entities. +func (m *UserMutation) SetID(id uuid.UUID) { + m.id = &id } -// WhereP appends storage-level predicates to the TeamImageMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *TeamImageMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.TeamImage, len(ps)) - for i := range ps { - p[i] = ps[i] +// 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 *UserMutation) ID() (id uuid.UUID, exists bool) { + if m.id == nil { + return } - m.Where(p...) + return *m.id, true } -// Op returns the operation name. -func (m *TeamImageMutation) Op() Op { - return m.op +// 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 *UserMutation) 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().User.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } } -// SetOp allows setting the mutation operation. -func (m *TeamImageMutation) SetOp(op Op) { - m.op = op +// SetDeletedAt sets the "deleted_at" field. +func (m *UserMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t } -// Type returns the node type of this mutation (TeamImage). -func (m *TeamImageMutation) Type() string { - return m.typ +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *UserMutation) DeletedAt() (r time.Time, exists bool) { + v := m.deleted_at + if v == nil { + return + } + return *v, true } -// 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 *TeamImageMutation) Fields() []string { - fields := make([]string, 0, 3) - if m.team != nil { - fields = append(fields, teamimage.FieldTeamID) - } - if m.image != nil { - fields = append(fields, teamimage.FieldImageID) +// OldDeletedAt returns the old "deleted_at" field's value of the User entity. +// If the User 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 *UserMutation) OldDeletedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") } - if m.created_at != nil { - fields = append(fields, teamimage.FieldCreatedAt) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDeletedAt requires an ID field in the mutation") } - 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 *TeamImageMutation) Field(name string) (ent.Value, bool) { - switch name { - case teamimage.FieldTeamID: - return m.TeamID() - case teamimage.FieldImageID: - return m.ImageID() - case teamimage.FieldCreatedAt: - return m.CreatedAt() + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDeletedAt: %w", err) } - return nil, false + return oldValue.DeletedAt, nil } -// 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 *TeamImageMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case teamimage.FieldTeamID: - return m.OldTeamID(ctx) - case teamimage.FieldImageID: - return m.OldImageID(ctx) - case teamimage.FieldCreatedAt: - return m.OldCreatedAt(ctx) - } - return nil, fmt.Errorf("unknown TeamImage field %s", name) +// ClearDeletedAt clears the value of the "deleted_at" field. +func (m *UserMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[user.FieldDeletedAt] = struct{}{} } -// 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 *TeamImageMutation) SetField(name string, value ent.Value) error { - switch name { - case teamimage.FieldTeamID: - v, ok := value.(uuid.UUID) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetTeamID(v) - return nil - case teamimage.FieldImageID: - v, ok := value.(uuid.UUID) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetImageID(v) - return nil - case teamimage.FieldCreatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCreatedAt(v) - return nil - } - return fmt.Errorf("unknown TeamImage field %s", name) +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *UserMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[user.FieldDeletedAt] + return ok } -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *TeamImageMutation) AddedFields() []string { - return nil +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *UserMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, user.FieldDeletedAt) } -// 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 *TeamImageMutation) AddedField(name string) (ent.Value, bool) { - return nil, false +// SetName sets the "name" field. +func (m *UserMutation) SetName(s string) { + m.name = &s } -// 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 *TeamImageMutation) AddField(name string, value ent.Value) error { - switch name { +// Name returns the value of the "name" field in the mutation. +func (m *UserMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return } - return fmt.Errorf("unknown TeamImage numeric field %s", name) + return *v, true } -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *TeamImageMutation) ClearedFields() []string { - return nil +// OldName returns the old "name" field's value of the User entity. +// If the User 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 *UserMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil } -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *TeamImageMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok +// ResetName resets all changes to the "name" field. +func (m *UserMutation) ResetName() { + m.name = nil } -// 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 *TeamImageMutation) ClearField(name string) error { - return fmt.Errorf("unknown TeamImage nullable field %s", name) +// SetEmail sets the "email" field. +func (m *UserMutation) SetEmail(s string) { + m.email = &s } -// 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 *TeamImageMutation) ResetField(name string) error { - switch name { - case teamimage.FieldTeamID: - m.ResetTeamID() - return nil - case teamimage.FieldImageID: - m.ResetImageID() - return nil - case teamimage.FieldCreatedAt: - m.ResetCreatedAt() - return nil +// Email returns the value of the "email" field in the mutation. +func (m *UserMutation) Email() (r string, exists bool) { + v := m.email + if v == nil { + return } - return fmt.Errorf("unknown TeamImage field %s", name) + return *v, true } -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *TeamImageMutation) AddedEdges() []string { - edges := make([]string, 0, 2) - if m.team != nil { - edges = append(edges, teamimage.EdgeTeam) +// OldEmail returns the old "email" field's value of the User entity. +// If the User 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 *UserMutation) OldEmail(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEmail is only allowed on UpdateOne operations") } - if m.image != nil { - edges = append(edges, teamimage.EdgeImage) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEmail requires an ID field in the mutation") } - return edges + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEmail: %w", err) + } + return oldValue.Email, nil } -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *TeamImageMutation) AddedIDs(name string) []ent.Value { - switch name { - case teamimage.EdgeTeam: - if id := m.team; id != nil { - return []ent.Value{*id} - } - case teamimage.EdgeImage: - if id := m.image; id != nil { - return []ent.Value{*id} - } - } - return nil +// ClearEmail clears the value of the "email" field. +func (m *UserMutation) ClearEmail() { + m.email = nil + m.clearedFields[user.FieldEmail] = struct{}{} } -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *TeamImageMutation) RemovedEdges() []string { - edges := make([]string, 0, 2) - return edges +// EmailCleared returns if the "email" field was cleared in this mutation. +func (m *UserMutation) EmailCleared() bool { + _, ok := m.clearedFields[user.FieldEmail] + return ok } -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *TeamImageMutation) RemovedIDs(name string) []ent.Value { - return nil +// ResetEmail resets all changes to the "email" field. +func (m *UserMutation) ResetEmail() { + m.email = nil + delete(m.clearedFields, user.FieldEmail) } -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *TeamImageMutation) ClearedEdges() []string { - edges := make([]string, 0, 2) - if m.clearedteam { - edges = append(edges, teamimage.EdgeTeam) - } - if m.clearedimage { - edges = append(edges, teamimage.EdgeImage) - } - return edges +// SetAvatarURL sets the "avatar_url" field. +func (m *UserMutation) SetAvatarURL(s string) { + m.avatar_url = &s } -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *TeamImageMutation) EdgeCleared(name string) bool { - switch name { - case teamimage.EdgeTeam: - return m.clearedteam - case teamimage.EdgeImage: - return m.clearedimage +// AvatarURL returns the value of the "avatar_url" field in the mutation. +func (m *UserMutation) AvatarURL() (r string, exists bool) { + v := m.avatar_url + if v == nil { + return } - return false + return *v, true } -// 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 *TeamImageMutation) ClearEdge(name string) error { - switch name { - case teamimage.EdgeTeam: - m.ClearTeam() - return nil - case teamimage.EdgeImage: - m.ClearImage() - return nil +// OldAvatarURL returns the old "avatar_url" field's value of the User entity. +// If the User 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 *UserMutation) OldAvatarURL(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldAvatarURL is only allowed on UpdateOne operations") } - return fmt.Errorf("unknown TeamImage unique edge %s", name) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldAvatarURL requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldAvatarURL: %w", err) + } + return oldValue.AvatarURL, nil } -// 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 *TeamImageMutation) ResetEdge(name string) error { - switch name { - case teamimage.EdgeTeam: - m.ResetTeam() - return nil - case teamimage.EdgeImage: - m.ResetImage() - return nil - } - return fmt.Errorf("unknown TeamImage edge %s", name) +// ClearAvatarURL clears the value of the "avatar_url" field. +func (m *UserMutation) ClearAvatarURL() { + m.avatar_url = nil + m.clearedFields[user.FieldAvatarURL] = struct{}{} } -// TeamMemberMutation represents an operation that mutates the TeamMember nodes in the graph. -type TeamMemberMutation struct { - config - op Op - typ string - id *uuid.UUID - role *consts.TeamMemberRole - created_at *time.Time - clearedFields map[string]struct{} - team *uuid.UUID - clearedteam bool - user *uuid.UUID - cleareduser bool - done bool - oldValue func(context.Context) (*TeamMember, error) - predicates []predicate.TeamMember +// AvatarURLCleared returns if the "avatar_url" field was cleared in this mutation. +func (m *UserMutation) AvatarURLCleared() bool { + _, ok := m.clearedFields[user.FieldAvatarURL] + return ok } -var _ ent.Mutation = (*TeamMemberMutation)(nil) +// ResetAvatarURL resets all changes to the "avatar_url" field. +func (m *UserMutation) ResetAvatarURL() { + m.avatar_url = nil + delete(m.clearedFields, user.FieldAvatarURL) +} -// teammemberOption allows management of the mutation configuration using functional options. -type teammemberOption func(*TeamMemberMutation) +// SetPassword sets the "password" field. +func (m *UserMutation) SetPassword(s string) { + m.password = &s +} -// newTeamMemberMutation creates new mutation for the TeamMember entity. -func newTeamMemberMutation(c config, op Op, opts ...teammemberOption) *TeamMemberMutation { - m := &TeamMemberMutation{ - config: c, - op: op, - typ: TypeTeamMember, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) +// Password returns the value of the "password" field in the mutation. +func (m *UserMutation) Password() (r string, exists bool) { + v := m.password + if v == nil { + return } - return m + return *v, true } -// withTeamMemberID sets the ID field of the mutation. -func withTeamMemberID(id uuid.UUID) teammemberOption { - return func(m *TeamMemberMutation) { - var ( - err error - once sync.Once - value *TeamMember - ) - m.oldValue = func(ctx context.Context) (*TeamMember, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().TeamMember.Get(ctx, id) - } - }) - return value, err - } - m.id = &id +// OldPassword returns the old "password" field's value of the User entity. +// If the User 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 *UserMutation) OldPassword(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPassword is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPassword requires an ID field in the mutation") } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPassword: %w", err) + } + return oldValue.Password, nil } -// withTeamMember sets the old TeamMember of the mutation. -func withTeamMember(node *TeamMember) teammemberOption { - return func(m *TeamMemberMutation) { - m.oldValue = func(context.Context) (*TeamMember, error) { - return node, nil - } - m.id = &node.ID - } +// ClearPassword clears the value of the "password" field. +func (m *UserMutation) ClearPassword() { + m.password = nil + m.clearedFields[user.FieldPassword] = struct{}{} } -// 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 TeamMemberMutation) Client() *Client { - client := &Client{config: m.config} - client.init() - return client +// PasswordCleared returns if the "password" field was cleared in this mutation. +func (m *UserMutation) PasswordCleared() bool { + _, ok := m.clearedFields[user.FieldPassword] + return ok } -// Tx returns an `ent.Tx` for mutations that were executed in transactions; -// it returns an error otherwise. -func (m TeamMemberMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("db: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil +// ResetPassword resets all changes to the "password" field. +func (m *UserMutation) ResetPassword() { + m.password = nil + delete(m.clearedFields, user.FieldPassword) } -// SetID sets the value of the id field. Note that this -// operation is only accepted on creation of TeamMember entities. -func (m *TeamMemberMutation) SetID(id uuid.UUID) { - m.id = &id +// SetRole sets the "role" field. +func (m *UserMutation) SetRole(cr consts.UserRole) { + m.role = &cr } -// 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 *TeamMemberMutation) ID() (id uuid.UUID, exists bool) { - if m.id == nil { +// Role returns the value of the "role" field in the mutation. +func (m *UserMutation) Role() (r consts.UserRole, exists bool) { + v := m.role + if v == nil { return } - return *m.id, true + return *v, 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 *TeamMemberMutation) 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().TeamMember.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) +// OldRole returns the old "role" field's value of the User entity. +// If the User 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 *UserMutation) OldRole(ctx context.Context) (v consts.UserRole, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRole is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRole requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRole: %w", err) } + return oldValue.Role, nil } -// SetTeamID sets the "team_id" field. -func (m *TeamMemberMutation) SetTeamID(u uuid.UUID) { - m.team = &u +// ResetRole resets all changes to the "role" field. +func (m *UserMutation) ResetRole() { + m.role = nil } -// TeamID returns the value of the "team_id" field in the mutation. -func (m *TeamMemberMutation) TeamID() (r uuid.UUID, exists bool) { - v := m.team +// SetStatus sets the "status" field. +func (m *UserMutation) SetStatus(cs consts.UserStatus) { + m.status = &cs +} + +// Status returns the value of the "status" field in the mutation. +func (m *UserMutation) Status() (r consts.UserStatus, exists bool) { + v := m.status if v == nil { return } return *v, true } -// OldTeamID returns the old "team_id" field's value of the TeamMember entity. -// If the TeamMember object wasn't provided to the builder, the object is fetched from the database. +// OldStatus returns the old "status" field's value of the User entity. +// If the User 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 *TeamMemberMutation) OldTeamID(ctx context.Context) (v uuid.UUID, err error) { +func (m *UserMutation) OldStatus(ctx context.Context) (v consts.UserStatus, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldTeamID is only allowed on UpdateOne operations") + return v, errors.New("OldStatus is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldTeamID requires an ID field in the mutation") + return v, errors.New("OldStatus requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldTeamID: %w", err) + return v, fmt.Errorf("querying old value for OldStatus: %w", err) } - return oldValue.TeamID, nil + return oldValue.Status, nil } -// ResetTeamID resets all changes to the "team_id" field. -func (m *TeamMemberMutation) ResetTeamID() { - m.team = nil +// ResetStatus resets all changes to the "status" field. +func (m *UserMutation) ResetStatus() { + m.status = nil } -// SetUserID sets the "user_id" field. -func (m *TeamMemberMutation) SetUserID(u uuid.UUID) { - m.user = &u +// SetIsBlocked sets the "is_blocked" field. +func (m *UserMutation) SetIsBlocked(b bool) { + m.is_blocked = &b } -// UserID returns the value of the "user_id" field in the mutation. -func (m *TeamMemberMutation) UserID() (r uuid.UUID, exists bool) { - v := m.user +// IsBlocked returns the value of the "is_blocked" field in the mutation. +func (m *UserMutation) IsBlocked() (r bool, exists bool) { + v := m.is_blocked if v == nil { return } return *v, true } -// OldUserID returns the old "user_id" field's value of the TeamMember entity. -// If the TeamMember object wasn't provided to the builder, the object is fetched from the database. +// OldIsBlocked returns the old "is_blocked" field's value of the User entity. +// If the User 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 *TeamMemberMutation) OldUserID(ctx context.Context) (v uuid.UUID, err error) { +func (m *UserMutation) OldIsBlocked(ctx context.Context) (v bool, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUserID is only allowed on UpdateOne operations") + return v, errors.New("OldIsBlocked is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUserID requires an ID field in the mutation") + return v, errors.New("OldIsBlocked requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldUserID: %w", err) + return v, fmt.Errorf("querying old value for OldIsBlocked: %w", err) } - return oldValue.UserID, nil + return oldValue.IsBlocked, nil } -// ResetUserID resets all changes to the "user_id" field. -func (m *TeamMemberMutation) ResetUserID() { - m.user = nil +// ResetIsBlocked resets all changes to the "is_blocked" field. +func (m *UserMutation) ResetIsBlocked() { + m.is_blocked = nil } -// SetRole sets the "role" field. -func (m *TeamMemberMutation) SetRole(cmr consts.TeamMemberRole) { - m.role = &cmr +// SetDefaultConfigs sets the "default_configs" field. +func (m *UserMutation) SetDefaultConfigs(mct map[consts.DefaultConfigType]uuid.UUID) { + m.default_configs = &mct } -// Role returns the value of the "role" field in the mutation. -func (m *TeamMemberMutation) Role() (r consts.TeamMemberRole, exists bool) { - v := m.role +// DefaultConfigs returns the value of the "default_configs" field in the mutation. +func (m *UserMutation) DefaultConfigs() (r map[consts.DefaultConfigType]uuid.UUID, exists bool) { + v := m.default_configs if v == nil { return } return *v, true } -// OldRole returns the old "role" field's value of the TeamMember entity. -// If the TeamMember object wasn't provided to the builder, the object is fetched from the database. +// OldDefaultConfigs returns the old "default_configs" field's value of the User entity. +// If the User 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 *TeamMemberMutation) OldRole(ctx context.Context) (v consts.TeamMemberRole, err error) { +func (m *UserMutation) OldDefaultConfigs(ctx context.Context) (v map[consts.DefaultConfigType]uuid.UUID, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldRole is only allowed on UpdateOne operations") + return v, errors.New("OldDefaultConfigs is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldRole requires an ID field in the mutation") + return v, errors.New("OldDefaultConfigs requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldRole: %w", err) + return v, fmt.Errorf("querying old value for OldDefaultConfigs: %w", err) } - return oldValue.Role, nil + return oldValue.DefaultConfigs, nil } -// ResetRole resets all changes to the "role" field. -func (m *TeamMemberMutation) ResetRole() { - m.role = nil +// ClearDefaultConfigs clears the value of the "default_configs" field. +func (m *UserMutation) ClearDefaultConfigs() { + m.default_configs = nil + m.clearedFields[user.FieldDefaultConfigs] = struct{}{} +} + +// DefaultConfigsCleared returns if the "default_configs" field was cleared in this mutation. +func (m *UserMutation) DefaultConfigsCleared() bool { + _, ok := m.clearedFields[user.FieldDefaultConfigs] + return ok +} + +// ResetDefaultConfigs resets all changes to the "default_configs" field. +func (m *UserMutation) ResetDefaultConfigs() { + m.default_configs = nil + delete(m.clearedFields, user.FieldDefaultConfigs) } // SetCreatedAt sets the "created_at" field. -func (m *TeamMemberMutation) SetCreatedAt(t time.Time) { +func (m *UserMutation) SetCreatedAt(t time.Time) { m.created_at = &t } // CreatedAt returns the value of the "created_at" field in the mutation. -func (m *TeamMemberMutation) CreatedAt() (r time.Time, exists bool) { +func (m *UserMutation) CreatedAt() (r time.Time, exists bool) { v := m.created_at if v == nil { return @@ -8223,648 +12827,613 @@ func (m *TeamMemberMutation) CreatedAt() (r time.Time, exists bool) { return *v, true } -// OldCreatedAt returns the old "created_at" field's value of the TeamMember entity. -// If the TeamMember object wasn't provided to the builder, the object is fetched from the database. +// OldCreatedAt returns the old "created_at" field's value of the User entity. +// If the User 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 *TeamMemberMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { +func (m *UserMutation) 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) + 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 *UserMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUpdatedAt sets the "updated_at" field. +func (m *UserMutation) SetUpdatedAt(t time.Time) { + m.updated_at = &t +} + +// UpdatedAt returns the value of the "updated_at" field in the mutation. +func (m *UserMutation) 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 User entity. +// If the User 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 *UserMutation) 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 *UserMutation) ResetUpdatedAt() { + m.updated_at = nil +} + +// AddIdentityIDs adds the "identities" edge to the UserIdentity entity by ids. +func (m *UserMutation) AddIdentityIDs(ids ...uuid.UUID) { + if m.identities == nil { + m.identities = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.identities[ids[i]] = struct{}{} } - return oldValue.CreatedAt, nil } -// ResetCreatedAt resets all changes to the "created_at" field. -func (m *TeamMemberMutation) ResetCreatedAt() { - m.created_at = nil +// ClearIdentities clears the "identities" edge to the UserIdentity entity. +func (m *UserMutation) ClearIdentities() { + m.clearedidentities = true } -// ClearTeam clears the "team" edge to the Team entity. -func (m *TeamMemberMutation) ClearTeam() { - m.clearedteam = true - m.clearedFields[teammember.FieldTeamID] = struct{}{} +// IdentitiesCleared reports if the "identities" edge to the UserIdentity entity was cleared. +func (m *UserMutation) IdentitiesCleared() bool { + return m.clearedidentities } -// TeamCleared reports if the "team" edge to the Team entity was cleared. -func (m *TeamMemberMutation) TeamCleared() bool { - return m.clearedteam +// RemoveIdentityIDs removes the "identities" edge to the UserIdentity entity by IDs. +func (m *UserMutation) RemoveIdentityIDs(ids ...uuid.UUID) { + if m.removedidentities == nil { + m.removedidentities = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.identities, ids[i]) + m.removedidentities[ids[i]] = struct{}{} + } } -// TeamIDs returns the "team" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// TeamID instead. It exists only for internal usage by the builders. -func (m *TeamMemberMutation) TeamIDs() (ids []uuid.UUID) { - if id := m.team; id != nil { - ids = append(ids, *id) +// RemovedIdentities returns the removed IDs of the "identities" edge to the UserIdentity entity. +func (m *UserMutation) RemovedIdentitiesIDs() (ids []uuid.UUID) { + for id := range m.removedidentities { + ids = append(ids, id) } return } -// ResetTeam resets all changes to the "team" edge. -func (m *TeamMemberMutation) ResetTeam() { - m.team = nil - m.clearedteam = false -} - -// ClearUser clears the "user" edge to the User entity. -func (m *TeamMemberMutation) ClearUser() { - m.cleareduser = true - m.clearedFields[teammember.FieldUserID] = struct{}{} +// IdentitiesIDs returns the "identities" edge IDs in the mutation. +func (m *UserMutation) IdentitiesIDs() (ids []uuid.UUID) { + for id := range m.identities { + ids = append(ids, id) + } + return } -// UserCleared reports if the "user" edge to the User entity was cleared. -func (m *TeamMemberMutation) UserCleared() bool { - return m.cleareduser +// ResetIdentities resets all changes to the "identities" edge. +func (m *UserMutation) ResetIdentities() { + m.identities = nil + m.clearedidentities = false + m.removedidentities = nil } -// UserIDs returns the "user" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// UserID instead. It exists only for internal usage by the builders. -func (m *TeamMemberMutation) UserIDs() (ids []uuid.UUID) { - if id := m.user; id != nil { - ids = append(ids, *id) +// AddAuditIDs adds the "audits" edge to the Audit entity by ids. +func (m *UserMutation) AddAuditIDs(ids ...uuid.UUID) { + if m.audits == nil { + m.audits = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.audits[ids[i]] = struct{}{} } - return } -// ResetUser resets all changes to the "user" edge. -func (m *TeamMemberMutation) ResetUser() { - m.user = nil - m.cleareduser = false +// ClearAudits clears the "audits" edge to the Audit entity. +func (m *UserMutation) ClearAudits() { + m.clearedaudits = true } -// Where appends a list predicates to the TeamMemberMutation builder. -func (m *TeamMemberMutation) Where(ps ...predicate.TeamMember) { - m.predicates = append(m.predicates, ps...) +// AuditsCleared reports if the "audits" edge to the Audit entity was cleared. +func (m *UserMutation) AuditsCleared() bool { + return m.clearedaudits } -// WhereP appends storage-level predicates to the TeamMemberMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *TeamMemberMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.TeamMember, len(ps)) - for i := range ps { - p[i] = ps[i] +// RemoveAuditIDs removes the "audits" edge to the Audit entity by IDs. +func (m *UserMutation) RemoveAuditIDs(ids ...uuid.UUID) { + if m.removedaudits == nil { + m.removedaudits = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.audits, ids[i]) + m.removedaudits[ids[i]] = struct{}{} } - m.Where(p...) } -// Op returns the operation name. -func (m *TeamMemberMutation) Op() Op { - return m.op +// RemovedAudits returns the removed IDs of the "audits" edge to the Audit entity. +func (m *UserMutation) RemovedAuditsIDs() (ids []uuid.UUID) { + for id := range m.removedaudits { + ids = append(ids, id) + } + return } -// SetOp allows setting the mutation operation. -func (m *TeamMemberMutation) SetOp(op Op) { - m.op = op +// AuditsIDs returns the "audits" edge IDs in the mutation. +func (m *UserMutation) AuditsIDs() (ids []uuid.UUID) { + for id := range m.audits { + ids = append(ids, id) + } + return } -// Type returns the node type of this mutation (TeamMember). -func (m *TeamMemberMutation) Type() string { - return m.typ +// ResetAudits resets all changes to the "audits" edge. +func (m *UserMutation) ResetAudits() { + m.audits = nil + m.clearedaudits = false + m.removedaudits = nil } -// 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 *TeamMemberMutation) Fields() []string { - fields := make([]string, 0, 4) - if m.team != nil { - fields = append(fields, teammember.FieldTeamID) - } - if m.user != nil { - fields = append(fields, teammember.FieldUserID) - } - if m.role != nil { - fields = append(fields, teammember.FieldRole) +// AddTeamIDs adds the "teams" edge to the Team entity by ids. +func (m *UserMutation) AddTeamIDs(ids ...uuid.UUID) { + if m.teams == nil { + m.teams = make(map[uuid.UUID]struct{}) } - if m.created_at != nil { - fields = append(fields, teammember.FieldCreatedAt) + for i := range ids { + m.teams[ids[i]] = struct{}{} } - 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 *TeamMemberMutation) Field(name string) (ent.Value, bool) { - switch name { - case teammember.FieldTeamID: - return m.TeamID() - case teammember.FieldUserID: - return m.UserID() - case teammember.FieldRole: - return m.Role() - case teammember.FieldCreatedAt: - return m.CreatedAt() - } - return nil, false +// ClearTeams clears the "teams" edge to the Team entity. +func (m *UserMutation) ClearTeams() { + m.clearedteams = true } -// 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 *TeamMemberMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case teammember.FieldTeamID: - return m.OldTeamID(ctx) - case teammember.FieldUserID: - return m.OldUserID(ctx) - case teammember.FieldRole: - return m.OldRole(ctx) - case teammember.FieldCreatedAt: - return m.OldCreatedAt(ctx) - } - return nil, fmt.Errorf("unknown TeamMember field %s", name) +// TeamsCleared reports if the "teams" edge to the Team entity was cleared. +func (m *UserMutation) TeamsCleared() bool { + return m.clearedteams } -// 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 *TeamMemberMutation) SetField(name string, value ent.Value) error { - switch name { - case teammember.FieldTeamID: - v, ok := value.(uuid.UUID) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetTeamID(v) - return nil - case teammember.FieldUserID: - v, ok := value.(uuid.UUID) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUserID(v) - return nil - case teammember.FieldRole: - v, ok := value.(consts.TeamMemberRole) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetRole(v) - return nil - case teammember.FieldCreatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCreatedAt(v) - return nil +// RemoveTeamIDs removes the "teams" edge to the Team entity by IDs. +func (m *UserMutation) RemoveTeamIDs(ids ...uuid.UUID) { + if m.removedteams == nil { + m.removedteams = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.teams, ids[i]) + m.removedteams[ids[i]] = struct{}{} } - return fmt.Errorf("unknown TeamMember field %s", name) -} - -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *TeamMemberMutation) AddedFields() []string { - return nil } -// AddedField returns the numeric value that was incremented/decremented on a field -// with the given name. The second boolean return value indicates that this field -// was not set, or was not defined in the schema. -func (m *TeamMemberMutation) AddedField(name string) (ent.Value, bool) { - return nil, false +// RemovedTeams returns the removed IDs of the "teams" edge to the Team entity. +func (m *UserMutation) RemovedTeamsIDs() (ids []uuid.UUID) { + for id := range m.removedteams { + ids = append(ids, id) + } + return } -// 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 *TeamMemberMutation) AddField(name string, value ent.Value) error { - switch name { +// TeamsIDs returns the "teams" edge IDs in the mutation. +func (m *UserMutation) TeamsIDs() (ids []uuid.UUID) { + for id := range m.teams { + ids = append(ids, id) } - return fmt.Errorf("unknown TeamMember numeric field %s", name) + return } -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *TeamMemberMutation) ClearedFields() []string { - return nil +// ResetTeams resets all changes to the "teams" edge. +func (m *UserMutation) ResetTeams() { + m.teams = nil + m.clearedteams = false + m.removedteams = nil } -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *TeamMemberMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok +// AddGroupIDs adds the "groups" edge to the TeamGroup entity by ids. +func (m *UserMutation) AddGroupIDs(ids ...uuid.UUID) { + if m.groups == nil { + m.groups = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.groups[ids[i]] = struct{}{} + } } -// 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 *TeamMemberMutation) ClearField(name string) error { - return fmt.Errorf("unknown TeamMember nullable field %s", name) +// ClearGroups clears the "groups" edge to the TeamGroup entity. +func (m *UserMutation) ClearGroups() { + m.clearedgroups = true } -// 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 *TeamMemberMutation) ResetField(name string) error { - switch name { - case teammember.FieldTeamID: - m.ResetTeamID() - return nil - case teammember.FieldUserID: - m.ResetUserID() - return nil - case teammember.FieldRole: - m.ResetRole() - return nil - case teammember.FieldCreatedAt: - m.ResetCreatedAt() - return nil - } - return fmt.Errorf("unknown TeamMember field %s", name) +// GroupsCleared reports if the "groups" edge to the TeamGroup entity was cleared. +func (m *UserMutation) GroupsCleared() bool { + return m.clearedgroups } -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *TeamMemberMutation) AddedEdges() []string { - edges := make([]string, 0, 2) - if m.team != nil { - edges = append(edges, teammember.EdgeTeam) +// RemoveGroupIDs removes the "groups" edge to the TeamGroup entity by IDs. +func (m *UserMutation) RemoveGroupIDs(ids ...uuid.UUID) { + if m.removedgroups == nil { + m.removedgroups = make(map[uuid.UUID]struct{}) } - if m.user != nil { - edges = append(edges, teammember.EdgeUser) + for i := range ids { + delete(m.groups, ids[i]) + m.removedgroups[ids[i]] = struct{}{} } - return edges } -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *TeamMemberMutation) AddedIDs(name string) []ent.Value { - switch name { - case teammember.EdgeTeam: - if id := m.team; id != nil { - return []ent.Value{*id} - } - case teammember.EdgeUser: - if id := m.user; id != nil { - return []ent.Value{*id} - } +// RemovedGroups returns the removed IDs of the "groups" edge to the TeamGroup entity. +func (m *UserMutation) RemovedGroupsIDs() (ids []uuid.UUID) { + for id := range m.removedgroups { + ids = append(ids, id) } - return nil + return } -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *TeamMemberMutation) RemovedEdges() []string { - edges := make([]string, 0, 2) - return edges +// GroupsIDs returns the "groups" edge IDs in the mutation. +func (m *UserMutation) GroupsIDs() (ids []uuid.UUID) { + for id := range m.groups { + ids = append(ids, id) + } + return } -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *TeamMemberMutation) RemovedIDs(name string) []ent.Value { - return nil +// ResetGroups resets all changes to the "groups" edge. +func (m *UserMutation) ResetGroups() { + m.groups = nil + m.clearedgroups = false + m.removedgroups = nil } -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *TeamMemberMutation) ClearedEdges() []string { - edges := make([]string, 0, 2) - if m.clearedteam { - edges = append(edges, teammember.EdgeTeam) +// AddModelIDs adds the "models" edge to the Model entity by ids. +func (m *UserMutation) AddModelIDs(ids ...uuid.UUID) { + if m.models == nil { + m.models = make(map[uuid.UUID]struct{}) } - if m.cleareduser { - edges = append(edges, teammember.EdgeUser) + for i := range ids { + m.models[ids[i]] = struct{}{} } - return edges } -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *TeamMemberMutation) EdgeCleared(name string) bool { - switch name { - case teammember.EdgeTeam: - return m.clearedteam - case teammember.EdgeUser: - return m.cleareduser - } - return false +// ClearModels clears the "models" edge to the Model entity. +func (m *UserMutation) ClearModels() { + m.clearedmodels = true } -// 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 *TeamMemberMutation) ClearEdge(name string) error { - switch name { - case teammember.EdgeTeam: - m.ClearTeam() - return nil - case teammember.EdgeUser: - m.ClearUser() - return nil - } - return fmt.Errorf("unknown TeamMember unique edge %s", name) +// ModelsCleared reports if the "models" edge to the Model entity was cleared. +func (m *UserMutation) ModelsCleared() bool { + return m.clearedmodels } -// 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 *TeamMemberMutation) ResetEdge(name string) error { - switch name { - case teammember.EdgeTeam: - m.ResetTeam() - return nil - case teammember.EdgeUser: - m.ResetUser() - return nil +// RemoveModelIDs removes the "models" edge to the Model entity by IDs. +func (m *UserMutation) RemoveModelIDs(ids ...uuid.UUID) { + if m.removedmodels == nil { + m.removedmodels = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.models, ids[i]) + m.removedmodels[ids[i]] = struct{}{} } - return fmt.Errorf("unknown TeamMember edge %s", name) } -// TeamModelMutation represents an operation that mutates the TeamModel nodes in the graph. -type TeamModelMutation struct { - config - op Op - typ string - id *uuid.UUID - created_at *time.Time - clearedFields map[string]struct{} - team *uuid.UUID - clearedteam bool - model *uuid.UUID - clearedmodel bool - done bool - oldValue func(context.Context) (*TeamModel, error) - predicates []predicate.TeamModel +// RemovedModels returns the removed IDs of the "models" edge to the Model entity. +func (m *UserMutation) RemovedModelsIDs() (ids []uuid.UUID) { + for id := range m.removedmodels { + ids = append(ids, id) + } + return } -var _ ent.Mutation = (*TeamModelMutation)(nil) +// ModelsIDs returns the "models" edge IDs in the mutation. +func (m *UserMutation) ModelsIDs() (ids []uuid.UUID) { + for id := range m.models { + ids = append(ids, id) + } + return +} -// teammodelOption allows management of the mutation configuration using functional options. -type teammodelOption func(*TeamModelMutation) +// ResetModels resets all changes to the "models" edge. +func (m *UserMutation) ResetModels() { + m.models = nil + m.clearedmodels = false + m.removedmodels = nil +} -// newTeamModelMutation creates new mutation for the TeamModel entity. -func newTeamModelMutation(c config, op Op, opts ...teammodelOption) *TeamModelMutation { - m := &TeamModelMutation{ - config: c, - op: op, - typ: TypeTeamModel, - clearedFields: make(map[string]struct{}), +// AddImageIDs adds the "images" edge to the Image entity by ids. +func (m *UserMutation) AddImageIDs(ids ...uuid.UUID) { + if m.images == nil { + m.images = make(map[uuid.UUID]struct{}) } - for _, opt := range opts { - opt(m) + for i := range ids { + m.images[ids[i]] = struct{}{} } - return m } -// withTeamModelID sets the ID field of the mutation. -func withTeamModelID(id uuid.UUID) teammodelOption { - return func(m *TeamModelMutation) { - var ( - err error - once sync.Once - value *TeamModel - ) - m.oldValue = func(ctx context.Context) (*TeamModel, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().TeamModel.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } +// ClearImages clears the "images" edge to the Image entity. +func (m *UserMutation) ClearImages() { + m.clearedimages = true +} + +// ImagesCleared reports if the "images" edge to the Image entity was cleared. +func (m *UserMutation) ImagesCleared() bool { + return m.clearedimages } -// withTeamModel sets the old TeamModel of the mutation. -func withTeamModel(node *TeamModel) teammodelOption { - return func(m *TeamModelMutation) { - m.oldValue = func(context.Context) (*TeamModel, error) { - return node, nil - } - m.id = &node.ID +// RemoveImageIDs removes the "images" edge to the Image entity by IDs. +func (m *UserMutation) RemoveImageIDs(ids ...uuid.UUID) { + if m.removedimages == nil { + m.removedimages = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.images, ids[i]) + m.removedimages[ids[i]] = struct{}{} } } -// 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 TeamModelMutation) Client() *Client { - client := &Client{config: m.config} - client.init() - return client +// RemovedImages returns the removed IDs of the "images" edge to the Image entity. +func (m *UserMutation) RemovedImagesIDs() (ids []uuid.UUID) { + for id := range m.removedimages { + ids = append(ids, id) + } + return } -// Tx returns an `ent.Tx` for mutations that were executed in transactions; -// it returns an error otherwise. -func (m TeamModelMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("db: mutation is not running in a transaction") +// ImagesIDs returns the "images" edge IDs in the mutation. +func (m *UserMutation) ImagesIDs() (ids []uuid.UUID) { + for id := range m.images { + ids = append(ids, id) } - tx := &Tx{config: m.config} - tx.init() - return tx, nil + return } -// SetID sets the value of the id field. Note that this -// operation is only accepted on creation of TeamModel entities. -func (m *TeamModelMutation) SetID(id uuid.UUID) { - m.id = &id +// ResetImages resets all changes to the "images" edge. +func (m *UserMutation) ResetImages() { + m.images = nil + m.clearedimages = false + m.removedimages = nil } -// 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 *TeamModelMutation) ID() (id uuid.UUID, exists bool) { - if m.id == nil { - return +// AddHostIDs adds the "hosts" edge to the Host entity by ids. +func (m *UserMutation) AddHostIDs(ids ...string) { + if m.hosts == nil { + m.hosts = make(map[string]struct{}) } - 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 *TeamModelMutation) 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().TeamModel.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + for i := range ids { + m.hosts[ids[i]] = struct{}{} } } -// SetTeamID sets the "team_id" field. -func (m *TeamModelMutation) SetTeamID(u uuid.UUID) { - m.team = &u +// ClearHosts clears the "hosts" edge to the Host entity. +func (m *UserMutation) ClearHosts() { + m.clearedhosts = true } -// TeamID returns the value of the "team_id" field in the mutation. -func (m *TeamModelMutation) TeamID() (r uuid.UUID, exists bool) { - v := m.team - if v == nil { - return - } - return *v, true +// HostsCleared reports if the "hosts" edge to the Host entity was cleared. +func (m *UserMutation) HostsCleared() bool { + return m.clearedhosts } -// OldTeamID returns the old "team_id" field's value of the TeamModel entity. -// If the TeamModel 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 *TeamModelMutation) OldTeamID(ctx context.Context) (v uuid.UUID, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldTeamID is only allowed on UpdateOne operations") +// RemoveHostIDs removes the "hosts" edge to the Host entity by IDs. +func (m *UserMutation) RemoveHostIDs(ids ...string) { + if m.removedhosts == nil { + m.removedhosts = make(map[string]struct{}) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldTeamID requires an ID field in the mutation") + for i := range ids { + delete(m.hosts, ids[i]) + m.removedhosts[ids[i]] = struct{}{} } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldTeamID: %w", err) +} + +// RemovedHosts returns the removed IDs of the "hosts" edge to the Host entity. +func (m *UserMutation) RemovedHostsIDs() (ids []string) { + for id := range m.removedhosts { + ids = append(ids, id) } - return oldValue.TeamID, nil + return } -// ResetTeamID resets all changes to the "team_id" field. -func (m *TeamModelMutation) ResetTeamID() { - m.team = nil +// HostsIDs returns the "hosts" edge IDs in the mutation. +func (m *UserMutation) HostsIDs() (ids []string) { + for id := range m.hosts { + ids = append(ids, id) + } + return } -// SetModelID sets the "model_id" field. -func (m *TeamModelMutation) SetModelID(u uuid.UUID) { - m.model = &u +// ResetHosts resets all changes to the "hosts" edge. +func (m *UserMutation) ResetHosts() { + m.hosts = nil + m.clearedhosts = false + m.removedhosts = nil } -// ModelID returns the value of the "model_id" field in the mutation. -func (m *TeamModelMutation) ModelID() (r uuid.UUID, exists bool) { - v := m.model - if v == nil { - return +// AddVMIDs adds the "vms" edge to the VirtualMachine entity by ids. +func (m *UserMutation) AddVMIDs(ids ...string) { + if m.vms == nil { + m.vms = make(map[string]struct{}) + } + for i := range ids { + m.vms[ids[i]] = struct{}{} } - return *v, true } -// OldModelID returns the old "model_id" field's value of the TeamModel entity. -// If the TeamModel 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 *TeamModelMutation) OldModelID(ctx context.Context) (v uuid.UUID, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldModelID is only allowed on UpdateOne operations") +// ClearVms clears the "vms" edge to the VirtualMachine entity. +func (m *UserMutation) ClearVms() { + m.clearedvms = true +} + +// VmsCleared reports if the "vms" edge to the VirtualMachine entity was cleared. +func (m *UserMutation) VmsCleared() bool { + return m.clearedvms +} + +// RemoveVMIDs removes the "vms" edge to the VirtualMachine entity by IDs. +func (m *UserMutation) RemoveVMIDs(ids ...string) { + if m.removedvms == nil { + m.removedvms = make(map[string]struct{}) } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldModelID requires an ID field in the mutation") + for i := range ids { + delete(m.vms, ids[i]) + m.removedvms[ids[i]] = struct{}{} } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldModelID: %w", err) +} + +// RemovedVms returns the removed IDs of the "vms" edge to the VirtualMachine entity. +func (m *UserMutation) RemovedVmsIDs() (ids []string) { + for id := range m.removedvms { + ids = append(ids, id) } - return oldValue.ModelID, nil + return } -// ResetModelID resets all changes to the "model_id" field. -func (m *TeamModelMutation) ResetModelID() { - m.model = nil +// VmsIDs returns the "vms" edge IDs in the mutation. +func (m *UserMutation) VmsIDs() (ids []string) { + for id := range m.vms { + ids = append(ids, id) + } + return } -// SetCreatedAt sets the "created_at" field. -func (m *TeamModelMutation) SetCreatedAt(t time.Time) { - m.created_at = &t +// ResetVms resets all changes to the "vms" edge. +func (m *UserMutation) ResetVms() { + m.vms = nil + m.clearedvms = false + m.removedvms = nil } -// CreatedAt returns the value of the "created_at" field in the mutation. -func (m *TeamModelMutation) CreatedAt() (r time.Time, exists bool) { - v := m.created_at - if v == nil { - return +// AddTeamMemberIDs adds the "team_members" edge to the TeamMember entity by ids. +func (m *UserMutation) AddTeamMemberIDs(ids ...uuid.UUID) { + if m.team_members == nil { + m.team_members = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.team_members[ids[i]] = struct{}{} } - return *v, true } -// OldCreatedAt returns the old "created_at" field's value of the TeamModel entity. -// If the TeamModel 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 *TeamModelMutation) 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") +// ClearTeamMembers clears the "team_members" edge to the TeamMember entity. +func (m *UserMutation) ClearTeamMembers() { + m.clearedteam_members = true +} + +// TeamMembersCleared reports if the "team_members" edge to the TeamMember entity was cleared. +func (m *UserMutation) TeamMembersCleared() bool { + return m.clearedteam_members +} + +// RemoveTeamMemberIDs removes the "team_members" edge to the TeamMember entity by IDs. +func (m *UserMutation) RemoveTeamMemberIDs(ids ...uuid.UUID) { + if m.removedteam_members == nil { + m.removedteam_members = make(map[uuid.UUID]struct{}) } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) + for i := range ids { + delete(m.team_members, ids[i]) + m.removedteam_members[ids[i]] = struct{}{} } - return oldValue.CreatedAt, nil } -// ResetCreatedAt resets all changes to the "created_at" field. -func (m *TeamModelMutation) ResetCreatedAt() { - m.created_at = nil +// RemovedTeamMembers returns the removed IDs of the "team_members" edge to the TeamMember entity. +func (m *UserMutation) RemovedTeamMembersIDs() (ids []uuid.UUID) { + for id := range m.removedteam_members { + ids = append(ids, id) + } + return } -// ClearTeam clears the "team" edge to the Team entity. -func (m *TeamModelMutation) ClearTeam() { - m.clearedteam = true - m.clearedFields[teammodel.FieldTeamID] = struct{}{} +// TeamMembersIDs returns the "team_members" edge IDs in the mutation. +func (m *UserMutation) TeamMembersIDs() (ids []uuid.UUID) { + for id := range m.team_members { + ids = append(ids, id) + } + return } -// TeamCleared reports if the "team" edge to the Team entity was cleared. -func (m *TeamModelMutation) TeamCleared() bool { - return m.clearedteam +// ResetTeamMembers resets all changes to the "team_members" edge. +func (m *UserMutation) ResetTeamMembers() { + m.team_members = nil + m.clearedteam_members = false + m.removedteam_members = nil } -// TeamIDs returns the "team" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// TeamID instead. It exists only for internal usage by the builders. -func (m *TeamModelMutation) TeamIDs() (ids []uuid.UUID) { - if id := m.team; id != nil { - ids = append(ids, *id) +// AddTeamGroupMemberIDs adds the "team_group_members" edge to the TeamGroupMember entity by ids. +func (m *UserMutation) AddTeamGroupMemberIDs(ids ...uuid.UUID) { + if m.team_group_members == nil { + m.team_group_members = make(map[uuid.UUID]struct{}) + } + for i := range ids { + m.team_group_members[ids[i]] = struct{}{} } - return } -// ResetTeam resets all changes to the "team" edge. -func (m *TeamModelMutation) ResetTeam() { - m.team = nil - m.clearedteam = false +// ClearTeamGroupMembers clears the "team_group_members" edge to the TeamGroupMember entity. +func (m *UserMutation) ClearTeamGroupMembers() { + m.clearedteam_group_members = true } -// ClearModel clears the "model" edge to the Model entity. -func (m *TeamModelMutation) ClearModel() { - m.clearedmodel = true - m.clearedFields[teammodel.FieldModelID] = struct{}{} +// TeamGroupMembersCleared reports if the "team_group_members" edge to the TeamGroupMember entity was cleared. +func (m *UserMutation) TeamGroupMembersCleared() bool { + return m.clearedteam_group_members +} + +// RemoveTeamGroupMemberIDs removes the "team_group_members" edge to the TeamGroupMember entity by IDs. +func (m *UserMutation) RemoveTeamGroupMemberIDs(ids ...uuid.UUID) { + if m.removedteam_group_members == nil { + m.removedteam_group_members = make(map[uuid.UUID]struct{}) + } + for i := range ids { + delete(m.team_group_members, ids[i]) + m.removedteam_group_members[ids[i]] = struct{}{} + } } -// ModelCleared reports if the "model" edge to the Model entity was cleared. -func (m *TeamModelMutation) ModelCleared() bool { - return m.clearedmodel +// RemovedTeamGroupMembers returns the removed IDs of the "team_group_members" edge to the TeamGroupMember entity. +func (m *UserMutation) RemovedTeamGroupMembersIDs() (ids []uuid.UUID) { + for id := range m.removedteam_group_members { + ids = append(ids, id) + } + return } -// ModelIDs returns the "model" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// ModelID instead. It exists only for internal usage by the builders. -func (m *TeamModelMutation) ModelIDs() (ids []uuid.UUID) { - if id := m.model; id != nil { - ids = append(ids, *id) +// TeamGroupMembersIDs returns the "team_group_members" edge IDs in the mutation. +func (m *UserMutation) TeamGroupMembersIDs() (ids []uuid.UUID) { + for id := range m.team_group_members { + ids = append(ids, id) } return } -// ResetModel resets all changes to the "model" edge. -func (m *TeamModelMutation) ResetModel() { - m.model = nil - m.clearedmodel = false +// ResetTeamGroupMembers resets all changes to the "team_group_members" edge. +func (m *UserMutation) ResetTeamGroupMembers() { + m.team_group_members = nil + m.clearedteam_group_members = false + m.removedteam_group_members = nil } -// Where appends a list predicates to the TeamModelMutation builder. -func (m *TeamModelMutation) Where(ps ...predicate.TeamModel) { +// Where appends a list predicates to the UserMutation builder. +func (m *UserMutation) Where(ps ...predicate.User) { m.predicates = append(m.predicates, ps...) } -// WhereP appends storage-level predicates to the TeamModelMutation builder. Using this method, +// WhereP appends storage-level predicates to the UserMutation builder. Using this method, // users can use type-assertion to append predicates that do not depend on any generated package. -func (m *TeamModelMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.TeamModel, len(ps)) +func (m *UserMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.User, len(ps)) for i := range ps { p[i] = ps[i] } @@ -8872,33 +13441,57 @@ func (m *TeamModelMutation) WhereP(ps ...func(*sql.Selector)) { } // Op returns the operation name. -func (m *TeamModelMutation) Op() Op { +func (m *UserMutation) Op() Op { return m.op } // SetOp allows setting the mutation operation. -func (m *TeamModelMutation) SetOp(op Op) { +func (m *UserMutation) SetOp(op Op) { m.op = op } -// Type returns the node type of this mutation (TeamModel). -func (m *TeamModelMutation) Type() string { +// Type returns the node type of this mutation (User). +func (m *UserMutation) 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 *TeamModelMutation) Fields() []string { - fields := make([]string, 0, 3) - if m.team != nil { - fields = append(fields, teammodel.FieldTeamID) +func (m *UserMutation) Fields() []string { + fields := make([]string, 0, 11) + if m.deleted_at != nil { + fields = append(fields, user.FieldDeletedAt) } - if m.model != nil { - fields = append(fields, teammodel.FieldModelID) + if m.name != nil { + fields = append(fields, user.FieldName) + } + if m.email != nil { + fields = append(fields, user.FieldEmail) + } + if m.avatar_url != nil { + fields = append(fields, user.FieldAvatarURL) + } + if m.password != nil { + fields = append(fields, user.FieldPassword) + } + if m.role != nil { + fields = append(fields, user.FieldRole) + } + if m.status != nil { + fields = append(fields, user.FieldStatus) + } + if m.is_blocked != nil { + fields = append(fields, user.FieldIsBlocked) + } + if m.default_configs != nil { + fields = append(fields, user.FieldDefaultConfigs) } if m.created_at != nil { - fields = append(fields, teammodel.FieldCreatedAt) + fields = append(fields, user.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, user.FieldUpdatedAt) } return fields } @@ -8906,14 +13499,30 @@ func (m *TeamModelMutation) Fields() []string { // 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 *TeamModelMutation) Field(name string) (ent.Value, bool) { +func (m *UserMutation) Field(name string) (ent.Value, bool) { switch name { - case teammodel.FieldTeamID: - return m.TeamID() - case teammodel.FieldModelID: - return m.ModelID() - case teammodel.FieldCreatedAt: + case user.FieldDeletedAt: + return m.DeletedAt() + case user.FieldName: + return m.Name() + case user.FieldEmail: + return m.Email() + case user.FieldAvatarURL: + return m.AvatarURL() + case user.FieldPassword: + return m.Password() + case user.FieldRole: + return m.Role() + case user.FieldStatus: + return m.Status() + case user.FieldIsBlocked: + return m.IsBlocked() + case user.FieldDefaultConfigs: + return m.DefaultConfigs() + case user.FieldCreatedAt: return m.CreatedAt() + case user.FieldUpdatedAt: + return m.UpdatedAt() } return nil, false } @@ -8921,256 +13530,586 @@ func (m *TeamModelMutation) Field(name string) (ent.Value, bool) { // 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 *TeamModelMutation) OldField(ctx context.Context, name string) (ent.Value, error) { +func (m *UserMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { - case teammodel.FieldTeamID: - return m.OldTeamID(ctx) - case teammodel.FieldModelID: - return m.OldModelID(ctx) - case teammodel.FieldCreatedAt: + case user.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case user.FieldName: + return m.OldName(ctx) + case user.FieldEmail: + return m.OldEmail(ctx) + case user.FieldAvatarURL: + return m.OldAvatarURL(ctx) + case user.FieldPassword: + return m.OldPassword(ctx) + case user.FieldRole: + return m.OldRole(ctx) + case user.FieldStatus: + return m.OldStatus(ctx) + case user.FieldIsBlocked: + return m.OldIsBlocked(ctx) + case user.FieldDefaultConfigs: + return m.OldDefaultConfigs(ctx) + case user.FieldCreatedAt: return m.OldCreatedAt(ctx) + case user.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) } - return nil, fmt.Errorf("unknown TeamModel field %s", name) + return nil, fmt.Errorf("unknown User 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 *TeamModelMutation) SetField(name string, value ent.Value) error { +func (m *UserMutation) SetField(name string, value ent.Value) error { switch name { - case teammodel.FieldTeamID: - v, ok := value.(uuid.UUID) + case user.FieldDeletedAt: + v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetTeamID(v) + m.SetDeletedAt(v) return nil - case teammodel.FieldModelID: - v, ok := value.(uuid.UUID) + case user.FieldName: + v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetModelID(v) + m.SetName(v) return nil - case teammodel.FieldCreatedAt: + case user.FieldEmail: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEmail(v) + return nil + case user.FieldAvatarURL: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAvatarURL(v) + return nil + case user.FieldPassword: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPassword(v) + return nil + case user.FieldRole: + v, ok := value.(consts.UserRole) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRole(v) + return nil + case user.FieldStatus: + v, ok := value.(consts.UserStatus) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatus(v) + return nil + case user.FieldIsBlocked: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIsBlocked(v) + return nil + case user.FieldDefaultConfigs: + v, ok := value.(map[consts.DefaultConfigType]uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDefaultConfigs(v) + return nil + case user.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 user.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil } - return fmt.Errorf("unknown TeamModel field %s", name) + return fmt.Errorf("unknown User field %s", name) } // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. -func (m *TeamModelMutation) AddedFields() []string { +func (m *UserMutation) AddedFields() []string { return nil } // AddedField returns the numeric value that was incremented/decremented on a field // with the given name. The second boolean return value indicates that this field // was not set, or was not defined in the schema. -func (m *TeamModelMutation) AddedField(name string) (ent.Value, bool) { +func (m *UserMutation) AddedField(name string) (ent.Value, bool) { return nil, false } // AddField adds the value to the field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. -func (m *TeamModelMutation) AddField(name string, value ent.Value) error { +func (m *UserMutation) AddField(name string, value ent.Value) error { switch name { } - return fmt.Errorf("unknown TeamModel numeric field %s", name) + return fmt.Errorf("unknown User numeric field %s", name) } // ClearedFields returns all nullable fields that were cleared during this // mutation. -func (m *TeamModelMutation) ClearedFields() []string { - return nil +func (m *UserMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(user.FieldDeletedAt) { + fields = append(fields, user.FieldDeletedAt) + } + if m.FieldCleared(user.FieldEmail) { + fields = append(fields, user.FieldEmail) + } + if m.FieldCleared(user.FieldAvatarURL) { + fields = append(fields, user.FieldAvatarURL) + } + if m.FieldCleared(user.FieldPassword) { + fields = append(fields, user.FieldPassword) + } + if m.FieldCleared(user.FieldDefaultConfigs) { + fields = append(fields, user.FieldDefaultConfigs) + } + return fields } // FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. -func (m *TeamModelMutation) FieldCleared(name string) bool { +func (m *UserMutation) 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 *TeamModelMutation) ClearField(name string) error { - return fmt.Errorf("unknown TeamModel nullable field %s", name) +func (m *UserMutation) ClearField(name string) error { + switch name { + case user.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case user.FieldEmail: + m.ClearEmail() + return nil + case user.FieldAvatarURL: + m.ClearAvatarURL() + return nil + case user.FieldPassword: + m.ClearPassword() + return nil + case user.FieldDefaultConfigs: + m.ClearDefaultConfigs() + return nil + } + return fmt.Errorf("unknown User 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 *TeamModelMutation) ResetField(name string) error { +func (m *UserMutation) ResetField(name string) error { switch name { - case teammodel.FieldTeamID: - m.ResetTeamID() + case user.FieldDeletedAt: + m.ResetDeletedAt() return nil - case teammodel.FieldModelID: - m.ResetModelID() + case user.FieldName: + m.ResetName() return nil - case teammodel.FieldCreatedAt: + case user.FieldEmail: + m.ResetEmail() + return nil + case user.FieldAvatarURL: + m.ResetAvatarURL() + return nil + case user.FieldPassword: + m.ResetPassword() + return nil + case user.FieldRole: + m.ResetRole() + return nil + case user.FieldStatus: + m.ResetStatus() + return nil + case user.FieldIsBlocked: + m.ResetIsBlocked() + return nil + case user.FieldDefaultConfigs: + m.ResetDefaultConfigs() + return nil + case user.FieldCreatedAt: m.ResetCreatedAt() return nil + case user.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil } - return fmt.Errorf("unknown TeamModel field %s", name) + return fmt.Errorf("unknown User field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. -func (m *TeamModelMutation) AddedEdges() []string { - edges := make([]string, 0, 2) - if m.team != nil { - edges = append(edges, teammodel.EdgeTeam) +func (m *UserMutation) AddedEdges() []string { + edges := make([]string, 0, 10) + if m.identities != nil { + edges = append(edges, user.EdgeIdentities) } - if m.model != nil { - edges = append(edges, teammodel.EdgeModel) + if m.audits != nil { + edges = append(edges, user.EdgeAudits) + } + if m.teams != nil { + edges = append(edges, user.EdgeTeams) + } + if m.groups != nil { + edges = append(edges, user.EdgeGroups) + } + if m.models != nil { + edges = append(edges, user.EdgeModels) + } + if m.images != nil { + edges = append(edges, user.EdgeImages) + } + if m.hosts != nil { + edges = append(edges, user.EdgeHosts) + } + if m.vms != nil { + edges = append(edges, user.EdgeVms) + } + if m.team_members != nil { + edges = append(edges, user.EdgeTeamMembers) + } + if m.team_group_members != nil { + edges = append(edges, user.EdgeTeamGroupMembers) } return edges } // AddedIDs returns all IDs (to other nodes) that were added for the given edge // name in this mutation. -func (m *TeamModelMutation) AddedIDs(name string) []ent.Value { +func (m *UserMutation) AddedIDs(name string) []ent.Value { switch name { - case teammodel.EdgeTeam: - if id := m.team; id != nil { - return []ent.Value{*id} + case user.EdgeIdentities: + ids := make([]ent.Value, 0, len(m.identities)) + for id := range m.identities { + ids = append(ids, id) } - case teammodel.EdgeModel: - if id := m.model; id != nil { - return []ent.Value{*id} + return ids + case user.EdgeAudits: + ids := make([]ent.Value, 0, len(m.audits)) + for id := range m.audits { + ids = append(ids, id) + } + return ids + case user.EdgeTeams: + ids := make([]ent.Value, 0, len(m.teams)) + for id := range m.teams { + ids = append(ids, id) + } + return ids + case user.EdgeGroups: + ids := make([]ent.Value, 0, len(m.groups)) + for id := range m.groups { + ids = append(ids, id) + } + return ids + case user.EdgeModels: + ids := make([]ent.Value, 0, len(m.models)) + for id := range m.models { + ids = append(ids, id) + } + return ids + case user.EdgeImages: + ids := make([]ent.Value, 0, len(m.images)) + for id := range m.images { + ids = append(ids, id) + } + return ids + case user.EdgeHosts: + ids := make([]ent.Value, 0, len(m.hosts)) + for id := range m.hosts { + ids = append(ids, id) + } + return ids + case user.EdgeVms: + ids := make([]ent.Value, 0, len(m.vms)) + for id := range m.vms { + ids = append(ids, id) + } + return ids + case user.EdgeTeamMembers: + ids := make([]ent.Value, 0, len(m.team_members)) + for id := range m.team_members { + ids = append(ids, id) + } + return ids + case user.EdgeTeamGroupMembers: + ids := make([]ent.Value, 0, len(m.team_group_members)) + for id := range m.team_group_members { + ids = append(ids, id) } + return ids } return nil } // RemovedEdges returns all edge names that were removed in this mutation. -func (m *TeamModelMutation) RemovedEdges() []string { - edges := make([]string, 0, 2) +func (m *UserMutation) RemovedEdges() []string { + edges := make([]string, 0, 10) + if m.removedidentities != nil { + edges = append(edges, user.EdgeIdentities) + } + if m.removedaudits != nil { + edges = append(edges, user.EdgeAudits) + } + if m.removedteams != nil { + edges = append(edges, user.EdgeTeams) + } + if m.removedgroups != nil { + edges = append(edges, user.EdgeGroups) + } + if m.removedmodels != nil { + edges = append(edges, user.EdgeModels) + } + if m.removedimages != nil { + edges = append(edges, user.EdgeImages) + } + if m.removedhosts != nil { + edges = append(edges, user.EdgeHosts) + } + if m.removedvms != nil { + edges = append(edges, user.EdgeVms) + } + if m.removedteam_members != nil { + edges = append(edges, user.EdgeTeamMembers) + } + if m.removedteam_group_members != nil { + edges = append(edges, user.EdgeTeamGroupMembers) + } return edges } // RemovedIDs returns all IDs (to other nodes) that were removed for the edge with // the given name in this mutation. -func (m *TeamModelMutation) RemovedIDs(name string) []ent.Value { +func (m *UserMutation) RemovedIDs(name string) []ent.Value { + switch name { + case user.EdgeIdentities: + ids := make([]ent.Value, 0, len(m.removedidentities)) + for id := range m.removedidentities { + ids = append(ids, id) + } + return ids + case user.EdgeAudits: + ids := make([]ent.Value, 0, len(m.removedaudits)) + for id := range m.removedaudits { + ids = append(ids, id) + } + return ids + case user.EdgeTeams: + ids := make([]ent.Value, 0, len(m.removedteams)) + for id := range m.removedteams { + ids = append(ids, id) + } + return ids + case user.EdgeGroups: + ids := make([]ent.Value, 0, len(m.removedgroups)) + for id := range m.removedgroups { + ids = append(ids, id) + } + return ids + case user.EdgeModels: + ids := make([]ent.Value, 0, len(m.removedmodels)) + for id := range m.removedmodels { + ids = append(ids, id) + } + return ids + case user.EdgeImages: + ids := make([]ent.Value, 0, len(m.removedimages)) + for id := range m.removedimages { + ids = append(ids, id) + } + return ids + case user.EdgeHosts: + ids := make([]ent.Value, 0, len(m.removedhosts)) + for id := range m.removedhosts { + ids = append(ids, id) + } + return ids + case user.EdgeVms: + ids := make([]ent.Value, 0, len(m.removedvms)) + for id := range m.removedvms { + ids = append(ids, id) + } + return ids + case user.EdgeTeamMembers: + ids := make([]ent.Value, 0, len(m.removedteam_members)) + for id := range m.removedteam_members { + ids = append(ids, id) + } + return ids + case user.EdgeTeamGroupMembers: + ids := make([]ent.Value, 0, len(m.removedteam_group_members)) + for id := range m.removedteam_group_members { + ids = append(ids, id) + } + return ids + } return nil } // ClearedEdges returns all edge names that were cleared in this mutation. -func (m *TeamModelMutation) ClearedEdges() []string { - edges := make([]string, 0, 2) - if m.clearedteam { - edges = append(edges, teammodel.EdgeTeam) +func (m *UserMutation) ClearedEdges() []string { + edges := make([]string, 0, 10) + if m.clearedidentities { + edges = append(edges, user.EdgeIdentities) + } + if m.clearedaudits { + edges = append(edges, user.EdgeAudits) + } + if m.clearedteams { + edges = append(edges, user.EdgeTeams) + } + if m.clearedgroups { + edges = append(edges, user.EdgeGroups) + } + if m.clearedmodels { + edges = append(edges, user.EdgeModels) + } + if m.clearedimages { + edges = append(edges, user.EdgeImages) + } + if m.clearedhosts { + edges = append(edges, user.EdgeHosts) + } + if m.clearedvms { + edges = append(edges, user.EdgeVms) + } + if m.clearedteam_members { + edges = append(edges, user.EdgeTeamMembers) } - if m.clearedmodel { - edges = append(edges, teammodel.EdgeModel) + if m.clearedteam_group_members { + edges = append(edges, user.EdgeTeamGroupMembers) } return edges } // EdgeCleared returns a boolean which indicates if the edge with the given name // was cleared in this mutation. -func (m *TeamModelMutation) EdgeCleared(name string) bool { +func (m *UserMutation) EdgeCleared(name string) bool { switch name { - case teammodel.EdgeTeam: - return m.clearedteam - case teammodel.EdgeModel: - return m.clearedmodel + case user.EdgeIdentities: + return m.clearedidentities + case user.EdgeAudits: + return m.clearedaudits + case user.EdgeTeams: + return m.clearedteams + case user.EdgeGroups: + return m.clearedgroups + case user.EdgeModels: + return m.clearedmodels + case user.EdgeImages: + return m.clearedimages + case user.EdgeHosts: + return m.clearedhosts + case user.EdgeVms: + return m.clearedvms + case user.EdgeTeamMembers: + return m.clearedteam_members + case user.EdgeTeamGroupMembers: + return m.clearedteam_group_members } 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 *TeamModelMutation) ClearEdge(name string) error { +func (m *UserMutation) ClearEdge(name string) error { switch name { - case teammodel.EdgeTeam: - m.ClearTeam() - return nil - case teammodel.EdgeModel: - m.ClearModel() - return nil } - return fmt.Errorf("unknown TeamModel unique edge %s", name) + return fmt.Errorf("unknown User 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 *TeamModelMutation) ResetEdge(name string) error { +func (m *UserMutation) ResetEdge(name string) error { switch name { - case teammodel.EdgeTeam: - m.ResetTeam() + case user.EdgeIdentities: + m.ResetIdentities() return nil - case teammodel.EdgeModel: - m.ResetModel() + case user.EdgeAudits: + m.ResetAudits() + return nil + case user.EdgeTeams: + m.ResetTeams() + return nil + case user.EdgeGroups: + m.ResetGroups() + return nil + case user.EdgeModels: + m.ResetModels() + return nil + case user.EdgeImages: + m.ResetImages() + return nil + case user.EdgeHosts: + m.ResetHosts() + return nil + case user.EdgeVms: + m.ResetVms() + return nil + case user.EdgeTeamMembers: + m.ResetTeamMembers() + return nil + case user.EdgeTeamGroupMembers: + m.ResetTeamGroupMembers() return nil } - return fmt.Errorf("unknown TeamModel edge %s", name) + return fmt.Errorf("unknown User edge %s", name) } -// UserMutation represents an operation that mutates the User nodes in the graph. -type UserMutation struct { +// UserIdentityMutation represents an operation that mutates the UserIdentity nodes in the graph. +type UserIdentityMutation struct { config - op Op - typ string - id *uuid.UUID - deleted_at *time.Time - name *string - email *string - avatar_url *string - password *string - role *consts.UserRole - status *consts.UserStatus - is_blocked *bool - default_configs *map[consts.DefaultConfigType]uuid.UUID - created_at *time.Time - updated_at *time.Time - clearedFields map[string]struct{} - identities map[uuid.UUID]struct{} - removedidentities map[uuid.UUID]struct{} - clearedidentities bool - audits map[uuid.UUID]struct{} - removedaudits map[uuid.UUID]struct{} - clearedaudits bool - teams map[uuid.UUID]struct{} - removedteams map[uuid.UUID]struct{} - clearedteams bool - groups map[uuid.UUID]struct{} - removedgroups map[uuid.UUID]struct{} - clearedgroups bool - models map[uuid.UUID]struct{} - removedmodels map[uuid.UUID]struct{} - clearedmodels bool - images map[uuid.UUID]struct{} - removedimages map[uuid.UUID]struct{} - clearedimages bool - team_members map[uuid.UUID]struct{} - removedteam_members map[uuid.UUID]struct{} - clearedteam_members bool - team_group_members map[uuid.UUID]struct{} - removedteam_group_members map[uuid.UUID]struct{} - clearedteam_group_members bool - done bool - oldValue func(context.Context) (*User, error) - predicates []predicate.User + op Op + typ string + id *uuid.UUID + deleted_at *time.Time + platform *consts.UserPlatform + identity_id *string + username *string + email *string + avatar_url *string + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + user *uuid.UUID + cleareduser bool + done bool + oldValue func(context.Context) (*UserIdentity, error) + predicates []predicate.UserIdentity } -var _ ent.Mutation = (*UserMutation)(nil) +var _ ent.Mutation = (*UserIdentityMutation)(nil) -// userOption allows management of the mutation configuration using functional options. -type userOption func(*UserMutation) +// useridentityOption allows management of the mutation configuration using functional options. +type useridentityOption func(*UserIdentityMutation) -// newUserMutation creates new mutation for the User entity. -func newUserMutation(c config, op Op, opts ...userOption) *UserMutation { - m := &UserMutation{ +// newUserIdentityMutation creates new mutation for the UserIdentity entity. +func newUserIdentityMutation(c config, op Op, opts ...useridentityOption) *UserIdentityMutation { + m := &UserIdentityMutation{ config: c, op: op, - typ: TypeUser, + typ: TypeUserIdentity, clearedFields: make(map[string]struct{}), } for _, opt := range opts { @@ -9179,20 +14118,20 @@ func newUserMutation(c config, op Op, opts ...userOption) *UserMutation { return m } -// withUserID sets the ID field of the mutation. -func withUserID(id uuid.UUID) userOption { - return func(m *UserMutation) { +// withUserIdentityID sets the ID field of the mutation. +func withUserIdentityID(id uuid.UUID) useridentityOption { + return func(m *UserIdentityMutation) { var ( err error once sync.Once - value *User + value *UserIdentity ) - m.oldValue = func(ctx context.Context) (*User, error) { + m.oldValue = func(ctx context.Context) (*UserIdentity, error) { once.Do(func() { if m.done { err = errors.New("querying old values post mutation is not allowed") } else { - value, err = m.Client().User.Get(ctx, id) + value, err = m.Client().UserIdentity.Get(ctx, id) } }) return value, err @@ -9201,10 +14140,10 @@ func withUserID(id uuid.UUID) userOption { } } -// withUser sets the old User of the mutation. -func withUser(node *User) userOption { - return func(m *UserMutation) { - m.oldValue = func(context.Context) (*User, error) { +// withUserIdentity sets the old UserIdentity of the mutation. +func withUserIdentity(node *UserIdentity) useridentityOption { + return func(m *UserIdentityMutation) { + m.oldValue = func(context.Context) (*UserIdentity, error) { return node, nil } m.id = &node.ID @@ -9213,7 +14152,7 @@ func withUser(node *User) userOption { // 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 UserMutation) Client() *Client { +func (m UserIdentityMutation) Client() *Client { client := &Client{config: m.config} client.init() return client @@ -9221,445 +14160,347 @@ func (m UserMutation) Client() *Client { // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. -func (m UserMutation) Tx() (*Tx, error) { +func (m UserIdentityMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { return nil, errors.New("db: 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 User entities. -func (m *UserMutation) 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 *UserMutation) 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 *UserMutation) 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().User.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) - } -} - -// SetDeletedAt sets the "deleted_at" field. -func (m *UserMutation) SetDeletedAt(t time.Time) { - m.deleted_at = &t -} - -// DeletedAt returns the value of the "deleted_at" field in the mutation. -func (m *UserMutation) DeletedAt() (r time.Time, exists bool) { - v := m.deleted_at - if v == nil { - return - } - return *v, true -} - -// OldDeletedAt returns the old "deleted_at" field's value of the User entity. -// If the User 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 *UserMutation) OldDeletedAt(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldDeletedAt requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldDeletedAt: %w", err) - } - return oldValue.DeletedAt, nil -} - -// ClearDeletedAt clears the value of the "deleted_at" field. -func (m *UserMutation) ClearDeletedAt() { - m.deleted_at = nil - m.clearedFields[user.FieldDeletedAt] = struct{}{} -} - -// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. -func (m *UserMutation) DeletedAtCleared() bool { - _, ok := m.clearedFields[user.FieldDeletedAt] - return ok -} - -// ResetDeletedAt resets all changes to the "deleted_at" field. -func (m *UserMutation) ResetDeletedAt() { - m.deleted_at = nil - delete(m.clearedFields, user.FieldDeletedAt) + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil } -// SetName sets the "name" field. -func (m *UserMutation) SetName(s string) { - m.name = &s +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of UserIdentity entities. +func (m *UserIdentityMutation) SetID(id uuid.UUID) { + m.id = &id } -// Name returns the value of the "name" field in the mutation. -func (m *UserMutation) Name() (r string, exists bool) { - v := m.name - if v == nil { +// 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 *UserIdentityMutation) ID() (id uuid.UUID, exists bool) { + if m.id == nil { return } - return *v, true + return *m.id, true } -// OldName returns the old "name" field's value of the User entity. -// If the User 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 *UserMutation) OldName(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldName is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldName requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldName: %w", err) +// 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 *UserIdentityMutation) 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().UserIdentity.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } - return oldValue.Name, nil -} - -// ResetName resets all changes to the "name" field. -func (m *UserMutation) ResetName() { - m.name = nil } -// SetEmail sets the "email" field. -func (m *UserMutation) SetEmail(s string) { - m.email = &s +// SetDeletedAt sets the "deleted_at" field. +func (m *UserIdentityMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t } -// Email returns the value of the "email" field in the mutation. -func (m *UserMutation) Email() (r string, exists bool) { - v := m.email +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *UserIdentityMutation) DeletedAt() (r time.Time, exists bool) { + v := m.deleted_at if v == nil { return } return *v, true } -// OldEmail returns the old "email" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. +// OldDeletedAt returns the old "deleted_at" field's value of the UserIdentity entity. +// If the UserIdentity 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 *UserMutation) OldEmail(ctx context.Context) (v string, err error) { +func (m *UserIdentityMutation) OldDeletedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldEmail is only allowed on UpdateOne operations") + return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldEmail requires an ID field in the mutation") + return v, errors.New("OldDeletedAt requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldEmail: %w", err) + return v, fmt.Errorf("querying old value for OldDeletedAt: %w", err) } - return oldValue.Email, nil + return oldValue.DeletedAt, nil } -// ClearEmail clears the value of the "email" field. -func (m *UserMutation) ClearEmail() { - m.email = nil - m.clearedFields[user.FieldEmail] = struct{}{} +// ClearDeletedAt clears the value of the "deleted_at" field. +func (m *UserIdentityMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[useridentity.FieldDeletedAt] = struct{}{} } -// EmailCleared returns if the "email" field was cleared in this mutation. -func (m *UserMutation) EmailCleared() bool { - _, ok := m.clearedFields[user.FieldEmail] +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *UserIdentityMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[useridentity.FieldDeletedAt] return ok } -// ResetEmail resets all changes to the "email" field. -func (m *UserMutation) ResetEmail() { - m.email = nil - delete(m.clearedFields, user.FieldEmail) +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *UserIdentityMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, useridentity.FieldDeletedAt) } -// SetAvatarURL sets the "avatar_url" field. -func (m *UserMutation) SetAvatarURL(s string) { - m.avatar_url = &s +// SetUserID sets the "user_id" field. +func (m *UserIdentityMutation) SetUserID(u uuid.UUID) { + m.user = &u } -// AvatarURL returns the value of the "avatar_url" field in the mutation. -func (m *UserMutation) AvatarURL() (r string, exists bool) { - v := m.avatar_url +// UserID returns the value of the "user_id" field in the mutation. +func (m *UserIdentityMutation) UserID() (r uuid.UUID, exists bool) { + v := m.user if v == nil { return } return *v, true } -// OldAvatarURL returns the old "avatar_url" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. +// OldUserID returns the old "user_id" field's value of the UserIdentity entity. +// If the UserIdentity 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 *UserMutation) OldAvatarURL(ctx context.Context) (v string, err error) { +func (m *UserIdentityMutation) OldUserID(ctx context.Context) (v uuid.UUID, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldAvatarURL is only allowed on UpdateOne operations") + return v, errors.New("OldUserID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldAvatarURL requires an ID field in the mutation") + return v, errors.New("OldUserID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldAvatarURL: %w", err) + return v, fmt.Errorf("querying old value for OldUserID: %w", err) } - return oldValue.AvatarURL, nil -} - -// ClearAvatarURL clears the value of the "avatar_url" field. -func (m *UserMutation) ClearAvatarURL() { - m.avatar_url = nil - m.clearedFields[user.FieldAvatarURL] = struct{}{} -} - -// AvatarURLCleared returns if the "avatar_url" field was cleared in this mutation. -func (m *UserMutation) AvatarURLCleared() bool { - _, ok := m.clearedFields[user.FieldAvatarURL] - return ok + return oldValue.UserID, nil } -// ResetAvatarURL resets all changes to the "avatar_url" field. -func (m *UserMutation) ResetAvatarURL() { - m.avatar_url = nil - delete(m.clearedFields, user.FieldAvatarURL) +// ResetUserID resets all changes to the "user_id" field. +func (m *UserIdentityMutation) ResetUserID() { + m.user = nil } -// SetPassword sets the "password" field. -func (m *UserMutation) SetPassword(s string) { - m.password = &s +// SetPlatform sets the "platform" field. +func (m *UserIdentityMutation) SetPlatform(cp consts.UserPlatform) { + m.platform = &cp } -// Password returns the value of the "password" field in the mutation. -func (m *UserMutation) Password() (r string, exists bool) { - v := m.password +// Platform returns the value of the "platform" field in the mutation. +func (m *UserIdentityMutation) Platform() (r consts.UserPlatform, exists bool) { + v := m.platform if v == nil { return } return *v, true } -// OldPassword returns the old "password" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. +// OldPlatform returns the old "platform" field's value of the UserIdentity entity. +// If the UserIdentity 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 *UserMutation) OldPassword(ctx context.Context) (v string, err error) { +func (m *UserIdentityMutation) OldPlatform(ctx context.Context) (v consts.UserPlatform, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldPassword is only allowed on UpdateOne operations") + return v, errors.New("OldPlatform is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldPassword requires an ID field in the mutation") + return v, errors.New("OldPlatform requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldPassword: %w", err) + return v, fmt.Errorf("querying old value for OldPlatform: %w", err) } - return oldValue.Password, nil -} - -// ClearPassword clears the value of the "password" field. -func (m *UserMutation) ClearPassword() { - m.password = nil - m.clearedFields[user.FieldPassword] = struct{}{} -} - -// PasswordCleared returns if the "password" field was cleared in this mutation. -func (m *UserMutation) PasswordCleared() bool { - _, ok := m.clearedFields[user.FieldPassword] - return ok + return oldValue.Platform, nil } -// ResetPassword resets all changes to the "password" field. -func (m *UserMutation) ResetPassword() { - m.password = nil - delete(m.clearedFields, user.FieldPassword) +// ResetPlatform resets all changes to the "platform" field. +func (m *UserIdentityMutation) ResetPlatform() { + m.platform = nil } -// SetRole sets the "role" field. -func (m *UserMutation) SetRole(cr consts.UserRole) { - m.role = &cr +// SetIdentityID sets the "identity_id" field. +func (m *UserIdentityMutation) SetIdentityID(s string) { + m.identity_id = &s } -// Role returns the value of the "role" field in the mutation. -func (m *UserMutation) Role() (r consts.UserRole, exists bool) { - v := m.role +// IdentityID returns the value of the "identity_id" field in the mutation. +func (m *UserIdentityMutation) IdentityID() (r string, exists bool) { + v := m.identity_id if v == nil { return } return *v, true } -// OldRole returns the old "role" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. +// OldIdentityID returns the old "identity_id" field's value of the UserIdentity entity. +// If the UserIdentity 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 *UserMutation) OldRole(ctx context.Context) (v consts.UserRole, err error) { +func (m *UserIdentityMutation) OldIdentityID(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldRole is only allowed on UpdateOne operations") + return v, errors.New("OldIdentityID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldRole requires an ID field in the mutation") + return v, errors.New("OldIdentityID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldRole: %w", err) + return v, fmt.Errorf("querying old value for OldIdentityID: %w", err) } - return oldValue.Role, nil + return oldValue.IdentityID, nil } -// ResetRole resets all changes to the "role" field. -func (m *UserMutation) ResetRole() { - m.role = nil +// ResetIdentityID resets all changes to the "identity_id" field. +func (m *UserIdentityMutation) ResetIdentityID() { + m.identity_id = nil } -// SetStatus sets the "status" field. -func (m *UserMutation) SetStatus(cs consts.UserStatus) { - m.status = &cs +// SetUsername sets the "username" field. +func (m *UserIdentityMutation) SetUsername(s string) { + m.username = &s } -// Status returns the value of the "status" field in the mutation. -func (m *UserMutation) Status() (r consts.UserStatus, exists bool) { - v := m.status +// Username returns the value of the "username" field in the mutation. +func (m *UserIdentityMutation) Username() (r string, exists bool) { + v := m.username if v == nil { return } return *v, true } -// OldStatus returns the old "status" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. +// OldUsername returns the old "username" field's value of the UserIdentity entity. +// If the UserIdentity 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 *UserMutation) OldStatus(ctx context.Context) (v consts.UserStatus, err error) { +func (m *UserIdentityMutation) OldUsername(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldStatus is only allowed on UpdateOne operations") + return v, errors.New("OldUsername is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldStatus requires an ID field in the mutation") + return v, errors.New("OldUsername requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldStatus: %w", err) + return v, fmt.Errorf("querying old value for OldUsername: %w", err) } - return oldValue.Status, nil + return oldValue.Username, nil } - -// ResetStatus resets all changes to the "status" field. -func (m *UserMutation) ResetStatus() { - m.status = nil + +// ResetUsername resets all changes to the "username" field. +func (m *UserIdentityMutation) ResetUsername() { + m.username = nil } -// SetIsBlocked sets the "is_blocked" field. -func (m *UserMutation) SetIsBlocked(b bool) { - m.is_blocked = &b +// SetEmail sets the "email" field. +func (m *UserIdentityMutation) SetEmail(s string) { + m.email = &s } -// IsBlocked returns the value of the "is_blocked" field in the mutation. -func (m *UserMutation) IsBlocked() (r bool, exists bool) { - v := m.is_blocked +// Email returns the value of the "email" field in the mutation. +func (m *UserIdentityMutation) Email() (r string, exists bool) { + v := m.email if v == nil { return } return *v, true } -// OldIsBlocked returns the old "is_blocked" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. +// OldEmail returns the old "email" field's value of the UserIdentity entity. +// If the UserIdentity 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 *UserMutation) OldIsBlocked(ctx context.Context) (v bool, err error) { +func (m *UserIdentityMutation) OldEmail(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldIsBlocked is only allowed on UpdateOne operations") + return v, errors.New("OldEmail is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldIsBlocked requires an ID field in the mutation") + return v, errors.New("OldEmail requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldIsBlocked: %w", err) + return v, fmt.Errorf("querying old value for OldEmail: %w", err) } - return oldValue.IsBlocked, nil + return oldValue.Email, nil } -// ResetIsBlocked resets all changes to the "is_blocked" field. -func (m *UserMutation) ResetIsBlocked() { - m.is_blocked = nil +// ClearEmail clears the value of the "email" field. +func (m *UserIdentityMutation) ClearEmail() { + m.email = nil + m.clearedFields[useridentity.FieldEmail] = struct{}{} } -// SetDefaultConfigs sets the "default_configs" field. -func (m *UserMutation) SetDefaultConfigs(mct map[consts.DefaultConfigType]uuid.UUID) { - m.default_configs = &mct +// EmailCleared returns if the "email" field was cleared in this mutation. +func (m *UserIdentityMutation) EmailCleared() bool { + _, ok := m.clearedFields[useridentity.FieldEmail] + return ok } -// DefaultConfigs returns the value of the "default_configs" field in the mutation. -func (m *UserMutation) DefaultConfigs() (r map[consts.DefaultConfigType]uuid.UUID, exists bool) { - v := m.default_configs +// ResetEmail resets all changes to the "email" field. +func (m *UserIdentityMutation) ResetEmail() { + m.email = nil + delete(m.clearedFields, useridentity.FieldEmail) +} + +// SetAvatarURL sets the "avatar_url" field. +func (m *UserIdentityMutation) SetAvatarURL(s string) { + m.avatar_url = &s +} + +// AvatarURL returns the value of the "avatar_url" field in the mutation. +func (m *UserIdentityMutation) AvatarURL() (r string, exists bool) { + v := m.avatar_url if v == nil { return } return *v, true } -// OldDefaultConfigs returns the old "default_configs" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. +// OldAvatarURL returns the old "avatar_url" field's value of the UserIdentity entity. +// If the UserIdentity 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 *UserMutation) OldDefaultConfigs(ctx context.Context) (v map[consts.DefaultConfigType]uuid.UUID, err error) { +func (m *UserIdentityMutation) OldAvatarURL(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldDefaultConfigs is only allowed on UpdateOne operations") + return v, errors.New("OldAvatarURL is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldDefaultConfigs requires an ID field in the mutation") + return v, errors.New("OldAvatarURL requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldDefaultConfigs: %w", err) + return v, fmt.Errorf("querying old value for OldAvatarURL: %w", err) } - return oldValue.DefaultConfigs, nil + return oldValue.AvatarURL, nil } -// ClearDefaultConfigs clears the value of the "default_configs" field. -func (m *UserMutation) ClearDefaultConfigs() { - m.default_configs = nil - m.clearedFields[user.FieldDefaultConfigs] = struct{}{} +// ClearAvatarURL clears the value of the "avatar_url" field. +func (m *UserIdentityMutation) ClearAvatarURL() { + m.avatar_url = nil + m.clearedFields[useridentity.FieldAvatarURL] = struct{}{} } -// DefaultConfigsCleared returns if the "default_configs" field was cleared in this mutation. -func (m *UserMutation) DefaultConfigsCleared() bool { - _, ok := m.clearedFields[user.FieldDefaultConfigs] +// AvatarURLCleared returns if the "avatar_url" field was cleared in this mutation. +func (m *UserIdentityMutation) AvatarURLCleared() bool { + _, ok := m.clearedFields[useridentity.FieldAvatarURL] return ok } -// ResetDefaultConfigs resets all changes to the "default_configs" field. -func (m *UserMutation) ResetDefaultConfigs() { - m.default_configs = nil - delete(m.clearedFields, user.FieldDefaultConfigs) +// ResetAvatarURL resets all changes to the "avatar_url" field. +func (m *UserIdentityMutation) ResetAvatarURL() { + m.avatar_url = nil + delete(m.clearedFields, useridentity.FieldAvatarURL) } // SetCreatedAt sets the "created_at" field. -func (m *UserMutation) SetCreatedAt(t time.Time) { +func (m *UserIdentityMutation) SetCreatedAt(t time.Time) { m.created_at = &t } // CreatedAt returns the value of the "created_at" field in the mutation. -func (m *UserMutation) CreatedAt() (r time.Time, exists bool) { +func (m *UserIdentityMutation) CreatedAt() (r time.Time, exists bool) { v := m.created_at if v == nil { return @@ -9667,10 +14508,10 @@ func (m *UserMutation) CreatedAt() (r time.Time, exists bool) { return *v, true } -// OldCreatedAt returns the old "created_at" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. +// OldCreatedAt returns the old "created_at" field's value of the UserIdentity entity. +// If the UserIdentity 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 *UserMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { +func (m *UserIdentityMutation) 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") } @@ -9685,17 +14526,17 @@ func (m *UserMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error } // ResetCreatedAt resets all changes to the "created_at" field. -func (m *UserMutation) ResetCreatedAt() { +func (m *UserIdentityMutation) ResetCreatedAt() { m.created_at = nil } // SetUpdatedAt sets the "updated_at" field. -func (m *UserMutation) SetUpdatedAt(t time.Time) { +func (m *UserIdentityMutation) SetUpdatedAt(t time.Time) { m.updated_at = &t } // UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *UserMutation) UpdatedAt() (r time.Time, exists bool) { +func (m *UserIdentityMutation) UpdatedAt() (r time.Time, exists bool) { v := m.updated_at if v == nil { return @@ -9703,10 +14544,10 @@ func (m *UserMutation) UpdatedAt() (r time.Time, exists bool) { return *v, true } -// OldUpdatedAt returns the old "updated_at" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. +// OldUpdatedAt returns the old "updated_at" field's value of the UserIdentity entity. +// If the UserIdentity 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 *UserMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { +func (m *UserIdentityMutation) 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") } @@ -9720,1467 +14561,1687 @@ func (m *UserMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error return oldValue.UpdatedAt, nil } -// ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *UserMutation) ResetUpdatedAt() { +// ClearUpdatedAt clears the value of the "updated_at" field. +func (m *UserIdentityMutation) ClearUpdatedAt() { m.updated_at = nil + m.clearedFields[useridentity.FieldUpdatedAt] = struct{}{} } -// AddIdentityIDs adds the "identities" edge to the UserIdentity entity by ids. -func (m *UserMutation) AddIdentityIDs(ids ...uuid.UUID) { - if m.identities == nil { - m.identities = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.identities[ids[i]] = struct{}{} - } -} - -// ClearIdentities clears the "identities" edge to the UserIdentity entity. -func (m *UserMutation) ClearIdentities() { - m.clearedidentities = true -} - -// IdentitiesCleared reports if the "identities" edge to the UserIdentity entity was cleared. -func (m *UserMutation) IdentitiesCleared() bool { - return m.clearedidentities -} - -// RemoveIdentityIDs removes the "identities" edge to the UserIdentity entity by IDs. -func (m *UserMutation) RemoveIdentityIDs(ids ...uuid.UUID) { - if m.removedidentities == nil { - m.removedidentities = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.identities, ids[i]) - m.removedidentities[ids[i]] = struct{}{} - } -} - -// RemovedIdentities returns the removed IDs of the "identities" edge to the UserIdentity entity. -func (m *UserMutation) RemovedIdentitiesIDs() (ids []uuid.UUID) { - for id := range m.removedidentities { - ids = append(ids, id) - } - return -} - -// IdentitiesIDs returns the "identities" edge IDs in the mutation. -func (m *UserMutation) IdentitiesIDs() (ids []uuid.UUID) { - for id := range m.identities { - ids = append(ids, id) - } - return -} - -// ResetIdentities resets all changes to the "identities" edge. -func (m *UserMutation) ResetIdentities() { - m.identities = nil - m.clearedidentities = false - m.removedidentities = nil -} - -// AddAuditIDs adds the "audits" edge to the Audit entity by ids. -func (m *UserMutation) AddAuditIDs(ids ...uuid.UUID) { - if m.audits == nil { - m.audits = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.audits[ids[i]] = struct{}{} - } -} - -// ClearAudits clears the "audits" edge to the Audit entity. -func (m *UserMutation) ClearAudits() { - m.clearedaudits = true -} - -// AuditsCleared reports if the "audits" edge to the Audit entity was cleared. -func (m *UserMutation) AuditsCleared() bool { - return m.clearedaudits -} - -// RemoveAuditIDs removes the "audits" edge to the Audit entity by IDs. -func (m *UserMutation) RemoveAuditIDs(ids ...uuid.UUID) { - if m.removedaudits == nil { - m.removedaudits = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.audits, ids[i]) - m.removedaudits[ids[i]] = struct{}{} - } -} - -// RemovedAudits returns the removed IDs of the "audits" edge to the Audit entity. -func (m *UserMutation) RemovedAuditsIDs() (ids []uuid.UUID) { - for id := range m.removedaudits { - ids = append(ids, id) - } - return -} - -// AuditsIDs returns the "audits" edge IDs in the mutation. -func (m *UserMutation) AuditsIDs() (ids []uuid.UUID) { - for id := range m.audits { - ids = append(ids, id) - } - return -} - -// ResetAudits resets all changes to the "audits" edge. -func (m *UserMutation) ResetAudits() { - m.audits = nil - m.clearedaudits = false - m.removedaudits = nil -} - -// AddTeamIDs adds the "teams" edge to the Team entity by ids. -func (m *UserMutation) AddTeamIDs(ids ...uuid.UUID) { - if m.teams == nil { - m.teams = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.teams[ids[i]] = struct{}{} - } -} - -// ClearTeams clears the "teams" edge to the Team entity. -func (m *UserMutation) ClearTeams() { - m.clearedteams = true +// UpdatedAtCleared returns if the "updated_at" field was cleared in this mutation. +func (m *UserIdentityMutation) UpdatedAtCleared() bool { + _, ok := m.clearedFields[useridentity.FieldUpdatedAt] + return ok } -// TeamsCleared reports if the "teams" edge to the Team entity was cleared. -func (m *UserMutation) TeamsCleared() bool { - return m.clearedteams +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *UserIdentityMutation) ResetUpdatedAt() { + m.updated_at = nil + delete(m.clearedFields, useridentity.FieldUpdatedAt) } -// RemoveTeamIDs removes the "teams" edge to the Team entity by IDs. -func (m *UserMutation) RemoveTeamIDs(ids ...uuid.UUID) { - if m.removedteams == nil { - m.removedteams = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.teams, ids[i]) - m.removedteams[ids[i]] = struct{}{} - } +// ClearUser clears the "user" edge to the User entity. +func (m *UserIdentityMutation) ClearUser() { + m.cleareduser = true + m.clearedFields[useridentity.FieldUserID] = struct{}{} } -// RemovedTeams returns the removed IDs of the "teams" edge to the Team entity. -func (m *UserMutation) RemovedTeamsIDs() (ids []uuid.UUID) { - for id := range m.removedteams { - ids = append(ids, id) - } - return +// UserCleared reports if the "user" edge to the User entity was cleared. +func (m *UserIdentityMutation) UserCleared() bool { + return m.cleareduser } -// TeamsIDs returns the "teams" edge IDs in the mutation. -func (m *UserMutation) TeamsIDs() (ids []uuid.UUID) { - for id := range m.teams { - ids = append(ids, id) +// UserIDs returns the "user" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UserID instead. It exists only for internal usage by the builders. +func (m *UserIdentityMutation) UserIDs() (ids []uuid.UUID) { + if id := m.user; id != nil { + ids = append(ids, *id) } return } -// ResetTeams resets all changes to the "teams" edge. -func (m *UserMutation) ResetTeams() { - m.teams = nil - m.clearedteams = false - m.removedteams = nil +// ResetUser resets all changes to the "user" edge. +func (m *UserIdentityMutation) ResetUser() { + m.user = nil + m.cleareduser = false } -// AddGroupIDs adds the "groups" edge to the TeamGroup entity by ids. -func (m *UserMutation) AddGroupIDs(ids ...uuid.UUID) { - if m.groups == nil { - m.groups = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.groups[ids[i]] = struct{}{} +// Where appends a list predicates to the UserIdentityMutation builder. +func (m *UserIdentityMutation) Where(ps ...predicate.UserIdentity) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the UserIdentityMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *UserIdentityMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.UserIdentity, len(ps)) + for i := range ps { + p[i] = ps[i] } + m.Where(p...) } -// ClearGroups clears the "groups" edge to the TeamGroup entity. -func (m *UserMutation) ClearGroups() { - m.clearedgroups = true +// Op returns the operation name. +func (m *UserIdentityMutation) Op() Op { + return m.op } -// GroupsCleared reports if the "groups" edge to the TeamGroup entity was cleared. -func (m *UserMutation) GroupsCleared() bool { - return m.clearedgroups +// SetOp allows setting the mutation operation. +func (m *UserIdentityMutation) SetOp(op Op) { + m.op = op } -// RemoveGroupIDs removes the "groups" edge to the TeamGroup entity by IDs. -func (m *UserMutation) RemoveGroupIDs(ids ...uuid.UUID) { - if m.removedgroups == nil { - m.removedgroups = make(map[uuid.UUID]struct{}) +// Type returns the node type of this mutation (UserIdentity). +func (m *UserIdentityMutation) 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 *UserIdentityMutation) Fields() []string { + fields := make([]string, 0, 9) + if m.deleted_at != nil { + fields = append(fields, useridentity.FieldDeletedAt) } - for i := range ids { - delete(m.groups, ids[i]) - m.removedgroups[ids[i]] = struct{}{} + if m.user != nil { + fields = append(fields, useridentity.FieldUserID) + } + if m.platform != nil { + fields = append(fields, useridentity.FieldPlatform) } + if m.identity_id != nil { + fields = append(fields, useridentity.FieldIdentityID) + } + if m.username != nil { + fields = append(fields, useridentity.FieldUsername) + } + if m.email != nil { + fields = append(fields, useridentity.FieldEmail) + } + if m.avatar_url != nil { + fields = append(fields, useridentity.FieldAvatarURL) + } + if m.created_at != nil { + fields = append(fields, useridentity.FieldCreatedAt) + } + if m.updated_at != nil { + fields = append(fields, useridentity.FieldUpdatedAt) + } + return fields } -// RemovedGroups returns the removed IDs of the "groups" edge to the TeamGroup entity. -func (m *UserMutation) RemovedGroupsIDs() (ids []uuid.UUID) { - for id := range m.removedgroups { - ids = append(ids, id) +// 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 *UserIdentityMutation) Field(name string) (ent.Value, bool) { + switch name { + case useridentity.FieldDeletedAt: + return m.DeletedAt() + case useridentity.FieldUserID: + return m.UserID() + case useridentity.FieldPlatform: + return m.Platform() + case useridentity.FieldIdentityID: + return m.IdentityID() + case useridentity.FieldUsername: + return m.Username() + case useridentity.FieldEmail: + return m.Email() + case useridentity.FieldAvatarURL: + return m.AvatarURL() + case useridentity.FieldCreatedAt: + return m.CreatedAt() + case useridentity.FieldUpdatedAt: + return m.UpdatedAt() } - return + return nil, false } -// GroupsIDs returns the "groups" edge IDs in the mutation. -func (m *UserMutation) GroupsIDs() (ids []uuid.UUID) { - for id := range m.groups { - ids = append(ids, id) +// 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 *UserIdentityMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case useridentity.FieldDeletedAt: + return m.OldDeletedAt(ctx) + case useridentity.FieldUserID: + return m.OldUserID(ctx) + case useridentity.FieldPlatform: + return m.OldPlatform(ctx) + case useridentity.FieldIdentityID: + return m.OldIdentityID(ctx) + case useridentity.FieldUsername: + return m.OldUsername(ctx) + case useridentity.FieldEmail: + return m.OldEmail(ctx) + case useridentity.FieldAvatarURL: + return m.OldAvatarURL(ctx) + case useridentity.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case useridentity.FieldUpdatedAt: + return m.OldUpdatedAt(ctx) } - return + return nil, fmt.Errorf("unknown UserIdentity field %s", name) } -// ResetGroups resets all changes to the "groups" edge. -func (m *UserMutation) ResetGroups() { - m.groups = nil - m.clearedgroups = false - m.removedgroups = nil +// 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 *UserIdentityMutation) SetField(name string, value ent.Value) error { + switch name { + case useridentity.FieldDeletedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDeletedAt(v) + return nil + case useridentity.FieldUserID: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil + case useridentity.FieldPlatform: + v, ok := value.(consts.UserPlatform) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPlatform(v) + return nil + case useridentity.FieldIdentityID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIdentityID(v) + return nil + case useridentity.FieldUsername: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUsername(v) + return nil + case useridentity.FieldEmail: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEmail(v) + return nil + case useridentity.FieldAvatarURL: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetAvatarURL(v) + return nil + case useridentity.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 useridentity.FieldUpdatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUpdatedAt(v) + return nil + } + return fmt.Errorf("unknown UserIdentity field %s", name) } -// AddModelIDs adds the "models" edge to the Model entity by ids. -func (m *UserMutation) AddModelIDs(ids ...uuid.UUID) { - if m.models == nil { - m.models = make(map[uuid.UUID]struct{}) - } - for i := range ids { - m.models[ids[i]] = struct{}{} - } +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *UserIdentityMutation) AddedFields() []string { + return nil } -// ClearModels clears the "models" edge to the Model entity. -func (m *UserMutation) ClearModels() { - m.clearedmodels = true +// 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 *UserIdentityMutation) AddedField(name string) (ent.Value, bool) { + return nil, false } -// ModelsCleared reports if the "models" edge to the Model entity was cleared. -func (m *UserMutation) ModelsCleared() bool { - return m.clearedmodels +// 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 *UserIdentityMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown UserIdentity numeric field %s", name) } -// RemoveModelIDs removes the "models" edge to the Model entity by IDs. -func (m *UserMutation) RemoveModelIDs(ids ...uuid.UUID) { - if m.removedmodels == nil { - m.removedmodels = make(map[uuid.UUID]struct{}) +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *UserIdentityMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(useridentity.FieldDeletedAt) { + fields = append(fields, useridentity.FieldDeletedAt) } - for i := range ids { - delete(m.models, ids[i]) - m.removedmodels[ids[i]] = struct{}{} + if m.FieldCleared(useridentity.FieldEmail) { + fields = append(fields, useridentity.FieldEmail) + } + if m.FieldCleared(useridentity.FieldAvatarURL) { + fields = append(fields, useridentity.FieldAvatarURL) } + if m.FieldCleared(useridentity.FieldUpdatedAt) { + fields = append(fields, useridentity.FieldUpdatedAt) + } + return fields } -// RemovedModels returns the removed IDs of the "models" edge to the Model entity. -func (m *UserMutation) RemovedModelsIDs() (ids []uuid.UUID) { - for id := range m.removedmodels { - ids = append(ids, id) - } - return +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *UserIdentityMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok } -// ModelsIDs returns the "models" edge IDs in the mutation. -func (m *UserMutation) ModelsIDs() (ids []uuid.UUID) { - for id := range m.models { - ids = append(ids, id) +// 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 *UserIdentityMutation) ClearField(name string) error { + switch name { + case useridentity.FieldDeletedAt: + m.ClearDeletedAt() + return nil + case useridentity.FieldEmail: + m.ClearEmail() + return nil + case useridentity.FieldAvatarURL: + m.ClearAvatarURL() + return nil + case useridentity.FieldUpdatedAt: + m.ClearUpdatedAt() + return nil } - return + return fmt.Errorf("unknown UserIdentity nullable field %s", name) } -// ResetModels resets all changes to the "models" edge. -func (m *UserMutation) ResetModels() { - m.models = nil - m.clearedmodels = false - m.removedmodels = nil +// 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 *UserIdentityMutation) ResetField(name string) error { + switch name { + case useridentity.FieldDeletedAt: + m.ResetDeletedAt() + return nil + case useridentity.FieldUserID: + m.ResetUserID() + return nil + case useridentity.FieldPlatform: + m.ResetPlatform() + return nil + case useridentity.FieldIdentityID: + m.ResetIdentityID() + return nil + case useridentity.FieldUsername: + m.ResetUsername() + return nil + case useridentity.FieldEmail: + m.ResetEmail() + return nil + case useridentity.FieldAvatarURL: + m.ResetAvatarURL() + return nil + case useridentity.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case useridentity.FieldUpdatedAt: + m.ResetUpdatedAt() + return nil + } + return fmt.Errorf("unknown UserIdentity field %s", name) } -// AddImageIDs adds the "images" edge to the Image entity by ids. -func (m *UserMutation) AddImageIDs(ids ...uuid.UUID) { - if m.images == nil { - m.images = make(map[uuid.UUID]struct{}) +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *UserIdentityMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.user != nil { + edges = append(edges, useridentity.EdgeUser) } - for i := range ids { - m.images[ids[i]] = struct{}{} + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *UserIdentityMutation) AddedIDs(name string) []ent.Value { + switch name { + case useridentity.EdgeUser: + if id := m.user; id != nil { + return []ent.Value{*id} + } } + return nil } -// ClearImages clears the "images" edge to the Image entity. -func (m *UserMutation) ClearImages() { - m.clearedimages = true +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *UserIdentityMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + return edges } -// ImagesCleared reports if the "images" edge to the Image entity was cleared. -func (m *UserMutation) ImagesCleared() bool { - return m.clearedimages +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *UserIdentityMutation) RemovedIDs(name string) []ent.Value { + return nil } -// RemoveImageIDs removes the "images" edge to the Image entity by IDs. -func (m *UserMutation) RemoveImageIDs(ids ...uuid.UUID) { - if m.removedimages == nil { - m.removedimages = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.images, ids[i]) - m.removedimages[ids[i]] = struct{}{} +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *UserIdentityMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.cleareduser { + edges = append(edges, useridentity.EdgeUser) } + return edges } -// RemovedImages returns the removed IDs of the "images" edge to the Image entity. -func (m *UserMutation) RemovedImagesIDs() (ids []uuid.UUID) { - for id := range m.removedimages { - ids = append(ids, id) +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *UserIdentityMutation) EdgeCleared(name string) bool { + switch name { + case useridentity.EdgeUser: + return m.cleareduser } - return + return false } -// ImagesIDs returns the "images" edge IDs in the mutation. -func (m *UserMutation) ImagesIDs() (ids []uuid.UUID) { - for id := range m.images { - ids = append(ids, id) +// 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 *UserIdentityMutation) ClearEdge(name string) error { + switch name { + case useridentity.EdgeUser: + m.ClearUser() + return nil } - return + return fmt.Errorf("unknown UserIdentity unique edge %s", name) } -// ResetImages resets all changes to the "images" edge. -func (m *UserMutation) ResetImages() { - m.images = nil - m.clearedimages = false - m.removedimages = nil +// 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 *UserIdentityMutation) ResetEdge(name string) error { + switch name { + case useridentity.EdgeUser: + m.ResetUser() + return nil + } + return fmt.Errorf("unknown UserIdentity edge %s", name) } -// AddTeamMemberIDs adds the "team_members" edge to the TeamMember entity by ids. -func (m *UserMutation) AddTeamMemberIDs(ids ...uuid.UUID) { - if m.team_members == nil { - m.team_members = make(map[uuid.UUID]struct{}) +// VirtualMachineMutation represents an operation that mutates the VirtualMachine nodes in the graph. +type VirtualMachineMutation struct { + config + op Op + typ string + id *string + deleted_at *time.Time + environment_id *string + name *string + hostname *string + arch *string + cores *int + addcores *int + memory *int64 + addmemory *int64 + os *string + external_ip *string + internal_ip *string + ttl_kind *consts.VirtualmachineTTLKind + ttl *int64 + addttl *int64 + version *string + machine_id *string + repo_url *string + repo_filename *string + branch *string + is_recycled *bool + conditions **types.VirtualMachineCondition + created_at *time.Time + updated_at *time.Time + clearedFields map[string]struct{} + host *string + clearedhost bool + model *uuid.UUID + clearedmodel bool + user *uuid.UUID + cleareduser bool + done bool + oldValue func(context.Context) (*VirtualMachine, error) + predicates []predicate.VirtualMachine +} + +var _ ent.Mutation = (*VirtualMachineMutation)(nil) + +// virtualmachineOption allows management of the mutation configuration using functional options. +type virtualmachineOption func(*VirtualMachineMutation) + +// newVirtualMachineMutation creates new mutation for the VirtualMachine entity. +func newVirtualMachineMutation(c config, op Op, opts ...virtualmachineOption) *VirtualMachineMutation { + m := &VirtualMachineMutation{ + config: c, + op: op, + typ: TypeVirtualMachine, + clearedFields: make(map[string]struct{}), } - for i := range ids { - m.team_members[ids[i]] = struct{}{} + for _, opt := range opts { + opt(m) } + return m } -// ClearTeamMembers clears the "team_members" edge to the TeamMember entity. -func (m *UserMutation) ClearTeamMembers() { - m.clearedteam_members = true -} - -// TeamMembersCleared reports if the "team_members" edge to the TeamMember entity was cleared. -func (m *UserMutation) TeamMembersCleared() bool { - return m.clearedteam_members -} - -// RemoveTeamMemberIDs removes the "team_members" edge to the TeamMember entity by IDs. -func (m *UserMutation) RemoveTeamMemberIDs(ids ...uuid.UUID) { - if m.removedteam_members == nil { - m.removedteam_members = make(map[uuid.UUID]struct{}) - } - for i := range ids { - delete(m.team_members, ids[i]) - m.removedteam_members[ids[i]] = struct{}{} +// withVirtualMachineID sets the ID field of the mutation. +func withVirtualMachineID(id string) virtualmachineOption { + return func(m *VirtualMachineMutation) { + var ( + err error + once sync.Once + value *VirtualMachine + ) + m.oldValue = func(ctx context.Context) (*VirtualMachine, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().VirtualMachine.Get(ctx, id) + } + }) + return value, err + } + m.id = &id } } -// RemovedTeamMembers returns the removed IDs of the "team_members" edge to the TeamMember entity. -func (m *UserMutation) RemovedTeamMembersIDs() (ids []uuid.UUID) { - for id := range m.removedteam_members { - ids = append(ids, id) +// withVirtualMachine sets the old VirtualMachine of the mutation. +func withVirtualMachine(node *VirtualMachine) virtualmachineOption { + return func(m *VirtualMachineMutation) { + m.oldValue = func(context.Context) (*VirtualMachine, error) { + return node, nil + } + m.id = &node.ID } - return } -// TeamMembersIDs returns the "team_members" edge IDs in the mutation. -func (m *UserMutation) TeamMembersIDs() (ids []uuid.UUID) { - for id := range m.team_members { - ids = append(ids, 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 VirtualMachineMutation) 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 VirtualMachineMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("db: mutation is not running in a transaction") } - return + tx := &Tx{config: m.config} + tx.init() + return tx, nil } -// ResetTeamMembers resets all changes to the "team_members" edge. -func (m *UserMutation) ResetTeamMembers() { - m.team_members = nil - m.clearedteam_members = false - m.removedteam_members = nil +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of VirtualMachine entities. +func (m *VirtualMachineMutation) SetID(id string) { + m.id = &id } -// AddTeamGroupMemberIDs adds the "team_group_members" edge to the TeamGroupMember entity by ids. -func (m *UserMutation) AddTeamGroupMemberIDs(ids ...uuid.UUID) { - if m.team_group_members == nil { - m.team_group_members = make(map[uuid.UUID]struct{}) +// 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 *VirtualMachineMutation) ID() (id string, exists bool) { + if m.id == nil { + return } - for i := range ids { - m.team_group_members[ids[i]] = struct{}{} + 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 *VirtualMachineMutation) IDs(ctx context.Context) ([]string, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []string{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().VirtualMachine.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } } -// ClearTeamGroupMembers clears the "team_group_members" edge to the TeamGroupMember entity. -func (m *UserMutation) ClearTeamGroupMembers() { - m.clearedteam_group_members = true +// SetDeletedAt sets the "deleted_at" field. +func (m *VirtualMachineMutation) SetDeletedAt(t time.Time) { + m.deleted_at = &t } -// TeamGroupMembersCleared reports if the "team_group_members" edge to the TeamGroupMember entity was cleared. -func (m *UserMutation) TeamGroupMembersCleared() bool { - return m.clearedteam_group_members +// DeletedAt returns the value of the "deleted_at" field in the mutation. +func (m *VirtualMachineMutation) DeletedAt() (r time.Time, exists bool) { + v := m.deleted_at + if v == nil { + return + } + return *v, true } -// RemoveTeamGroupMemberIDs removes the "team_group_members" edge to the TeamGroupMember entity by IDs. -func (m *UserMutation) RemoveTeamGroupMemberIDs(ids ...uuid.UUID) { - if m.removedteam_group_members == nil { - m.removedteam_group_members = make(map[uuid.UUID]struct{}) +// OldDeletedAt returns the old "deleted_at" field's value of the VirtualMachine entity. +// If the VirtualMachine 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 *VirtualMachineMutation) OldDeletedAt(ctx context.Context) (v time.Time, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") } - for i := range ids { - delete(m.team_group_members, ids[i]) - m.removedteam_group_members[ids[i]] = struct{}{} + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDeletedAt requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDeletedAt: %w", err) } + return oldValue.DeletedAt, nil } -// RemovedTeamGroupMembers returns the removed IDs of the "team_group_members" edge to the TeamGroupMember entity. -func (m *UserMutation) RemovedTeamGroupMembersIDs() (ids []uuid.UUID) { - for id := range m.removedteam_group_members { - ids = append(ids, id) - } - return +// ClearDeletedAt clears the value of the "deleted_at" field. +func (m *VirtualMachineMutation) ClearDeletedAt() { + m.deleted_at = nil + m.clearedFields[virtualmachine.FieldDeletedAt] = struct{}{} } -// TeamGroupMembersIDs returns the "team_group_members" edge IDs in the mutation. -func (m *UserMutation) TeamGroupMembersIDs() (ids []uuid.UUID) { - for id := range m.team_group_members { - ids = append(ids, id) - } - return +// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. +func (m *VirtualMachineMutation) DeletedAtCleared() bool { + _, ok := m.clearedFields[virtualmachine.FieldDeletedAt] + return ok } -// ResetTeamGroupMembers resets all changes to the "team_group_members" edge. -func (m *UserMutation) ResetTeamGroupMembers() { - m.team_group_members = nil - m.clearedteam_group_members = false - m.removedteam_group_members = nil +// ResetDeletedAt resets all changes to the "deleted_at" field. +func (m *VirtualMachineMutation) ResetDeletedAt() { + m.deleted_at = nil + delete(m.clearedFields, virtualmachine.FieldDeletedAt) } -// Where appends a list predicates to the UserMutation builder. -func (m *UserMutation) Where(ps ...predicate.User) { - m.predicates = append(m.predicates, ps...) +// SetHostID sets the "host_id" field. +func (m *VirtualMachineMutation) SetHostID(s string) { + m.host = &s } -// WhereP appends storage-level predicates to the UserMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *UserMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.User, len(ps)) - for i := range ps { - p[i] = ps[i] +// HostID returns the value of the "host_id" field in the mutation. +func (m *VirtualMachineMutation) HostID() (r string, exists bool) { + v := m.host + if v == nil { + return } - m.Where(p...) + return *v, true } -// Op returns the operation name. -func (m *UserMutation) Op() Op { - return m.op +// OldHostID returns the old "host_id" field's value of the VirtualMachine entity. +// If the VirtualMachine 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 *VirtualMachineMutation) OldHostID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldHostID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldHostID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldHostID: %w", err) + } + return oldValue.HostID, nil } -// SetOp allows setting the mutation operation. -func (m *UserMutation) SetOp(op Op) { - m.op = op +// ResetHostID resets all changes to the "host_id" field. +func (m *VirtualMachineMutation) ResetHostID() { + m.host = nil } -// Type returns the node type of this mutation (User). -func (m *UserMutation) Type() string { - return m.typ +// SetUserID sets the "user_id" field. +func (m *VirtualMachineMutation) SetUserID(u uuid.UUID) { + m.user = &u } -// 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 *UserMutation) Fields() []string { - fields := make([]string, 0, 11) - if m.deleted_at != nil { - fields = append(fields, user.FieldDeletedAt) - } - if m.name != nil { - fields = append(fields, user.FieldName) - } - if m.email != nil { - fields = append(fields, user.FieldEmail) - } - if m.avatar_url != nil { - fields = append(fields, user.FieldAvatarURL) - } - if m.password != nil { - fields = append(fields, user.FieldPassword) - } - if m.role != nil { - fields = append(fields, user.FieldRole) - } - if m.status != nil { - fields = append(fields, user.FieldStatus) - } - if m.is_blocked != nil { - fields = append(fields, user.FieldIsBlocked) +// UserID returns the value of the "user_id" field in the mutation. +func (m *VirtualMachineMutation) UserID() (r uuid.UUID, exists bool) { + v := m.user + if v == nil { + return } - if m.default_configs != nil { - fields = append(fields, user.FieldDefaultConfigs) + return *v, true +} + +// OldUserID returns the old "user_id" field's value of the VirtualMachine entity. +// If the VirtualMachine 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 *VirtualMachineMutation) OldUserID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUserID is only allowed on UpdateOne operations") } - if m.created_at != nil { - fields = append(fields, user.FieldCreatedAt) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUserID requires an ID field in the mutation") } - if m.updated_at != nil { - fields = append(fields, user.FieldUpdatedAt) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUserID: %w", err) } - return fields + return oldValue.UserID, nil } -// 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 *UserMutation) Field(name string) (ent.Value, bool) { - switch name { - case user.FieldDeletedAt: - return m.DeletedAt() - case user.FieldName: - return m.Name() - case user.FieldEmail: - return m.Email() - case user.FieldAvatarURL: - return m.AvatarURL() - case user.FieldPassword: - return m.Password() - case user.FieldRole: - return m.Role() - case user.FieldStatus: - return m.Status() - case user.FieldIsBlocked: - return m.IsBlocked() - case user.FieldDefaultConfigs: - return m.DefaultConfigs() - case user.FieldCreatedAt: - return m.CreatedAt() - case user.FieldUpdatedAt: - return m.UpdatedAt() - } - return nil, false +// ClearUserID clears the value of the "user_id" field. +func (m *VirtualMachineMutation) ClearUserID() { + m.user = nil + m.clearedFields[virtualmachine.FieldUserID] = struct{}{} } -// 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 *UserMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case user.FieldDeletedAt: - return m.OldDeletedAt(ctx) - case user.FieldName: - return m.OldName(ctx) - case user.FieldEmail: - return m.OldEmail(ctx) - case user.FieldAvatarURL: - return m.OldAvatarURL(ctx) - case user.FieldPassword: - return m.OldPassword(ctx) - case user.FieldRole: - return m.OldRole(ctx) - case user.FieldStatus: - return m.OldStatus(ctx) - case user.FieldIsBlocked: - return m.OldIsBlocked(ctx) - case user.FieldDefaultConfigs: - return m.OldDefaultConfigs(ctx) - case user.FieldCreatedAt: - return m.OldCreatedAt(ctx) - case user.FieldUpdatedAt: - return m.OldUpdatedAt(ctx) +// UserIDCleared returns if the "user_id" field was cleared in this mutation. +func (m *VirtualMachineMutation) UserIDCleared() bool { + _, ok := m.clearedFields[virtualmachine.FieldUserID] + return ok +} + +// ResetUserID resets all changes to the "user_id" field. +func (m *VirtualMachineMutation) ResetUserID() { + m.user = nil + delete(m.clearedFields, virtualmachine.FieldUserID) +} + +// SetModelID sets the "model_id" field. +func (m *VirtualMachineMutation) SetModelID(u uuid.UUID) { + m.model = &u +} + +// ModelID returns the value of the "model_id" field in the mutation. +func (m *VirtualMachineMutation) ModelID() (r uuid.UUID, exists bool) { + v := m.model + if v == nil { + return } - return nil, fmt.Errorf("unknown User field %s", name) + return *v, true } -// 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 *UserMutation) SetField(name string, value ent.Value) error { - switch name { - case user.FieldDeletedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetDeletedAt(v) - return nil - case user.FieldName: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetName(v) - return nil - case user.FieldEmail: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetEmail(v) - return nil - case user.FieldAvatarURL: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetAvatarURL(v) - return nil - case user.FieldPassword: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetPassword(v) - return nil - case user.FieldRole: - v, ok := value.(consts.UserRole) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetRole(v) - return nil - case user.FieldStatus: - v, ok := value.(consts.UserStatus) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetStatus(v) - return nil - case user.FieldIsBlocked: - v, ok := value.(bool) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetIsBlocked(v) - return nil - case user.FieldDefaultConfigs: - v, ok := value.(map[consts.DefaultConfigType]uuid.UUID) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetDefaultConfigs(v) - return nil - case user.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 user.FieldUpdatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUpdatedAt(v) - return nil +// OldModelID returns the old "model_id" field's value of the VirtualMachine entity. +// If the VirtualMachine 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 *VirtualMachineMutation) OldModelID(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldModelID is only allowed on UpdateOne operations") } - return fmt.Errorf("unknown User field %s", name) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldModelID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldModelID: %w", err) + } + return oldValue.ModelID, nil } -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *UserMutation) AddedFields() []string { - return nil +// ClearModelID clears the value of the "model_id" field. +func (m *VirtualMachineMutation) ClearModelID() { + m.model = nil + m.clearedFields[virtualmachine.FieldModelID] = struct{}{} } -// 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 *UserMutation) AddedField(name string) (ent.Value, bool) { - return nil, false +// ModelIDCleared returns if the "model_id" field was cleared in this mutation. +func (m *VirtualMachineMutation) ModelIDCleared() bool { + _, ok := m.clearedFields[virtualmachine.FieldModelID] + return ok } -// 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 *UserMutation) AddField(name string, value ent.Value) error { - switch name { +// ResetModelID resets all changes to the "model_id" field. +func (m *VirtualMachineMutation) ResetModelID() { + m.model = nil + delete(m.clearedFields, virtualmachine.FieldModelID) +} + +// SetEnvironmentID sets the "environment_id" field. +func (m *VirtualMachineMutation) SetEnvironmentID(s string) { + m.environment_id = &s +} + +// EnvironmentID returns the value of the "environment_id" field in the mutation. +func (m *VirtualMachineMutation) EnvironmentID() (r string, exists bool) { + v := m.environment_id + if v == nil { + return } - return fmt.Errorf("unknown User numeric field %s", name) + return *v, true } -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *UserMutation) ClearedFields() []string { - var fields []string - if m.FieldCleared(user.FieldDeletedAt) { - fields = append(fields, user.FieldDeletedAt) +// OldEnvironmentID returns the old "environment_id" field's value of the VirtualMachine entity. +// If the VirtualMachine 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 *VirtualMachineMutation) OldEnvironmentID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEnvironmentID is only allowed on UpdateOne operations") } - if m.FieldCleared(user.FieldEmail) { - fields = append(fields, user.FieldEmail) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEnvironmentID requires an ID field in the mutation") } - if m.FieldCleared(user.FieldAvatarURL) { - fields = append(fields, user.FieldAvatarURL) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEnvironmentID: %w", err) } - if m.FieldCleared(user.FieldPassword) { - fields = append(fields, user.FieldPassword) + return oldValue.EnvironmentID, nil +} + +// ClearEnvironmentID clears the value of the "environment_id" field. +func (m *VirtualMachineMutation) ClearEnvironmentID() { + m.environment_id = nil + m.clearedFields[virtualmachine.FieldEnvironmentID] = struct{}{} +} + +// EnvironmentIDCleared returns if the "environment_id" field was cleared in this mutation. +func (m *VirtualMachineMutation) EnvironmentIDCleared() bool { + _, ok := m.clearedFields[virtualmachine.FieldEnvironmentID] + return ok +} + +// ResetEnvironmentID resets all changes to the "environment_id" field. +func (m *VirtualMachineMutation) ResetEnvironmentID() { + m.environment_id = nil + delete(m.clearedFields, virtualmachine.FieldEnvironmentID) +} + +// SetName sets the "name" field. +func (m *VirtualMachineMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *VirtualMachineMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return } - if m.FieldCleared(user.FieldDefaultConfigs) { - fields = append(fields, user.FieldDefaultConfigs) + return *v, true +} + +// OldName returns the old "name" field's value of the VirtualMachine entity. +// If the VirtualMachine 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 *VirtualMachineMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") } - return fields + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil } -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *UserMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok +// ResetName resets all changes to the "name" field. +func (m *VirtualMachineMutation) ResetName() { + m.name = nil } -// 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 *UserMutation) ClearField(name string) error { - switch name { - case user.FieldDeletedAt: - m.ClearDeletedAt() - return nil - case user.FieldEmail: - m.ClearEmail() - return nil - case user.FieldAvatarURL: - m.ClearAvatarURL() - return nil - case user.FieldPassword: - m.ClearPassword() - return nil - case user.FieldDefaultConfigs: - m.ClearDefaultConfigs() - return nil +// SetHostname sets the "hostname" field. +func (m *VirtualMachineMutation) SetHostname(s string) { + m.hostname = &s +} + +// Hostname returns the value of the "hostname" field in the mutation. +func (m *VirtualMachineMutation) Hostname() (r string, exists bool) { + v := m.hostname + if v == nil { + return } - return fmt.Errorf("unknown User nullable field %s", name) + return *v, true } -// 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 *UserMutation) ResetField(name string) error { - switch name { - case user.FieldDeletedAt: - m.ResetDeletedAt() - return nil - case user.FieldName: - m.ResetName() - return nil - case user.FieldEmail: - m.ResetEmail() - return nil - case user.FieldAvatarURL: - m.ResetAvatarURL() - return nil - case user.FieldPassword: - m.ResetPassword() - return nil - case user.FieldRole: - m.ResetRole() - return nil - case user.FieldStatus: - m.ResetStatus() - return nil - case user.FieldIsBlocked: - m.ResetIsBlocked() - return nil - case user.FieldDefaultConfigs: - m.ResetDefaultConfigs() - return nil - case user.FieldCreatedAt: - m.ResetCreatedAt() - return nil - case user.FieldUpdatedAt: - m.ResetUpdatedAt() - return nil +// OldHostname returns the old "hostname" field's value of the VirtualMachine entity. +// If the VirtualMachine 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 *VirtualMachineMutation) OldHostname(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldHostname is only allowed on UpdateOne operations") } - return fmt.Errorf("unknown User field %s", name) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldHostname requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldHostname: %w", err) + } + return oldValue.Hostname, nil } -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *UserMutation) AddedEdges() []string { - edges := make([]string, 0, 8) - if m.identities != nil { - edges = append(edges, user.EdgeIdentities) +// ClearHostname clears the value of the "hostname" field. +func (m *VirtualMachineMutation) ClearHostname() { + m.hostname = nil + m.clearedFields[virtualmachine.FieldHostname] = struct{}{} +} + +// HostnameCleared returns if the "hostname" field was cleared in this mutation. +func (m *VirtualMachineMutation) HostnameCleared() bool { + _, ok := m.clearedFields[virtualmachine.FieldHostname] + return ok +} + +// ResetHostname resets all changes to the "hostname" field. +func (m *VirtualMachineMutation) ResetHostname() { + m.hostname = nil + delete(m.clearedFields, virtualmachine.FieldHostname) +} + +// SetArch sets the "arch" field. +func (m *VirtualMachineMutation) SetArch(s string) { + m.arch = &s +} + +// Arch returns the value of the "arch" field in the mutation. +func (m *VirtualMachineMutation) Arch() (r string, exists bool) { + v := m.arch + if v == nil { + return } - if m.audits != nil { - edges = append(edges, user.EdgeAudits) + return *v, true +} + +// OldArch returns the old "arch" field's value of the VirtualMachine entity. +// If the VirtualMachine 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 *VirtualMachineMutation) OldArch(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldArch is only allowed on UpdateOne operations") } - if m.teams != nil { - edges = append(edges, user.EdgeTeams) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldArch requires an ID field in the mutation") } - if m.groups != nil { - edges = append(edges, user.EdgeGroups) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldArch: %w", err) } - if m.models != nil { - edges = append(edges, user.EdgeModels) + return oldValue.Arch, nil +} + +// ClearArch clears the value of the "arch" field. +func (m *VirtualMachineMutation) ClearArch() { + m.arch = nil + m.clearedFields[virtualmachine.FieldArch] = struct{}{} +} + +// ArchCleared returns if the "arch" field was cleared in this mutation. +func (m *VirtualMachineMutation) ArchCleared() bool { + _, ok := m.clearedFields[virtualmachine.FieldArch] + return ok +} + +// ResetArch resets all changes to the "arch" field. +func (m *VirtualMachineMutation) ResetArch() { + m.arch = nil + delete(m.clearedFields, virtualmachine.FieldArch) +} + +// SetCores sets the "cores" field. +func (m *VirtualMachineMutation) SetCores(i int) { + m.cores = &i + m.addcores = nil +} + +// Cores returns the value of the "cores" field in the mutation. +func (m *VirtualMachineMutation) Cores() (r int, exists bool) { + v := m.cores + if v == nil { + return } - if m.images != nil { - edges = append(edges, user.EdgeImages) + return *v, true +} + +// OldCores returns the old "cores" field's value of the VirtualMachine entity. +// If the VirtualMachine 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 *VirtualMachineMutation) OldCores(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCores is only allowed on UpdateOne operations") } - if m.team_members != nil { - edges = append(edges, user.EdgeTeamMembers) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCores requires an ID field in the mutation") } - if m.team_group_members != nil { - edges = append(edges, user.EdgeTeamGroupMembers) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCores: %w", err) } - return edges + return oldValue.Cores, nil } -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *UserMutation) AddedIDs(name string) []ent.Value { - switch name { - case user.EdgeIdentities: - ids := make([]ent.Value, 0, len(m.identities)) - for id := range m.identities { - ids = append(ids, id) - } - return ids - case user.EdgeAudits: - ids := make([]ent.Value, 0, len(m.audits)) - for id := range m.audits { - ids = append(ids, id) - } - return ids - case user.EdgeTeams: - ids := make([]ent.Value, 0, len(m.teams)) - for id := range m.teams { - ids = append(ids, id) - } - return ids - case user.EdgeGroups: - ids := make([]ent.Value, 0, len(m.groups)) - for id := range m.groups { - ids = append(ids, id) - } - return ids - case user.EdgeModels: - ids := make([]ent.Value, 0, len(m.models)) - for id := range m.models { - ids = append(ids, id) - } - return ids - case user.EdgeImages: - ids := make([]ent.Value, 0, len(m.images)) - for id := range m.images { - ids = append(ids, id) - } - return ids - case user.EdgeTeamMembers: - ids := make([]ent.Value, 0, len(m.team_members)) - for id := range m.team_members { - ids = append(ids, id) - } - return ids - case user.EdgeTeamGroupMembers: - ids := make([]ent.Value, 0, len(m.team_group_members)) - for id := range m.team_group_members { - ids = append(ids, id) - } - return ids +// AddCores adds i to the "cores" field. +func (m *VirtualMachineMutation) AddCores(i int) { + if m.addcores != nil { + *m.addcores += i + } else { + m.addcores = &i } - return nil } -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *UserMutation) RemovedEdges() []string { - edges := make([]string, 0, 8) - if m.removedidentities != nil { - edges = append(edges, user.EdgeIdentities) - } - if m.removedaudits != nil { - edges = append(edges, user.EdgeAudits) +// AddedCores returns the value that was added to the "cores" field in this mutation. +func (m *VirtualMachineMutation) AddedCores() (r int, exists bool) { + v := m.addcores + if v == nil { + return } - if m.removedteams != nil { - edges = append(edges, user.EdgeTeams) + return *v, true +} + +// ClearCores clears the value of the "cores" field. +func (m *VirtualMachineMutation) ClearCores() { + m.cores = nil + m.addcores = nil + m.clearedFields[virtualmachine.FieldCores] = struct{}{} +} + +// CoresCleared returns if the "cores" field was cleared in this mutation. +func (m *VirtualMachineMutation) CoresCleared() bool { + _, ok := m.clearedFields[virtualmachine.FieldCores] + return ok +} + +// ResetCores resets all changes to the "cores" field. +func (m *VirtualMachineMutation) ResetCores() { + m.cores = nil + m.addcores = nil + delete(m.clearedFields, virtualmachine.FieldCores) +} + +// SetMemory sets the "memory" field. +func (m *VirtualMachineMutation) SetMemory(i int64) { + m.memory = &i + m.addmemory = nil +} + +// Memory returns the value of the "memory" field in the mutation. +func (m *VirtualMachineMutation) Memory() (r int64, exists bool) { + v := m.memory + if v == nil { + return } - if m.removedgroups != nil { - edges = append(edges, user.EdgeGroups) + return *v, true +} + +// OldMemory returns the old "memory" field's value of the VirtualMachine entity. +// If the VirtualMachine 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 *VirtualMachineMutation) OldMemory(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMemory is only allowed on UpdateOne operations") } - if m.removedmodels != nil { - edges = append(edges, user.EdgeModels) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMemory requires an ID field in the mutation") } - if m.removedimages != nil { - edges = append(edges, user.EdgeImages) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMemory: %w", err) } - if m.removedteam_members != nil { - edges = append(edges, user.EdgeTeamMembers) + return oldValue.Memory, nil +} + +// AddMemory adds i to the "memory" field. +func (m *VirtualMachineMutation) AddMemory(i int64) { + if m.addmemory != nil { + *m.addmemory += i + } else { + m.addmemory = &i } - if m.removedteam_group_members != nil { - edges = append(edges, user.EdgeTeamGroupMembers) +} + +// AddedMemory returns the value that was added to the "memory" field in this mutation. +func (m *VirtualMachineMutation) AddedMemory() (r int64, exists bool) { + v := m.addmemory + if v == nil { + return } - return edges + return *v, true } -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *UserMutation) RemovedIDs(name string) []ent.Value { - switch name { - case user.EdgeIdentities: - ids := make([]ent.Value, 0, len(m.removedidentities)) - for id := range m.removedidentities { - ids = append(ids, id) - } - return ids - case user.EdgeAudits: - ids := make([]ent.Value, 0, len(m.removedaudits)) - for id := range m.removedaudits { - ids = append(ids, id) - } - return ids - case user.EdgeTeams: - ids := make([]ent.Value, 0, len(m.removedteams)) - for id := range m.removedteams { - ids = append(ids, id) - } - return ids - case user.EdgeGroups: - ids := make([]ent.Value, 0, len(m.removedgroups)) - for id := range m.removedgroups { - ids = append(ids, id) - } - return ids - case user.EdgeModels: - ids := make([]ent.Value, 0, len(m.removedmodels)) - for id := range m.removedmodels { - ids = append(ids, id) - } - return ids - case user.EdgeImages: - ids := make([]ent.Value, 0, len(m.removedimages)) - for id := range m.removedimages { - ids = append(ids, id) - } - return ids - case user.EdgeTeamMembers: - ids := make([]ent.Value, 0, len(m.removedteam_members)) - for id := range m.removedteam_members { - ids = append(ids, id) - } - return ids - case user.EdgeTeamGroupMembers: - ids := make([]ent.Value, 0, len(m.removedteam_group_members)) - for id := range m.removedteam_group_members { - ids = append(ids, id) - } - return ids +// ClearMemory clears the value of the "memory" field. +func (m *VirtualMachineMutation) ClearMemory() { + m.memory = nil + m.addmemory = nil + m.clearedFields[virtualmachine.FieldMemory] = struct{}{} +} + +// MemoryCleared returns if the "memory" field was cleared in this mutation. +func (m *VirtualMachineMutation) MemoryCleared() bool { + _, ok := m.clearedFields[virtualmachine.FieldMemory] + return ok +} + +// ResetMemory resets all changes to the "memory" field. +func (m *VirtualMachineMutation) ResetMemory() { + m.memory = nil + m.addmemory = nil + delete(m.clearedFields, virtualmachine.FieldMemory) +} + +// SetOs sets the "os" field. +func (m *VirtualMachineMutation) SetOs(s string) { + m.os = &s +} + +// Os returns the value of the "os" field in the mutation. +func (m *VirtualMachineMutation) Os() (r string, exists bool) { + v := m.os + if v == nil { + return } - return nil + return *v, true } -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *UserMutation) ClearedEdges() []string { - edges := make([]string, 0, 8) - if m.clearedidentities { - edges = append(edges, user.EdgeIdentities) +// OldOs returns the old "os" field's value of the VirtualMachine entity. +// If the VirtualMachine 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 *VirtualMachineMutation) OldOs(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldOs is only allowed on UpdateOne operations") } - if m.clearedaudits { - edges = append(edges, user.EdgeAudits) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldOs requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldOs: %w", err) + } + return oldValue.Os, nil +} + +// ClearOs clears the value of the "os" field. +func (m *VirtualMachineMutation) ClearOs() { + m.os = nil + m.clearedFields[virtualmachine.FieldOs] = struct{}{} +} + +// OsCleared returns if the "os" field was cleared in this mutation. +func (m *VirtualMachineMutation) OsCleared() bool { + _, ok := m.clearedFields[virtualmachine.FieldOs] + return ok +} + +// ResetOs resets all changes to the "os" field. +func (m *VirtualMachineMutation) ResetOs() { + m.os = nil + delete(m.clearedFields, virtualmachine.FieldOs) +} + +// SetExternalIP sets the "external_ip" field. +func (m *VirtualMachineMutation) SetExternalIP(s string) { + m.external_ip = &s +} + +// ExternalIP returns the value of the "external_ip" field in the mutation. +func (m *VirtualMachineMutation) ExternalIP() (r string, exists bool) { + v := m.external_ip + if v == nil { + return } - if m.clearedteams { - edges = append(edges, user.EdgeTeams) + return *v, true +} + +// OldExternalIP returns the old "external_ip" field's value of the VirtualMachine entity. +// If the VirtualMachine 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 *VirtualMachineMutation) OldExternalIP(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldExternalIP is only allowed on UpdateOne operations") } - if m.clearedgroups { - edges = append(edges, user.EdgeGroups) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldExternalIP requires an ID field in the mutation") } - if m.clearedmodels { - edges = append(edges, user.EdgeModels) + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldExternalIP: %w", err) } - if m.clearedimages { - edges = append(edges, user.EdgeImages) + return oldValue.ExternalIP, nil +} + +// ClearExternalIP clears the value of the "external_ip" field. +func (m *VirtualMachineMutation) ClearExternalIP() { + m.external_ip = nil + m.clearedFields[virtualmachine.FieldExternalIP] = struct{}{} +} + +// ExternalIPCleared returns if the "external_ip" field was cleared in this mutation. +func (m *VirtualMachineMutation) ExternalIPCleared() bool { + _, ok := m.clearedFields[virtualmachine.FieldExternalIP] + return ok +} + +// ResetExternalIP resets all changes to the "external_ip" field. +func (m *VirtualMachineMutation) ResetExternalIP() { + m.external_ip = nil + delete(m.clearedFields, virtualmachine.FieldExternalIP) +} + +// SetInternalIP sets the "internal_ip" field. +func (m *VirtualMachineMutation) SetInternalIP(s string) { + m.internal_ip = &s +} + +// InternalIP returns the value of the "internal_ip" field in the mutation. +func (m *VirtualMachineMutation) InternalIP() (r string, exists bool) { + v := m.internal_ip + if v == nil { + return } - if m.clearedteam_members { - edges = append(edges, user.EdgeTeamMembers) + return *v, true +} + +// OldInternalIP returns the old "internal_ip" field's value of the VirtualMachine entity. +// If the VirtualMachine 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 *VirtualMachineMutation) OldInternalIP(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInternalIP is only allowed on UpdateOne operations") } - if m.clearedteam_group_members { - edges = append(edges, user.EdgeTeamGroupMembers) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInternalIP requires an ID field in the mutation") } - return edges + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInternalIP: %w", err) + } + return oldValue.InternalIP, nil } -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *UserMutation) EdgeCleared(name string) bool { - switch name { - case user.EdgeIdentities: - return m.clearedidentities - case user.EdgeAudits: - return m.clearedaudits - case user.EdgeTeams: - return m.clearedteams - case user.EdgeGroups: - return m.clearedgroups - case user.EdgeModels: - return m.clearedmodels - case user.EdgeImages: - return m.clearedimages - case user.EdgeTeamMembers: - return m.clearedteam_members - case user.EdgeTeamGroupMembers: - return m.clearedteam_group_members - } - return false +// ClearInternalIP clears the value of the "internal_ip" field. +func (m *VirtualMachineMutation) ClearInternalIP() { + m.internal_ip = nil + m.clearedFields[virtualmachine.FieldInternalIP] = struct{}{} } -// 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 *UserMutation) ClearEdge(name string) error { - switch name { +// InternalIPCleared returns if the "internal_ip" field was cleared in this mutation. +func (m *VirtualMachineMutation) InternalIPCleared() bool { + _, ok := m.clearedFields[virtualmachine.FieldInternalIP] + return ok +} + +// ResetInternalIP resets all changes to the "internal_ip" field. +func (m *VirtualMachineMutation) ResetInternalIP() { + m.internal_ip = nil + delete(m.clearedFields, virtualmachine.FieldInternalIP) +} + +// SetTTLKind sets the "ttl_kind" field. +func (m *VirtualMachineMutation) SetTTLKind(ctk consts.VirtualmachineTTLKind) { + m.ttl_kind = &ctk +} + +// TTLKind returns the value of the "ttl_kind" field in the mutation. +func (m *VirtualMachineMutation) TTLKind() (r consts.VirtualmachineTTLKind, exists bool) { + v := m.ttl_kind + if v == nil { + return } - return fmt.Errorf("unknown User unique edge %s", name) + return *v, true } -// 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 *UserMutation) ResetEdge(name string) error { - switch name { - case user.EdgeIdentities: - m.ResetIdentities() - return nil - case user.EdgeAudits: - m.ResetAudits() - return nil - case user.EdgeTeams: - m.ResetTeams() - return nil - case user.EdgeGroups: - m.ResetGroups() - return nil - case user.EdgeModels: - m.ResetModels() - return nil - case user.EdgeImages: - m.ResetImages() - return nil - case user.EdgeTeamMembers: - m.ResetTeamMembers() - return nil - case user.EdgeTeamGroupMembers: - m.ResetTeamGroupMembers() - return nil +// OldTTLKind returns the old "ttl_kind" field's value of the VirtualMachine entity. +// If the VirtualMachine 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 *VirtualMachineMutation) OldTTLKind(ctx context.Context) (v consts.VirtualmachineTTLKind, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTTLKind is only allowed on UpdateOne operations") } - return fmt.Errorf("unknown User edge %s", name) + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTTLKind requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTTLKind: %w", err) + } + return oldValue.TTLKind, nil } -// UserIdentityMutation represents an operation that mutates the UserIdentity nodes in the graph. -type UserIdentityMutation struct { - config - op Op - typ string - id *uuid.UUID - deleted_at *time.Time - platform *consts.UserPlatform - identity_id *string - username *string - email *string - avatar_url *string - created_at *time.Time - updated_at *time.Time - clearedFields map[string]struct{} - user *uuid.UUID - cleareduser bool - done bool - oldValue func(context.Context) (*UserIdentity, error) - predicates []predicate.UserIdentity +// ClearTTLKind clears the value of the "ttl_kind" field. +func (m *VirtualMachineMutation) ClearTTLKind() { + m.ttl_kind = nil + m.clearedFields[virtualmachine.FieldTTLKind] = struct{}{} } -var _ ent.Mutation = (*UserIdentityMutation)(nil) +// TTLKindCleared returns if the "ttl_kind" field was cleared in this mutation. +func (m *VirtualMachineMutation) TTLKindCleared() bool { + _, ok := m.clearedFields[virtualmachine.FieldTTLKind] + return ok +} -// useridentityOption allows management of the mutation configuration using functional options. -type useridentityOption func(*UserIdentityMutation) +// ResetTTLKind resets all changes to the "ttl_kind" field. +func (m *VirtualMachineMutation) ResetTTLKind() { + m.ttl_kind = nil + delete(m.clearedFields, virtualmachine.FieldTTLKind) +} -// newUserIdentityMutation creates new mutation for the UserIdentity entity. -func newUserIdentityMutation(c config, op Op, opts ...useridentityOption) *UserIdentityMutation { - m := &UserIdentityMutation{ - config: c, - op: op, - typ: TypeUserIdentity, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m +// SetTTL sets the "ttl" field. +func (m *VirtualMachineMutation) SetTTL(i int64) { + m.ttl = &i + m.addttl = nil } -// withUserIdentityID sets the ID field of the mutation. -func withUserIdentityID(id uuid.UUID) useridentityOption { - return func(m *UserIdentityMutation) { - var ( - err error - once sync.Once - value *UserIdentity - ) - m.oldValue = func(ctx context.Context) (*UserIdentity, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().UserIdentity.Get(ctx, id) - } - }) - return value, err - } - m.id = &id +// TTL returns the value of the "ttl" field in the mutation. +func (m *VirtualMachineMutation) TTL() (r int64, exists bool) { + v := m.ttl + if v == nil { + return } + return *v, true } -// withUserIdentity sets the old UserIdentity of the mutation. -func withUserIdentity(node *UserIdentity) useridentityOption { - return func(m *UserIdentityMutation) { - m.oldValue = func(context.Context) (*UserIdentity, error) { - return node, nil - } - m.id = &node.ID +// OldTTL returns the old "ttl" field's value of the VirtualMachine entity. +// If the VirtualMachine 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 *VirtualMachineMutation) OldTTL(ctx context.Context) (v int64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTTL is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTTL requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTTL: %w", err) } + return oldValue.TTL, nil } -// 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 UserIdentityMutation) Client() *Client { - client := &Client{config: m.config} - client.init() - return client +// AddTTL adds i to the "ttl" field. +func (m *VirtualMachineMutation) AddTTL(i int64) { + if m.addttl != nil { + *m.addttl += i + } else { + m.addttl = &i + } } -// Tx returns an `ent.Tx` for mutations that were executed in transactions; -// it returns an error otherwise. -func (m UserIdentityMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("db: mutation is not running in a transaction") +// AddedTTL returns the value that was added to the "ttl" field in this mutation. +func (m *VirtualMachineMutation) AddedTTL() (r int64, exists bool) { + v := m.addttl + if v == nil { + return } - tx := &Tx{config: m.config} - tx.init() - return tx, nil + return *v, true } -// SetID sets the value of the id field. Note that this -// operation is only accepted on creation of UserIdentity entities. -func (m *UserIdentityMutation) SetID(id uuid.UUID) { - m.id = &id +// ClearTTL clears the value of the "ttl" field. +func (m *VirtualMachineMutation) ClearTTL() { + m.ttl = nil + m.addttl = nil + m.clearedFields[virtualmachine.FieldTTL] = struct{}{} } -// 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 *UserIdentityMutation) ID() (id uuid.UUID, exists bool) { - if m.id == nil { - return - } - return *m.id, true +// TTLCleared returns if the "ttl" field was cleared in this mutation. +func (m *VirtualMachineMutation) TTLCleared() bool { + _, ok := m.clearedFields[virtualmachine.FieldTTL] + return ok } -// 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 *UserIdentityMutation) 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().UserIdentity.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) - } +// ResetTTL resets all changes to the "ttl" field. +func (m *VirtualMachineMutation) ResetTTL() { + m.ttl = nil + m.addttl = nil + delete(m.clearedFields, virtualmachine.FieldTTL) } -// SetDeletedAt sets the "deleted_at" field. -func (m *UserIdentityMutation) SetDeletedAt(t time.Time) { - m.deleted_at = &t +// SetVersion sets the "version" field. +func (m *VirtualMachineMutation) SetVersion(s string) { + m.version = &s } -// DeletedAt returns the value of the "deleted_at" field in the mutation. -func (m *UserIdentityMutation) DeletedAt() (r time.Time, exists bool) { - v := m.deleted_at +// Version returns the value of the "version" field in the mutation. +func (m *VirtualMachineMutation) Version() (r string, exists bool) { + v := m.version if v == nil { return } return *v, true } -// OldDeletedAt returns the old "deleted_at" field's value of the UserIdentity entity. -// If the UserIdentity object wasn't provided to the builder, the object is fetched from the database. +// OldVersion returns the old "version" field's value of the VirtualMachine entity. +// If the VirtualMachine 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 *UserIdentityMutation) OldDeletedAt(ctx context.Context) (v time.Time, err error) { +func (m *VirtualMachineMutation) OldVersion(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldDeletedAt is only allowed on UpdateOne operations") + return v, errors.New("OldVersion is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldDeletedAt requires an ID field in the mutation") + return v, errors.New("OldVersion requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldDeletedAt: %w", err) + return v, fmt.Errorf("querying old value for OldVersion: %w", err) } - return oldValue.DeletedAt, nil + return oldValue.Version, nil } - -// ClearDeletedAt clears the value of the "deleted_at" field. -func (m *UserIdentityMutation) ClearDeletedAt() { - m.deleted_at = nil - m.clearedFields[useridentity.FieldDeletedAt] = struct{}{} + +// ClearVersion clears the value of the "version" field. +func (m *VirtualMachineMutation) ClearVersion() { + m.version = nil + m.clearedFields[virtualmachine.FieldVersion] = struct{}{} } -// DeletedAtCleared returns if the "deleted_at" field was cleared in this mutation. -func (m *UserIdentityMutation) DeletedAtCleared() bool { - _, ok := m.clearedFields[useridentity.FieldDeletedAt] +// VersionCleared returns if the "version" field was cleared in this mutation. +func (m *VirtualMachineMutation) VersionCleared() bool { + _, ok := m.clearedFields[virtualmachine.FieldVersion] return ok } -// ResetDeletedAt resets all changes to the "deleted_at" field. -func (m *UserIdentityMutation) ResetDeletedAt() { - m.deleted_at = nil - delete(m.clearedFields, useridentity.FieldDeletedAt) +// ResetVersion resets all changes to the "version" field. +func (m *VirtualMachineMutation) ResetVersion() { + m.version = nil + delete(m.clearedFields, virtualmachine.FieldVersion) } -// SetUserID sets the "user_id" field. -func (m *UserIdentityMutation) SetUserID(u uuid.UUID) { - m.user = &u +// SetMachineID sets the "machine_id" field. +func (m *VirtualMachineMutation) SetMachineID(s string) { + m.machine_id = &s } -// UserID returns the value of the "user_id" field in the mutation. -func (m *UserIdentityMutation) UserID() (r uuid.UUID, exists bool) { - v := m.user +// MachineID returns the value of the "machine_id" field in the mutation. +func (m *VirtualMachineMutation) MachineID() (r string, exists bool) { + v := m.machine_id if v == nil { return } return *v, true } -// OldUserID returns the old "user_id" field's value of the UserIdentity entity. -// If the UserIdentity object wasn't provided to the builder, the object is fetched from the database. +// OldMachineID returns the old "machine_id" field's value of the VirtualMachine entity. +// If the VirtualMachine 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 *UserIdentityMutation) OldUserID(ctx context.Context) (v uuid.UUID, err error) { +func (m *VirtualMachineMutation) OldMachineID(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUserID is only allowed on UpdateOne operations") + return v, errors.New("OldMachineID is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUserID requires an ID field in the mutation") + return v, errors.New("OldMachineID requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldUserID: %w", err) + return v, fmt.Errorf("querying old value for OldMachineID: %w", err) } - return oldValue.UserID, nil + return oldValue.MachineID, nil } -// ResetUserID resets all changes to the "user_id" field. -func (m *UserIdentityMutation) ResetUserID() { - m.user = nil +// ClearMachineID clears the value of the "machine_id" field. +func (m *VirtualMachineMutation) ClearMachineID() { + m.machine_id = nil + m.clearedFields[virtualmachine.FieldMachineID] = struct{}{} } -// SetPlatform sets the "platform" field. -func (m *UserIdentityMutation) SetPlatform(cp consts.UserPlatform) { - m.platform = &cp +// MachineIDCleared returns if the "machine_id" field was cleared in this mutation. +func (m *VirtualMachineMutation) MachineIDCleared() bool { + _, ok := m.clearedFields[virtualmachine.FieldMachineID] + return ok } -// Platform returns the value of the "platform" field in the mutation. -func (m *UserIdentityMutation) Platform() (r consts.UserPlatform, exists bool) { - v := m.platform +// ResetMachineID resets all changes to the "machine_id" field. +func (m *VirtualMachineMutation) ResetMachineID() { + m.machine_id = nil + delete(m.clearedFields, virtualmachine.FieldMachineID) +} + +// SetRepoURL sets the "repo_url" field. +func (m *VirtualMachineMutation) SetRepoURL(s string) { + m.repo_url = &s +} + +// RepoURL returns the value of the "repo_url" field in the mutation. +func (m *VirtualMachineMutation) RepoURL() (r string, exists bool) { + v := m.repo_url if v == nil { return } return *v, true } -// OldPlatform returns the old "platform" field's value of the UserIdentity entity. -// If the UserIdentity object wasn't provided to the builder, the object is fetched from the database. +// OldRepoURL returns the old "repo_url" field's value of the VirtualMachine entity. +// If the VirtualMachine 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 *UserIdentityMutation) OldPlatform(ctx context.Context) (v consts.UserPlatform, err error) { +func (m *VirtualMachineMutation) OldRepoURL(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldPlatform is only allowed on UpdateOne operations") + return v, errors.New("OldRepoURL is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldPlatform requires an ID field in the mutation") + return v, errors.New("OldRepoURL requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldPlatform: %w", err) + return v, fmt.Errorf("querying old value for OldRepoURL: %w", err) } - return oldValue.Platform, nil + return oldValue.RepoURL, nil } -// ResetPlatform resets all changes to the "platform" field. -func (m *UserIdentityMutation) ResetPlatform() { - m.platform = nil +// ClearRepoURL clears the value of the "repo_url" field. +func (m *VirtualMachineMutation) ClearRepoURL() { + m.repo_url = nil + m.clearedFields[virtualmachine.FieldRepoURL] = struct{}{} } -// SetIdentityID sets the "identity_id" field. -func (m *UserIdentityMutation) SetIdentityID(s string) { - m.identity_id = &s +// RepoURLCleared returns if the "repo_url" field was cleared in this mutation. +func (m *VirtualMachineMutation) RepoURLCleared() bool { + _, ok := m.clearedFields[virtualmachine.FieldRepoURL] + return ok } -// IdentityID returns the value of the "identity_id" field in the mutation. -func (m *UserIdentityMutation) IdentityID() (r string, exists bool) { - v := m.identity_id +// ResetRepoURL resets all changes to the "repo_url" field. +func (m *VirtualMachineMutation) ResetRepoURL() { + m.repo_url = nil + delete(m.clearedFields, virtualmachine.FieldRepoURL) +} + +// SetRepoFilename sets the "repo_filename" field. +func (m *VirtualMachineMutation) SetRepoFilename(s string) { + m.repo_filename = &s +} + +// RepoFilename returns the value of the "repo_filename" field in the mutation. +func (m *VirtualMachineMutation) RepoFilename() (r string, exists bool) { + v := m.repo_filename if v == nil { return } return *v, true } -// OldIdentityID returns the old "identity_id" field's value of the UserIdentity entity. -// If the UserIdentity object wasn't provided to the builder, the object is fetched from the database. +// OldRepoFilename returns the old "repo_filename" field's value of the VirtualMachine entity. +// If the VirtualMachine 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 *UserIdentityMutation) OldIdentityID(ctx context.Context) (v string, err error) { +func (m *VirtualMachineMutation) OldRepoFilename(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldIdentityID is only allowed on UpdateOne operations") + return v, errors.New("OldRepoFilename is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldIdentityID requires an ID field in the mutation") + return v, errors.New("OldRepoFilename requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldIdentityID: %w", err) + return v, fmt.Errorf("querying old value for OldRepoFilename: %w", err) } - return oldValue.IdentityID, nil + return oldValue.RepoFilename, nil } -// ResetIdentityID resets all changes to the "identity_id" field. -func (m *UserIdentityMutation) ResetIdentityID() { - m.identity_id = nil +// ClearRepoFilename clears the value of the "repo_filename" field. +func (m *VirtualMachineMutation) ClearRepoFilename() { + m.repo_filename = nil + m.clearedFields[virtualmachine.FieldRepoFilename] = struct{}{} } -// SetUsername sets the "username" field. -func (m *UserIdentityMutation) SetUsername(s string) { - m.username = &s +// RepoFilenameCleared returns if the "repo_filename" field was cleared in this mutation. +func (m *VirtualMachineMutation) RepoFilenameCleared() bool { + _, ok := m.clearedFields[virtualmachine.FieldRepoFilename] + return ok } -// Username returns the value of the "username" field in the mutation. -func (m *UserIdentityMutation) Username() (r string, exists bool) { - v := m.username +// ResetRepoFilename resets all changes to the "repo_filename" field. +func (m *VirtualMachineMutation) ResetRepoFilename() { + m.repo_filename = nil + delete(m.clearedFields, virtualmachine.FieldRepoFilename) +} + +// SetBranch sets the "branch" field. +func (m *VirtualMachineMutation) SetBranch(s string) { + m.branch = &s +} + +// Branch returns the value of the "branch" field in the mutation. +func (m *VirtualMachineMutation) Branch() (r string, exists bool) { + v := m.branch if v == nil { return } return *v, true } -// OldUsername returns the old "username" field's value of the UserIdentity entity. -// If the UserIdentity object wasn't provided to the builder, the object is fetched from the database. +// OldBranch returns the old "branch" field's value of the VirtualMachine entity. +// If the VirtualMachine 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 *UserIdentityMutation) OldUsername(ctx context.Context) (v string, err error) { +func (m *VirtualMachineMutation) OldBranch(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUsername is only allowed on UpdateOne operations") + return v, errors.New("OldBranch is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUsername requires an ID field in the mutation") + return v, errors.New("OldBranch requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldUsername: %w", err) + return v, fmt.Errorf("querying old value for OldBranch: %w", err) } - return oldValue.Username, nil + return oldValue.Branch, nil } -// ResetUsername resets all changes to the "username" field. -func (m *UserIdentityMutation) ResetUsername() { - m.username = nil +// ClearBranch clears the value of the "branch" field. +func (m *VirtualMachineMutation) ClearBranch() { + m.branch = nil + m.clearedFields[virtualmachine.FieldBranch] = struct{}{} } -// SetEmail sets the "email" field. -func (m *UserIdentityMutation) SetEmail(s string) { - m.email = &s +// BranchCleared returns if the "branch" field was cleared in this mutation. +func (m *VirtualMachineMutation) BranchCleared() bool { + _, ok := m.clearedFields[virtualmachine.FieldBranch] + return ok } -// Email returns the value of the "email" field in the mutation. -func (m *UserIdentityMutation) Email() (r string, exists bool) { - v := m.email +// ResetBranch resets all changes to the "branch" field. +func (m *VirtualMachineMutation) ResetBranch() { + m.branch = nil + delete(m.clearedFields, virtualmachine.FieldBranch) +} + +// SetIsRecycled sets the "is_recycled" field. +func (m *VirtualMachineMutation) SetIsRecycled(b bool) { + m.is_recycled = &b +} + +// IsRecycled returns the value of the "is_recycled" field in the mutation. +func (m *VirtualMachineMutation) IsRecycled() (r bool, exists bool) { + v := m.is_recycled if v == nil { return } return *v, true } -// OldEmail returns the old "email" field's value of the UserIdentity entity. -// If the UserIdentity object wasn't provided to the builder, the object is fetched from the database. +// OldIsRecycled returns the old "is_recycled" field's value of the VirtualMachine entity. +// If the VirtualMachine 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 *UserIdentityMutation) OldEmail(ctx context.Context) (v string, err error) { +func (m *VirtualMachineMutation) OldIsRecycled(ctx context.Context) (v bool, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldEmail is only allowed on UpdateOne operations") + return v, errors.New("OldIsRecycled is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldEmail requires an ID field in the mutation") + return v, errors.New("OldIsRecycled requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldEmail: %w", err) + return v, fmt.Errorf("querying old value for OldIsRecycled: %w", err) } - return oldValue.Email, nil + return oldValue.IsRecycled, nil } -// ClearEmail clears the value of the "email" field. -func (m *UserIdentityMutation) ClearEmail() { - m.email = nil - m.clearedFields[useridentity.FieldEmail] = struct{}{} +// ClearIsRecycled clears the value of the "is_recycled" field. +func (m *VirtualMachineMutation) ClearIsRecycled() { + m.is_recycled = nil + m.clearedFields[virtualmachine.FieldIsRecycled] = struct{}{} } -// EmailCleared returns if the "email" field was cleared in this mutation. -func (m *UserIdentityMutation) EmailCleared() bool { - _, ok := m.clearedFields[useridentity.FieldEmail] +// IsRecycledCleared returns if the "is_recycled" field was cleared in this mutation. +func (m *VirtualMachineMutation) IsRecycledCleared() bool { + _, ok := m.clearedFields[virtualmachine.FieldIsRecycled] return ok } -// ResetEmail resets all changes to the "email" field. -func (m *UserIdentityMutation) ResetEmail() { - m.email = nil - delete(m.clearedFields, useridentity.FieldEmail) +// ResetIsRecycled resets all changes to the "is_recycled" field. +func (m *VirtualMachineMutation) ResetIsRecycled() { + m.is_recycled = nil + delete(m.clearedFields, virtualmachine.FieldIsRecycled) } -// SetAvatarURL sets the "avatar_url" field. -func (m *UserIdentityMutation) SetAvatarURL(s string) { - m.avatar_url = &s +// SetConditions sets the "conditions" field. +func (m *VirtualMachineMutation) SetConditions(tmc *types.VirtualMachineCondition) { + m.conditions = &tmc } -// AvatarURL returns the value of the "avatar_url" field in the mutation. -func (m *UserIdentityMutation) AvatarURL() (r string, exists bool) { - v := m.avatar_url +// Conditions returns the value of the "conditions" field in the mutation. +func (m *VirtualMachineMutation) Conditions() (r *types.VirtualMachineCondition, exists bool) { + v := m.conditions if v == nil { return } return *v, true } -// OldAvatarURL returns the old "avatar_url" field's value of the UserIdentity entity. -// If the UserIdentity object wasn't provided to the builder, the object is fetched from the database. +// OldConditions returns the old "conditions" field's value of the VirtualMachine entity. +// If the VirtualMachine 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 *UserIdentityMutation) OldAvatarURL(ctx context.Context) (v string, err error) { +func (m *VirtualMachineMutation) OldConditions(ctx context.Context) (v *types.VirtualMachineCondition, err error) { if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldAvatarURL is only allowed on UpdateOne operations") + return v, errors.New("OldConditions is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { - return v, errors.New("OldAvatarURL requires an ID field in the mutation") + return v, errors.New("OldConditions requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { - return v, fmt.Errorf("querying old value for OldAvatarURL: %w", err) + return v, fmt.Errorf("querying old value for OldConditions: %w", err) } - return oldValue.AvatarURL, nil + return oldValue.Conditions, nil } -// ClearAvatarURL clears the value of the "avatar_url" field. -func (m *UserIdentityMutation) ClearAvatarURL() { - m.avatar_url = nil - m.clearedFields[useridentity.FieldAvatarURL] = struct{}{} +// ClearConditions clears the value of the "conditions" field. +func (m *VirtualMachineMutation) ClearConditions() { + m.conditions = nil + m.clearedFields[virtualmachine.FieldConditions] = struct{}{} } -// AvatarURLCleared returns if the "avatar_url" field was cleared in this mutation. -func (m *UserIdentityMutation) AvatarURLCleared() bool { - _, ok := m.clearedFields[useridentity.FieldAvatarURL] +// ConditionsCleared returns if the "conditions" field was cleared in this mutation. +func (m *VirtualMachineMutation) ConditionsCleared() bool { + _, ok := m.clearedFields[virtualmachine.FieldConditions] return ok } -// ResetAvatarURL resets all changes to the "avatar_url" field. -func (m *UserIdentityMutation) ResetAvatarURL() { - m.avatar_url = nil - delete(m.clearedFields, useridentity.FieldAvatarURL) +// ResetConditions resets all changes to the "conditions" field. +func (m *VirtualMachineMutation) ResetConditions() { + m.conditions = nil + delete(m.clearedFields, virtualmachine.FieldConditions) } // SetCreatedAt sets the "created_at" field. -func (m *UserIdentityMutation) SetCreatedAt(t time.Time) { +func (m *VirtualMachineMutation) SetCreatedAt(t time.Time) { m.created_at = &t } // CreatedAt returns the value of the "created_at" field in the mutation. -func (m *UserIdentityMutation) CreatedAt() (r time.Time, exists bool) { +func (m *VirtualMachineMutation) CreatedAt() (r time.Time, exists bool) { v := m.created_at if v == nil { return @@ -11188,10 +16249,10 @@ func (m *UserIdentityMutation) CreatedAt() (r time.Time, exists bool) { return *v, true } -// OldCreatedAt returns the old "created_at" field's value of the UserIdentity entity. -// If the UserIdentity object wasn't provided to the builder, the object is fetched from the database. +// OldCreatedAt returns the old "created_at" field's value of the VirtualMachine entity. +// If the VirtualMachine 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 *UserIdentityMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { +func (m *VirtualMachineMutation) 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") } @@ -11206,17 +16267,17 @@ func (m *UserIdentityMutation) OldCreatedAt(ctx context.Context) (v time.Time, e } // ResetCreatedAt resets all changes to the "created_at" field. -func (m *UserIdentityMutation) ResetCreatedAt() { +func (m *VirtualMachineMutation) ResetCreatedAt() { m.created_at = nil } // SetUpdatedAt sets the "updated_at" field. -func (m *UserIdentityMutation) SetUpdatedAt(t time.Time) { +func (m *VirtualMachineMutation) SetUpdatedAt(t time.Time) { m.updated_at = &t } // UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *UserIdentityMutation) UpdatedAt() (r time.Time, exists bool) { +func (m *VirtualMachineMutation) UpdatedAt() (r time.Time, exists bool) { v := m.updated_at if v == nil { return @@ -11224,10 +16285,10 @@ func (m *UserIdentityMutation) UpdatedAt() (r time.Time, exists bool) { return *v, true } -// OldUpdatedAt returns the old "updated_at" field's value of the UserIdentity entity. -// If the UserIdentity object wasn't provided to the builder, the object is fetched from the database. +// OldUpdatedAt returns the old "updated_at" field's value of the VirtualMachine entity. +// If the VirtualMachine 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 *UserIdentityMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { +func (m *VirtualMachineMutation) 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") } @@ -11241,39 +16302,80 @@ func (m *UserIdentityMutation) OldUpdatedAt(ctx context.Context) (v time.Time, e return oldValue.UpdatedAt, nil } -// ClearUpdatedAt clears the value of the "updated_at" field. -func (m *UserIdentityMutation) ClearUpdatedAt() { +// ResetUpdatedAt resets all changes to the "updated_at" field. +func (m *VirtualMachineMutation) ResetUpdatedAt() { m.updated_at = nil - m.clearedFields[useridentity.FieldUpdatedAt] = struct{}{} } -// UpdatedAtCleared returns if the "updated_at" field was cleared in this mutation. -func (m *UserIdentityMutation) UpdatedAtCleared() bool { - _, ok := m.clearedFields[useridentity.FieldUpdatedAt] - return ok +// ClearHost clears the "host" edge to the Host entity. +func (m *VirtualMachineMutation) ClearHost() { + m.clearedhost = true + m.clearedFields[virtualmachine.FieldHostID] = struct{}{} } -// ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *UserIdentityMutation) ResetUpdatedAt() { - m.updated_at = nil - delete(m.clearedFields, useridentity.FieldUpdatedAt) +// HostCleared reports if the "host" edge to the Host entity was cleared. +func (m *VirtualMachineMutation) HostCleared() bool { + return m.clearedhost +} + +// HostIDs returns the "host" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// HostID instead. It exists only for internal usage by the builders. +func (m *VirtualMachineMutation) HostIDs() (ids []string) { + if id := m.host; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetHost resets all changes to the "host" edge. +func (m *VirtualMachineMutation) ResetHost() { + m.host = nil + m.clearedhost = false +} + +// ClearModel clears the "model" edge to the Model entity. +func (m *VirtualMachineMutation) ClearModel() { + m.clearedmodel = true + m.clearedFields[virtualmachine.FieldModelID] = struct{}{} +} + +// ModelCleared reports if the "model" edge to the Model entity was cleared. +func (m *VirtualMachineMutation) ModelCleared() bool { + return m.ModelIDCleared() || m.clearedmodel +} + +// ModelIDs returns the "model" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// ModelID instead. It exists only for internal usage by the builders. +func (m *VirtualMachineMutation) ModelIDs() (ids []uuid.UUID) { + if id := m.model; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetModel resets all changes to the "model" edge. +func (m *VirtualMachineMutation) ResetModel() { + m.model = nil + m.clearedmodel = false } // ClearUser clears the "user" edge to the User entity. -func (m *UserIdentityMutation) ClearUser() { +func (m *VirtualMachineMutation) ClearUser() { m.cleareduser = true - m.clearedFields[useridentity.FieldUserID] = struct{}{} + m.clearedFields[virtualmachine.FieldUserID] = struct{}{} } // UserCleared reports if the "user" edge to the User entity was cleared. -func (m *UserIdentityMutation) UserCleared() bool { - return m.cleareduser +func (m *VirtualMachineMutation) UserCleared() bool { + return m.UserIDCleared() || m.cleareduser } // UserIDs returns the "user" edge IDs in the mutation. // Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use // UserID instead. It exists only for internal usage by the builders. -func (m *UserIdentityMutation) UserIDs() (ids []uuid.UUID) { +func (m *VirtualMachineMutation) UserIDs() (ids []uuid.UUID) { if id := m.user; id != nil { ids = append(ids, *id) } @@ -11281,20 +16383,20 @@ func (m *UserIdentityMutation) UserIDs() (ids []uuid.UUID) { } // ResetUser resets all changes to the "user" edge. -func (m *UserIdentityMutation) ResetUser() { +func (m *VirtualMachineMutation) ResetUser() { m.user = nil m.cleareduser = false } -// Where appends a list predicates to the UserIdentityMutation builder. -func (m *UserIdentityMutation) Where(ps ...predicate.UserIdentity) { +// Where appends a list predicates to the VirtualMachineMutation builder. +func (m *VirtualMachineMutation) Where(ps ...predicate.VirtualMachine) { m.predicates = append(m.predicates, ps...) } -// WhereP appends storage-level predicates to the UserIdentityMutation builder. Using this method, +// WhereP appends storage-level predicates to the VirtualMachineMutation builder. Using this method, // users can use type-assertion to append predicates that do not depend on any generated package. -func (m *UserIdentityMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.UserIdentity, len(ps)) +func (m *VirtualMachineMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.VirtualMachine, len(ps)) for i := range ps { p[i] = ps[i] } @@ -11302,51 +16404,96 @@ func (m *UserIdentityMutation) WhereP(ps ...func(*sql.Selector)) { } // Op returns the operation name. -func (m *UserIdentityMutation) Op() Op { +func (m *VirtualMachineMutation) Op() Op { return m.op } // SetOp allows setting the mutation operation. -func (m *UserIdentityMutation) SetOp(op Op) { +func (m *VirtualMachineMutation) SetOp(op Op) { m.op = op } -// Type returns the node type of this mutation (UserIdentity). -func (m *UserIdentityMutation) Type() string { +// Type returns the node type of this mutation (VirtualMachine). +func (m *VirtualMachineMutation) 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 *UserIdentityMutation) Fields() []string { - fields := make([]string, 0, 9) +func (m *VirtualMachineMutation) Fields() []string { + fields := make([]string, 0, 24) if m.deleted_at != nil { - fields = append(fields, useridentity.FieldDeletedAt) + fields = append(fields, virtualmachine.FieldDeletedAt) + } + if m.host != nil { + fields = append(fields, virtualmachine.FieldHostID) } if m.user != nil { - fields = append(fields, useridentity.FieldUserID) + fields = append(fields, virtualmachine.FieldUserID) } - if m.platform != nil { - fields = append(fields, useridentity.FieldPlatform) + if m.model != nil { + fields = append(fields, virtualmachine.FieldModelID) } - if m.identity_id != nil { - fields = append(fields, useridentity.FieldIdentityID) + if m.environment_id != nil { + fields = append(fields, virtualmachine.FieldEnvironmentID) } - if m.username != nil { - fields = append(fields, useridentity.FieldUsername) + if m.name != nil { + fields = append(fields, virtualmachine.FieldName) } - if m.email != nil { - fields = append(fields, useridentity.FieldEmail) + if m.hostname != nil { + fields = append(fields, virtualmachine.FieldHostname) } - if m.avatar_url != nil { - fields = append(fields, useridentity.FieldAvatarURL) + if m.arch != nil { + fields = append(fields, virtualmachine.FieldArch) + } + if m.cores != nil { + fields = append(fields, virtualmachine.FieldCores) + } + if m.memory != nil { + fields = append(fields, virtualmachine.FieldMemory) + } + if m.os != nil { + fields = append(fields, virtualmachine.FieldOs) + } + if m.external_ip != nil { + fields = append(fields, virtualmachine.FieldExternalIP) + } + if m.internal_ip != nil { + fields = append(fields, virtualmachine.FieldInternalIP) + } + if m.ttl_kind != nil { + fields = append(fields, virtualmachine.FieldTTLKind) + } + if m.ttl != nil { + fields = append(fields, virtualmachine.FieldTTL) + } + if m.version != nil { + fields = append(fields, virtualmachine.FieldVersion) + } + if m.machine_id != nil { + fields = append(fields, virtualmachine.FieldMachineID) + } + if m.repo_url != nil { + fields = append(fields, virtualmachine.FieldRepoURL) + } + if m.repo_filename != nil { + fields = append(fields, virtualmachine.FieldRepoFilename) + } + if m.branch != nil { + fields = append(fields, virtualmachine.FieldBranch) + } + if m.is_recycled != nil { + fields = append(fields, virtualmachine.FieldIsRecycled) + } + if m.conditions != nil { + fields = append(fields, virtualmachine.FieldConditions) } if m.created_at != nil { - fields = append(fields, useridentity.FieldCreatedAt) + fields = append(fields, virtualmachine.FieldCreatedAt) } if m.updated_at != nil { - fields = append(fields, useridentity.FieldUpdatedAt) + fields = append(fields, virtualmachine.FieldUpdatedAt) } return fields } @@ -11354,25 +16501,55 @@ func (m *UserIdentityMutation) Fields() []string { // 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 *UserIdentityMutation) Field(name string) (ent.Value, bool) { +func (m *VirtualMachineMutation) Field(name string) (ent.Value, bool) { switch name { - case useridentity.FieldDeletedAt: + case virtualmachine.FieldDeletedAt: return m.DeletedAt() - case useridentity.FieldUserID: + case virtualmachine.FieldHostID: + return m.HostID() + case virtualmachine.FieldUserID: return m.UserID() - case useridentity.FieldPlatform: - return m.Platform() - case useridentity.FieldIdentityID: - return m.IdentityID() - case useridentity.FieldUsername: - return m.Username() - case useridentity.FieldEmail: - return m.Email() - case useridentity.FieldAvatarURL: - return m.AvatarURL() - case useridentity.FieldCreatedAt: + case virtualmachine.FieldModelID: + return m.ModelID() + case virtualmachine.FieldEnvironmentID: + return m.EnvironmentID() + case virtualmachine.FieldName: + return m.Name() + case virtualmachine.FieldHostname: + return m.Hostname() + case virtualmachine.FieldArch: + return m.Arch() + case virtualmachine.FieldCores: + return m.Cores() + case virtualmachine.FieldMemory: + return m.Memory() + case virtualmachine.FieldOs: + return m.Os() + case virtualmachine.FieldExternalIP: + return m.ExternalIP() + case virtualmachine.FieldInternalIP: + return m.InternalIP() + case virtualmachine.FieldTTLKind: + return m.TTLKind() + case virtualmachine.FieldTTL: + return m.TTL() + case virtualmachine.FieldVersion: + return m.Version() + case virtualmachine.FieldMachineID: + return m.MachineID() + case virtualmachine.FieldRepoURL: + return m.RepoURL() + case virtualmachine.FieldRepoFilename: + return m.RepoFilename() + case virtualmachine.FieldBranch: + return m.Branch() + case virtualmachine.FieldIsRecycled: + return m.IsRecycled() + case virtualmachine.FieldConditions: + return m.Conditions() + case virtualmachine.FieldCreatedAt: return m.CreatedAt() - case useridentity.FieldUpdatedAt: + case virtualmachine.FieldUpdatedAt: return m.UpdatedAt() } return nil, false @@ -11381,92 +16558,227 @@ func (m *UserIdentityMutation) Field(name string) (ent.Value, bool) { // 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 *UserIdentityMutation) OldField(ctx context.Context, name string) (ent.Value, error) { +func (m *VirtualMachineMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { - case useridentity.FieldDeletedAt: + case virtualmachine.FieldDeletedAt: return m.OldDeletedAt(ctx) - case useridentity.FieldUserID: + case virtualmachine.FieldHostID: + return m.OldHostID(ctx) + case virtualmachine.FieldUserID: return m.OldUserID(ctx) - case useridentity.FieldPlatform: - return m.OldPlatform(ctx) - case useridentity.FieldIdentityID: - return m.OldIdentityID(ctx) - case useridentity.FieldUsername: - return m.OldUsername(ctx) - case useridentity.FieldEmail: - return m.OldEmail(ctx) - case useridentity.FieldAvatarURL: - return m.OldAvatarURL(ctx) - case useridentity.FieldCreatedAt: + case virtualmachine.FieldModelID: + return m.OldModelID(ctx) + case virtualmachine.FieldEnvironmentID: + return m.OldEnvironmentID(ctx) + case virtualmachine.FieldName: + return m.OldName(ctx) + case virtualmachine.FieldHostname: + return m.OldHostname(ctx) + case virtualmachine.FieldArch: + return m.OldArch(ctx) + case virtualmachine.FieldCores: + return m.OldCores(ctx) + case virtualmachine.FieldMemory: + return m.OldMemory(ctx) + case virtualmachine.FieldOs: + return m.OldOs(ctx) + case virtualmachine.FieldExternalIP: + return m.OldExternalIP(ctx) + case virtualmachine.FieldInternalIP: + return m.OldInternalIP(ctx) + case virtualmachine.FieldTTLKind: + return m.OldTTLKind(ctx) + case virtualmachine.FieldTTL: + return m.OldTTL(ctx) + case virtualmachine.FieldVersion: + return m.OldVersion(ctx) + case virtualmachine.FieldMachineID: + return m.OldMachineID(ctx) + case virtualmachine.FieldRepoURL: + return m.OldRepoURL(ctx) + case virtualmachine.FieldRepoFilename: + return m.OldRepoFilename(ctx) + case virtualmachine.FieldBranch: + return m.OldBranch(ctx) + case virtualmachine.FieldIsRecycled: + return m.OldIsRecycled(ctx) + case virtualmachine.FieldConditions: + return m.OldConditions(ctx) + case virtualmachine.FieldCreatedAt: return m.OldCreatedAt(ctx) - case useridentity.FieldUpdatedAt: + case virtualmachine.FieldUpdatedAt: return m.OldUpdatedAt(ctx) } - return nil, fmt.Errorf("unknown UserIdentity field %s", name) + return nil, fmt.Errorf("unknown VirtualMachine 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 *UserIdentityMutation) SetField(name string, value ent.Value) error { +func (m *VirtualMachineMutation) SetField(name string, value ent.Value) error { switch name { - case useridentity.FieldDeletedAt: + case virtualmachine.FieldDeletedAt: v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetDeletedAt(v) return nil - case useridentity.FieldUserID: + case virtualmachine.FieldHostID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetHostID(v) + return nil + case virtualmachine.FieldUserID: v, ok := value.(uuid.UUID) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetUserID(v) return nil - case useridentity.FieldPlatform: - v, ok := value.(consts.UserPlatform) + case virtualmachine.FieldModelID: + v, ok := value.(uuid.UUID) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetPlatform(v) + m.SetModelID(v) return nil - case useridentity.FieldIdentityID: + case virtualmachine.FieldEnvironmentID: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetIdentityID(v) + m.SetEnvironmentID(v) return nil - case useridentity.FieldUsername: + case virtualmachine.FieldName: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetUsername(v) + m.SetName(v) return nil - case useridentity.FieldEmail: + case virtualmachine.FieldHostname: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetEmail(v) + m.SetHostname(v) return nil - case useridentity.FieldAvatarURL: + case virtualmachine.FieldArch: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } - m.SetAvatarURL(v) + m.SetArch(v) return nil - case useridentity.FieldCreatedAt: + case virtualmachine.FieldCores: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCores(v) + return nil + case virtualmachine.FieldMemory: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMemory(v) + return nil + case virtualmachine.FieldOs: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetOs(v) + return nil + case virtualmachine.FieldExternalIP: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetExternalIP(v) + return nil + case virtualmachine.FieldInternalIP: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInternalIP(v) + return nil + case virtualmachine.FieldTTLKind: + v, ok := value.(consts.VirtualmachineTTLKind) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTTLKind(v) + return nil + case virtualmachine.FieldTTL: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTTL(v) + return nil + case virtualmachine.FieldVersion: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetVersion(v) + return nil + case virtualmachine.FieldMachineID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMachineID(v) + return nil + case virtualmachine.FieldRepoURL: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRepoURL(v) + return nil + case virtualmachine.FieldRepoFilename: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRepoFilename(v) + return nil + case virtualmachine.FieldBranch: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBranch(v) + return nil + case virtualmachine.FieldIsRecycled: + v, ok := value.(bool) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetIsRecycled(v) + return nil + case virtualmachine.FieldConditions: + v, ok := value.(*types.VirtualMachineCondition) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetConditions(v) + return nil + case virtualmachine.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 useridentity.FieldUpdatedAt: + case virtualmachine.FieldUpdatedAt: v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) @@ -11474,126 +16786,320 @@ func (m *UserIdentityMutation) SetField(name string, value ent.Value) error { m.SetUpdatedAt(v) return nil } - return fmt.Errorf("unknown UserIdentity field %s", name) + return fmt.Errorf("unknown VirtualMachine field %s", name) } // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. -func (m *UserIdentityMutation) AddedFields() []string { - return nil +func (m *VirtualMachineMutation) AddedFields() []string { + var fields []string + if m.addcores != nil { + fields = append(fields, virtualmachine.FieldCores) + } + if m.addmemory != nil { + fields = append(fields, virtualmachine.FieldMemory) + } + if m.addttl != nil { + fields = append(fields, virtualmachine.FieldTTL) + } + 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 *UserIdentityMutation) AddedField(name string) (ent.Value, bool) { +func (m *VirtualMachineMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case virtualmachine.FieldCores: + return m.AddedCores() + case virtualmachine.FieldMemory: + return m.AddedMemory() + case virtualmachine.FieldTTL: + return m.AddedTTL() + } 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 *UserIdentityMutation) AddField(name string, value ent.Value) error { +func (m *VirtualMachineMutation) AddField(name string, value ent.Value) error { switch name { + case virtualmachine.FieldCores: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddCores(v) + return nil + case virtualmachine.FieldMemory: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddMemory(v) + return nil + case virtualmachine.FieldTTL: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddTTL(v) + return nil } - return fmt.Errorf("unknown UserIdentity numeric field %s", name) + return fmt.Errorf("unknown VirtualMachine numeric field %s", name) } // ClearedFields returns all nullable fields that were cleared during this // mutation. -func (m *UserIdentityMutation) ClearedFields() []string { +func (m *VirtualMachineMutation) ClearedFields() []string { var fields []string - if m.FieldCleared(useridentity.FieldDeletedAt) { - fields = append(fields, useridentity.FieldDeletedAt) + if m.FieldCleared(virtualmachine.FieldDeletedAt) { + fields = append(fields, virtualmachine.FieldDeletedAt) } - if m.FieldCleared(useridentity.FieldEmail) { - fields = append(fields, useridentity.FieldEmail) + if m.FieldCleared(virtualmachine.FieldUserID) { + fields = append(fields, virtualmachine.FieldUserID) } - if m.FieldCleared(useridentity.FieldAvatarURL) { - fields = append(fields, useridentity.FieldAvatarURL) + if m.FieldCleared(virtualmachine.FieldModelID) { + fields = append(fields, virtualmachine.FieldModelID) } - if m.FieldCleared(useridentity.FieldUpdatedAt) { - fields = append(fields, useridentity.FieldUpdatedAt) + if m.FieldCleared(virtualmachine.FieldEnvironmentID) { + fields = append(fields, virtualmachine.FieldEnvironmentID) + } + if m.FieldCleared(virtualmachine.FieldHostname) { + fields = append(fields, virtualmachine.FieldHostname) + } + if m.FieldCleared(virtualmachine.FieldArch) { + fields = append(fields, virtualmachine.FieldArch) + } + if m.FieldCleared(virtualmachine.FieldCores) { + fields = append(fields, virtualmachine.FieldCores) + } + if m.FieldCleared(virtualmachine.FieldMemory) { + fields = append(fields, virtualmachine.FieldMemory) + } + if m.FieldCleared(virtualmachine.FieldOs) { + fields = append(fields, virtualmachine.FieldOs) + } + if m.FieldCleared(virtualmachine.FieldExternalIP) { + fields = append(fields, virtualmachine.FieldExternalIP) + } + if m.FieldCleared(virtualmachine.FieldInternalIP) { + fields = append(fields, virtualmachine.FieldInternalIP) + } + if m.FieldCleared(virtualmachine.FieldTTLKind) { + fields = append(fields, virtualmachine.FieldTTLKind) + } + if m.FieldCleared(virtualmachine.FieldTTL) { + fields = append(fields, virtualmachine.FieldTTL) + } + if m.FieldCleared(virtualmachine.FieldVersion) { + fields = append(fields, virtualmachine.FieldVersion) + } + if m.FieldCleared(virtualmachine.FieldMachineID) { + fields = append(fields, virtualmachine.FieldMachineID) + } + if m.FieldCleared(virtualmachine.FieldRepoURL) { + fields = append(fields, virtualmachine.FieldRepoURL) + } + if m.FieldCleared(virtualmachine.FieldRepoFilename) { + fields = append(fields, virtualmachine.FieldRepoFilename) + } + if m.FieldCleared(virtualmachine.FieldBranch) { + fields = append(fields, virtualmachine.FieldBranch) + } + if m.FieldCleared(virtualmachine.FieldIsRecycled) { + fields = append(fields, virtualmachine.FieldIsRecycled) + } + if m.FieldCleared(virtualmachine.FieldConditions) { + fields = append(fields, virtualmachine.FieldConditions) } return fields } // FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. -func (m *UserIdentityMutation) FieldCleared(name string) bool { +func (m *VirtualMachineMutation) 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 *UserIdentityMutation) ClearField(name string) error { +func (m *VirtualMachineMutation) ClearField(name string) error { switch name { - case useridentity.FieldDeletedAt: + case virtualmachine.FieldDeletedAt: m.ClearDeletedAt() return nil - case useridentity.FieldEmail: - m.ClearEmail() + case virtualmachine.FieldUserID: + m.ClearUserID() return nil - case useridentity.FieldAvatarURL: - m.ClearAvatarURL() + case virtualmachine.FieldModelID: + m.ClearModelID() return nil - case useridentity.FieldUpdatedAt: - m.ClearUpdatedAt() + case virtualmachine.FieldEnvironmentID: + m.ClearEnvironmentID() + return nil + case virtualmachine.FieldHostname: + m.ClearHostname() + return nil + case virtualmachine.FieldArch: + m.ClearArch() + return nil + case virtualmachine.FieldCores: + m.ClearCores() + return nil + case virtualmachine.FieldMemory: + m.ClearMemory() + return nil + case virtualmachine.FieldOs: + m.ClearOs() + return nil + case virtualmachine.FieldExternalIP: + m.ClearExternalIP() + return nil + case virtualmachine.FieldInternalIP: + m.ClearInternalIP() + return nil + case virtualmachine.FieldTTLKind: + m.ClearTTLKind() + return nil + case virtualmachine.FieldTTL: + m.ClearTTL() + return nil + case virtualmachine.FieldVersion: + m.ClearVersion() + return nil + case virtualmachine.FieldMachineID: + m.ClearMachineID() + return nil + case virtualmachine.FieldRepoURL: + m.ClearRepoURL() + return nil + case virtualmachine.FieldRepoFilename: + m.ClearRepoFilename() + return nil + case virtualmachine.FieldBranch: + m.ClearBranch() + return nil + case virtualmachine.FieldIsRecycled: + m.ClearIsRecycled() + return nil + case virtualmachine.FieldConditions: + m.ClearConditions() return nil } - return fmt.Errorf("unknown UserIdentity nullable field %s", name) + return fmt.Errorf("unknown VirtualMachine 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 *UserIdentityMutation) ResetField(name string) error { +func (m *VirtualMachineMutation) ResetField(name string) error { switch name { - case useridentity.FieldDeletedAt: + case virtualmachine.FieldDeletedAt: m.ResetDeletedAt() return nil - case useridentity.FieldUserID: + case virtualmachine.FieldHostID: + m.ResetHostID() + return nil + case virtualmachine.FieldUserID: m.ResetUserID() return nil - case useridentity.FieldPlatform: - m.ResetPlatform() + case virtualmachine.FieldModelID: + m.ResetModelID() return nil - case useridentity.FieldIdentityID: - m.ResetIdentityID() + case virtualmachine.FieldEnvironmentID: + m.ResetEnvironmentID() return nil - case useridentity.FieldUsername: - m.ResetUsername() + case virtualmachine.FieldName: + m.ResetName() return nil - case useridentity.FieldEmail: - m.ResetEmail() + case virtualmachine.FieldHostname: + m.ResetHostname() return nil - case useridentity.FieldAvatarURL: - m.ResetAvatarURL() + case virtualmachine.FieldArch: + m.ResetArch() return nil - case useridentity.FieldCreatedAt: + case virtualmachine.FieldCores: + m.ResetCores() + return nil + case virtualmachine.FieldMemory: + m.ResetMemory() + return nil + case virtualmachine.FieldOs: + m.ResetOs() + return nil + case virtualmachine.FieldExternalIP: + m.ResetExternalIP() + return nil + case virtualmachine.FieldInternalIP: + m.ResetInternalIP() + return nil + case virtualmachine.FieldTTLKind: + m.ResetTTLKind() + return nil + case virtualmachine.FieldTTL: + m.ResetTTL() + return nil + case virtualmachine.FieldVersion: + m.ResetVersion() + return nil + case virtualmachine.FieldMachineID: + m.ResetMachineID() + return nil + case virtualmachine.FieldRepoURL: + m.ResetRepoURL() + return nil + case virtualmachine.FieldRepoFilename: + m.ResetRepoFilename() + return nil + case virtualmachine.FieldBranch: + m.ResetBranch() + return nil + case virtualmachine.FieldIsRecycled: + m.ResetIsRecycled() + return nil + case virtualmachine.FieldConditions: + m.ResetConditions() + return nil + case virtualmachine.FieldCreatedAt: m.ResetCreatedAt() return nil - case useridentity.FieldUpdatedAt: + case virtualmachine.FieldUpdatedAt: m.ResetUpdatedAt() return nil } - return fmt.Errorf("unknown UserIdentity field %s", name) + return fmt.Errorf("unknown VirtualMachine field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. -func (m *UserIdentityMutation) AddedEdges() []string { - edges := make([]string, 0, 1) +func (m *VirtualMachineMutation) AddedEdges() []string { + edges := make([]string, 0, 3) + if m.host != nil { + edges = append(edges, virtualmachine.EdgeHost) + } + if m.model != nil { + edges = append(edges, virtualmachine.EdgeModel) + } if m.user != nil { - edges = append(edges, useridentity.EdgeUser) + edges = append(edges, virtualmachine.EdgeUser) } return edges } // AddedIDs returns all IDs (to other nodes) that were added for the given edge // name in this mutation. -func (m *UserIdentityMutation) AddedIDs(name string) []ent.Value { +func (m *VirtualMachineMutation) AddedIDs(name string) []ent.Value { switch name { - case useridentity.EdgeUser: + case virtualmachine.EdgeHost: + if id := m.host; id != nil { + return []ent.Value{*id} + } + case virtualmachine.EdgeModel: + if id := m.model; id != nil { + return []ent.Value{*id} + } + case virtualmachine.EdgeUser: if id := m.user; id != nil { return []ent.Value{*id} } @@ -11602,31 +17108,41 @@ func (m *UserIdentityMutation) AddedIDs(name string) []ent.Value { } // RemovedEdges returns all edge names that were removed in this mutation. -func (m *UserIdentityMutation) RemovedEdges() []string { - edges := make([]string, 0, 1) +func (m *VirtualMachineMutation) RemovedEdges() []string { + edges := make([]string, 0, 3) return edges } // RemovedIDs returns all IDs (to other nodes) that were removed for the edge with // the given name in this mutation. -func (m *UserIdentityMutation) RemovedIDs(name string) []ent.Value { +func (m *VirtualMachineMutation) RemovedIDs(name string) []ent.Value { return nil } // ClearedEdges returns all edge names that were cleared in this mutation. -func (m *UserIdentityMutation) ClearedEdges() []string { - edges := make([]string, 0, 1) +func (m *VirtualMachineMutation) ClearedEdges() []string { + edges := make([]string, 0, 3) + if m.clearedhost { + edges = append(edges, virtualmachine.EdgeHost) + } + if m.clearedmodel { + edges = append(edges, virtualmachine.EdgeModel) + } if m.cleareduser { - edges = append(edges, useridentity.EdgeUser) + edges = append(edges, virtualmachine.EdgeUser) } return edges } // EdgeCleared returns a boolean which indicates if the edge with the given name // was cleared in this mutation. -func (m *UserIdentityMutation) EdgeCleared(name string) bool { +func (m *VirtualMachineMutation) EdgeCleared(name string) bool { switch name { - case useridentity.EdgeUser: + case virtualmachine.EdgeHost: + return m.clearedhost + case virtualmachine.EdgeModel: + return m.clearedmodel + case virtualmachine.EdgeUser: return m.cleareduser } return false @@ -11634,22 +17150,34 @@ func (m *UserIdentityMutation) EdgeCleared(name string) bool { // 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 *UserIdentityMutation) ClearEdge(name string) error { +func (m *VirtualMachineMutation) ClearEdge(name string) error { switch name { - case useridentity.EdgeUser: + case virtualmachine.EdgeHost: + m.ClearHost() + return nil + case virtualmachine.EdgeModel: + m.ClearModel() + return nil + case virtualmachine.EdgeUser: m.ClearUser() return nil } - return fmt.Errorf("unknown UserIdentity unique edge %s", name) + return fmt.Errorf("unknown VirtualMachine 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 *UserIdentityMutation) ResetEdge(name string) error { +func (m *VirtualMachineMutation) ResetEdge(name string) error { switch name { - case useridentity.EdgeUser: + case virtualmachine.EdgeHost: + m.ResetHost() + return nil + case virtualmachine.EdgeModel: + m.ResetModel() + return nil + case virtualmachine.EdgeUser: m.ResetUser() return nil } - return fmt.Errorf("unknown UserIdentity edge %s", name) + return fmt.Errorf("unknown VirtualMachine edge %s", name) } diff --git a/backend/db/page.go b/backend/db/page.go index 23be5ed2..752b3538 100644 --- a/backend/db/page.go +++ b/backend/db/page.go @@ -25,6 +25,20 @@ func (_m *AuditQuery) Page(ctx context.Context, page, size int) ([]*Audit, *Page return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil } +func (_m *HostQuery) Page(ctx context.Context, page, size int) ([]*Host, *PageInfo, error) { + cnt, err := _m.Count(ctx) + if err != nil { + return nil, nil, err + } + offset := size * (page - 1) + rs, err := _m.Offset(offset).Limit(size).All(ctx) + if err != nil { + return nil, nil, err + } + has := (page * size) < cnt + return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil +} + func (_m *ImageQuery) Page(ctx context.Context, page, size int) ([]*Image, *PageInfo, error) { cnt, err := _m.Count(ctx) if err != nil { @@ -81,6 +95,20 @@ func (_m *TeamGroupQuery) Page(ctx context.Context, page, size int) ([]*TeamGrou return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil } +func (_m *TeamGroupHostQuery) Page(ctx context.Context, page, size int) ([]*TeamGroupHost, *PageInfo, error) { + cnt, err := _m.Count(ctx) + if err != nil { + return nil, nil, err + } + offset := size * (page - 1) + rs, err := _m.Offset(offset).Limit(size).All(ctx) + if err != nil { + return nil, nil, err + } + has := (page * size) < cnt + return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil +} + func (_m *TeamGroupImageQuery) Page(ctx context.Context, page, size int) ([]*TeamGroupImage, *PageInfo, error) { cnt, err := _m.Count(ctx) if err != nil { @@ -123,6 +151,20 @@ func (_m *TeamGroupModelQuery) Page(ctx context.Context, page, size int) ([]*Tea return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil } +func (_m *TeamHostQuery) Page(ctx context.Context, page, size int) ([]*TeamHost, *PageInfo, error) { + cnt, err := _m.Count(ctx) + if err != nil { + return nil, nil, err + } + offset := size * (page - 1) + rs, err := _m.Offset(offset).Limit(size).All(ctx) + if err != nil { + return nil, nil, err + } + has := (page * size) < cnt + return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil +} + func (_m *TeamImageQuery) Page(ctx context.Context, page, size int) ([]*TeamImage, *PageInfo, error) { cnt, err := _m.Count(ctx) if err != nil { @@ -192,3 +234,17 @@ func (_m *UserIdentityQuery) Page(ctx context.Context, page, size int) ([]*UserI has := (page * size) < cnt return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil } + +func (_m *VirtualMachineQuery) Page(ctx context.Context, page, size int) ([]*VirtualMachine, *PageInfo, error) { + cnt, err := _m.Count(ctx) + if err != nil { + return nil, nil, err + } + offset := size * (page - 1) + rs, err := _m.Offset(offset).Limit(size).All(ctx) + if err != nil { + return nil, nil, err + } + has := (page * size) < cnt + return rs, &PageInfo{HasNextPage: has, TotalCount: int64(cnt)}, nil +} diff --git a/backend/db/predicate/predicate.go b/backend/db/predicate/predicate.go index fb6ed195..5adffad7 100644 --- a/backend/db/predicate/predicate.go +++ b/backend/db/predicate/predicate.go @@ -9,6 +9,9 @@ import ( // Audit is the predicate function for audit builders. type Audit func(*sql.Selector) +// Host is the predicate function for host builders. +type Host func(*sql.Selector) + // Image is the predicate function for image builders. type Image func(*sql.Selector) @@ -21,6 +24,9 @@ type Team func(*sql.Selector) // TeamGroup is the predicate function for teamgroup builders. type TeamGroup func(*sql.Selector) +// TeamGroupHost is the predicate function for teamgrouphost builders. +type TeamGroupHost func(*sql.Selector) + // TeamGroupImage is the predicate function for teamgroupimage builders. type TeamGroupImage func(*sql.Selector) @@ -30,6 +36,9 @@ type TeamGroupMember func(*sql.Selector) // TeamGroupModel is the predicate function for teamgroupmodel builders. type TeamGroupModel func(*sql.Selector) +// TeamHost is the predicate function for teamhost builders. +type TeamHost func(*sql.Selector) + // TeamImage is the predicate function for teamimage builders. type TeamImage func(*sql.Selector) @@ -44,3 +53,6 @@ type User func(*sql.Selector) // UserIdentity is the predicate function for useridentity builders. type UserIdentity func(*sql.Selector) + +// VirtualMachine is the predicate function for virtualmachine builders. +type VirtualMachine func(*sql.Selector) diff --git a/backend/db/runtime/runtime.go b/backend/db/runtime/runtime.go index a0b9a7fd..199877e6 100644 --- a/backend/db/runtime/runtime.go +++ b/backend/db/runtime/runtime.go @@ -6,18 +6,22 @@ import ( "time" "github.com/chaitin/MonkeyCode/backend/db/audit" + "github.com/chaitin/MonkeyCode/backend/db/host" "github.com/chaitin/MonkeyCode/backend/db/image" "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/team" "github.com/chaitin/MonkeyCode/backend/db/teamgroup" + "github.com/chaitin/MonkeyCode/backend/db/teamgrouphost" "github.com/chaitin/MonkeyCode/backend/db/teamgroupimage" "github.com/chaitin/MonkeyCode/backend/db/teamgroupmember" "github.com/chaitin/MonkeyCode/backend/db/teamgroupmodel" + "github.com/chaitin/MonkeyCode/backend/db/teamhost" "github.com/chaitin/MonkeyCode/backend/db/teamimage" "github.com/chaitin/MonkeyCode/backend/db/teammember" "github.com/chaitin/MonkeyCode/backend/db/teammodel" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/chaitin/MonkeyCode/backend/db/useridentity" + "github.com/chaitin/MonkeyCode/backend/db/virtualmachine" "github.com/chaitin/MonkeyCode/backend/ent/schema" ) @@ -31,6 +35,27 @@ func init() { auditDescCreatedAt := auditFields[7].Descriptor() // audit.DefaultCreatedAt holds the default value on creation for the created_at field. audit.DefaultCreatedAt = auditDescCreatedAt.Default.(func() time.Time) + hostMixin := schema.Host{}.Mixin() + hostMixinHooks0 := hostMixin[0].Hooks() + host.Hooks[0] = hostMixinHooks0[0] + hostMixinInters0 := hostMixin[0].Interceptors() + host.Interceptors[0] = hostMixinInters0[0] + hostFields := schema.Host{}.Fields() + _ = hostFields + // hostDescWeight is the schema descriptor for weight field. + hostDescWeight := hostFields[5].Descriptor() + // host.DefaultWeight holds the default value on creation for the weight field. + host.DefaultWeight = hostDescWeight.Default.(int) + // hostDescCreatedAt is the schema descriptor for created_at field. + hostDescCreatedAt := hostFields[14].Descriptor() + // host.DefaultCreatedAt holds the default value on creation for the created_at field. + host.DefaultCreatedAt = hostDescCreatedAt.Default.(func() time.Time) + // hostDescUpdatedAt is the schema descriptor for updated_at field. + hostDescUpdatedAt := hostFields[15].Descriptor() + // host.DefaultUpdatedAt holds the default value on creation for the updated_at field. + host.DefaultUpdatedAt = hostDescUpdatedAt.Default.(func() time.Time) + // host.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. + host.UpdateDefaultUpdatedAt = hostDescUpdatedAt.UpdateDefault.(func() time.Time) imageMixin := schema.Image{}.Mixin() imageMixinHooks0 := imageMixin[0].Hooks() image.Hooks[0] = imageMixinHooks0[0] @@ -125,6 +150,12 @@ func init() { teamgroup.DefaultUpdatedAt = teamgroupDescUpdatedAt.Default.(func() time.Time) // teamgroup.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. teamgroup.UpdateDefaultUpdatedAt = teamgroupDescUpdatedAt.UpdateDefault.(func() time.Time) + teamgrouphostFields := schema.TeamGroupHost{}.Fields() + _ = teamgrouphostFields + // teamgrouphostDescCreatedAt is the schema descriptor for created_at field. + teamgrouphostDescCreatedAt := teamgrouphostFields[3].Descriptor() + // teamgrouphost.DefaultCreatedAt holds the default value on creation for the created_at field. + teamgrouphost.DefaultCreatedAt = teamgrouphostDescCreatedAt.Default.(func() time.Time) teamgroupimageFields := schema.TeamGroupImage{}.Fields() _ = teamgroupimageFields // teamgroupimageDescCreatedAt is the schema descriptor for created_at field. @@ -143,6 +174,12 @@ func init() { teamgroupmodelDescCreatedAt := teamgroupmodelFields[3].Descriptor() // teamgroupmodel.DefaultCreatedAt holds the default value on creation for the created_at field. teamgroupmodel.DefaultCreatedAt = teamgroupmodelDescCreatedAt.Default.(func() time.Time) + teamhostFields := schema.TeamHost{}.Fields() + _ = teamhostFields + // teamhostDescCreatedAt is the schema descriptor for created_at field. + teamhostDescCreatedAt := teamhostFields[3].Descriptor() + // teamhost.DefaultCreatedAt holds the default value on creation for the created_at field. + teamhost.DefaultCreatedAt = teamhostDescCreatedAt.Default.(func() time.Time) teamimageFields := schema.TeamImage{}.Fields() _ = teamimageFields // teamimageDescCreatedAt is the schema descriptor for created_at field. @@ -213,6 +250,21 @@ func init() { useridentityDescUpdatedAt := useridentityFields[8].Descriptor() // useridentity.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. useridentity.UpdateDefaultUpdatedAt = useridentityDescUpdatedAt.UpdateDefault.(func() time.Time) + virtualmachineMixin := schema.VirtualMachine{}.Mixin() + virtualmachineMixinHooks0 := virtualmachineMixin[0].Hooks() + virtualmachine.Hooks[0] = virtualmachineMixinHooks0[0] + virtualmachineMixinInters0 := virtualmachineMixin[0].Interceptors() + virtualmachine.Interceptors[0] = virtualmachineMixinInters0[0] + virtualmachineFields := schema.VirtualMachine{}.Fields() + _ = virtualmachineFields + // virtualmachineDescCreatedAt is the schema descriptor for created_at field. + virtualmachineDescCreatedAt := virtualmachineFields[22].Descriptor() + // virtualmachine.DefaultCreatedAt holds the default value on creation for the created_at field. + virtualmachine.DefaultCreatedAt = virtualmachineDescCreatedAt.Default.(func() time.Time) + // virtualmachineDescUpdatedAt is the schema descriptor for updated_at field. + virtualmachineDescUpdatedAt := virtualmachineFields[23].Descriptor() + // virtualmachine.DefaultUpdatedAt holds the default value on creation for the updated_at field. + virtualmachine.DefaultUpdatedAt = virtualmachineDescUpdatedAt.Default.(func() time.Time) } const ( diff --git a/backend/db/teamgroup.go b/backend/db/teamgroup.go index 8560a192..8c7c21bd 100644 --- a/backend/db/teamgroup.go +++ b/backend/db/teamgroup.go @@ -45,15 +45,19 @@ type TeamGroupEdges struct { Models []*Model `json:"models,omitempty"` // Images holds the value of the images edge. Images []*Image `json:"images,omitempty"` + // Hosts holds the value of the hosts edge. + Hosts []*Host `json:"hosts,omitempty"` // TeamGroupMembers holds the value of the team_group_members edge. TeamGroupMembers []*TeamGroupMember `json:"team_group_members,omitempty"` // TeamGroupModels holds the value of the team_group_models edge. TeamGroupModels []*TeamGroupModel `json:"team_group_models,omitempty"` // TeamGroupImages holds the value of the team_group_images edge. TeamGroupImages []*TeamGroupImage `json:"team_group_images,omitempty"` + // TeamGroupHosts holds the value of the team_group_hosts edge. + TeamGroupHosts []*TeamGroupHost `json:"team_group_hosts,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [7]bool + loadedTypes [9]bool } // MembersOrErr returns the Members value or an error if the edge @@ -94,10 +98,19 @@ func (e TeamGroupEdges) ImagesOrErr() ([]*Image, error) { return nil, &NotLoadedError{edge: "images"} } +// HostsOrErr returns the Hosts value or an error if the edge +// was not loaded in eager-loading. +func (e TeamGroupEdges) HostsOrErr() ([]*Host, error) { + if e.loadedTypes[4] { + return e.Hosts, nil + } + return nil, &NotLoadedError{edge: "hosts"} +} + // TeamGroupMembersOrErr returns the TeamGroupMembers value or an error if the edge // was not loaded in eager-loading. func (e TeamGroupEdges) TeamGroupMembersOrErr() ([]*TeamGroupMember, error) { - if e.loadedTypes[4] { + if e.loadedTypes[5] { return e.TeamGroupMembers, nil } return nil, &NotLoadedError{edge: "team_group_members"} @@ -106,7 +119,7 @@ func (e TeamGroupEdges) TeamGroupMembersOrErr() ([]*TeamGroupMember, error) { // TeamGroupModelsOrErr returns the TeamGroupModels value or an error if the edge // was not loaded in eager-loading. func (e TeamGroupEdges) TeamGroupModelsOrErr() ([]*TeamGroupModel, error) { - if e.loadedTypes[5] { + if e.loadedTypes[6] { return e.TeamGroupModels, nil } return nil, &NotLoadedError{edge: "team_group_models"} @@ -115,12 +128,21 @@ func (e TeamGroupEdges) TeamGroupModelsOrErr() ([]*TeamGroupModel, error) { // TeamGroupImagesOrErr returns the TeamGroupImages value or an error if the edge // was not loaded in eager-loading. func (e TeamGroupEdges) TeamGroupImagesOrErr() ([]*TeamGroupImage, error) { - if e.loadedTypes[6] { + if e.loadedTypes[7] { return e.TeamGroupImages, nil } return nil, &NotLoadedError{edge: "team_group_images"} } +// TeamGroupHostsOrErr returns the TeamGroupHosts value or an error if the edge +// was not loaded in eager-loading. +func (e TeamGroupEdges) TeamGroupHostsOrErr() ([]*TeamGroupHost, error) { + if e.loadedTypes[8] { + return e.TeamGroupHosts, nil + } + return nil, &NotLoadedError{edge: "team_group_hosts"} +} + // scanValues returns the types for scanning values from sql.Rows. func (*TeamGroup) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) @@ -216,6 +238,11 @@ func (_m *TeamGroup) QueryImages() *ImageQuery { return NewTeamGroupClient(_m.config).QueryImages(_m) } +// QueryHosts queries the "hosts" edge of the TeamGroup entity. +func (_m *TeamGroup) QueryHosts() *HostQuery { + return NewTeamGroupClient(_m.config).QueryHosts(_m) +} + // QueryTeamGroupMembers queries the "team_group_members" edge of the TeamGroup entity. func (_m *TeamGroup) QueryTeamGroupMembers() *TeamGroupMemberQuery { return NewTeamGroupClient(_m.config).QueryTeamGroupMembers(_m) @@ -231,6 +258,11 @@ func (_m *TeamGroup) QueryTeamGroupImages() *TeamGroupImageQuery { return NewTeamGroupClient(_m.config).QueryTeamGroupImages(_m) } +// QueryTeamGroupHosts queries the "team_group_hosts" edge of the TeamGroup entity. +func (_m *TeamGroup) QueryTeamGroupHosts() *TeamGroupHostQuery { + return NewTeamGroupClient(_m.config).QueryTeamGroupHosts(_m) +} + // Update returns a builder for updating this TeamGroup. // Note that you need to call TeamGroup.Unwrap() before calling this method if this TeamGroup // was returned from a transaction, and the transaction was committed or rolled back. diff --git a/backend/db/teamgroup/teamgroup.go b/backend/db/teamgroup/teamgroup.go index 0e67990a..d71ec41b 100644 --- a/backend/db/teamgroup/teamgroup.go +++ b/backend/db/teamgroup/teamgroup.go @@ -33,12 +33,16 @@ const ( EdgeModels = "models" // EdgeImages holds the string denoting the images edge name in mutations. EdgeImages = "images" + // EdgeHosts holds the string denoting the hosts edge name in mutations. + EdgeHosts = "hosts" // EdgeTeamGroupMembers holds the string denoting the team_group_members edge name in mutations. EdgeTeamGroupMembers = "team_group_members" // EdgeTeamGroupModels holds the string denoting the team_group_models edge name in mutations. EdgeTeamGroupModels = "team_group_models" // EdgeTeamGroupImages holds the string denoting the team_group_images edge name in mutations. EdgeTeamGroupImages = "team_group_images" + // EdgeTeamGroupHosts holds the string denoting the team_group_hosts edge name in mutations. + EdgeTeamGroupHosts = "team_group_hosts" // Table holds the table name of the teamgroup in the database. Table = "team_groups" // MembersTable is the table that holds the members relation/edge. The primary key declared below. @@ -63,6 +67,11 @@ const ( // ImagesInverseTable is the table name for the Image entity. // It exists in this package in order to avoid circular dependency with the "image" package. ImagesInverseTable = "images" + // HostsTable is the table that holds the hosts relation/edge. The primary key declared below. + HostsTable = "team_group_hosts" + // HostsInverseTable is the table name for the Host entity. + // It exists in this package in order to avoid circular dependency with the "host" package. + HostsInverseTable = "hosts" // TeamGroupMembersTable is the table that holds the team_group_members relation/edge. TeamGroupMembersTable = "team_group_members" // TeamGroupMembersInverseTable is the table name for the TeamGroupMember entity. @@ -84,6 +93,13 @@ const ( TeamGroupImagesInverseTable = "team_group_images" // TeamGroupImagesColumn is the table column denoting the team_group_images relation/edge. TeamGroupImagesColumn = "group_id" + // TeamGroupHostsTable is the table that holds the team_group_hosts relation/edge. + TeamGroupHostsTable = "team_group_hosts" + // TeamGroupHostsInverseTable is the table name for the TeamGroupHost entity. + // It exists in this package in order to avoid circular dependency with the "teamgrouphost" package. + TeamGroupHostsInverseTable = "team_group_hosts" + // TeamGroupHostsColumn is the table column denoting the team_group_hosts relation/edge. + TeamGroupHostsColumn = "group_id" ) // Columns holds all SQL columns for teamgroup fields. @@ -106,6 +122,9 @@ var ( // ImagesPrimaryKey and ImagesColumn2 are the table columns denoting the // primary key for the images relation (M2M). ImagesPrimaryKey = []string{"group_id", "image_id"} + // HostsPrimaryKey and HostsColumn2 are the table columns denoting the + // primary key for the hosts relation (M2M). + HostsPrimaryKey = []string{"group_id", "host_id"} ) // ValidColumn reports if the column name is valid (part of the table columns). @@ -216,6 +235,20 @@ func ByImages(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { } } +// ByHostsCount orders the results by hosts count. +func ByHostsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newHostsStep(), opts...) + } +} + +// ByHosts orders the results by hosts terms. +func ByHosts(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newHostsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + // ByTeamGroupMembersCount orders the results by team_group_members count. func ByTeamGroupMembersCount(opts ...sql.OrderTermOption) OrderOption { return func(s *sql.Selector) { @@ -257,6 +290,20 @@ func ByTeamGroupImages(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { sqlgraph.OrderByNeighborTerms(s, newTeamGroupImagesStep(), append([]sql.OrderTerm{term}, terms...)...) } } + +// ByTeamGroupHostsCount orders the results by team_group_hosts count. +func ByTeamGroupHostsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newTeamGroupHostsStep(), opts...) + } +} + +// ByTeamGroupHosts orders the results by team_group_hosts terms. +func ByTeamGroupHosts(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newTeamGroupHostsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} func newMembersStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), @@ -285,6 +332,13 @@ func newImagesStep() *sqlgraph.Step { sqlgraph.Edge(sqlgraph.M2M, false, ImagesTable, ImagesPrimaryKey...), ) } +func newHostsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(HostsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, HostsTable, HostsPrimaryKey...), + ) +} func newTeamGroupMembersStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), @@ -306,3 +360,10 @@ func newTeamGroupImagesStep() *sqlgraph.Step { sqlgraph.Edge(sqlgraph.O2M, true, TeamGroupImagesTable, TeamGroupImagesColumn), ) } +func newTeamGroupHostsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TeamGroupHostsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, TeamGroupHostsTable, TeamGroupHostsColumn), + ) +} diff --git a/backend/db/teamgroup/where.go b/backend/db/teamgroup/where.go index 536a5520..93e7954a 100644 --- a/backend/db/teamgroup/where.go +++ b/backend/db/teamgroup/where.go @@ -388,6 +388,29 @@ func HasImagesWith(preds ...predicate.Image) predicate.TeamGroup { }) } +// HasHosts applies the HasEdge predicate on the "hosts" edge. +func HasHosts() predicate.TeamGroup { + return predicate.TeamGroup(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, HostsTable, HostsPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasHostsWith applies the HasEdge predicate on the "hosts" edge with a given conditions (other predicates). +func HasHostsWith(preds ...predicate.Host) predicate.TeamGroup { + return predicate.TeamGroup(func(s *sql.Selector) { + step := newHostsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + // HasTeamGroupMembers applies the HasEdge predicate on the "team_group_members" edge. func HasTeamGroupMembers() predicate.TeamGroup { return predicate.TeamGroup(func(s *sql.Selector) { @@ -457,6 +480,29 @@ func HasTeamGroupImagesWith(preds ...predicate.TeamGroupImage) predicate.TeamGro }) } +// HasTeamGroupHosts applies the HasEdge predicate on the "team_group_hosts" edge. +func HasTeamGroupHosts() predicate.TeamGroup { + return predicate.TeamGroup(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, TeamGroupHostsTable, TeamGroupHostsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasTeamGroupHostsWith applies the HasEdge predicate on the "team_group_hosts" edge with a given conditions (other predicates). +func HasTeamGroupHostsWith(preds ...predicate.TeamGroupHost) predicate.TeamGroup { + return predicate.TeamGroup(func(s *sql.Selector) { + step := newTeamGroupHostsStep() + 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.TeamGroup) predicate.TeamGroup { return predicate.TeamGroup(sql.AndPredicates(predicates...)) diff --git a/backend/db/teamgroup_create.go b/backend/db/teamgroup_create.go index e8a1a049..0adb5a5e 100644 --- a/backend/db/teamgroup_create.go +++ b/backend/db/teamgroup_create.go @@ -12,10 +12,12 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/host" "github.com/chaitin/MonkeyCode/backend/db/image" "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/team" "github.com/chaitin/MonkeyCode/backend/db/teamgroup" + "github.com/chaitin/MonkeyCode/backend/db/teamgrouphost" "github.com/chaitin/MonkeyCode/backend/db/teamgroupimage" "github.com/chaitin/MonkeyCode/backend/db/teamgroupmember" "github.com/chaitin/MonkeyCode/backend/db/teamgroupmodel" @@ -141,6 +143,21 @@ func (_c *TeamGroupCreate) AddImages(v ...*Image) *TeamGroupCreate { return _c.AddImageIDs(ids...) } +// AddHostIDs adds the "hosts" edge to the Host entity by IDs. +func (_c *TeamGroupCreate) AddHostIDs(ids ...string) *TeamGroupCreate { + _c.mutation.AddHostIDs(ids...) + return _c +} + +// AddHosts adds the "hosts" edges to the Host entity. +func (_c *TeamGroupCreate) AddHosts(v ...*Host) *TeamGroupCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddHostIDs(ids...) +} + // AddTeamGroupMemberIDs adds the "team_group_members" edge to the TeamGroupMember entity by IDs. func (_c *TeamGroupCreate) AddTeamGroupMemberIDs(ids ...uuid.UUID) *TeamGroupCreate { _c.mutation.AddTeamGroupMemberIDs(ids...) @@ -186,6 +203,21 @@ func (_c *TeamGroupCreate) AddTeamGroupImages(v ...*TeamGroupImage) *TeamGroupCr return _c.AddTeamGroupImageIDs(ids...) } +// AddTeamGroupHostIDs adds the "team_group_hosts" edge to the TeamGroupHost entity by IDs. +func (_c *TeamGroupCreate) AddTeamGroupHostIDs(ids ...uuid.UUID) *TeamGroupCreate { + _c.mutation.AddTeamGroupHostIDs(ids...) + return _c +} + +// AddTeamGroupHosts adds the "team_group_hosts" edges to the TeamGroupHost entity. +func (_c *TeamGroupCreate) AddTeamGroupHosts(v ...*TeamGroupHost) *TeamGroupCreate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddTeamGroupHostIDs(ids...) +} + // Mutation returns the TeamGroupMutation object of the builder. func (_c *TeamGroupCreate) Mutation() *TeamGroupMutation { return _c.mutation @@ -386,6 +418,26 @@ func (_c *TeamGroupCreate) createSpec() (*TeamGroup, *sqlgraph.CreateSpec) { edge.Target.Fields = specE.Fields _spec.Edges = append(_spec.Edges, edge) } + if nodes := _c.mutation.HostsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: teamgroup.HostsTable, + Columns: teamgroup.HostsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &TeamGroupHostCreate{config: _c.config, mutation: newTeamGroupHostMutation(_c.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges = append(_spec.Edges, edge) + } if nodes := _c.mutation.TeamGroupMembersIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, @@ -434,6 +486,22 @@ func (_c *TeamGroupCreate) createSpec() (*TeamGroup, *sqlgraph.CreateSpec) { } _spec.Edges = append(_spec.Edges, edge) } + if nodes := _c.mutation.TeamGroupHostsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: teamgroup.TeamGroupHostsTable, + Columns: []string{teamgroup.TeamGroupHostsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(teamgrouphost.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } return _node, _spec } diff --git a/backend/db/teamgroup_query.go b/backend/db/teamgroup_query.go index 135aabef..794b1caf 100644 --- a/backend/db/teamgroup_query.go +++ b/backend/db/teamgroup_query.go @@ -13,11 +13,13 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/host" "github.com/chaitin/MonkeyCode/backend/db/image" "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/predicate" "github.com/chaitin/MonkeyCode/backend/db/team" "github.com/chaitin/MonkeyCode/backend/db/teamgroup" + "github.com/chaitin/MonkeyCode/backend/db/teamgrouphost" "github.com/chaitin/MonkeyCode/backend/db/teamgroupimage" "github.com/chaitin/MonkeyCode/backend/db/teamgroupmember" "github.com/chaitin/MonkeyCode/backend/db/teamgroupmodel" @@ -36,9 +38,11 @@ type TeamGroupQuery struct { withTeam *TeamQuery withModels *ModelQuery withImages *ImageQuery + withHosts *HostQuery withTeamGroupMembers *TeamGroupMemberQuery withTeamGroupModels *TeamGroupModelQuery withTeamGroupImages *TeamGroupImageQuery + withTeamGroupHosts *TeamGroupHostQuery modifiers []func(*sql.Selector) // intermediate query (i.e. traversal path). sql *sql.Selector @@ -164,6 +168,28 @@ func (_q *TeamGroupQuery) QueryImages() *ImageQuery { return query } +// QueryHosts chains the current query on the "hosts" edge. +func (_q *TeamGroupQuery) QueryHosts() *HostQuery { + query := (&HostClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(teamgroup.Table, teamgroup.FieldID, selector), + sqlgraph.To(host.Table, host.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, teamgroup.HostsTable, teamgroup.HostsPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + // QueryTeamGroupMembers chains the current query on the "team_group_members" edge. func (_q *TeamGroupQuery) QueryTeamGroupMembers() *TeamGroupMemberQuery { query := (&TeamGroupMemberClient{config: _q.config}).Query() @@ -230,6 +256,28 @@ func (_q *TeamGroupQuery) QueryTeamGroupImages() *TeamGroupImageQuery { return query } +// QueryTeamGroupHosts chains the current query on the "team_group_hosts" edge. +func (_q *TeamGroupQuery) QueryTeamGroupHosts() *TeamGroupHostQuery { + query := (&TeamGroupHostClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(teamgroup.Table, teamgroup.FieldID, selector), + sqlgraph.To(teamgrouphost.Table, teamgrouphost.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, teamgroup.TeamGroupHostsTable, teamgroup.TeamGroupHostsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + // First returns the first TeamGroup entity from the query. // Returns a *NotFoundError when no TeamGroup was found. func (_q *TeamGroupQuery) First(ctx context.Context) (*TeamGroup, error) { @@ -426,9 +474,11 @@ func (_q *TeamGroupQuery) Clone() *TeamGroupQuery { withTeam: _q.withTeam.Clone(), withModels: _q.withModels.Clone(), withImages: _q.withImages.Clone(), + withHosts: _q.withHosts.Clone(), withTeamGroupMembers: _q.withTeamGroupMembers.Clone(), withTeamGroupModels: _q.withTeamGroupModels.Clone(), withTeamGroupImages: _q.withTeamGroupImages.Clone(), + withTeamGroupHosts: _q.withTeamGroupHosts.Clone(), // clone intermediate query. sql: _q.sql.Clone(), path: _q.path, @@ -480,6 +530,17 @@ func (_q *TeamGroupQuery) WithImages(opts ...func(*ImageQuery)) *TeamGroupQuery return _q } +// WithHosts tells the query-builder to eager-load the nodes that are connected to +// the "hosts" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *TeamGroupQuery) WithHosts(opts ...func(*HostQuery)) *TeamGroupQuery { + query := (&HostClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withHosts = query + return _q +} + // WithTeamGroupMembers tells the query-builder to eager-load the nodes that are connected to // the "team_group_members" edge. The optional arguments are used to configure the query builder of the edge. func (_q *TeamGroupQuery) WithTeamGroupMembers(opts ...func(*TeamGroupMemberQuery)) *TeamGroupQuery { @@ -513,6 +574,17 @@ func (_q *TeamGroupQuery) WithTeamGroupImages(opts ...func(*TeamGroupImageQuery) return _q } +// WithTeamGroupHosts tells the query-builder to eager-load the nodes that are connected to +// the "team_group_hosts" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *TeamGroupQuery) WithTeamGroupHosts(opts ...func(*TeamGroupHostQuery)) *TeamGroupQuery { + query := (&TeamGroupHostClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withTeamGroupHosts = query + return _q +} + // GroupBy is used to group vertices by one or more fields/columns. // It is often used with aggregate functions, like: count, max, mean, min, sum. // @@ -591,14 +663,16 @@ func (_q *TeamGroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Te var ( nodes = []*TeamGroup{} _spec = _q.querySpec() - loadedTypes = [7]bool{ + loadedTypes = [9]bool{ _q.withMembers != nil, _q.withTeam != nil, _q.withModels != nil, _q.withImages != nil, + _q.withHosts != nil, _q.withTeamGroupMembers != nil, _q.withTeamGroupModels != nil, _q.withTeamGroupImages != nil, + _q.withTeamGroupHosts != nil, } ) _spec.ScanValues = func(columns []string) ([]any, error) { @@ -649,6 +723,13 @@ func (_q *TeamGroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Te return nil, err } } + if query := _q.withHosts; query != nil { + if err := _q.loadHosts(ctx, query, nodes, + func(n *TeamGroup) { n.Edges.Hosts = []*Host{} }, + func(n *TeamGroup, e *Host) { n.Edges.Hosts = append(n.Edges.Hosts, e) }); err != nil { + return nil, err + } + } if query := _q.withTeamGroupMembers; query != nil { if err := _q.loadTeamGroupMembers(ctx, query, nodes, func(n *TeamGroup) { n.Edges.TeamGroupMembers = []*TeamGroupMember{} }, @@ -670,6 +751,13 @@ func (_q *TeamGroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Te return nil, err } } + if query := _q.withTeamGroupHosts; query != nil { + if err := _q.loadTeamGroupHosts(ctx, query, nodes, + func(n *TeamGroup) { n.Edges.TeamGroupHosts = []*TeamGroupHost{} }, + func(n *TeamGroup, e *TeamGroupHost) { n.Edges.TeamGroupHosts = append(n.Edges.TeamGroupHosts, e) }); err != nil { + return nil, err + } + } return nodes, nil } @@ -885,6 +973,67 @@ func (_q *TeamGroupQuery) loadImages(ctx context.Context, query *ImageQuery, nod } return nil } +func (_q *TeamGroupQuery) loadHosts(ctx context.Context, query *HostQuery, nodes []*TeamGroup, init func(*TeamGroup), assign func(*TeamGroup, *Host)) error { + edgeIDs := make([]driver.Value, len(nodes)) + byID := make(map[uuid.UUID]*TeamGroup) + nids := make(map[string]map[*TeamGroup]struct{}) + for i, node := range nodes { + edgeIDs[i] = node.ID + byID[node.ID] = node + if init != nil { + init(node) + } + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(teamgroup.HostsTable) + s.Join(joinT).On(s.C(host.FieldID), joinT.C(teamgroup.HostsPrimaryKey[1])) + s.Where(sql.InValues(joinT.C(teamgroup.HostsPrimaryKey[0]), edgeIDs...)) + columns := s.SelectedColumns() + s.Select(joinT.C(teamgroup.HostsPrimaryKey[0])) + s.AppendSelect(columns...) + s.SetDistinct(false) + }) + if err := query.prepareQuery(ctx); err != nil { + return err + } + qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) { + assign := spec.Assign + values := spec.ScanValues + spec.ScanValues = func(columns []string) ([]any, error) { + values, err := values(columns[1:]) + if err != nil { + return nil, err + } + return append([]any{new(uuid.UUID)}, values...), nil + } + spec.Assign = func(columns []string, values []any) error { + outValue := *values[0].(*uuid.UUID) + inValue := values[1].(*sql.NullString).String + if nids[inValue] == nil { + nids[inValue] = map[*TeamGroup]struct{}{byID[outValue]: {}} + return assign(columns[1:], values[1:]) + } + nids[inValue][byID[outValue]] = struct{}{} + return nil + } + }) + }) + neighbors, err := withInterceptors[[]*Host](ctx, query, qr, query.inters) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nids[n.ID] + if !ok { + return fmt.Errorf(`unexpected "hosts" node returned %v`, n.ID) + } + for kn := range nodes { + assign(kn, n) + } + } + return nil +} func (_q *TeamGroupQuery) loadTeamGroupMembers(ctx context.Context, query *TeamGroupMemberQuery, nodes []*TeamGroup, init func(*TeamGroup), assign func(*TeamGroup, *TeamGroupMember)) error { fks := make([]driver.Value, 0, len(nodes)) nodeids := make(map[uuid.UUID]*TeamGroup) @@ -975,6 +1124,36 @@ func (_q *TeamGroupQuery) loadTeamGroupImages(ctx context.Context, query *TeamGr } return nil } +func (_q *TeamGroupQuery) loadTeamGroupHosts(ctx context.Context, query *TeamGroupHostQuery, nodes []*TeamGroup, init func(*TeamGroup), assign func(*TeamGroup, *TeamGroupHost)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[uuid.UUID]*TeamGroup) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(teamgrouphost.FieldGroupID) + } + query.Where(predicate.TeamGroupHost(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(teamgroup.TeamGroupHostsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.GroupID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "group_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} func (_q *TeamGroupQuery) sqlCount(ctx context.Context) (int, error) { _spec := _q.querySpec() diff --git a/backend/db/teamgroup_update.go b/backend/db/teamgroup_update.go index 31e3f087..85457c84 100644 --- a/backend/db/teamgroup_update.go +++ b/backend/db/teamgroup_update.go @@ -11,11 +11,13 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/host" "github.com/chaitin/MonkeyCode/backend/db/image" "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/predicate" "github.com/chaitin/MonkeyCode/backend/db/team" "github.com/chaitin/MonkeyCode/backend/db/teamgroup" + "github.com/chaitin/MonkeyCode/backend/db/teamgrouphost" "github.com/chaitin/MonkeyCode/backend/db/teamgroupimage" "github.com/chaitin/MonkeyCode/backend/db/teamgroupmember" "github.com/chaitin/MonkeyCode/backend/db/teamgroupmodel" @@ -155,6 +157,21 @@ func (_u *TeamGroupUpdate) AddImages(v ...*Image) *TeamGroupUpdate { return _u.AddImageIDs(ids...) } +// AddHostIDs adds the "hosts" edge to the Host entity by IDs. +func (_u *TeamGroupUpdate) AddHostIDs(ids ...string) *TeamGroupUpdate { + _u.mutation.AddHostIDs(ids...) + return _u +} + +// AddHosts adds the "hosts" edges to the Host entity. +func (_u *TeamGroupUpdate) AddHosts(v ...*Host) *TeamGroupUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddHostIDs(ids...) +} + // AddTeamGroupMemberIDs adds the "team_group_members" edge to the TeamGroupMember entity by IDs. func (_u *TeamGroupUpdate) AddTeamGroupMemberIDs(ids ...uuid.UUID) *TeamGroupUpdate { _u.mutation.AddTeamGroupMemberIDs(ids...) @@ -200,6 +217,21 @@ func (_u *TeamGroupUpdate) AddTeamGroupImages(v ...*TeamGroupImage) *TeamGroupUp return _u.AddTeamGroupImageIDs(ids...) } +// AddTeamGroupHostIDs adds the "team_group_hosts" edge to the TeamGroupHost entity by IDs. +func (_u *TeamGroupUpdate) AddTeamGroupHostIDs(ids ...uuid.UUID) *TeamGroupUpdate { + _u.mutation.AddTeamGroupHostIDs(ids...) + return _u +} + +// AddTeamGroupHosts adds the "team_group_hosts" edges to the TeamGroupHost entity. +func (_u *TeamGroupUpdate) AddTeamGroupHosts(v ...*TeamGroupHost) *TeamGroupUpdate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddTeamGroupHostIDs(ids...) +} + // Mutation returns the TeamGroupMutation object of the builder. func (_u *TeamGroupUpdate) Mutation() *TeamGroupMutation { return _u.mutation @@ -274,6 +306,27 @@ func (_u *TeamGroupUpdate) RemoveImages(v ...*Image) *TeamGroupUpdate { return _u.RemoveImageIDs(ids...) } +// ClearHosts clears all "hosts" edges to the Host entity. +func (_u *TeamGroupUpdate) ClearHosts() *TeamGroupUpdate { + _u.mutation.ClearHosts() + return _u +} + +// RemoveHostIDs removes the "hosts" edge to Host entities by IDs. +func (_u *TeamGroupUpdate) RemoveHostIDs(ids ...string) *TeamGroupUpdate { + _u.mutation.RemoveHostIDs(ids...) + return _u +} + +// RemoveHosts removes "hosts" edges to Host entities. +func (_u *TeamGroupUpdate) RemoveHosts(v ...*Host) *TeamGroupUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveHostIDs(ids...) +} + // ClearTeamGroupMembers clears all "team_group_members" edges to the TeamGroupMember entity. func (_u *TeamGroupUpdate) ClearTeamGroupMembers() *TeamGroupUpdate { _u.mutation.ClearTeamGroupMembers() @@ -337,6 +390,27 @@ func (_u *TeamGroupUpdate) RemoveTeamGroupImages(v ...*TeamGroupImage) *TeamGrou return _u.RemoveTeamGroupImageIDs(ids...) } +// ClearTeamGroupHosts clears all "team_group_hosts" edges to the TeamGroupHost entity. +func (_u *TeamGroupUpdate) ClearTeamGroupHosts() *TeamGroupUpdate { + _u.mutation.ClearTeamGroupHosts() + return _u +} + +// RemoveTeamGroupHostIDs removes the "team_group_hosts" edge to TeamGroupHost entities by IDs. +func (_u *TeamGroupUpdate) RemoveTeamGroupHostIDs(ids ...uuid.UUID) *TeamGroupUpdate { + _u.mutation.RemoveTeamGroupHostIDs(ids...) + return _u +} + +// RemoveTeamGroupHosts removes "team_group_hosts" edges to TeamGroupHost entities. +func (_u *TeamGroupUpdate) RemoveTeamGroupHosts(v ...*TeamGroupHost) *TeamGroupUpdate { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveTeamGroupHostIDs(ids...) +} + // Save executes the query and returns the number of nodes affected by the update operation. func (_u *TeamGroupUpdate) Save(ctx context.Context) (int, error) { if err := _u.defaults(); err != nil { @@ -620,6 +694,63 @@ func (_u *TeamGroupUpdate) sqlSave(ctx context.Context) (_node int, err error) { edge.Target.Fields = specE.Fields _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if _u.mutation.HostsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: teamgroup.HostsTable, + Columns: teamgroup.HostsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + createE := &TeamGroupHostCreate{config: _u.config, mutation: newTeamGroupHostMutation(_u.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedHostsIDs(); len(nodes) > 0 && !_u.mutation.HostsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: teamgroup.HostsTable, + Columns: teamgroup.HostsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &TeamGroupHostCreate{config: _u.config, mutation: newTeamGroupHostMutation(_u.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.HostsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: teamgroup.HostsTable, + Columns: teamgroup.HostsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &TeamGroupHostCreate{config: _u.config, mutation: newTeamGroupHostMutation(_u.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if _u.mutation.TeamGroupMembersCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, @@ -755,6 +886,51 @@ func (_u *TeamGroupUpdate) sqlSave(ctx context.Context) (_node int, err error) { } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if _u.mutation.TeamGroupHostsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: teamgroup.TeamGroupHostsTable, + Columns: []string{teamgroup.TeamGroupHostsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(teamgrouphost.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedTeamGroupHostsIDs(); len(nodes) > 0 && !_u.mutation.TeamGroupHostsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: teamgroup.TeamGroupHostsTable, + Columns: []string{teamgroup.TeamGroupHostsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(teamgrouphost.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.TeamGroupHostsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: teamgroup.TeamGroupHostsTable, + Columns: []string{teamgroup.TeamGroupHostsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(teamgrouphost.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } _spec.AddModifiers(_u.modifiers...) if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { @@ -895,6 +1071,21 @@ func (_u *TeamGroupUpdateOne) AddImages(v ...*Image) *TeamGroupUpdateOne { return _u.AddImageIDs(ids...) } +// AddHostIDs adds the "hosts" edge to the Host entity by IDs. +func (_u *TeamGroupUpdateOne) AddHostIDs(ids ...string) *TeamGroupUpdateOne { + _u.mutation.AddHostIDs(ids...) + return _u +} + +// AddHosts adds the "hosts" edges to the Host entity. +func (_u *TeamGroupUpdateOne) AddHosts(v ...*Host) *TeamGroupUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddHostIDs(ids...) +} + // AddTeamGroupMemberIDs adds the "team_group_members" edge to the TeamGroupMember entity by IDs. func (_u *TeamGroupUpdateOne) AddTeamGroupMemberIDs(ids ...uuid.UUID) *TeamGroupUpdateOne { _u.mutation.AddTeamGroupMemberIDs(ids...) @@ -940,6 +1131,21 @@ func (_u *TeamGroupUpdateOne) AddTeamGroupImages(v ...*TeamGroupImage) *TeamGrou return _u.AddTeamGroupImageIDs(ids...) } +// AddTeamGroupHostIDs adds the "team_group_hosts" edge to the TeamGroupHost entity by IDs. +func (_u *TeamGroupUpdateOne) AddTeamGroupHostIDs(ids ...uuid.UUID) *TeamGroupUpdateOne { + _u.mutation.AddTeamGroupHostIDs(ids...) + return _u +} + +// AddTeamGroupHosts adds the "team_group_hosts" edges to the TeamGroupHost entity. +func (_u *TeamGroupUpdateOne) AddTeamGroupHosts(v ...*TeamGroupHost) *TeamGroupUpdateOne { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddTeamGroupHostIDs(ids...) +} + // Mutation returns the TeamGroupMutation object of the builder. func (_u *TeamGroupUpdateOne) Mutation() *TeamGroupMutation { return _u.mutation @@ -1014,6 +1220,27 @@ func (_u *TeamGroupUpdateOne) RemoveImages(v ...*Image) *TeamGroupUpdateOne { return _u.RemoveImageIDs(ids...) } +// ClearHosts clears all "hosts" edges to the Host entity. +func (_u *TeamGroupUpdateOne) ClearHosts() *TeamGroupUpdateOne { + _u.mutation.ClearHosts() + return _u +} + +// RemoveHostIDs removes the "hosts" edge to Host entities by IDs. +func (_u *TeamGroupUpdateOne) RemoveHostIDs(ids ...string) *TeamGroupUpdateOne { + _u.mutation.RemoveHostIDs(ids...) + return _u +} + +// RemoveHosts removes "hosts" edges to Host entities. +func (_u *TeamGroupUpdateOne) RemoveHosts(v ...*Host) *TeamGroupUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveHostIDs(ids...) +} + // ClearTeamGroupMembers clears all "team_group_members" edges to the TeamGroupMember entity. func (_u *TeamGroupUpdateOne) ClearTeamGroupMembers() *TeamGroupUpdateOne { _u.mutation.ClearTeamGroupMembers() @@ -1077,6 +1304,27 @@ func (_u *TeamGroupUpdateOne) RemoveTeamGroupImages(v ...*TeamGroupImage) *TeamG return _u.RemoveTeamGroupImageIDs(ids...) } +// ClearTeamGroupHosts clears all "team_group_hosts" edges to the TeamGroupHost entity. +func (_u *TeamGroupUpdateOne) ClearTeamGroupHosts() *TeamGroupUpdateOne { + _u.mutation.ClearTeamGroupHosts() + return _u +} + +// RemoveTeamGroupHostIDs removes the "team_group_hosts" edge to TeamGroupHost entities by IDs. +func (_u *TeamGroupUpdateOne) RemoveTeamGroupHostIDs(ids ...uuid.UUID) *TeamGroupUpdateOne { + _u.mutation.RemoveTeamGroupHostIDs(ids...) + return _u +} + +// RemoveTeamGroupHosts removes "team_group_hosts" edges to TeamGroupHost entities. +func (_u *TeamGroupUpdateOne) RemoveTeamGroupHosts(v ...*TeamGroupHost) *TeamGroupUpdateOne { + ids := make([]uuid.UUID, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveTeamGroupHostIDs(ids...) +} + // Where appends a list predicates to the TeamGroupUpdate builder. func (_u *TeamGroupUpdateOne) Where(ps ...predicate.TeamGroup) *TeamGroupUpdateOne { _u.mutation.Where(ps...) @@ -1390,6 +1638,63 @@ func (_u *TeamGroupUpdateOne) sqlSave(ctx context.Context) (_node *TeamGroup, er edge.Target.Fields = specE.Fields _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if _u.mutation.HostsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: teamgroup.HostsTable, + Columns: teamgroup.HostsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + createE := &TeamGroupHostCreate{config: _u.config, mutation: newTeamGroupHostMutation(_u.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedHostsIDs(); len(nodes) > 0 && !_u.mutation.HostsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: teamgroup.HostsTable, + Columns: teamgroup.HostsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &TeamGroupHostCreate{config: _u.config, mutation: newTeamGroupHostMutation(_u.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.HostsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: teamgroup.HostsTable, + Columns: teamgroup.HostsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &TeamGroupHostCreate{config: _u.config, mutation: newTeamGroupHostMutation(_u.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if _u.mutation.TeamGroupMembersCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, @@ -1525,6 +1830,51 @@ func (_u *TeamGroupUpdateOne) sqlSave(ctx context.Context) (_node *TeamGroup, er } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if _u.mutation.TeamGroupHostsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: teamgroup.TeamGroupHostsTable, + Columns: []string{teamgroup.TeamGroupHostsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(teamgrouphost.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedTeamGroupHostsIDs(); len(nodes) > 0 && !_u.mutation.TeamGroupHostsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: teamgroup.TeamGroupHostsTable, + Columns: []string{teamgroup.TeamGroupHostsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(teamgrouphost.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.TeamGroupHostsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: teamgroup.TeamGroupHostsTable, + Columns: []string{teamgroup.TeamGroupHostsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(teamgrouphost.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } _spec.AddModifiers(_u.modifiers...) _node = &TeamGroup{config: _u.config} _spec.Assign = _node.assignValues diff --git a/backend/db/teamgrouphost.go b/backend/db/teamgrouphost.go new file mode 100644 index 00000000..1e1eb747 --- /dev/null +++ b/backend/db/teamgrouphost.go @@ -0,0 +1,177 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/chaitin/MonkeyCode/backend/db/host" + "github.com/chaitin/MonkeyCode/backend/db/teamgroup" + "github.com/chaitin/MonkeyCode/backend/db/teamgrouphost" + "github.com/google/uuid" +) + +// TeamGroupHost is the model entity for the TeamGroupHost schema. +type TeamGroupHost struct { + config `json:"-"` + // ID of the ent. + ID uuid.UUID `json:"id,omitempty"` + // GroupID holds the value of the "group_id" field. + GroupID uuid.UUID `json:"group_id,omitempty"` + // HostID holds the value of the "host_id" field. + HostID string `json:"host_id,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the TeamGroupHostQuery when eager-loading is set. + Edges TeamGroupHostEdges `json:"edges"` + selectValues sql.SelectValues +} + +// TeamGroupHostEdges holds the relations/edges for other nodes in the graph. +type TeamGroupHostEdges struct { + // Group holds the value of the group edge. + Group *TeamGroup `json:"group,omitempty"` + // Host holds the value of the host edge. + Host *Host `json:"host,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// GroupOrErr returns the Group value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e TeamGroupHostEdges) GroupOrErr() (*TeamGroup, error) { + if e.Group != nil { + return e.Group, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: teamgroup.Label} + } + return nil, &NotLoadedError{edge: "group"} +} + +// HostOrErr returns the Host value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e TeamGroupHostEdges) HostOrErr() (*Host, error) { + if e.Host != nil { + return e.Host, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: host.Label} + } + return nil, &NotLoadedError{edge: "host"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*TeamGroupHost) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case teamgrouphost.FieldHostID: + values[i] = new(sql.NullString) + case teamgrouphost.FieldCreatedAt: + values[i] = new(sql.NullTime) + case teamgrouphost.FieldID, teamgrouphost.FieldGroupID: + values[i] = new(uuid.UUID) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the TeamGroupHost fields. +func (_m *TeamGroupHost) 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 teamgrouphost.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + _m.ID = *value + } + case teamgrouphost.FieldGroupID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field group_id", values[i]) + } else if value != nil { + _m.GroupID = *value + } + case teamgrouphost.FieldHostID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field host_id", values[i]) + } else if value.Valid { + _m.HostID = value.String + } + case teamgrouphost.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the TeamGroupHost. +// This includes values selected through modifiers, order, etc. +func (_m *TeamGroupHost) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryGroup queries the "group" edge of the TeamGroupHost entity. +func (_m *TeamGroupHost) QueryGroup() *TeamGroupQuery { + return NewTeamGroupHostClient(_m.config).QueryGroup(_m) +} + +// QueryHost queries the "host" edge of the TeamGroupHost entity. +func (_m *TeamGroupHost) QueryHost() *HostQuery { + return NewTeamGroupHostClient(_m.config).QueryHost(_m) +} + +// Update returns a builder for updating this TeamGroupHost. +// Note that you need to call TeamGroupHost.Unwrap() before calling this method if this TeamGroupHost +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *TeamGroupHost) Update() *TeamGroupHostUpdateOne { + return NewTeamGroupHostClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the TeamGroupHost entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *TeamGroupHost) Unwrap() *TeamGroupHost { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: TeamGroupHost is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *TeamGroupHost) String() string { + var builder strings.Builder + builder.WriteString("TeamGroupHost(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("group_id=") + builder.WriteString(fmt.Sprintf("%v", _m.GroupID)) + builder.WriteString(", ") + builder.WriteString("host_id=") + builder.WriteString(_m.HostID) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// TeamGroupHosts is a parsable slice of TeamGroupHost. +type TeamGroupHosts []*TeamGroupHost diff --git a/backend/db/teamgrouphost/teamgrouphost.go b/backend/db/teamgrouphost/teamgrouphost.go new file mode 100644 index 00000000..25e91ec8 --- /dev/null +++ b/backend/db/teamgrouphost/teamgrouphost.go @@ -0,0 +1,117 @@ +// Code generated by ent, DO NOT EDIT. + +package teamgrouphost + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the teamgrouphost type in the database. + Label = "team_group_host" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldGroupID holds the string denoting the group_id field in the database. + FieldGroupID = "group_id" + // FieldHostID holds the string denoting the host_id field in the database. + FieldHostID = "host_id" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // EdgeGroup holds the string denoting the group edge name in mutations. + EdgeGroup = "group" + // EdgeHost holds the string denoting the host edge name in mutations. + EdgeHost = "host" + // Table holds the table name of the teamgrouphost in the database. + Table = "team_group_hosts" + // GroupTable is the table that holds the group relation/edge. + GroupTable = "team_group_hosts" + // GroupInverseTable is the table name for the TeamGroup entity. + // It exists in this package in order to avoid circular dependency with the "teamgroup" package. + GroupInverseTable = "team_groups" + // GroupColumn is the table column denoting the group relation/edge. + GroupColumn = "group_id" + // HostTable is the table that holds the host relation/edge. + HostTable = "team_group_hosts" + // HostInverseTable is the table name for the Host entity. + // It exists in this package in order to avoid circular dependency with the "host" package. + HostInverseTable = "hosts" + // HostColumn is the table column denoting the host relation/edge. + HostColumn = "host_id" +) + +// Columns holds all SQL columns for teamgrouphost fields. +var Columns = []string{ + FieldID, + FieldGroupID, + FieldHostID, + FieldCreatedAt, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time +) + +// OrderOption defines the ordering options for the TeamGroupHost queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByGroupID orders the results by the group_id field. +func ByGroupID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldGroupID, opts...).ToFunc() +} + +// ByHostID orders the results by the host_id field. +func ByHostID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldHostID, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByGroupField orders the results by group field. +func ByGroupField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newGroupStep(), sql.OrderByField(field, opts...)) + } +} + +// ByHostField orders the results by host field. +func ByHostField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newHostStep(), sql.OrderByField(field, opts...)) + } +} +func newGroupStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(GroupInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, GroupTable, GroupColumn), + ) +} +func newHostStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(HostInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, HostTable, HostColumn), + ) +} diff --git a/backend/db/teamgrouphost/where.go b/backend/db/teamgrouphost/where.go new file mode 100644 index 00000000..fc78d224 --- /dev/null +++ b/backend/db/teamgrouphost/where.go @@ -0,0 +1,258 @@ +// Code generated by ent, DO NOT EDIT. + +package teamgrouphost + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// ID filters vertices based on their ID field. +func ID(id uuid.UUID) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldLTE(FieldID, id)) +} + +// GroupID applies equality check predicate on the "group_id" field. It's identical to GroupIDEQ. +func GroupID(v uuid.UUID) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldEQ(FieldGroupID, v)) +} + +// HostID applies equality check predicate on the "host_id" field. It's identical to HostIDEQ. +func HostID(v string) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldEQ(FieldHostID, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldEQ(FieldCreatedAt, v)) +} + +// GroupIDEQ applies the EQ predicate on the "group_id" field. +func GroupIDEQ(v uuid.UUID) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldEQ(FieldGroupID, v)) +} + +// GroupIDNEQ applies the NEQ predicate on the "group_id" field. +func GroupIDNEQ(v uuid.UUID) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldNEQ(FieldGroupID, v)) +} + +// GroupIDIn applies the In predicate on the "group_id" field. +func GroupIDIn(vs ...uuid.UUID) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldIn(FieldGroupID, vs...)) +} + +// GroupIDNotIn applies the NotIn predicate on the "group_id" field. +func GroupIDNotIn(vs ...uuid.UUID) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldNotIn(FieldGroupID, vs...)) +} + +// HostIDEQ applies the EQ predicate on the "host_id" field. +func HostIDEQ(v string) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldEQ(FieldHostID, v)) +} + +// HostIDNEQ applies the NEQ predicate on the "host_id" field. +func HostIDNEQ(v string) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldNEQ(FieldHostID, v)) +} + +// HostIDIn applies the In predicate on the "host_id" field. +func HostIDIn(vs ...string) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldIn(FieldHostID, vs...)) +} + +// HostIDNotIn applies the NotIn predicate on the "host_id" field. +func HostIDNotIn(vs ...string) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldNotIn(FieldHostID, vs...)) +} + +// HostIDGT applies the GT predicate on the "host_id" field. +func HostIDGT(v string) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldGT(FieldHostID, v)) +} + +// HostIDGTE applies the GTE predicate on the "host_id" field. +func HostIDGTE(v string) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldGTE(FieldHostID, v)) +} + +// HostIDLT applies the LT predicate on the "host_id" field. +func HostIDLT(v string) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldLT(FieldHostID, v)) +} + +// HostIDLTE applies the LTE predicate on the "host_id" field. +func HostIDLTE(v string) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldLTE(FieldHostID, v)) +} + +// HostIDContains applies the Contains predicate on the "host_id" field. +func HostIDContains(v string) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldContains(FieldHostID, v)) +} + +// HostIDHasPrefix applies the HasPrefix predicate on the "host_id" field. +func HostIDHasPrefix(v string) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldHasPrefix(FieldHostID, v)) +} + +// HostIDHasSuffix applies the HasSuffix predicate on the "host_id" field. +func HostIDHasSuffix(v string) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldHasSuffix(FieldHostID, v)) +} + +// HostIDEqualFold applies the EqualFold predicate on the "host_id" field. +func HostIDEqualFold(v string) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldEqualFold(FieldHostID, v)) +} + +// HostIDContainsFold applies the ContainsFold predicate on the "host_id" field. +func HostIDContainsFold(v string) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldContainsFold(FieldHostID, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.FieldLTE(FieldCreatedAt, v)) +} + +// HasGroup applies the HasEdge predicate on the "group" edge. +func HasGroup() predicate.TeamGroupHost { + return predicate.TeamGroupHost(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, 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.TeamGroup) predicate.TeamGroupHost { + return predicate.TeamGroupHost(func(s *sql.Selector) { + step := newGroupStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasHost applies the HasEdge predicate on the "host" edge. +func HasHost() predicate.TeamGroupHost { + return predicate.TeamGroupHost(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, HostTable, HostColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasHostWith applies the HasEdge predicate on the "host" edge with a given conditions (other predicates). +func HasHostWith(preds ...predicate.Host) predicate.TeamGroupHost { + return predicate.TeamGroupHost(func(s *sql.Selector) { + step := newHostStep() + 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.TeamGroupHost) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.TeamGroupHost) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.TeamGroupHost) predicate.TeamGroupHost { + return predicate.TeamGroupHost(sql.NotPredicates(p)) +} diff --git a/backend/db/teamgrouphost_create.go b/backend/db/teamgrouphost_create.go new file mode 100644 index 00000000..23d43a49 --- /dev/null +++ b/backend/db/teamgrouphost_create.go @@ -0,0 +1,659 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/host" + "github.com/chaitin/MonkeyCode/backend/db/teamgroup" + "github.com/chaitin/MonkeyCode/backend/db/teamgrouphost" + "github.com/google/uuid" +) + +// TeamGroupHostCreate is the builder for creating a TeamGroupHost entity. +type TeamGroupHostCreate struct { + config + mutation *TeamGroupHostMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetGroupID sets the "group_id" field. +func (_c *TeamGroupHostCreate) SetGroupID(v uuid.UUID) *TeamGroupHostCreate { + _c.mutation.SetGroupID(v) + return _c +} + +// SetHostID sets the "host_id" field. +func (_c *TeamGroupHostCreate) SetHostID(v string) *TeamGroupHostCreate { + _c.mutation.SetHostID(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *TeamGroupHostCreate) SetCreatedAt(v time.Time) *TeamGroupHostCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *TeamGroupHostCreate) SetNillableCreatedAt(v *time.Time) *TeamGroupHostCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *TeamGroupHostCreate) SetID(v uuid.UUID) *TeamGroupHostCreate { + _c.mutation.SetID(v) + return _c +} + +// SetGroup sets the "group" edge to the TeamGroup entity. +func (_c *TeamGroupHostCreate) SetGroup(v *TeamGroup) *TeamGroupHostCreate { + return _c.SetGroupID(v.ID) +} + +// SetHost sets the "host" edge to the Host entity. +func (_c *TeamGroupHostCreate) SetHost(v *Host) *TeamGroupHostCreate { + return _c.SetHostID(v.ID) +} + +// Mutation returns the TeamGroupHostMutation object of the builder. +func (_c *TeamGroupHostCreate) Mutation() *TeamGroupHostMutation { + return _c.mutation +} + +// Save creates the TeamGroupHost in the database. +func (_c *TeamGroupHostCreate) Save(ctx context.Context) (*TeamGroupHost, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *TeamGroupHostCreate) SaveX(ctx context.Context) *TeamGroupHost { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *TeamGroupHostCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *TeamGroupHostCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *TeamGroupHostCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := teamgrouphost.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *TeamGroupHostCreate) check() error { + if _, ok := _c.mutation.GroupID(); !ok { + return &ValidationError{Name: "group_id", err: errors.New(`db: missing required field "TeamGroupHost.group_id"`)} + } + if _, ok := _c.mutation.HostID(); !ok { + return &ValidationError{Name: "host_id", err: errors.New(`db: missing required field "TeamGroupHost.host_id"`)} + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "TeamGroupHost.created_at"`)} + } + if len(_c.mutation.GroupIDs()) == 0 { + return &ValidationError{Name: "group", err: errors.New(`db: missing required edge "TeamGroupHost.group"`)} + } + if len(_c.mutation.HostIDs()) == 0 { + return &ValidationError{Name: "host", err: errors.New(`db: missing required edge "TeamGroupHost.host"`)} + } + return nil +} + +func (_c *TeamGroupHostCreate) sqlSave(ctx context.Context) (*TeamGroupHost, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + 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 + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *TeamGroupHostCreate) createSpec() (*TeamGroupHost, *sqlgraph.CreateSpec) { + var ( + _node = &TeamGroupHost{config: _c.config} + _spec = sqlgraph.NewCreateSpec(teamgrouphost.Table, sqlgraph.NewFieldSpec(teamgrouphost.FieldID, field.TypeUUID)) + ) + _spec.OnConflict = _c.conflict + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(teamgrouphost.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if nodes := _c.mutation.GroupIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: teamgrouphost.GroupTable, + Columns: []string{teamgrouphost.GroupColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(teamgroup.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.GroupID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.HostIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: teamgrouphost.HostTable, + Columns: []string{teamgrouphost.HostColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.HostID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.TeamGroupHost.Create(). +// SetGroupID(v). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.TeamGroupHostUpsert) { +// SetGroupID(v+v). +// }). +// Exec(ctx) +func (_c *TeamGroupHostCreate) OnConflict(opts ...sql.ConflictOption) *TeamGroupHostUpsertOne { + _c.conflict = opts + return &TeamGroupHostUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.TeamGroupHost.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *TeamGroupHostCreate) OnConflictColumns(columns ...string) *TeamGroupHostUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &TeamGroupHostUpsertOne{ + create: _c, + } +} + +type ( + // TeamGroupHostUpsertOne is the builder for "upsert"-ing + // one TeamGroupHost node. + TeamGroupHostUpsertOne struct { + create *TeamGroupHostCreate + } + + // TeamGroupHostUpsert is the "OnConflict" setter. + TeamGroupHostUpsert struct { + *sql.UpdateSet + } +) + +// SetGroupID sets the "group_id" field. +func (u *TeamGroupHostUpsert) SetGroupID(v uuid.UUID) *TeamGroupHostUpsert { + u.Set(teamgrouphost.FieldGroupID, v) + return u +} + +// UpdateGroupID sets the "group_id" field to the value that was provided on create. +func (u *TeamGroupHostUpsert) UpdateGroupID() *TeamGroupHostUpsert { + u.SetExcluded(teamgrouphost.FieldGroupID) + return u +} + +// SetHostID sets the "host_id" field. +func (u *TeamGroupHostUpsert) SetHostID(v string) *TeamGroupHostUpsert { + u.Set(teamgrouphost.FieldHostID, v) + return u +} + +// UpdateHostID sets the "host_id" field to the value that was provided on create. +func (u *TeamGroupHostUpsert) UpdateHostID() *TeamGroupHostUpsert { + u.SetExcluded(teamgrouphost.FieldHostID) + return u +} + +// SetCreatedAt sets the "created_at" field. +func (u *TeamGroupHostUpsert) SetCreatedAt(v time.Time) *TeamGroupHostUpsert { + u.Set(teamgrouphost.FieldCreatedAt, v) + return u +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *TeamGroupHostUpsert) UpdateCreatedAt() *TeamGroupHostUpsert { + u.SetExcluded(teamgrouphost.FieldCreatedAt) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.TeamGroupHost.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(teamgrouphost.FieldID) +// }), +// ). +// Exec(ctx) +func (u *TeamGroupHostUpsertOne) UpdateNewValues() *TeamGroupHostUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + if _, exists := u.create.mutation.ID(); exists { + s.SetIgnore(teamgrouphost.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.TeamGroupHost.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *TeamGroupHostUpsertOne) Ignore() *TeamGroupHostUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *TeamGroupHostUpsertOne) DoNothing() *TeamGroupHostUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the TeamGroupHostCreate.OnConflict +// documentation for more info. +func (u *TeamGroupHostUpsertOne) Update(set func(*TeamGroupHostUpsert)) *TeamGroupHostUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&TeamGroupHostUpsert{UpdateSet: update}) + })) + return u +} + +// SetGroupID sets the "group_id" field. +func (u *TeamGroupHostUpsertOne) SetGroupID(v uuid.UUID) *TeamGroupHostUpsertOne { + return u.Update(func(s *TeamGroupHostUpsert) { + s.SetGroupID(v) + }) +} + +// UpdateGroupID sets the "group_id" field to the value that was provided on create. +func (u *TeamGroupHostUpsertOne) UpdateGroupID() *TeamGroupHostUpsertOne { + return u.Update(func(s *TeamGroupHostUpsert) { + s.UpdateGroupID() + }) +} + +// SetHostID sets the "host_id" field. +func (u *TeamGroupHostUpsertOne) SetHostID(v string) *TeamGroupHostUpsertOne { + return u.Update(func(s *TeamGroupHostUpsert) { + s.SetHostID(v) + }) +} + +// UpdateHostID sets the "host_id" field to the value that was provided on create. +func (u *TeamGroupHostUpsertOne) UpdateHostID() *TeamGroupHostUpsertOne { + return u.Update(func(s *TeamGroupHostUpsert) { + s.UpdateHostID() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *TeamGroupHostUpsertOne) SetCreatedAt(v time.Time) *TeamGroupHostUpsertOne { + return u.Update(func(s *TeamGroupHostUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *TeamGroupHostUpsertOne) UpdateCreatedAt() *TeamGroupHostUpsertOne { + return u.Update(func(s *TeamGroupHostUpsert) { + s.UpdateCreatedAt() + }) +} + +// Exec executes the query. +func (u *TeamGroupHostUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for TeamGroupHostCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *TeamGroupHostUpsertOne) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} + +// Exec executes the UPSERT query and returns the inserted/updated ID. +func (u *TeamGroupHostUpsertOne) ID(ctx context.Context) (id uuid.UUID, err error) { + if u.create.driver.Dialect() == dialect.MySQL { + // In case of "ON CONFLICT", there is no way to get back non-numeric ID + // fields from the database since MySQL does not support the RETURNING clause. + return id, errors.New("db: TeamGroupHostUpsertOne.ID is not supported by MySQL driver. Use TeamGroupHostUpsertOne.Exec instead") + } + node, err := u.create.Save(ctx) + if err != nil { + return id, err + } + return node.ID, nil +} + +// IDX is like ID, but panics if an error occurs. +func (u *TeamGroupHostUpsertOne) IDX(ctx context.Context) uuid.UUID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// TeamGroupHostCreateBulk is the builder for creating many TeamGroupHost entities in bulk. +type TeamGroupHostCreateBulk struct { + config + err error + builders []*TeamGroupHostCreate + conflict []sql.ConflictOption +} + +// Save creates the TeamGroupHost entities in the database. +func (_c *TeamGroupHostCreateBulk) Save(ctx context.Context) ([]*TeamGroupHost, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*TeamGroupHost, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*TeamGroupHostMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.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, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *TeamGroupHostCreateBulk) SaveX(ctx context.Context) []*TeamGroupHost { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *TeamGroupHostCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *TeamGroupHostCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.TeamGroupHost.CreateBulk(builders...). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.TeamGroupHostUpsert) { +// SetGroupID(v+v). +// }). +// Exec(ctx) +func (_c *TeamGroupHostCreateBulk) OnConflict(opts ...sql.ConflictOption) *TeamGroupHostUpsertBulk { + _c.conflict = opts + return &TeamGroupHostUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.TeamGroupHost.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *TeamGroupHostCreateBulk) OnConflictColumns(columns ...string) *TeamGroupHostUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &TeamGroupHostUpsertBulk{ + create: _c, + } +} + +// TeamGroupHostUpsertBulk is the builder for "upsert"-ing +// a bulk of TeamGroupHost nodes. +type TeamGroupHostUpsertBulk struct { + create *TeamGroupHostCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.TeamGroupHost.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(teamgrouphost.FieldID) +// }), +// ). +// Exec(ctx) +func (u *TeamGroupHostUpsertBulk) UpdateNewValues() *TeamGroupHostUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + for _, b := range u.create.builders { + if _, exists := b.mutation.ID(); exists { + s.SetIgnore(teamgrouphost.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.TeamGroupHost.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *TeamGroupHostUpsertBulk) Ignore() *TeamGroupHostUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *TeamGroupHostUpsertBulk) DoNothing() *TeamGroupHostUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the TeamGroupHostCreateBulk.OnConflict +// documentation for more info. +func (u *TeamGroupHostUpsertBulk) Update(set func(*TeamGroupHostUpsert)) *TeamGroupHostUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&TeamGroupHostUpsert{UpdateSet: update}) + })) + return u +} + +// SetGroupID sets the "group_id" field. +func (u *TeamGroupHostUpsertBulk) SetGroupID(v uuid.UUID) *TeamGroupHostUpsertBulk { + return u.Update(func(s *TeamGroupHostUpsert) { + s.SetGroupID(v) + }) +} + +// UpdateGroupID sets the "group_id" field to the value that was provided on create. +func (u *TeamGroupHostUpsertBulk) UpdateGroupID() *TeamGroupHostUpsertBulk { + return u.Update(func(s *TeamGroupHostUpsert) { + s.UpdateGroupID() + }) +} + +// SetHostID sets the "host_id" field. +func (u *TeamGroupHostUpsertBulk) SetHostID(v string) *TeamGroupHostUpsertBulk { + return u.Update(func(s *TeamGroupHostUpsert) { + s.SetHostID(v) + }) +} + +// UpdateHostID sets the "host_id" field to the value that was provided on create. +func (u *TeamGroupHostUpsertBulk) UpdateHostID() *TeamGroupHostUpsertBulk { + return u.Update(func(s *TeamGroupHostUpsert) { + s.UpdateHostID() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *TeamGroupHostUpsertBulk) SetCreatedAt(v time.Time) *TeamGroupHostUpsertBulk { + return u.Update(func(s *TeamGroupHostUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *TeamGroupHostUpsertBulk) UpdateCreatedAt() *TeamGroupHostUpsertBulk { + return u.Update(func(s *TeamGroupHostUpsert) { + s.UpdateCreatedAt() + }) +} + +// Exec executes the query. +func (u *TeamGroupHostUpsertBulk) Exec(ctx context.Context) error { + if u.create.err != nil { + return u.create.err + } + for i, b := range u.create.builders { + if len(b.conflict) != 0 { + return fmt.Errorf("db: OnConflict was set for builder %d. Set it on the TeamGroupHostCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for TeamGroupHostCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *TeamGroupHostUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/teamgrouphost_delete.go b/backend/db/teamgrouphost_delete.go new file mode 100644 index 00000000..80ee2bf3 --- /dev/null +++ b/backend/db/teamgrouphost_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/teamgrouphost" +) + +// TeamGroupHostDelete is the builder for deleting a TeamGroupHost entity. +type TeamGroupHostDelete struct { + config + hooks []Hook + mutation *TeamGroupHostMutation +} + +// Where appends a list predicates to the TeamGroupHostDelete builder. +func (_d *TeamGroupHostDelete) Where(ps ...predicate.TeamGroupHost) *TeamGroupHostDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *TeamGroupHostDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *TeamGroupHostDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *TeamGroupHostDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(teamgrouphost.Table, sqlgraph.NewFieldSpec(teamgrouphost.FieldID, field.TypeUUID)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// TeamGroupHostDeleteOne is the builder for deleting a single TeamGroupHost entity. +type TeamGroupHostDeleteOne struct { + _d *TeamGroupHostDelete +} + +// Where appends a list predicates to the TeamGroupHostDelete builder. +func (_d *TeamGroupHostDeleteOne) Where(ps ...predicate.TeamGroupHost) *TeamGroupHostDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *TeamGroupHostDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{teamgrouphost.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *TeamGroupHostDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/teamgrouphost_query.go b/backend/db/teamgrouphost_query.go new file mode 100644 index 00000000..134ecbd7 --- /dev/null +++ b/backend/db/teamgrouphost_query.go @@ -0,0 +1,732 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/host" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/teamgroup" + "github.com/chaitin/MonkeyCode/backend/db/teamgrouphost" + "github.com/google/uuid" +) + +// TeamGroupHostQuery is the builder for querying TeamGroupHost entities. +type TeamGroupHostQuery struct { + config + ctx *QueryContext + order []teamgrouphost.OrderOption + inters []Interceptor + predicates []predicate.TeamGroupHost + withGroup *TeamGroupQuery + withHost *HostQuery + modifiers []func(*sql.Selector) + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the TeamGroupHostQuery builder. +func (_q *TeamGroupHostQuery) Where(ps ...predicate.TeamGroupHost) *TeamGroupHostQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *TeamGroupHostQuery) Limit(limit int) *TeamGroupHostQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *TeamGroupHostQuery) Offset(offset int) *TeamGroupHostQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *TeamGroupHostQuery) Unique(unique bool) *TeamGroupHostQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *TeamGroupHostQuery) Order(o ...teamgrouphost.OrderOption) *TeamGroupHostQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryGroup chains the current query on the "group" edge. +func (_q *TeamGroupHostQuery) QueryGroup() *TeamGroupQuery { + query := (&TeamGroupClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(teamgrouphost.Table, teamgrouphost.FieldID, selector), + sqlgraph.To(teamgroup.Table, teamgroup.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, teamgrouphost.GroupTable, teamgrouphost.GroupColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryHost chains the current query on the "host" edge. +func (_q *TeamGroupHostQuery) QueryHost() *HostQuery { + query := (&HostClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(teamgrouphost.Table, teamgrouphost.FieldID, selector), + sqlgraph.To(host.Table, host.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, teamgrouphost.HostTable, teamgrouphost.HostColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first TeamGroupHost entity from the query. +// Returns a *NotFoundError when no TeamGroupHost was found. +func (_q *TeamGroupHostQuery) First(ctx context.Context) (*TeamGroupHost, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{teamgrouphost.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *TeamGroupHostQuery) FirstX(ctx context.Context) *TeamGroupHost { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first TeamGroupHost ID from the query. +// Returns a *NotFoundError when no TeamGroupHost ID was found. +func (_q *TeamGroupHostQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{teamgrouphost.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *TeamGroupHostQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single TeamGroupHost entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one TeamGroupHost entity is found. +// Returns a *NotFoundError when no TeamGroupHost entities are found. +func (_q *TeamGroupHostQuery) Only(ctx context.Context) (*TeamGroupHost, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{teamgrouphost.Label} + default: + return nil, &NotSingularError{teamgrouphost.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *TeamGroupHostQuery) OnlyX(ctx context.Context) *TeamGroupHost { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only TeamGroupHost ID in the query. +// Returns a *NotSingularError when more than one TeamGroupHost ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *TeamGroupHostQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{teamgrouphost.Label} + default: + err = &NotSingularError{teamgrouphost.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *TeamGroupHostQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of TeamGroupHosts. +func (_q *TeamGroupHostQuery) All(ctx context.Context) ([]*TeamGroupHost, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*TeamGroupHost, *TeamGroupHostQuery]() + return withInterceptors[[]*TeamGroupHost](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *TeamGroupHostQuery) AllX(ctx context.Context) []*TeamGroupHost { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of TeamGroupHost IDs. +func (_q *TeamGroupHostQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(teamgrouphost.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *TeamGroupHostQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *TeamGroupHostQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*TeamGroupHostQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *TeamGroupHostQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *TeamGroupHostQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("db: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *TeamGroupHostQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the TeamGroupHostQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *TeamGroupHostQuery) Clone() *TeamGroupHostQuery { + if _q == nil { + return nil + } + return &TeamGroupHostQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]teamgrouphost.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.TeamGroupHost{}, _q.predicates...), + withGroup: _q.withGroup.Clone(), + withHost: _q.withHost.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + modifiers: append([]func(*sql.Selector){}, _q.modifiers...), + } +} + +// 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 (_q *TeamGroupHostQuery) WithGroup(opts ...func(*TeamGroupQuery)) *TeamGroupHostQuery { + query := (&TeamGroupClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withGroup = query + return _q +} + +// WithHost tells the query-builder to eager-load the nodes that are connected to +// the "host" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *TeamGroupHostQuery) WithHost(opts ...func(*HostQuery)) *TeamGroupHostQuery { + query := (&HostClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withHost = query + return _q +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// GroupID uuid.UUID `json:"group_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.TeamGroupHost.Query(). +// GroupBy(teamgrouphost.FieldGroupID). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *TeamGroupHostQuery) GroupBy(field string, fields ...string) *TeamGroupHostGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &TeamGroupHostGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = teamgrouphost.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// GroupID uuid.UUID `json:"group_id,omitempty"` +// } +// +// client.TeamGroupHost.Query(). +// Select(teamgrouphost.FieldGroupID). +// Scan(ctx, &v) +func (_q *TeamGroupHostQuery) Select(fields ...string) *TeamGroupHostSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &TeamGroupHostSelect{TeamGroupHostQuery: _q} + sbuild.label = teamgrouphost.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a TeamGroupHostSelect configured with the given aggregations. +func (_q *TeamGroupHostQuery) Aggregate(fns ...AggregateFunc) *TeamGroupHostSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *TeamGroupHostQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !teamgrouphost.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *TeamGroupHostQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*TeamGroupHost, error) { + var ( + nodes = []*TeamGroupHost{} + _spec = _q.querySpec() + loadedTypes = [2]bool{ + _q.withGroup != nil, + _q.withHost != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*TeamGroupHost).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &TeamGroupHost{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withGroup; query != nil { + if err := _q.loadGroup(ctx, query, nodes, nil, + func(n *TeamGroupHost, e *TeamGroup) { n.Edges.Group = e }); err != nil { + return nil, err + } + } + if query := _q.withHost; query != nil { + if err := _q.loadHost(ctx, query, nodes, nil, + func(n *TeamGroupHost, e *Host) { n.Edges.Host = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *TeamGroupHostQuery) loadGroup(ctx context.Context, query *TeamGroupQuery, nodes []*TeamGroupHost, init func(*TeamGroupHost), assign func(*TeamGroupHost, *TeamGroup)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*TeamGroupHost) + for i := range nodes { + fk := nodes[i].GroupID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(teamgroup.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_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *TeamGroupHostQuery) loadHost(ctx context.Context, query *HostQuery, nodes []*TeamGroupHost, init func(*TeamGroupHost), assign func(*TeamGroupHost, *Host)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*TeamGroupHost) + for i := range nodes { + fk := nodes[i].HostID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(host.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 "host_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *TeamGroupHostQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *TeamGroupHostQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(teamgrouphost.Table, teamgrouphost.Columns, sqlgraph.NewFieldSpec(teamgrouphost.FieldID, field.TypeUUID)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, teamgrouphost.FieldID) + for i := range fields { + if fields[i] != teamgrouphost.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withGroup != nil { + _spec.Node.AddColumnOnce(teamgrouphost.FieldGroupID) + } + if _q.withHost != nil { + _spec.Node.AddColumnOnce(teamgrouphost.FieldHostID) + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *TeamGroupHostQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(teamgrouphost.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = teamgrouphost.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, m := range _q.modifiers { + m(selector) + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// ForUpdate locks the selected rows against concurrent updates, and prevent them from being +// updated, deleted or "selected ... for update" by other sessions, until the transaction is +// either committed or rolled-back. +func (_q *TeamGroupHostQuery) ForUpdate(opts ...sql.LockOption) *TeamGroupHostQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return _q +} + +// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock +// on any rows that are read. Other sessions can read the rows, but cannot modify them +// until your transaction commits. +func (_q *TeamGroupHostQuery) ForShare(opts ...sql.LockOption) *TeamGroupHostQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (_q *TeamGroupHostQuery) Modify(modifiers ...func(s *sql.Selector)) *TeamGroupHostSelect { + _q.modifiers = append(_q.modifiers, modifiers...) + return _q.Select() +} + +// TeamGroupHostGroupBy is the group-by builder for TeamGroupHost entities. +type TeamGroupHostGroupBy struct { + selector + build *TeamGroupHostQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *TeamGroupHostGroupBy) Aggregate(fns ...AggregateFunc) *TeamGroupHostGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *TeamGroupHostGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*TeamGroupHostQuery, *TeamGroupHostGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *TeamGroupHostGroupBy) sqlScan(ctx context.Context, root *TeamGroupHostQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// TeamGroupHostSelect is the builder for selecting fields of TeamGroupHost entities. +type TeamGroupHostSelect struct { + *TeamGroupHostQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *TeamGroupHostSelect) Aggregate(fns ...AggregateFunc) *TeamGroupHostSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *TeamGroupHostSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*TeamGroupHostQuery, *TeamGroupHostSelect](ctx, _s.TeamGroupHostQuery, _s, _s.inters, v) +} + +func (_s *TeamGroupHostSelect) sqlScan(ctx context.Context, root *TeamGroupHostQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (_s *TeamGroupHostSelect) Modify(modifiers ...func(s *sql.Selector)) *TeamGroupHostSelect { + _s.modifiers = append(_s.modifiers, modifiers...) + return _s +} diff --git a/backend/db/teamgrouphost_update.go b/backend/db/teamgrouphost_update.go new file mode 100644 index 00000000..e6cf3075 --- /dev/null +++ b/backend/db/teamgrouphost_update.go @@ -0,0 +1,473 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/host" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/teamgroup" + "github.com/chaitin/MonkeyCode/backend/db/teamgrouphost" + "github.com/google/uuid" +) + +// TeamGroupHostUpdate is the builder for updating TeamGroupHost entities. +type TeamGroupHostUpdate struct { + config + hooks []Hook + mutation *TeamGroupHostMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the TeamGroupHostUpdate builder. +func (_u *TeamGroupHostUpdate) Where(ps ...predicate.TeamGroupHost) *TeamGroupHostUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetGroupID sets the "group_id" field. +func (_u *TeamGroupHostUpdate) SetGroupID(v uuid.UUID) *TeamGroupHostUpdate { + _u.mutation.SetGroupID(v) + return _u +} + +// SetNillableGroupID sets the "group_id" field if the given value is not nil. +func (_u *TeamGroupHostUpdate) SetNillableGroupID(v *uuid.UUID) *TeamGroupHostUpdate { + if v != nil { + _u.SetGroupID(*v) + } + return _u +} + +// SetHostID sets the "host_id" field. +func (_u *TeamGroupHostUpdate) SetHostID(v string) *TeamGroupHostUpdate { + _u.mutation.SetHostID(v) + return _u +} + +// SetNillableHostID sets the "host_id" field if the given value is not nil. +func (_u *TeamGroupHostUpdate) SetNillableHostID(v *string) *TeamGroupHostUpdate { + if v != nil { + _u.SetHostID(*v) + } + return _u +} + +// SetCreatedAt sets the "created_at" field. +func (_u *TeamGroupHostUpdate) SetCreatedAt(v time.Time) *TeamGroupHostUpdate { + _u.mutation.SetCreatedAt(v) + return _u +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_u *TeamGroupHostUpdate) SetNillableCreatedAt(v *time.Time) *TeamGroupHostUpdate { + if v != nil { + _u.SetCreatedAt(*v) + } + return _u +} + +// SetGroup sets the "group" edge to the TeamGroup entity. +func (_u *TeamGroupHostUpdate) SetGroup(v *TeamGroup) *TeamGroupHostUpdate { + return _u.SetGroupID(v.ID) +} + +// SetHost sets the "host" edge to the Host entity. +func (_u *TeamGroupHostUpdate) SetHost(v *Host) *TeamGroupHostUpdate { + return _u.SetHostID(v.ID) +} + +// Mutation returns the TeamGroupHostMutation object of the builder. +func (_u *TeamGroupHostUpdate) Mutation() *TeamGroupHostMutation { + return _u.mutation +} + +// ClearGroup clears the "group" edge to the TeamGroup entity. +func (_u *TeamGroupHostUpdate) ClearGroup() *TeamGroupHostUpdate { + _u.mutation.ClearGroup() + return _u +} + +// ClearHost clears the "host" edge to the Host entity. +func (_u *TeamGroupHostUpdate) ClearHost() *TeamGroupHostUpdate { + _u.mutation.ClearHost() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *TeamGroupHostUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *TeamGroupHostUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *TeamGroupHostUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *TeamGroupHostUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *TeamGroupHostUpdate) check() error { + if _u.mutation.GroupCleared() && len(_u.mutation.GroupIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "TeamGroupHost.group"`) + } + if _u.mutation.HostCleared() && len(_u.mutation.HostIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "TeamGroupHost.host"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *TeamGroupHostUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *TeamGroupHostUpdate { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *TeamGroupHostUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(teamgrouphost.Table, teamgrouphost.Columns, sqlgraph.NewFieldSpec(teamgrouphost.FieldID, field.TypeUUID)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.CreatedAt(); ok { + _spec.SetField(teamgrouphost.FieldCreatedAt, field.TypeTime, value) + } + if _u.mutation.GroupCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: teamgrouphost.GroupTable, + Columns: []string{teamgrouphost.GroupColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(teamgroup.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.GroupIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: teamgrouphost.GroupTable, + Columns: []string{teamgrouphost.GroupColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(teamgroup.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.HostCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: teamgrouphost.HostTable, + Columns: []string{teamgrouphost.HostColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.HostIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: teamgrouphost.HostTable, + Columns: []string{teamgrouphost.HostColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(_u.modifiers...) + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{teamgrouphost.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// TeamGroupHostUpdateOne is the builder for updating a single TeamGroupHost entity. +type TeamGroupHostUpdateOne struct { + config + fields []string + hooks []Hook + mutation *TeamGroupHostMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetGroupID sets the "group_id" field. +func (_u *TeamGroupHostUpdateOne) SetGroupID(v uuid.UUID) *TeamGroupHostUpdateOne { + _u.mutation.SetGroupID(v) + return _u +} + +// SetNillableGroupID sets the "group_id" field if the given value is not nil. +func (_u *TeamGroupHostUpdateOne) SetNillableGroupID(v *uuid.UUID) *TeamGroupHostUpdateOne { + if v != nil { + _u.SetGroupID(*v) + } + return _u +} + +// SetHostID sets the "host_id" field. +func (_u *TeamGroupHostUpdateOne) SetHostID(v string) *TeamGroupHostUpdateOne { + _u.mutation.SetHostID(v) + return _u +} + +// SetNillableHostID sets the "host_id" field if the given value is not nil. +func (_u *TeamGroupHostUpdateOne) SetNillableHostID(v *string) *TeamGroupHostUpdateOne { + if v != nil { + _u.SetHostID(*v) + } + return _u +} + +// SetCreatedAt sets the "created_at" field. +func (_u *TeamGroupHostUpdateOne) SetCreatedAt(v time.Time) *TeamGroupHostUpdateOne { + _u.mutation.SetCreatedAt(v) + return _u +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_u *TeamGroupHostUpdateOne) SetNillableCreatedAt(v *time.Time) *TeamGroupHostUpdateOne { + if v != nil { + _u.SetCreatedAt(*v) + } + return _u +} + +// SetGroup sets the "group" edge to the TeamGroup entity. +func (_u *TeamGroupHostUpdateOne) SetGroup(v *TeamGroup) *TeamGroupHostUpdateOne { + return _u.SetGroupID(v.ID) +} + +// SetHost sets the "host" edge to the Host entity. +func (_u *TeamGroupHostUpdateOne) SetHost(v *Host) *TeamGroupHostUpdateOne { + return _u.SetHostID(v.ID) +} + +// Mutation returns the TeamGroupHostMutation object of the builder. +func (_u *TeamGroupHostUpdateOne) Mutation() *TeamGroupHostMutation { + return _u.mutation +} + +// ClearGroup clears the "group" edge to the TeamGroup entity. +func (_u *TeamGroupHostUpdateOne) ClearGroup() *TeamGroupHostUpdateOne { + _u.mutation.ClearGroup() + return _u +} + +// ClearHost clears the "host" edge to the Host entity. +func (_u *TeamGroupHostUpdateOne) ClearHost() *TeamGroupHostUpdateOne { + _u.mutation.ClearHost() + return _u +} + +// Where appends a list predicates to the TeamGroupHostUpdate builder. +func (_u *TeamGroupHostUpdateOne) Where(ps ...predicate.TeamGroupHost) *TeamGroupHostUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *TeamGroupHostUpdateOne) Select(field string, fields ...string) *TeamGroupHostUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated TeamGroupHost entity. +func (_u *TeamGroupHostUpdateOne) Save(ctx context.Context) (*TeamGroupHost, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *TeamGroupHostUpdateOne) SaveX(ctx context.Context) *TeamGroupHost { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *TeamGroupHostUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *TeamGroupHostUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *TeamGroupHostUpdateOne) check() error { + if _u.mutation.GroupCleared() && len(_u.mutation.GroupIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "TeamGroupHost.group"`) + } + if _u.mutation.HostCleared() && len(_u.mutation.HostIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "TeamGroupHost.host"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *TeamGroupHostUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *TeamGroupHostUpdateOne { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *TeamGroupHostUpdateOne) sqlSave(ctx context.Context) (_node *TeamGroupHost, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(teamgrouphost.Table, teamgrouphost.Columns, sqlgraph.NewFieldSpec(teamgrouphost.FieldID, field.TypeUUID)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "TeamGroupHost.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, teamgrouphost.FieldID) + for _, f := range fields { + if !teamgrouphost.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != teamgrouphost.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.CreatedAt(); ok { + _spec.SetField(teamgrouphost.FieldCreatedAt, field.TypeTime, value) + } + if _u.mutation.GroupCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: teamgrouphost.GroupTable, + Columns: []string{teamgrouphost.GroupColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(teamgroup.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.GroupIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: teamgrouphost.GroupTable, + Columns: []string{teamgrouphost.GroupColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(teamgroup.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.HostCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: teamgrouphost.HostTable, + Columns: []string{teamgrouphost.HostColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.HostIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: teamgrouphost.HostTable, + Columns: []string{teamgrouphost.HostColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(_u.modifiers...) + _node = &TeamGroupHost{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{teamgrouphost.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/backend/db/teamhost.go b/backend/db/teamhost.go new file mode 100644 index 00000000..fffed991 --- /dev/null +++ b/backend/db/teamhost.go @@ -0,0 +1,177 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/chaitin/MonkeyCode/backend/db/host" + "github.com/chaitin/MonkeyCode/backend/db/team" + "github.com/chaitin/MonkeyCode/backend/db/teamhost" + "github.com/google/uuid" +) + +// TeamHost is the model entity for the TeamHost schema. +type TeamHost struct { + config `json:"-"` + // ID of the ent. + ID uuid.UUID `json:"id,omitempty"` + // TeamID holds the value of the "team_id" field. + TeamID uuid.UUID `json:"team_id,omitempty"` + // HostID holds the value of the "host_id" field. + HostID string `json:"host_id,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the TeamHostQuery when eager-loading is set. + Edges TeamHostEdges `json:"edges"` + selectValues sql.SelectValues +} + +// TeamHostEdges holds the relations/edges for other nodes in the graph. +type TeamHostEdges struct { + // Team holds the value of the team edge. + Team *Team `json:"team,omitempty"` + // Host holds the value of the host edge. + Host *Host `json:"host,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// TeamOrErr returns the Team value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e TeamHostEdges) TeamOrErr() (*Team, error) { + if e.Team != nil { + return e.Team, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: team.Label} + } + return nil, &NotLoadedError{edge: "team"} +} + +// HostOrErr returns the Host value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e TeamHostEdges) HostOrErr() (*Host, error) { + if e.Host != nil { + return e.Host, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: host.Label} + } + return nil, &NotLoadedError{edge: "host"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*TeamHost) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case teamhost.FieldHostID: + values[i] = new(sql.NullString) + case teamhost.FieldCreatedAt: + values[i] = new(sql.NullTime) + case teamhost.FieldID, teamhost.FieldTeamID: + values[i] = new(uuid.UUID) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the TeamHost fields. +func (_m *TeamHost) 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 teamhost.FieldID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value != nil { + _m.ID = *value + } + case teamhost.FieldTeamID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field team_id", values[i]) + } else if value != nil { + _m.TeamID = *value + } + case teamhost.FieldHostID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field host_id", values[i]) + } else if value.Valid { + _m.HostID = value.String + } + case teamhost.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the TeamHost. +// This includes values selected through modifiers, order, etc. +func (_m *TeamHost) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryTeam queries the "team" edge of the TeamHost entity. +func (_m *TeamHost) QueryTeam() *TeamQuery { + return NewTeamHostClient(_m.config).QueryTeam(_m) +} + +// QueryHost queries the "host" edge of the TeamHost entity. +func (_m *TeamHost) QueryHost() *HostQuery { + return NewTeamHostClient(_m.config).QueryHost(_m) +} + +// Update returns a builder for updating this TeamHost. +// Note that you need to call TeamHost.Unwrap() before calling this method if this TeamHost +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *TeamHost) Update() *TeamHostUpdateOne { + return NewTeamHostClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the TeamHost entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *TeamHost) Unwrap() *TeamHost { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: TeamHost is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *TeamHost) String() string { + var builder strings.Builder + builder.WriteString("TeamHost(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("team_id=") + builder.WriteString(fmt.Sprintf("%v", _m.TeamID)) + builder.WriteString(", ") + builder.WriteString("host_id=") + builder.WriteString(_m.HostID) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// TeamHosts is a parsable slice of TeamHost. +type TeamHosts []*TeamHost diff --git a/backend/db/teamhost/teamhost.go b/backend/db/teamhost/teamhost.go new file mode 100644 index 00000000..b3902d4f --- /dev/null +++ b/backend/db/teamhost/teamhost.go @@ -0,0 +1,117 @@ +// Code generated by ent, DO NOT EDIT. + +package teamhost + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the teamhost type in the database. + Label = "team_host" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldTeamID holds the string denoting the team_id field in the database. + FieldTeamID = "team_id" + // FieldHostID holds the string denoting the host_id field in the database. + FieldHostID = "host_id" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // EdgeTeam holds the string denoting the team edge name in mutations. + EdgeTeam = "team" + // EdgeHost holds the string denoting the host edge name in mutations. + EdgeHost = "host" + // Table holds the table name of the teamhost in the database. + Table = "team_hosts" + // TeamTable is the table that holds the team relation/edge. + TeamTable = "team_hosts" + // TeamInverseTable is the table name for the Team entity. + // It exists in this package in order to avoid circular dependency with the "team" package. + TeamInverseTable = "teams" + // TeamColumn is the table column denoting the team relation/edge. + TeamColumn = "team_id" + // HostTable is the table that holds the host relation/edge. + HostTable = "team_hosts" + // HostInverseTable is the table name for the Host entity. + // It exists in this package in order to avoid circular dependency with the "host" package. + HostInverseTable = "hosts" + // HostColumn is the table column denoting the host relation/edge. + HostColumn = "host_id" +) + +// Columns holds all SQL columns for teamhost fields. +var Columns = []string{ + FieldID, + FieldTeamID, + FieldHostID, + FieldCreatedAt, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time +) + +// OrderOption defines the ordering options for the TeamHost queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByTeamID orders the results by the team_id field. +func ByTeamID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTeamID, opts...).ToFunc() +} + +// ByHostID orders the results by the host_id field. +func ByHostID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldHostID, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByTeamField orders the results by team field. +func ByTeamField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newTeamStep(), sql.OrderByField(field, opts...)) + } +} + +// ByHostField orders the results by host field. +func ByHostField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newHostStep(), sql.OrderByField(field, opts...)) + } +} +func newTeamStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TeamInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, TeamTable, TeamColumn), + ) +} +func newHostStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(HostInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, HostTable, HostColumn), + ) +} diff --git a/backend/db/teamhost/where.go b/backend/db/teamhost/where.go new file mode 100644 index 00000000..75b178cb --- /dev/null +++ b/backend/db/teamhost/where.go @@ -0,0 +1,258 @@ +// Code generated by ent, DO NOT EDIT. + +package teamhost + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// ID filters vertices based on their ID field. +func ID(id uuid.UUID) predicate.TeamHost { + return predicate.TeamHost(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id uuid.UUID) predicate.TeamHost { + return predicate.TeamHost(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id uuid.UUID) predicate.TeamHost { + return predicate.TeamHost(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...uuid.UUID) predicate.TeamHost { + return predicate.TeamHost(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...uuid.UUID) predicate.TeamHost { + return predicate.TeamHost(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id uuid.UUID) predicate.TeamHost { + return predicate.TeamHost(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id uuid.UUID) predicate.TeamHost { + return predicate.TeamHost(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id uuid.UUID) predicate.TeamHost { + return predicate.TeamHost(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id uuid.UUID) predicate.TeamHost { + return predicate.TeamHost(sql.FieldLTE(FieldID, id)) +} + +// TeamID applies equality check predicate on the "team_id" field. It's identical to TeamIDEQ. +func TeamID(v uuid.UUID) predicate.TeamHost { + return predicate.TeamHost(sql.FieldEQ(FieldTeamID, v)) +} + +// HostID applies equality check predicate on the "host_id" field. It's identical to HostIDEQ. +func HostID(v string) predicate.TeamHost { + return predicate.TeamHost(sql.FieldEQ(FieldHostID, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.TeamHost { + return predicate.TeamHost(sql.FieldEQ(FieldCreatedAt, v)) +} + +// TeamIDEQ applies the EQ predicate on the "team_id" field. +func TeamIDEQ(v uuid.UUID) predicate.TeamHost { + return predicate.TeamHost(sql.FieldEQ(FieldTeamID, v)) +} + +// TeamIDNEQ applies the NEQ predicate on the "team_id" field. +func TeamIDNEQ(v uuid.UUID) predicate.TeamHost { + return predicate.TeamHost(sql.FieldNEQ(FieldTeamID, v)) +} + +// TeamIDIn applies the In predicate on the "team_id" field. +func TeamIDIn(vs ...uuid.UUID) predicate.TeamHost { + return predicate.TeamHost(sql.FieldIn(FieldTeamID, vs...)) +} + +// TeamIDNotIn applies the NotIn predicate on the "team_id" field. +func TeamIDNotIn(vs ...uuid.UUID) predicate.TeamHost { + return predicate.TeamHost(sql.FieldNotIn(FieldTeamID, vs...)) +} + +// HostIDEQ applies the EQ predicate on the "host_id" field. +func HostIDEQ(v string) predicate.TeamHost { + return predicate.TeamHost(sql.FieldEQ(FieldHostID, v)) +} + +// HostIDNEQ applies the NEQ predicate on the "host_id" field. +func HostIDNEQ(v string) predicate.TeamHost { + return predicate.TeamHost(sql.FieldNEQ(FieldHostID, v)) +} + +// HostIDIn applies the In predicate on the "host_id" field. +func HostIDIn(vs ...string) predicate.TeamHost { + return predicate.TeamHost(sql.FieldIn(FieldHostID, vs...)) +} + +// HostIDNotIn applies the NotIn predicate on the "host_id" field. +func HostIDNotIn(vs ...string) predicate.TeamHost { + return predicate.TeamHost(sql.FieldNotIn(FieldHostID, vs...)) +} + +// HostIDGT applies the GT predicate on the "host_id" field. +func HostIDGT(v string) predicate.TeamHost { + return predicate.TeamHost(sql.FieldGT(FieldHostID, v)) +} + +// HostIDGTE applies the GTE predicate on the "host_id" field. +func HostIDGTE(v string) predicate.TeamHost { + return predicate.TeamHost(sql.FieldGTE(FieldHostID, v)) +} + +// HostIDLT applies the LT predicate on the "host_id" field. +func HostIDLT(v string) predicate.TeamHost { + return predicate.TeamHost(sql.FieldLT(FieldHostID, v)) +} + +// HostIDLTE applies the LTE predicate on the "host_id" field. +func HostIDLTE(v string) predicate.TeamHost { + return predicate.TeamHost(sql.FieldLTE(FieldHostID, v)) +} + +// HostIDContains applies the Contains predicate on the "host_id" field. +func HostIDContains(v string) predicate.TeamHost { + return predicate.TeamHost(sql.FieldContains(FieldHostID, v)) +} + +// HostIDHasPrefix applies the HasPrefix predicate on the "host_id" field. +func HostIDHasPrefix(v string) predicate.TeamHost { + return predicate.TeamHost(sql.FieldHasPrefix(FieldHostID, v)) +} + +// HostIDHasSuffix applies the HasSuffix predicate on the "host_id" field. +func HostIDHasSuffix(v string) predicate.TeamHost { + return predicate.TeamHost(sql.FieldHasSuffix(FieldHostID, v)) +} + +// HostIDEqualFold applies the EqualFold predicate on the "host_id" field. +func HostIDEqualFold(v string) predicate.TeamHost { + return predicate.TeamHost(sql.FieldEqualFold(FieldHostID, v)) +} + +// HostIDContainsFold applies the ContainsFold predicate on the "host_id" field. +func HostIDContainsFold(v string) predicate.TeamHost { + return predicate.TeamHost(sql.FieldContainsFold(FieldHostID, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.TeamHost { + return predicate.TeamHost(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.TeamHost { + return predicate.TeamHost(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.TeamHost { + return predicate.TeamHost(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.TeamHost { + return predicate.TeamHost(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.TeamHost { + return predicate.TeamHost(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.TeamHost { + return predicate.TeamHost(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.TeamHost { + return predicate.TeamHost(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.TeamHost { + return predicate.TeamHost(sql.FieldLTE(FieldCreatedAt, v)) +} + +// HasTeam applies the HasEdge predicate on the "team" edge. +func HasTeam() predicate.TeamHost { + return predicate.TeamHost(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, TeamTable, TeamColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasTeamWith applies the HasEdge predicate on the "team" edge with a given conditions (other predicates). +func HasTeamWith(preds ...predicate.Team) predicate.TeamHost { + return predicate.TeamHost(func(s *sql.Selector) { + step := newTeamStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasHost applies the HasEdge predicate on the "host" edge. +func HasHost() predicate.TeamHost { + return predicate.TeamHost(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, HostTable, HostColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasHostWith applies the HasEdge predicate on the "host" edge with a given conditions (other predicates). +func HasHostWith(preds ...predicate.Host) predicate.TeamHost { + return predicate.TeamHost(func(s *sql.Selector) { + step := newHostStep() + 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.TeamHost) predicate.TeamHost { + return predicate.TeamHost(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.TeamHost) predicate.TeamHost { + return predicate.TeamHost(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.TeamHost) predicate.TeamHost { + return predicate.TeamHost(sql.NotPredicates(p)) +} diff --git a/backend/db/teamhost_create.go b/backend/db/teamhost_create.go new file mode 100644 index 00000000..446753b6 --- /dev/null +++ b/backend/db/teamhost_create.go @@ -0,0 +1,659 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/host" + "github.com/chaitin/MonkeyCode/backend/db/team" + "github.com/chaitin/MonkeyCode/backend/db/teamhost" + "github.com/google/uuid" +) + +// TeamHostCreate is the builder for creating a TeamHost entity. +type TeamHostCreate struct { + config + mutation *TeamHostMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetTeamID sets the "team_id" field. +func (_c *TeamHostCreate) SetTeamID(v uuid.UUID) *TeamHostCreate { + _c.mutation.SetTeamID(v) + return _c +} + +// SetHostID sets the "host_id" field. +func (_c *TeamHostCreate) SetHostID(v string) *TeamHostCreate { + _c.mutation.SetHostID(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *TeamHostCreate) SetCreatedAt(v time.Time) *TeamHostCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *TeamHostCreate) SetNillableCreatedAt(v *time.Time) *TeamHostCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *TeamHostCreate) SetID(v uuid.UUID) *TeamHostCreate { + _c.mutation.SetID(v) + return _c +} + +// SetTeam sets the "team" edge to the Team entity. +func (_c *TeamHostCreate) SetTeam(v *Team) *TeamHostCreate { + return _c.SetTeamID(v.ID) +} + +// SetHost sets the "host" edge to the Host entity. +func (_c *TeamHostCreate) SetHost(v *Host) *TeamHostCreate { + return _c.SetHostID(v.ID) +} + +// Mutation returns the TeamHostMutation object of the builder. +func (_c *TeamHostCreate) Mutation() *TeamHostMutation { + return _c.mutation +} + +// Save creates the TeamHost in the database. +func (_c *TeamHostCreate) Save(ctx context.Context) (*TeamHost, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *TeamHostCreate) SaveX(ctx context.Context) *TeamHost { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *TeamHostCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *TeamHostCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *TeamHostCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := teamhost.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *TeamHostCreate) check() error { + if _, ok := _c.mutation.TeamID(); !ok { + return &ValidationError{Name: "team_id", err: errors.New(`db: missing required field "TeamHost.team_id"`)} + } + if _, ok := _c.mutation.HostID(); !ok { + return &ValidationError{Name: "host_id", err: errors.New(`db: missing required field "TeamHost.host_id"`)} + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "TeamHost.created_at"`)} + } + if len(_c.mutation.TeamIDs()) == 0 { + return &ValidationError{Name: "team", err: errors.New(`db: missing required edge "TeamHost.team"`)} + } + if len(_c.mutation.HostIDs()) == 0 { + return &ValidationError{Name: "host", err: errors.New(`db: missing required edge "TeamHost.host"`)} + } + return nil +} + +func (_c *TeamHostCreate) sqlSave(ctx context.Context) (*TeamHost, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + 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 + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *TeamHostCreate) createSpec() (*TeamHost, *sqlgraph.CreateSpec) { + var ( + _node = &TeamHost{config: _c.config} + _spec = sqlgraph.NewCreateSpec(teamhost.Table, sqlgraph.NewFieldSpec(teamhost.FieldID, field.TypeUUID)) + ) + _spec.OnConflict = _c.conflict + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = &id + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(teamhost.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if nodes := _c.mutation.TeamIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: teamhost.TeamTable, + Columns: []string{teamhost.TeamColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(team.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.TeamID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.HostIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: teamhost.HostTable, + Columns: []string{teamhost.HostColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.HostID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.TeamHost.Create(). +// SetTeamID(v). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.TeamHostUpsert) { +// SetTeamID(v+v). +// }). +// Exec(ctx) +func (_c *TeamHostCreate) OnConflict(opts ...sql.ConflictOption) *TeamHostUpsertOne { + _c.conflict = opts + return &TeamHostUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.TeamHost.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *TeamHostCreate) OnConflictColumns(columns ...string) *TeamHostUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &TeamHostUpsertOne{ + create: _c, + } +} + +type ( + // TeamHostUpsertOne is the builder for "upsert"-ing + // one TeamHost node. + TeamHostUpsertOne struct { + create *TeamHostCreate + } + + // TeamHostUpsert is the "OnConflict" setter. + TeamHostUpsert struct { + *sql.UpdateSet + } +) + +// SetTeamID sets the "team_id" field. +func (u *TeamHostUpsert) SetTeamID(v uuid.UUID) *TeamHostUpsert { + u.Set(teamhost.FieldTeamID, v) + return u +} + +// UpdateTeamID sets the "team_id" field to the value that was provided on create. +func (u *TeamHostUpsert) UpdateTeamID() *TeamHostUpsert { + u.SetExcluded(teamhost.FieldTeamID) + return u +} + +// SetHostID sets the "host_id" field. +func (u *TeamHostUpsert) SetHostID(v string) *TeamHostUpsert { + u.Set(teamhost.FieldHostID, v) + return u +} + +// UpdateHostID sets the "host_id" field to the value that was provided on create. +func (u *TeamHostUpsert) UpdateHostID() *TeamHostUpsert { + u.SetExcluded(teamhost.FieldHostID) + return u +} + +// SetCreatedAt sets the "created_at" field. +func (u *TeamHostUpsert) SetCreatedAt(v time.Time) *TeamHostUpsert { + u.Set(teamhost.FieldCreatedAt, v) + return u +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *TeamHostUpsert) UpdateCreatedAt() *TeamHostUpsert { + u.SetExcluded(teamhost.FieldCreatedAt) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.TeamHost.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(teamhost.FieldID) +// }), +// ). +// Exec(ctx) +func (u *TeamHostUpsertOne) UpdateNewValues() *TeamHostUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + if _, exists := u.create.mutation.ID(); exists { + s.SetIgnore(teamhost.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.TeamHost.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *TeamHostUpsertOne) Ignore() *TeamHostUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *TeamHostUpsertOne) DoNothing() *TeamHostUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the TeamHostCreate.OnConflict +// documentation for more info. +func (u *TeamHostUpsertOne) Update(set func(*TeamHostUpsert)) *TeamHostUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&TeamHostUpsert{UpdateSet: update}) + })) + return u +} + +// SetTeamID sets the "team_id" field. +func (u *TeamHostUpsertOne) SetTeamID(v uuid.UUID) *TeamHostUpsertOne { + return u.Update(func(s *TeamHostUpsert) { + s.SetTeamID(v) + }) +} + +// UpdateTeamID sets the "team_id" field to the value that was provided on create. +func (u *TeamHostUpsertOne) UpdateTeamID() *TeamHostUpsertOne { + return u.Update(func(s *TeamHostUpsert) { + s.UpdateTeamID() + }) +} + +// SetHostID sets the "host_id" field. +func (u *TeamHostUpsertOne) SetHostID(v string) *TeamHostUpsertOne { + return u.Update(func(s *TeamHostUpsert) { + s.SetHostID(v) + }) +} + +// UpdateHostID sets the "host_id" field to the value that was provided on create. +func (u *TeamHostUpsertOne) UpdateHostID() *TeamHostUpsertOne { + return u.Update(func(s *TeamHostUpsert) { + s.UpdateHostID() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *TeamHostUpsertOne) SetCreatedAt(v time.Time) *TeamHostUpsertOne { + return u.Update(func(s *TeamHostUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *TeamHostUpsertOne) UpdateCreatedAt() *TeamHostUpsertOne { + return u.Update(func(s *TeamHostUpsert) { + s.UpdateCreatedAt() + }) +} + +// Exec executes the query. +func (u *TeamHostUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for TeamHostCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *TeamHostUpsertOne) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} + +// Exec executes the UPSERT query and returns the inserted/updated ID. +func (u *TeamHostUpsertOne) ID(ctx context.Context) (id uuid.UUID, err error) { + if u.create.driver.Dialect() == dialect.MySQL { + // In case of "ON CONFLICT", there is no way to get back non-numeric ID + // fields from the database since MySQL does not support the RETURNING clause. + return id, errors.New("db: TeamHostUpsertOne.ID is not supported by MySQL driver. Use TeamHostUpsertOne.Exec instead") + } + node, err := u.create.Save(ctx) + if err != nil { + return id, err + } + return node.ID, nil +} + +// IDX is like ID, but panics if an error occurs. +func (u *TeamHostUpsertOne) IDX(ctx context.Context) uuid.UUID { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// TeamHostCreateBulk is the builder for creating many TeamHost entities in bulk. +type TeamHostCreateBulk struct { + config + err error + builders []*TeamHostCreate + conflict []sql.ConflictOption +} + +// Save creates the TeamHost entities in the database. +func (_c *TeamHostCreateBulk) Save(ctx context.Context) ([]*TeamHost, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*TeamHost, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*TeamHostMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.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, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *TeamHostCreateBulk) SaveX(ctx context.Context) []*TeamHost { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *TeamHostCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *TeamHostCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.TeamHost.CreateBulk(builders...). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.TeamHostUpsert) { +// SetTeamID(v+v). +// }). +// Exec(ctx) +func (_c *TeamHostCreateBulk) OnConflict(opts ...sql.ConflictOption) *TeamHostUpsertBulk { + _c.conflict = opts + return &TeamHostUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.TeamHost.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *TeamHostCreateBulk) OnConflictColumns(columns ...string) *TeamHostUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &TeamHostUpsertBulk{ + create: _c, + } +} + +// TeamHostUpsertBulk is the builder for "upsert"-ing +// a bulk of TeamHost nodes. +type TeamHostUpsertBulk struct { + create *TeamHostCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.TeamHost.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(teamhost.FieldID) +// }), +// ). +// Exec(ctx) +func (u *TeamHostUpsertBulk) UpdateNewValues() *TeamHostUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + for _, b := range u.create.builders { + if _, exists := b.mutation.ID(); exists { + s.SetIgnore(teamhost.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.TeamHost.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *TeamHostUpsertBulk) Ignore() *TeamHostUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *TeamHostUpsertBulk) DoNothing() *TeamHostUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the TeamHostCreateBulk.OnConflict +// documentation for more info. +func (u *TeamHostUpsertBulk) Update(set func(*TeamHostUpsert)) *TeamHostUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&TeamHostUpsert{UpdateSet: update}) + })) + return u +} + +// SetTeamID sets the "team_id" field. +func (u *TeamHostUpsertBulk) SetTeamID(v uuid.UUID) *TeamHostUpsertBulk { + return u.Update(func(s *TeamHostUpsert) { + s.SetTeamID(v) + }) +} + +// UpdateTeamID sets the "team_id" field to the value that was provided on create. +func (u *TeamHostUpsertBulk) UpdateTeamID() *TeamHostUpsertBulk { + return u.Update(func(s *TeamHostUpsert) { + s.UpdateTeamID() + }) +} + +// SetHostID sets the "host_id" field. +func (u *TeamHostUpsertBulk) SetHostID(v string) *TeamHostUpsertBulk { + return u.Update(func(s *TeamHostUpsert) { + s.SetHostID(v) + }) +} + +// UpdateHostID sets the "host_id" field to the value that was provided on create. +func (u *TeamHostUpsertBulk) UpdateHostID() *TeamHostUpsertBulk { + return u.Update(func(s *TeamHostUpsert) { + s.UpdateHostID() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *TeamHostUpsertBulk) SetCreatedAt(v time.Time) *TeamHostUpsertBulk { + return u.Update(func(s *TeamHostUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *TeamHostUpsertBulk) UpdateCreatedAt() *TeamHostUpsertBulk { + return u.Update(func(s *TeamHostUpsert) { + s.UpdateCreatedAt() + }) +} + +// Exec executes the query. +func (u *TeamHostUpsertBulk) Exec(ctx context.Context) error { + if u.create.err != nil { + return u.create.err + } + for i, b := range u.create.builders { + if len(b.conflict) != 0 { + return fmt.Errorf("db: OnConflict was set for builder %d. Set it on the TeamHostCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for TeamHostCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *TeamHostUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/teamhost_delete.go b/backend/db/teamhost_delete.go new file mode 100644 index 00000000..91ff587e --- /dev/null +++ b/backend/db/teamhost_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/teamhost" +) + +// TeamHostDelete is the builder for deleting a TeamHost entity. +type TeamHostDelete struct { + config + hooks []Hook + mutation *TeamHostMutation +} + +// Where appends a list predicates to the TeamHostDelete builder. +func (_d *TeamHostDelete) Where(ps ...predicate.TeamHost) *TeamHostDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *TeamHostDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *TeamHostDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *TeamHostDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(teamhost.Table, sqlgraph.NewFieldSpec(teamhost.FieldID, field.TypeUUID)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// TeamHostDeleteOne is the builder for deleting a single TeamHost entity. +type TeamHostDeleteOne struct { + _d *TeamHostDelete +} + +// Where appends a list predicates to the TeamHostDelete builder. +func (_d *TeamHostDeleteOne) Where(ps ...predicate.TeamHost) *TeamHostDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *TeamHostDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{teamhost.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *TeamHostDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/teamhost_query.go b/backend/db/teamhost_query.go new file mode 100644 index 00000000..9906c544 --- /dev/null +++ b/backend/db/teamhost_query.go @@ -0,0 +1,732 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/host" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/team" + "github.com/chaitin/MonkeyCode/backend/db/teamhost" + "github.com/google/uuid" +) + +// TeamHostQuery is the builder for querying TeamHost entities. +type TeamHostQuery struct { + config + ctx *QueryContext + order []teamhost.OrderOption + inters []Interceptor + predicates []predicate.TeamHost + withTeam *TeamQuery + withHost *HostQuery + modifiers []func(*sql.Selector) + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the TeamHostQuery builder. +func (_q *TeamHostQuery) Where(ps ...predicate.TeamHost) *TeamHostQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *TeamHostQuery) Limit(limit int) *TeamHostQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *TeamHostQuery) Offset(offset int) *TeamHostQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *TeamHostQuery) Unique(unique bool) *TeamHostQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *TeamHostQuery) Order(o ...teamhost.OrderOption) *TeamHostQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryTeam chains the current query on the "team" edge. +func (_q *TeamHostQuery) QueryTeam() *TeamQuery { + query := (&TeamClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(teamhost.Table, teamhost.FieldID, selector), + sqlgraph.To(team.Table, team.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, teamhost.TeamTable, teamhost.TeamColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryHost chains the current query on the "host" edge. +func (_q *TeamHostQuery) QueryHost() *HostQuery { + query := (&HostClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(teamhost.Table, teamhost.FieldID, selector), + sqlgraph.To(host.Table, host.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, teamhost.HostTable, teamhost.HostColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first TeamHost entity from the query. +// Returns a *NotFoundError when no TeamHost was found. +func (_q *TeamHostQuery) First(ctx context.Context) (*TeamHost, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{teamhost.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *TeamHostQuery) FirstX(ctx context.Context) *TeamHost { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first TeamHost ID from the query. +// Returns a *NotFoundError when no TeamHost ID was found. +func (_q *TeamHostQuery) FirstID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{teamhost.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *TeamHostQuery) FirstIDX(ctx context.Context) uuid.UUID { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single TeamHost entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one TeamHost entity is found. +// Returns a *NotFoundError when no TeamHost entities are found. +func (_q *TeamHostQuery) Only(ctx context.Context) (*TeamHost, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{teamhost.Label} + default: + return nil, &NotSingularError{teamhost.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *TeamHostQuery) OnlyX(ctx context.Context) *TeamHost { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only TeamHost ID in the query. +// Returns a *NotSingularError when more than one TeamHost ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *TeamHostQuery) OnlyID(ctx context.Context) (id uuid.UUID, err error) { + var ids []uuid.UUID + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{teamhost.Label} + default: + err = &NotSingularError{teamhost.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *TeamHostQuery) OnlyIDX(ctx context.Context) uuid.UUID { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of TeamHosts. +func (_q *TeamHostQuery) All(ctx context.Context) ([]*TeamHost, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*TeamHost, *TeamHostQuery]() + return withInterceptors[[]*TeamHost](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *TeamHostQuery) AllX(ctx context.Context) []*TeamHost { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of TeamHost IDs. +func (_q *TeamHostQuery) IDs(ctx context.Context) (ids []uuid.UUID, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(teamhost.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *TeamHostQuery) IDsX(ctx context.Context) []uuid.UUID { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *TeamHostQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*TeamHostQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *TeamHostQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *TeamHostQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("db: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *TeamHostQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the TeamHostQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *TeamHostQuery) Clone() *TeamHostQuery { + if _q == nil { + return nil + } + return &TeamHostQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]teamhost.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.TeamHost{}, _q.predicates...), + withTeam: _q.withTeam.Clone(), + withHost: _q.withHost.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + modifiers: append([]func(*sql.Selector){}, _q.modifiers...), + } +} + +// WithTeam tells the query-builder to eager-load the nodes that are connected to +// the "team" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *TeamHostQuery) WithTeam(opts ...func(*TeamQuery)) *TeamHostQuery { + query := (&TeamClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withTeam = query + return _q +} + +// WithHost tells the query-builder to eager-load the nodes that are connected to +// the "host" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *TeamHostQuery) WithHost(opts ...func(*HostQuery)) *TeamHostQuery { + query := (&HostClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withHost = query + return _q +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// TeamID uuid.UUID `json:"team_id,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.TeamHost.Query(). +// GroupBy(teamhost.FieldTeamID). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *TeamHostQuery) GroupBy(field string, fields ...string) *TeamHostGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &TeamHostGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = teamhost.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// TeamID uuid.UUID `json:"team_id,omitempty"` +// } +// +// client.TeamHost.Query(). +// Select(teamhost.FieldTeamID). +// Scan(ctx, &v) +func (_q *TeamHostQuery) Select(fields ...string) *TeamHostSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &TeamHostSelect{TeamHostQuery: _q} + sbuild.label = teamhost.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a TeamHostSelect configured with the given aggregations. +func (_q *TeamHostQuery) Aggregate(fns ...AggregateFunc) *TeamHostSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *TeamHostQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !teamhost.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *TeamHostQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*TeamHost, error) { + var ( + nodes = []*TeamHost{} + _spec = _q.querySpec() + loadedTypes = [2]bool{ + _q.withTeam != nil, + _q.withHost != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*TeamHost).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &TeamHost{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withTeam; query != nil { + if err := _q.loadTeam(ctx, query, nodes, nil, + func(n *TeamHost, e *Team) { n.Edges.Team = e }); err != nil { + return nil, err + } + } + if query := _q.withHost; query != nil { + if err := _q.loadHost(ctx, query, nodes, nil, + func(n *TeamHost, e *Host) { n.Edges.Host = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *TeamHostQuery) loadTeam(ctx context.Context, query *TeamQuery, nodes []*TeamHost, init func(*TeamHost), assign func(*TeamHost, *Team)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*TeamHost) + for i := range nodes { + fk := nodes[i].TeamID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(team.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 "team_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *TeamHostQuery) loadHost(ctx context.Context, query *HostQuery, nodes []*TeamHost, init func(*TeamHost), assign func(*TeamHost, *Host)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*TeamHost) + for i := range nodes { + fk := nodes[i].HostID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(host.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 "host_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *TeamHostQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *TeamHostQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(teamhost.Table, teamhost.Columns, sqlgraph.NewFieldSpec(teamhost.FieldID, field.TypeUUID)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, teamhost.FieldID) + for i := range fields { + if fields[i] != teamhost.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withTeam != nil { + _spec.Node.AddColumnOnce(teamhost.FieldTeamID) + } + if _q.withHost != nil { + _spec.Node.AddColumnOnce(teamhost.FieldHostID) + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *TeamHostQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(teamhost.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = teamhost.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, m := range _q.modifiers { + m(selector) + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// ForUpdate locks the selected rows against concurrent updates, and prevent them from being +// updated, deleted or "selected ... for update" by other sessions, until the transaction is +// either committed or rolled-back. +func (_q *TeamHostQuery) ForUpdate(opts ...sql.LockOption) *TeamHostQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return _q +} + +// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock +// on any rows that are read. Other sessions can read the rows, but cannot modify them +// until your transaction commits. +func (_q *TeamHostQuery) ForShare(opts ...sql.LockOption) *TeamHostQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (_q *TeamHostQuery) Modify(modifiers ...func(s *sql.Selector)) *TeamHostSelect { + _q.modifiers = append(_q.modifiers, modifiers...) + return _q.Select() +} + +// TeamHostGroupBy is the group-by builder for TeamHost entities. +type TeamHostGroupBy struct { + selector + build *TeamHostQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *TeamHostGroupBy) Aggregate(fns ...AggregateFunc) *TeamHostGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *TeamHostGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*TeamHostQuery, *TeamHostGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *TeamHostGroupBy) sqlScan(ctx context.Context, root *TeamHostQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// TeamHostSelect is the builder for selecting fields of TeamHost entities. +type TeamHostSelect struct { + *TeamHostQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *TeamHostSelect) Aggregate(fns ...AggregateFunc) *TeamHostSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *TeamHostSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*TeamHostQuery, *TeamHostSelect](ctx, _s.TeamHostQuery, _s, _s.inters, v) +} + +func (_s *TeamHostSelect) sqlScan(ctx context.Context, root *TeamHostQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (_s *TeamHostSelect) Modify(modifiers ...func(s *sql.Selector)) *TeamHostSelect { + _s.modifiers = append(_s.modifiers, modifiers...) + return _s +} diff --git a/backend/db/teamhost_update.go b/backend/db/teamhost_update.go new file mode 100644 index 00000000..8cc3b780 --- /dev/null +++ b/backend/db/teamhost_update.go @@ -0,0 +1,473 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/host" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/team" + "github.com/chaitin/MonkeyCode/backend/db/teamhost" + "github.com/google/uuid" +) + +// TeamHostUpdate is the builder for updating TeamHost entities. +type TeamHostUpdate struct { + config + hooks []Hook + mutation *TeamHostMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the TeamHostUpdate builder. +func (_u *TeamHostUpdate) Where(ps ...predicate.TeamHost) *TeamHostUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetTeamID sets the "team_id" field. +func (_u *TeamHostUpdate) SetTeamID(v uuid.UUID) *TeamHostUpdate { + _u.mutation.SetTeamID(v) + return _u +} + +// SetNillableTeamID sets the "team_id" field if the given value is not nil. +func (_u *TeamHostUpdate) SetNillableTeamID(v *uuid.UUID) *TeamHostUpdate { + if v != nil { + _u.SetTeamID(*v) + } + return _u +} + +// SetHostID sets the "host_id" field. +func (_u *TeamHostUpdate) SetHostID(v string) *TeamHostUpdate { + _u.mutation.SetHostID(v) + return _u +} + +// SetNillableHostID sets the "host_id" field if the given value is not nil. +func (_u *TeamHostUpdate) SetNillableHostID(v *string) *TeamHostUpdate { + if v != nil { + _u.SetHostID(*v) + } + return _u +} + +// SetCreatedAt sets the "created_at" field. +func (_u *TeamHostUpdate) SetCreatedAt(v time.Time) *TeamHostUpdate { + _u.mutation.SetCreatedAt(v) + return _u +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_u *TeamHostUpdate) SetNillableCreatedAt(v *time.Time) *TeamHostUpdate { + if v != nil { + _u.SetCreatedAt(*v) + } + return _u +} + +// SetTeam sets the "team" edge to the Team entity. +func (_u *TeamHostUpdate) SetTeam(v *Team) *TeamHostUpdate { + return _u.SetTeamID(v.ID) +} + +// SetHost sets the "host" edge to the Host entity. +func (_u *TeamHostUpdate) SetHost(v *Host) *TeamHostUpdate { + return _u.SetHostID(v.ID) +} + +// Mutation returns the TeamHostMutation object of the builder. +func (_u *TeamHostUpdate) Mutation() *TeamHostMutation { + return _u.mutation +} + +// ClearTeam clears the "team" edge to the Team entity. +func (_u *TeamHostUpdate) ClearTeam() *TeamHostUpdate { + _u.mutation.ClearTeam() + return _u +} + +// ClearHost clears the "host" edge to the Host entity. +func (_u *TeamHostUpdate) ClearHost() *TeamHostUpdate { + _u.mutation.ClearHost() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *TeamHostUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *TeamHostUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *TeamHostUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *TeamHostUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *TeamHostUpdate) check() error { + if _u.mutation.TeamCleared() && len(_u.mutation.TeamIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "TeamHost.team"`) + } + if _u.mutation.HostCleared() && len(_u.mutation.HostIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "TeamHost.host"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *TeamHostUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *TeamHostUpdate { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *TeamHostUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(teamhost.Table, teamhost.Columns, sqlgraph.NewFieldSpec(teamhost.FieldID, field.TypeUUID)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.CreatedAt(); ok { + _spec.SetField(teamhost.FieldCreatedAt, field.TypeTime, value) + } + if _u.mutation.TeamCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: teamhost.TeamTable, + Columns: []string{teamhost.TeamColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(team.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.TeamIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: teamhost.TeamTable, + Columns: []string{teamhost.TeamColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(team.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.HostCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: teamhost.HostTable, + Columns: []string{teamhost.HostColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.HostIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: teamhost.HostTable, + Columns: []string{teamhost.HostColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(_u.modifiers...) + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{teamhost.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// TeamHostUpdateOne is the builder for updating a single TeamHost entity. +type TeamHostUpdateOne struct { + config + fields []string + hooks []Hook + mutation *TeamHostMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetTeamID sets the "team_id" field. +func (_u *TeamHostUpdateOne) SetTeamID(v uuid.UUID) *TeamHostUpdateOne { + _u.mutation.SetTeamID(v) + return _u +} + +// SetNillableTeamID sets the "team_id" field if the given value is not nil. +func (_u *TeamHostUpdateOne) SetNillableTeamID(v *uuid.UUID) *TeamHostUpdateOne { + if v != nil { + _u.SetTeamID(*v) + } + return _u +} + +// SetHostID sets the "host_id" field. +func (_u *TeamHostUpdateOne) SetHostID(v string) *TeamHostUpdateOne { + _u.mutation.SetHostID(v) + return _u +} + +// SetNillableHostID sets the "host_id" field if the given value is not nil. +func (_u *TeamHostUpdateOne) SetNillableHostID(v *string) *TeamHostUpdateOne { + if v != nil { + _u.SetHostID(*v) + } + return _u +} + +// SetCreatedAt sets the "created_at" field. +func (_u *TeamHostUpdateOne) SetCreatedAt(v time.Time) *TeamHostUpdateOne { + _u.mutation.SetCreatedAt(v) + return _u +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_u *TeamHostUpdateOne) SetNillableCreatedAt(v *time.Time) *TeamHostUpdateOne { + if v != nil { + _u.SetCreatedAt(*v) + } + return _u +} + +// SetTeam sets the "team" edge to the Team entity. +func (_u *TeamHostUpdateOne) SetTeam(v *Team) *TeamHostUpdateOne { + return _u.SetTeamID(v.ID) +} + +// SetHost sets the "host" edge to the Host entity. +func (_u *TeamHostUpdateOne) SetHost(v *Host) *TeamHostUpdateOne { + return _u.SetHostID(v.ID) +} + +// Mutation returns the TeamHostMutation object of the builder. +func (_u *TeamHostUpdateOne) Mutation() *TeamHostMutation { + return _u.mutation +} + +// ClearTeam clears the "team" edge to the Team entity. +func (_u *TeamHostUpdateOne) ClearTeam() *TeamHostUpdateOne { + _u.mutation.ClearTeam() + return _u +} + +// ClearHost clears the "host" edge to the Host entity. +func (_u *TeamHostUpdateOne) ClearHost() *TeamHostUpdateOne { + _u.mutation.ClearHost() + return _u +} + +// Where appends a list predicates to the TeamHostUpdate builder. +func (_u *TeamHostUpdateOne) Where(ps ...predicate.TeamHost) *TeamHostUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *TeamHostUpdateOne) Select(field string, fields ...string) *TeamHostUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated TeamHost entity. +func (_u *TeamHostUpdateOne) Save(ctx context.Context) (*TeamHost, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *TeamHostUpdateOne) SaveX(ctx context.Context) *TeamHost { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *TeamHostUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *TeamHostUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *TeamHostUpdateOne) check() error { + if _u.mutation.TeamCleared() && len(_u.mutation.TeamIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "TeamHost.team"`) + } + if _u.mutation.HostCleared() && len(_u.mutation.HostIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "TeamHost.host"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *TeamHostUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *TeamHostUpdateOne { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *TeamHostUpdateOne) sqlSave(ctx context.Context) (_node *TeamHost, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(teamhost.Table, teamhost.Columns, sqlgraph.NewFieldSpec(teamhost.FieldID, field.TypeUUID)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "TeamHost.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, teamhost.FieldID) + for _, f := range fields { + if !teamhost.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != teamhost.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.CreatedAt(); ok { + _spec.SetField(teamhost.FieldCreatedAt, field.TypeTime, value) + } + if _u.mutation.TeamCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: teamhost.TeamTable, + Columns: []string{teamhost.TeamColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(team.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.TeamIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: teamhost.TeamTable, + Columns: []string{teamhost.TeamColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(team.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.HostCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: teamhost.HostTable, + Columns: []string{teamhost.HostColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.HostIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: teamhost.HostTable, + Columns: []string{teamhost.HostColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(_u.modifiers...) + _node = &TeamHost{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{teamhost.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/backend/db/tx.go b/backend/db/tx.go index d605f7c0..e3f0c953 100644 --- a/backend/db/tx.go +++ b/backend/db/tx.go @@ -16,6 +16,8 @@ type Tx struct { config // Audit is the client for interacting with the Audit builders. Audit *AuditClient + // Host is the client for interacting with the Host builders. + Host *HostClient // Image is the client for interacting with the Image builders. Image *ImageClient // Model is the client for interacting with the Model builders. @@ -24,12 +26,16 @@ type Tx struct { Team *TeamClient // TeamGroup is the client for interacting with the TeamGroup builders. TeamGroup *TeamGroupClient + // TeamGroupHost is the client for interacting with the TeamGroupHost builders. + TeamGroupHost *TeamGroupHostClient // TeamGroupImage is the client for interacting with the TeamGroupImage builders. TeamGroupImage *TeamGroupImageClient // TeamGroupMember is the client for interacting with the TeamGroupMember builders. TeamGroupMember *TeamGroupMemberClient // TeamGroupModel is the client for interacting with the TeamGroupModel builders. TeamGroupModel *TeamGroupModelClient + // TeamHost is the client for interacting with the TeamHost builders. + TeamHost *TeamHostClient // TeamImage is the client for interacting with the TeamImage builders. TeamImage *TeamImageClient // TeamMember is the client for interacting with the TeamMember builders. @@ -40,6 +46,8 @@ type Tx struct { User *UserClient // UserIdentity is the client for interacting with the UserIdentity builders. UserIdentity *UserIdentityClient + // VirtualMachine is the client for interacting with the VirtualMachine builders. + VirtualMachine *VirtualMachineClient // lazily loaded. client *Client @@ -172,18 +180,22 @@ func (tx *Tx) Client() *Client { func (tx *Tx) init() { tx.Audit = NewAuditClient(tx.config) + tx.Host = NewHostClient(tx.config) tx.Image = NewImageClient(tx.config) tx.Model = NewModelClient(tx.config) tx.Team = NewTeamClient(tx.config) tx.TeamGroup = NewTeamGroupClient(tx.config) + tx.TeamGroupHost = NewTeamGroupHostClient(tx.config) tx.TeamGroupImage = NewTeamGroupImageClient(tx.config) tx.TeamGroupMember = NewTeamGroupMemberClient(tx.config) tx.TeamGroupModel = NewTeamGroupModelClient(tx.config) + tx.TeamHost = NewTeamHostClient(tx.config) tx.TeamImage = NewTeamImageClient(tx.config) tx.TeamMember = NewTeamMemberClient(tx.config) tx.TeamModel = NewTeamModelClient(tx.config) tx.User = NewUserClient(tx.config) tx.UserIdentity = NewUserIdentityClient(tx.config) + tx.VirtualMachine = NewVirtualMachineClient(tx.config) } // txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation. diff --git a/backend/db/user.go b/backend/db/user.go index 6d058589..10cd7b3e 100644 --- a/backend/db/user.go +++ b/backend/db/user.go @@ -62,13 +62,17 @@ type UserEdges struct { Models []*Model `json:"models,omitempty"` // Images holds the value of the images edge. Images []*Image `json:"images,omitempty"` + // Hosts holds the value of the hosts edge. + Hosts []*Host `json:"hosts,omitempty"` + // Vms holds the value of the vms edge. + Vms []*VirtualMachine `json:"vms,omitempty"` // TeamMembers holds the value of the team_members edge. TeamMembers []*TeamMember `json:"team_members,omitempty"` // TeamGroupMembers holds the value of the team_group_members edge. TeamGroupMembers []*TeamGroupMember `json:"team_group_members,omitempty"` // loadedTypes holds the information for reporting if a // type was loaded (or requested) in eager-loading or not. - loadedTypes [8]bool + loadedTypes [10]bool } // IdentitiesOrErr returns the Identities value or an error if the edge @@ -125,10 +129,28 @@ func (e UserEdges) ImagesOrErr() ([]*Image, error) { return nil, &NotLoadedError{edge: "images"} } +// HostsOrErr returns the Hosts value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) HostsOrErr() ([]*Host, error) { + if e.loadedTypes[6] { + return e.Hosts, nil + } + return nil, &NotLoadedError{edge: "hosts"} +} + +// VmsOrErr returns the Vms value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) VmsOrErr() ([]*VirtualMachine, error) { + if e.loadedTypes[7] { + return e.Vms, nil + } + return nil, &NotLoadedError{edge: "vms"} +} + // TeamMembersOrErr returns the TeamMembers value or an error if the edge // was not loaded in eager-loading. func (e UserEdges) TeamMembersOrErr() ([]*TeamMember, error) { - if e.loadedTypes[6] { + if e.loadedTypes[8] { return e.TeamMembers, nil } return nil, &NotLoadedError{edge: "team_members"} @@ -137,7 +159,7 @@ func (e UserEdges) TeamMembersOrErr() ([]*TeamMember, error) { // TeamGroupMembersOrErr returns the TeamGroupMembers value or an error if the edge // was not loaded in eager-loading. func (e UserEdges) TeamGroupMembersOrErr() ([]*TeamGroupMember, error) { - if e.loadedTypes[7] { + if e.loadedTypes[9] { return e.TeamGroupMembers, nil } return nil, &NotLoadedError{edge: "team_group_members"} @@ -290,6 +312,16 @@ func (_m *User) QueryImages() *ImageQuery { return NewUserClient(_m.config).QueryImages(_m) } +// QueryHosts queries the "hosts" edge of the User entity. +func (_m *User) QueryHosts() *HostQuery { + return NewUserClient(_m.config).QueryHosts(_m) +} + +// QueryVms queries the "vms" edge of the User entity. +func (_m *User) QueryVms() *VirtualMachineQuery { + return NewUserClient(_m.config).QueryVms(_m) +} + // QueryTeamMembers queries the "team_members" edge of the User entity. func (_m *User) QueryTeamMembers() *TeamMemberQuery { return NewUserClient(_m.config).QueryTeamMembers(_m) diff --git a/backend/db/user/user.go b/backend/db/user/user.go index 384dd3f9..b1cf5c2b 100644 --- a/backend/db/user/user.go +++ b/backend/db/user/user.go @@ -49,6 +49,10 @@ const ( EdgeModels = "models" // EdgeImages holds the string denoting the images edge name in mutations. EdgeImages = "images" + // EdgeHosts holds the string denoting the hosts edge name in mutations. + EdgeHosts = "hosts" + // EdgeVms holds the string denoting the vms edge name in mutations. + EdgeVms = "vms" // EdgeTeamMembers holds the string denoting the team_members edge name in mutations. EdgeTeamMembers = "team_members" // EdgeTeamGroupMembers holds the string denoting the team_group_members edge name in mutations. @@ -93,6 +97,20 @@ const ( ImagesInverseTable = "images" // ImagesColumn is the table column denoting the images relation/edge. ImagesColumn = "user_id" + // HostsTable is the table that holds the hosts relation/edge. + HostsTable = "hosts" + // HostsInverseTable is the table name for the Host entity. + // It exists in this package in order to avoid circular dependency with the "host" package. + HostsInverseTable = "hosts" + // HostsColumn is the table column denoting the hosts relation/edge. + HostsColumn = "user_id" + // VmsTable is the table that holds the vms relation/edge. + VmsTable = "virtualmachines" + // VmsInverseTable is the table name for the VirtualMachine entity. + // It exists in this package in order to avoid circular dependency with the "virtualmachine" package. + VmsInverseTable = "virtualmachines" + // VmsColumn is the table column denoting the vms relation/edge. + VmsColumn = "user_id" // TeamMembersTable is the table that holds the team_members relation/edge. TeamMembersTable = "team_members" // TeamMembersInverseTable is the table name for the TeamMember entity. @@ -306,6 +324,34 @@ func ByImages(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { } } +// ByHostsCount orders the results by hosts count. +func ByHostsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newHostsStep(), opts...) + } +} + +// ByHosts orders the results by hosts terms. +func ByHosts(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newHostsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByVmsCount orders the results by vms count. +func ByVmsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newVmsStep(), opts...) + } +} + +// ByVms orders the results by vms terms. +func ByVms(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newVmsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + // ByTeamMembersCount orders the results by team_members count. func ByTeamMembersCount(opts ...sql.OrderTermOption) OrderOption { return func(s *sql.Selector) { @@ -375,6 +421,20 @@ func newImagesStep() *sqlgraph.Step { sqlgraph.Edge(sqlgraph.O2M, false, ImagesTable, ImagesColumn), ) } +func newHostsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(HostsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, HostsTable, HostsColumn), + ) +} +func newVmsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(VmsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, VmsTable, VmsColumn), + ) +} func newTeamMembersStep() *sqlgraph.Step { return sqlgraph.NewStep( sqlgraph.From(Table, FieldID), diff --git a/backend/db/user/where.go b/backend/db/user/where.go index 6d7c8406..061fc47f 100644 --- a/backend/db/user/where.go +++ b/backend/db/user/where.go @@ -855,6 +855,52 @@ func HasImagesWith(preds ...predicate.Image) predicate.User { }) } +// HasHosts applies the HasEdge predicate on the "hosts" edge. +func HasHosts() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, HostsTable, HostsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasHostsWith applies the HasEdge predicate on the "hosts" edge with a given conditions (other predicates). +func HasHostsWith(preds ...predicate.Host) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := newHostsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasVms applies the HasEdge predicate on the "vms" edge. +func HasVms() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, VmsTable, VmsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasVmsWith applies the HasEdge predicate on the "vms" edge with a given conditions (other predicates). +func HasVmsWith(preds ...predicate.VirtualMachine) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := newVmsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + // HasTeamMembers applies the HasEdge predicate on the "team_members" edge. func HasTeamMembers() predicate.User { return predicate.User(func(s *sql.Selector) { diff --git a/backend/db/user_create.go b/backend/db/user_create.go index d62650e7..b65ed84a 100644 --- a/backend/db/user_create.go +++ b/backend/db/user_create.go @@ -14,6 +14,7 @@ import ( "entgo.io/ent/schema/field" "github.com/chaitin/MonkeyCode/backend/consts" "github.com/chaitin/MonkeyCode/backend/db/audit" + "github.com/chaitin/MonkeyCode/backend/db/host" "github.com/chaitin/MonkeyCode/backend/db/image" "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/team" @@ -22,6 +23,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/teammember" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/chaitin/MonkeyCode/backend/db/useridentity" + "github.com/chaitin/MonkeyCode/backend/db/virtualmachine" "github.com/google/uuid" ) @@ -251,6 +253,36 @@ func (_c *UserCreate) AddImages(v ...*Image) *UserCreate { return _c.AddImageIDs(ids...) } +// AddHostIDs adds the "hosts" edge to the Host entity by IDs. +func (_c *UserCreate) AddHostIDs(ids ...string) *UserCreate { + _c.mutation.AddHostIDs(ids...) + return _c +} + +// AddHosts adds the "hosts" edges to the Host entity. +func (_c *UserCreate) AddHosts(v ...*Host) *UserCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddHostIDs(ids...) +} + +// AddVMIDs adds the "vms" edge to the VirtualMachine entity by IDs. +func (_c *UserCreate) AddVMIDs(ids ...string) *UserCreate { + _c.mutation.AddVMIDs(ids...) + return _c +} + +// AddVms adds the "vms" edges to the VirtualMachine entity. +func (_c *UserCreate) AddVms(v ...*VirtualMachine) *UserCreate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddVMIDs(ids...) +} + // AddTeamMemberIDs adds the "team_members" edge to the TeamMember entity by IDs. func (_c *UserCreate) AddTeamMemberIDs(ids ...uuid.UUID) *UserCreate { _c.mutation.AddTeamMemberIDs(ids...) @@ -548,6 +580,38 @@ func (_c *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) { } _spec.Edges = append(_spec.Edges, edge) } + if nodes := _c.mutation.HostsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.HostsTable, + Columns: []string{user.HostsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.VmsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.VmsTable, + Columns: []string{user.VmsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(virtualmachine.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } if nodes := _c.mutation.TeamMembersIDs(); len(nodes) > 0 { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, diff --git a/backend/db/user_query.go b/backend/db/user_query.go index 1b93e444..8225d38c 100644 --- a/backend/db/user_query.go +++ b/backend/db/user_query.go @@ -14,6 +14,7 @@ import ( "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" "github.com/chaitin/MonkeyCode/backend/db/audit" + "github.com/chaitin/MonkeyCode/backend/db/host" "github.com/chaitin/MonkeyCode/backend/db/image" "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/predicate" @@ -23,6 +24,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/teammember" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/chaitin/MonkeyCode/backend/db/useridentity" + "github.com/chaitin/MonkeyCode/backend/db/virtualmachine" "github.com/google/uuid" ) @@ -39,6 +41,8 @@ type UserQuery struct { withGroups *TeamGroupQuery withModels *ModelQuery withImages *ImageQuery + withHosts *HostQuery + withVms *VirtualMachineQuery withTeamMembers *TeamMemberQuery withTeamGroupMembers *TeamGroupMemberQuery modifiers []func(*sql.Selector) @@ -210,6 +214,50 @@ func (_q *UserQuery) QueryImages() *ImageQuery { return query } +// QueryHosts chains the current query on the "hosts" edge. +func (_q *UserQuery) QueryHosts() *HostQuery { + query := (&HostClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, selector), + sqlgraph.To(host.Table, host.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, user.HostsTable, user.HostsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryVms chains the current query on the "vms" edge. +func (_q *UserQuery) QueryVms() *VirtualMachineQuery { + query := (&VirtualMachineClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, selector), + sqlgraph.To(virtualmachine.Table, virtualmachine.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, user.VmsTable, user.VmsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + // QueryTeamMembers chains the current query on the "team_members" edge. func (_q *UserQuery) QueryTeamMembers() *TeamMemberQuery { query := (&TeamMemberClient{config: _q.config}).Query() @@ -452,6 +500,8 @@ func (_q *UserQuery) Clone() *UserQuery { withGroups: _q.withGroups.Clone(), withModels: _q.withModels.Clone(), withImages: _q.withImages.Clone(), + withHosts: _q.withHosts.Clone(), + withVms: _q.withVms.Clone(), withTeamMembers: _q.withTeamMembers.Clone(), withTeamGroupMembers: _q.withTeamGroupMembers.Clone(), // clone intermediate query. @@ -527,6 +577,28 @@ func (_q *UserQuery) WithImages(opts ...func(*ImageQuery)) *UserQuery { return _q } +// WithHosts tells the query-builder to eager-load the nodes that are connected to +// the "hosts" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *UserQuery) WithHosts(opts ...func(*HostQuery)) *UserQuery { + query := (&HostClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withHosts = query + return _q +} + +// WithVms tells the query-builder to eager-load the nodes that are connected to +// the "vms" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *UserQuery) WithVms(opts ...func(*VirtualMachineQuery)) *UserQuery { + query := (&VirtualMachineClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withVms = query + return _q +} + // WithTeamMembers tells the query-builder to eager-load the nodes that are connected to // the "team_members" edge. The optional arguments are used to configure the query builder of the edge. func (_q *UserQuery) WithTeamMembers(opts ...func(*TeamMemberQuery)) *UserQuery { @@ -627,13 +699,15 @@ func (_q *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e var ( nodes = []*User{} _spec = _q.querySpec() - loadedTypes = [8]bool{ + loadedTypes = [10]bool{ _q.withIdentities != nil, _q.withAudits != nil, _q.withTeams != nil, _q.withGroups != nil, _q.withModels != nil, _q.withImages != nil, + _q.withHosts != nil, + _q.withVms != nil, _q.withTeamMembers != nil, _q.withTeamGroupMembers != nil, } @@ -701,6 +775,20 @@ func (_q *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, e return nil, err } } + if query := _q.withHosts; query != nil { + if err := _q.loadHosts(ctx, query, nodes, + func(n *User) { n.Edges.Hosts = []*Host{} }, + func(n *User, e *Host) { n.Edges.Hosts = append(n.Edges.Hosts, e) }); err != nil { + return nil, err + } + } + if query := _q.withVms; query != nil { + if err := _q.loadVms(ctx, query, nodes, + func(n *User) { n.Edges.Vms = []*VirtualMachine{} }, + func(n *User, e *VirtualMachine) { n.Edges.Vms = append(n.Edges.Vms, e) }); err != nil { + return nil, err + } + } if query := _q.withTeamMembers; query != nil { if err := _q.loadTeamMembers(ctx, query, nodes, func(n *User) { n.Edges.TeamMembers = []*TeamMember{} }, @@ -960,6 +1048,66 @@ func (_q *UserQuery) loadImages(ctx context.Context, query *ImageQuery, nodes [] } return nil } +func (_q *UserQuery) loadHosts(ctx context.Context, query *HostQuery, nodes []*User, init func(*User), assign func(*User, *Host)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[uuid.UUID]*User) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(host.FieldUserID) + } + query.Where(predicate.Host(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(user.HostsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.UserID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "user_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (_q *UserQuery) loadVms(ctx context.Context, query *VirtualMachineQuery, nodes []*User, init func(*User), assign func(*User, *VirtualMachine)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[uuid.UUID]*User) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(virtualmachine.FieldUserID) + } + query.Where(predicate.VirtualMachine(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(user.VmsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.UserID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "user_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} func (_q *UserQuery) loadTeamMembers(ctx context.Context, query *TeamMemberQuery, nodes []*User, init func(*User), assign func(*User, *TeamMember)) error { fks := make([]driver.Value, 0, len(nodes)) nodeids := make(map[uuid.UUID]*User) diff --git a/backend/db/user_update.go b/backend/db/user_update.go index 4c757247..1728d0aa 100644 --- a/backend/db/user_update.go +++ b/backend/db/user_update.go @@ -13,6 +13,7 @@ import ( "entgo.io/ent/schema/field" "github.com/chaitin/MonkeyCode/backend/consts" "github.com/chaitin/MonkeyCode/backend/db/audit" + "github.com/chaitin/MonkeyCode/backend/db/host" "github.com/chaitin/MonkeyCode/backend/db/image" "github.com/chaitin/MonkeyCode/backend/db/model" "github.com/chaitin/MonkeyCode/backend/db/predicate" @@ -22,6 +23,7 @@ import ( "github.com/chaitin/MonkeyCode/backend/db/teammember" "github.com/chaitin/MonkeyCode/backend/db/user" "github.com/chaitin/MonkeyCode/backend/db/useridentity" + "github.com/chaitin/MonkeyCode/backend/db/virtualmachine" "github.com/google/uuid" ) @@ -297,6 +299,36 @@ func (_u *UserUpdate) AddImages(v ...*Image) *UserUpdate { return _u.AddImageIDs(ids...) } +// AddHostIDs adds the "hosts" edge to the Host entity by IDs. +func (_u *UserUpdate) AddHostIDs(ids ...string) *UserUpdate { + _u.mutation.AddHostIDs(ids...) + return _u +} + +// AddHosts adds the "hosts" edges to the Host entity. +func (_u *UserUpdate) AddHosts(v ...*Host) *UserUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddHostIDs(ids...) +} + +// AddVMIDs adds the "vms" edge to the VirtualMachine entity by IDs. +func (_u *UserUpdate) AddVMIDs(ids ...string) *UserUpdate { + _u.mutation.AddVMIDs(ids...) + return _u +} + +// AddVms adds the "vms" edges to the VirtualMachine entity. +func (_u *UserUpdate) AddVms(v ...*VirtualMachine) *UserUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddVMIDs(ids...) +} + // AddTeamMemberIDs adds the "team_members" edge to the TeamMember entity by IDs. func (_u *UserUpdate) AddTeamMemberIDs(ids ...uuid.UUID) *UserUpdate { _u.mutation.AddTeamMemberIDs(ids...) @@ -458,6 +490,48 @@ func (_u *UserUpdate) RemoveImages(v ...*Image) *UserUpdate { return _u.RemoveImageIDs(ids...) } +// ClearHosts clears all "hosts" edges to the Host entity. +func (_u *UserUpdate) ClearHosts() *UserUpdate { + _u.mutation.ClearHosts() + return _u +} + +// RemoveHostIDs removes the "hosts" edge to Host entities by IDs. +func (_u *UserUpdate) RemoveHostIDs(ids ...string) *UserUpdate { + _u.mutation.RemoveHostIDs(ids...) + return _u +} + +// RemoveHosts removes "hosts" edges to Host entities. +func (_u *UserUpdate) RemoveHosts(v ...*Host) *UserUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveHostIDs(ids...) +} + +// ClearVms clears all "vms" edges to the VirtualMachine entity. +func (_u *UserUpdate) ClearVms() *UserUpdate { + _u.mutation.ClearVms() + return _u +} + +// RemoveVMIDs removes the "vms" edge to VirtualMachine entities by IDs. +func (_u *UserUpdate) RemoveVMIDs(ids ...string) *UserUpdate { + _u.mutation.RemoveVMIDs(ids...) + return _u +} + +// RemoveVms removes "vms" edges to VirtualMachine entities. +func (_u *UserUpdate) RemoveVms(v ...*VirtualMachine) *UserUpdate { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveVMIDs(ids...) +} + // ClearTeamMembers clears all "team_members" edges to the TeamMember entity. func (_u *UserUpdate) ClearTeamMembers() *UserUpdate { _u.mutation.ClearTeamMembers() @@ -912,6 +986,96 @@ func (_u *UserUpdate) sqlSave(ctx context.Context) (_node int, err error) { } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if _u.mutation.HostsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.HostsTable, + Columns: []string{user.HostsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedHostsIDs(); len(nodes) > 0 && !_u.mutation.HostsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.HostsTable, + Columns: []string{user.HostsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.HostsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.HostsTable, + Columns: []string{user.HostsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.VmsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.VmsTable, + Columns: []string{user.VmsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(virtualmachine.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedVmsIDs(); len(nodes) > 0 && !_u.mutation.VmsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.VmsTable, + Columns: []string{user.VmsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(virtualmachine.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.VmsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.VmsTable, + Columns: []string{user.VmsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(virtualmachine.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if _u.mutation.TeamMembersCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, @@ -1282,6 +1446,36 @@ func (_u *UserUpdateOne) AddImages(v ...*Image) *UserUpdateOne { return _u.AddImageIDs(ids...) } +// AddHostIDs adds the "hosts" edge to the Host entity by IDs. +func (_u *UserUpdateOne) AddHostIDs(ids ...string) *UserUpdateOne { + _u.mutation.AddHostIDs(ids...) + return _u +} + +// AddHosts adds the "hosts" edges to the Host entity. +func (_u *UserUpdateOne) AddHosts(v ...*Host) *UserUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddHostIDs(ids...) +} + +// AddVMIDs adds the "vms" edge to the VirtualMachine entity by IDs. +func (_u *UserUpdateOne) AddVMIDs(ids ...string) *UserUpdateOne { + _u.mutation.AddVMIDs(ids...) + return _u +} + +// AddVms adds the "vms" edges to the VirtualMachine entity. +func (_u *UserUpdateOne) AddVms(v ...*VirtualMachine) *UserUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddVMIDs(ids...) +} + // AddTeamMemberIDs adds the "team_members" edge to the TeamMember entity by IDs. func (_u *UserUpdateOne) AddTeamMemberIDs(ids ...uuid.UUID) *UserUpdateOne { _u.mutation.AddTeamMemberIDs(ids...) @@ -1443,6 +1637,48 @@ func (_u *UserUpdateOne) RemoveImages(v ...*Image) *UserUpdateOne { return _u.RemoveImageIDs(ids...) } +// ClearHosts clears all "hosts" edges to the Host entity. +func (_u *UserUpdateOne) ClearHosts() *UserUpdateOne { + _u.mutation.ClearHosts() + return _u +} + +// RemoveHostIDs removes the "hosts" edge to Host entities by IDs. +func (_u *UserUpdateOne) RemoveHostIDs(ids ...string) *UserUpdateOne { + _u.mutation.RemoveHostIDs(ids...) + return _u +} + +// RemoveHosts removes "hosts" edges to Host entities. +func (_u *UserUpdateOne) RemoveHosts(v ...*Host) *UserUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveHostIDs(ids...) +} + +// ClearVms clears all "vms" edges to the VirtualMachine entity. +func (_u *UserUpdateOne) ClearVms() *UserUpdateOne { + _u.mutation.ClearVms() + return _u +} + +// RemoveVMIDs removes the "vms" edge to VirtualMachine entities by IDs. +func (_u *UserUpdateOne) RemoveVMIDs(ids ...string) *UserUpdateOne { + _u.mutation.RemoveVMIDs(ids...) + return _u +} + +// RemoveVms removes "vms" edges to VirtualMachine entities. +func (_u *UserUpdateOne) RemoveVms(v ...*VirtualMachine) *UserUpdateOne { + ids := make([]string, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveVMIDs(ids...) +} + // ClearTeamMembers clears all "team_members" edges to the TeamMember entity. func (_u *UserUpdateOne) ClearTeamMembers() *UserUpdateOne { _u.mutation.ClearTeamMembers() @@ -1927,6 +2163,96 @@ func (_u *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) { } _spec.Edges.Add = append(_spec.Edges.Add, edge) } + if _u.mutation.HostsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.HostsTable, + Columns: []string{user.HostsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedHostsIDs(); len(nodes) > 0 && !_u.mutation.HostsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.HostsTable, + Columns: []string{user.HostsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.HostsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.HostsTable, + Columns: []string{user.HostsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.VmsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.VmsTable, + Columns: []string{user.VmsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(virtualmachine.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedVmsIDs(); len(nodes) > 0 && !_u.mutation.VmsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.VmsTable, + Columns: []string{user.VmsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(virtualmachine.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.VmsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: user.VmsTable, + Columns: []string{user.VmsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(virtualmachine.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } if _u.mutation.TeamMembersCleared() { edge := &sqlgraph.EdgeSpec{ Rel: sqlgraph.O2M, diff --git a/backend/db/virtualmachine.go b/backend/db/virtualmachine.go new file mode 100644 index 00000000..31456bfb --- /dev/null +++ b/backend/db/virtualmachine.go @@ -0,0 +1,438 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "encoding/json" + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/chaitin/MonkeyCode/backend/consts" + "github.com/chaitin/MonkeyCode/backend/db/host" + "github.com/chaitin/MonkeyCode/backend/db/model" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/virtualmachine" + "github.com/chaitin/MonkeyCode/backend/ent/types" + "github.com/google/uuid" +) + +// VirtualMachine is the model entity for the VirtualMachine schema. +type VirtualMachine struct { + config `json:"-"` + // ID of the ent. + ID string `json:"id,omitempty"` + // DeletedAt holds the value of the "deleted_at" field. + DeletedAt time.Time `json:"deleted_at,omitempty"` + // HostID holds the value of the "host_id" field. + HostID string `json:"host_id,omitempty"` + // UserID holds the value of the "user_id" field. + UserID uuid.UUID `json:"user_id,omitempty"` + // ModelID holds the value of the "model_id" field. + ModelID uuid.UUID `json:"model_id,omitempty"` + // EnvironmentID holds the value of the "environment_id" field. + EnvironmentID string `json:"environment_id,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Hostname holds the value of the "hostname" field. + Hostname string `json:"hostname,omitempty"` + // Arch holds the value of the "arch" field. + Arch string `json:"arch,omitempty"` + // Cores holds the value of the "cores" field. + Cores int `json:"cores,omitempty"` + // Memory holds the value of the "memory" field. + Memory int64 `json:"memory,omitempty"` + // Os holds the value of the "os" field. + Os string `json:"os,omitempty"` + // ExternalIP holds the value of the "external_ip" field. + ExternalIP string `json:"external_ip,omitempty"` + // InternalIP holds the value of the "internal_ip" field. + InternalIP string `json:"internal_ip,omitempty"` + // TTLKind holds the value of the "ttl_kind" field. + TTLKind consts.VirtualmachineTTLKind `json:"ttl_kind,omitempty"` + // TTL holds the value of the "ttl" field. + TTL int64 `json:"ttl,omitempty"` + // Version holds the value of the "version" field. + Version string `json:"version,omitempty"` + // MachineID holds the value of the "machine_id" field. + MachineID string `json:"machine_id,omitempty"` + // RepoURL holds the value of the "repo_url" field. + RepoURL string `json:"repo_url,omitempty"` + // RepoFilename holds the value of the "repo_filename" field. + RepoFilename string `json:"repo_filename,omitempty"` + // Branch holds the value of the "branch" field. + Branch string `json:"branch,omitempty"` + // IsRecycled holds the value of the "is_recycled" field. + IsRecycled bool `json:"is_recycled,omitempty"` + // Conditions holds the value of the "conditions" field. + Conditions *types.VirtualMachineCondition `json:"conditions,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"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the VirtualMachineQuery when eager-loading is set. + Edges VirtualMachineEdges `json:"edges"` + selectValues sql.SelectValues +} + +// VirtualMachineEdges holds the relations/edges for other nodes in the graph. +type VirtualMachineEdges struct { + // Host holds the value of the host edge. + Host *Host `json:"host,omitempty"` + // Model holds the value of the model edge. + Model *Model `json:"model,omitempty"` + // User holds the value of the user edge. + User *User `json:"user,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [3]bool +} + +// HostOrErr returns the Host value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e VirtualMachineEdges) HostOrErr() (*Host, error) { + if e.Host != nil { + return e.Host, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: host.Label} + } + return nil, &NotLoadedError{edge: "host"} +} + +// ModelOrErr returns the Model value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e VirtualMachineEdges) ModelOrErr() (*Model, error) { + if e.Model != nil { + return e.Model, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: model.Label} + } + return nil, &NotLoadedError{edge: "model"} +} + +// UserOrErr returns the User value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e VirtualMachineEdges) UserOrErr() (*User, error) { + if e.User != nil { + return e.User, nil + } else if e.loadedTypes[2] { + return nil, &NotFoundError{label: user.Label} + } + return nil, &NotLoadedError{edge: "user"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*VirtualMachine) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case virtualmachine.FieldConditions: + values[i] = new([]byte) + case virtualmachine.FieldIsRecycled: + values[i] = new(sql.NullBool) + case virtualmachine.FieldCores, virtualmachine.FieldMemory, virtualmachine.FieldTTL: + values[i] = new(sql.NullInt64) + case virtualmachine.FieldID, virtualmachine.FieldHostID, virtualmachine.FieldEnvironmentID, virtualmachine.FieldName, virtualmachine.FieldHostname, virtualmachine.FieldArch, virtualmachine.FieldOs, virtualmachine.FieldExternalIP, virtualmachine.FieldInternalIP, virtualmachine.FieldTTLKind, virtualmachine.FieldVersion, virtualmachine.FieldMachineID, virtualmachine.FieldRepoURL, virtualmachine.FieldRepoFilename, virtualmachine.FieldBranch: + values[i] = new(sql.NullString) + case virtualmachine.FieldDeletedAt, virtualmachine.FieldCreatedAt, virtualmachine.FieldUpdatedAt: + values[i] = new(sql.NullTime) + case virtualmachine.FieldUserID, virtualmachine.FieldModelID: + values[i] = new(uuid.UUID) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the VirtualMachine fields. +func (_m *VirtualMachine) 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 virtualmachine.FieldID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field id", values[i]) + } else if value.Valid { + _m.ID = value.String + } + case virtualmachine.FieldDeletedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field deleted_at", values[i]) + } else if value.Valid { + _m.DeletedAt = value.Time + } + case virtualmachine.FieldHostID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field host_id", values[i]) + } else if value.Valid { + _m.HostID = value.String + } + case virtualmachine.FieldUserID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field user_id", values[i]) + } else if value != nil { + _m.UserID = *value + } + case virtualmachine.FieldModelID: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field model_id", values[i]) + } else if value != nil { + _m.ModelID = *value + } + case virtualmachine.FieldEnvironmentID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field environment_id", values[i]) + } else if value.Valid { + _m.EnvironmentID = value.String + } + case virtualmachine.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + _m.Name = value.String + } + case virtualmachine.FieldHostname: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field hostname", values[i]) + } else if value.Valid { + _m.Hostname = value.String + } + case virtualmachine.FieldArch: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field arch", values[i]) + } else if value.Valid { + _m.Arch = value.String + } + case virtualmachine.FieldCores: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field cores", values[i]) + } else if value.Valid { + _m.Cores = int(value.Int64) + } + case virtualmachine.FieldMemory: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field memory", values[i]) + } else if value.Valid { + _m.Memory = value.Int64 + } + case virtualmachine.FieldOs: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field os", values[i]) + } else if value.Valid { + _m.Os = value.String + } + case virtualmachine.FieldExternalIP: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field external_ip", values[i]) + } else if value.Valid { + _m.ExternalIP = value.String + } + case virtualmachine.FieldInternalIP: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field internal_ip", values[i]) + } else if value.Valid { + _m.InternalIP = value.String + } + case virtualmachine.FieldTTLKind: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field ttl_kind", values[i]) + } else if value.Valid { + _m.TTLKind = consts.VirtualmachineTTLKind(value.String) + } + case virtualmachine.FieldTTL: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field ttl", values[i]) + } else if value.Valid { + _m.TTL = value.Int64 + } + case virtualmachine.FieldVersion: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field version", values[i]) + } else if value.Valid { + _m.Version = value.String + } + case virtualmachine.FieldMachineID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field machine_id", values[i]) + } else if value.Valid { + _m.MachineID = value.String + } + case virtualmachine.FieldRepoURL: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field repo_url", values[i]) + } else if value.Valid { + _m.RepoURL = value.String + } + case virtualmachine.FieldRepoFilename: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field repo_filename", values[i]) + } else if value.Valid { + _m.RepoFilename = value.String + } + case virtualmachine.FieldBranch: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field branch", values[i]) + } else if value.Valid { + _m.Branch = value.String + } + case virtualmachine.FieldIsRecycled: + if value, ok := values[i].(*sql.NullBool); !ok { + return fmt.Errorf("unexpected type %T for field is_recycled", values[i]) + } else if value.Valid { + _m.IsRecycled = value.Bool + } + case virtualmachine.FieldConditions: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field conditions", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Conditions); err != nil { + return fmt.Errorf("unmarshal field conditions: %w", err) + } + } + case virtualmachine.FieldCreatedAt: + if value, ok := values[i].(*sql.NullTime); !ok { + return fmt.Errorf("unexpected type %T for field created_at", values[i]) + } else if value.Valid { + _m.CreatedAt = value.Time + } + case virtualmachine.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 { + _m.UpdatedAt = value.Time + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the VirtualMachine. +// This includes values selected through modifiers, order, etc. +func (_m *VirtualMachine) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryHost queries the "host" edge of the VirtualMachine entity. +func (_m *VirtualMachine) QueryHost() *HostQuery { + return NewVirtualMachineClient(_m.config).QueryHost(_m) +} + +// QueryModel queries the "model" edge of the VirtualMachine entity. +func (_m *VirtualMachine) QueryModel() *ModelQuery { + return NewVirtualMachineClient(_m.config).QueryModel(_m) +} + +// QueryUser queries the "user" edge of the VirtualMachine entity. +func (_m *VirtualMachine) QueryUser() *UserQuery { + return NewVirtualMachineClient(_m.config).QueryUser(_m) +} + +// Update returns a builder for updating this VirtualMachine. +// Note that you need to call VirtualMachine.Unwrap() before calling this method if this VirtualMachine +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *VirtualMachine) Update() *VirtualMachineUpdateOne { + return NewVirtualMachineClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the VirtualMachine entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (_m *VirtualMachine) Unwrap() *VirtualMachine { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("db: VirtualMachine is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *VirtualMachine) String() string { + var builder strings.Builder + builder.WriteString("VirtualMachine(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("deleted_at=") + builder.WriteString(_m.DeletedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("host_id=") + builder.WriteString(_m.HostID) + builder.WriteString(", ") + builder.WriteString("user_id=") + builder.WriteString(fmt.Sprintf("%v", _m.UserID)) + builder.WriteString(", ") + builder.WriteString("model_id=") + builder.WriteString(fmt.Sprintf("%v", _m.ModelID)) + builder.WriteString(", ") + builder.WriteString("environment_id=") + builder.WriteString(_m.EnvironmentID) + builder.WriteString(", ") + builder.WriteString("name=") + builder.WriteString(_m.Name) + builder.WriteString(", ") + builder.WriteString("hostname=") + builder.WriteString(_m.Hostname) + builder.WriteString(", ") + builder.WriteString("arch=") + builder.WriteString(_m.Arch) + builder.WriteString(", ") + builder.WriteString("cores=") + builder.WriteString(fmt.Sprintf("%v", _m.Cores)) + builder.WriteString(", ") + builder.WriteString("memory=") + builder.WriteString(fmt.Sprintf("%v", _m.Memory)) + builder.WriteString(", ") + builder.WriteString("os=") + builder.WriteString(_m.Os) + builder.WriteString(", ") + builder.WriteString("external_ip=") + builder.WriteString(_m.ExternalIP) + builder.WriteString(", ") + builder.WriteString("internal_ip=") + builder.WriteString(_m.InternalIP) + builder.WriteString(", ") + builder.WriteString("ttl_kind=") + builder.WriteString(fmt.Sprintf("%v", _m.TTLKind)) + builder.WriteString(", ") + builder.WriteString("ttl=") + builder.WriteString(fmt.Sprintf("%v", _m.TTL)) + builder.WriteString(", ") + builder.WriteString("version=") + builder.WriteString(_m.Version) + builder.WriteString(", ") + builder.WriteString("machine_id=") + builder.WriteString(_m.MachineID) + builder.WriteString(", ") + builder.WriteString("repo_url=") + builder.WriteString(_m.RepoURL) + builder.WriteString(", ") + builder.WriteString("repo_filename=") + builder.WriteString(_m.RepoFilename) + builder.WriteString(", ") + builder.WriteString("branch=") + builder.WriteString(_m.Branch) + builder.WriteString(", ") + builder.WriteString("is_recycled=") + builder.WriteString(fmt.Sprintf("%v", _m.IsRecycled)) + builder.WriteString(", ") + builder.WriteString("conditions=") + builder.WriteString(fmt.Sprintf("%v", _m.Conditions)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("updated_at=") + builder.WriteString(_m.UpdatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// VirtualMachines is a parsable slice of VirtualMachine. +type VirtualMachines []*VirtualMachine diff --git a/backend/db/virtualmachine/virtualmachine.go b/backend/db/virtualmachine/virtualmachine.go new file mode 100644 index 00000000..d00914f0 --- /dev/null +++ b/backend/db/virtualmachine/virtualmachine.go @@ -0,0 +1,313 @@ +// Code generated by ent, DO NOT EDIT. + +package virtualmachine + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the virtualmachine type in the database. + Label = "virtual_machine" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldDeletedAt holds the string denoting the deleted_at field in the database. + FieldDeletedAt = "deleted_at" + // FieldHostID holds the string denoting the host_id field in the database. + FieldHostID = "host_id" + // FieldUserID holds the string denoting the user_id field in the database. + FieldUserID = "user_id" + // FieldModelID holds the string denoting the model_id field in the database. + FieldModelID = "model_id" + // FieldEnvironmentID holds the string denoting the environment_id field in the database. + FieldEnvironmentID = "environment_id" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldHostname holds the string denoting the hostname field in the database. + FieldHostname = "hostname" + // FieldArch holds the string denoting the arch field in the database. + FieldArch = "arch" + // FieldCores holds the string denoting the cores field in the database. + FieldCores = "cores" + // FieldMemory holds the string denoting the memory field in the database. + FieldMemory = "memory" + // FieldOs holds the string denoting the os field in the database. + FieldOs = "os" + // FieldExternalIP holds the string denoting the external_ip field in the database. + FieldExternalIP = "external_ip" + // FieldInternalIP holds the string denoting the internal_ip field in the database. + FieldInternalIP = "internal_ip" + // FieldTTLKind holds the string denoting the ttl_kind field in the database. + FieldTTLKind = "ttl_kind" + // FieldTTL holds the string denoting the ttl field in the database. + FieldTTL = "ttl" + // FieldVersion holds the string denoting the version field in the database. + FieldVersion = "version" + // FieldMachineID holds the string denoting the machine_id field in the database. + FieldMachineID = "machine_id" + // FieldRepoURL holds the string denoting the repo_url field in the database. + FieldRepoURL = "repo_url" + // FieldRepoFilename holds the string denoting the repo_filename field in the database. + FieldRepoFilename = "repo_filename" + // FieldBranch holds the string denoting the branch field in the database. + FieldBranch = "branch" + // FieldIsRecycled holds the string denoting the is_recycled field in the database. + FieldIsRecycled = "is_recycled" + // FieldConditions holds the string denoting the conditions field in the database. + FieldConditions = "conditions" + // 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" + // EdgeHost holds the string denoting the host edge name in mutations. + EdgeHost = "host" + // EdgeModel holds the string denoting the model edge name in mutations. + EdgeModel = "model" + // EdgeUser holds the string denoting the user edge name in mutations. + EdgeUser = "user" + // Table holds the table name of the virtualmachine in the database. + Table = "virtualmachines" + // HostTable is the table that holds the host relation/edge. + HostTable = "virtualmachines" + // HostInverseTable is the table name for the Host entity. + // It exists in this package in order to avoid circular dependency with the "host" package. + HostInverseTable = "hosts" + // HostColumn is the table column denoting the host relation/edge. + HostColumn = "host_id" + // ModelTable is the table that holds the model relation/edge. + ModelTable = "virtualmachines" + // ModelInverseTable is the table name for the Model entity. + // It exists in this package in order to avoid circular dependency with the "model" package. + ModelInverseTable = "models" + // ModelColumn is the table column denoting the model relation/edge. + ModelColumn = "model_id" + // UserTable is the table that holds the user relation/edge. + UserTable = "virtualmachines" + // UserInverseTable is the table name for the User entity. + // It exists in this package in order to avoid circular dependency with the "user" package. + UserInverseTable = "users" + // UserColumn is the table column denoting the user relation/edge. + UserColumn = "user_id" +) + +// Columns holds all SQL columns for virtualmachine fields. +var Columns = []string{ + FieldID, + FieldDeletedAt, + FieldHostID, + FieldUserID, + FieldModelID, + FieldEnvironmentID, + FieldName, + FieldHostname, + FieldArch, + FieldCores, + FieldMemory, + FieldOs, + FieldExternalIP, + FieldInternalIP, + FieldTTLKind, + FieldTTL, + FieldVersion, + FieldMachineID, + FieldRepoURL, + FieldRepoFilename, + FieldBranch, + FieldIsRecycled, + FieldConditions, + FieldCreatedAt, + FieldUpdatedAt, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +// Note that the variables below are initialized by the runtime +// package on the initialization of the application. Therefore, +// it should be imported in the main as follows: +// +// import _ "github.com/chaitin/MonkeyCode/backend/db/runtime" +var ( + Hooks [1]ent.Hook + Interceptors [1]ent.Interceptor + // 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 +) + +// OrderOption defines the ordering options for the VirtualMachine queries. +type OrderOption func(*sql.Selector) + +// ByID orders the results by the id field. +func ByID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldID, opts...).ToFunc() +} + +// ByDeletedAt orders the results by the deleted_at field. +func ByDeletedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDeletedAt, opts...).ToFunc() +} + +// ByHostID orders the results by the host_id field. +func ByHostID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldHostID, opts...).ToFunc() +} + +// ByUserID orders the results by the user_id field. +func ByUserID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUserID, opts...).ToFunc() +} + +// ByModelID orders the results by the model_id field. +func ByModelID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldModelID, opts...).ToFunc() +} + +// ByEnvironmentID orders the results by the environment_id field. +func ByEnvironmentID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldEnvironmentID, opts...).ToFunc() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByHostname orders the results by the hostname field. +func ByHostname(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldHostname, opts...).ToFunc() +} + +// ByArch orders the results by the arch field. +func ByArch(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldArch, opts...).ToFunc() +} + +// ByCores orders the results by the cores field. +func ByCores(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCores, opts...).ToFunc() +} + +// ByMemory orders the results by the memory field. +func ByMemory(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMemory, opts...).ToFunc() +} + +// ByOs orders the results by the os field. +func ByOs(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldOs, opts...).ToFunc() +} + +// ByExternalIP orders the results by the external_ip field. +func ByExternalIP(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldExternalIP, opts...).ToFunc() +} + +// ByInternalIP orders the results by the internal_ip field. +func ByInternalIP(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldInternalIP, opts...).ToFunc() +} + +// ByTTLKind orders the results by the ttl_kind field. +func ByTTLKind(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTTLKind, opts...).ToFunc() +} + +// ByTTL orders the results by the ttl field. +func ByTTL(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTTL, opts...).ToFunc() +} + +// ByVersion orders the results by the version field. +func ByVersion(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldVersion, opts...).ToFunc() +} + +// ByMachineID orders the results by the machine_id field. +func ByMachineID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldMachineID, opts...).ToFunc() +} + +// ByRepoURL orders the results by the repo_url field. +func ByRepoURL(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRepoURL, opts...).ToFunc() +} + +// ByRepoFilename orders the results by the repo_filename field. +func ByRepoFilename(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldRepoFilename, opts...).ToFunc() +} + +// ByBranch orders the results by the branch field. +func ByBranch(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldBranch, opts...).ToFunc() +} + +// ByIsRecycled orders the results by the is_recycled field. +func ByIsRecycled(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldIsRecycled, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByUpdatedAt orders the results by the updated_at field. +func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() +} + +// ByHostField orders the results by host field. +func ByHostField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newHostStep(), sql.OrderByField(field, opts...)) + } +} + +// ByModelField orders the results by model field. +func ByModelField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newModelStep(), sql.OrderByField(field, opts...)) + } +} + +// ByUserField orders the results by user field. +func ByUserField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newUserStep(), sql.OrderByField(field, opts...)) + } +} +func newHostStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(HostInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, HostTable, HostColumn), + ) +} +func newModelStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ModelInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ModelTable, ModelColumn), + ) +} +func newUserStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UserInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn), + ) +} diff --git a/backend/db/virtualmachine/where.go b/backend/db/virtualmachine/where.go new file mode 100644 index 00000000..2cfd2117 --- /dev/null +++ b/backend/db/virtualmachine/where.go @@ -0,0 +1,1687 @@ +// Code generated by ent, DO NOT EDIT. + +package virtualmachine + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/chaitin/MonkeyCode/backend/consts" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/google/uuid" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldContainsFold(FieldID, id)) +} + +// DeletedAt applies equality check predicate on the "deleted_at" field. It's identical to DeletedAtEQ. +func DeletedAt(v time.Time) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldDeletedAt, v)) +} + +// HostID applies equality check predicate on the "host_id" field. It's identical to HostIDEQ. +func HostID(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldHostID, v)) +} + +// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. +func UserID(v uuid.UUID) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldUserID, v)) +} + +// ModelID applies equality check predicate on the "model_id" field. It's identical to ModelIDEQ. +func ModelID(v uuid.UUID) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldModelID, v)) +} + +// EnvironmentID applies equality check predicate on the "environment_id" field. It's identical to EnvironmentIDEQ. +func EnvironmentID(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldEnvironmentID, v)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldName, v)) +} + +// Hostname applies equality check predicate on the "hostname" field. It's identical to HostnameEQ. +func Hostname(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldHostname, v)) +} + +// Arch applies equality check predicate on the "arch" field. It's identical to ArchEQ. +func Arch(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldArch, v)) +} + +// Cores applies equality check predicate on the "cores" field. It's identical to CoresEQ. +func Cores(v int) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldCores, v)) +} + +// Memory applies equality check predicate on the "memory" field. It's identical to MemoryEQ. +func Memory(v int64) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldMemory, v)) +} + +// Os applies equality check predicate on the "os" field. It's identical to OsEQ. +func Os(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldOs, v)) +} + +// ExternalIP applies equality check predicate on the "external_ip" field. It's identical to ExternalIPEQ. +func ExternalIP(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldExternalIP, v)) +} + +// InternalIP applies equality check predicate on the "internal_ip" field. It's identical to InternalIPEQ. +func InternalIP(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldInternalIP, v)) +} + +// TTLKind applies equality check predicate on the "ttl_kind" field. It's identical to TTLKindEQ. +func TTLKind(v consts.VirtualmachineTTLKind) predicate.VirtualMachine { + vc := string(v) + return predicate.VirtualMachine(sql.FieldEQ(FieldTTLKind, vc)) +} + +// TTL applies equality check predicate on the "ttl" field. It's identical to TTLEQ. +func TTL(v int64) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldTTL, v)) +} + +// Version applies equality check predicate on the "version" field. It's identical to VersionEQ. +func Version(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldVersion, v)) +} + +// MachineID applies equality check predicate on the "machine_id" field. It's identical to MachineIDEQ. +func MachineID(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldMachineID, v)) +} + +// RepoURL applies equality check predicate on the "repo_url" field. It's identical to RepoURLEQ. +func RepoURL(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldRepoURL, v)) +} + +// RepoFilename applies equality check predicate on the "repo_filename" field. It's identical to RepoFilenameEQ. +func RepoFilename(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldRepoFilename, v)) +} + +// Branch applies equality check predicate on the "branch" field. It's identical to BranchEQ. +func Branch(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldBranch, v)) +} + +// IsRecycled applies equality check predicate on the "is_recycled" field. It's identical to IsRecycledEQ. +func IsRecycled(v bool) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldIsRecycled, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldCreatedAt, v)) +} + +// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. +func UpdatedAt(v time.Time) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// DeletedAtEQ applies the EQ predicate on the "deleted_at" field. +func DeletedAtEQ(v time.Time) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldDeletedAt, v)) +} + +// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field. +func DeletedAtNEQ(v time.Time) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNEQ(FieldDeletedAt, v)) +} + +// DeletedAtIn applies the In predicate on the "deleted_at" field. +func DeletedAtIn(vs ...time.Time) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIn(FieldDeletedAt, vs...)) +} + +// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field. +func DeletedAtNotIn(vs ...time.Time) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotIn(FieldDeletedAt, vs...)) +} + +// DeletedAtGT applies the GT predicate on the "deleted_at" field. +func DeletedAtGT(v time.Time) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGT(FieldDeletedAt, v)) +} + +// DeletedAtGTE applies the GTE predicate on the "deleted_at" field. +func DeletedAtGTE(v time.Time) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGTE(FieldDeletedAt, v)) +} + +// DeletedAtLT applies the LT predicate on the "deleted_at" field. +func DeletedAtLT(v time.Time) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLT(FieldDeletedAt, v)) +} + +// DeletedAtLTE applies the LTE predicate on the "deleted_at" field. +func DeletedAtLTE(v time.Time) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLTE(FieldDeletedAt, v)) +} + +// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field. +func DeletedAtIsNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIsNull(FieldDeletedAt)) +} + +// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field. +func DeletedAtNotNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotNull(FieldDeletedAt)) +} + +// HostIDEQ applies the EQ predicate on the "host_id" field. +func HostIDEQ(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldHostID, v)) +} + +// HostIDNEQ applies the NEQ predicate on the "host_id" field. +func HostIDNEQ(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNEQ(FieldHostID, v)) +} + +// HostIDIn applies the In predicate on the "host_id" field. +func HostIDIn(vs ...string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIn(FieldHostID, vs...)) +} + +// HostIDNotIn applies the NotIn predicate on the "host_id" field. +func HostIDNotIn(vs ...string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotIn(FieldHostID, vs...)) +} + +// HostIDGT applies the GT predicate on the "host_id" field. +func HostIDGT(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGT(FieldHostID, v)) +} + +// HostIDGTE applies the GTE predicate on the "host_id" field. +func HostIDGTE(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGTE(FieldHostID, v)) +} + +// HostIDLT applies the LT predicate on the "host_id" field. +func HostIDLT(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLT(FieldHostID, v)) +} + +// HostIDLTE applies the LTE predicate on the "host_id" field. +func HostIDLTE(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLTE(FieldHostID, v)) +} + +// HostIDContains applies the Contains predicate on the "host_id" field. +func HostIDContains(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldContains(FieldHostID, v)) +} + +// HostIDHasPrefix applies the HasPrefix predicate on the "host_id" field. +func HostIDHasPrefix(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldHasPrefix(FieldHostID, v)) +} + +// HostIDHasSuffix applies the HasSuffix predicate on the "host_id" field. +func HostIDHasSuffix(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldHasSuffix(FieldHostID, v)) +} + +// HostIDEqualFold applies the EqualFold predicate on the "host_id" field. +func HostIDEqualFold(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEqualFold(FieldHostID, v)) +} + +// HostIDContainsFold applies the ContainsFold predicate on the "host_id" field. +func HostIDContainsFold(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldContainsFold(FieldHostID, v)) +} + +// UserIDEQ applies the EQ predicate on the "user_id" field. +func UserIDEQ(v uuid.UUID) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldUserID, v)) +} + +// UserIDNEQ applies the NEQ predicate on the "user_id" field. +func UserIDNEQ(v uuid.UUID) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNEQ(FieldUserID, v)) +} + +// UserIDIn applies the In predicate on the "user_id" field. +func UserIDIn(vs ...uuid.UUID) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIn(FieldUserID, vs...)) +} + +// UserIDNotIn applies the NotIn predicate on the "user_id" field. +func UserIDNotIn(vs ...uuid.UUID) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotIn(FieldUserID, vs...)) +} + +// UserIDIsNil applies the IsNil predicate on the "user_id" field. +func UserIDIsNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIsNull(FieldUserID)) +} + +// UserIDNotNil applies the NotNil predicate on the "user_id" field. +func UserIDNotNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotNull(FieldUserID)) +} + +// ModelIDEQ applies the EQ predicate on the "model_id" field. +func ModelIDEQ(v uuid.UUID) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldModelID, v)) +} + +// ModelIDNEQ applies the NEQ predicate on the "model_id" field. +func ModelIDNEQ(v uuid.UUID) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNEQ(FieldModelID, v)) +} + +// ModelIDIn applies the In predicate on the "model_id" field. +func ModelIDIn(vs ...uuid.UUID) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIn(FieldModelID, vs...)) +} + +// ModelIDNotIn applies the NotIn predicate on the "model_id" field. +func ModelIDNotIn(vs ...uuid.UUID) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotIn(FieldModelID, vs...)) +} + +// ModelIDIsNil applies the IsNil predicate on the "model_id" field. +func ModelIDIsNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIsNull(FieldModelID)) +} + +// ModelIDNotNil applies the NotNil predicate on the "model_id" field. +func ModelIDNotNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotNull(FieldModelID)) +} + +// EnvironmentIDEQ applies the EQ predicate on the "environment_id" field. +func EnvironmentIDEQ(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldEnvironmentID, v)) +} + +// EnvironmentIDNEQ applies the NEQ predicate on the "environment_id" field. +func EnvironmentIDNEQ(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNEQ(FieldEnvironmentID, v)) +} + +// EnvironmentIDIn applies the In predicate on the "environment_id" field. +func EnvironmentIDIn(vs ...string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIn(FieldEnvironmentID, vs...)) +} + +// EnvironmentIDNotIn applies the NotIn predicate on the "environment_id" field. +func EnvironmentIDNotIn(vs ...string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotIn(FieldEnvironmentID, vs...)) +} + +// EnvironmentIDGT applies the GT predicate on the "environment_id" field. +func EnvironmentIDGT(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGT(FieldEnvironmentID, v)) +} + +// EnvironmentIDGTE applies the GTE predicate on the "environment_id" field. +func EnvironmentIDGTE(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGTE(FieldEnvironmentID, v)) +} + +// EnvironmentIDLT applies the LT predicate on the "environment_id" field. +func EnvironmentIDLT(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLT(FieldEnvironmentID, v)) +} + +// EnvironmentIDLTE applies the LTE predicate on the "environment_id" field. +func EnvironmentIDLTE(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLTE(FieldEnvironmentID, v)) +} + +// EnvironmentIDContains applies the Contains predicate on the "environment_id" field. +func EnvironmentIDContains(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldContains(FieldEnvironmentID, v)) +} + +// EnvironmentIDHasPrefix applies the HasPrefix predicate on the "environment_id" field. +func EnvironmentIDHasPrefix(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldHasPrefix(FieldEnvironmentID, v)) +} + +// EnvironmentIDHasSuffix applies the HasSuffix predicate on the "environment_id" field. +func EnvironmentIDHasSuffix(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldHasSuffix(FieldEnvironmentID, v)) +} + +// EnvironmentIDIsNil applies the IsNil predicate on the "environment_id" field. +func EnvironmentIDIsNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIsNull(FieldEnvironmentID)) +} + +// EnvironmentIDNotNil applies the NotNil predicate on the "environment_id" field. +func EnvironmentIDNotNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotNull(FieldEnvironmentID)) +} + +// EnvironmentIDEqualFold applies the EqualFold predicate on the "environment_id" field. +func EnvironmentIDEqualFold(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEqualFold(FieldEnvironmentID, v)) +} + +// EnvironmentIDContainsFold applies the ContainsFold predicate on the "environment_id" field. +func EnvironmentIDContainsFold(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldContainsFold(FieldEnvironmentID, v)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldContainsFold(FieldName, v)) +} + +// HostnameEQ applies the EQ predicate on the "hostname" field. +func HostnameEQ(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldHostname, v)) +} + +// HostnameNEQ applies the NEQ predicate on the "hostname" field. +func HostnameNEQ(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNEQ(FieldHostname, v)) +} + +// HostnameIn applies the In predicate on the "hostname" field. +func HostnameIn(vs ...string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIn(FieldHostname, vs...)) +} + +// HostnameNotIn applies the NotIn predicate on the "hostname" field. +func HostnameNotIn(vs ...string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotIn(FieldHostname, vs...)) +} + +// HostnameGT applies the GT predicate on the "hostname" field. +func HostnameGT(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGT(FieldHostname, v)) +} + +// HostnameGTE applies the GTE predicate on the "hostname" field. +func HostnameGTE(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGTE(FieldHostname, v)) +} + +// HostnameLT applies the LT predicate on the "hostname" field. +func HostnameLT(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLT(FieldHostname, v)) +} + +// HostnameLTE applies the LTE predicate on the "hostname" field. +func HostnameLTE(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLTE(FieldHostname, v)) +} + +// HostnameContains applies the Contains predicate on the "hostname" field. +func HostnameContains(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldContains(FieldHostname, v)) +} + +// HostnameHasPrefix applies the HasPrefix predicate on the "hostname" field. +func HostnameHasPrefix(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldHasPrefix(FieldHostname, v)) +} + +// HostnameHasSuffix applies the HasSuffix predicate on the "hostname" field. +func HostnameHasSuffix(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldHasSuffix(FieldHostname, v)) +} + +// HostnameIsNil applies the IsNil predicate on the "hostname" field. +func HostnameIsNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIsNull(FieldHostname)) +} + +// HostnameNotNil applies the NotNil predicate on the "hostname" field. +func HostnameNotNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotNull(FieldHostname)) +} + +// HostnameEqualFold applies the EqualFold predicate on the "hostname" field. +func HostnameEqualFold(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEqualFold(FieldHostname, v)) +} + +// HostnameContainsFold applies the ContainsFold predicate on the "hostname" field. +func HostnameContainsFold(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldContainsFold(FieldHostname, v)) +} + +// ArchEQ applies the EQ predicate on the "arch" field. +func ArchEQ(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldArch, v)) +} + +// ArchNEQ applies the NEQ predicate on the "arch" field. +func ArchNEQ(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNEQ(FieldArch, v)) +} + +// ArchIn applies the In predicate on the "arch" field. +func ArchIn(vs ...string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIn(FieldArch, vs...)) +} + +// ArchNotIn applies the NotIn predicate on the "arch" field. +func ArchNotIn(vs ...string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotIn(FieldArch, vs...)) +} + +// ArchGT applies the GT predicate on the "arch" field. +func ArchGT(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGT(FieldArch, v)) +} + +// ArchGTE applies the GTE predicate on the "arch" field. +func ArchGTE(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGTE(FieldArch, v)) +} + +// ArchLT applies the LT predicate on the "arch" field. +func ArchLT(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLT(FieldArch, v)) +} + +// ArchLTE applies the LTE predicate on the "arch" field. +func ArchLTE(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLTE(FieldArch, v)) +} + +// ArchContains applies the Contains predicate on the "arch" field. +func ArchContains(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldContains(FieldArch, v)) +} + +// ArchHasPrefix applies the HasPrefix predicate on the "arch" field. +func ArchHasPrefix(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldHasPrefix(FieldArch, v)) +} + +// ArchHasSuffix applies the HasSuffix predicate on the "arch" field. +func ArchHasSuffix(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldHasSuffix(FieldArch, v)) +} + +// ArchIsNil applies the IsNil predicate on the "arch" field. +func ArchIsNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIsNull(FieldArch)) +} + +// ArchNotNil applies the NotNil predicate on the "arch" field. +func ArchNotNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotNull(FieldArch)) +} + +// ArchEqualFold applies the EqualFold predicate on the "arch" field. +func ArchEqualFold(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEqualFold(FieldArch, v)) +} + +// ArchContainsFold applies the ContainsFold predicate on the "arch" field. +func ArchContainsFold(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldContainsFold(FieldArch, v)) +} + +// CoresEQ applies the EQ predicate on the "cores" field. +func CoresEQ(v int) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldCores, v)) +} + +// CoresNEQ applies the NEQ predicate on the "cores" field. +func CoresNEQ(v int) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNEQ(FieldCores, v)) +} + +// CoresIn applies the In predicate on the "cores" field. +func CoresIn(vs ...int) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIn(FieldCores, vs...)) +} + +// CoresNotIn applies the NotIn predicate on the "cores" field. +func CoresNotIn(vs ...int) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotIn(FieldCores, vs...)) +} + +// CoresGT applies the GT predicate on the "cores" field. +func CoresGT(v int) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGT(FieldCores, v)) +} + +// CoresGTE applies the GTE predicate on the "cores" field. +func CoresGTE(v int) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGTE(FieldCores, v)) +} + +// CoresLT applies the LT predicate on the "cores" field. +func CoresLT(v int) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLT(FieldCores, v)) +} + +// CoresLTE applies the LTE predicate on the "cores" field. +func CoresLTE(v int) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLTE(FieldCores, v)) +} + +// CoresIsNil applies the IsNil predicate on the "cores" field. +func CoresIsNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIsNull(FieldCores)) +} + +// CoresNotNil applies the NotNil predicate on the "cores" field. +func CoresNotNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotNull(FieldCores)) +} + +// MemoryEQ applies the EQ predicate on the "memory" field. +func MemoryEQ(v int64) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldMemory, v)) +} + +// MemoryNEQ applies the NEQ predicate on the "memory" field. +func MemoryNEQ(v int64) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNEQ(FieldMemory, v)) +} + +// MemoryIn applies the In predicate on the "memory" field. +func MemoryIn(vs ...int64) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIn(FieldMemory, vs...)) +} + +// MemoryNotIn applies the NotIn predicate on the "memory" field. +func MemoryNotIn(vs ...int64) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotIn(FieldMemory, vs...)) +} + +// MemoryGT applies the GT predicate on the "memory" field. +func MemoryGT(v int64) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGT(FieldMemory, v)) +} + +// MemoryGTE applies the GTE predicate on the "memory" field. +func MemoryGTE(v int64) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGTE(FieldMemory, v)) +} + +// MemoryLT applies the LT predicate on the "memory" field. +func MemoryLT(v int64) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLT(FieldMemory, v)) +} + +// MemoryLTE applies the LTE predicate on the "memory" field. +func MemoryLTE(v int64) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLTE(FieldMemory, v)) +} + +// MemoryIsNil applies the IsNil predicate on the "memory" field. +func MemoryIsNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIsNull(FieldMemory)) +} + +// MemoryNotNil applies the NotNil predicate on the "memory" field. +func MemoryNotNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotNull(FieldMemory)) +} + +// OsEQ applies the EQ predicate on the "os" field. +func OsEQ(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldOs, v)) +} + +// OsNEQ applies the NEQ predicate on the "os" field. +func OsNEQ(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNEQ(FieldOs, v)) +} + +// OsIn applies the In predicate on the "os" field. +func OsIn(vs ...string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIn(FieldOs, vs...)) +} + +// OsNotIn applies the NotIn predicate on the "os" field. +func OsNotIn(vs ...string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotIn(FieldOs, vs...)) +} + +// OsGT applies the GT predicate on the "os" field. +func OsGT(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGT(FieldOs, v)) +} + +// OsGTE applies the GTE predicate on the "os" field. +func OsGTE(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGTE(FieldOs, v)) +} + +// OsLT applies the LT predicate on the "os" field. +func OsLT(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLT(FieldOs, v)) +} + +// OsLTE applies the LTE predicate on the "os" field. +func OsLTE(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLTE(FieldOs, v)) +} + +// OsContains applies the Contains predicate on the "os" field. +func OsContains(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldContains(FieldOs, v)) +} + +// OsHasPrefix applies the HasPrefix predicate on the "os" field. +func OsHasPrefix(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldHasPrefix(FieldOs, v)) +} + +// OsHasSuffix applies the HasSuffix predicate on the "os" field. +func OsHasSuffix(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldHasSuffix(FieldOs, v)) +} + +// OsIsNil applies the IsNil predicate on the "os" field. +func OsIsNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIsNull(FieldOs)) +} + +// OsNotNil applies the NotNil predicate on the "os" field. +func OsNotNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotNull(FieldOs)) +} + +// OsEqualFold applies the EqualFold predicate on the "os" field. +func OsEqualFold(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEqualFold(FieldOs, v)) +} + +// OsContainsFold applies the ContainsFold predicate on the "os" field. +func OsContainsFold(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldContainsFold(FieldOs, v)) +} + +// ExternalIPEQ applies the EQ predicate on the "external_ip" field. +func ExternalIPEQ(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldExternalIP, v)) +} + +// ExternalIPNEQ applies the NEQ predicate on the "external_ip" field. +func ExternalIPNEQ(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNEQ(FieldExternalIP, v)) +} + +// ExternalIPIn applies the In predicate on the "external_ip" field. +func ExternalIPIn(vs ...string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIn(FieldExternalIP, vs...)) +} + +// ExternalIPNotIn applies the NotIn predicate on the "external_ip" field. +func ExternalIPNotIn(vs ...string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotIn(FieldExternalIP, vs...)) +} + +// ExternalIPGT applies the GT predicate on the "external_ip" field. +func ExternalIPGT(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGT(FieldExternalIP, v)) +} + +// ExternalIPGTE applies the GTE predicate on the "external_ip" field. +func ExternalIPGTE(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGTE(FieldExternalIP, v)) +} + +// ExternalIPLT applies the LT predicate on the "external_ip" field. +func ExternalIPLT(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLT(FieldExternalIP, v)) +} + +// ExternalIPLTE applies the LTE predicate on the "external_ip" field. +func ExternalIPLTE(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLTE(FieldExternalIP, v)) +} + +// ExternalIPContains applies the Contains predicate on the "external_ip" field. +func ExternalIPContains(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldContains(FieldExternalIP, v)) +} + +// ExternalIPHasPrefix applies the HasPrefix predicate on the "external_ip" field. +func ExternalIPHasPrefix(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldHasPrefix(FieldExternalIP, v)) +} + +// ExternalIPHasSuffix applies the HasSuffix predicate on the "external_ip" field. +func ExternalIPHasSuffix(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldHasSuffix(FieldExternalIP, v)) +} + +// ExternalIPIsNil applies the IsNil predicate on the "external_ip" field. +func ExternalIPIsNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIsNull(FieldExternalIP)) +} + +// ExternalIPNotNil applies the NotNil predicate on the "external_ip" field. +func ExternalIPNotNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotNull(FieldExternalIP)) +} + +// ExternalIPEqualFold applies the EqualFold predicate on the "external_ip" field. +func ExternalIPEqualFold(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEqualFold(FieldExternalIP, v)) +} + +// ExternalIPContainsFold applies the ContainsFold predicate on the "external_ip" field. +func ExternalIPContainsFold(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldContainsFold(FieldExternalIP, v)) +} + +// InternalIPEQ applies the EQ predicate on the "internal_ip" field. +func InternalIPEQ(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldInternalIP, v)) +} + +// InternalIPNEQ applies the NEQ predicate on the "internal_ip" field. +func InternalIPNEQ(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNEQ(FieldInternalIP, v)) +} + +// InternalIPIn applies the In predicate on the "internal_ip" field. +func InternalIPIn(vs ...string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIn(FieldInternalIP, vs...)) +} + +// InternalIPNotIn applies the NotIn predicate on the "internal_ip" field. +func InternalIPNotIn(vs ...string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotIn(FieldInternalIP, vs...)) +} + +// InternalIPGT applies the GT predicate on the "internal_ip" field. +func InternalIPGT(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGT(FieldInternalIP, v)) +} + +// InternalIPGTE applies the GTE predicate on the "internal_ip" field. +func InternalIPGTE(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGTE(FieldInternalIP, v)) +} + +// InternalIPLT applies the LT predicate on the "internal_ip" field. +func InternalIPLT(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLT(FieldInternalIP, v)) +} + +// InternalIPLTE applies the LTE predicate on the "internal_ip" field. +func InternalIPLTE(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLTE(FieldInternalIP, v)) +} + +// InternalIPContains applies the Contains predicate on the "internal_ip" field. +func InternalIPContains(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldContains(FieldInternalIP, v)) +} + +// InternalIPHasPrefix applies the HasPrefix predicate on the "internal_ip" field. +func InternalIPHasPrefix(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldHasPrefix(FieldInternalIP, v)) +} + +// InternalIPHasSuffix applies the HasSuffix predicate on the "internal_ip" field. +func InternalIPHasSuffix(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldHasSuffix(FieldInternalIP, v)) +} + +// InternalIPIsNil applies the IsNil predicate on the "internal_ip" field. +func InternalIPIsNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIsNull(FieldInternalIP)) +} + +// InternalIPNotNil applies the NotNil predicate on the "internal_ip" field. +func InternalIPNotNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotNull(FieldInternalIP)) +} + +// InternalIPEqualFold applies the EqualFold predicate on the "internal_ip" field. +func InternalIPEqualFold(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEqualFold(FieldInternalIP, v)) +} + +// InternalIPContainsFold applies the ContainsFold predicate on the "internal_ip" field. +func InternalIPContainsFold(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldContainsFold(FieldInternalIP, v)) +} + +// TTLKindEQ applies the EQ predicate on the "ttl_kind" field. +func TTLKindEQ(v consts.VirtualmachineTTLKind) predicate.VirtualMachine { + vc := string(v) + return predicate.VirtualMachine(sql.FieldEQ(FieldTTLKind, vc)) +} + +// TTLKindNEQ applies the NEQ predicate on the "ttl_kind" field. +func TTLKindNEQ(v consts.VirtualmachineTTLKind) predicate.VirtualMachine { + vc := string(v) + return predicate.VirtualMachine(sql.FieldNEQ(FieldTTLKind, vc)) +} + +// TTLKindIn applies the In predicate on the "ttl_kind" field. +func TTLKindIn(vs ...consts.VirtualmachineTTLKind) predicate.VirtualMachine { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.VirtualMachine(sql.FieldIn(FieldTTLKind, v...)) +} + +// TTLKindNotIn applies the NotIn predicate on the "ttl_kind" field. +func TTLKindNotIn(vs ...consts.VirtualmachineTTLKind) predicate.VirtualMachine { + v := make([]any, len(vs)) + for i := range v { + v[i] = string(vs[i]) + } + return predicate.VirtualMachine(sql.FieldNotIn(FieldTTLKind, v...)) +} + +// TTLKindGT applies the GT predicate on the "ttl_kind" field. +func TTLKindGT(v consts.VirtualmachineTTLKind) predicate.VirtualMachine { + vc := string(v) + return predicate.VirtualMachine(sql.FieldGT(FieldTTLKind, vc)) +} + +// TTLKindGTE applies the GTE predicate on the "ttl_kind" field. +func TTLKindGTE(v consts.VirtualmachineTTLKind) predicate.VirtualMachine { + vc := string(v) + return predicate.VirtualMachine(sql.FieldGTE(FieldTTLKind, vc)) +} + +// TTLKindLT applies the LT predicate on the "ttl_kind" field. +func TTLKindLT(v consts.VirtualmachineTTLKind) predicate.VirtualMachine { + vc := string(v) + return predicate.VirtualMachine(sql.FieldLT(FieldTTLKind, vc)) +} + +// TTLKindLTE applies the LTE predicate on the "ttl_kind" field. +func TTLKindLTE(v consts.VirtualmachineTTLKind) predicate.VirtualMachine { + vc := string(v) + return predicate.VirtualMachine(sql.FieldLTE(FieldTTLKind, vc)) +} + +// TTLKindContains applies the Contains predicate on the "ttl_kind" field. +func TTLKindContains(v consts.VirtualmachineTTLKind) predicate.VirtualMachine { + vc := string(v) + return predicate.VirtualMachine(sql.FieldContains(FieldTTLKind, vc)) +} + +// TTLKindHasPrefix applies the HasPrefix predicate on the "ttl_kind" field. +func TTLKindHasPrefix(v consts.VirtualmachineTTLKind) predicate.VirtualMachine { + vc := string(v) + return predicate.VirtualMachine(sql.FieldHasPrefix(FieldTTLKind, vc)) +} + +// TTLKindHasSuffix applies the HasSuffix predicate on the "ttl_kind" field. +func TTLKindHasSuffix(v consts.VirtualmachineTTLKind) predicate.VirtualMachine { + vc := string(v) + return predicate.VirtualMachine(sql.FieldHasSuffix(FieldTTLKind, vc)) +} + +// TTLKindIsNil applies the IsNil predicate on the "ttl_kind" field. +func TTLKindIsNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIsNull(FieldTTLKind)) +} + +// TTLKindNotNil applies the NotNil predicate on the "ttl_kind" field. +func TTLKindNotNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotNull(FieldTTLKind)) +} + +// TTLKindEqualFold applies the EqualFold predicate on the "ttl_kind" field. +func TTLKindEqualFold(v consts.VirtualmachineTTLKind) predicate.VirtualMachine { + vc := string(v) + return predicate.VirtualMachine(sql.FieldEqualFold(FieldTTLKind, vc)) +} + +// TTLKindContainsFold applies the ContainsFold predicate on the "ttl_kind" field. +func TTLKindContainsFold(v consts.VirtualmachineTTLKind) predicate.VirtualMachine { + vc := string(v) + return predicate.VirtualMachine(sql.FieldContainsFold(FieldTTLKind, vc)) +} + +// TTLEQ applies the EQ predicate on the "ttl" field. +func TTLEQ(v int64) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldTTL, v)) +} + +// TTLNEQ applies the NEQ predicate on the "ttl" field. +func TTLNEQ(v int64) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNEQ(FieldTTL, v)) +} + +// TTLIn applies the In predicate on the "ttl" field. +func TTLIn(vs ...int64) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIn(FieldTTL, vs...)) +} + +// TTLNotIn applies the NotIn predicate on the "ttl" field. +func TTLNotIn(vs ...int64) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotIn(FieldTTL, vs...)) +} + +// TTLGT applies the GT predicate on the "ttl" field. +func TTLGT(v int64) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGT(FieldTTL, v)) +} + +// TTLGTE applies the GTE predicate on the "ttl" field. +func TTLGTE(v int64) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGTE(FieldTTL, v)) +} + +// TTLLT applies the LT predicate on the "ttl" field. +func TTLLT(v int64) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLT(FieldTTL, v)) +} + +// TTLLTE applies the LTE predicate on the "ttl" field. +func TTLLTE(v int64) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLTE(FieldTTL, v)) +} + +// TTLIsNil applies the IsNil predicate on the "ttl" field. +func TTLIsNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIsNull(FieldTTL)) +} + +// TTLNotNil applies the NotNil predicate on the "ttl" field. +func TTLNotNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotNull(FieldTTL)) +} + +// VersionEQ applies the EQ predicate on the "version" field. +func VersionEQ(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldVersion, v)) +} + +// VersionNEQ applies the NEQ predicate on the "version" field. +func VersionNEQ(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNEQ(FieldVersion, v)) +} + +// VersionIn applies the In predicate on the "version" field. +func VersionIn(vs ...string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIn(FieldVersion, vs...)) +} + +// VersionNotIn applies the NotIn predicate on the "version" field. +func VersionNotIn(vs ...string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotIn(FieldVersion, vs...)) +} + +// VersionGT applies the GT predicate on the "version" field. +func VersionGT(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGT(FieldVersion, v)) +} + +// VersionGTE applies the GTE predicate on the "version" field. +func VersionGTE(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGTE(FieldVersion, v)) +} + +// VersionLT applies the LT predicate on the "version" field. +func VersionLT(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLT(FieldVersion, v)) +} + +// VersionLTE applies the LTE predicate on the "version" field. +func VersionLTE(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLTE(FieldVersion, v)) +} + +// VersionContains applies the Contains predicate on the "version" field. +func VersionContains(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldContains(FieldVersion, v)) +} + +// VersionHasPrefix applies the HasPrefix predicate on the "version" field. +func VersionHasPrefix(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldHasPrefix(FieldVersion, v)) +} + +// VersionHasSuffix applies the HasSuffix predicate on the "version" field. +func VersionHasSuffix(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldHasSuffix(FieldVersion, v)) +} + +// VersionIsNil applies the IsNil predicate on the "version" field. +func VersionIsNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIsNull(FieldVersion)) +} + +// VersionNotNil applies the NotNil predicate on the "version" field. +func VersionNotNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotNull(FieldVersion)) +} + +// VersionEqualFold applies the EqualFold predicate on the "version" field. +func VersionEqualFold(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEqualFold(FieldVersion, v)) +} + +// VersionContainsFold applies the ContainsFold predicate on the "version" field. +func VersionContainsFold(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldContainsFold(FieldVersion, v)) +} + +// MachineIDEQ applies the EQ predicate on the "machine_id" field. +func MachineIDEQ(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldMachineID, v)) +} + +// MachineIDNEQ applies the NEQ predicate on the "machine_id" field. +func MachineIDNEQ(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNEQ(FieldMachineID, v)) +} + +// MachineIDIn applies the In predicate on the "machine_id" field. +func MachineIDIn(vs ...string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIn(FieldMachineID, vs...)) +} + +// MachineIDNotIn applies the NotIn predicate on the "machine_id" field. +func MachineIDNotIn(vs ...string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotIn(FieldMachineID, vs...)) +} + +// MachineIDGT applies the GT predicate on the "machine_id" field. +func MachineIDGT(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGT(FieldMachineID, v)) +} + +// MachineIDGTE applies the GTE predicate on the "machine_id" field. +func MachineIDGTE(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGTE(FieldMachineID, v)) +} + +// MachineIDLT applies the LT predicate on the "machine_id" field. +func MachineIDLT(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLT(FieldMachineID, v)) +} + +// MachineIDLTE applies the LTE predicate on the "machine_id" field. +func MachineIDLTE(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLTE(FieldMachineID, v)) +} + +// MachineIDContains applies the Contains predicate on the "machine_id" field. +func MachineIDContains(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldContains(FieldMachineID, v)) +} + +// MachineIDHasPrefix applies the HasPrefix predicate on the "machine_id" field. +func MachineIDHasPrefix(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldHasPrefix(FieldMachineID, v)) +} + +// MachineIDHasSuffix applies the HasSuffix predicate on the "machine_id" field. +func MachineIDHasSuffix(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldHasSuffix(FieldMachineID, v)) +} + +// MachineIDIsNil applies the IsNil predicate on the "machine_id" field. +func MachineIDIsNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIsNull(FieldMachineID)) +} + +// MachineIDNotNil applies the NotNil predicate on the "machine_id" field. +func MachineIDNotNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotNull(FieldMachineID)) +} + +// MachineIDEqualFold applies the EqualFold predicate on the "machine_id" field. +func MachineIDEqualFold(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEqualFold(FieldMachineID, v)) +} + +// MachineIDContainsFold applies the ContainsFold predicate on the "machine_id" field. +func MachineIDContainsFold(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldContainsFold(FieldMachineID, v)) +} + +// RepoURLEQ applies the EQ predicate on the "repo_url" field. +func RepoURLEQ(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldRepoURL, v)) +} + +// RepoURLNEQ applies the NEQ predicate on the "repo_url" field. +func RepoURLNEQ(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNEQ(FieldRepoURL, v)) +} + +// RepoURLIn applies the In predicate on the "repo_url" field. +func RepoURLIn(vs ...string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIn(FieldRepoURL, vs...)) +} + +// RepoURLNotIn applies the NotIn predicate on the "repo_url" field. +func RepoURLNotIn(vs ...string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotIn(FieldRepoURL, vs...)) +} + +// RepoURLGT applies the GT predicate on the "repo_url" field. +func RepoURLGT(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGT(FieldRepoURL, v)) +} + +// RepoURLGTE applies the GTE predicate on the "repo_url" field. +func RepoURLGTE(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGTE(FieldRepoURL, v)) +} + +// RepoURLLT applies the LT predicate on the "repo_url" field. +func RepoURLLT(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLT(FieldRepoURL, v)) +} + +// RepoURLLTE applies the LTE predicate on the "repo_url" field. +func RepoURLLTE(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLTE(FieldRepoURL, v)) +} + +// RepoURLContains applies the Contains predicate on the "repo_url" field. +func RepoURLContains(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldContains(FieldRepoURL, v)) +} + +// RepoURLHasPrefix applies the HasPrefix predicate on the "repo_url" field. +func RepoURLHasPrefix(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldHasPrefix(FieldRepoURL, v)) +} + +// RepoURLHasSuffix applies the HasSuffix predicate on the "repo_url" field. +func RepoURLHasSuffix(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldHasSuffix(FieldRepoURL, v)) +} + +// RepoURLIsNil applies the IsNil predicate on the "repo_url" field. +func RepoURLIsNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIsNull(FieldRepoURL)) +} + +// RepoURLNotNil applies the NotNil predicate on the "repo_url" field. +func RepoURLNotNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotNull(FieldRepoURL)) +} + +// RepoURLEqualFold applies the EqualFold predicate on the "repo_url" field. +func RepoURLEqualFold(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEqualFold(FieldRepoURL, v)) +} + +// RepoURLContainsFold applies the ContainsFold predicate on the "repo_url" field. +func RepoURLContainsFold(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldContainsFold(FieldRepoURL, v)) +} + +// RepoFilenameEQ applies the EQ predicate on the "repo_filename" field. +func RepoFilenameEQ(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldRepoFilename, v)) +} + +// RepoFilenameNEQ applies the NEQ predicate on the "repo_filename" field. +func RepoFilenameNEQ(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNEQ(FieldRepoFilename, v)) +} + +// RepoFilenameIn applies the In predicate on the "repo_filename" field. +func RepoFilenameIn(vs ...string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIn(FieldRepoFilename, vs...)) +} + +// RepoFilenameNotIn applies the NotIn predicate on the "repo_filename" field. +func RepoFilenameNotIn(vs ...string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotIn(FieldRepoFilename, vs...)) +} + +// RepoFilenameGT applies the GT predicate on the "repo_filename" field. +func RepoFilenameGT(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGT(FieldRepoFilename, v)) +} + +// RepoFilenameGTE applies the GTE predicate on the "repo_filename" field. +func RepoFilenameGTE(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGTE(FieldRepoFilename, v)) +} + +// RepoFilenameLT applies the LT predicate on the "repo_filename" field. +func RepoFilenameLT(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLT(FieldRepoFilename, v)) +} + +// RepoFilenameLTE applies the LTE predicate on the "repo_filename" field. +func RepoFilenameLTE(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLTE(FieldRepoFilename, v)) +} + +// RepoFilenameContains applies the Contains predicate on the "repo_filename" field. +func RepoFilenameContains(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldContains(FieldRepoFilename, v)) +} + +// RepoFilenameHasPrefix applies the HasPrefix predicate on the "repo_filename" field. +func RepoFilenameHasPrefix(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldHasPrefix(FieldRepoFilename, v)) +} + +// RepoFilenameHasSuffix applies the HasSuffix predicate on the "repo_filename" field. +func RepoFilenameHasSuffix(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldHasSuffix(FieldRepoFilename, v)) +} + +// RepoFilenameIsNil applies the IsNil predicate on the "repo_filename" field. +func RepoFilenameIsNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIsNull(FieldRepoFilename)) +} + +// RepoFilenameNotNil applies the NotNil predicate on the "repo_filename" field. +func RepoFilenameNotNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotNull(FieldRepoFilename)) +} + +// RepoFilenameEqualFold applies the EqualFold predicate on the "repo_filename" field. +func RepoFilenameEqualFold(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEqualFold(FieldRepoFilename, v)) +} + +// RepoFilenameContainsFold applies the ContainsFold predicate on the "repo_filename" field. +func RepoFilenameContainsFold(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldContainsFold(FieldRepoFilename, v)) +} + +// BranchEQ applies the EQ predicate on the "branch" field. +func BranchEQ(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldBranch, v)) +} + +// BranchNEQ applies the NEQ predicate on the "branch" field. +func BranchNEQ(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNEQ(FieldBranch, v)) +} + +// BranchIn applies the In predicate on the "branch" field. +func BranchIn(vs ...string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIn(FieldBranch, vs...)) +} + +// BranchNotIn applies the NotIn predicate on the "branch" field. +func BranchNotIn(vs ...string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotIn(FieldBranch, vs...)) +} + +// BranchGT applies the GT predicate on the "branch" field. +func BranchGT(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGT(FieldBranch, v)) +} + +// BranchGTE applies the GTE predicate on the "branch" field. +func BranchGTE(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGTE(FieldBranch, v)) +} + +// BranchLT applies the LT predicate on the "branch" field. +func BranchLT(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLT(FieldBranch, v)) +} + +// BranchLTE applies the LTE predicate on the "branch" field. +func BranchLTE(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLTE(FieldBranch, v)) +} + +// BranchContains applies the Contains predicate on the "branch" field. +func BranchContains(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldContains(FieldBranch, v)) +} + +// BranchHasPrefix applies the HasPrefix predicate on the "branch" field. +func BranchHasPrefix(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldHasPrefix(FieldBranch, v)) +} + +// BranchHasSuffix applies the HasSuffix predicate on the "branch" field. +func BranchHasSuffix(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldHasSuffix(FieldBranch, v)) +} + +// BranchIsNil applies the IsNil predicate on the "branch" field. +func BranchIsNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIsNull(FieldBranch)) +} + +// BranchNotNil applies the NotNil predicate on the "branch" field. +func BranchNotNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotNull(FieldBranch)) +} + +// BranchEqualFold applies the EqualFold predicate on the "branch" field. +func BranchEqualFold(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEqualFold(FieldBranch, v)) +} + +// BranchContainsFold applies the ContainsFold predicate on the "branch" field. +func BranchContainsFold(v string) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldContainsFold(FieldBranch, v)) +} + +// IsRecycledEQ applies the EQ predicate on the "is_recycled" field. +func IsRecycledEQ(v bool) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldIsRecycled, v)) +} + +// IsRecycledNEQ applies the NEQ predicate on the "is_recycled" field. +func IsRecycledNEQ(v bool) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNEQ(FieldIsRecycled, v)) +} + +// IsRecycledIsNil applies the IsNil predicate on the "is_recycled" field. +func IsRecycledIsNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIsNull(FieldIsRecycled)) +} + +// IsRecycledNotNil applies the NotNil predicate on the "is_recycled" field. +func IsRecycledNotNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotNull(FieldIsRecycled)) +} + +// ConditionsIsNil applies the IsNil predicate on the "conditions" field. +func ConditionsIsNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIsNull(FieldConditions)) +} + +// ConditionsNotNil applies the NotNil predicate on the "conditions" field. +func ConditionsNotNil() predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotNull(FieldConditions)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. +func UpdatedAtEQ(v time.Time) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. +func UpdatedAtNEQ(v time.Time) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNEQ(FieldUpdatedAt, v)) +} + +// UpdatedAtIn applies the In predicate on the "updated_at" field. +func UpdatedAtIn(vs ...time.Time) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. +func UpdatedAtNotIn(vs ...time.Time) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldNotIn(FieldUpdatedAt, vs...)) +} + +// UpdatedAtGT applies the GT predicate on the "updated_at" field. +func UpdatedAtGT(v time.Time) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGT(FieldUpdatedAt, v)) +} + +// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. +func UpdatedAtGTE(v time.Time) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldGTE(FieldUpdatedAt, v)) +} + +// UpdatedAtLT applies the LT predicate on the "updated_at" field. +func UpdatedAtLT(v time.Time) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLT(FieldUpdatedAt, v)) +} + +// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. +func UpdatedAtLTE(v time.Time) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.FieldLTE(FieldUpdatedAt, v)) +} + +// HasHost applies the HasEdge predicate on the "host" edge. +func HasHost() predicate.VirtualMachine { + return predicate.VirtualMachine(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, HostTable, HostColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasHostWith applies the HasEdge predicate on the "host" edge with a given conditions (other predicates). +func HasHostWith(preds ...predicate.Host) predicate.VirtualMachine { + return predicate.VirtualMachine(func(s *sql.Selector) { + step := newHostStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasModel applies the HasEdge predicate on the "model" edge. +func HasModel() predicate.VirtualMachine { + return predicate.VirtualMachine(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ModelTable, ModelColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasModelWith applies the HasEdge predicate on the "model" edge with a given conditions (other predicates). +func HasModelWith(preds ...predicate.Model) predicate.VirtualMachine { + return predicate.VirtualMachine(func(s *sql.Selector) { + step := newModelStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasUser applies the HasEdge predicate on the "user" edge. +func HasUser() predicate.VirtualMachine { + return predicate.VirtualMachine(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates). +func HasUserWith(preds ...predicate.User) predicate.VirtualMachine { + return predicate.VirtualMachine(func(s *sql.Selector) { + step := newUserStep() + 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.VirtualMachine) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.VirtualMachine) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.VirtualMachine) predicate.VirtualMachine { + return predicate.VirtualMachine(sql.NotPredicates(p)) +} diff --git a/backend/db/virtualmachine_create.go b/backend/db/virtualmachine_create.go new file mode 100644 index 00000000..8d511116 --- /dev/null +++ b/backend/db/virtualmachine_create.go @@ -0,0 +1,2363 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/consts" + "github.com/chaitin/MonkeyCode/backend/db/host" + "github.com/chaitin/MonkeyCode/backend/db/model" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/virtualmachine" + "github.com/chaitin/MonkeyCode/backend/ent/types" + "github.com/google/uuid" +) + +// VirtualMachineCreate is the builder for creating a VirtualMachine entity. +type VirtualMachineCreate struct { + config + mutation *VirtualMachineMutation + hooks []Hook + conflict []sql.ConflictOption +} + +// SetDeletedAt sets the "deleted_at" field. +func (_c *VirtualMachineCreate) SetDeletedAt(v time.Time) *VirtualMachineCreate { + _c.mutation.SetDeletedAt(v) + return _c +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_c *VirtualMachineCreate) SetNillableDeletedAt(v *time.Time) *VirtualMachineCreate { + if v != nil { + _c.SetDeletedAt(*v) + } + return _c +} + +// SetHostID sets the "host_id" field. +func (_c *VirtualMachineCreate) SetHostID(v string) *VirtualMachineCreate { + _c.mutation.SetHostID(v) + return _c +} + +// SetUserID sets the "user_id" field. +func (_c *VirtualMachineCreate) SetUserID(v uuid.UUID) *VirtualMachineCreate { + _c.mutation.SetUserID(v) + return _c +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (_c *VirtualMachineCreate) SetNillableUserID(v *uuid.UUID) *VirtualMachineCreate { + if v != nil { + _c.SetUserID(*v) + } + return _c +} + +// SetModelID sets the "model_id" field. +func (_c *VirtualMachineCreate) SetModelID(v uuid.UUID) *VirtualMachineCreate { + _c.mutation.SetModelID(v) + return _c +} + +// SetNillableModelID sets the "model_id" field if the given value is not nil. +func (_c *VirtualMachineCreate) SetNillableModelID(v *uuid.UUID) *VirtualMachineCreate { + if v != nil { + _c.SetModelID(*v) + } + return _c +} + +// SetEnvironmentID sets the "environment_id" field. +func (_c *VirtualMachineCreate) SetEnvironmentID(v string) *VirtualMachineCreate { + _c.mutation.SetEnvironmentID(v) + return _c +} + +// SetNillableEnvironmentID sets the "environment_id" field if the given value is not nil. +func (_c *VirtualMachineCreate) SetNillableEnvironmentID(v *string) *VirtualMachineCreate { + if v != nil { + _c.SetEnvironmentID(*v) + } + return _c +} + +// SetName sets the "name" field. +func (_c *VirtualMachineCreate) SetName(v string) *VirtualMachineCreate { + _c.mutation.SetName(v) + return _c +} + +// SetHostname sets the "hostname" field. +func (_c *VirtualMachineCreate) SetHostname(v string) *VirtualMachineCreate { + _c.mutation.SetHostname(v) + return _c +} + +// SetNillableHostname sets the "hostname" field if the given value is not nil. +func (_c *VirtualMachineCreate) SetNillableHostname(v *string) *VirtualMachineCreate { + if v != nil { + _c.SetHostname(*v) + } + return _c +} + +// SetArch sets the "arch" field. +func (_c *VirtualMachineCreate) SetArch(v string) *VirtualMachineCreate { + _c.mutation.SetArch(v) + return _c +} + +// SetNillableArch sets the "arch" field if the given value is not nil. +func (_c *VirtualMachineCreate) SetNillableArch(v *string) *VirtualMachineCreate { + if v != nil { + _c.SetArch(*v) + } + return _c +} + +// SetCores sets the "cores" field. +func (_c *VirtualMachineCreate) SetCores(v int) *VirtualMachineCreate { + _c.mutation.SetCores(v) + return _c +} + +// SetNillableCores sets the "cores" field if the given value is not nil. +func (_c *VirtualMachineCreate) SetNillableCores(v *int) *VirtualMachineCreate { + if v != nil { + _c.SetCores(*v) + } + return _c +} + +// SetMemory sets the "memory" field. +func (_c *VirtualMachineCreate) SetMemory(v int64) *VirtualMachineCreate { + _c.mutation.SetMemory(v) + return _c +} + +// SetNillableMemory sets the "memory" field if the given value is not nil. +func (_c *VirtualMachineCreate) SetNillableMemory(v *int64) *VirtualMachineCreate { + if v != nil { + _c.SetMemory(*v) + } + return _c +} + +// SetOs sets the "os" field. +func (_c *VirtualMachineCreate) SetOs(v string) *VirtualMachineCreate { + _c.mutation.SetOs(v) + return _c +} + +// SetNillableOs sets the "os" field if the given value is not nil. +func (_c *VirtualMachineCreate) SetNillableOs(v *string) *VirtualMachineCreate { + if v != nil { + _c.SetOs(*v) + } + return _c +} + +// SetExternalIP sets the "external_ip" field. +func (_c *VirtualMachineCreate) SetExternalIP(v string) *VirtualMachineCreate { + _c.mutation.SetExternalIP(v) + return _c +} + +// SetNillableExternalIP sets the "external_ip" field if the given value is not nil. +func (_c *VirtualMachineCreate) SetNillableExternalIP(v *string) *VirtualMachineCreate { + if v != nil { + _c.SetExternalIP(*v) + } + return _c +} + +// SetInternalIP sets the "internal_ip" field. +func (_c *VirtualMachineCreate) SetInternalIP(v string) *VirtualMachineCreate { + _c.mutation.SetInternalIP(v) + return _c +} + +// SetNillableInternalIP sets the "internal_ip" field if the given value is not nil. +func (_c *VirtualMachineCreate) SetNillableInternalIP(v *string) *VirtualMachineCreate { + if v != nil { + _c.SetInternalIP(*v) + } + return _c +} + +// SetTTLKind sets the "ttl_kind" field. +func (_c *VirtualMachineCreate) SetTTLKind(v consts.VirtualmachineTTLKind) *VirtualMachineCreate { + _c.mutation.SetTTLKind(v) + return _c +} + +// SetNillableTTLKind sets the "ttl_kind" field if the given value is not nil. +func (_c *VirtualMachineCreate) SetNillableTTLKind(v *consts.VirtualmachineTTLKind) *VirtualMachineCreate { + if v != nil { + _c.SetTTLKind(*v) + } + return _c +} + +// SetTTL sets the "ttl" field. +func (_c *VirtualMachineCreate) SetTTL(v int64) *VirtualMachineCreate { + _c.mutation.SetTTL(v) + return _c +} + +// SetNillableTTL sets the "ttl" field if the given value is not nil. +func (_c *VirtualMachineCreate) SetNillableTTL(v *int64) *VirtualMachineCreate { + if v != nil { + _c.SetTTL(*v) + } + return _c +} + +// SetVersion sets the "version" field. +func (_c *VirtualMachineCreate) SetVersion(v string) *VirtualMachineCreate { + _c.mutation.SetVersion(v) + return _c +} + +// SetNillableVersion sets the "version" field if the given value is not nil. +func (_c *VirtualMachineCreate) SetNillableVersion(v *string) *VirtualMachineCreate { + if v != nil { + _c.SetVersion(*v) + } + return _c +} + +// SetMachineID sets the "machine_id" field. +func (_c *VirtualMachineCreate) SetMachineID(v string) *VirtualMachineCreate { + _c.mutation.SetMachineID(v) + return _c +} + +// SetNillableMachineID sets the "machine_id" field if the given value is not nil. +func (_c *VirtualMachineCreate) SetNillableMachineID(v *string) *VirtualMachineCreate { + if v != nil { + _c.SetMachineID(*v) + } + return _c +} + +// SetRepoURL sets the "repo_url" field. +func (_c *VirtualMachineCreate) SetRepoURL(v string) *VirtualMachineCreate { + _c.mutation.SetRepoURL(v) + return _c +} + +// SetNillableRepoURL sets the "repo_url" field if the given value is not nil. +func (_c *VirtualMachineCreate) SetNillableRepoURL(v *string) *VirtualMachineCreate { + if v != nil { + _c.SetRepoURL(*v) + } + return _c +} + +// SetRepoFilename sets the "repo_filename" field. +func (_c *VirtualMachineCreate) SetRepoFilename(v string) *VirtualMachineCreate { + _c.mutation.SetRepoFilename(v) + return _c +} + +// SetNillableRepoFilename sets the "repo_filename" field if the given value is not nil. +func (_c *VirtualMachineCreate) SetNillableRepoFilename(v *string) *VirtualMachineCreate { + if v != nil { + _c.SetRepoFilename(*v) + } + return _c +} + +// SetBranch sets the "branch" field. +func (_c *VirtualMachineCreate) SetBranch(v string) *VirtualMachineCreate { + _c.mutation.SetBranch(v) + return _c +} + +// SetNillableBranch sets the "branch" field if the given value is not nil. +func (_c *VirtualMachineCreate) SetNillableBranch(v *string) *VirtualMachineCreate { + if v != nil { + _c.SetBranch(*v) + } + return _c +} + +// SetIsRecycled sets the "is_recycled" field. +func (_c *VirtualMachineCreate) SetIsRecycled(v bool) *VirtualMachineCreate { + _c.mutation.SetIsRecycled(v) + return _c +} + +// SetNillableIsRecycled sets the "is_recycled" field if the given value is not nil. +func (_c *VirtualMachineCreate) SetNillableIsRecycled(v *bool) *VirtualMachineCreate { + if v != nil { + _c.SetIsRecycled(*v) + } + return _c +} + +// SetConditions sets the "conditions" field. +func (_c *VirtualMachineCreate) SetConditions(v *types.VirtualMachineCondition) *VirtualMachineCreate { + _c.mutation.SetConditions(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *VirtualMachineCreate) SetCreatedAt(v time.Time) *VirtualMachineCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *VirtualMachineCreate) SetNillableCreatedAt(v *time.Time) *VirtualMachineCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetUpdatedAt sets the "updated_at" field. +func (_c *VirtualMachineCreate) SetUpdatedAt(v time.Time) *VirtualMachineCreate { + _c.mutation.SetUpdatedAt(v) + return _c +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_c *VirtualMachineCreate) SetNillableUpdatedAt(v *time.Time) *VirtualMachineCreate { + if v != nil { + _c.SetUpdatedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *VirtualMachineCreate) SetID(v string) *VirtualMachineCreate { + _c.mutation.SetID(v) + return _c +} + +// SetHost sets the "host" edge to the Host entity. +func (_c *VirtualMachineCreate) SetHost(v *Host) *VirtualMachineCreate { + return _c.SetHostID(v.ID) +} + +// SetModel sets the "model" edge to the Model entity. +func (_c *VirtualMachineCreate) SetModel(v *Model) *VirtualMachineCreate { + return _c.SetModelID(v.ID) +} + +// SetUser sets the "user" edge to the User entity. +func (_c *VirtualMachineCreate) SetUser(v *User) *VirtualMachineCreate { + return _c.SetUserID(v.ID) +} + +// Mutation returns the VirtualMachineMutation object of the builder. +func (_c *VirtualMachineCreate) Mutation() *VirtualMachineMutation { + return _c.mutation +} + +// Save creates the VirtualMachine in the database. +func (_c *VirtualMachineCreate) Save(ctx context.Context) (*VirtualMachine, error) { + if err := _c.defaults(); err != nil { + return nil, err + } + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *VirtualMachineCreate) SaveX(ctx context.Context) *VirtualMachine { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *VirtualMachineCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *VirtualMachineCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (_c *VirtualMachineCreate) defaults() error { + if _, ok := _c.mutation.CreatedAt(); !ok { + if virtualmachine.DefaultCreatedAt == nil { + return fmt.Errorf("db: uninitialized virtualmachine.DefaultCreatedAt (forgotten import db/runtime?)") + } + v := virtualmachine.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + if virtualmachine.DefaultUpdatedAt == nil { + return fmt.Errorf("db: uninitialized virtualmachine.DefaultUpdatedAt (forgotten import db/runtime?)") + } + v := virtualmachine.DefaultUpdatedAt() + _c.mutation.SetUpdatedAt(v) + } + return nil +} + +// check runs all checks and user-defined validators on the builder. +func (_c *VirtualMachineCreate) check() error { + if _, ok := _c.mutation.HostID(); !ok { + return &ValidationError{Name: "host_id", err: errors.New(`db: missing required field "VirtualMachine.host_id"`)} + } + if _, ok := _c.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`db: missing required field "VirtualMachine.name"`)} + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "VirtualMachine.created_at"`)} + } + if _, ok := _c.mutation.UpdatedAt(); !ok { + return &ValidationError{Name: "updated_at", err: errors.New(`db: missing required field "VirtualMachine.updated_at"`)} + } + if len(_c.mutation.HostIDs()) == 0 { + return &ValidationError{Name: "host", err: errors.New(`db: missing required edge "VirtualMachine.host"`)} + } + return nil +} + +func (_c *VirtualMachineCreate) sqlSave(ctx context.Context) (*VirtualMachine, error) { + if err := _c.check(); err != nil { + return nil, err + } + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != nil { + if id, ok := _spec.ID.Value.(string); ok { + _node.ID = id + } else { + return nil, fmt.Errorf("unexpected VirtualMachine.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *VirtualMachineCreate) createSpec() (*VirtualMachine, *sqlgraph.CreateSpec) { + var ( + _node = &VirtualMachine{config: _c.config} + _spec = sqlgraph.NewCreateSpec(virtualmachine.Table, sqlgraph.NewFieldSpec(virtualmachine.FieldID, field.TypeString)) + ) + _spec.OnConflict = _c.conflict + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.DeletedAt(); ok { + _spec.SetField(virtualmachine.FieldDeletedAt, field.TypeTime, value) + _node.DeletedAt = value + } + if value, ok := _c.mutation.EnvironmentID(); ok { + _spec.SetField(virtualmachine.FieldEnvironmentID, field.TypeString, value) + _node.EnvironmentID = value + } + if value, ok := _c.mutation.Name(); ok { + _spec.SetField(virtualmachine.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := _c.mutation.Hostname(); ok { + _spec.SetField(virtualmachine.FieldHostname, field.TypeString, value) + _node.Hostname = value + } + if value, ok := _c.mutation.Arch(); ok { + _spec.SetField(virtualmachine.FieldArch, field.TypeString, value) + _node.Arch = value + } + if value, ok := _c.mutation.Cores(); ok { + _spec.SetField(virtualmachine.FieldCores, field.TypeInt, value) + _node.Cores = value + } + if value, ok := _c.mutation.Memory(); ok { + _spec.SetField(virtualmachine.FieldMemory, field.TypeInt64, value) + _node.Memory = value + } + if value, ok := _c.mutation.Os(); ok { + _spec.SetField(virtualmachine.FieldOs, field.TypeString, value) + _node.Os = value + } + if value, ok := _c.mutation.ExternalIP(); ok { + _spec.SetField(virtualmachine.FieldExternalIP, field.TypeString, value) + _node.ExternalIP = value + } + if value, ok := _c.mutation.InternalIP(); ok { + _spec.SetField(virtualmachine.FieldInternalIP, field.TypeString, value) + _node.InternalIP = value + } + if value, ok := _c.mutation.TTLKind(); ok { + _spec.SetField(virtualmachine.FieldTTLKind, field.TypeString, value) + _node.TTLKind = value + } + if value, ok := _c.mutation.TTL(); ok { + _spec.SetField(virtualmachine.FieldTTL, field.TypeInt64, value) + _node.TTL = value + } + if value, ok := _c.mutation.Version(); ok { + _spec.SetField(virtualmachine.FieldVersion, field.TypeString, value) + _node.Version = value + } + if value, ok := _c.mutation.MachineID(); ok { + _spec.SetField(virtualmachine.FieldMachineID, field.TypeString, value) + _node.MachineID = value + } + if value, ok := _c.mutation.RepoURL(); ok { + _spec.SetField(virtualmachine.FieldRepoURL, field.TypeString, value) + _node.RepoURL = value + } + if value, ok := _c.mutation.RepoFilename(); ok { + _spec.SetField(virtualmachine.FieldRepoFilename, field.TypeString, value) + _node.RepoFilename = value + } + if value, ok := _c.mutation.Branch(); ok { + _spec.SetField(virtualmachine.FieldBranch, field.TypeString, value) + _node.Branch = value + } + if value, ok := _c.mutation.IsRecycled(); ok { + _spec.SetField(virtualmachine.FieldIsRecycled, field.TypeBool, value) + _node.IsRecycled = value + } + if value, ok := _c.mutation.Conditions(); ok { + _spec.SetField(virtualmachine.FieldConditions, field.TypeJSON, value) + _node.Conditions = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(virtualmachine.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := _c.mutation.UpdatedAt(); ok { + _spec.SetField(virtualmachine.FieldUpdatedAt, field.TypeTime, value) + _node.UpdatedAt = value + } + if nodes := _c.mutation.HostIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: virtualmachine.HostTable, + Columns: []string{virtualmachine.HostColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.HostID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.ModelIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: virtualmachine.ModelTable, + Columns: []string{virtualmachine.ModelColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.ModelID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: virtualmachine.UserTable, + Columns: []string{virtualmachine.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.UserID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.VirtualMachine.Create(). +// SetDeletedAt(v). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.VirtualMachineUpsert) { +// SetDeletedAt(v+v). +// }). +// Exec(ctx) +func (_c *VirtualMachineCreate) OnConflict(opts ...sql.ConflictOption) *VirtualMachineUpsertOne { + _c.conflict = opts + return &VirtualMachineUpsertOne{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.VirtualMachine.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *VirtualMachineCreate) OnConflictColumns(columns ...string) *VirtualMachineUpsertOne { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &VirtualMachineUpsertOne{ + create: _c, + } +} + +type ( + // VirtualMachineUpsertOne is the builder for "upsert"-ing + // one VirtualMachine node. + VirtualMachineUpsertOne struct { + create *VirtualMachineCreate + } + + // VirtualMachineUpsert is the "OnConflict" setter. + VirtualMachineUpsert struct { + *sql.UpdateSet + } +) + +// SetDeletedAt sets the "deleted_at" field. +func (u *VirtualMachineUpsert) SetDeletedAt(v time.Time) *VirtualMachineUpsert { + u.Set(virtualmachine.FieldDeletedAt, v) + return u +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *VirtualMachineUpsert) UpdateDeletedAt() *VirtualMachineUpsert { + u.SetExcluded(virtualmachine.FieldDeletedAt) + return u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *VirtualMachineUpsert) ClearDeletedAt() *VirtualMachineUpsert { + u.SetNull(virtualmachine.FieldDeletedAt) + return u +} + +// SetHostID sets the "host_id" field. +func (u *VirtualMachineUpsert) SetHostID(v string) *VirtualMachineUpsert { + u.Set(virtualmachine.FieldHostID, v) + return u +} + +// UpdateHostID sets the "host_id" field to the value that was provided on create. +func (u *VirtualMachineUpsert) UpdateHostID() *VirtualMachineUpsert { + u.SetExcluded(virtualmachine.FieldHostID) + return u +} + +// SetUserID sets the "user_id" field. +func (u *VirtualMachineUpsert) SetUserID(v uuid.UUID) *VirtualMachineUpsert { + u.Set(virtualmachine.FieldUserID, v) + return u +} + +// UpdateUserID sets the "user_id" field to the value that was provided on create. +func (u *VirtualMachineUpsert) UpdateUserID() *VirtualMachineUpsert { + u.SetExcluded(virtualmachine.FieldUserID) + return u +} + +// ClearUserID clears the value of the "user_id" field. +func (u *VirtualMachineUpsert) ClearUserID() *VirtualMachineUpsert { + u.SetNull(virtualmachine.FieldUserID) + return u +} + +// SetModelID sets the "model_id" field. +func (u *VirtualMachineUpsert) SetModelID(v uuid.UUID) *VirtualMachineUpsert { + u.Set(virtualmachine.FieldModelID, v) + return u +} + +// UpdateModelID sets the "model_id" field to the value that was provided on create. +func (u *VirtualMachineUpsert) UpdateModelID() *VirtualMachineUpsert { + u.SetExcluded(virtualmachine.FieldModelID) + return u +} + +// ClearModelID clears the value of the "model_id" field. +func (u *VirtualMachineUpsert) ClearModelID() *VirtualMachineUpsert { + u.SetNull(virtualmachine.FieldModelID) + return u +} + +// SetEnvironmentID sets the "environment_id" field. +func (u *VirtualMachineUpsert) SetEnvironmentID(v string) *VirtualMachineUpsert { + u.Set(virtualmachine.FieldEnvironmentID, v) + return u +} + +// UpdateEnvironmentID sets the "environment_id" field to the value that was provided on create. +func (u *VirtualMachineUpsert) UpdateEnvironmentID() *VirtualMachineUpsert { + u.SetExcluded(virtualmachine.FieldEnvironmentID) + return u +} + +// ClearEnvironmentID clears the value of the "environment_id" field. +func (u *VirtualMachineUpsert) ClearEnvironmentID() *VirtualMachineUpsert { + u.SetNull(virtualmachine.FieldEnvironmentID) + return u +} + +// SetName sets the "name" field. +func (u *VirtualMachineUpsert) SetName(v string) *VirtualMachineUpsert { + u.Set(virtualmachine.FieldName, v) + return u +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *VirtualMachineUpsert) UpdateName() *VirtualMachineUpsert { + u.SetExcluded(virtualmachine.FieldName) + return u +} + +// SetHostname sets the "hostname" field. +func (u *VirtualMachineUpsert) SetHostname(v string) *VirtualMachineUpsert { + u.Set(virtualmachine.FieldHostname, v) + return u +} + +// UpdateHostname sets the "hostname" field to the value that was provided on create. +func (u *VirtualMachineUpsert) UpdateHostname() *VirtualMachineUpsert { + u.SetExcluded(virtualmachine.FieldHostname) + return u +} + +// ClearHostname clears the value of the "hostname" field. +func (u *VirtualMachineUpsert) ClearHostname() *VirtualMachineUpsert { + u.SetNull(virtualmachine.FieldHostname) + return u +} + +// SetArch sets the "arch" field. +func (u *VirtualMachineUpsert) SetArch(v string) *VirtualMachineUpsert { + u.Set(virtualmachine.FieldArch, v) + return u +} + +// UpdateArch sets the "arch" field to the value that was provided on create. +func (u *VirtualMachineUpsert) UpdateArch() *VirtualMachineUpsert { + u.SetExcluded(virtualmachine.FieldArch) + return u +} + +// ClearArch clears the value of the "arch" field. +func (u *VirtualMachineUpsert) ClearArch() *VirtualMachineUpsert { + u.SetNull(virtualmachine.FieldArch) + return u +} + +// SetCores sets the "cores" field. +func (u *VirtualMachineUpsert) SetCores(v int) *VirtualMachineUpsert { + u.Set(virtualmachine.FieldCores, v) + return u +} + +// UpdateCores sets the "cores" field to the value that was provided on create. +func (u *VirtualMachineUpsert) UpdateCores() *VirtualMachineUpsert { + u.SetExcluded(virtualmachine.FieldCores) + return u +} + +// AddCores adds v to the "cores" field. +func (u *VirtualMachineUpsert) AddCores(v int) *VirtualMachineUpsert { + u.Add(virtualmachine.FieldCores, v) + return u +} + +// ClearCores clears the value of the "cores" field. +func (u *VirtualMachineUpsert) ClearCores() *VirtualMachineUpsert { + u.SetNull(virtualmachine.FieldCores) + return u +} + +// SetMemory sets the "memory" field. +func (u *VirtualMachineUpsert) SetMemory(v int64) *VirtualMachineUpsert { + u.Set(virtualmachine.FieldMemory, v) + return u +} + +// UpdateMemory sets the "memory" field to the value that was provided on create. +func (u *VirtualMachineUpsert) UpdateMemory() *VirtualMachineUpsert { + u.SetExcluded(virtualmachine.FieldMemory) + return u +} + +// AddMemory adds v to the "memory" field. +func (u *VirtualMachineUpsert) AddMemory(v int64) *VirtualMachineUpsert { + u.Add(virtualmachine.FieldMemory, v) + return u +} + +// ClearMemory clears the value of the "memory" field. +func (u *VirtualMachineUpsert) ClearMemory() *VirtualMachineUpsert { + u.SetNull(virtualmachine.FieldMemory) + return u +} + +// SetOs sets the "os" field. +func (u *VirtualMachineUpsert) SetOs(v string) *VirtualMachineUpsert { + u.Set(virtualmachine.FieldOs, v) + return u +} + +// UpdateOs sets the "os" field to the value that was provided on create. +func (u *VirtualMachineUpsert) UpdateOs() *VirtualMachineUpsert { + u.SetExcluded(virtualmachine.FieldOs) + return u +} + +// ClearOs clears the value of the "os" field. +func (u *VirtualMachineUpsert) ClearOs() *VirtualMachineUpsert { + u.SetNull(virtualmachine.FieldOs) + return u +} + +// SetExternalIP sets the "external_ip" field. +func (u *VirtualMachineUpsert) SetExternalIP(v string) *VirtualMachineUpsert { + u.Set(virtualmachine.FieldExternalIP, v) + return u +} + +// UpdateExternalIP sets the "external_ip" field to the value that was provided on create. +func (u *VirtualMachineUpsert) UpdateExternalIP() *VirtualMachineUpsert { + u.SetExcluded(virtualmachine.FieldExternalIP) + return u +} + +// ClearExternalIP clears the value of the "external_ip" field. +func (u *VirtualMachineUpsert) ClearExternalIP() *VirtualMachineUpsert { + u.SetNull(virtualmachine.FieldExternalIP) + return u +} + +// SetInternalIP sets the "internal_ip" field. +func (u *VirtualMachineUpsert) SetInternalIP(v string) *VirtualMachineUpsert { + u.Set(virtualmachine.FieldInternalIP, v) + return u +} + +// UpdateInternalIP sets the "internal_ip" field to the value that was provided on create. +func (u *VirtualMachineUpsert) UpdateInternalIP() *VirtualMachineUpsert { + u.SetExcluded(virtualmachine.FieldInternalIP) + return u +} + +// ClearInternalIP clears the value of the "internal_ip" field. +func (u *VirtualMachineUpsert) ClearInternalIP() *VirtualMachineUpsert { + u.SetNull(virtualmachine.FieldInternalIP) + return u +} + +// SetTTLKind sets the "ttl_kind" field. +func (u *VirtualMachineUpsert) SetTTLKind(v consts.VirtualmachineTTLKind) *VirtualMachineUpsert { + u.Set(virtualmachine.FieldTTLKind, v) + return u +} + +// UpdateTTLKind sets the "ttl_kind" field to the value that was provided on create. +func (u *VirtualMachineUpsert) UpdateTTLKind() *VirtualMachineUpsert { + u.SetExcluded(virtualmachine.FieldTTLKind) + return u +} + +// ClearTTLKind clears the value of the "ttl_kind" field. +func (u *VirtualMachineUpsert) ClearTTLKind() *VirtualMachineUpsert { + u.SetNull(virtualmachine.FieldTTLKind) + return u +} + +// SetTTL sets the "ttl" field. +func (u *VirtualMachineUpsert) SetTTL(v int64) *VirtualMachineUpsert { + u.Set(virtualmachine.FieldTTL, v) + return u +} + +// UpdateTTL sets the "ttl" field to the value that was provided on create. +func (u *VirtualMachineUpsert) UpdateTTL() *VirtualMachineUpsert { + u.SetExcluded(virtualmachine.FieldTTL) + return u +} + +// AddTTL adds v to the "ttl" field. +func (u *VirtualMachineUpsert) AddTTL(v int64) *VirtualMachineUpsert { + u.Add(virtualmachine.FieldTTL, v) + return u +} + +// ClearTTL clears the value of the "ttl" field. +func (u *VirtualMachineUpsert) ClearTTL() *VirtualMachineUpsert { + u.SetNull(virtualmachine.FieldTTL) + return u +} + +// SetVersion sets the "version" field. +func (u *VirtualMachineUpsert) SetVersion(v string) *VirtualMachineUpsert { + u.Set(virtualmachine.FieldVersion, v) + return u +} + +// UpdateVersion sets the "version" field to the value that was provided on create. +func (u *VirtualMachineUpsert) UpdateVersion() *VirtualMachineUpsert { + u.SetExcluded(virtualmachine.FieldVersion) + return u +} + +// ClearVersion clears the value of the "version" field. +func (u *VirtualMachineUpsert) ClearVersion() *VirtualMachineUpsert { + u.SetNull(virtualmachine.FieldVersion) + return u +} + +// SetMachineID sets the "machine_id" field. +func (u *VirtualMachineUpsert) SetMachineID(v string) *VirtualMachineUpsert { + u.Set(virtualmachine.FieldMachineID, v) + return u +} + +// UpdateMachineID sets the "machine_id" field to the value that was provided on create. +func (u *VirtualMachineUpsert) UpdateMachineID() *VirtualMachineUpsert { + u.SetExcluded(virtualmachine.FieldMachineID) + return u +} + +// ClearMachineID clears the value of the "machine_id" field. +func (u *VirtualMachineUpsert) ClearMachineID() *VirtualMachineUpsert { + u.SetNull(virtualmachine.FieldMachineID) + return u +} + +// SetRepoURL sets the "repo_url" field. +func (u *VirtualMachineUpsert) SetRepoURL(v string) *VirtualMachineUpsert { + u.Set(virtualmachine.FieldRepoURL, v) + return u +} + +// UpdateRepoURL sets the "repo_url" field to the value that was provided on create. +func (u *VirtualMachineUpsert) UpdateRepoURL() *VirtualMachineUpsert { + u.SetExcluded(virtualmachine.FieldRepoURL) + return u +} + +// ClearRepoURL clears the value of the "repo_url" field. +func (u *VirtualMachineUpsert) ClearRepoURL() *VirtualMachineUpsert { + u.SetNull(virtualmachine.FieldRepoURL) + return u +} + +// SetRepoFilename sets the "repo_filename" field. +func (u *VirtualMachineUpsert) SetRepoFilename(v string) *VirtualMachineUpsert { + u.Set(virtualmachine.FieldRepoFilename, v) + return u +} + +// UpdateRepoFilename sets the "repo_filename" field to the value that was provided on create. +func (u *VirtualMachineUpsert) UpdateRepoFilename() *VirtualMachineUpsert { + u.SetExcluded(virtualmachine.FieldRepoFilename) + return u +} + +// ClearRepoFilename clears the value of the "repo_filename" field. +func (u *VirtualMachineUpsert) ClearRepoFilename() *VirtualMachineUpsert { + u.SetNull(virtualmachine.FieldRepoFilename) + return u +} + +// SetBranch sets the "branch" field. +func (u *VirtualMachineUpsert) SetBranch(v string) *VirtualMachineUpsert { + u.Set(virtualmachine.FieldBranch, v) + return u +} + +// UpdateBranch sets the "branch" field to the value that was provided on create. +func (u *VirtualMachineUpsert) UpdateBranch() *VirtualMachineUpsert { + u.SetExcluded(virtualmachine.FieldBranch) + return u +} + +// ClearBranch clears the value of the "branch" field. +func (u *VirtualMachineUpsert) ClearBranch() *VirtualMachineUpsert { + u.SetNull(virtualmachine.FieldBranch) + return u +} + +// SetIsRecycled sets the "is_recycled" field. +func (u *VirtualMachineUpsert) SetIsRecycled(v bool) *VirtualMachineUpsert { + u.Set(virtualmachine.FieldIsRecycled, v) + return u +} + +// UpdateIsRecycled sets the "is_recycled" field to the value that was provided on create. +func (u *VirtualMachineUpsert) UpdateIsRecycled() *VirtualMachineUpsert { + u.SetExcluded(virtualmachine.FieldIsRecycled) + return u +} + +// ClearIsRecycled clears the value of the "is_recycled" field. +func (u *VirtualMachineUpsert) ClearIsRecycled() *VirtualMachineUpsert { + u.SetNull(virtualmachine.FieldIsRecycled) + return u +} + +// SetConditions sets the "conditions" field. +func (u *VirtualMachineUpsert) SetConditions(v *types.VirtualMachineCondition) *VirtualMachineUpsert { + u.Set(virtualmachine.FieldConditions, v) + return u +} + +// UpdateConditions sets the "conditions" field to the value that was provided on create. +func (u *VirtualMachineUpsert) UpdateConditions() *VirtualMachineUpsert { + u.SetExcluded(virtualmachine.FieldConditions) + return u +} + +// ClearConditions clears the value of the "conditions" field. +func (u *VirtualMachineUpsert) ClearConditions() *VirtualMachineUpsert { + u.SetNull(virtualmachine.FieldConditions) + return u +} + +// SetCreatedAt sets the "created_at" field. +func (u *VirtualMachineUpsert) SetCreatedAt(v time.Time) *VirtualMachineUpsert { + u.Set(virtualmachine.FieldCreatedAt, v) + return u +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *VirtualMachineUpsert) UpdateCreatedAt() *VirtualMachineUpsert { + u.SetExcluded(virtualmachine.FieldCreatedAt) + return u +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *VirtualMachineUpsert) SetUpdatedAt(v time.Time) *VirtualMachineUpsert { + u.Set(virtualmachine.FieldUpdatedAt, v) + return u +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *VirtualMachineUpsert) UpdateUpdatedAt() *VirtualMachineUpsert { + u.SetExcluded(virtualmachine.FieldUpdatedAt) + return u +} + +// UpdateNewValues updates the mutable fields using the new values that were set on create except the ID field. +// Using this option is equivalent to using: +// +// client.VirtualMachine.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(virtualmachine.FieldID) +// }), +// ). +// Exec(ctx) +func (u *VirtualMachineUpsertOne) UpdateNewValues() *VirtualMachineUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + if _, exists := u.create.mutation.ID(); exists { + s.SetIgnore(virtualmachine.FieldID) + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.VirtualMachine.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *VirtualMachineUpsertOne) Ignore() *VirtualMachineUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *VirtualMachineUpsertOne) DoNothing() *VirtualMachineUpsertOne { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the VirtualMachineCreate.OnConflict +// documentation for more info. +func (u *VirtualMachineUpsertOne) Update(set func(*VirtualMachineUpsert)) *VirtualMachineUpsertOne { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&VirtualMachineUpsert{UpdateSet: update}) + })) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *VirtualMachineUpsertOne) SetDeletedAt(v time.Time) *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *VirtualMachineUpsertOne) UpdateDeletedAt() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *VirtualMachineUpsertOne) ClearDeletedAt() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearDeletedAt() + }) +} + +// SetHostID sets the "host_id" field. +func (u *VirtualMachineUpsertOne) SetHostID(v string) *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetHostID(v) + }) +} + +// UpdateHostID sets the "host_id" field to the value that was provided on create. +func (u *VirtualMachineUpsertOne) UpdateHostID() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateHostID() + }) +} + +// SetUserID sets the "user_id" field. +func (u *VirtualMachineUpsertOne) SetUserID(v uuid.UUID) *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetUserID(v) + }) +} + +// UpdateUserID sets the "user_id" field to the value that was provided on create. +func (u *VirtualMachineUpsertOne) UpdateUserID() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateUserID() + }) +} + +// ClearUserID clears the value of the "user_id" field. +func (u *VirtualMachineUpsertOne) ClearUserID() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearUserID() + }) +} + +// SetModelID sets the "model_id" field. +func (u *VirtualMachineUpsertOne) SetModelID(v uuid.UUID) *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetModelID(v) + }) +} + +// UpdateModelID sets the "model_id" field to the value that was provided on create. +func (u *VirtualMachineUpsertOne) UpdateModelID() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateModelID() + }) +} + +// ClearModelID clears the value of the "model_id" field. +func (u *VirtualMachineUpsertOne) ClearModelID() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearModelID() + }) +} + +// SetEnvironmentID sets the "environment_id" field. +func (u *VirtualMachineUpsertOne) SetEnvironmentID(v string) *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetEnvironmentID(v) + }) +} + +// UpdateEnvironmentID sets the "environment_id" field to the value that was provided on create. +func (u *VirtualMachineUpsertOne) UpdateEnvironmentID() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateEnvironmentID() + }) +} + +// ClearEnvironmentID clears the value of the "environment_id" field. +func (u *VirtualMachineUpsertOne) ClearEnvironmentID() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearEnvironmentID() + }) +} + +// SetName sets the "name" field. +func (u *VirtualMachineUpsertOne) SetName(v string) *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *VirtualMachineUpsertOne) UpdateName() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateName() + }) +} + +// SetHostname sets the "hostname" field. +func (u *VirtualMachineUpsertOne) SetHostname(v string) *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetHostname(v) + }) +} + +// UpdateHostname sets the "hostname" field to the value that was provided on create. +func (u *VirtualMachineUpsertOne) UpdateHostname() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateHostname() + }) +} + +// ClearHostname clears the value of the "hostname" field. +func (u *VirtualMachineUpsertOne) ClearHostname() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearHostname() + }) +} + +// SetArch sets the "arch" field. +func (u *VirtualMachineUpsertOne) SetArch(v string) *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetArch(v) + }) +} + +// UpdateArch sets the "arch" field to the value that was provided on create. +func (u *VirtualMachineUpsertOne) UpdateArch() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateArch() + }) +} + +// ClearArch clears the value of the "arch" field. +func (u *VirtualMachineUpsertOne) ClearArch() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearArch() + }) +} + +// SetCores sets the "cores" field. +func (u *VirtualMachineUpsertOne) SetCores(v int) *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetCores(v) + }) +} + +// AddCores adds v to the "cores" field. +func (u *VirtualMachineUpsertOne) AddCores(v int) *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.AddCores(v) + }) +} + +// UpdateCores sets the "cores" field to the value that was provided on create. +func (u *VirtualMachineUpsertOne) UpdateCores() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateCores() + }) +} + +// ClearCores clears the value of the "cores" field. +func (u *VirtualMachineUpsertOne) ClearCores() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearCores() + }) +} + +// SetMemory sets the "memory" field. +func (u *VirtualMachineUpsertOne) SetMemory(v int64) *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetMemory(v) + }) +} + +// AddMemory adds v to the "memory" field. +func (u *VirtualMachineUpsertOne) AddMemory(v int64) *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.AddMemory(v) + }) +} + +// UpdateMemory sets the "memory" field to the value that was provided on create. +func (u *VirtualMachineUpsertOne) UpdateMemory() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateMemory() + }) +} + +// ClearMemory clears the value of the "memory" field. +func (u *VirtualMachineUpsertOne) ClearMemory() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearMemory() + }) +} + +// SetOs sets the "os" field. +func (u *VirtualMachineUpsertOne) SetOs(v string) *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetOs(v) + }) +} + +// UpdateOs sets the "os" field to the value that was provided on create. +func (u *VirtualMachineUpsertOne) UpdateOs() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateOs() + }) +} + +// ClearOs clears the value of the "os" field. +func (u *VirtualMachineUpsertOne) ClearOs() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearOs() + }) +} + +// SetExternalIP sets the "external_ip" field. +func (u *VirtualMachineUpsertOne) SetExternalIP(v string) *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetExternalIP(v) + }) +} + +// UpdateExternalIP sets the "external_ip" field to the value that was provided on create. +func (u *VirtualMachineUpsertOne) UpdateExternalIP() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateExternalIP() + }) +} + +// ClearExternalIP clears the value of the "external_ip" field. +func (u *VirtualMachineUpsertOne) ClearExternalIP() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearExternalIP() + }) +} + +// SetInternalIP sets the "internal_ip" field. +func (u *VirtualMachineUpsertOne) SetInternalIP(v string) *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetInternalIP(v) + }) +} + +// UpdateInternalIP sets the "internal_ip" field to the value that was provided on create. +func (u *VirtualMachineUpsertOne) UpdateInternalIP() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateInternalIP() + }) +} + +// ClearInternalIP clears the value of the "internal_ip" field. +func (u *VirtualMachineUpsertOne) ClearInternalIP() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearInternalIP() + }) +} + +// SetTTLKind sets the "ttl_kind" field. +func (u *VirtualMachineUpsertOne) SetTTLKind(v consts.VirtualmachineTTLKind) *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetTTLKind(v) + }) +} + +// UpdateTTLKind sets the "ttl_kind" field to the value that was provided on create. +func (u *VirtualMachineUpsertOne) UpdateTTLKind() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateTTLKind() + }) +} + +// ClearTTLKind clears the value of the "ttl_kind" field. +func (u *VirtualMachineUpsertOne) ClearTTLKind() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearTTLKind() + }) +} + +// SetTTL sets the "ttl" field. +func (u *VirtualMachineUpsertOne) SetTTL(v int64) *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetTTL(v) + }) +} + +// AddTTL adds v to the "ttl" field. +func (u *VirtualMachineUpsertOne) AddTTL(v int64) *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.AddTTL(v) + }) +} + +// UpdateTTL sets the "ttl" field to the value that was provided on create. +func (u *VirtualMachineUpsertOne) UpdateTTL() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateTTL() + }) +} + +// ClearTTL clears the value of the "ttl" field. +func (u *VirtualMachineUpsertOne) ClearTTL() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearTTL() + }) +} + +// SetVersion sets the "version" field. +func (u *VirtualMachineUpsertOne) SetVersion(v string) *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetVersion(v) + }) +} + +// UpdateVersion sets the "version" field to the value that was provided on create. +func (u *VirtualMachineUpsertOne) UpdateVersion() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateVersion() + }) +} + +// ClearVersion clears the value of the "version" field. +func (u *VirtualMachineUpsertOne) ClearVersion() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearVersion() + }) +} + +// SetMachineID sets the "machine_id" field. +func (u *VirtualMachineUpsertOne) SetMachineID(v string) *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetMachineID(v) + }) +} + +// UpdateMachineID sets the "machine_id" field to the value that was provided on create. +func (u *VirtualMachineUpsertOne) UpdateMachineID() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateMachineID() + }) +} + +// ClearMachineID clears the value of the "machine_id" field. +func (u *VirtualMachineUpsertOne) ClearMachineID() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearMachineID() + }) +} + +// SetRepoURL sets the "repo_url" field. +func (u *VirtualMachineUpsertOne) SetRepoURL(v string) *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetRepoURL(v) + }) +} + +// UpdateRepoURL sets the "repo_url" field to the value that was provided on create. +func (u *VirtualMachineUpsertOne) UpdateRepoURL() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateRepoURL() + }) +} + +// ClearRepoURL clears the value of the "repo_url" field. +func (u *VirtualMachineUpsertOne) ClearRepoURL() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearRepoURL() + }) +} + +// SetRepoFilename sets the "repo_filename" field. +func (u *VirtualMachineUpsertOne) SetRepoFilename(v string) *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetRepoFilename(v) + }) +} + +// UpdateRepoFilename sets the "repo_filename" field to the value that was provided on create. +func (u *VirtualMachineUpsertOne) UpdateRepoFilename() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateRepoFilename() + }) +} + +// ClearRepoFilename clears the value of the "repo_filename" field. +func (u *VirtualMachineUpsertOne) ClearRepoFilename() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearRepoFilename() + }) +} + +// SetBranch sets the "branch" field. +func (u *VirtualMachineUpsertOne) SetBranch(v string) *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetBranch(v) + }) +} + +// UpdateBranch sets the "branch" field to the value that was provided on create. +func (u *VirtualMachineUpsertOne) UpdateBranch() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateBranch() + }) +} + +// ClearBranch clears the value of the "branch" field. +func (u *VirtualMachineUpsertOne) ClearBranch() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearBranch() + }) +} + +// SetIsRecycled sets the "is_recycled" field. +func (u *VirtualMachineUpsertOne) SetIsRecycled(v bool) *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetIsRecycled(v) + }) +} + +// UpdateIsRecycled sets the "is_recycled" field to the value that was provided on create. +func (u *VirtualMachineUpsertOne) UpdateIsRecycled() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateIsRecycled() + }) +} + +// ClearIsRecycled clears the value of the "is_recycled" field. +func (u *VirtualMachineUpsertOne) ClearIsRecycled() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearIsRecycled() + }) +} + +// SetConditions sets the "conditions" field. +func (u *VirtualMachineUpsertOne) SetConditions(v *types.VirtualMachineCondition) *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetConditions(v) + }) +} + +// UpdateConditions sets the "conditions" field to the value that was provided on create. +func (u *VirtualMachineUpsertOne) UpdateConditions() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateConditions() + }) +} + +// ClearConditions clears the value of the "conditions" field. +func (u *VirtualMachineUpsertOne) ClearConditions() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearConditions() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *VirtualMachineUpsertOne) SetCreatedAt(v time.Time) *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *VirtualMachineUpsertOne) UpdateCreatedAt() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateCreatedAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *VirtualMachineUpsertOne) SetUpdatedAt(v time.Time) *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *VirtualMachineUpsertOne) UpdateUpdatedAt() *VirtualMachineUpsertOne { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateUpdatedAt() + }) +} + +// Exec executes the query. +func (u *VirtualMachineUpsertOne) Exec(ctx context.Context) error { + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for VirtualMachineCreate.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *VirtualMachineUpsertOne) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} + +// Exec executes the UPSERT query and returns the inserted/updated ID. +func (u *VirtualMachineUpsertOne) ID(ctx context.Context) (id string, err error) { + if u.create.driver.Dialect() == dialect.MySQL { + // In case of "ON CONFLICT", there is no way to get back non-numeric ID + // fields from the database since MySQL does not support the RETURNING clause. + return id, errors.New("db: VirtualMachineUpsertOne.ID is not supported by MySQL driver. Use VirtualMachineUpsertOne.Exec instead") + } + node, err := u.create.Save(ctx) + if err != nil { + return id, err + } + return node.ID, nil +} + +// IDX is like ID, but panics if an error occurs. +func (u *VirtualMachineUpsertOne) IDX(ctx context.Context) string { + id, err := u.ID(ctx) + if err != nil { + panic(err) + } + return id +} + +// VirtualMachineCreateBulk is the builder for creating many VirtualMachine entities in bulk. +type VirtualMachineCreateBulk struct { + config + err error + builders []*VirtualMachineCreate + conflict []sql.ConflictOption +} + +// Save creates the VirtualMachine entities in the database. +func (_c *VirtualMachineCreateBulk) Save(ctx context.Context) ([]*VirtualMachine, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*VirtualMachine, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*VirtualMachineMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + spec.OnConflict = _c.conflict + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.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, _c.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (_c *VirtualMachineCreateBulk) SaveX(ctx context.Context) []*VirtualMachine { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *VirtualMachineCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *VirtualMachineCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause +// of the `INSERT` statement. For example: +// +// client.VirtualMachine.CreateBulk(builders...). +// OnConflict( +// // Update the row with the new values +// // the was proposed for insertion. +// sql.ResolveWithNewValues(), +// ). +// // Override some of the fields with custom +// // update values. +// Update(func(u *ent.VirtualMachineUpsert) { +// SetDeletedAt(v+v). +// }). +// Exec(ctx) +func (_c *VirtualMachineCreateBulk) OnConflict(opts ...sql.ConflictOption) *VirtualMachineUpsertBulk { + _c.conflict = opts + return &VirtualMachineUpsertBulk{ + create: _c, + } +} + +// OnConflictColumns calls `OnConflict` and configures the columns +// as conflict target. Using this option is equivalent to using: +// +// client.VirtualMachine.Create(). +// OnConflict(sql.ConflictColumns(columns...)). +// Exec(ctx) +func (_c *VirtualMachineCreateBulk) OnConflictColumns(columns ...string) *VirtualMachineUpsertBulk { + _c.conflict = append(_c.conflict, sql.ConflictColumns(columns...)) + return &VirtualMachineUpsertBulk{ + create: _c, + } +} + +// VirtualMachineUpsertBulk is the builder for "upsert"-ing +// a bulk of VirtualMachine nodes. +type VirtualMachineUpsertBulk struct { + create *VirtualMachineCreateBulk +} + +// UpdateNewValues updates the mutable fields using the new values that +// were set on create. Using this option is equivalent to using: +// +// client.VirtualMachine.Create(). +// OnConflict( +// sql.ResolveWithNewValues(), +// sql.ResolveWith(func(u *sql.UpdateSet) { +// u.SetIgnore(virtualmachine.FieldID) +// }), +// ). +// Exec(ctx) +func (u *VirtualMachineUpsertBulk) UpdateNewValues() *VirtualMachineUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues()) + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) { + for _, b := range u.create.builders { + if _, exists := b.mutation.ID(); exists { + s.SetIgnore(virtualmachine.FieldID) + } + } + })) + return u +} + +// Ignore sets each column to itself in case of conflict. +// Using this option is equivalent to using: +// +// client.VirtualMachine.Create(). +// OnConflict(sql.ResolveWithIgnore()). +// Exec(ctx) +func (u *VirtualMachineUpsertBulk) Ignore() *VirtualMachineUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore()) + return u +} + +// DoNothing configures the conflict_action to `DO NOTHING`. +// Supported only by SQLite and PostgreSQL. +func (u *VirtualMachineUpsertBulk) DoNothing() *VirtualMachineUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.DoNothing()) + return u +} + +// Update allows overriding fields `UPDATE` values. See the VirtualMachineCreateBulk.OnConflict +// documentation for more info. +func (u *VirtualMachineUpsertBulk) Update(set func(*VirtualMachineUpsert)) *VirtualMachineUpsertBulk { + u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) { + set(&VirtualMachineUpsert{UpdateSet: update}) + })) + return u +} + +// SetDeletedAt sets the "deleted_at" field. +func (u *VirtualMachineUpsertBulk) SetDeletedAt(v time.Time) *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetDeletedAt(v) + }) +} + +// UpdateDeletedAt sets the "deleted_at" field to the value that was provided on create. +func (u *VirtualMachineUpsertBulk) UpdateDeletedAt() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateDeletedAt() + }) +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (u *VirtualMachineUpsertBulk) ClearDeletedAt() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearDeletedAt() + }) +} + +// SetHostID sets the "host_id" field. +func (u *VirtualMachineUpsertBulk) SetHostID(v string) *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetHostID(v) + }) +} + +// UpdateHostID sets the "host_id" field to the value that was provided on create. +func (u *VirtualMachineUpsertBulk) UpdateHostID() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateHostID() + }) +} + +// SetUserID sets the "user_id" field. +func (u *VirtualMachineUpsertBulk) SetUserID(v uuid.UUID) *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetUserID(v) + }) +} + +// UpdateUserID sets the "user_id" field to the value that was provided on create. +func (u *VirtualMachineUpsertBulk) UpdateUserID() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateUserID() + }) +} + +// ClearUserID clears the value of the "user_id" field. +func (u *VirtualMachineUpsertBulk) ClearUserID() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearUserID() + }) +} + +// SetModelID sets the "model_id" field. +func (u *VirtualMachineUpsertBulk) SetModelID(v uuid.UUID) *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetModelID(v) + }) +} + +// UpdateModelID sets the "model_id" field to the value that was provided on create. +func (u *VirtualMachineUpsertBulk) UpdateModelID() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateModelID() + }) +} + +// ClearModelID clears the value of the "model_id" field. +func (u *VirtualMachineUpsertBulk) ClearModelID() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearModelID() + }) +} + +// SetEnvironmentID sets the "environment_id" field. +func (u *VirtualMachineUpsertBulk) SetEnvironmentID(v string) *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetEnvironmentID(v) + }) +} + +// UpdateEnvironmentID sets the "environment_id" field to the value that was provided on create. +func (u *VirtualMachineUpsertBulk) UpdateEnvironmentID() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateEnvironmentID() + }) +} + +// ClearEnvironmentID clears the value of the "environment_id" field. +func (u *VirtualMachineUpsertBulk) ClearEnvironmentID() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearEnvironmentID() + }) +} + +// SetName sets the "name" field. +func (u *VirtualMachineUpsertBulk) SetName(v string) *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetName(v) + }) +} + +// UpdateName sets the "name" field to the value that was provided on create. +func (u *VirtualMachineUpsertBulk) UpdateName() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateName() + }) +} + +// SetHostname sets the "hostname" field. +func (u *VirtualMachineUpsertBulk) SetHostname(v string) *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetHostname(v) + }) +} + +// UpdateHostname sets the "hostname" field to the value that was provided on create. +func (u *VirtualMachineUpsertBulk) UpdateHostname() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateHostname() + }) +} + +// ClearHostname clears the value of the "hostname" field. +func (u *VirtualMachineUpsertBulk) ClearHostname() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearHostname() + }) +} + +// SetArch sets the "arch" field. +func (u *VirtualMachineUpsertBulk) SetArch(v string) *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetArch(v) + }) +} + +// UpdateArch sets the "arch" field to the value that was provided on create. +func (u *VirtualMachineUpsertBulk) UpdateArch() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateArch() + }) +} + +// ClearArch clears the value of the "arch" field. +func (u *VirtualMachineUpsertBulk) ClearArch() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearArch() + }) +} + +// SetCores sets the "cores" field. +func (u *VirtualMachineUpsertBulk) SetCores(v int) *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetCores(v) + }) +} + +// AddCores adds v to the "cores" field. +func (u *VirtualMachineUpsertBulk) AddCores(v int) *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.AddCores(v) + }) +} + +// UpdateCores sets the "cores" field to the value that was provided on create. +func (u *VirtualMachineUpsertBulk) UpdateCores() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateCores() + }) +} + +// ClearCores clears the value of the "cores" field. +func (u *VirtualMachineUpsertBulk) ClearCores() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearCores() + }) +} + +// SetMemory sets the "memory" field. +func (u *VirtualMachineUpsertBulk) SetMemory(v int64) *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetMemory(v) + }) +} + +// AddMemory adds v to the "memory" field. +func (u *VirtualMachineUpsertBulk) AddMemory(v int64) *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.AddMemory(v) + }) +} + +// UpdateMemory sets the "memory" field to the value that was provided on create. +func (u *VirtualMachineUpsertBulk) UpdateMemory() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateMemory() + }) +} + +// ClearMemory clears the value of the "memory" field. +func (u *VirtualMachineUpsertBulk) ClearMemory() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearMemory() + }) +} + +// SetOs sets the "os" field. +func (u *VirtualMachineUpsertBulk) SetOs(v string) *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetOs(v) + }) +} + +// UpdateOs sets the "os" field to the value that was provided on create. +func (u *VirtualMachineUpsertBulk) UpdateOs() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateOs() + }) +} + +// ClearOs clears the value of the "os" field. +func (u *VirtualMachineUpsertBulk) ClearOs() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearOs() + }) +} + +// SetExternalIP sets the "external_ip" field. +func (u *VirtualMachineUpsertBulk) SetExternalIP(v string) *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetExternalIP(v) + }) +} + +// UpdateExternalIP sets the "external_ip" field to the value that was provided on create. +func (u *VirtualMachineUpsertBulk) UpdateExternalIP() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateExternalIP() + }) +} + +// ClearExternalIP clears the value of the "external_ip" field. +func (u *VirtualMachineUpsertBulk) ClearExternalIP() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearExternalIP() + }) +} + +// SetInternalIP sets the "internal_ip" field. +func (u *VirtualMachineUpsertBulk) SetInternalIP(v string) *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetInternalIP(v) + }) +} + +// UpdateInternalIP sets the "internal_ip" field to the value that was provided on create. +func (u *VirtualMachineUpsertBulk) UpdateInternalIP() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateInternalIP() + }) +} + +// ClearInternalIP clears the value of the "internal_ip" field. +func (u *VirtualMachineUpsertBulk) ClearInternalIP() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearInternalIP() + }) +} + +// SetTTLKind sets the "ttl_kind" field. +func (u *VirtualMachineUpsertBulk) SetTTLKind(v consts.VirtualmachineTTLKind) *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetTTLKind(v) + }) +} + +// UpdateTTLKind sets the "ttl_kind" field to the value that was provided on create. +func (u *VirtualMachineUpsertBulk) UpdateTTLKind() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateTTLKind() + }) +} + +// ClearTTLKind clears the value of the "ttl_kind" field. +func (u *VirtualMachineUpsertBulk) ClearTTLKind() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearTTLKind() + }) +} + +// SetTTL sets the "ttl" field. +func (u *VirtualMachineUpsertBulk) SetTTL(v int64) *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetTTL(v) + }) +} + +// AddTTL adds v to the "ttl" field. +func (u *VirtualMachineUpsertBulk) AddTTL(v int64) *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.AddTTL(v) + }) +} + +// UpdateTTL sets the "ttl" field to the value that was provided on create. +func (u *VirtualMachineUpsertBulk) UpdateTTL() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateTTL() + }) +} + +// ClearTTL clears the value of the "ttl" field. +func (u *VirtualMachineUpsertBulk) ClearTTL() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearTTL() + }) +} + +// SetVersion sets the "version" field. +func (u *VirtualMachineUpsertBulk) SetVersion(v string) *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetVersion(v) + }) +} + +// UpdateVersion sets the "version" field to the value that was provided on create. +func (u *VirtualMachineUpsertBulk) UpdateVersion() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateVersion() + }) +} + +// ClearVersion clears the value of the "version" field. +func (u *VirtualMachineUpsertBulk) ClearVersion() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearVersion() + }) +} + +// SetMachineID sets the "machine_id" field. +func (u *VirtualMachineUpsertBulk) SetMachineID(v string) *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetMachineID(v) + }) +} + +// UpdateMachineID sets the "machine_id" field to the value that was provided on create. +func (u *VirtualMachineUpsertBulk) UpdateMachineID() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateMachineID() + }) +} + +// ClearMachineID clears the value of the "machine_id" field. +func (u *VirtualMachineUpsertBulk) ClearMachineID() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearMachineID() + }) +} + +// SetRepoURL sets the "repo_url" field. +func (u *VirtualMachineUpsertBulk) SetRepoURL(v string) *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetRepoURL(v) + }) +} + +// UpdateRepoURL sets the "repo_url" field to the value that was provided on create. +func (u *VirtualMachineUpsertBulk) UpdateRepoURL() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateRepoURL() + }) +} + +// ClearRepoURL clears the value of the "repo_url" field. +func (u *VirtualMachineUpsertBulk) ClearRepoURL() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearRepoURL() + }) +} + +// SetRepoFilename sets the "repo_filename" field. +func (u *VirtualMachineUpsertBulk) SetRepoFilename(v string) *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetRepoFilename(v) + }) +} + +// UpdateRepoFilename sets the "repo_filename" field to the value that was provided on create. +func (u *VirtualMachineUpsertBulk) UpdateRepoFilename() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateRepoFilename() + }) +} + +// ClearRepoFilename clears the value of the "repo_filename" field. +func (u *VirtualMachineUpsertBulk) ClearRepoFilename() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearRepoFilename() + }) +} + +// SetBranch sets the "branch" field. +func (u *VirtualMachineUpsertBulk) SetBranch(v string) *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetBranch(v) + }) +} + +// UpdateBranch sets the "branch" field to the value that was provided on create. +func (u *VirtualMachineUpsertBulk) UpdateBranch() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateBranch() + }) +} + +// ClearBranch clears the value of the "branch" field. +func (u *VirtualMachineUpsertBulk) ClearBranch() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearBranch() + }) +} + +// SetIsRecycled sets the "is_recycled" field. +func (u *VirtualMachineUpsertBulk) SetIsRecycled(v bool) *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetIsRecycled(v) + }) +} + +// UpdateIsRecycled sets the "is_recycled" field to the value that was provided on create. +func (u *VirtualMachineUpsertBulk) UpdateIsRecycled() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateIsRecycled() + }) +} + +// ClearIsRecycled clears the value of the "is_recycled" field. +func (u *VirtualMachineUpsertBulk) ClearIsRecycled() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearIsRecycled() + }) +} + +// SetConditions sets the "conditions" field. +func (u *VirtualMachineUpsertBulk) SetConditions(v *types.VirtualMachineCondition) *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetConditions(v) + }) +} + +// UpdateConditions sets the "conditions" field to the value that was provided on create. +func (u *VirtualMachineUpsertBulk) UpdateConditions() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateConditions() + }) +} + +// ClearConditions clears the value of the "conditions" field. +func (u *VirtualMachineUpsertBulk) ClearConditions() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.ClearConditions() + }) +} + +// SetCreatedAt sets the "created_at" field. +func (u *VirtualMachineUpsertBulk) SetCreatedAt(v time.Time) *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetCreatedAt(v) + }) +} + +// UpdateCreatedAt sets the "created_at" field to the value that was provided on create. +func (u *VirtualMachineUpsertBulk) UpdateCreatedAt() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateCreatedAt() + }) +} + +// SetUpdatedAt sets the "updated_at" field. +func (u *VirtualMachineUpsertBulk) SetUpdatedAt(v time.Time) *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.SetUpdatedAt(v) + }) +} + +// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create. +func (u *VirtualMachineUpsertBulk) UpdateUpdatedAt() *VirtualMachineUpsertBulk { + return u.Update(func(s *VirtualMachineUpsert) { + s.UpdateUpdatedAt() + }) +} + +// Exec executes the query. +func (u *VirtualMachineUpsertBulk) Exec(ctx context.Context) error { + if u.create.err != nil { + return u.create.err + } + for i, b := range u.create.builders { + if len(b.conflict) != 0 { + return fmt.Errorf("db: OnConflict was set for builder %d. Set it on the VirtualMachineCreateBulk instead", i) + } + } + if len(u.create.conflict) == 0 { + return errors.New("db: missing options for VirtualMachineCreateBulk.OnConflict") + } + return u.create.Exec(ctx) +} + +// ExecX is like Exec, but panics if an error occurs. +func (u *VirtualMachineUpsertBulk) ExecX(ctx context.Context) { + if err := u.create.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/virtualmachine_delete.go b/backend/db/virtualmachine_delete.go new file mode 100644 index 00000000..99869445 --- /dev/null +++ b/backend/db/virtualmachine_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/virtualmachine" +) + +// VirtualMachineDelete is the builder for deleting a VirtualMachine entity. +type VirtualMachineDelete struct { + config + hooks []Hook + mutation *VirtualMachineMutation +} + +// Where appends a list predicates to the VirtualMachineDelete builder. +func (_d *VirtualMachineDelete) Where(ps ...predicate.VirtualMachine) *VirtualMachineDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *VirtualMachineDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *VirtualMachineDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *VirtualMachineDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(virtualmachine.Table, sqlgraph.NewFieldSpec(virtualmachine.FieldID, field.TypeString)) + if ps := _d.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + _d.mutation.done = true + return affected, err +} + +// VirtualMachineDeleteOne is the builder for deleting a single VirtualMachine entity. +type VirtualMachineDeleteOne struct { + _d *VirtualMachineDelete +} + +// Where appends a list predicates to the VirtualMachineDelete builder. +func (_d *VirtualMachineDeleteOne) Where(ps ...predicate.VirtualMachine) *VirtualMachineDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *VirtualMachineDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{virtualmachine.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *VirtualMachineDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/backend/db/virtualmachine_query.go b/backend/db/virtualmachine_query.go new file mode 100644 index 00000000..e6dd70c3 --- /dev/null +++ b/backend/db/virtualmachine_query.go @@ -0,0 +1,807 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/db/host" + "github.com/chaitin/MonkeyCode/backend/db/model" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/virtualmachine" + "github.com/google/uuid" +) + +// VirtualMachineQuery is the builder for querying VirtualMachine entities. +type VirtualMachineQuery struct { + config + ctx *QueryContext + order []virtualmachine.OrderOption + inters []Interceptor + predicates []predicate.VirtualMachine + withHost *HostQuery + withModel *ModelQuery + withUser *UserQuery + modifiers []func(*sql.Selector) + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the VirtualMachineQuery builder. +func (_q *VirtualMachineQuery) Where(ps ...predicate.VirtualMachine) *VirtualMachineQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *VirtualMachineQuery) Limit(limit int) *VirtualMachineQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *VirtualMachineQuery) Offset(offset int) *VirtualMachineQuery { + _q.ctx.Offset = &offset + return _q +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (_q *VirtualMachineQuery) Unique(unique bool) *VirtualMachineQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *VirtualMachineQuery) Order(o ...virtualmachine.OrderOption) *VirtualMachineQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryHost chains the current query on the "host" edge. +func (_q *VirtualMachineQuery) QueryHost() *HostQuery { + query := (&HostClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(virtualmachine.Table, virtualmachine.FieldID, selector), + sqlgraph.To(host.Table, host.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, virtualmachine.HostTable, virtualmachine.HostColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryModel chains the current query on the "model" edge. +func (_q *VirtualMachineQuery) QueryModel() *ModelQuery { + query := (&ModelClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(virtualmachine.Table, virtualmachine.FieldID, selector), + sqlgraph.To(model.Table, model.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, virtualmachine.ModelTable, virtualmachine.ModelColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryUser chains the current query on the "user" edge. +func (_q *VirtualMachineQuery) QueryUser() *UserQuery { + query := (&UserClient{config: _q.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + selector := _q.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(virtualmachine.Table, virtualmachine.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, virtualmachine.UserTable, virtualmachine.UserColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first VirtualMachine entity from the query. +// Returns a *NotFoundError when no VirtualMachine was found. +func (_q *VirtualMachineQuery) First(ctx context.Context) (*VirtualMachine, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{virtualmachine.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *VirtualMachineQuery) FirstX(ctx context.Context) *VirtualMachine { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first VirtualMachine ID from the query. +// Returns a *NotFoundError when no VirtualMachine ID was found. +func (_q *VirtualMachineQuery) FirstID(ctx context.Context) (id string, err error) { + var ids []string + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{virtualmachine.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *VirtualMachineQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single VirtualMachine entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one VirtualMachine entity is found. +// Returns a *NotFoundError when no VirtualMachine entities are found. +func (_q *VirtualMachineQuery) Only(ctx context.Context) (*VirtualMachine, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{virtualmachine.Label} + default: + return nil, &NotSingularError{virtualmachine.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *VirtualMachineQuery) OnlyX(ctx context.Context) *VirtualMachine { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only VirtualMachine ID in the query. +// Returns a *NotSingularError when more than one VirtualMachine ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *VirtualMachineQuery) OnlyID(ctx context.Context) (id string, err error) { + var ids []string + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{virtualmachine.Label} + default: + err = &NotSingularError{virtualmachine.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *VirtualMachineQuery) OnlyIDX(ctx context.Context) string { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of VirtualMachines. +func (_q *VirtualMachineQuery) All(ctx context.Context) ([]*VirtualMachine, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*VirtualMachine, *VirtualMachineQuery]() + return withInterceptors[[]*VirtualMachine](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *VirtualMachineQuery) AllX(ctx context.Context) []*VirtualMachine { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of VirtualMachine IDs. +func (_q *VirtualMachineQuery) IDs(ctx context.Context) (ids []string, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(virtualmachine.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *VirtualMachineQuery) IDsX(ctx context.Context) []string { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *VirtualMachineQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, _q, querierCount[*VirtualMachineQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *VirtualMachineQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (_q *VirtualMachineQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("db: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *VirtualMachineQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the VirtualMachineQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (_q *VirtualMachineQuery) Clone() *VirtualMachineQuery { + if _q == nil { + return nil + } + return &VirtualMachineQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]virtualmachine.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.VirtualMachine{}, _q.predicates...), + withHost: _q.withHost.Clone(), + withModel: _q.withModel.Clone(), + withUser: _q.withUser.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + modifiers: append([]func(*sql.Selector){}, _q.modifiers...), + } +} + +// WithHost tells the query-builder to eager-load the nodes that are connected to +// the "host" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *VirtualMachineQuery) WithHost(opts ...func(*HostQuery)) *VirtualMachineQuery { + query := (&HostClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withHost = query + return _q +} + +// WithModel tells the query-builder to eager-load the nodes that are connected to +// the "model" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *VirtualMachineQuery) WithModel(opts ...func(*ModelQuery)) *VirtualMachineQuery { + query := (&ModelClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withModel = query + return _q +} + +// WithUser tells the query-builder to eager-load the nodes that are connected to +// the "user" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *VirtualMachineQuery) WithUser(opts ...func(*UserQuery)) *VirtualMachineQuery { + query := (&UserClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withUser = query + return _q +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// DeletedAt time.Time `json:"deleted_at,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.VirtualMachine.Query(). +// GroupBy(virtualmachine.FieldDeletedAt). +// Aggregate(db.Count()). +// Scan(ctx, &v) +func (_q *VirtualMachineQuery) GroupBy(field string, fields ...string) *VirtualMachineGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &VirtualMachineGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = virtualmachine.Label + grbuild.scan = grbuild.Scan + return grbuild +} + +// Select allows the selection one or more fields/columns for the given query, +// instead of selecting all fields in the entity. +// +// Example: +// +// var v []struct { +// DeletedAt time.Time `json:"deleted_at,omitempty"` +// } +// +// client.VirtualMachine.Query(). +// Select(virtualmachine.FieldDeletedAt). +// Scan(ctx, &v) +func (_q *VirtualMachineQuery) Select(fields ...string) *VirtualMachineSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &VirtualMachineSelect{VirtualMachineQuery: _q} + sbuild.label = virtualmachine.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a VirtualMachineSelect configured with the given aggregations. +func (_q *VirtualMachineQuery) Aggregate(fns ...AggregateFunc) *VirtualMachineSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *VirtualMachineQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !virtualmachine.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + } + if _q.path != nil { + prev, err := _q.path(ctx) + if err != nil { + return err + } + _q.sql = prev + } + return nil +} + +func (_q *VirtualMachineQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*VirtualMachine, error) { + var ( + nodes = []*VirtualMachine{} + _spec = _q.querySpec() + loadedTypes = [3]bool{ + _q.withHost != nil, + _q.withModel != nil, + _q.withUser != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*VirtualMachine).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &VirtualMachine{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withHost; query != nil { + if err := _q.loadHost(ctx, query, nodes, nil, + func(n *VirtualMachine, e *Host) { n.Edges.Host = e }); err != nil { + return nil, err + } + } + if query := _q.withModel; query != nil { + if err := _q.loadModel(ctx, query, nodes, nil, + func(n *VirtualMachine, e *Model) { n.Edges.Model = e }); err != nil { + return nil, err + } + } + if query := _q.withUser; query != nil { + if err := _q.loadUser(ctx, query, nodes, nil, + func(n *VirtualMachine, e *User) { n.Edges.User = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *VirtualMachineQuery) loadHost(ctx context.Context, query *HostQuery, nodes []*VirtualMachine, init func(*VirtualMachine), assign func(*VirtualMachine, *Host)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*VirtualMachine) + for i := range nodes { + fk := nodes[i].HostID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(host.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 "host_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *VirtualMachineQuery) loadModel(ctx context.Context, query *ModelQuery, nodes []*VirtualMachine, init func(*VirtualMachine), assign func(*VirtualMachine, *Model)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*VirtualMachine) + for i := range nodes { + fk := nodes[i].ModelID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(model.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 "model_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *VirtualMachineQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*VirtualMachine, init func(*VirtualMachine), assign func(*VirtualMachine, *User)) error { + ids := make([]uuid.UUID, 0, len(nodes)) + nodeids := make(map[uuid.UUID][]*VirtualMachine) + for i := range nodes { + fk := nodes[i].UserID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(user.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "user_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *VirtualMachineQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + if len(_q.modifiers) > 0 { + _spec.Modifiers = _q.modifiers + } + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique + } + return sqlgraph.CountNodes(ctx, _q.driver, _spec) +} + +func (_q *VirtualMachineQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(virtualmachine.Table, virtualmachine.Columns, sqlgraph.NewFieldSpec(virtualmachine.FieldID, field.TypeString)) + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if _q.path != nil { + _spec.Unique = true + } + if fields := _q.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, virtualmachine.FieldID) + for i := range fields { + if fields[i] != virtualmachine.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if _q.withHost != nil { + _spec.Node.AddColumnOnce(virtualmachine.FieldHostID) + } + if _q.withModel != nil { + _spec.Node.AddColumnOnce(virtualmachine.FieldModelID) + } + if _q.withUser != nil { + _spec.Node.AddColumnOnce(virtualmachine.FieldUserID) + } + } + if ps := _q.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := _q.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := _q.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := _q.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (_q *VirtualMachineQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(virtualmachine.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = virtualmachine.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if _q.sql != nil { + selector = _q.sql + selector.Select(selector.Columns(columns...)...) + } + if _q.ctx.Unique != nil && *_q.ctx.Unique { + selector.Distinct() + } + for _, m := range _q.modifiers { + m(selector) + } + for _, p := range _q.predicates { + p(selector) + } + for _, p := range _q.order { + p(selector) + } + if offset := _q.ctx.Offset; offset != nil { + // limit is mandatory for offset clause. We start + // with default value, and override it below if needed. + selector.Offset(*offset).Limit(math.MaxInt32) + } + if limit := _q.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// ForUpdate locks the selected rows against concurrent updates, and prevent them from being +// updated, deleted or "selected ... for update" by other sessions, until the transaction is +// either committed or rolled-back. +func (_q *VirtualMachineQuery) ForUpdate(opts ...sql.LockOption) *VirtualMachineQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForUpdate(opts...) + }) + return _q +} + +// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock +// on any rows that are read. Other sessions can read the rows, but cannot modify them +// until your transaction commits. +func (_q *VirtualMachineQuery) ForShare(opts ...sql.LockOption) *VirtualMachineQuery { + if _q.driver.Dialect() == dialect.Postgres { + _q.Unique(false) + } + _q.modifiers = append(_q.modifiers, func(s *sql.Selector) { + s.ForShare(opts...) + }) + return _q +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (_q *VirtualMachineQuery) Modify(modifiers ...func(s *sql.Selector)) *VirtualMachineSelect { + _q.modifiers = append(_q.modifiers, modifiers...) + return _q.Select() +} + +// VirtualMachineGroupBy is the group-by builder for VirtualMachine entities. +type VirtualMachineGroupBy struct { + selector + build *VirtualMachineQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *VirtualMachineGroupBy) Aggregate(fns ...AggregateFunc) *VirtualMachineGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *VirtualMachineGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*VirtualMachineQuery, *VirtualMachineGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *VirtualMachineGroupBy) sqlScan(ctx context.Context, root *VirtualMachineQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*_g.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// VirtualMachineSelect is the builder for selecting fields of VirtualMachine entities. +type VirtualMachineSelect struct { + *VirtualMachineQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *VirtualMachineSelect) Aggregate(fns ...AggregateFunc) *VirtualMachineSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *VirtualMachineSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*VirtualMachineQuery, *VirtualMachineSelect](ctx, _s.VirtualMachineQuery, _s, _s.inters, v) +} + +func (_s *VirtualMachineSelect) sqlScan(ctx context.Context, root *VirtualMachineQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*_s.selector.flds); { + case n == 0 && len(aggregation) > 0: + selector.Select(aggregation...) + case n != 0 && len(aggregation) > 0: + selector.AppendSelect(aggregation...) + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := _s.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (_s *VirtualMachineSelect) Modify(modifiers ...func(s *sql.Selector)) *VirtualMachineSelect { + _s.modifiers = append(_s.modifiers, modifiers...) + return _s +} diff --git a/backend/db/virtualmachine_update.go b/backend/db/virtualmachine_update.go new file mode 100644 index 00000000..ce3e9383 --- /dev/null +++ b/backend/db/virtualmachine_update.go @@ -0,0 +1,1650 @@ +// Code generated by ent, DO NOT EDIT. + +package db + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/chaitin/MonkeyCode/backend/consts" + "github.com/chaitin/MonkeyCode/backend/db/host" + "github.com/chaitin/MonkeyCode/backend/db/model" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/virtualmachine" + "github.com/chaitin/MonkeyCode/backend/ent/types" + "github.com/google/uuid" +) + +// VirtualMachineUpdate is the builder for updating VirtualMachine entities. +type VirtualMachineUpdate struct { + config + hooks []Hook + mutation *VirtualMachineMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the VirtualMachineUpdate builder. +func (_u *VirtualMachineUpdate) Where(ps ...predicate.VirtualMachine) *VirtualMachineUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *VirtualMachineUpdate) SetDeletedAt(v time.Time) *VirtualMachineUpdate { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *VirtualMachineUpdate) SetNillableDeletedAt(v *time.Time) *VirtualMachineUpdate { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *VirtualMachineUpdate) ClearDeletedAt() *VirtualMachineUpdate { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetHostID sets the "host_id" field. +func (_u *VirtualMachineUpdate) SetHostID(v string) *VirtualMachineUpdate { + _u.mutation.SetHostID(v) + return _u +} + +// SetNillableHostID sets the "host_id" field if the given value is not nil. +func (_u *VirtualMachineUpdate) SetNillableHostID(v *string) *VirtualMachineUpdate { + if v != nil { + _u.SetHostID(*v) + } + return _u +} + +// SetUserID sets the "user_id" field. +func (_u *VirtualMachineUpdate) SetUserID(v uuid.UUID) *VirtualMachineUpdate { + _u.mutation.SetUserID(v) + return _u +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (_u *VirtualMachineUpdate) SetNillableUserID(v *uuid.UUID) *VirtualMachineUpdate { + if v != nil { + _u.SetUserID(*v) + } + return _u +} + +// ClearUserID clears the value of the "user_id" field. +func (_u *VirtualMachineUpdate) ClearUserID() *VirtualMachineUpdate { + _u.mutation.ClearUserID() + return _u +} + +// SetModelID sets the "model_id" field. +func (_u *VirtualMachineUpdate) SetModelID(v uuid.UUID) *VirtualMachineUpdate { + _u.mutation.SetModelID(v) + return _u +} + +// SetNillableModelID sets the "model_id" field if the given value is not nil. +func (_u *VirtualMachineUpdate) SetNillableModelID(v *uuid.UUID) *VirtualMachineUpdate { + if v != nil { + _u.SetModelID(*v) + } + return _u +} + +// ClearModelID clears the value of the "model_id" field. +func (_u *VirtualMachineUpdate) ClearModelID() *VirtualMachineUpdate { + _u.mutation.ClearModelID() + return _u +} + +// SetEnvironmentID sets the "environment_id" field. +func (_u *VirtualMachineUpdate) SetEnvironmentID(v string) *VirtualMachineUpdate { + _u.mutation.SetEnvironmentID(v) + return _u +} + +// SetNillableEnvironmentID sets the "environment_id" field if the given value is not nil. +func (_u *VirtualMachineUpdate) SetNillableEnvironmentID(v *string) *VirtualMachineUpdate { + if v != nil { + _u.SetEnvironmentID(*v) + } + return _u +} + +// ClearEnvironmentID clears the value of the "environment_id" field. +func (_u *VirtualMachineUpdate) ClearEnvironmentID() *VirtualMachineUpdate { + _u.mutation.ClearEnvironmentID() + return _u +} + +// SetName sets the "name" field. +func (_u *VirtualMachineUpdate) SetName(v string) *VirtualMachineUpdate { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *VirtualMachineUpdate) SetNillableName(v *string) *VirtualMachineUpdate { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetHostname sets the "hostname" field. +func (_u *VirtualMachineUpdate) SetHostname(v string) *VirtualMachineUpdate { + _u.mutation.SetHostname(v) + return _u +} + +// SetNillableHostname sets the "hostname" field if the given value is not nil. +func (_u *VirtualMachineUpdate) SetNillableHostname(v *string) *VirtualMachineUpdate { + if v != nil { + _u.SetHostname(*v) + } + return _u +} + +// ClearHostname clears the value of the "hostname" field. +func (_u *VirtualMachineUpdate) ClearHostname() *VirtualMachineUpdate { + _u.mutation.ClearHostname() + return _u +} + +// SetArch sets the "arch" field. +func (_u *VirtualMachineUpdate) SetArch(v string) *VirtualMachineUpdate { + _u.mutation.SetArch(v) + return _u +} + +// SetNillableArch sets the "arch" field if the given value is not nil. +func (_u *VirtualMachineUpdate) SetNillableArch(v *string) *VirtualMachineUpdate { + if v != nil { + _u.SetArch(*v) + } + return _u +} + +// ClearArch clears the value of the "arch" field. +func (_u *VirtualMachineUpdate) ClearArch() *VirtualMachineUpdate { + _u.mutation.ClearArch() + return _u +} + +// SetCores sets the "cores" field. +func (_u *VirtualMachineUpdate) SetCores(v int) *VirtualMachineUpdate { + _u.mutation.ResetCores() + _u.mutation.SetCores(v) + return _u +} + +// SetNillableCores sets the "cores" field if the given value is not nil. +func (_u *VirtualMachineUpdate) SetNillableCores(v *int) *VirtualMachineUpdate { + if v != nil { + _u.SetCores(*v) + } + return _u +} + +// AddCores adds value to the "cores" field. +func (_u *VirtualMachineUpdate) AddCores(v int) *VirtualMachineUpdate { + _u.mutation.AddCores(v) + return _u +} + +// ClearCores clears the value of the "cores" field. +func (_u *VirtualMachineUpdate) ClearCores() *VirtualMachineUpdate { + _u.mutation.ClearCores() + return _u +} + +// SetMemory sets the "memory" field. +func (_u *VirtualMachineUpdate) SetMemory(v int64) *VirtualMachineUpdate { + _u.mutation.ResetMemory() + _u.mutation.SetMemory(v) + return _u +} + +// SetNillableMemory sets the "memory" field if the given value is not nil. +func (_u *VirtualMachineUpdate) SetNillableMemory(v *int64) *VirtualMachineUpdate { + if v != nil { + _u.SetMemory(*v) + } + return _u +} + +// AddMemory adds value to the "memory" field. +func (_u *VirtualMachineUpdate) AddMemory(v int64) *VirtualMachineUpdate { + _u.mutation.AddMemory(v) + return _u +} + +// ClearMemory clears the value of the "memory" field. +func (_u *VirtualMachineUpdate) ClearMemory() *VirtualMachineUpdate { + _u.mutation.ClearMemory() + return _u +} + +// SetOs sets the "os" field. +func (_u *VirtualMachineUpdate) SetOs(v string) *VirtualMachineUpdate { + _u.mutation.SetOs(v) + return _u +} + +// SetNillableOs sets the "os" field if the given value is not nil. +func (_u *VirtualMachineUpdate) SetNillableOs(v *string) *VirtualMachineUpdate { + if v != nil { + _u.SetOs(*v) + } + return _u +} + +// ClearOs clears the value of the "os" field. +func (_u *VirtualMachineUpdate) ClearOs() *VirtualMachineUpdate { + _u.mutation.ClearOs() + return _u +} + +// SetExternalIP sets the "external_ip" field. +func (_u *VirtualMachineUpdate) SetExternalIP(v string) *VirtualMachineUpdate { + _u.mutation.SetExternalIP(v) + return _u +} + +// SetNillableExternalIP sets the "external_ip" field if the given value is not nil. +func (_u *VirtualMachineUpdate) SetNillableExternalIP(v *string) *VirtualMachineUpdate { + if v != nil { + _u.SetExternalIP(*v) + } + return _u +} + +// ClearExternalIP clears the value of the "external_ip" field. +func (_u *VirtualMachineUpdate) ClearExternalIP() *VirtualMachineUpdate { + _u.mutation.ClearExternalIP() + return _u +} + +// SetInternalIP sets the "internal_ip" field. +func (_u *VirtualMachineUpdate) SetInternalIP(v string) *VirtualMachineUpdate { + _u.mutation.SetInternalIP(v) + return _u +} + +// SetNillableInternalIP sets the "internal_ip" field if the given value is not nil. +func (_u *VirtualMachineUpdate) SetNillableInternalIP(v *string) *VirtualMachineUpdate { + if v != nil { + _u.SetInternalIP(*v) + } + return _u +} + +// ClearInternalIP clears the value of the "internal_ip" field. +func (_u *VirtualMachineUpdate) ClearInternalIP() *VirtualMachineUpdate { + _u.mutation.ClearInternalIP() + return _u +} + +// SetTTLKind sets the "ttl_kind" field. +func (_u *VirtualMachineUpdate) SetTTLKind(v consts.VirtualmachineTTLKind) *VirtualMachineUpdate { + _u.mutation.SetTTLKind(v) + return _u +} + +// SetNillableTTLKind sets the "ttl_kind" field if the given value is not nil. +func (_u *VirtualMachineUpdate) SetNillableTTLKind(v *consts.VirtualmachineTTLKind) *VirtualMachineUpdate { + if v != nil { + _u.SetTTLKind(*v) + } + return _u +} + +// ClearTTLKind clears the value of the "ttl_kind" field. +func (_u *VirtualMachineUpdate) ClearTTLKind() *VirtualMachineUpdate { + _u.mutation.ClearTTLKind() + return _u +} + +// SetTTL sets the "ttl" field. +func (_u *VirtualMachineUpdate) SetTTL(v int64) *VirtualMachineUpdate { + _u.mutation.ResetTTL() + _u.mutation.SetTTL(v) + return _u +} + +// SetNillableTTL sets the "ttl" field if the given value is not nil. +func (_u *VirtualMachineUpdate) SetNillableTTL(v *int64) *VirtualMachineUpdate { + if v != nil { + _u.SetTTL(*v) + } + return _u +} + +// AddTTL adds value to the "ttl" field. +func (_u *VirtualMachineUpdate) AddTTL(v int64) *VirtualMachineUpdate { + _u.mutation.AddTTL(v) + return _u +} + +// ClearTTL clears the value of the "ttl" field. +func (_u *VirtualMachineUpdate) ClearTTL() *VirtualMachineUpdate { + _u.mutation.ClearTTL() + return _u +} + +// SetVersion sets the "version" field. +func (_u *VirtualMachineUpdate) SetVersion(v string) *VirtualMachineUpdate { + _u.mutation.SetVersion(v) + return _u +} + +// SetNillableVersion sets the "version" field if the given value is not nil. +func (_u *VirtualMachineUpdate) SetNillableVersion(v *string) *VirtualMachineUpdate { + if v != nil { + _u.SetVersion(*v) + } + return _u +} + +// ClearVersion clears the value of the "version" field. +func (_u *VirtualMachineUpdate) ClearVersion() *VirtualMachineUpdate { + _u.mutation.ClearVersion() + return _u +} + +// SetMachineID sets the "machine_id" field. +func (_u *VirtualMachineUpdate) SetMachineID(v string) *VirtualMachineUpdate { + _u.mutation.SetMachineID(v) + return _u +} + +// SetNillableMachineID sets the "machine_id" field if the given value is not nil. +func (_u *VirtualMachineUpdate) SetNillableMachineID(v *string) *VirtualMachineUpdate { + if v != nil { + _u.SetMachineID(*v) + } + return _u +} + +// ClearMachineID clears the value of the "machine_id" field. +func (_u *VirtualMachineUpdate) ClearMachineID() *VirtualMachineUpdate { + _u.mutation.ClearMachineID() + return _u +} + +// SetRepoURL sets the "repo_url" field. +func (_u *VirtualMachineUpdate) SetRepoURL(v string) *VirtualMachineUpdate { + _u.mutation.SetRepoURL(v) + return _u +} + +// SetNillableRepoURL sets the "repo_url" field if the given value is not nil. +func (_u *VirtualMachineUpdate) SetNillableRepoURL(v *string) *VirtualMachineUpdate { + if v != nil { + _u.SetRepoURL(*v) + } + return _u +} + +// ClearRepoURL clears the value of the "repo_url" field. +func (_u *VirtualMachineUpdate) ClearRepoURL() *VirtualMachineUpdate { + _u.mutation.ClearRepoURL() + return _u +} + +// SetRepoFilename sets the "repo_filename" field. +func (_u *VirtualMachineUpdate) SetRepoFilename(v string) *VirtualMachineUpdate { + _u.mutation.SetRepoFilename(v) + return _u +} + +// SetNillableRepoFilename sets the "repo_filename" field if the given value is not nil. +func (_u *VirtualMachineUpdate) SetNillableRepoFilename(v *string) *VirtualMachineUpdate { + if v != nil { + _u.SetRepoFilename(*v) + } + return _u +} + +// ClearRepoFilename clears the value of the "repo_filename" field. +func (_u *VirtualMachineUpdate) ClearRepoFilename() *VirtualMachineUpdate { + _u.mutation.ClearRepoFilename() + return _u +} + +// SetBranch sets the "branch" field. +func (_u *VirtualMachineUpdate) SetBranch(v string) *VirtualMachineUpdate { + _u.mutation.SetBranch(v) + return _u +} + +// SetNillableBranch sets the "branch" field if the given value is not nil. +func (_u *VirtualMachineUpdate) SetNillableBranch(v *string) *VirtualMachineUpdate { + if v != nil { + _u.SetBranch(*v) + } + return _u +} + +// ClearBranch clears the value of the "branch" field. +func (_u *VirtualMachineUpdate) ClearBranch() *VirtualMachineUpdate { + _u.mutation.ClearBranch() + return _u +} + +// SetIsRecycled sets the "is_recycled" field. +func (_u *VirtualMachineUpdate) SetIsRecycled(v bool) *VirtualMachineUpdate { + _u.mutation.SetIsRecycled(v) + return _u +} + +// SetNillableIsRecycled sets the "is_recycled" field if the given value is not nil. +func (_u *VirtualMachineUpdate) SetNillableIsRecycled(v *bool) *VirtualMachineUpdate { + if v != nil { + _u.SetIsRecycled(*v) + } + return _u +} + +// ClearIsRecycled clears the value of the "is_recycled" field. +func (_u *VirtualMachineUpdate) ClearIsRecycled() *VirtualMachineUpdate { + _u.mutation.ClearIsRecycled() + return _u +} + +// SetConditions sets the "conditions" field. +func (_u *VirtualMachineUpdate) SetConditions(v *types.VirtualMachineCondition) *VirtualMachineUpdate { + _u.mutation.SetConditions(v) + return _u +} + +// ClearConditions clears the value of the "conditions" field. +func (_u *VirtualMachineUpdate) ClearConditions() *VirtualMachineUpdate { + _u.mutation.ClearConditions() + return _u +} + +// SetCreatedAt sets the "created_at" field. +func (_u *VirtualMachineUpdate) SetCreatedAt(v time.Time) *VirtualMachineUpdate { + _u.mutation.SetCreatedAt(v) + return _u +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_u *VirtualMachineUpdate) SetNillableCreatedAt(v *time.Time) *VirtualMachineUpdate { + if v != nil { + _u.SetCreatedAt(*v) + } + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *VirtualMachineUpdate) SetUpdatedAt(v time.Time) *VirtualMachineUpdate { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_u *VirtualMachineUpdate) SetNillableUpdatedAt(v *time.Time) *VirtualMachineUpdate { + if v != nil { + _u.SetUpdatedAt(*v) + } + return _u +} + +// SetHost sets the "host" edge to the Host entity. +func (_u *VirtualMachineUpdate) SetHost(v *Host) *VirtualMachineUpdate { + return _u.SetHostID(v.ID) +} + +// SetModel sets the "model" edge to the Model entity. +func (_u *VirtualMachineUpdate) SetModel(v *Model) *VirtualMachineUpdate { + return _u.SetModelID(v.ID) +} + +// SetUser sets the "user" edge to the User entity. +func (_u *VirtualMachineUpdate) SetUser(v *User) *VirtualMachineUpdate { + return _u.SetUserID(v.ID) +} + +// Mutation returns the VirtualMachineMutation object of the builder. +func (_u *VirtualMachineUpdate) Mutation() *VirtualMachineMutation { + return _u.mutation +} + +// ClearHost clears the "host" edge to the Host entity. +func (_u *VirtualMachineUpdate) ClearHost() *VirtualMachineUpdate { + _u.mutation.ClearHost() + return _u +} + +// ClearModel clears the "model" edge to the Model entity. +func (_u *VirtualMachineUpdate) ClearModel() *VirtualMachineUpdate { + _u.mutation.ClearModel() + return _u +} + +// ClearUser clears the "user" edge to the User entity. +func (_u *VirtualMachineUpdate) ClearUser() *VirtualMachineUpdate { + _u.mutation.ClearUser() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *VirtualMachineUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *VirtualMachineUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *VirtualMachineUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *VirtualMachineUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *VirtualMachineUpdate) check() error { + if _u.mutation.HostCleared() && len(_u.mutation.HostIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "VirtualMachine.host"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *VirtualMachineUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *VirtualMachineUpdate { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *VirtualMachineUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(virtualmachine.Table, virtualmachine.Columns, sqlgraph.NewFieldSpec(virtualmachine.FieldID, field.TypeString)) + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(virtualmachine.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(virtualmachine.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.EnvironmentID(); ok { + _spec.SetField(virtualmachine.FieldEnvironmentID, field.TypeString, value) + } + if _u.mutation.EnvironmentIDCleared() { + _spec.ClearField(virtualmachine.FieldEnvironmentID, field.TypeString) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(virtualmachine.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Hostname(); ok { + _spec.SetField(virtualmachine.FieldHostname, field.TypeString, value) + } + if _u.mutation.HostnameCleared() { + _spec.ClearField(virtualmachine.FieldHostname, field.TypeString) + } + if value, ok := _u.mutation.Arch(); ok { + _spec.SetField(virtualmachine.FieldArch, field.TypeString, value) + } + if _u.mutation.ArchCleared() { + _spec.ClearField(virtualmachine.FieldArch, field.TypeString) + } + if value, ok := _u.mutation.Cores(); ok { + _spec.SetField(virtualmachine.FieldCores, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedCores(); ok { + _spec.AddField(virtualmachine.FieldCores, field.TypeInt, value) + } + if _u.mutation.CoresCleared() { + _spec.ClearField(virtualmachine.FieldCores, field.TypeInt) + } + if value, ok := _u.mutation.Memory(); ok { + _spec.SetField(virtualmachine.FieldMemory, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedMemory(); ok { + _spec.AddField(virtualmachine.FieldMemory, field.TypeInt64, value) + } + if _u.mutation.MemoryCleared() { + _spec.ClearField(virtualmachine.FieldMemory, field.TypeInt64) + } + if value, ok := _u.mutation.Os(); ok { + _spec.SetField(virtualmachine.FieldOs, field.TypeString, value) + } + if _u.mutation.OsCleared() { + _spec.ClearField(virtualmachine.FieldOs, field.TypeString) + } + if value, ok := _u.mutation.ExternalIP(); ok { + _spec.SetField(virtualmachine.FieldExternalIP, field.TypeString, value) + } + if _u.mutation.ExternalIPCleared() { + _spec.ClearField(virtualmachine.FieldExternalIP, field.TypeString) + } + if value, ok := _u.mutation.InternalIP(); ok { + _spec.SetField(virtualmachine.FieldInternalIP, field.TypeString, value) + } + if _u.mutation.InternalIPCleared() { + _spec.ClearField(virtualmachine.FieldInternalIP, field.TypeString) + } + if value, ok := _u.mutation.TTLKind(); ok { + _spec.SetField(virtualmachine.FieldTTLKind, field.TypeString, value) + } + if _u.mutation.TTLKindCleared() { + _spec.ClearField(virtualmachine.FieldTTLKind, field.TypeString) + } + if value, ok := _u.mutation.TTL(); ok { + _spec.SetField(virtualmachine.FieldTTL, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedTTL(); ok { + _spec.AddField(virtualmachine.FieldTTL, field.TypeInt64, value) + } + if _u.mutation.TTLCleared() { + _spec.ClearField(virtualmachine.FieldTTL, field.TypeInt64) + } + if value, ok := _u.mutation.Version(); ok { + _spec.SetField(virtualmachine.FieldVersion, field.TypeString, value) + } + if _u.mutation.VersionCleared() { + _spec.ClearField(virtualmachine.FieldVersion, field.TypeString) + } + if value, ok := _u.mutation.MachineID(); ok { + _spec.SetField(virtualmachine.FieldMachineID, field.TypeString, value) + } + if _u.mutation.MachineIDCleared() { + _spec.ClearField(virtualmachine.FieldMachineID, field.TypeString) + } + if value, ok := _u.mutation.RepoURL(); ok { + _spec.SetField(virtualmachine.FieldRepoURL, field.TypeString, value) + } + if _u.mutation.RepoURLCleared() { + _spec.ClearField(virtualmachine.FieldRepoURL, field.TypeString) + } + if value, ok := _u.mutation.RepoFilename(); ok { + _spec.SetField(virtualmachine.FieldRepoFilename, field.TypeString, value) + } + if _u.mutation.RepoFilenameCleared() { + _spec.ClearField(virtualmachine.FieldRepoFilename, field.TypeString) + } + if value, ok := _u.mutation.Branch(); ok { + _spec.SetField(virtualmachine.FieldBranch, field.TypeString, value) + } + if _u.mutation.BranchCleared() { + _spec.ClearField(virtualmachine.FieldBranch, field.TypeString) + } + if value, ok := _u.mutation.IsRecycled(); ok { + _spec.SetField(virtualmachine.FieldIsRecycled, field.TypeBool, value) + } + if _u.mutation.IsRecycledCleared() { + _spec.ClearField(virtualmachine.FieldIsRecycled, field.TypeBool) + } + if value, ok := _u.mutation.Conditions(); ok { + _spec.SetField(virtualmachine.FieldConditions, field.TypeJSON, value) + } + if _u.mutation.ConditionsCleared() { + _spec.ClearField(virtualmachine.FieldConditions, field.TypeJSON) + } + if value, ok := _u.mutation.CreatedAt(); ok { + _spec.SetField(virtualmachine.FieldCreatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(virtualmachine.FieldUpdatedAt, field.TypeTime, value) + } + if _u.mutation.HostCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: virtualmachine.HostTable, + Columns: []string{virtualmachine.HostColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.HostIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: virtualmachine.HostTable, + Columns: []string{virtualmachine.HostColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.ModelCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: virtualmachine.ModelTable, + Columns: []string{virtualmachine.ModelColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ModelIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: virtualmachine.ModelTable, + Columns: []string{virtualmachine.ModelColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: virtualmachine.UserTable, + Columns: []string{virtualmachine.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: virtualmachine.UserTable, + Columns: []string{virtualmachine.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(_u.modifiers...) + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{virtualmachine.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// VirtualMachineUpdateOne is the builder for updating a single VirtualMachine entity. +type VirtualMachineUpdateOne struct { + config + fields []string + hooks []Hook + mutation *VirtualMachineMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetDeletedAt sets the "deleted_at" field. +func (_u *VirtualMachineUpdateOne) SetDeletedAt(v time.Time) *VirtualMachineUpdateOne { + _u.mutation.SetDeletedAt(v) + return _u +} + +// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil. +func (_u *VirtualMachineUpdateOne) SetNillableDeletedAt(v *time.Time) *VirtualMachineUpdateOne { + if v != nil { + _u.SetDeletedAt(*v) + } + return _u +} + +// ClearDeletedAt clears the value of the "deleted_at" field. +func (_u *VirtualMachineUpdateOne) ClearDeletedAt() *VirtualMachineUpdateOne { + _u.mutation.ClearDeletedAt() + return _u +} + +// SetHostID sets the "host_id" field. +func (_u *VirtualMachineUpdateOne) SetHostID(v string) *VirtualMachineUpdateOne { + _u.mutation.SetHostID(v) + return _u +} + +// SetNillableHostID sets the "host_id" field if the given value is not nil. +func (_u *VirtualMachineUpdateOne) SetNillableHostID(v *string) *VirtualMachineUpdateOne { + if v != nil { + _u.SetHostID(*v) + } + return _u +} + +// SetUserID sets the "user_id" field. +func (_u *VirtualMachineUpdateOne) SetUserID(v uuid.UUID) *VirtualMachineUpdateOne { + _u.mutation.SetUserID(v) + return _u +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (_u *VirtualMachineUpdateOne) SetNillableUserID(v *uuid.UUID) *VirtualMachineUpdateOne { + if v != nil { + _u.SetUserID(*v) + } + return _u +} + +// ClearUserID clears the value of the "user_id" field. +func (_u *VirtualMachineUpdateOne) ClearUserID() *VirtualMachineUpdateOne { + _u.mutation.ClearUserID() + return _u +} + +// SetModelID sets the "model_id" field. +func (_u *VirtualMachineUpdateOne) SetModelID(v uuid.UUID) *VirtualMachineUpdateOne { + _u.mutation.SetModelID(v) + return _u +} + +// SetNillableModelID sets the "model_id" field if the given value is not nil. +func (_u *VirtualMachineUpdateOne) SetNillableModelID(v *uuid.UUID) *VirtualMachineUpdateOne { + if v != nil { + _u.SetModelID(*v) + } + return _u +} + +// ClearModelID clears the value of the "model_id" field. +func (_u *VirtualMachineUpdateOne) ClearModelID() *VirtualMachineUpdateOne { + _u.mutation.ClearModelID() + return _u +} + +// SetEnvironmentID sets the "environment_id" field. +func (_u *VirtualMachineUpdateOne) SetEnvironmentID(v string) *VirtualMachineUpdateOne { + _u.mutation.SetEnvironmentID(v) + return _u +} + +// SetNillableEnvironmentID sets the "environment_id" field if the given value is not nil. +func (_u *VirtualMachineUpdateOne) SetNillableEnvironmentID(v *string) *VirtualMachineUpdateOne { + if v != nil { + _u.SetEnvironmentID(*v) + } + return _u +} + +// ClearEnvironmentID clears the value of the "environment_id" field. +func (_u *VirtualMachineUpdateOne) ClearEnvironmentID() *VirtualMachineUpdateOne { + _u.mutation.ClearEnvironmentID() + return _u +} + +// SetName sets the "name" field. +func (_u *VirtualMachineUpdateOne) SetName(v string) *VirtualMachineUpdateOne { + _u.mutation.SetName(v) + return _u +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (_u *VirtualMachineUpdateOne) SetNillableName(v *string) *VirtualMachineUpdateOne { + if v != nil { + _u.SetName(*v) + } + return _u +} + +// SetHostname sets the "hostname" field. +func (_u *VirtualMachineUpdateOne) SetHostname(v string) *VirtualMachineUpdateOne { + _u.mutation.SetHostname(v) + return _u +} + +// SetNillableHostname sets the "hostname" field if the given value is not nil. +func (_u *VirtualMachineUpdateOne) SetNillableHostname(v *string) *VirtualMachineUpdateOne { + if v != nil { + _u.SetHostname(*v) + } + return _u +} + +// ClearHostname clears the value of the "hostname" field. +func (_u *VirtualMachineUpdateOne) ClearHostname() *VirtualMachineUpdateOne { + _u.mutation.ClearHostname() + return _u +} + +// SetArch sets the "arch" field. +func (_u *VirtualMachineUpdateOne) SetArch(v string) *VirtualMachineUpdateOne { + _u.mutation.SetArch(v) + return _u +} + +// SetNillableArch sets the "arch" field if the given value is not nil. +func (_u *VirtualMachineUpdateOne) SetNillableArch(v *string) *VirtualMachineUpdateOne { + if v != nil { + _u.SetArch(*v) + } + return _u +} + +// ClearArch clears the value of the "arch" field. +func (_u *VirtualMachineUpdateOne) ClearArch() *VirtualMachineUpdateOne { + _u.mutation.ClearArch() + return _u +} + +// SetCores sets the "cores" field. +func (_u *VirtualMachineUpdateOne) SetCores(v int) *VirtualMachineUpdateOne { + _u.mutation.ResetCores() + _u.mutation.SetCores(v) + return _u +} + +// SetNillableCores sets the "cores" field if the given value is not nil. +func (_u *VirtualMachineUpdateOne) SetNillableCores(v *int) *VirtualMachineUpdateOne { + if v != nil { + _u.SetCores(*v) + } + return _u +} + +// AddCores adds value to the "cores" field. +func (_u *VirtualMachineUpdateOne) AddCores(v int) *VirtualMachineUpdateOne { + _u.mutation.AddCores(v) + return _u +} + +// ClearCores clears the value of the "cores" field. +func (_u *VirtualMachineUpdateOne) ClearCores() *VirtualMachineUpdateOne { + _u.mutation.ClearCores() + return _u +} + +// SetMemory sets the "memory" field. +func (_u *VirtualMachineUpdateOne) SetMemory(v int64) *VirtualMachineUpdateOne { + _u.mutation.ResetMemory() + _u.mutation.SetMemory(v) + return _u +} + +// SetNillableMemory sets the "memory" field if the given value is not nil. +func (_u *VirtualMachineUpdateOne) SetNillableMemory(v *int64) *VirtualMachineUpdateOne { + if v != nil { + _u.SetMemory(*v) + } + return _u +} + +// AddMemory adds value to the "memory" field. +func (_u *VirtualMachineUpdateOne) AddMemory(v int64) *VirtualMachineUpdateOne { + _u.mutation.AddMemory(v) + return _u +} + +// ClearMemory clears the value of the "memory" field. +func (_u *VirtualMachineUpdateOne) ClearMemory() *VirtualMachineUpdateOne { + _u.mutation.ClearMemory() + return _u +} + +// SetOs sets the "os" field. +func (_u *VirtualMachineUpdateOne) SetOs(v string) *VirtualMachineUpdateOne { + _u.mutation.SetOs(v) + return _u +} + +// SetNillableOs sets the "os" field if the given value is not nil. +func (_u *VirtualMachineUpdateOne) SetNillableOs(v *string) *VirtualMachineUpdateOne { + if v != nil { + _u.SetOs(*v) + } + return _u +} + +// ClearOs clears the value of the "os" field. +func (_u *VirtualMachineUpdateOne) ClearOs() *VirtualMachineUpdateOne { + _u.mutation.ClearOs() + return _u +} + +// SetExternalIP sets the "external_ip" field. +func (_u *VirtualMachineUpdateOne) SetExternalIP(v string) *VirtualMachineUpdateOne { + _u.mutation.SetExternalIP(v) + return _u +} + +// SetNillableExternalIP sets the "external_ip" field if the given value is not nil. +func (_u *VirtualMachineUpdateOne) SetNillableExternalIP(v *string) *VirtualMachineUpdateOne { + if v != nil { + _u.SetExternalIP(*v) + } + return _u +} + +// ClearExternalIP clears the value of the "external_ip" field. +func (_u *VirtualMachineUpdateOne) ClearExternalIP() *VirtualMachineUpdateOne { + _u.mutation.ClearExternalIP() + return _u +} + +// SetInternalIP sets the "internal_ip" field. +func (_u *VirtualMachineUpdateOne) SetInternalIP(v string) *VirtualMachineUpdateOne { + _u.mutation.SetInternalIP(v) + return _u +} + +// SetNillableInternalIP sets the "internal_ip" field if the given value is not nil. +func (_u *VirtualMachineUpdateOne) SetNillableInternalIP(v *string) *VirtualMachineUpdateOne { + if v != nil { + _u.SetInternalIP(*v) + } + return _u +} + +// ClearInternalIP clears the value of the "internal_ip" field. +func (_u *VirtualMachineUpdateOne) ClearInternalIP() *VirtualMachineUpdateOne { + _u.mutation.ClearInternalIP() + return _u +} + +// SetTTLKind sets the "ttl_kind" field. +func (_u *VirtualMachineUpdateOne) SetTTLKind(v consts.VirtualmachineTTLKind) *VirtualMachineUpdateOne { + _u.mutation.SetTTLKind(v) + return _u +} + +// SetNillableTTLKind sets the "ttl_kind" field if the given value is not nil. +func (_u *VirtualMachineUpdateOne) SetNillableTTLKind(v *consts.VirtualmachineTTLKind) *VirtualMachineUpdateOne { + if v != nil { + _u.SetTTLKind(*v) + } + return _u +} + +// ClearTTLKind clears the value of the "ttl_kind" field. +func (_u *VirtualMachineUpdateOne) ClearTTLKind() *VirtualMachineUpdateOne { + _u.mutation.ClearTTLKind() + return _u +} + +// SetTTL sets the "ttl" field. +func (_u *VirtualMachineUpdateOne) SetTTL(v int64) *VirtualMachineUpdateOne { + _u.mutation.ResetTTL() + _u.mutation.SetTTL(v) + return _u +} + +// SetNillableTTL sets the "ttl" field if the given value is not nil. +func (_u *VirtualMachineUpdateOne) SetNillableTTL(v *int64) *VirtualMachineUpdateOne { + if v != nil { + _u.SetTTL(*v) + } + return _u +} + +// AddTTL adds value to the "ttl" field. +func (_u *VirtualMachineUpdateOne) AddTTL(v int64) *VirtualMachineUpdateOne { + _u.mutation.AddTTL(v) + return _u +} + +// ClearTTL clears the value of the "ttl" field. +func (_u *VirtualMachineUpdateOne) ClearTTL() *VirtualMachineUpdateOne { + _u.mutation.ClearTTL() + return _u +} + +// SetVersion sets the "version" field. +func (_u *VirtualMachineUpdateOne) SetVersion(v string) *VirtualMachineUpdateOne { + _u.mutation.SetVersion(v) + return _u +} + +// SetNillableVersion sets the "version" field if the given value is not nil. +func (_u *VirtualMachineUpdateOne) SetNillableVersion(v *string) *VirtualMachineUpdateOne { + if v != nil { + _u.SetVersion(*v) + } + return _u +} + +// ClearVersion clears the value of the "version" field. +func (_u *VirtualMachineUpdateOne) ClearVersion() *VirtualMachineUpdateOne { + _u.mutation.ClearVersion() + return _u +} + +// SetMachineID sets the "machine_id" field. +func (_u *VirtualMachineUpdateOne) SetMachineID(v string) *VirtualMachineUpdateOne { + _u.mutation.SetMachineID(v) + return _u +} + +// SetNillableMachineID sets the "machine_id" field if the given value is not nil. +func (_u *VirtualMachineUpdateOne) SetNillableMachineID(v *string) *VirtualMachineUpdateOne { + if v != nil { + _u.SetMachineID(*v) + } + return _u +} + +// ClearMachineID clears the value of the "machine_id" field. +func (_u *VirtualMachineUpdateOne) ClearMachineID() *VirtualMachineUpdateOne { + _u.mutation.ClearMachineID() + return _u +} + +// SetRepoURL sets the "repo_url" field. +func (_u *VirtualMachineUpdateOne) SetRepoURL(v string) *VirtualMachineUpdateOne { + _u.mutation.SetRepoURL(v) + return _u +} + +// SetNillableRepoURL sets the "repo_url" field if the given value is not nil. +func (_u *VirtualMachineUpdateOne) SetNillableRepoURL(v *string) *VirtualMachineUpdateOne { + if v != nil { + _u.SetRepoURL(*v) + } + return _u +} + +// ClearRepoURL clears the value of the "repo_url" field. +func (_u *VirtualMachineUpdateOne) ClearRepoURL() *VirtualMachineUpdateOne { + _u.mutation.ClearRepoURL() + return _u +} + +// SetRepoFilename sets the "repo_filename" field. +func (_u *VirtualMachineUpdateOne) SetRepoFilename(v string) *VirtualMachineUpdateOne { + _u.mutation.SetRepoFilename(v) + return _u +} + +// SetNillableRepoFilename sets the "repo_filename" field if the given value is not nil. +func (_u *VirtualMachineUpdateOne) SetNillableRepoFilename(v *string) *VirtualMachineUpdateOne { + if v != nil { + _u.SetRepoFilename(*v) + } + return _u +} + +// ClearRepoFilename clears the value of the "repo_filename" field. +func (_u *VirtualMachineUpdateOne) ClearRepoFilename() *VirtualMachineUpdateOne { + _u.mutation.ClearRepoFilename() + return _u +} + +// SetBranch sets the "branch" field. +func (_u *VirtualMachineUpdateOne) SetBranch(v string) *VirtualMachineUpdateOne { + _u.mutation.SetBranch(v) + return _u +} + +// SetNillableBranch sets the "branch" field if the given value is not nil. +func (_u *VirtualMachineUpdateOne) SetNillableBranch(v *string) *VirtualMachineUpdateOne { + if v != nil { + _u.SetBranch(*v) + } + return _u +} + +// ClearBranch clears the value of the "branch" field. +func (_u *VirtualMachineUpdateOne) ClearBranch() *VirtualMachineUpdateOne { + _u.mutation.ClearBranch() + return _u +} + +// SetIsRecycled sets the "is_recycled" field. +func (_u *VirtualMachineUpdateOne) SetIsRecycled(v bool) *VirtualMachineUpdateOne { + _u.mutation.SetIsRecycled(v) + return _u +} + +// SetNillableIsRecycled sets the "is_recycled" field if the given value is not nil. +func (_u *VirtualMachineUpdateOne) SetNillableIsRecycled(v *bool) *VirtualMachineUpdateOne { + if v != nil { + _u.SetIsRecycled(*v) + } + return _u +} + +// ClearIsRecycled clears the value of the "is_recycled" field. +func (_u *VirtualMachineUpdateOne) ClearIsRecycled() *VirtualMachineUpdateOne { + _u.mutation.ClearIsRecycled() + return _u +} + +// SetConditions sets the "conditions" field. +func (_u *VirtualMachineUpdateOne) SetConditions(v *types.VirtualMachineCondition) *VirtualMachineUpdateOne { + _u.mutation.SetConditions(v) + return _u +} + +// ClearConditions clears the value of the "conditions" field. +func (_u *VirtualMachineUpdateOne) ClearConditions() *VirtualMachineUpdateOne { + _u.mutation.ClearConditions() + return _u +} + +// SetCreatedAt sets the "created_at" field. +func (_u *VirtualMachineUpdateOne) SetCreatedAt(v time.Time) *VirtualMachineUpdateOne { + _u.mutation.SetCreatedAt(v) + return _u +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_u *VirtualMachineUpdateOne) SetNillableCreatedAt(v *time.Time) *VirtualMachineUpdateOne { + if v != nil { + _u.SetCreatedAt(*v) + } + return _u +} + +// SetUpdatedAt sets the "updated_at" field. +func (_u *VirtualMachineUpdateOne) SetUpdatedAt(v time.Time) *VirtualMachineUpdateOne { + _u.mutation.SetUpdatedAt(v) + return _u +} + +// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. +func (_u *VirtualMachineUpdateOne) SetNillableUpdatedAt(v *time.Time) *VirtualMachineUpdateOne { + if v != nil { + _u.SetUpdatedAt(*v) + } + return _u +} + +// SetHost sets the "host" edge to the Host entity. +func (_u *VirtualMachineUpdateOne) SetHost(v *Host) *VirtualMachineUpdateOne { + return _u.SetHostID(v.ID) +} + +// SetModel sets the "model" edge to the Model entity. +func (_u *VirtualMachineUpdateOne) SetModel(v *Model) *VirtualMachineUpdateOne { + return _u.SetModelID(v.ID) +} + +// SetUser sets the "user" edge to the User entity. +func (_u *VirtualMachineUpdateOne) SetUser(v *User) *VirtualMachineUpdateOne { + return _u.SetUserID(v.ID) +} + +// Mutation returns the VirtualMachineMutation object of the builder. +func (_u *VirtualMachineUpdateOne) Mutation() *VirtualMachineMutation { + return _u.mutation +} + +// ClearHost clears the "host" edge to the Host entity. +func (_u *VirtualMachineUpdateOne) ClearHost() *VirtualMachineUpdateOne { + _u.mutation.ClearHost() + return _u +} + +// ClearModel clears the "model" edge to the Model entity. +func (_u *VirtualMachineUpdateOne) ClearModel() *VirtualMachineUpdateOne { + _u.mutation.ClearModel() + return _u +} + +// ClearUser clears the "user" edge to the User entity. +func (_u *VirtualMachineUpdateOne) ClearUser() *VirtualMachineUpdateOne { + _u.mutation.ClearUser() + return _u +} + +// Where appends a list predicates to the VirtualMachineUpdate builder. +func (_u *VirtualMachineUpdateOne) Where(ps ...predicate.VirtualMachine) *VirtualMachineUpdateOne { + _u.mutation.Where(ps...) + return _u +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (_u *VirtualMachineUpdateOne) Select(field string, fields ...string) *VirtualMachineUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated VirtualMachine entity. +func (_u *VirtualMachineUpdateOne) Save(ctx context.Context) (*VirtualMachine, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *VirtualMachineUpdateOne) SaveX(ctx context.Context) *VirtualMachine { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *VirtualMachineUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *VirtualMachineUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_u *VirtualMachineUpdateOne) check() error { + if _u.mutation.HostCleared() && len(_u.mutation.HostIDs()) > 0 { + return errors.New(`db: clearing a required unique edge "VirtualMachine.host"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (_u *VirtualMachineUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *VirtualMachineUpdateOne { + _u.modifiers = append(_u.modifiers, modifiers...) + return _u +} + +func (_u *VirtualMachineUpdateOne) sqlSave(ctx context.Context) (_node *VirtualMachine, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(virtualmachine.Table, virtualmachine.Columns, sqlgraph.NewFieldSpec(virtualmachine.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "VirtualMachine.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := _u.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, virtualmachine.FieldID) + for _, f := range fields { + if !virtualmachine.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} + } + if f != virtualmachine.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := _u.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := _u.mutation.DeletedAt(); ok { + _spec.SetField(virtualmachine.FieldDeletedAt, field.TypeTime, value) + } + if _u.mutation.DeletedAtCleared() { + _spec.ClearField(virtualmachine.FieldDeletedAt, field.TypeTime) + } + if value, ok := _u.mutation.EnvironmentID(); ok { + _spec.SetField(virtualmachine.FieldEnvironmentID, field.TypeString, value) + } + if _u.mutation.EnvironmentIDCleared() { + _spec.ClearField(virtualmachine.FieldEnvironmentID, field.TypeString) + } + if value, ok := _u.mutation.Name(); ok { + _spec.SetField(virtualmachine.FieldName, field.TypeString, value) + } + if value, ok := _u.mutation.Hostname(); ok { + _spec.SetField(virtualmachine.FieldHostname, field.TypeString, value) + } + if _u.mutation.HostnameCleared() { + _spec.ClearField(virtualmachine.FieldHostname, field.TypeString) + } + if value, ok := _u.mutation.Arch(); ok { + _spec.SetField(virtualmachine.FieldArch, field.TypeString, value) + } + if _u.mutation.ArchCleared() { + _spec.ClearField(virtualmachine.FieldArch, field.TypeString) + } + if value, ok := _u.mutation.Cores(); ok { + _spec.SetField(virtualmachine.FieldCores, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedCores(); ok { + _spec.AddField(virtualmachine.FieldCores, field.TypeInt, value) + } + if _u.mutation.CoresCleared() { + _spec.ClearField(virtualmachine.FieldCores, field.TypeInt) + } + if value, ok := _u.mutation.Memory(); ok { + _spec.SetField(virtualmachine.FieldMemory, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedMemory(); ok { + _spec.AddField(virtualmachine.FieldMemory, field.TypeInt64, value) + } + if _u.mutation.MemoryCleared() { + _spec.ClearField(virtualmachine.FieldMemory, field.TypeInt64) + } + if value, ok := _u.mutation.Os(); ok { + _spec.SetField(virtualmachine.FieldOs, field.TypeString, value) + } + if _u.mutation.OsCleared() { + _spec.ClearField(virtualmachine.FieldOs, field.TypeString) + } + if value, ok := _u.mutation.ExternalIP(); ok { + _spec.SetField(virtualmachine.FieldExternalIP, field.TypeString, value) + } + if _u.mutation.ExternalIPCleared() { + _spec.ClearField(virtualmachine.FieldExternalIP, field.TypeString) + } + if value, ok := _u.mutation.InternalIP(); ok { + _spec.SetField(virtualmachine.FieldInternalIP, field.TypeString, value) + } + if _u.mutation.InternalIPCleared() { + _spec.ClearField(virtualmachine.FieldInternalIP, field.TypeString) + } + if value, ok := _u.mutation.TTLKind(); ok { + _spec.SetField(virtualmachine.FieldTTLKind, field.TypeString, value) + } + if _u.mutation.TTLKindCleared() { + _spec.ClearField(virtualmachine.FieldTTLKind, field.TypeString) + } + if value, ok := _u.mutation.TTL(); ok { + _spec.SetField(virtualmachine.FieldTTL, field.TypeInt64, value) + } + if value, ok := _u.mutation.AddedTTL(); ok { + _spec.AddField(virtualmachine.FieldTTL, field.TypeInt64, value) + } + if _u.mutation.TTLCleared() { + _spec.ClearField(virtualmachine.FieldTTL, field.TypeInt64) + } + if value, ok := _u.mutation.Version(); ok { + _spec.SetField(virtualmachine.FieldVersion, field.TypeString, value) + } + if _u.mutation.VersionCleared() { + _spec.ClearField(virtualmachine.FieldVersion, field.TypeString) + } + if value, ok := _u.mutation.MachineID(); ok { + _spec.SetField(virtualmachine.FieldMachineID, field.TypeString, value) + } + if _u.mutation.MachineIDCleared() { + _spec.ClearField(virtualmachine.FieldMachineID, field.TypeString) + } + if value, ok := _u.mutation.RepoURL(); ok { + _spec.SetField(virtualmachine.FieldRepoURL, field.TypeString, value) + } + if _u.mutation.RepoURLCleared() { + _spec.ClearField(virtualmachine.FieldRepoURL, field.TypeString) + } + if value, ok := _u.mutation.RepoFilename(); ok { + _spec.SetField(virtualmachine.FieldRepoFilename, field.TypeString, value) + } + if _u.mutation.RepoFilenameCleared() { + _spec.ClearField(virtualmachine.FieldRepoFilename, field.TypeString) + } + if value, ok := _u.mutation.Branch(); ok { + _spec.SetField(virtualmachine.FieldBranch, field.TypeString, value) + } + if _u.mutation.BranchCleared() { + _spec.ClearField(virtualmachine.FieldBranch, field.TypeString) + } + if value, ok := _u.mutation.IsRecycled(); ok { + _spec.SetField(virtualmachine.FieldIsRecycled, field.TypeBool, value) + } + if _u.mutation.IsRecycledCleared() { + _spec.ClearField(virtualmachine.FieldIsRecycled, field.TypeBool) + } + if value, ok := _u.mutation.Conditions(); ok { + _spec.SetField(virtualmachine.FieldConditions, field.TypeJSON, value) + } + if _u.mutation.ConditionsCleared() { + _spec.ClearField(virtualmachine.FieldConditions, field.TypeJSON) + } + if value, ok := _u.mutation.CreatedAt(); ok { + _spec.SetField(virtualmachine.FieldCreatedAt, field.TypeTime, value) + } + if value, ok := _u.mutation.UpdatedAt(); ok { + _spec.SetField(virtualmachine.FieldUpdatedAt, field.TypeTime, value) + } + if _u.mutation.HostCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: virtualmachine.HostTable, + Columns: []string{virtualmachine.HostColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.HostIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: virtualmachine.HostTable, + Columns: []string{virtualmachine.HostColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(host.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.ModelCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: virtualmachine.ModelTable, + Columns: []string{virtualmachine.ModelColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ModelIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: virtualmachine.ModelTable, + Columns: []string{virtualmachine.ModelColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(model.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: virtualmachine.UserTable, + Columns: []string{virtualmachine.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: virtualmachine.UserTable, + Columns: []string{virtualmachine.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeUUID), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(_u.modifiers...) + _node = &VirtualMachine{config: _u.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{virtualmachine.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + _u.mutation.done = true + return _node, nil +} diff --git a/backend/ent/schema/host.go b/backend/ent/schema/host.go new file mode 100644 index 00000000..804fa3f3 --- /dev/null +++ b/backend/ent/schema/host.go @@ -0,0 +1,63 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "github.com/google/uuid" + + "github.com/chaitin/MonkeyCode/backend/pkg/entx" +) + +// Host holds the schema definition for the Host entity. +type Host struct { + ent.Schema +} + +func (Host) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Table("hosts"), + entx.NewCursor(entx.CursorKindCreatedAt), + } +} + +func (Host) Mixin() []ent.Mixin { + return []ent.Mixin{ + entx.SoftDeleteMixin2{}, + } +} + +// Fields of the Host. +func (Host) Fields() []ent.Field { + return []ent.Field{ + field.String("id").Unique(), + field.UUID("user_id", uuid.UUID{}), + field.String("hostname").Optional(), + field.String("arch").Optional(), + field.Int("cores").Optional(), + field.Int("weight").Default(1), + field.Int64("memory").Optional(), + field.Int64("disk").Optional(), + field.String("os").Optional(), + field.String("external_ip").Optional(), + field.String("internal_ip").Optional(), + field.String("version").Optional(), + field.String("machine_id").Optional(), + field.String("remark").Optional(), + field.Time("created_at").Default(time.Now), + field.Time("updated_at").Default(time.Now).UpdateDefault(time.Now), + } +} + +// Edges of the Host. +func (Host) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("vms", VirtualMachine.Type), + edge.From("user", User.Type).Field("user_id").Ref("hosts").Unique().Required(), + edge.From("groups", TeamGroup.Type).Ref("hosts").Through("team_group_hosts", TeamGroupHost.Type), + } +} diff --git a/backend/ent/schema/model.go b/backend/ent/schema/model.go index 396989e6..dd0b72b6 100644 --- a/backend/ent/schema/model.go +++ b/backend/ent/schema/model.go @@ -58,5 +58,6 @@ func (Model) Edges() []ent.Edge { edge.From("user", User.Type).Ref("models").Field("user_id").Unique().Required(), edge.From("teams", Team.Type).Ref("models").Through("team_models", TeamModel.Type), edge.From("groups", TeamGroup.Type).Ref("models").Through("team_group_models", TeamGroupModel.Type), + edge.To("vms", VirtualMachine.Type), } } diff --git a/backend/ent/schema/teamgroup.go b/backend/ent/schema/teamgroup.go index eec37a50..bb4a8f27 100644 --- a/backend/ent/schema/teamgroup.go +++ b/backend/ent/schema/teamgroup.go @@ -49,5 +49,6 @@ func (TeamGroup) Edges() []ent.Edge { edge.From("team", Team.Type).Ref("groups").Field("team_id").Unique().Required(), edge.To("models", Model.Type).Through("team_group_models", TeamGroupModel.Type), edge.To("images", Image.Type).Through("team_group_images", TeamGroupImage.Type), + edge.To("hosts", Host.Type).Through("team_group_hosts", TeamGroupHost.Type), } } diff --git a/backend/ent/schema/teamgrouphost.go b/backend/ent/schema/teamgrouphost.go new file mode 100644 index 00000000..338aacd7 --- /dev/null +++ b/backend/ent/schema/teamgrouphost.go @@ -0,0 +1,44 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "github.com/google/uuid" + + "github.com/chaitin/MonkeyCode/backend/pkg/entx" +) + +// TeamGroupHost holds the schema definition for the TeamGroupHost entity. +type TeamGroupHost struct { + ent.Schema +} + +func (TeamGroupHost) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Table("team_group_hosts"), + entx.NewCursor(entx.CursorKindCreatedAt), + } +} + +// Fields of the TeamGroupHost. +func (TeamGroupHost) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuid.UUID{}).Unique(), + field.UUID("group_id", uuid.UUID{}), + field.String("host_id"), + field.Time("created_at").Default(time.Now), + } +} + +// Edges of the TeamGroupHost. +func (TeamGroupHost) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("group", TeamGroup.Type).Field("group_id").Unique().Required(), + edge.To("host", Host.Type).Field("host_id").Unique().Required(), + } +} diff --git a/backend/ent/schema/teamhost.go b/backend/ent/schema/teamhost.go new file mode 100644 index 00000000..e4dff56f --- /dev/null +++ b/backend/ent/schema/teamhost.go @@ -0,0 +1,41 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "github.com/google/uuid" +) + +// TeamHost holds the schema definition for the TeamHost entity. +type TeamHost struct { + ent.Schema +} + +func (TeamHost) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Table("team_hosts"), + } +} + +// Fields of the TeamHost. +func (TeamHost) Fields() []ent.Field { + return []ent.Field{ + field.UUID("id", uuid.UUID{}).Unique(), + field.UUID("team_id", uuid.UUID{}), + field.String("host_id"), + field.Time("created_at").Default(time.Now), + } +} + +// Edges of the TeamHost. +func (TeamHost) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("team", Team.Type).Field("team_id").Unique().Required(), + edge.To("host", Host.Type).Field("host_id").Unique().Required(), + } +} diff --git a/backend/ent/schema/user.go b/backend/ent/schema/user.go index f025403c..e21bd47e 100644 --- a/backend/ent/schema/user.go +++ b/backend/ent/schema/user.go @@ -57,5 +57,7 @@ func (User) Edges() []ent.Edge { edge.To("groups", TeamGroup.Type).Through("team_group_members", TeamGroupMember.Type), edge.To("models", Model.Type), edge.To("images", Image.Type), + edge.To("hosts", Host.Type), + edge.To("vms", VirtualMachine.Type), } } diff --git a/backend/ent/schema/virtualmachine.go b/backend/ent/schema/virtualmachine.go new file mode 100644 index 00000000..aa4b0472 --- /dev/null +++ b/backend/ent/schema/virtualmachine.go @@ -0,0 +1,72 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "github.com/google/uuid" + + "github.com/chaitin/MonkeyCode/backend/consts" + "github.com/chaitin/MonkeyCode/backend/ent/types" + "github.com/chaitin/MonkeyCode/backend/pkg/entx" +) + +// VirtualMachine holds the schema definition for the VirtualMachine entity. +type VirtualMachine struct { + ent.Schema +} + +func (VirtualMachine) Annotations() []schema.Annotation { + return []schema.Annotation{ + entsql.Table("virtualmachines"), + } +} + +func (VirtualMachine) Mixin() []ent.Mixin { + return []ent.Mixin{ + entx.SoftDeleteMixin2{}, + } +} + +// Fields of the VirtualMachine. +func (VirtualMachine) Fields() []ent.Field { + return []ent.Field{ + field.String("id").Unique(), + field.String("host_id"), + field.UUID("user_id", uuid.UUID{}).Optional(), + field.UUID("model_id", uuid.UUID{}).Optional(), + field.String("environment_id").Optional(), + field.String("name"), + field.String("hostname").Optional(), + field.String("arch").Optional(), + field.Int("cores").Optional(), + field.Int64("memory").Optional(), + field.String("os").Optional(), + field.String("external_ip").Optional(), + field.String("internal_ip").Optional(), + field.String("ttl_kind").GoType(consts.VirtualmachineTTLKind("")).Optional(), + field.Int64("ttl").Optional(), + field.String("version").Optional(), + field.String("machine_id").Optional(), + field.String("repo_url").Optional(), + field.String("repo_filename").Optional(), + field.String("branch").Optional(), + field.Bool("is_recycled").Optional(), + field.JSON("conditions", &types.VirtualMachineCondition{}).Optional(), + field.Time("created_at").Default(time.Now), + field.Time("updated_at").Default(time.Now), + } +} + +// Edges of the VirtualMachine. +func (VirtualMachine) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("host", Host.Type).Ref("vms").Field("host_id").Unique().Required(), + edge.From("model", Model.Type).Ref("vms").Field("model_id").Unique(), + edge.From("user", User.Type).Ref("vms").Field("user_id").Unique(), + } +} diff --git a/backend/migration/000003_host_vm.down.sql b/backend/migration/000003_host_vm.down.sql new file mode 100644 index 00000000..2812312b --- /dev/null +++ b/backend/migration/000003_host_vm.down.sql @@ -0,0 +1,4 @@ +DROP TABLE IF EXISTS team_group_hosts; +DROP TABLE IF EXISTS team_hosts; +DROP TABLE IF EXISTS virtualmachines; +DROP TABLE IF EXISTS hosts; diff --git a/backend/migration/000003_host_vm.up.sql b/backend/migration/000003_host_vm.up.sql new file mode 100644 index 00000000..f64540fe --- /dev/null +++ b/backend/migration/000003_host_vm.up.sql @@ -0,0 +1,78 @@ +-- hosts 宿主机表 +CREATE TABLE IF NOT EXISTS hosts ( + id VARCHAR(255) PRIMARY KEY, + user_id UUID NOT NULL REFERENCES users(id), + hostname VARCHAR(255), + arch VARCHAR(255), + cores INTEGER DEFAULT 0, + weight INTEGER DEFAULT 1, + memory BIGINT DEFAULT 0, + disk BIGINT DEFAULT 0, + os VARCHAR(255), + external_ip VARCHAR(255), + internal_ip VARCHAR(255), + version VARCHAR(255), + machine_id VARCHAR(255), + remark VARCHAR(255), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + is_soft_deleted BOOLEAN NOT NULL DEFAULT FALSE +); + +CREATE INDEX IF NOT EXISTS idx_hosts_user_id ON hosts(user_id); +CREATE INDEX IF NOT EXISTS idx_hosts_created_at ON hosts(created_at); + +-- virtualmachines 虚拟机表 +CREATE TABLE IF NOT EXISTS virtualmachines ( + id VARCHAR(255) PRIMARY KEY, + host_id VARCHAR(255) NOT NULL REFERENCES hosts(id), + user_id UUID REFERENCES users(id), + model_id UUID REFERENCES models(id), + environment_id VARCHAR(255), + name VARCHAR(255) NOT NULL, + hostname VARCHAR(255), + arch VARCHAR(255), + cores INTEGER DEFAULT 0, + memory BIGINT DEFAULT 0, + os VARCHAR(255), + external_ip VARCHAR(255), + internal_ip VARCHAR(255), + ttl_kind VARCHAR(255), + ttl BIGINT DEFAULT 0, + version VARCHAR(255), + machine_id VARCHAR(255), + repo_url VARCHAR(255), + repo_filename VARCHAR(255), + branch VARCHAR(255), + is_recycled BOOLEAN DEFAULT FALSE, + conditions JSONB, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + is_soft_deleted BOOLEAN NOT NULL DEFAULT FALSE +); + +CREATE INDEX IF NOT EXISTS idx_virtualmachines_host_id ON virtualmachines(host_id); +CREATE INDEX IF NOT EXISTS idx_virtualmachines_user_id ON virtualmachines(user_id); +CREATE INDEX IF NOT EXISTS idx_virtualmachines_created_at ON virtualmachines(created_at); + +-- team_hosts 团队-宿主机关联表 +CREATE TABLE IF NOT EXISTS team_hosts ( + id UUID PRIMARY KEY, + team_id UUID NOT NULL REFERENCES teams(id), + host_id VARCHAR(255) NOT NULL REFERENCES hosts(id), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + UNIQUE(team_id, host_id) +); + +CREATE INDEX IF NOT EXISTS idx_team_hosts_team_id ON team_hosts(team_id); + +-- team_group_hosts 团队组-宿主机关联表 +CREATE TABLE IF NOT EXISTS team_group_hosts ( + id UUID PRIMARY KEY, + group_id UUID NOT NULL REFERENCES team_groups(id), + host_id VARCHAR(255) NOT NULL REFERENCES hosts(id), + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + UNIQUE(group_id, host_id) +); + +CREATE INDEX IF NOT EXISTS idx_team_group_hosts_group_id ON team_group_hosts(group_id); From b8e23bf5504fd610a9e4ab4fa0814ce3a73285c7 Mon Sep 17 00:00:00 2001 From: yokowu <18836617@qq.com> Date: Tue, 17 Mar 2026 11:25:25 +0800 Subject: [PATCH 3/5] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=20Host/VM=20doma?= =?UTF-8?q?in=20=E7=B1=BB=E5=9E=8B=E5=92=8C=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - domain/host.go: Host/VirtualMachine 结构体、Usecase/Repo 接口、请求/响应类型 - domain/team_host.go: TeamHost 接口和类型 - domain/publichost.go: PublicHost 接口 - domain/terminal.go: 终端相关类型 --- backend/domain/host.go | 367 +++++++++++++++++++++++++++++++++++ backend/domain/publichost.go | 17 ++ backend/domain/team_host.go | 62 ++++++ backend/domain/terminal.go | 78 ++++++++ 4 files changed, 524 insertions(+) create mode 100644 backend/domain/host.go create mode 100644 backend/domain/publichost.go create mode 100644 backend/domain/team_host.go create mode 100644 backend/domain/terminal.go diff --git a/backend/domain/host.go b/backend/domain/host.go new file mode 100644 index 00000000..e6657466 --- /dev/null +++ b/backend/domain/host.go @@ -0,0 +1,367 @@ +package domain + +import ( + "context" + "strings" + "time" + + "github.com/google/uuid" + + "github.com/chaitin/MonkeyCode/backend/consts" + "github.com/chaitin/MonkeyCode/backend/db" + etypes "github.com/chaitin/MonkeyCode/backend/ent/types" + "github.com/chaitin/MonkeyCode/backend/pkg/cvt" + "github.com/chaitin/MonkeyCode/backend/pkg/taskflow" +) + +// HostUsecase 主机业务逻辑接口 +type HostUsecase interface { + GetInstallCommand(ctx context.Context, user *User) (string, error) + InstallScript(ctx context.Context, token *InstallReq) (string, error) + List(ctx context.Context, uid uuid.UUID) (*HostListResp, error) + VMInfo(ctx context.Context, uid uuid.UUID, id string) (*VirtualMachine, error) + ConnectVMTerminal(ctx context.Context, uid uuid.UUID, req TerminalReq) (taskflow.Sheller, error) + TerminalList(ctx context.Context, id string) ([]*Terminal, error) + CloseTerminal(ctx context.Context, id, terminalID string) error + ShareTerminal(ctx context.Context, user *User, req *ShareTerminalReq) (*ShareTerminalResp, error) + JoinTerminal(ctx context.Context, req *JoinTerminalReq) (taskflow.Sheller, *SharedTerminal, error) + WithVMPermission(ctx context.Context, uid uuid.UUID, id string, fn func(*VirtualMachine) error) error + CreateVM(ctx context.Context, user *User, req *CreateVMReq) (*VirtualMachine, error) + DeleteVM(ctx context.Context, uid uuid.UUID, hostID, vmID string) error + DeleteHost(ctx context.Context, uid uuid.UUID, id string) error + UpdateHost(ctx context.Context, uid uuid.UUID, req *UpdateHostReq) error + EnqueueAllCountDownVM(ctx context.Context) ([]string, error) + FireExpiredVM(ctx context.Context, fire bool) ([]FireExpiredVMItem, error) + UpdateVM(ctx context.Context, req UpdateVMReq) (*VirtualMachine, error) + ApplyPort(ctx context.Context, uid uuid.UUID, req *ApplyPortReq) (*VMPort, error) + RecyclePort(ctx context.Context, uid uuid.UUID, req *RecyclePortReq) error +} + +// HostRepo 主机数据访问接口 +type HostRepo interface { + List(ctx context.Context, uid uuid.UUID) ([]*db.Host, error) + GetHost(ctx context.Context, uid uuid.UUID, id string) (*Host, error) + GetByID(ctx context.Context, id string) (*db.Host, error) + GetVirtualMachine(ctx context.Context, id string) (*db.VirtualMachine, error) + GetVirtualMachineByEnvID(ctx context.Context, envID string) (*db.VirtualMachine, error) + GetVirtualMachineWithUser(ctx context.Context, uid uuid.UUID, id string) (*db.VirtualMachine, error) + CreateVirtualMachine(ctx context.Context, user *User, req *CreateVMReq, getRepoToken func(context.Context) (string, error), fn func(*db.Model, *db.Image) (*VirtualMachine, error)) (*VirtualMachine, error) + PastHourVirtualMachine(ctx context.Context) ([]*db.VirtualMachine, error) + AllCountDownVirtualMachine(ctx context.Context) ([]*db.VirtualMachine, error) + DeleteVirtualMachine(ctx context.Context, uid uuid.UUID, hostID, id string, fn func(*db.VirtualMachine) error) error + UpsertVirtualMachine(ctx context.Context, vm *taskflow.VirtualMachine) error + UpdateVirtualMachine(ctx context.Context, id string, fn func(*db.VirtualMachineUpdateOne) error) error + UpsertHost(ctx context.Context, h *taskflow.Host) error + DeleteHost(ctx context.Context, uid uuid.UUID, id string) error + UpdateHost(ctx context.Context, uid uuid.UUID, req *UpdateHostReq) error + UpdateVM(ctx context.Context, req UpdateVMReq, fn func(*db.VirtualMachine) error) (*db.VirtualMachine, int64, error) +} + +// VmExpireInfo VM 过期信息 +type VmExpireInfo struct { + UID uuid.UUID `json:"uid"` + VmID string `json:"vm_id"` + HostID string `json:"host_id"` + EnvID string `json:"env_id"` +} + +// InstallReq 安装请求 +type InstallReq struct { + Token string `json:"token" query:"token"` +} + +// InstallCommand 安装命令 +type InstallCommand struct { + Command string `json:"command"` +} + +// DeleteVirtualMachineReq 删除虚拟机请求 +type DeleteVirtualMachineReq struct { + ID string `json:"id" query:"id" param:"id" validate:"required"` + HostID string `json:"host_id" query:"host_id" param:"host_id" validate:"required"` +} + +// VMTerminalMessageType WebSocket 消息类型 +type VMTerminalMessageType string + +const ( + VMTerminalMessageTypeData VMTerminalMessageType = "data" + VMTerminalMessageTypeControl VMTerminalMessageType = "control" + VMTerminalMessageTypeError VMTerminalMessageType = "error" + VMTerminalMessageTypeResize VMTerminalMessageType = "resize" + VMTerminalMessageTypePing VMTerminalMessageType = "ping" + VMTerminalMessageTypePong VMTerminalMessageType = "pong" + VMTerminalMessageTypeConnected VMTerminalMessageType = "connected" +) + +// VMTerminalMessage WebSocket 消息结构 +type VMTerminalMessage struct { + Type VMTerminalMessageType `json:"type"` + Data string `json:"data"` +} + +// VMTerminalSuccess 连接成功信息 +type VMTerminalSuccess struct { + Username string `json:"username"` + Email string `json:"email"` + AvatarURL string `json:"avatar_url"` +} + +// VMTerminalResizeData 调整终端大小的数据 +type VMTerminalResizeData struct { + Col int `json:"col"` + Row int `json:"row"` +} + +// VirtualMachine 虚拟机 +type VirtualMachine struct { + ID string `json:"id"` + Hostname string `json:"hostname"` + OS string `json:"os"` + Cores int32 `json:"cores"` + Memory uint64 `json:"memory"` + Status taskflow.VirtualMachineStatus `json:"status"` + Name string `json:"name"` + LifeTimeSeconds int64 `json:"life_time_seconds"` + Host *Host `json:"host,omitempty"` + Version string `json:"version"` + CreatedAt int64 `json:"created_at"` + EnvironmentID string `json:"environment_id,omitempty"` + Owner *User `json:"owner,omitempty"` + Conditions []*etypes.Condition `json:"conditions"` + Ports []*VMPort `json:"ports,omitempty"` +} + +// From 从数据库模型转换 +func (v *VirtualMachine) From(vm *db.VirtualMachine) *VirtualMachine { + if vm == nil { + return v + } + + v.ID = vm.ID + v.Hostname = vm.Hostname + v.OS = vm.Os + v.Cores = int32(vm.Cores) + v.Memory = uint64(vm.Memory) + v.Name = vm.Name + v.Version = vm.Version + v.CreatedAt = vm.CreatedAt.Unix() + + if vm.Conditions != nil { + v.Conditions = vm.Conditions.Conditions + if v.Status != taskflow.VirtualMachineStatusOnline { + v.Status = taskflow.VirtualMachineStatusPending + for _, cond := range vm.Conditions.Conditions { + switch cond.Type { + case etypes.ConditionTypeFailed: + v.Status = taskflow.VirtualMachineStatusOffline + case etypes.ConditionTypeReady: + if time.Since(time.UnixMilli(cond.LastTransitionTime)) > 3*time.Minute { + v.Status = taskflow.VirtualMachineStatusOffline + } + } + } + } + } + + switch vm.TTLKind { + case consts.CountDown: + v.LifeTimeSeconds = vm.TTL - (time.Now().Unix() - vm.CreatedAt.Unix()) + case consts.Forever: + v.LifeTimeSeconds = 0 + } + if vm.Edges.Host != nil { + v.Host = cvt.From(vm.Edges.Host, &Host{}) + } + if vm.Edges.User != nil { + v.Owner = cvt.From(vm.Edges.User, &User{}) + } + return v +} + +// Host 宿主机 +type Host struct { + ID string `json:"id"` + Arch string `json:"arch"` + Cores int `json:"cores"` + OS string `json:"os"` + Status consts.HostStatus `json:"status"` + Memory uint64 `json:"memory"` + Name string `json:"name"` + ExternalIP string `json:"external_ip"` + Default bool `json:"default"` + Version string `json:"version"` + VirtualMachines []*VirtualMachine `json:"virtualmachines,omitempty"` + IsDefault bool `json:"is_default"` + Owner *Owner `json:"owner,omitempty"` + Groups []*TeamGroup `json:"groups,omitempty"` + Remark string `json:"remark,omitempty"` + Weight int `json:"weight"` +} + +// From 从数据库模型转换 +func (h *Host) From(e *db.Host) *Host { + if e == nil { + return h + } + + h.ID = e.ID + h.Arch = e.Arch + h.OS = e.Os + h.Cores = e.Cores + h.Memory = uint64(e.Memory) + h.Name = e.Hostname + h.ExternalIP = e.ExternalIP + h.Version = e.Version + h.VirtualMachines = cvt.Iter(e.Edges.Vms, func(_ int, v *db.VirtualMachine) *VirtualMachine { + return cvt.From(v, &VirtualMachine{}) + }) + h.Remark = e.Remark + h.Weight = e.Weight + if h.Weight <= 0 { + h.Weight = 1 + } + + if user := e.Edges.User; user != nil { + if user.Role == consts.UserRoleAdmin { + ls := strings.Split(h.ID, "-") + h.ID = "public_host" + if len(ls) > 3 { + h.ID = h.ID + "_" + strings.Join(ls[:3], "_") + } + h.Name = "MonkeyCode-AI" + h.ExternalIP = "" + return h + } + + h.Owner = &Owner{ + ID: user.ID.String(), + Type: consts.OwnerTypePrivate, + Name: user.Name, + } + } + + if gs := e.Edges.Groups; len(gs) > 0 { + h.Groups = cvt.Iter(gs, func(_ int, g *db.TeamGroup) *TeamGroup { + return cvt.From(g, &TeamGroup{}) + }) + + g := gs[0] + if team := g.Edges.Team; team != nil { + h.Owner = &Owner{ + ID: team.ID.String(), + Type: consts.OwnerTypeTeam, + Name: team.Name, + } + } + } + + return h +} + +// GetIsDefault 获取是否为默认主机 +func (h *Host) GetIsDefault(user *db.User) bool { + if defaultHostID, ok := user.DefaultConfigs[consts.DefaultConfigTypeHost]; ok { + if defaultHostID.String() == h.ID { + return true + } + } + return false +} + +// HostListResp 主机列表响应 +type HostListResp struct { + Hosts []*Host `json:"hosts"` +} + +// Resource 资源配置 +type Resource struct { + CPU int `json:"cpu"` + Memory int64 `json:"memory"` +} + +// ModelConfig 模型配置 +type ModelConfig struct { + URL string `json:"url"` + Key string `json:"key"` + Name string `json:"name"` +} + +// TaskRepoReq 仓库请求 +type TaskRepoReq struct { + RepoURL string `json:"repo_url"` + Branch string `json:"branch"` + RepoFilename string `json:"repo_filename"` + ZipURL string `json:"zip_url"` +} + +// CreateVMReq 创建虚拟机请求 +type CreateVMReq struct { + HostID string `json:"host_id" validate:"required"` + Name string `json:"name" validate:"required"` + ImageID uuid.UUID `json:"image_id" validate:"required"` + ModelID string `json:"model_id" validate:"required"` + Life int64 `json:"life"` + Resource *Resource `json:"resource" validate:"required"` + InstallCodingAgents bool `json:"install_coding_agents,omitempty"` + RepoReq *TaskRepoReq `json:"repo,omitempty"` + GitIdentityID uuid.UUID `json:"git_identity_id"` + Now time.Time `json:"-"` + UsePublicHost bool `json:"-"` +} + +// UpdateVMReq 更新虚拟机请求 +type UpdateVMReq struct { + ID string `json:"id" validate:"required"` + HostID string `json:"host_id" validate:"required"` + Life int64 `json:"life" validate:"min=3600"` + UID uuid.UUID `json:"-"` + UserName string `json:"-"` +} + +// UpdateHostReq 更新宿主机请求 +type UpdateHostReq struct { + ID string `param:"id" validate:"required" json:"-" swaggerignore:"true"` + IsDefault bool `json:"is_default,omitempty"` + Remark string `json:"remark,omitempty"` + Weight *int `json:"weight,omitempty" validate:"omitempty,min=1"` +} + +// ApplyPortReq 申请端口请求 +type ApplyPortReq struct { + ID string `json:"id" param:"id" validate:"required" swaggerignore:"true"` + HostID string `json:"host_id" param:"host_id" validate:"required" swaggerignore:"true"` + Port uint16 `json:"port" validate:"required,min=1,max=65535"` + WhiteList []string `json:"white_list" validate:"required,dive,ip"` + ForwardID string `json:"forward_id" validate:"omitempty"` +} + +// RecyclePortReq 回收端口请求 +type RecyclePortReq struct { + ID string `json:"id" param:"id" validate:"required" swaggerignore:"true"` + HostID string `json:"host_id" param:"host_id" validate:"required" swaggerignore:"true"` + ForwardID string `json:"forward_id" validate:"required"` +} + +// VMPort 虚拟机端口 +type VMPort struct { + ForwardID *string `json:"forward_id,omitempty"` + Port uint16 `json:"port"` + PreviewURL *string `json:"preview_url,omitempty"` + Status consts.PortStatus `json:"status,omitempty"` + WhiteList []string `json:"white_list,omitempty"` + ErrorMessage string `json:"error_message,omitempty"` + Success *bool `json:"success,omitempty"` +} + +// FireExpiredVMReq 触发过期 VM 请求 +type FireExpiredVMReq struct { + ID string `json:"id" query:"id"` + Fire bool `json:"fire" query:"fire"` +} + +// FireExpiredVMItem 触发过期 VM 结果 +type FireExpiredVMItem struct { + ID string `json:"id"` + Message string `json:"message"` +} diff --git a/backend/domain/publichost.go b/backend/domain/publichost.go new file mode 100644 index 00000000..c2d5eb97 --- /dev/null +++ b/backend/domain/publichost.go @@ -0,0 +1,17 @@ +package domain + +import ( + "context" + + "github.com/chaitin/MonkeyCode/backend/db" +) + +// PublicHostUsecase 公共主机业务逻辑接口 +type PublicHostUsecase interface { + PickHost(ctx context.Context) (*Host, error) +} + +// PublicHostRepo 公共主机数据访问接口 +type PublicHostRepo interface { + All(ctx context.Context) ([]*db.Host, error) +} diff --git a/backend/domain/team_host.go b/backend/domain/team_host.go new file mode 100644 index 00000000..5b6e2164 --- /dev/null +++ b/backend/domain/team_host.go @@ -0,0 +1,62 @@ +package domain + +import ( + "context" + + "github.com/google/uuid" + + "github.com/chaitin/MonkeyCode/backend/db" + "github.com/chaitin/MonkeyCode/backend/pkg/cvt" + "github.com/chaitin/MonkeyCode/backend/pkg/taskflow" +) + +// TeamHostUsecase 团队宿主机业务逻辑接口 +type TeamHostUsecase interface { + GetInstallCommand(ctx context.Context, teamUser *TeamUser) (string, error) + List(ctx context.Context, teamUser *TeamUser) (*ListTeamHostsResp, error) + Delete(ctx context.Context, teamUser *TeamUser, req *DeleteTeamHostReq) error + Update(ctx context.Context, teamUser *TeamUser, req *UpdateTeamHostReq) (*Host, error) +} + +// TeamHostRepo 团队宿主机数据访问接口 +type TeamHostRepo interface { + List(ctx context.Context, teamID uuid.UUID) ([]*db.Host, error) + Delete(ctx context.Context, teamUser *TeamUser, hostID string) error + UpsertHost(ctx context.Context, user *User, info *taskflow.Host) error + Update(ctx context.Context, teamUser *TeamUser, req *UpdateTeamHostReq) (*db.Host, error) +} + +// UpdateTeamHostReq 更新团队宿主机请求 +type UpdateTeamHostReq struct { + HostID string `param:"host_id" validate:"required" json:"-" swaggerignore:"true"` + GroupIDs []uuid.UUID `json:"group_ids" validate:"omitempty"` + Remark string `json:"remark,omitempty"` +} + +// ListTeamHostsResp 团队宿主机列表响应 +type ListTeamHostsResp struct { + Hosts []*Host `json:"hosts"` +} + +// DeleteTeamHostReq 删除团队宿主机请求 +type DeleteTeamHostReq struct { + HostID string `param:"host_id" validate:"required" json:"-" swaggerignore:"true"` +} + +// TeamGroupHost 团队分组宿主机信息 +type TeamGroupHost struct { + GroupID uuid.UUID `json:"group_id"` + CreatedAt int64 `json:"created_at"` + Host *Host `json:"host,omitempty"` +} + +// From 从数据库模型转换 +func (t *TeamGroupHost) From(src *db.TeamGroupHost) *TeamGroupHost { + if src == nil { + return t + } + t.GroupID = src.GroupID + t.CreatedAt = src.CreatedAt.Unix() + t.Host = cvt.From(src.Edges.Host, &Host{}) + return t +} diff --git a/backend/domain/terminal.go b/backend/domain/terminal.go new file mode 100644 index 00000000..7af14365 --- /dev/null +++ b/backend/domain/terminal.go @@ -0,0 +1,78 @@ +package domain + +import ( + "github.com/chaitin/MonkeyCode/backend/consts" + "github.com/chaitin/MonkeyCode/backend/pkg/taskflow" +) + +// CloseTerminalReq 关闭终端请求 +type CloseTerminalReq struct { + ID string `json:"id" query:"id" param:"id" validate:"required"` + TerminalID string `json:"terminal_id" param:"terminal_id" validate:"required"` +} + +// TerminalReq 终端连接请求 +type TerminalReq struct { + ID string `json:"id" query:"id" param:"id" validate:"required"` + TerminalID string `json:"terminal_id" query:"terminal_id"` + Exec string `json:"exec" query:"exec"` + Col int `json:"col" query:"col"` + Row int `json:"row" query:"row"` +} + +// JoinTerminalReq 加入终端请求 +type JoinTerminalReq struct { + TerminalID string `json:"terminal_id" query:"terminal_id"` + Password string `json:"password" query:"password"` + Col int `json:"col" query:"col"` + Row int `json:"row" query:"row"` +} + +// SharedTerminal 共享终端信息 +type SharedTerminal struct { + ID string `json:"id" query:"id" param:"id" validate:"required"` + Mode consts.TerminalMode `json:"mode" query:"mode"` + TerminalID string `json:"terminal_id" query:"terminal_id"` + User *User `json:"user"` +} + +// ShareTerminalReq 共享终端请求 +type ShareTerminalReq struct { + ID string `json:"id" query:"id" param:"id" validate:"required"` + Mode consts.TerminalMode `json:"mode" query:"mode"` + TerminalID string `json:"terminal_id" query:"terminal_id"` +} + +// ShareTerminalResp 共享终端响应 +type ShareTerminalResp struct { + Password string `json:"password"` +} + +// TerminalSession 终端会话信息 +type TerminalSession struct { + ID string `json:"id"` + Type consts.TerminalType `json:"type"` + CreatedAt int64 `json:"created_at"` + UpdatedAt int64 `json:"updated_at"` + IsActive bool `json:"is_active"` +} + +// Terminal 终端信息 +type Terminal struct { + ID string `json:"id"` + Title string `json:"title"` + ConnectedCount uint32 `json:"connected_count"` + CreatedAt int64 `json:"created_at"` +} + +// From 从 taskflow 类型转换 +func (t *Terminal) From(src *taskflow.Terminal) *Terminal { + if src == nil { + return t + } + t.ID = src.ID + t.Title = src.Title + t.ConnectedCount = src.ConnectedCount + t.CreatedAt = src.CreatedAt + return t +} From 0b2a5a91d84319ace3cd08426a4a022d625b6b5b Mon Sep 17 00:00:00 2001 From: yokowu <18836617@qq.com> Date: Tue, 17 Mar 2026 11:31:59 +0800 Subject: [PATCH 4/5] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=20Redis=20?= =?UTF-8?q?=E5=BB=B6=E8=BF=9F=E9=98=9F=E5=88=97=E5=92=8C=20VM=20=E8=BF=87?= =?UTF-8?q?=E6=9C=9F=E9=98=9F=E5=88=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - pkg/delayqueue/delayqueue.go: 通用泛型 Redis 延迟队列实现 - pkg/delayqueue/vmexpirequeue.go: VM 过期专用队列 --- backend/pkg/delayqueue/delayqueue.go | 317 ++++++++++++++++++++++++ backend/pkg/delayqueue/vmexpirequeue.go | 26 ++ 2 files changed, 343 insertions(+) create mode 100644 backend/pkg/delayqueue/delayqueue.go create mode 100644 backend/pkg/delayqueue/vmexpirequeue.go diff --git a/backend/pkg/delayqueue/delayqueue.go b/backend/pkg/delayqueue/delayqueue.go new file mode 100644 index 00000000..9d420835 --- /dev/null +++ b/backend/pkg/delayqueue/delayqueue.go @@ -0,0 +1,317 @@ +package delayqueue + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "time" + + "github.com/google/uuid" + "github.com/redis/go-redis/v9" +) + +// Job 表示一个延迟任务(泛型载荷) +type Job[T any] struct { + ID string + Queue string + Payload T + Attempts int +} + +// Handler 处理任务(泛型载荷) +type Handler[T any] func(ctx context.Context, job *Job[T]) error + +// RedisDelayQueue 基于 Redis 的延迟队列(泛型载荷) +type RedisDelayQueue[T any] struct { + rdb *redis.Client + logger *slog.Logger + prefix string + pollInterval time.Duration + batchSize int + requeueDelay time.Duration + maxAttempts int + jobTTL time.Duration +} + +// Option 可选项(泛型载荷) +type Option[T any] func(*RedisDelayQueue[T]) + +const ( + defaultPrefix = "mcai" + defaultPollInterval = 500 * time.Millisecond + defaultBatchSize = 64 + defaultRequeueDelay = 5 * time.Second + defaultMaxAttempts = 5 + defaultJobTTL = 7 * 24 * time.Hour +) + +// NewRedisDelayQueue 创建延迟队列(泛型) +func NewRedisDelayQueue[T any](rdb *redis.Client, logger *slog.Logger, opts ...Option[T]) *RedisDelayQueue[T] { + q := &RedisDelayQueue[T]{ + rdb: rdb, + logger: logger, + prefix: defaultPrefix, + pollInterval: defaultPollInterval, + batchSize: defaultBatchSize, + requeueDelay: defaultRequeueDelay, + maxAttempts: defaultMaxAttempts, + jobTTL: defaultJobTTL, + } + for _, opt := range opts { + opt(q) + } + return q +} + +func WithPrefix[T any](prefix string) Option[T] { + return func(q *RedisDelayQueue[T]) { q.prefix = prefix } +} + +func WithPollInterval[T any](d time.Duration) Option[T] { + return func(q *RedisDelayQueue[T]) { q.pollInterval = d } +} + +func WithBatchSize[T any](n int) Option[T] { + return func(q *RedisDelayQueue[T]) { q.batchSize = n } +} + +func WithRequeueDelay[T any](d time.Duration) Option[T] { + return func(q *RedisDelayQueue[T]) { q.requeueDelay = d } +} + +func WithMaxAttempts[T any](n int) Option[T] { + return func(q *RedisDelayQueue[T]) { q.maxAttempts = n } +} + +func WithJobTTL[T any](d time.Duration) Option[T] { + return func(q *RedisDelayQueue[T]) { q.jobTTL = d } +} + +// Enqueue 入队(若任务不存在则写入 payload;若已存在则仅更新到期时间) +func (q *RedisDelayQueue[T]) Enqueue(ctx context.Context, queue string, payload T, runAt time.Time, id string) (string, error) { + if id == "" { + id = uuid.NewString() + } + + jobKey := q.jobKey(queue, id) + exists, err := q.rdb.Exists(ctx, jobKey).Result() + if err != nil { + return "", err + } + if exists == 0 { + b, err := json.Marshal(&jobData[T]{Payload: payload, Attempts: 0}) + if err != nil { + return "", err + } + if err := q.rdb.Set(ctx, jobKey, b, q.jobTTL).Err(); err != nil { + return "", err + } + } + + zkey := q.zsetKey(queue) + score := float64(runAt.UnixMilli()) + if err := q.rdb.ZAdd(ctx, zkey, redis.Z{Score: score, Member: id}).Err(); err != nil { + if exists == 0 { + _ = q.rdb.Del(ctx, jobKey).Err() + } + return "", err + } + return id, nil +} + +// GetJobInfo 查询任务信息 +func (q *RedisDelayQueue[T]) GetJobInfo(ctx context.Context, queue, id string) (*Job[T], time.Time, bool, error) { + zkey := q.zsetKey(queue) + score, err := q.rdb.ZScore(ctx, zkey, id).Result() + if err == redis.Nil { + return nil, time.Time{}, false, nil + } + if err != nil { + return nil, time.Time{}, false, err + } + runAt := time.UnixMilli(int64(score)) + + job, err := q.loadJob(ctx, queue, id) + if err != nil { + return nil, time.Time{}, false, err + } + if job == nil { + return nil, time.Time{}, false, nil + } + return job, runAt, true, nil +} + +// Remove 移除任务 +func (q *RedisDelayQueue[T]) Remove(ctx context.Context, queue, id string) error { + if err := q.rdb.ZRem(ctx, q.zsetKey(queue), id).Err(); err != nil { + return err + } + return q.rdb.Del(ctx, q.jobKey(queue, id)).Err() +} + +// RemoveByPrefix 批量移除匹配前缀的任务 +func (q *RedisDelayQueue[T]) RemoveByPrefix(ctx context.Context, queue, prefix string) (int, error) { + zkey := q.zsetKey(queue) + cursor := uint64(0) + removed := 0 + for { + res, newCursor, err := q.rdb.ZScan(ctx, zkey, cursor, prefix+"*", 200).Result() + if err != nil { + return removed, err + } + for i := 0; i+1 < len(res); i += 2 { + id := res[i] + if err := q.Remove(ctx, queue, id); err != nil { + return removed, err + } + removed++ + } + cursor = newCursor + if cursor == 0 { + break + } + } + return removed, nil +} + +// StartConsumer 启动消费循环(阻塞) +func (q *RedisDelayQueue[T]) StartConsumer(ctx context.Context, queue string, handler Handler[T]) error { + ticker := time.NewTicker(q.pollInterval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return ctx.Err() + case <-ticker.C: + if err := q.pollOnce(ctx, queue, handler); err != nil { + q.logger.Warn("delayqueue poll error", "queue", queue, "err", err) + return err + } + } + } +} + +func (q *RedisDelayQueue[T]) pollOnce(ctx context.Context, queue string, handler Handler[T]) error { + ids, err := q.claimDue(ctx, queue, q.batchSize) + if err != nil { + return err + } + for _, id := range ids { + job, err := q.loadJob(ctx, queue, id) + if err != nil { + q.logger.Error("load job failed", "queue", queue, "id", id, "err", err) + continue + } + if job == nil { + continue + } + if err := handler(ctx, job); err != nil { + q.logger.Warn("handle job failed, will requeue", "queue", queue, "id", id, "attempts", job.Attempts+1, "err", err) + job.Attempts++ + if job.Attempts >= q.maxAttempts { + _ = q.deleteJob(ctx, queue, id) + continue + } + if err := q.saveJob(ctx, queue, id, job.Attempts, job.Payload); err != nil { + q.logger.Error("save job failed when requeue", "queue", queue, "id", id, "err", err) + continue + } + _, _ = q.Enqueue(ctx, queue, job.Payload, time.Now().Add(q.requeueDelay), id) + continue + } + if err := q.deleteJob(ctx, queue, id); err != nil { + if ctx.Err() != nil || errors.Is(err, redis.ErrClosed) { + q.logger.Debug("skip delete during shutdown", "queue", queue, "id", id, "err", err) + } else { + q.logger.Error("delete job payload failed", "queue", queue, "id", id, "err", err) + } + } + } + return nil +} + +func (q *RedisDelayQueue[T]) claimDue(ctx context.Context, queue string, count int) ([]string, error) { + zkey := q.zsetKey(queue) + now := time.Now().UnixMilli() + res, err := claimScript.Run(ctx, q.rdb, []string{zkey}, now, count).Result() + if err != nil { + return nil, err + } + items := make([]string, 0) + switch v := res.(type) { + case []any: + for _, it := range v { + items = append(items, fmt.Sprintf("%v", it)) + } + case []string: + items = append(items, v...) + } + return items, nil +} + +func (q *RedisDelayQueue[T]) loadJob(ctx context.Context, queue, id string) (*Job[T], error) { + jobKey := q.jobKey(queue, id) + b, err := q.rdb.Get(ctx, jobKey).Bytes() + if err == redis.Nil { + return nil, nil + } + if err != nil { + return nil, err + } + var data jobData[T] + if err := json.Unmarshal(b, &data); err != nil { + return nil, err + } + return &Job[T]{ + ID: id, + Queue: queue, + Payload: data.Payload, + Attempts: data.Attempts, + }, nil +} + +func (q *RedisDelayQueue[T]) saveJob(ctx context.Context, queue, id string, attempts int, payload T) error { + jobKey := q.jobKey(queue, id) + b, err := json.Marshal(&jobData[T]{Payload: payload, Attempts: attempts}) + if err != nil { + return err + } + return q.rdb.Set(ctx, jobKey, b, q.jobTTL).Err() +} + +func (q *RedisDelayQueue[T]) deleteJob(ctx context.Context, queue, id string) error { + return q.rdb.Del(ctx, q.jobKey(queue, id)).Err() +} + +// ExtendTTL 续期任务存储 TTL +func (q *RedisDelayQueue[T]) ExtendTTL(ctx context.Context, queue, id string, ttl time.Duration) error { + return q.rdb.Expire(ctx, q.jobKey(queue, id), ttl).Err() +} + +func (q *RedisDelayQueue[T]) zsetKey(queue string) string { + return fmt.Sprintf("%s:dq:%s:delayed", q.prefix, queue) +} + +func (q *RedisDelayQueue[T]) jobKey(queue, id string) string { + return fmt.Sprintf("%s:dq:%s:job:%s", q.prefix, queue, id) +} + +type jobData[T any] struct { + Payload T `json:"payload"` + Attempts int `json:"attempts"` +} + +var claimScript = redis.NewScript(` +local zkey = KEYS[1] +local now = tonumber(ARGV[1]) +local count = tonumber(ARGV[2]) +local items = redis.call('ZRANGEBYSCORE', zkey, '-inf', now, 'LIMIT', 0, count) +if #items > 0 then + for i=1,#items do + redis.call('ZREM', zkey, items[i]) + end +end +return items +`) diff --git a/backend/pkg/delayqueue/vmexpirequeue.go b/backend/pkg/delayqueue/vmexpirequeue.go new file mode 100644 index 00000000..6dbd04bc --- /dev/null +++ b/backend/pkg/delayqueue/vmexpirequeue.go @@ -0,0 +1,26 @@ +package delayqueue + +import ( + "log/slog" + "time" + + "github.com/redis/go-redis/v9" + + "github.com/chaitin/MonkeyCode/backend/domain" +) + +// VMExpireQueue VM 过期队列 +type VMExpireQueue struct { + *RedisDelayQueue[*domain.VmExpireInfo] +} + +// NewVMExpireQueue 创建 VM 过期队列 +func NewVMExpireQueue(redis *redis.Client, logger *slog.Logger) *VMExpireQueue { + queue := NewRedisDelayQueue( + redis, logger, + WithPrefix[*domain.VmExpireInfo]("mcai:vmexpire"), + WithRequeueDelay[*domain.VmExpireInfo](1*time.Minute), + WithPollInterval[*domain.VmExpireInfo](5*time.Second), + ) + return &VMExpireQueue{queue} +} From abd4381fcf21e29c8f3203c35dcb798f07bf6620 Mon Sep 17 00:00:00 2001 From: yokowu <18836617@qq.com> Date: Tue, 17 Mar 2026 14:36:07 +0800 Subject: [PATCH 5/5] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=20Host/VM=20Repo?= =?UTF-8?q?=E3=80=81Usecase=E3=80=81Handler=20=E5=B1=82=E5=8F=8A=E6=B3=A8?= =?UTF-8?q?=E5=86=8C=E9=9B=86=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phase 3 Chunk 5-8: 完成 Host/VM 模块从内部项目到开源项目的迁移。 Repo 层: - biz/host/repo/host.go: HostRepo (16 个方法) - biz/host/repo/publichost.go: PublicHostRepo - biz/team/repo/host.go: TeamHostRepo Usecase 层: - biz/host/usecase/host.go: HostUsecase (VM 生命周期、终端、端口转发) - biz/host/usecase/publichost.go: PublicHostUsecase (加权轮询) - biz/team/usecase/host.go: TeamHostUsecase Handler 层: - biz/host/handler/v1/host.go: 主机/VM REST + WebSocket 终端接口 - biz/team/handler/http/v1/host.go: 团队主机 CRUD 接口 注册与 Bridge: - biz/host/register.go, biz/register.go, biz/team/register.go - bridge.go: WithTaskflow, WithPublicHost, WithPrivilegeChecker - pkg/register.go: VMExpireQueue 注册 可选注入(开源项目默认不启用,内部项目通过 BridgeOption 注入): - PublicHost: 公共主机逻辑 (PickHost/CountLimit/TTLLimit) - PrivilegeChecker: 特权用户绕过 VM 所有权检查 新增工具包: - domain/domain.go: IDReq[T], PrivilegeChecker 接口 - pkg/ws: WebSocket 管理器 (基于 coder/websocket) - pkg/random: 随机字符串生成 - config: TaskFlow, PublicHost 配置段 --- backend/biz/host/handler/v1/host.go | 767 +++++++++++++++++++++++ backend/biz/host/handler/v1/internal.go | 394 ++++++++++++ backend/biz/host/register.go | 26 + backend/biz/host/repo/host.go | 553 ++++++++++++++++ backend/biz/host/repo/publichost.go | 40 ++ backend/biz/host/usecase/host.go | 728 +++++++++++++++++++++ backend/biz/host/usecase/publichost.go | 84 +++ backend/biz/register.go | 4 + backend/biz/team/handler/http/v1/host.go | 121 ++++ backend/biz/team/register.go | 6 + backend/biz/team/repo/host.go | 238 +++++++ backend/biz/team/usecase/host.go | 136 ++++ backend/bridge.go | 24 + backend/config/config.go | 15 + backend/consts/user.go | 4 - backend/domain/domain.go | 32 + backend/go.mod | 3 +- backend/go.sum | 2 + backend/pkg/random/random.go | 13 + backend/pkg/register.go | 15 + backend/pkg/taskflow/types.go | 81 +++ backend/pkg/ws/ws.go | 63 ++ 22 files changed, 3344 insertions(+), 5 deletions(-) create mode 100644 backend/biz/host/handler/v1/host.go create mode 100644 backend/biz/host/handler/v1/internal.go create mode 100644 backend/biz/host/register.go create mode 100644 backend/biz/host/repo/host.go create mode 100644 backend/biz/host/repo/publichost.go create mode 100644 backend/biz/host/usecase/host.go create mode 100644 backend/biz/host/usecase/publichost.go create mode 100644 backend/biz/team/handler/http/v1/host.go create mode 100644 backend/biz/team/repo/host.go create mode 100644 backend/biz/team/usecase/host.go create mode 100644 backend/domain/domain.go create mode 100644 backend/pkg/random/random.go create mode 100644 backend/pkg/ws/ws.go diff --git a/backend/biz/host/handler/v1/host.go b/backend/biz/host/handler/v1/host.go new file mode 100644 index 00000000..a16880a6 --- /dev/null +++ b/backend/biz/host/handler/v1/host.go @@ -0,0 +1,767 @@ +package v1 + +import ( + "context" + "encoding/base64" + "encoding/json" + "fmt" + "log/slog" + "time" + + "github.com/GoYoko/web" + "github.com/samber/do" + + "github.com/chaitin/MonkeyCode/backend/consts" + "github.com/chaitin/MonkeyCode/backend/domain" + "github.com/chaitin/MonkeyCode/backend/errcode" + "github.com/chaitin/MonkeyCode/backend/middleware" + "github.com/chaitin/MonkeyCode/backend/pkg/cvt" + "github.com/chaitin/MonkeyCode/backend/pkg/taskflow" + "github.com/chaitin/MonkeyCode/backend/pkg/ws" +) + +type HostHandler struct { + usecase domain.HostUsecase + userusecase domain.UserUsecase + pubhost domain.PublicHostUsecase // 可选,由内部项目通过 WithPublicHost 注入 + logger *slog.Logger +} + +func NewHostHandler(i *do.Injector) (*HostHandler, error) { + w := do.MustInvoke[*web.Web](i) + auth := do.MustInvoke[*middleware.AuthMiddleware](i) + + h := &HostHandler{ + usecase: do.MustInvoke[domain.HostUsecase](i), + userusecase: do.MustInvoke[domain.UserUsecase](i), + logger: do.MustInvoke[*slog.Logger](i).With("module", "handler.host"), + } + + // 可选注入 PublicHostUsecase + if pubhost, err := do.Invoke[domain.PublicHostUsecase](i); err == nil { + h.pubhost = pubhost + } + + w.GET("/internal/vm/fire", web.BindHandler(h.fireExpiredVM)) + + g := w.Group("/api/v1/users/hosts") + + g.GET("/install", web.BindHandler(h.Install)) + g.GET("/vms/terminals/join", web.BindHandler(h.JoinTerminal)) + + g.Use(auth.Auth()) + g.GET("/install-command", web.BaseHandler(h.GetInstallCommand)) + g.DELETE("/:id", web.BindHandler(h.DeleteHost)) + g.PUT("/:id", web.BindHandler(h.UpdateHost)) + g.GET("", web.BaseHandler(h.HostList)) + g.POST("/vms", web.BindHandler(h.CreateVM)) + g.PUT("/vms", web.BindHandler(h.UpdateVM)) + g.DELETE("/:host_id/vms/:id", web.BindHandler(h.DeleteVM)) + g.GET("/vms/:id", web.BindHandler(h.VMInfo)) + g.GET("/vms/:id/terminals/connect", web.BindHandler(h.ConnectVMTerminal)) + g.GET("/vms/:id/terminals", web.BindHandler(h.TerminalList)) + g.POST("/vms/:id/terminals/share", web.BindHandler(h.ShareTerminal)) + g.DELETE("/vms/:id/terminals/:terminal_id", web.BindHandler(h.CloseTerminal)) + g.POST("/:host_id/vms/:id/ports", web.BindHandler(h.ApplyPort)) + g.DELETE("/:host_id/vms/:id/ports/:port", web.BindHandler(h.RecyclePort)) + return h, nil +} + +func (h *HostHandler) fireExpiredVM(c *web.Context, req domain.FireExpiredVMReq) error { + ids, err := h.usecase.FireExpiredVM(c.Request().Context(), req.Fire) + if err != nil { + return err + } + return c.Success(map[string]any{ + "total": len(ids), + "ids": ids, + }) +} + +// GetInstallCommand 获取绑定宿主机命令 +// +// @Summary 获取绑定宿主机命令 +// @Description 获取绑定宿主机命令 +// @Tags 【用户】主机管理 +// @Accept json +// @Produce json +// @Security MonkeyCodeAIAuth +// @Success 200 {object} web.Resp{data=domain.InstallCommand} "成功" +// @Router /api/v1/users/hosts/install-command [get] +func (h *HostHandler) GetInstallCommand(c *web.Context) error { + user := middleware.GetUser(c) + cmd, err := h.usecase.GetInstallCommand(c.Request().Context(), user) + if err != nil { + return err + } + return c.Success(domain.InstallCommand{ + Command: cmd, + }) +} + +func (h *HostHandler) Install(c *web.Context, req domain.InstallReq) error { + script, err := h.usecase.InstallScript(c.Request().Context(), &req) + if err != nil { + return err + } + + c.Response().Header().Set("Content-Type", "application/octet-stream") + c.Response().Header().Set("Attachment", "filename=install_script.sh") + _, err = c.Response().Write([]byte(script)) + return err +} + +// HostList 获取主机列表 +// +// @Summary 获取主机列表 +// @Description 获取主机列表 +// @Tags 【用户】主机管理 +// @Accept json +// @Produce json +// @Security MonkeyCodeAIAuth +// @Success 200 {object} web.Resp{data=domain.HostListResp} "成功" +// @Failure 401 {object} web.Resp "未授权" +// @Failure 500 {object} web.Resp "服务器错误" +// @Router /api/v1/users/hosts [get] +func (h *HostHandler) HostList(c *web.Context) error { + user := middleware.GetUser(c) + resp, err := h.usecase.List(c.Request().Context(), user.ID) + if err != nil { + return err + } + return c.Success(resp) +} + +// VMInfo 获取虚拟机详情 +// +// @Summary 获取虚拟机详情 +// @Description 获取虚拟机详情 +// @Tags 【用户】主机管理 +// @Accept json +// @Produce json +// @Security MonkeyCodeAIAuth +// @Param id path string true "虚拟机ID" +// @Success 200 {object} web.Resp{data=domain.VirtualMachine} "成功" +// @Failure 401 {object} web.Resp "未授权" +// @Failure 500 {object} web.Resp "服务器错误" +// @Router /api/v1/users/hosts/vms/{id} [get] +func (h *HostHandler) VMInfo(c *web.Context, req domain.IDReq[string]) error { + user := middleware.GetUser(c) + host, err := h.usecase.VMInfo(c.Request().Context(), user.ID, req.ID) + if err != nil { + return err + } + return c.Success(host) +} + +// TerminalList 获取虚拟机终端session列表 +// +// @Summary 获取虚拟机终端session列表 +// @Description 获取虚拟机终端session列表 +// @Tags 【用户】终端连接管理 +// @Accept json +// @Produce json +// @Security MonkeyCodeAIAuth +// @Param id path string true "虚拟机ID" +// @Success 200 {object} web.Resp{data=[]domain.Terminal} "成功" +// @Failure 401 {object} web.Resp "未授权" +// @Failure 500 {object} web.Resp "服务器错误" +// @Router /api/v1/users/hosts/vms/{id}/terminals [get] +func (h *HostHandler) TerminalList(c *web.Context, req domain.IDReq[string]) error { + user := middleware.GetUser(c) + return h.usecase.WithVMPermission(c.Request().Context(), user.ID, req.ID, func(v *domain.VirtualMachine) error { + ts, err := h.usecase.TerminalList(c.Request().Context(), req.ID) + if err != nil { + return err + } + return c.Success(ts) + }) +} + +// CloseTerminal 关闭虚拟机终端session +// +// @Summary 关闭虚拟机终端session +// @Description 关闭虚拟机终端session +// @Tags 【用户】终端连接管理 +// @Accept json +// @Produce json +// @Security MonkeyCodeAIAuth +// @Param id path string true "虚拟机ID" +// @Param terminal_id path string true "终端 id" +// @Success 200 {object} web.Resp{data=[]domain.Terminal} "成功" +// @Failure 401 {object} web.Resp "未授权" +// @Failure 500 {object} web.Resp "服务器错误" +// @Router /api/v1/users/hosts/vms/{id}/terminals/{terminal_id} [delete] +func (h *HostHandler) CloseTerminal(c *web.Context, req domain.CloseTerminalReq) error { + user := middleware.GetUser(c) + return h.usecase.WithVMPermission(c.Request().Context(), user.ID, req.ID, func(v *domain.VirtualMachine) error { + if err := h.usecase.CloseTerminal(c.Request().Context(), req.ID, req.TerminalID); err != nil { + return err + } + return c.Success(nil) + }) +} + +// JoinTerminal 通过 WebSocket 加入终端 +// +// @Summary 通过 WebSocket 加入终端 +// @Description 通过 WebSocket 加入终端 +// @Tags 【用户】终端连接管理 +// @Accept json +// @Produce json +// @Security MonkeyCodeAIAuth +// @Param request query domain.JoinTerminalReq true "参数" +// @Success 200 {object} web.Resp{data=domain.ShareTerminalResp} "成功" +// @Failure 400 {object} web.Resp "请求参数错误" +// @Failure 401 {object} web.Resp "未授权" +// @Router /api/v1/users/hosts/vms/terminals/join [get] +func (h *HostHandler) JoinTerminal(c *web.Context, req domain.JoinTerminalReq) error { + col := cvt.ZeroWithDefault(req.Col, 80) + row := cvt.ZeroWithDefault(req.Row, 24) + + wsConn, err := ws.Accept(c.Response(), c.Request()) + if err != nil { + h.logger.ErrorContext(c.Request().Context(), "failed to upgrade to websocket", "error", err) + return err + } + defer wsConn.Close() + + h.logger.InfoContext(c.Request().Context(), "websocket connection established", "col", col, "row", row) + + shell, shared, err := h.usecase.JoinTerminal(c.Request().Context(), &req) + if err != nil { + h.logger.With("req", req).ErrorContext(c.Request().Context(), "failed to connect to vm terminal 验证密码失败", "error", err) + wsConn.WriteJSON(domain.VMTerminalMessage{ + Type: domain.VMTerminalMessageTypeError, + Data: "验证密码失败", + }) + return err + } + defer shell.Stop() + + ctx, cancel := context.WithCancel(c.Request().Context()) + defer cancel() + go h.terminalPing(ctx, cancel, wsConn, req.TerminalID) + + go func() { + defer cancel() + for { + select { + case <-ctx.Done(): + return + default: + message, err := wsConn.ReadMessage() + if err != nil { + h.logger.ErrorContext(ctx, "websocket read error", "error", err) + return + } + var msg domain.VMTerminalMessage + if err := json.Unmarshal(message, &msg); err != nil { + h.logger.ErrorContext(ctx, "failed to unmarshal control message", "error", err) + continue + } + + switch msg.Type { + case domain.VMTerminalMessageTypeData: + b, err := base64.StdEncoding.DecodeString(msg.Data) + if err != nil { + h.logger.ErrorContext(ctx, "failed to decode base64 data", "error", err) + continue + } + shell.Write(taskflow.TerminalData{ + Data: b, + }) + + case domain.VMTerminalMessageTypeResize: + var resizeData domain.VMTerminalResizeData + if err := json.Unmarshal([]byte(msg.Data), &resizeData); err != nil { + h.logger.ErrorContext(ctx, "failed to unmarshal resize data", "error", err) + continue + } + shell.Write(taskflow.TerminalData{ + Resize: &taskflow.TerminalSize{ + Col: uint32(resizeData.Col), + Row: uint32(resizeData.Row), + }, + }) + + default: + h.logger.WarnContext(ctx, "unknown control action", "action", msg.Type) + } + } + } + }() + + if err := shell.BlockRead(func(td taskflow.TerminalData) { + if td.Connected { + success := &domain.VMTerminalSuccess{ + Username: shared.User.Name, + Email: shared.User.Email, + AvatarURL: shared.User.AvatarURL, + } + b, err := json.Marshal(success) + if err != nil { + h.logger.ErrorContext(ctx, "failed to marshal success message", "error", err) + b = fmt.Appendf(nil, `{"username": "%s"}`, shared.User.Name) + } + + wsConn.WriteJSON(domain.VMTerminalMessage{ + Type: domain.VMTerminalMessageTypeConnected, + Data: string(b), + }) + } + + if len(td.Data) > 0 { + data := base64.StdEncoding.EncodeToString(td.Data) + msg := &domain.VMTerminalMessage{ + Type: domain.VMTerminalMessageTypeData, + Data: data, + } + if err := wsConn.WriteJSON(msg); err != nil { + h.logger.With("error", err).ErrorContext(ctx, "failed to write message to frontend") + } + } + + if td.Resize != nil { + b, err := json.Marshal(td.Resize) + if err != nil { + h.logger.ErrorContext(ctx, "failed to marshal resize data", "error", err) + } else { + msg := &domain.VMTerminalMessage{ + Type: domain.VMTerminalMessageTypeResize, + Data: string(b), + } + if err := wsConn.WriteJSON(msg); err != nil { + h.logger.With("error", err).ErrorContext(ctx, "failed to write message to frontend") + } + } + } + + if td.Error != nil { + msg := &domain.VMTerminalMessage{ + Type: domain.VMTerminalMessageTypeError, + Data: *td.Error, + } + if err := wsConn.WriteJSON(msg); err != nil { + h.logger.With("error", err).ErrorContext(ctx, "failed to write message to frontend") + } + cancel() + } + }); err != nil { + h.logger.ErrorContext(ctx, "failed to block read from vm terminal", "error", err) + return err + } + + return nil +} + +// ConnectVMTerminal 通过 WebSocket 连接到虚拟机终端 +// +// @Summary 连接虚拟机终端 +// @Description 通过 WebSocket 连接到指定虚拟机的终端,支持双向通信 +// @Tags 【用户】终端连接管理 +// @Accept json +// @Produce json +// @Security MonkeyCodeAIAuth +// @Param id path string true "虚拟机ID" +// @Param terminal_id query string false "终端ID" +// @Param col query int false "终端列数" default(80) +// @Param row query int false "终端行数" default(24) +// @Success 101 {string} string "WebSocket 连接成功" +// @Failure 400 {object} web.Resp "请求参数错误" +// @Failure 401 {object} web.Resp "未授权" +// @Failure 500 {object} web.Resp "服务器错误" +// @Router /api/v1/users/hosts/vms/{id}/terminals/connect [get] +func (h *HostHandler) ConnectVMTerminal(c *web.Context, req domain.TerminalReq) error { + user := middleware.GetUser(c) + logger := h.logger.With("fn", "ConnectVMTerminal", "user", user, "req", req) + logger.InfoContext(c.Request().Context(), "connect vm terminal") + + if req.ID == "" { + return errcode.ErrVMIDRequired + } + + ctx, cancel := context.WithCancel(c.Request().Context()) + defer cancel() + + if err := h.usecase.WithVMPermission(ctx, user.ID, req.ID, func(v *domain.VirtualMachine) error { + return nil + }); err != nil { + logger.With("error", err).ErrorContext(ctx, "failed to check permission") + return err + } + + req.Col = cvt.ZeroWithDefault(req.Col, 80) + req.Row = cvt.ZeroWithDefault(req.Row, 24) + + wsConn, err := ws.Accept(c.Response(), c.Request()) + if err != nil { + logger.ErrorContext(ctx, "failed to upgrade to websocket", "error", err) + return err + } + defer wsConn.Close() + go h.terminalPing(ctx, cancel, wsConn, req.TerminalID) + + logger.InfoContext(ctx, "websocket connection established") + + shell, err := h.usecase.ConnectVMTerminal(ctx, user.ID, req) + if err != nil { + logger.ErrorContext(ctx, "failed to connect to vm terminal", "error", err, "vm_id", req.ID) + wsConn.WriteJSON(domain.VMTerminalMessage{ + Type: domain.VMTerminalMessageTypeError, + Data: err.Error(), + }) + return err + } + defer shell.Stop() + + go func() { + defer cancel() + for { + select { + case <-ctx.Done(): + logger.With("error", ctx.Err()).ErrorContext(ctx, "context canceled", "vm_id", req.ID) + return + default: + message, err := wsConn.ReadMessage() + if err != nil { + logger.ErrorContext(ctx, "websocket read error", "error", err, "vm_id", req.ID) + return + } + var msg domain.VMTerminalMessage + if err := json.Unmarshal(message, &msg); err != nil { + logger.ErrorContext(ctx, "failed to unmarshal control message", "error", err, "vm_id", req.ID) + continue + } + + switch msg.Type { + case domain.VMTerminalMessageTypeData: + b, err := base64.StdEncoding.DecodeString(msg.Data) + if err != nil { + logger.ErrorContext(ctx, "failed to decode base64 data", "error", err, "vm_id", req.ID) + continue + } + shell.Write(taskflow.TerminalData{ + Data: b, + }) + + case domain.VMTerminalMessageTypeResize: + var resizeData domain.VMTerminalResizeData + if err := json.Unmarshal([]byte(msg.Data), &resizeData); err != nil { + logger.ErrorContext(ctx, "failed to unmarshal resize data", "error", err, "vm_id", req.ID) + continue + } + logger.InfoContext(ctx, "terminal resize requested", "vm_id", req.ID, "col", resizeData.Col, "row", resizeData.Row) + shell.Write(taskflow.TerminalData{ + Resize: &taskflow.TerminalSize{ + Col: uint32(resizeData.Col), + Row: uint32(resizeData.Row), + }, + }) + + default: + logger.WarnContext(ctx, "unknown control action", "action", msg.Type, "vm_id", req.ID) + } + } + } + }() + + if err := shell.BlockRead(func(td taskflow.TerminalData) { + if td.Connected { + success := &domain.VMTerminalSuccess{ + Username: user.Name, + Email: user.Email, + AvatarURL: user.AvatarURL, + } + b, err := json.Marshal(success) + if err != nil { + logger.ErrorContext(ctx, "failed to marshal success message", "error", err) + b = fmt.Appendf(nil, `{"username": "%s"}`, user.Name) + } + wsConn.WriteJSON(domain.VMTerminalMessage{ + Type: domain.VMTerminalMessageTypeConnected, + Data: string(b), + }) + } + + if len(td.Data) > 0 { + data := base64.StdEncoding.EncodeToString(td.Data) + msg := &domain.VMTerminalMessage{ + Type: domain.VMTerminalMessageTypeData, + Data: data, + } + if err := wsConn.WriteJSON(msg); err != nil { + logger.With("error", err).ErrorContext(ctx, "failed to write message to frontend") + } + } + + if td.Resize != nil { + b, err := json.Marshal(td.Resize) + if err != nil { + logger.ErrorContext(ctx, "failed to marshal resize data", "error", err) + } else { + msg := &domain.VMTerminalMessage{ + Type: domain.VMTerminalMessageTypeResize, + Data: string(b), + } + if err := wsConn.WriteJSON(msg); err != nil { + logger.With("error", err).ErrorContext(ctx, "failed to write message to frontend") + } + } + } + if td.Error != nil { + msg := &domain.VMTerminalMessage{ + Type: domain.VMTerminalMessageTypeError, + Data: *td.Error, + } + if err := wsConn.WriteJSON(msg); err != nil { + logger.With("error", err).ErrorContext(ctx, "failed to write message to frontend") + } + + cancel() + } + }); err != nil { + logger.ErrorContext(ctx, "failed to block read from vm terminal", "error", err) + return err + } + + logger.InfoContext(ctx, "websocket connection closed") + + return nil +} + +func (h *HostHandler) terminalPing( + ctx context.Context, + cancel context.CancelFunc, + wsConn *ws.WebsocketManager, + terminalID string, +) { + ticker := time.NewTicker(10 * time.Second) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + if err := wsConn.WriteJSON(domain.VMTerminalMessage{ + Type: domain.VMTerminalMessageTypePing, + }); err != nil { + h.logger.With("error", err, "terminal", terminalID).Warn("failed to ping ws terminal") + cancel() + return + } + } + } +} + +// ShareTerminal 分享终端 +// +// @Summary 分享终端 +// @Description 分享终端 +// @Tags 【用户】终端连接管理 +// @Accept json +// @Produce json +// @Security MonkeyCodeAIAuth +// @Param request body domain.ShareTerminalReq true "分享终端请求" +// @Success 200 {object} web.Resp{data=domain.ShareTerminalResp} "成功" +// @Failure 400 {object} web.Resp "请求参数错误" +// @Failure 401 {object} web.Resp "未授权" +// @Router /api/v1/users/hosts/vms/{id}/terminals/share [post] +func (h *HostHandler) ShareTerminal(c *web.Context, req domain.ShareTerminalReq) error { + user := middleware.GetUser(c) + return h.usecase.WithVMPermission(c.Request().Context(), user.ID, req.ID, func(v *domain.VirtualMachine) error { + resp, err := h.usecase.ShareTerminal(c.Request().Context(), user, &req) + if err != nil { + return err + } + return c.Success(resp) + }) +} + +// CreateVM 创建虚拟机 +// +// @Summary 创建虚拟机 +// @Description 创建虚拟机 +// @Tags 【用户】主机管理 +// @Accept json +// @Produce json +// @Security MonkeyCodeAIAuth +// @Param request body domain.CreateVMReq true "创建虚拟机请求" +// @Success 200 {object} web.Resp{data=domain.VirtualMachine} "成功" +// @Failure 400 {object} web.Resp "请求参数错误" +// @Failure 401 {object} web.Resp "未授权" +// @Failure 500 {object} web.Resp "服务器错误" +// @Router /api/v1/users/hosts/vms [post] +func (h *HostHandler) CreateVM(c *web.Context, req domain.CreateVMReq) error { + user := middleware.GetUser(c) + + // 公共主机逻辑(仅在内部项目注入 PublicHostUsecase 时生效) + if req.HostID == consts.PUBLIC_HOST_ID && h.pubhost != nil { + if req.Life > 3*60*60 || req.Life <= 0 { + return errcode.ErrPublicHostBeyondLimit + } + + host, err := h.pubhost.PickHost(c.Request().Context()) + if err != nil { + return err + } + req.HostID = host.ID + req.UsePublicHost = true + h.logger.With("host", host).DebugContext(c.Request().Context(), "pick public host") + } + + vm, err := h.usecase.CreateVM(c.Request().Context(), user, &req) + if err != nil { + h.logger.With("error", err).ErrorContext(c.Request().Context(), "failed to create vm") + return err + } + + return c.Success(vm) +} + +// DeleteVM 删除虚拟机 +// +// @Summary 删除虚拟机 +// @Description 删除虚拟机 +// @Tags 【用户】主机管理 +// @Accept json +// @Produce json +// @Security MonkeyCodeAIAuth +// @Param host_id path string true "宿主机ID" +// @Param id path string true "虚拟机ID" +// @Success 200 {object} web.Resp "成功" +// @Failure 400 {object} web.Resp "请求参数错误" +// @Failure 401 {object} web.Resp "未授权" +// @Failure 404 {object} web.Resp "虚拟机不存在" +// @Failure 500 {object} web.Resp "服务器错误" +// @Router /api/v1/users/hosts/{host_id}/vms/{id} [delete] +func (h *HostHandler) DeleteVM(c *web.Context, req domain.DeleteVirtualMachineReq) error { + user := middleware.GetUser(c) + err := h.usecase.DeleteVM(c.Request().Context(), user.ID, req.HostID, req.ID) + if err != nil { + return err + } + return c.Success(nil) +} + +// UpdateVM 修改虚拟机 +// +// @Summary 修改虚拟机 +// @Description 修改虚拟机 +// @Tags 【用户】主机管理 +// @Accept json +// @Produce json +// @Security MonkeyCodeAIAuth +// @Param req body domain.UpdateVMReq true "修改虚拟机请求" +// @Success 200 {object} web.Resp{data=domain.VirtualMachine} "成功" +// @Failure 400 {object} web.Resp "请求参数错误" +// @Failure 401 {object} web.Resp "未授权" +// @Failure 404 {object} web.Resp "虚拟机不存在" +// @Failure 500 {object} web.Resp "服务器错误" +// @Router /api/v1/users/hosts/vms [put] +func (h *HostHandler) UpdateVM(c *web.Context, req domain.UpdateVMReq) error { + user := middleware.GetUser(c) + req.UID = user.ID + req.UserName = user.Name + resp, err := h.usecase.UpdateVM(c.Request().Context(), req) + if err != nil { + return err + } + return c.Success(resp) +} + +// DeleteHost 删除宿主机 +// +// @Summary 删除宿主机 +// @Description 删除宿主机 +// @Tags 【用户】主机管理 +// @Accept json +// @Produce json +// @Security MonkeyCodeAIAuth +// @Param id path string true "宿主机ID" +// @Success 200 {object} web.Resp "成功" +// @Failure 400 {object} web.Resp "请求参数错误" +// @Failure 401 {object} web.Resp "未授权" +// @Failure 500 {object} web.Resp "服务器错误" +// @Router /api/v1/users/hosts/{id} [delete] +func (h *HostHandler) DeleteHost(c *web.Context, req domain.IDReq[string]) error { + user := middleware.GetUser(c) + if err := h.usecase.DeleteHost(c.Request().Context(), user.ID, req.ID); err != nil { + return err + } + return c.Success(nil) +} + +// UpdateHost 更新宿主机 +// +// @Summary 更新宿主机 +// @Description 更新宿主机 +// @Tags 【用户】主机管理 +// @Accept json +// @Produce json +// @Security MonkeyCodeAIAuth +// @Param id path string true "宿主机ID" +// @Param request body domain.UpdateHostReq true "更新宿主机请求" +// @Success 200 {object} web.Resp "成功" +// @Failure 400 {object} web.Resp "请求参数错误" +// @Failure 401 {object} web.Resp "未授权" +// @Failure 500 {object} web.Resp "服务器错误" +// @Router /api/v1/users/hosts/{id} [put] +func (h *HostHandler) UpdateHost(c *web.Context, req domain.UpdateHostReq) error { + user := middleware.GetUser(c) + if err := h.usecase.UpdateHost(c.Request().Context(), user.ID, &req); err != nil { + return err + } + return c.Success(nil) +} + +// ApplyPort 为开发环境申请一个端口 +// +// @Summary 申请端口 +// @Description 为开发环境申请一个端口 +// @Tags 【用户】主机管理 +// @Accept json +// @Produce json +// @Security MonkeyCodeAIAuth +// @Param host_id path string true "宿主机ID" +// @Param id path string true "虚拟机ID" +// @Param request body domain.ApplyPortReq true "申请端口请求" +// @Success 200 {object} web.Resp{data=domain.VMPort} "成功" +// @Failure 400 {object} web.Resp "请求参数错误" +// @Failure 401 {object} web.Resp "未授权" +// @Failure 500 {object} web.Resp "服务器错误" +// @Router /api/v1/users/hosts/{host_id}/vms/{id}/ports [post] +func (h *HostHandler) ApplyPort(c *web.Context, req domain.ApplyPortReq) error { + user := middleware.GetUser(c) + port, err := h.usecase.ApplyPort(c.Request().Context(), user.ID, &req) + if err != nil { + h.logger.With("error", err).ErrorContext(c.Request().Context(), "failed to apply port") + return errcode.ErrApplyPortFailed.Wrap(err) + } + return c.Success(port) +} + +// RecyclePort 为开发环境回收一个端口 +// +// @Summary 回收端口 +// @Description 为开发环境回收一个端口 +// @Tags 【用户】主机管理 +// @Accept json +// @Produce json +// @Security MonkeyCodeAIAuth +// @Param host_id path string true "宿主机ID" +// @Param id path string true "虚拟机ID" +// @Param request body domain.RecyclePortReq true "回收端口请求" +// @Success 200 {object} web.Resp "成功" +// @Failure 400 {object} web.Resp "请求参数错误" +// @Failure 401 {object} web.Resp "未授权" +// @Failure 500 {object} web.Resp "服务器错误" +// @Router /api/v1/users/hosts/{host_id}/vms/{id}/ports/{port} [delete] +func (h *HostHandler) RecyclePort(c *web.Context, req domain.RecyclePortReq) error { + user := middleware.GetUser(c) + if err := h.usecase.RecyclePort(c.Request().Context(), user.ID, &req); err != nil { + h.logger.With("error", err).ErrorContext(c.Request().Context(), "failed to recycle port") + return errcode.ErrRecyclePortFailed.Wrap(err) + } + return c.Success(nil) +} diff --git a/backend/biz/host/handler/v1/internal.go b/backend/biz/host/handler/v1/internal.go new file mode 100644 index 00000000..2c640dd8 --- /dev/null +++ b/backend/biz/host/handler/v1/internal.go @@ -0,0 +1,394 @@ +package v1 + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log/slog" + "strings" + "time" + + "github.com/GoYoko/web" + "github.com/google/uuid" + "github.com/patrickmn/go-cache" + "github.com/redis/go-redis/v9" + "github.com/samber/do" + + "github.com/chaitin/MonkeyCode/backend/db" + "github.com/chaitin/MonkeyCode/backend/domain" + etypes "github.com/chaitin/MonkeyCode/backend/ent/types" + "github.com/chaitin/MonkeyCode/backend/pkg/cvt" + "github.com/chaitin/MonkeyCode/backend/pkg/taskflow" +) + +// InternalHostHandler 处理 taskflow 回调的 host/VM 相关接口 +type InternalHostHandler struct { + logger *slog.Logger + repo domain.HostRepo + teamRepo domain.TeamHostRepo + redis *redis.Client + cache *cache.Cache + hook domain.InternalHook // 可选,由内部项目通过 WithInternalHook 注入 +} + +func NewInternalHostHandler(i *do.Injector) (*InternalHostHandler, error) { + w := do.MustInvoke[*web.Web](i) + + h := &InternalHostHandler{ + logger: do.MustInvoke[*slog.Logger](i).With("module", "InternalHostHandler"), + repo: do.MustInvoke[domain.HostRepo](i), + teamRepo: do.MustInvoke[domain.TeamHostRepo](i), + redis: do.MustInvoke[*redis.Client](i), + cache: cache.New(15*time.Minute, 10*time.Minute), + } + + // 可选注入 InternalHook + if hook, err := do.Invoke[domain.InternalHook](i); err == nil { + h.hook = hook + } + + g := w.Group("/internal") + g.POST("/check-token", web.BindHandler(h.CheckToken)) + g.POST("/host-info", web.BindHandler(h.ReportHostInfo)) + g.POST("/vm-info", web.BindHandler(h.ReportVirtualMachine)) + g.POST("/vm-ready", web.BindHandler(h.VmReady)) + g.POST("/vm-conditions", web.BindHandler(h.VmConditions)) + g.POST("/llms", web.BindHandler(h.ListLLM)) + g.POST("/coding-config", web.BindHandler(h.GetCodingConfig)) + g.POST("/git-credential", web.BindHandler(h.GitCredential)) + g.GET("/vm/list", web.BaseHandler(h.VMList)) + + return h, nil +} + +// ReportHostInfo 上报宿主机信息 +func (h *InternalHostHandler) ReportHostInfo(c *web.Context, host taskflow.Host) error { + if err := h.repo.UpsertHost(context.Background(), &host); err != nil { + h.logger.ErrorContext(context.Background(), "upsert host failed", "error", err) + return err + } + return c.Success(nil) +} + +// ReportVirtualMachine 上报虚拟机信息 +func (h *InternalHostHandler) ReportVirtualMachine(c *web.Context, vm taskflow.VirtualMachine) error { + if err := h.repo.UpsertVirtualMachine(context.Background(), &vm); err != nil { + h.logger.ErrorContext(context.Background(), "upsert virtual machine failed", "error", err) + return err + } + return c.Success(nil) +} + +// ListLLM 列出虚拟机关联的 LLM +func (h *InternalHostHandler) ListLLM(c *web.Context, req taskflow.ListLLMReq) error { + vm, err := h.repo.GetVirtualMachine(c.Request().Context(), req.VmID) + if err != nil { + h.logger.ErrorContext(c.Request().Context(), "get virtual machine failed", "error", err) + return err + } + + if vm.HostID != req.HostID { + h.logger.ErrorContext(c.Request().Context(), "host id mismatch", "vm_host_id", vm.HostID, "req_host_id", req.HostID) + return errors.New("host id mismatch") + } + + if m := vm.Edges.Model; m != nil { + return c.Success([]*taskflow.LLMInfo{ + { + ApiKey: m.APIKey, + BaseURL: m.BaseURL, + Model: m.Model, + }, + }) + } + + return c.Success([]*taskflow.LLMInfo{}) +} + +// GetCodingConfig 获取编码配置 +func (h *InternalHostHandler) GetCodingConfig(c *web.Context, req taskflow.GetCodingConfigReq) error { + return c.Success(taskflow.CodingConfig{}) +} + +// VMList 根据 ID 获取虚拟机信息 +func (h *InternalHostHandler) VMList(c *web.Context) error { + id := c.Request().URL.Query().Get("id") + if id == "" { + return fmt.Errorf("id parameter is required") + } + + vm, err := h.repo.GetVirtualMachine(c.Request().Context(), id) + if err != nil { + h.logger.ErrorContext(c.Request().Context(), "get virtual machine failed", "id", id, "error", err) + return err + } + + result := &taskflow.VirtualMachine{ + ID: vm.ID, + HostID: vm.HostID, + Hostname: vm.Hostname, + OS: vm.Os, + Arch: vm.Arch, + Cores: int32(vm.Cores), + Memory: uint64(vm.Memory), + Version: vm.Version, + Status: taskflow.VirtualMachineStatusOffline, + CreatedAt: vm.CreatedAt.Unix(), + } + + if vm.EnvironmentID != "" { + result.EnvironmentID = vm.EnvironmentID + } + + return c.Success(result) +} + +// CheckToken 认证 token +func (h *InternalHostHandler) CheckToken(c *web.Context, req taskflow.CheckTokenReq) error { + logger := h.logger.With("fn", "CheckToken", "req", req) + var tk *taskflow.Token + var err error + if strings.HasPrefix(req.Token, "agent_") { + tk, err = h.agentAuth(c.Request().Context(), req.Token, req.MachineID) + } else { + tk, err = h.hostAuth(c.Request().Context(), req.Token, req.MachineID) + } + + if err != nil { + logger.With("error", err).ErrorContext(c.Request().Context(), "failed to check token") + return err + } + + logger.With("token", tk).DebugContext(c.Request().Context(), "check token success") + + return c.Success(tk) +} + +func (h *InternalHostHandler) agentAuth(ctx context.Context, token, mid string) (*taskflow.Token, error) { + // 1) 优先从 Redis 读取一次性 agent token,并清除 + key := fmt.Sprintf("agent:token:%s", token) + luaGetDel := ` +local v = redis.call('GET', KEYS[1]) +if v then + redis.call('DEL', KEYS[1]) + return v +end +return nil +` + res, err := h.redis.Eval(ctx, luaGetDel, []string{key}).Result() + h.logger.With("mid", mid, "key", key, "res", res, "error", err).DebugContext(ctx, "agent auth...") + if err == nil { + if b, ok := res.(string); ok && b != "" { + var t taskflow.Token + if uerr := json.Unmarshal([]byte(b), &t); uerr != nil { + h.logger.With("error", uerr, "token", token).ErrorContext(ctx, "failed to unmarshal token from redis") + return nil, uerr + } + + if mid != "" { + if err := h.repo.UpdateVirtualMachine(ctx, token, func(up *db.VirtualMachineUpdateOne) error { + up.SetMachineID(mid) + return nil + }); err != nil { + h.logger.With("error", err, "token", token).ErrorContext(ctx, "failed to update virtual machine machine id") + return nil, err + } + } + + return &t, nil + } + } else if !errors.Is(err, redis.Nil) { + h.logger.With("error", err, "token", token).ErrorContext(ctx, "failed to get redis token via lua, fallback to db") + } + + // 2) Redis 没值时根据数据库校验 token + vm, err := h.repo.GetVirtualMachine(ctx, token) + if err != nil { + return nil, err + } + + // 机器码绑定校验 + if mid != "" && vm.MachineID != "" && vm.MachineID != mid { + return nil, fmt.Errorf("mismatch machine id") + } + + if vm.IsRecycled { + return nil, fmt.Errorf("vm is recycled") + } + + if vm.Edges.Host == nil { + return nil, fmt.Errorf("no host found for vm") + } + + // 通过 hook 获取关联的 TaskID(内部项目注入时生效) + taskID := uuid.Nil + if h.hook != nil { + taskID = h.hook.OnAgentAuth(ctx, vm.ID) + } + + return &taskflow.Token{ + Kind: taskflow.AgentToken, + User: &taskflow.TokenUser{ + ID: vm.UserID.String(), + }, + ParentToken: vm.HostID, + Token: token, + TaskID: taskID, + }, nil +} + +func (h *InternalHostHandler) hostAuth(ctx context.Context, token, mid string) (*taskflow.Token, error) { + // 1) 优先从 Redis 读取一次性 host token,并清除(原子) + key := fmt.Sprintf("host:token:%s", token) + luaGetDel := ` +local v = redis.call('GET', KEYS[1]) +if v then + redis.call('DEL', KEYS[1]) + return v +end +return nil +` + res, err := h.redis.Eval(ctx, luaGetDel, []string{key}).Result() + if err == nil { + if b, ok := res.(string); ok && b != "" { + var u domain.User + if uerr := json.Unmarshal([]byte(b), &u); uerr != nil { + h.logger.With("error", uerr, "token", token).ErrorContext(ctx, "failed to unmarshal user from redis token") + return nil, uerr + } + h.logger.With("cache result", b, "user", u).DebugContext(ctx, "get result from redis by lua") + + typeUser := &taskflow.TokenUser{ + ID: u.ID.String(), + Name: u.Name, + AvatarURL: u.AvatarURL, + Email: u.Email, + } + if u.Team != nil { + typeUser.Team = &taskflow.TokenTeam{ + ID: u.Team.ID.String(), + Name: u.Name, + } + } + tk := &taskflow.Token{ + Kind: taskflow.OrchestratorToken, + Token: token, + User: typeUser, + } + + // 持久化宿主机与用户的映射 + if u.Team == nil { + if err := h.repo.UpsertHost(context.Background(), &taskflow.Host{ + ID: token, + UserID: u.ID.String(), + }); err != nil { + return nil, err + } + } else { + h.logger.With("team", u.Team, "user", u.ID).DebugContext(ctx, "upsert host to team") + if err := h.teamRepo.UpsertHost(context.Background(), &u, &taskflow.Host{ + ID: token, + UserID: u.ID.String(), + }); err != nil { + return nil, err + } + } + + return tk, nil + } + } else if !errors.Is(err, redis.Nil) { + h.logger.With("error", err, "token", token).ErrorContext(ctx, "failed to get redis host token via lua, fallback to db") + } + + // 2) Redis 无值则回退到数据库校验 + host, err := h.repo.GetByID(ctx, token) + if err != nil { + return nil, err + } + if mid != "" && host.MachineID != "" && mid != host.MachineID { + return nil, fmt.Errorf("mismatch machine id") + } + + return &taskflow.Token{ + Kind: taskflow.OrchestratorToken, + User: &taskflow.TokenUser{ + ID: host.UserID.String(), + }, + Token: token, + }, nil +} + +// VmReady VM 就绪回调 +func (h *InternalHostHandler) VmReady(c *web.Context, req taskflow.VirtualMachine) error { + h.logger.With("req", req).DebugContext(c.Request().Context(), "recv vm ready req") + + if h.hook != nil { + if err := h.hook.OnVmReady(c.Request().Context(), req.ID); err != nil { + return err + } + } + + return c.Success(nil) +} + +// VmConditions VM 条件更新回调 +func (h *InternalHostHandler) VmConditions(c *web.Context, req taskflow.VirtualMachineCondition) error { + if len(req.Conditions) == 0 { + return nil + } + + last := req.Conditions[len(req.Conditions)-1] + + key := fmt.Sprintf("conditions:%s.%s.%d.%d", req.EnvID, last.Type, last.Status, last.LastTransitionTime) + if _, ok := h.cache.Get(key); ok { + h.logger.DebugContext(c.Request().Context(), "hit cached conditions", "key", key) + return nil + } + + vm, err := h.repo.GetVirtualMachineByEnvID(c.Request().Context(), req.EnvID) + if err != nil { + return err + } + + // 条件失败时通过 hook 通知内部项目(任务状态转换等) + if h.hook != nil { + for _, cond := range req.Conditions { + if cond.Type == string(etypes.ConditionTypeFailed) { + if err := h.hook.OnVmConditionFailed(c.Request().Context(), vm.ID); err != nil { + h.logger.With("error", err).ErrorContext(c.Request().Context(), "hook OnVmConditionFailed failed") + } + break + } + } + } + + conds := cvt.From(&req, &etypes.VirtualMachineCondition{}) + h.logger.With("req", req, "conds", conds).DebugContext(c.Request().Context(), "recv vm conditions req") + if err := h.repo.UpdateVirtualMachine(c.Request().Context(), vm.ID, func(vmuo *db.VirtualMachineUpdateOne) error { + vmuo.SetConditions(conds) + return nil + }); err != nil { + h.logger.With("vm", vm, "error", err).ErrorContext(c.Request().Context(), "update vm conditions failed") + return err + } + + h.cache.Set(key, true, 15*time.Minute) + + return c.Success(nil) +} + +// GitCredential 获取 git 凭证 +func (h *InternalHostHandler) GitCredential(c *web.Context, req taskflow.GitCredentialRequest) error { + if h.hook == nil { + errMsg := "git credential not supported" + return c.Success(taskflow.GitCredentialResponse{Error: &errMsg}) + } + + resp, err := h.hook.GitCredential(c.Request().Context(), &req) + if err != nil { + errMsg := fmt.Sprintf("failed to get git credential: %v", err) + return c.Success(taskflow.GitCredentialResponse{Error: &errMsg}) + } + return c.Success(resp) +} diff --git a/backend/biz/host/register.go b/backend/biz/host/register.go new file mode 100644 index 00000000..84a36545 --- /dev/null +++ b/backend/biz/host/register.go @@ -0,0 +1,26 @@ +package host + +import ( + "github.com/samber/do" + + v1 "github.com/chaitin/MonkeyCode/backend/biz/host/handler/v1" + "github.com/chaitin/MonkeyCode/backend/biz/host/repo" + "github.com/chaitin/MonkeyCode/backend/biz/host/usecase" +) + +// RegisterHost 注册 host 模块 +func RegisterHost(i *do.Injector) { + // Repo + do.Provide(i, repo.NewHostRepo) + + // Usecase + do.Provide(i, usecase.NewHostUsecase) + + // Handler + do.Provide(i, v1.NewHostHandler) + do.MustInvoke[*v1.HostHandler](i) + + // Internal handler(taskflow 回调) + do.Provide(i, v1.NewInternalHostHandler) + do.MustInvoke[*v1.InternalHostHandler](i) +} diff --git a/backend/biz/host/repo/host.go b/backend/biz/host/repo/host.go new file mode 100644 index 00000000..52271bac --- /dev/null +++ b/backend/biz/host/repo/host.go @@ -0,0 +1,553 @@ +package repo + +import ( + "context" + "fmt" + "log/slog" + "strings" + "time" + + "entgo.io/ent/dialect/sql" + "github.com/google/uuid" + "github.com/patrickmn/go-cache" + "github.com/redis/go-redis/v9" + "github.com/samber/do" + + "github.com/chaitin/MonkeyCode/backend/config" + "github.com/chaitin/MonkeyCode/backend/consts" + "github.com/chaitin/MonkeyCode/backend/db" + "github.com/chaitin/MonkeyCode/backend/db/host" + "github.com/chaitin/MonkeyCode/backend/db/model" + "github.com/chaitin/MonkeyCode/backend/db/predicate" + "github.com/chaitin/MonkeyCode/backend/db/teamgroup" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/db/virtualmachine" + "github.com/chaitin/MonkeyCode/backend/domain" + "github.com/chaitin/MonkeyCode/backend/errcode" + "github.com/chaitin/MonkeyCode/backend/pkg/cvt" + "github.com/chaitin/MonkeyCode/backend/pkg/entx" + "github.com/chaitin/MonkeyCode/backend/pkg/taskflow" +) + +type HostRepo struct { + db *db.Client + cache *cache.Cache + logger *slog.Logger + cfg *config.Config + redis *redis.Client +} + +func NewHostRepo(i *do.Injector) (domain.HostRepo, error) { + return &HostRepo{ + db: do.MustInvoke[*db.Client](i), + cfg: do.MustInvoke[*config.Config](i), + cache: cache.New(15*time.Minute, 10*time.Minute), + logger: do.MustInvoke[*slog.Logger](i).With("module", "repo.HostRepo"), + redis: do.MustInvoke[*redis.Client](i), + }, nil +} + +func hostWithUserPredicate(uid uuid.UUID) predicate.Host { + return host.Or( + host.UserID(uid), + host.HasGroupsWith(teamgroup.HasMembersWith(user.ID(uid))), + host.HasUserWith(user.Role(consts.UserRoleAdmin)), + ) +} + +// List implements domain.HostRepo. +func (h *HostRepo) List(ctx context.Context, uid uuid.UUID) ([]*db.Host, error) { + return h.db.Host.Query(). + WithVms(func(vmq *db.VirtualMachineQuery) { + vmq.WithUser(). + Where(virtualmachine.UserID(uid)). + Order(virtualmachine.ByCreatedAt(sql.OrderDesc())) + }). + WithUser(). + WithGroups(func(tgq *db.TeamGroupQuery) { + tgq.WithTeam() + }). + Where(hostWithUserPredicate(uid)). + Order(host.ByCreatedAt(sql.OrderDesc())). + All(ctx) +} + +// GetHost implements domain.HostRepo. +func (h *HostRepo) GetHost(ctx context.Context, uid uuid.UUID, id string) (*domain.Host, error) { + dbHost, err := h.db.Host.Query(). + Where(hostWithUserPredicate(uid)). + Where(host.ID(id)). + First(ctx) + if err != nil { + return nil, err + } + return cvt.From(dbHost, &domain.Host{}), nil +} + +// UpsertVirtualMachine implements domain.HostRepo. +func (h *HostRepo) UpsertVirtualMachine(ctx context.Context, vm *taskflow.VirtualMachine) error { + if vm == nil { + return nil + } + + if old, ok := h.cache.Get(vm.ID); ok { + if oldInfo, ok := old.(*taskflow.VirtualMachine); ok { + if oldInfo.Arch == vm.Arch && + oldInfo.Cores == vm.Cores && + oldInfo.OS == vm.OS && + oldInfo.Hostname == vm.Hostname && + oldInfo.Memory == uint64(vm.Memory) && + oldInfo.Version == vm.Version { + return nil + } + } + } + + return entx.WithTx2(ctx, h.db, func(tx *db.Tx) error { + if oldVm, err := tx.VirtualMachine.Query(). + ForUpdate(). + Where(virtualmachine.ID(vm.ID)). + First(ctx); err == nil { + if err := tx.VirtualMachine.UpdateOneID(vm.ID). + SetArch(vm.Arch). + SetCores(int(vm.Cores)). + SetHostname(vm.Hostname). + SetOs(vm.OS). + SetMemory(int64(vm.Memory)). + SetVersion(vm.Version). + Exec(ctx); err != nil { + return err + } + vm.EnvironmentID = oldVm.EnvironmentID + h.cache.Set(vm.ID, vm, 10*time.Minute) + return nil + } + return nil + }) +} + +// UpsertHost implements domain.HostRepo. +func (h *HostRepo) UpsertHost(ctx context.Context, info *taskflow.Host) error { + if info == nil || strings.HasPrefix(info.ID, "agent_") { + return nil + } + uid, err := uuid.Parse(info.UserID) + if err != nil { + return fmt.Errorf("invalid user id %s", err) + } + + if old, ok := h.cache.Get(info.ID); ok { + if oldInfo, ok := old.(*domain.Host); ok { + if oldInfo.Arch == info.Arch && + oldInfo.Cores == int(info.Cores) && + oldInfo.Name == info.Hostname && + oldInfo.ExternalIP == info.PublicIP && + oldInfo.OS == info.OS && + oldInfo.Memory == uint64(info.Memory) && + oldInfo.Version == info.Version { + return nil + } + } + } + + return entx.WithTx2(ctx, h.db, func(tx *db.Tx) error { + if _, err := tx.Host.Query().Where(host.ID(info.ID)).First(ctx); err == nil { + if err := tx.Host.UpdateOneID(info.ID). + SetArch(info.Arch). + SetCores(int(info.Cores)). + SetOs(info.OS). + SetHostname(info.Hostname). + SetMemory(int64(info.Memory)). + SetExternalIP(info.PublicIP). + SetInternalIP(info.InternalIP). + SetHostname(info.Hostname). + SetVersion(info.Version). + Exec(ctx); err != nil { + return err + } + + h.cache.Set(info.ID, &domain.Host{ + ID: info.ID, + Arch: info.Arch, + Cores: int(info.Cores), + OS: info.OS, + Memory: info.Memory, + Name: info.Hostname, + ExternalIP: info.PublicIP, + Version: info.Version, + }, 10*time.Minute) + + return nil + } + + if err := tx.Host.Create(). + SetID(info.ID). + SetUserID(uid). + SetArch(info.Arch). + SetCores(int(info.Cores)). + SetOs(info.OS). + SetHostname(info.Hostname). + SetMemory(int64(info.Memory)). + SetExternalIP(info.PublicIP). + SetInternalIP(info.InternalIP). + SetHostname(info.Hostname). + Exec(ctx); err != nil { + return err + } + + h.cache.Set(info.ID, &domain.Host{ + ID: info.ID, + Arch: info.Arch, + OS: info.OS, + Cores: int(info.Cores), + Memory: info.Memory, + Name: info.Hostname, + ExternalIP: info.PublicIP, + }, 10*time.Minute) + + return nil + }) +} + +// GetVirtualMachineWithUser implements domain.HostRepo. +func (h *HostRepo) GetVirtualMachineWithUser(ctx context.Context, uid uuid.UUID, id string) (*db.VirtualMachine, error) { + vm, err := h.db.VirtualMachine.Query(). + ForUpdate(). + WithHost(). + WithModel(). + WithUser(). + Where(virtualmachine.HasHostWith(hostWithUserPredicate(uid))). + Where(virtualmachine.UserID(uid)). + Where(virtualmachine.ID(id)). + First(ctx) + if err != nil { + return nil, err + } + + return vm, nil +} + +// GetVirtualMachine implements domain.HostRepo. +func (h *HostRepo) GetVirtualMachine(ctx context.Context, id string) (*db.VirtualMachine, error) { + vm, err := h.db.VirtualMachine.Query(). + ForUpdate(). + WithHost(). + WithModel(). + WithUser(). + Where(virtualmachine.ID(id)). + First(ctx) + if err != nil { + return nil, err + } + + return vm, nil +} + +// GetByID implements domain.HostRepo. +func (h *HostRepo) GetByID(ctx context.Context, id string) (*db.Host, error) { + dbHost, err := h.db.Host.Query(). + Where(host.ID(id)). + First(ctx) + if err != nil { + return nil, err + } + return dbHost, nil +} + +// DeleteHost implements domain.HostRepo. +func (h *HostRepo) DeleteHost(ctx context.Context, uid uuid.UUID, id string) error { + _, err := h.db.Host.Query(). + Where(host.UserID(uid)). + Where(host.ID(id)). + First(ctx) + if err != nil { + return errcode.ErrPermision.Wrap(err) + } + + _, err = h.db.Host.Delete(). + Where(host.UserID(uid)). + Where(host.ID(id)). + Exec(ctx) + if err != nil { + return errcode.ErrDatabaseOperation.Wrap(err) + } + + return nil +} + +// CreateVirtualMachine implements domain.HostRepo. +func (h *HostRepo) CreateVirtualMachine(ctx context.Context, u *domain.User, req *domain.CreateVMReq, getRepoToken func(context.Context) (string, error), fn func(*db.Model, *db.Image) (*domain.VirtualMachine, error)) (*domain.VirtualMachine, error) { + var res *domain.VirtualMachine + err := entx.WithTx2(ctx, h.db, func(tx *db.Tx) error { + dbHost, err := tx.Host.Query(). + WithGroups(). + Where(hostWithUserPredicate(u.ID)). + Where(host.ID(req.HostID)). + First(ctx) + if err != nil { + return errcode.ErrPermision.Wrap(err) + } + + if len(dbHost.Edges.Groups) > 0 && (req.Life <= 0 || req.Life > 7*24*60*60) { + return errcode.ErrVmBeyondExpireTime.Wrap(fmt.Errorf("团队宿主机不支持创建永久虚拟机")) + } + + // 公共主机数量限制(仅在配置了 CountLimit 时生效) + if req.UsePublicHost && h.cfg.PublicHost.CountLimit > 0 { + cnt, err := tx.VirtualMachine.Query(). + Where(virtualmachine.UserID(u.ID)). + Where(virtualmachine.HasHostWith(host.HasUserWith(user.Role(consts.UserRoleAdmin)))). + Where(func(s *sql.Selector) { + s.Where(sql.P(func(b *sql.Builder) { + b.WriteString("NOW()"). + WriteOp(sql.OpLT). + Ident(s.C(virtualmachine.FieldCreatedAt)). + WriteOp(sql.OpAdd). + WriteString("make_interval(secs => "). + Ident(s.C(virtualmachine.FieldTTL)). + WriteByte(')') + })) + }). + Count(ctx) + if err != nil { + return errcode.ErrDatabaseOperation.Wrap(err) + } + if cnt >= h.cfg.PublicHost.CountLimit { + return errcode.ErrPublicHostBeyondLimit.Wrap(fmt.Errorf("public host limit reached: %d", h.cfg.PublicHost.CountLimit)) + } + } + + var m *db.Model + if len(req.ModelID) > 0 { + switch req.ModelID { + case "economy": + m, err = tx.Model.Query(). + WithUser(). + Where(model.HasUserWith(user.Role(consts.UserRoleAdmin))). + Where(model.Remark(req.ModelID)). + First(ctx) + if err != nil { + return err + } + default: + mid, err := uuid.Parse(req.ModelID) + if err != nil { + return err + } + m, err = tx.Model.Query().WithUser().Where(model.ID(mid)).First(ctx) + if err != nil { + return err + } + } + } + + repoURL := "" + repoFilename := "" + branch := "" + if req.RepoReq != nil { + repoURL = req.RepoReq.RepoURL + repoFilename = req.RepoReq.RepoFilename + branch = req.RepoReq.Branch + } + + image, err := tx.Image.Get(ctx, req.ImageID) + if err != nil { + return err + } + + vm, err := fn(m, image) + if err != nil { + return err + } + res = vm + + kind := consts.CountDown + if req.Life <= 0 { + kind = consts.Forever + } + + crt := tx.VirtualMachine.Create(). + SetID(vm.ID). + SetUserID(u.ID). + SetEnvironmentID(vm.EnvironmentID). + SetName(vm.Name). + SetHostID(vm.Host.ID). + SetTTLKind(kind). + SetTTL(req.Life). + SetCores(req.Resource.CPU). + SetMemory(req.Resource.Memory). + SetRepoURL(repoURL). + SetRepoFilename(repoFilename). + SetBranch(branch). + SetCreatedAt(req.Now) + + if len(req.ModelID) > 0 { + crt.SetModelID(m.ID) + } + if err := crt.Exec(ctx); err != nil { + return err + } + return nil + }) + return res, err +} + +// DeleteVirtualMachine implements domain.HostRepo. +func (h *HostRepo) DeleteVirtualMachine(ctx context.Context, uid uuid.UUID, hostID, id string, fn func(*db.VirtualMachine) error) error { + return entx.WithTx2(ctx, h.db, func(tx *db.Tx) error { + vm, err := tx.VirtualMachine.Query(). + Where(virtualmachine.ID(id)). + Where(virtualmachine.UserID(uid)). + First(ctx) + if err != nil { + return err + } + + if err := fn(vm); err != nil { + return err + } + + _, err = tx.VirtualMachine.Delete().Where(virtualmachine.ID(id)).Exec(ctx) + if err != nil { + return err + } + return nil + }) +} + +// UpdateVirtualMachine implements domain.HostRepo. +func (h *HostRepo) UpdateVirtualMachine(ctx context.Context, id string, fn func(*db.VirtualMachineUpdateOne) error) error { + return entx.WithTx2(ctx, h.db, func(tx *db.Tx) error { + old, err := tx.VirtualMachine.Get(ctx, id) + if err != nil { + return err + } + up := tx.VirtualMachine.UpdateOneID(old.ID) + if err := fn(up); err != nil { + return err + } + + return up.Exec(ctx) + }) +} + +// UpdateHost implements domain.HostRepo. +func (h *HostRepo) UpdateHost(ctx context.Context, uid uuid.UUID, req *domain.UpdateHostReq) error { + return entx.WithTx2(ctx, h.db, func(tx *db.Tx) error { + _, err := tx.Host.Query(). + Where(hostWithUserPredicate(uid)). + Where(host.ID(req.ID)). + First(ctx) + if err != nil { + return errcode.ErrPermision.Wrap(err) + } + + upt := tx.Host.Update(). + Where(host.UserID(uid)). + Where(host.ID(req.ID)) + if req.Remark != "" { + upt.SetRemark(req.Remark) + } + if req.Weight != nil { + upt.SetWeight(*req.Weight) + } + err = upt.Exec(ctx) + if err != nil { + return err + } + + // 默认主机配置 + if req.IsDefault { + u, err := tx.User.Get(ctx, uid) + if err != nil { + return err + } + defaultConfigs := u.DefaultConfigs + if defaultConfigs == nil { + defaultConfigs = make(map[consts.DefaultConfigType]uuid.UUID) + } + defaultConfigs[consts.DefaultConfigTypeHost] = uuid.MustParse(req.ID) + err = tx.User.UpdateOneID(uid). + SetDefaultConfigs(defaultConfigs). + Exec(ctx) + if err != nil { + return err + } + } + return nil + }) +} + +// PastHourVirtualMachine implements domain.HostRepo. +func (h *HostRepo) PastHourVirtualMachine(ctx context.Context) ([]*db.VirtualMachine, error) { + return h.db.VirtualMachine.Query(). + Where(virtualmachine.TTLKind(consts.CountDown)). + Where(virtualmachine.IsRecycled(false)). + Where(virtualmachine.CreatedAtGTE(time.Now().Add(-24 * time.Hour))). + All(ctx) +} + +// AllCountDownVirtualMachine implements domain.HostRepo. +func (h *HostRepo) AllCountDownVirtualMachine(ctx context.Context) ([]*db.VirtualMachine, error) { + return h.db.VirtualMachine.Query(). + Where(virtualmachine.TTLKind(consts.CountDown)). + Where(virtualmachine.IsRecycled(false)). + All(ctx) +} + +// UpdateVM implements domain.HostRepo. +func (h *HostRepo) UpdateVM(ctx context.Context, req domain.UpdateVMReq, fn func(*db.VirtualMachine) error) (*db.VirtualMachine, int64, error) { + var res *db.VirtualMachine + actualLife := req.Life + err := entx.WithTx2(ctx, h.db, func(tx *db.Tx) error { + vm, err := tx.VirtualMachine.Query(). + WithHost(func(hq *db.HostQuery) { + hq.WithUser() + }). + Where(virtualmachine.ID(req.ID)). + Where(virtualmachine.UserID(req.UID)). + First(ctx) + if err != nil { + return errcode.ErrDatabaseOperation.Wrap(err) + } + + // 公共主机 TTL 续期上限(仅在配置了 TTLLimit 时生效) + if req.Life > 0 && h.cfg.PublicHost.TTLLimit > 0 { + if vm.Edges.Host != nil && vm.Edges.Host.Edges.User != nil && + vm.Edges.Host.Edges.User.Role == consts.UserRoleAdmin { + now := time.Now() + expiredAt := vm.CreatedAt.Add(time.Duration(vm.TTL) * time.Second) + remaining := max(int64(expiredAt.Sub(now).Seconds()), 0) + maxAdditional := max(h.cfg.PublicHost.TTLLimit-remaining, 0) + actualLife = min(req.Life, maxAdditional) + } + } + + res = vm + if vm.TTLKind == consts.Forever { + return nil + } + + expiredAt := vm.CreatedAt.Add(time.Duration(vm.TTL) * time.Second) + if expiredAt.Before(time.Now()) { + return errcode.ErrVMExpired + } + + vm, err = tx.VirtualMachine.UpdateOneID(vm.ID). + AddTTL(actualLife). + Save(ctx) + if err != nil { + return errcode.ErrDatabaseOperation.Wrap(err) + } + res = vm + return fn(vm) + }) + return res, actualLife, err +} + +// GetVirtualMachineByEnvID implements domain.HostRepo. +func (h *HostRepo) GetVirtualMachineByEnvID(ctx context.Context, envID string) (*db.VirtualMachine, error) { + return h.db.VirtualMachine.Query(). + Where(virtualmachine.EnvironmentID(envID)). + First(ctx) +} diff --git a/backend/biz/host/repo/publichost.go b/backend/biz/host/repo/publichost.go new file mode 100644 index 00000000..fbd7e3cb --- /dev/null +++ b/backend/biz/host/repo/publichost.go @@ -0,0 +1,40 @@ +package repo + +import ( + "context" + + "github.com/samber/do" + + "github.com/chaitin/MonkeyCode/backend/consts" + "github.com/chaitin/MonkeyCode/backend/db" + "github.com/chaitin/MonkeyCode/backend/db/user" + "github.com/chaitin/MonkeyCode/backend/domain" +) + +type PublicHostRepo struct { + db *db.Client +} + +func NewPublicHostRepo(i *do.Injector) (domain.PublicHostRepo, error) { + return &PublicHostRepo{ + db: do.MustInvoke[*db.Client](i), + }, nil +} + +// All implements domain.PublicHostRepo. +func (p *PublicHostRepo) All(ctx context.Context) ([]*db.Host, error) { + us, err := p.db.User.Query(). + WithHosts(). + Where(user.Role(consts.UserRoleAdmin)). + All(ctx) + if err != nil { + return nil, err + } + hs := make([]*db.Host, 0) + for _, u := range us { + for _, h := range u.Edges.Hosts { + hs = append(hs, h) + } + } + return hs, nil +} diff --git a/backend/biz/host/usecase/host.go b/backend/biz/host/usecase/host.go new file mode 100644 index 00000000..b28f6c41 --- /dev/null +++ b/backend/biz/host/usecase/host.go @@ -0,0 +1,728 @@ +package usecase + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "html/template" + "log/slog" + "net/url" + "sort" + "strconv" + "time" + + "github.com/google/uuid" + "github.com/redis/go-redis/v9" + "github.com/samber/do" + + "github.com/chaitin/MonkeyCode/backend/config" + "github.com/chaitin/MonkeyCode/backend/consts" + "github.com/chaitin/MonkeyCode/backend/db" + "github.com/chaitin/MonkeyCode/backend/domain" + "github.com/chaitin/MonkeyCode/backend/errcode" + "github.com/chaitin/MonkeyCode/backend/pkg/cvt" + "github.com/chaitin/MonkeyCode/backend/pkg/delayqueue" + "github.com/chaitin/MonkeyCode/backend/pkg/entx" + "github.com/chaitin/MonkeyCode/backend/pkg/random" + "github.com/chaitin/MonkeyCode/backend/pkg/taskflow" + "github.com/chaitin/MonkeyCode/backend/templates" +) + +type HostUsecase struct { + cfg *config.Config + redis *redis.Client + taskflow taskflow.Clienter + logger *slog.Logger + repo domain.HostRepo + userRepo domain.UserRepo + vmexpireQueue *delayqueue.VMExpireQueue + privilegeChecker domain.PrivilegeChecker // 可选,由内部项目通过 WithPrivilegeChecker 注入 +} + +func NewHostUsecase(i *do.Injector) (domain.HostUsecase, error) { + h := &HostUsecase{ + cfg: do.MustInvoke[*config.Config](i), + redis: do.MustInvoke[*redis.Client](i), + taskflow: do.MustInvoke[taskflow.Clienter](i), + logger: do.MustInvoke[*slog.Logger](i).With("module", "HostUsecase"), + repo: do.MustInvoke[domain.HostRepo](i), + userRepo: do.MustInvoke[domain.UserRepo](i), + vmexpireQueue: do.MustInvoke[*delayqueue.VMExpireQueue](i), + } + + // 可选注入 PrivilegeChecker + if pc, err := do.Invoke[domain.PrivilegeChecker](i); err == nil { + h.privilegeChecker = pc + } + + go h.periodicEnqueueVm() + go h.vmexpireConsumer() + return h, nil +} + +func (h *HostUsecase) periodicEnqueueVm() { + t := time.NewTicker(10 * time.Minute) + for range t.C { + vms, err := h.repo.PastHourVirtualMachine(context.Background()) + if err != nil { + h.logger.With("error", err).Error("failed to list need expire virtualmachine") + return + } + + for _, vm := range vms { + if vm.TTL <= 0 { + continue + } + + if _, err := h.vmexpireQueue.Enqueue(context.Background(), consts.VM_EXPIRE_QUEUE_KEY, &domain.VmExpireInfo{ + UID: vm.UserID, + VmID: vm.ID, + HostID: vm.HostID, + EnvID: vm.EnvironmentID, + }, vm.CreatedAt.Add(time.Duration(vm.TTL)*time.Second), vm.ID); err != nil { + h.logger.With("error", err, "vm", vm).Error("failed to enqueue vm") + } + } + } +} + +func (h *HostUsecase) vmexpireConsumer() { + logger := h.logger.With("fn", "vmexpireConsumer") + index := 1 + for { + err := h.vmexpireQueue.StartConsumer(context.Background(), consts.VM_EXPIRE_QUEUE_KEY, func(ctx context.Context, job *delayqueue.Job[*domain.VmExpireInfo]) error { + innerLogger := logger.With("job", job) + innerLogger.InfoContext(ctx, "received expired virtualmachine") + + ctx = entx.SkipSoftDelete(ctx) + vm, err := h.repo.GetVirtualMachine(ctx, job.Payload.VmID) + if err != nil { + innerLogger.ErrorContext(ctx, "failed to get vm", "error", err) + return nil + } + + if err := h.taskflow.VirtualMachiner().Delete(ctx, &taskflow.DeleteVirtualMachineReq{ + UserID: vm.UserID.String(), + HostID: vm.HostID, + ID: vm.EnvironmentID, + }); err != nil { + innerLogger.ErrorContext(ctx, "failed to delete vm", "error", err) + } + + if err := h.repo.UpdateVirtualMachine(ctx, vm.ID, func(vmuo *db.VirtualMachineUpdateOne) error { + vmuo.SetIsRecycled(true) + return nil + }); err != nil { + innerLogger.ErrorContext(ctx, "failed to update vm", "error", err) + return err + } + + return nil + }) + + h.logger.With("error", err, "index", index).WarnContext(context.Background(), "start consumer error retrying...") + index++ + time.Sleep(10 * time.Second) + } +} + +// GetInstallCommand implements domain.HostUsecase. +func (h *HostUsecase) GetInstallCommand(ctx context.Context, user *domain.User) (string, error) { + token := uuid.NewString() + ub, err := json.Marshal(user) + if err != nil { + return "", err + } + key := fmt.Sprintf("host:token:%s", token) + if err := h.redis.Set(ctx, key, string(ub), 15*time.Minute).Err(); err != nil { + return "", err + } + + baseurl, err := url.Parse(h.cfg.Server.BaseURL) + if err != nil { + return "", fmt.Errorf("failed to parse baseurl [%s]", h.cfg.Server.BaseURL) + } + baseurl = baseurl.JoinPath("/api/v1/users/hosts/install") + values := url.Values{} + values.Add("token", token) + baseurl.RawQuery = values.Encode() + + return fmt.Sprintf(`bash -c "$(curl -fsSL '%s')"`, baseurl.String()), nil +} + +// InstallScript implements domain.HostUsecase. +func (h *HostUsecase) InstallScript(ctx context.Context, token *domain.InstallReq) (string, error) { + key := fmt.Sprintf("host:token:%s", token.Token) + if _, err := h.redis.Get(ctx, key).Result(); err != nil { + return "", errcode.ErrInvalidInstallToken + } + + tmp, err := template.New("install").Parse(string(templates.InstallTmpl)) + if err != nil { + return "", fmt.Errorf("failed to parse template %s", err) + } + buf := bytes.NewBuffer([]byte("")) + param := map[string]any{ + "token": token.Token, + "grpc_host": h.cfg.TaskFlow.GrpcHost, + "grpc_port": h.cfg.TaskFlow.GrpcPort, + "grpc_url": h.cfg.TaskFlow.GrpcURL, + } + if err := tmp.Execute(buf, param); err != nil { + return "", fmt.Errorf("failed to execute template %s", err) + } + return buf.String(), nil +} + +// List implements domain.HostUsecase. +func (h *HostUsecase) List(ctx context.Context, uid uuid.UUID) (*domain.HostListResp, error) { + user, err := h.userRepo.Get(ctx, uid) + if err != nil { + return nil, errcode.ErrDatabaseQuery.Wrap(err) + } + + hs, err := h.repo.List(ctx, uid) + if err != nil { + return &domain.HostListResp{}, err + } + + m, err := h.taskflow.Host().IsOnline(ctx, &taskflow.IsOnlineReq[string]{ + IDs: cvt.Iter(hs, func(_ int, host *db.Host) string { + return host.ID + }), + }) + if err != nil { + return nil, err + } + vmids := make([]string, 0) + for _, host := range hs { + for _, vm := range host.Edges.Vms { + vmids = append(vmids, vm.ID) + } + } + + vmonline, err := h.taskflow.VirtualMachiner().IsOnline(ctx, &taskflow.IsOnlineReq[string]{ + IDs: vmids, + }) + if err != nil { + return nil, err + } + + resp := &domain.HostListResp{} + for _, host := range hs { + status := consts.HostStatusOffline + if m.OnlineMap[host.ID] { + status = consts.HostStatusOnline + } + dHost := cvt.From(host, &domain.Host{Status: status}) + dHost.IsDefault = dHost.GetIsDefault(user) + dHost.VirtualMachines = cvt.Iter(host.Edges.Vms, func(_ int, vm *db.VirtualMachine) *domain.VirtualMachine { + status := taskflow.VirtualMachineStatusOffline + if vmonline.OnlineMap[vm.ID] { + status = taskflow.VirtualMachineStatusOnline + } + return cvt.From(vm, &domain.VirtualMachine{ + Status: status, + }) + }) + + resp.Hosts = append(resp.Hosts, dHost) + } + + return resp, nil +} + +// TerminalList implements domain.HostUsecase. +func (h *HostUsecase) TerminalList(ctx context.Context, id string) ([]*domain.Terminal, error) { + ts, err := h.taskflow.VirtualMachiner().TerminalList(ctx, id) + if err != nil { + return nil, err + } + return cvt.Iter(ts, func(_ int, t *taskflow.Terminal) *domain.Terminal { + return cvt.From(t, &domain.Terminal{}) + }), nil +} + +// CloseTerminal implements domain.HostUsecase. +func (h *HostUsecase) CloseTerminal(ctx context.Context, id string, terminalID string) error { + return h.taskflow.VirtualMachiner().CloseTerminal(ctx, &taskflow.CloseTerminalReq{ + ID: id, + TerminalID: terminalID, + }) +} + +// ConnectVMTerminal 连接到虚拟机终端 +func (h *HostUsecase) ConnectVMTerminal(ctx context.Context, uid uuid.UUID, req domain.TerminalReq) (taskflow.Sheller, error) { + return h.taskflow.VirtualMachiner().Terminal(ctx, &taskflow.TerminalReq{ + ID: req.ID, + TerminalID: req.TerminalID, + Exec: req.Exec, + TerminalSize: taskflow.TerminalSize{ + Col: uint32(req.Col), + Row: uint32(req.Row), + }, + }) +} + +// isPrivileged 检查用户是否为特权用户(仅在注入 PrivilegeChecker 时生效) +func (h *HostUsecase) isPrivileged(ctx context.Context, uid uuid.UUID) bool { + if h.privilegeChecker == nil { + return false + } + ok, err := h.privilegeChecker.IsPrivileged(ctx, uid) + if err != nil { + h.logger.ErrorContext(ctx, "failed to check privilege", "error", err, "uid", uid) + return false + } + return ok +} + +// WithVMPermission implements domain.HostUsecase. +func (h *HostUsecase) WithVMPermission(ctx context.Context, uid uuid.UUID, id string, fn func(*domain.VirtualMachine) error) error { + var ( + vm *db.VirtualMachine + err error + ) + + if h.isPrivileged(ctx, uid) { + vm, err = h.repo.GetVirtualMachine(ctx, id) + } else { + vm, err = h.repo.GetVirtualMachineWithUser(ctx, uid, id) + } + if err != nil { + return err + } + + return fn(cvt.From(vm, &domain.VirtualMachine{})) +} + +// CreateVM 创建虚拟机 +func (h *HostUsecase) CreateVM(ctx context.Context, user *domain.User, req *domain.CreateVMReq) (*domain.VirtualMachine, error) { + resp, err := h.taskflow.Host().IsOnline(ctx, &taskflow.IsOnlineReq[string]{ + IDs: []string{req.HostID}, + }) + if err != nil { + return nil, errcode.ErrHostOffline.Wrap(err) + } + if !resp.OnlineMap[req.HostID] { + return nil, errcode.ErrHostOffline + } + + req.Now = time.Now() + vm, err := h.repo.CreateVirtualMachine(ctx, user, req, nil, func(model *db.Model, image *db.Image) (*domain.VirtualMachine, error) { + kind := taskflow.TTLCountDown + if req.Life == 0 { + kind = taskflow.TTLForever + } + + h.logger.InfoContext(ctx, "create vm", "req", req, "kind", kind, "seconds", req.Life) + + temperature := new(float32) + var LLMConfig taskflow.LLMProviderReq + if model != nil { + LLMConfig = taskflow.LLMProviderReq{ + Provider: taskflow.LlmProviderOpenAI, + ApiKey: model.APIKey, + Model: model.Model, + Temperature: temperature, + BaseURL: model.BaseURL, + } + } + + repoURL := "" + branch := "" + zipURL := "" + if req.RepoReq != nil { + repoURL = req.RepoReq.RepoURL + branch = req.RepoReq.Branch + zipURL = req.RepoReq.ZipURL + } + + git := taskflow.Git{ + URL: repoURL, + Branch: branch, + } + + tfvm, err := h.taskflow.VirtualMachiner().Create( + ctx, + &taskflow.CreateVirtualMachineReq{ + UserID: user.ID.String(), + HostID: req.HostID, + Git: git, + ZipUrl: zipURL, + ProxyURL: "", + ImageURL: image.Name, + TTL: taskflow.TTL{ + Kind: kind, + Seconds: req.Life, + }, + LLM: LLMConfig, + Cores: strconv.Itoa(req.Resource.CPU), + Memory: uint64(req.Resource.Memory), + InstallCodingAgents: req.InstallCodingAgents, + }) + if err != nil { + h.logger.ErrorContext(ctx, "failed to create vm", "error", err) + return nil, err + } + if tfvm == nil { + return nil, fmt.Errorf("failed to create vm, vm is nil") + } + + h.logger.InfoContext(ctx, "create vm success", "vm", tfvm) + + if req.Life > 0 { + if _, err := h.vmexpireQueue.Enqueue(ctx, consts.VM_EXPIRE_QUEUE_KEY, &domain.VmExpireInfo{ + UID: user.ID, + VmID: tfvm.ID, + HostID: req.HostID, + EnvID: tfvm.EnvironmentID, + }, time.Now().Add(time.Duration(req.Life)*time.Second), tfvm.ID); err != nil { + h.logger.With("error", err, "vm", tfvm).ErrorContext(ctx, "failed to enqueue countdown vm") + } + } + + return &domain.VirtualMachine{ + ID: tfvm.ID, + EnvironmentID: tfvm.EnvironmentID, + Name: req.Name, + Host: &domain.Host{ + ID: req.HostID, + }, + LifeTimeSeconds: req.Life, + }, nil + }) + if err != nil { + return nil, err + } + if vm == nil { + return nil, fmt.Errorf("failed to create vm") + } + + return vm, nil +} + +// DeleteVM 删除虚拟机 +func (h *HostUsecase) DeleteVM(ctx context.Context, uid uuid.UUID, hostID, vmID string) error { + h.logger.InfoContext(ctx, "delete vm", "vmID", vmID) + return h.repo.DeleteVirtualMachine(ctx, uid, hostID, vmID, func(vm *db.VirtualMachine) error { + if err := h.taskflow.VirtualMachiner().Delete(ctx, &taskflow.DeleteVirtualMachineReq{ + UserID: uid.String(), + HostID: vm.HostID, + ID: vm.EnvironmentID, + }); err != nil { + h.logger.ErrorContext(ctx, "failed to delete vm", "error", err) + } + + // 清理延迟队列中的残留任务 + _ = h.vmexpireQueue.Remove(ctx, consts.VM_EXPIRE_QUEUE_KEY, vm.ID) + + return nil + }) +} + +// VMInfo implements domain.HostUsecase. +func (h *HostUsecase) VMInfo(ctx context.Context, uid uuid.UUID, id string) (*domain.VirtualMachine, error) { + var ( + vm *db.VirtualMachine + err error + ) + + if h.isPrivileged(ctx, uid) { + vm, err = h.repo.GetVirtualMachine(ctx, id) + } else { + vm, err = h.repo.GetVirtualMachineWithUser(ctx, uid, id) + } + if err != nil { + return nil, errcode.ErrDatabaseQuery.Wrap(err) + } + + vmonline, err := h.taskflow.VirtualMachiner().IsOnline(ctx, &taskflow.IsOnlineReq[string]{ + IDs: []string{vm.ID}, + }) + if err != nil { + return nil, err + } + + m, err := h.taskflow.Host().IsOnline(ctx, &taskflow.IsOnlineReq[string]{ + IDs: []string{vm.HostID}, + }) + if err != nil { + return nil, err + } + + status := taskflow.VirtualMachineStatusOffline + if vmonline.OnlineMap[vm.ID] { + status = taskflow.VirtualMachineStatusOnline + } + dvm := cvt.From(vm, &domain.VirtualMachine{ + Status: status, + }) + + if dvm.Host != nil { + dvm.Host.Status = consts.HostStatusOffline + if m.OnlineMap[dvm.Host.ID] { + dvm.Host.Status = consts.HostStatusOnline + } + } + + ports, err := h.GetPorts(ctx, vm.ID) + if err != nil { + return nil, err + } + dvm.Ports = ports + return dvm, nil +} + +// DeleteHost implements domain.HostUsecase. +func (h *HostUsecase) DeleteHost(ctx context.Context, uid uuid.UUID, id string) error { + return h.repo.DeleteHost(ctx, uid, id) +} + +// JoinTerminal implements domain.HostUsecase. +func (h *HostUsecase) JoinTerminal(ctx context.Context, req *domain.JoinTerminalReq) (taskflow.Sheller, *domain.SharedTerminal, error) { + b, err := h.redis.Get(ctx, req.Password).Result() + if err != nil { + return nil, nil, fmt.Errorf("failed to get password from redis %s", err) + } + var shared domain.SharedTerminal + if err := json.Unmarshal([]byte(b), &shared); err != nil { + return nil, nil, fmt.Errorf("failed to unmarshal share terminal req %s", err) + } + if shared.TerminalID != req.TerminalID { + return nil, nil, fmt.Errorf("terminal id mismatch %s", err) + } + + mode := taskflow.TerminalModeReadWrite + if shared.Mode == consts.TerminalModeReadOnly { + mode = taskflow.TerminalModeReadOnly + } + + shell, err := h.taskflow.VirtualMachiner().Terminal(ctx, &taskflow.TerminalReq{ + ID: shared.ID, + TerminalID: shared.TerminalID, + Mode: mode, + TerminalSize: taskflow.TerminalSize{ + Col: uint32(req.Col), + Row: uint32(req.Row), + }, + }) + if err != nil { + return nil, nil, fmt.Errorf("failed to create shell %s", err) + } + + return shell, &shared, nil +} + +// ShareTerminal implements domain.HostUsecase. +func (h *HostUsecase) ShareTerminal(ctx context.Context, user *domain.User, req *domain.ShareTerminalReq) (*domain.ShareTerminalResp, error) { + b, err := json.Marshal(&domain.SharedTerminal{ + ID: req.ID, + Mode: req.Mode, + TerminalID: req.TerminalID, + User: user, + }) + if err != nil { + return nil, fmt.Errorf("failed to marshal share terminal req %s", err) + } + pwd := random.String(8) + + if err := h.redis.Set(ctx, pwd, string(b), 5*time.Minute).Err(); err != nil { + return nil, fmt.Errorf("failed to set redis %s", err) + } + return &domain.ShareTerminalResp{ + Password: pwd, + }, nil +} + +// UpdateHost implements domain.HostUsecase. +func (h *HostUsecase) UpdateHost(ctx context.Context, uid uuid.UUID, req *domain.UpdateHostReq) error { + return h.repo.UpdateHost(ctx, uid, req) +} + +// FireExpiredVM implements domain.HostUsecase. +func (h *HostUsecase) FireExpiredVM(ctx context.Context, fire bool) ([]domain.FireExpiredVMItem, error) { + vms, err := h.repo.AllCountDownVirtualMachine(ctx) + if err != nil { + return nil, err + } + + vmonline, err := h.taskflow.VirtualMachiner().IsOnline(ctx, &taskflow.IsOnlineReq[string]{ + IDs: cvt.Iter(vms, func(_ int, vm *db.VirtualMachine) string { return vm.ID }), + }) + if err != nil { + return nil, err + } + + res := make([]domain.FireExpiredVMItem, 0) + for _, vm := range vms { + if vm.TTL <= 0 { + continue + } + + if !vmonline.OnlineMap[vm.ID] { + continue + } + + if vm.CreatedAt.Add(time.Duration(vm.TTL) * time.Second).Before(time.Now()) { + item := domain.FireExpiredVMItem{ + ID: vm.ID, + Message: "checked", + } + if fire { + if _, err := h.vmexpireQueue.Enqueue(context.Background(), consts.VM_EXPIRE_QUEUE_KEY, &domain.VmExpireInfo{ + UID: vm.UserID, + VmID: vm.ID, + HostID: vm.HostID, + EnvID: vm.EnvironmentID, + }, vm.CreatedAt.Add(time.Duration(vm.TTL)*time.Second), vm.ID); err != nil { + h.logger.With("error", err, "vm", vm).Error("failed to enqueue vm") + item.Message = err.Error() + } else { + h.logger.With("vm", vm).Info("enqueued vm") + item.Message = "enqueued" + } + } + res = append(res, item) + } + } + return res, nil +} + +// EnqueueAllCountDownVM implements domain.HostUsecase. +func (h *HostUsecase) EnqueueAllCountDownVM(ctx context.Context) ([]string, error) { + vms, err := h.repo.AllCountDownVirtualMachine(ctx) + if err != nil { + return nil, err + } + + res := make([]string, 0) + + for _, vm := range vms { + if vm.TTL <= 0 { + continue + } + + if _, err := h.vmexpireQueue.Enqueue(context.Background(), consts.VM_EXPIRE_QUEUE_KEY, &domain.VmExpireInfo{ + UID: vm.UserID, + VmID: vm.ID, + HostID: vm.HostID, + EnvID: vm.EnvironmentID, + }, vm.CreatedAt.Add(time.Duration(vm.TTL)*time.Second), vm.ID); err != nil { + h.logger.With("error", err, "vm", vm).Error("failed to enqueue vm") + } else { + h.logger.With("vm", vm).Info("enqueued vm") + res = append(res, vm.ID) + } + } + return res, nil +} + +// UpdateVM implements domain.HostUsecase. +func (h *HostUsecase) UpdateVM(ctx context.Context, req domain.UpdateVMReq) (*domain.VirtualMachine, error) { + vm, _, err := h.repo.UpdateVM(ctx, req, func(vm *db.VirtualMachine) error { + newExpiresAt := vm.CreatedAt.Add(time.Duration(vm.TTL) * time.Second) + + // 更新回收队列 + if _, err := h.vmexpireQueue.Enqueue(ctx, consts.VM_EXPIRE_QUEUE_KEY, &domain.VmExpireInfo{ + UID: vm.UserID, + VmID: vm.ID, + HostID: vm.HostID, + EnvID: vm.EnvironmentID, + }, newExpiresAt, vm.ID); err != nil { + return err + } + + return nil + }) + if err != nil { + return nil, err + } + + res := cvt.From(vm, &domain.VirtualMachine{}) + + return res, nil +} + +// ApplyPort implements domain.HostUsecase. +func (h *HostUsecase) ApplyPort(ctx context.Context, uid uuid.UUID, req *domain.ApplyPortReq) (*domain.VMPort, error) { + if req.ForwardID == "" { + forwardInfo, err := h.taskflow.PortForwarder().Create( + ctx, + taskflow.CreatePortForward{ + ID: req.ID, + UserID: uid.String(), + LocalPort: int32(req.Port), + WhitelistIPs: req.WhiteList, + }, + ) + if err != nil { + return nil, err + } + return &domain.VMPort{ + ForwardID: forwardInfo.ForwardID, + Port: uint16(forwardInfo.Port), + Status: consts.PortStatus(forwardInfo.Status), + WhiteList: forwardInfo.WhitelistIPs, + PreviewURL: forwardInfo.AccessURL, + Success: &forwardInfo.Success, + ErrorMessage: forwardInfo.ErrorMessage, + }, nil + } + + forwardInfo, err := h.taskflow.PortForwarder().Update( + ctx, + taskflow.UpdatePortForward{ + ID: req.ID, + ForwardID: req.ForwardID, + WhitelistIPs: req.WhiteList, + }, + ) + if err != nil { + return nil, err + } + return &domain.VMPort{ + ForwardID: forwardInfo.ForwardID, + PreviewURL: forwardInfo.AccessURL, + Port: uint16(forwardInfo.Port), + Status: consts.PortStatus(forwardInfo.Status), + WhiteList: forwardInfo.WhitelistIPs, + Success: &forwardInfo.Success, + ErrorMessage: forwardInfo.ErrorMessage, + }, nil +} + +// RecyclePort implements domain.HostUsecase. +func (h *HostUsecase) RecyclePort(ctx context.Context, uid uuid.UUID, req *domain.RecyclePortReq) error { + return h.taskflow.PortForwarder().Close(ctx, taskflow.ClosePortForward{ + ID: req.ID, + ForwardID: req.ForwardID, + }) +} + +// GetPorts 获取虚拟机端口列表 +func (h *HostUsecase) GetPorts(ctx context.Context, vid string) ([]*domain.VMPort, error) { + forwardInfos, err := h.taskflow.PortForwarder().List(ctx, vid) + if err != nil { + return nil, err + } + if forwardInfos == nil { + return []*domain.VMPort{}, nil + } + ports := cvt.Iter(forwardInfos, func(_ int, forwardInfo *taskflow.PortForwardInfo) *domain.VMPort { + vm := &domain.VMPort{ + Port: uint16(forwardInfo.Port), + Status: consts.PortStatus(forwardInfo.Status), + WhiteList: forwardInfo.WhitelistIPs, + ErrorMessage: forwardInfo.ErrorMessage, + ForwardID: forwardInfo.ForwardID, + PreviewURL: forwardInfo.AccessURL, + } + return vm + }) + sort.Slice(ports, func(i, j int) bool { + return ports[i].Port < ports[j].Port + }) + return ports, nil +} diff --git a/backend/biz/host/usecase/publichost.go b/backend/biz/host/usecase/publichost.go new file mode 100644 index 00000000..07f7954d --- /dev/null +++ b/backend/biz/host/usecase/publichost.go @@ -0,0 +1,84 @@ +package usecase + +import ( + "context" + "fmt" + "sync/atomic" + + "github.com/samber/do" + + "github.com/chaitin/MonkeyCode/backend/db" + "github.com/chaitin/MonkeyCode/backend/domain" + "github.com/chaitin/MonkeyCode/backend/errcode" + "github.com/chaitin/MonkeyCode/backend/pkg/cvt" + "github.com/chaitin/MonkeyCode/backend/pkg/taskflow" +) + +type PublicHostUsecase struct { + repo domain.PublicHostRepo + taskflow taskflow.Clienter + rr uint64 +} + +func NewPublicHostUsecase(i *do.Injector) (domain.PublicHostUsecase, error) { + return &PublicHostUsecase{ + repo: do.MustInvoke[domain.PublicHostRepo](i), + taskflow: do.MustInvoke[taskflow.Clienter](i), + }, nil +} + +// PickHost implements domain.PublicHostUsecase. +func (p *PublicHostUsecase) PickHost(ctx context.Context) (*domain.Host, error) { + hs, err := p.repo.All(ctx) + if err != nil { + return nil, err + } + + resp, err := p.taskflow.Host().IsOnline(ctx, &taskflow.IsOnlineReq[string]{ + IDs: cvt.Iter(hs, func(_ int, h *db.Host) string { return h.ID }), + }) + if err != nil { + return nil, err + } + + onlines := make([]*db.Host, 0) + for _, h := range hs { + if resp.OnlineMap[h.ID] { + onlines = append(onlines, h) + } + } + + if len(onlines) == 0 { + return nil, errcode.ErrPublicHostNotFound.Wrap(fmt.Errorf("no online public hosts found")) + } + + weights := make([]uint64, len(onlines)) + var totalWeight uint64 + for i, h := range onlines { + w := h.Weight + if w <= 0 { + w = 1 + } + weights[i] = uint64(w) + totalWeight += weights[i] + } + if totalWeight == 0 { + return nil, errcode.ErrPublicHostNotFound.Wrap(fmt.Errorf("no valid weights found")) + } + + idx := atomic.AddUint64(&p.rr, 1) - 1 + offset := idx % totalWeight + var selected *db.Host + for i, w := range weights { + if offset < w { + selected = onlines[i] + break + } + offset -= w + } + if selected == nil { + return nil, errcode.ErrPublicHostNotFound.Wrap(fmt.Errorf("failed to select public host")) + } + + return cvt.From(selected, &domain.Host{}), nil +} diff --git a/backend/biz/register.go b/backend/biz/register.go index 6000c3c1..72da98b2 100644 --- a/backend/biz/register.go +++ b/backend/biz/register.go @@ -3,6 +3,7 @@ package biz import ( "github.com/samber/do" + "github.com/chaitin/MonkeyCode/backend/biz/host" "github.com/chaitin/MonkeyCode/backend/biz/public" "github.com/chaitin/MonkeyCode/backend/biz/setting" "github.com/chaitin/MonkeyCode/backend/biz/team" @@ -20,5 +21,8 @@ func RegisterAll(i *do.Injector) error { return err } + // 注册 host 模块 + host.RegisterHost(i) + return nil } diff --git a/backend/biz/team/handler/http/v1/host.go b/backend/biz/team/handler/http/v1/host.go new file mode 100644 index 00000000..2e0a44e8 --- /dev/null +++ b/backend/biz/team/handler/http/v1/host.go @@ -0,0 +1,121 @@ +package v1 + +import ( + "github.com/GoYoko/web" + "github.com/samber/do" + + "github.com/chaitin/MonkeyCode/backend/domain" + "github.com/chaitin/MonkeyCode/backend/middleware" +) + +// TeamHostHandler 团队宿主机处理器 +type TeamHostHandler struct { + usecase domain.TeamHostUsecase +} + +// NewTeamHostHandler 创建团队宿主机处理器 +func NewTeamHostHandler(i *do.Injector) (*TeamHostHandler, error) { + w := do.MustInvoke[*web.Web](i) + auth := do.MustInvoke[*middleware.AuthMiddleware](i) + + h := &TeamHostHandler{ + usecase: do.MustInvoke[domain.TeamHostUsecase](i), + } + + g := w.Group("/api/v1/teams/hosts") + g.Use(auth.TeamAuth()) + + g.GET("/install-command", web.BaseHandler(h.GetInstallCommand)) + g.GET("", web.BaseHandler(h.List, web.WithPage())) + g.PUT("/:host_id", web.BindHandler(h.Update)) + g.DELETE("/:host_id", web.BindHandler(h.Delete)) + + return h, nil +} + +// List 获取团队宿主机列表 +// +// @Summary 获取团队宿主机列表 +// @Description 获取团队宿主机列表 +// @Tags 【Team 管理员】宿主机管理 +// @Accept json +// @Produce json +// @Security MonkeyCodeAITeamAuth +// @Param page query web.Pagination false "分页参数" +// @Success 200 {object} web.Resp{data=domain.ListTeamHostsResp} "成功" +// @Failure 401 {object} web.Resp "未授权" +// @Failure 500 {object} web.Resp "服务器内部错误" +// @Router /api/v1/teams/hosts [get] +func (h *TeamHostHandler) List(c *web.Context) error { + teamUser := middleware.GetTeamUser(c) + resp, err := h.usecase.List(c.Request().Context(), teamUser) + if err != nil { + return err + } + return c.Success(resp) +} + +// GetInstallCommand 获取宿主机安装命令 +// +// @Summary 获取宿主机安装命令 +// @Description 获取宿主机安装命令 +// @Tags 【Team 管理员】宿主机管理 +// @Accept json +// @Produce json +// @Security MonkeyCodeAITeamAuth +// @Success 200 {object} web.Resp{data=domain.InstallCommand} "成功" +// @Failure 401 {object} web.Resp "未授权" +// @Failure 500 {object} web.Resp "服务器内部错误" +// @Router /api/v1/teams/hosts/install-command [get] +func (h *TeamHostHandler) GetInstallCommand(c *web.Context) error { + teamUser := middleware.GetTeamUser(c) + cmd, err := h.usecase.GetInstallCommand(c.Request().Context(), teamUser) + if err != nil { + return err + } + return c.Success(domain.InstallCommand{Command: cmd}) +} + +// Update 更新团队宿主机 +// +// @Summary 更新团队宿主机 +// @Description 更新团队宿主机 +// @Tags 【Team 管理员】宿主机管理 +// @Accept json +// @Produce json +// @Security MonkeyCodeAITeamAuth +// @Param host_id path string true "宿主机ID" +// @Param param body domain.UpdateTeamHostReq true "参数" +// @Success 200 {object} web.Resp "成功" +// @Failure 401 {object} web.Resp "未授权" +// @Failure 500 {object} web.Resp "服务器内部错误" +// @Router /api/v1/teams/hosts/{host_id} [put] +func (h *TeamHostHandler) Update(c *web.Context, req domain.UpdateTeamHostReq) error { + teamUser := middleware.GetTeamUser(c) + resp, err := h.usecase.Update(c.Request().Context(), teamUser, &req) + if err != nil { + return err + } + return c.Success(resp) +} + +// Delete 删除团队宿主机 +// +// @Summary 删除团队宿主机 +// @Description 删除团队宿主机 +// @Tags 【Team 管理员】宿主机管理 +// @Accept json +// @Produce json +// @Security MonkeyCodeAITeamAuth +// @Param host_id path string true "宿主机ID" +// @Success 200 {object} web.Resp "成功" +// @Failure 401 {object} web.Resp "未授权" +// @Failure 500 {object} web.Resp "服务器内部错误" +// @Router /api/v1/teams/hosts/{host_id} [delete] +func (h *TeamHostHandler) Delete(c *web.Context, req domain.DeleteTeamHostReq) error { + teamUser := middleware.GetTeamUser(c) + if err := h.usecase.Delete(c.Request().Context(), teamUser, &req); err != nil { + return err + } + return c.Success(nil) +} diff --git a/backend/biz/team/register.go b/backend/biz/team/register.go index 868be6e1..ce7f2a2f 100644 --- a/backend/biz/team/register.go +++ b/backend/biz/team/register.go @@ -25,6 +25,11 @@ func RegisterTeam(i *do.Injector) error { do.Provide(i, usecase.NewTeamImageUsecase) do.Provide(i, v1.NewTeamImageHandler) + // 团队宿主机 + do.Provide(i, repo.NewTeamHostRepo) + do.Provide(i, usecase.NewTeamHostUsecase) + do.Provide(i, v1.NewTeamHostHandler) + // 注册 handler do.Provide(i, v1.NewTeamGroupUserHandler) _, err := do.Invoke[*v1.TeamGroupUserHandler](i) @@ -33,5 +38,6 @@ func RegisterTeam(i *do.Injector) error { } do.MustInvoke[*v1.TeamModelHandler](i) do.MustInvoke[*v1.TeamImageHandler](i) + do.MustInvoke[*v1.TeamHostHandler](i) return nil } diff --git a/backend/biz/team/repo/host.go b/backend/biz/team/repo/host.go new file mode 100644 index 00000000..4d3c1153 --- /dev/null +++ b/backend/biz/team/repo/host.go @@ -0,0 +1,238 @@ +package repo + +import ( + "context" + "fmt" + "log/slog" + "strings" + "time" + + "entgo.io/ent/dialect/sql" + "github.com/google/uuid" + "github.com/patrickmn/go-cache" + "github.com/samber/do" + + "github.com/chaitin/MonkeyCode/backend/db" + "github.com/chaitin/MonkeyCode/backend/db/host" + "github.com/chaitin/MonkeyCode/backend/db/team" + "github.com/chaitin/MonkeyCode/backend/db/teamgrouphost" + "github.com/chaitin/MonkeyCode/backend/db/teamhost" + "github.com/chaitin/MonkeyCode/backend/db/teammember" + "github.com/chaitin/MonkeyCode/backend/domain" + "github.com/chaitin/MonkeyCode/backend/errcode" + "github.com/chaitin/MonkeyCode/backend/pkg/cvt" + "github.com/chaitin/MonkeyCode/backend/pkg/entx" + "github.com/chaitin/MonkeyCode/backend/pkg/taskflow" +) + +// TeamHostRepo 团队宿主机数据访问层 +type TeamHostRepo struct { + db *db.Client + cache *cache.Cache + logger *slog.Logger +} + +// NewTeamHostRepo 创建团队宿主机数据访问层 +func NewTeamHostRepo(i *do.Injector) (domain.TeamHostRepo, error) { + return &TeamHostRepo{ + db: do.MustInvoke[*db.Client](i), + cache: cache.New(15*time.Minute, 10*time.Minute), + logger: do.MustInvoke[*slog.Logger](i).With("module", "repo.team_host"), + }, nil +} + +// List 获取团队宿主机列表 +func (r *TeamHostRepo) List(ctx context.Context, teamID uuid.UUID) ([]*db.Host, error) { + ths, err := r.db.TeamHost.Query(). + WithHost(func(hq *db.HostQuery) { + hq.WithVms(func(vmq *db.VirtualMachineQuery) { + vmq.WithUser() + }). + WithGroups() + }). + WithTeam(). + Where(teamhost.TeamID(teamID)). + Order(teamhost.ByCreatedAt(sql.OrderDesc())). + All(ctx) + if err != nil { + return nil, err + } + hs := cvt.Iter(ths, func(_ int, th *db.TeamHost) *db.Host { + return th.Edges.Host + }) + return hs, nil +} + +// Delete 删除团队宿主机 +func (r *TeamHostRepo) Delete(ctx context.Context, teamUser *domain.TeamUser, hostID string) error { + return entx.WithTx2(ctx, r.db, func(tx *db.Tx) error { + th, err := tx.TeamHost.Query(). + Where(teamhost.HostID(hostID)). + Where(teamhost.TeamID(teamUser.GetTeamID())). + Where(teamhost.HasTeamWith(team.HasTeamMembersWith(teammember.UserID(teamUser.User.ID)))). + First(ctx) + if err != nil { + return err + } + + if err := tx.TeamHost.DeleteOneID(th.ID).Exec(ctx); err != nil { + return err + } + + _, err = tx.Host.Delete(). + Where(host.ID(hostID)). + Exec(ctx) + if err != nil { + return err + } + + return nil + }) +} + +// UpsertHost implements domain.TeamHostRepo. +func (r *TeamHostRepo) UpsertHost(ctx context.Context, user *domain.User, info *taskflow.Host) error { + if info == nil || strings.HasPrefix(info.ID, "agent_") { + return nil + } + uid, err := uuid.Parse(info.UserID) + if err != nil { + return fmt.Errorf("invalid user id %s", err) + } + + if old, ok := r.cache.Get(info.ID); ok { + if oldInfo, ok := old.(*domain.Host); ok { + if oldInfo.Arch == info.Arch && + oldInfo.Cores == int(info.Cores) && + oldInfo.Name == info.Hostname && + oldInfo.ExternalIP == info.PublicIP && + oldInfo.OS == info.OS && + oldInfo.Memory == uint64(info.Memory) && + oldInfo.Version == info.Version { + return nil + } + } + } + + return entx.WithTx2(ctx, r.db, func(tx *db.Tx) error { + if _, err := tx.Host.Query().Where(host.ID(info.ID)).First(ctx); err == nil { + if err := tx.Host.UpdateOneID(info.ID). + SetArch(info.Arch). + SetCores(int(info.Cores)). + SetOs(info.OS). + SetHostname(info.Hostname). + SetMemory(int64(info.Memory)). + SetExternalIP(info.PublicIP). + SetInternalIP(info.InternalIP). + SetHostname(info.Hostname). + SetVersion(info.Version). + Exec(ctx); err != nil { + return err + } + + r.cache.Set(info.ID, &domain.Host{ + ID: info.ID, + Arch: info.Arch, + Cores: int(info.Cores), + OS: info.OS, + Memory: info.Memory, + Name: info.Hostname, + ExternalIP: info.PublicIP, + Version: info.Version, + }, 10*time.Minute) + + return nil + } + + if err := tx.Host.Create(). + SetID(info.ID). + SetUserID(uid). + SetArch(info.Arch). + SetCores(int(info.Cores)). + SetOs(info.OS). + SetHostname(info.Hostname). + SetMemory(int64(info.Memory)). + SetExternalIP(info.PublicIP). + SetInternalIP(info.InternalIP). + SetHostname(info.Hostname). + Exec(ctx); err != nil { + return err + } + + r.cache.Set(info.ID, &domain.Host{ + ID: info.ID, + Arch: info.Arch, + OS: info.OS, + Cores: int(info.Cores), + Memory: info.Memory, + Name: info.Hostname, + ExternalIP: info.PublicIP, + }, 10*time.Minute) + + if err := tx.TeamHost.Create(). + SetTeamID(user.Team.ID). + SetHostID(info.ID). + Exec(ctx); err != nil { + return err + } + + return nil + }) +} + +// Update implements domain.TeamHostRepo. +func (r *TeamHostRepo) Update(ctx context.Context, teamUser *domain.TeamUser, req *domain.UpdateTeamHostReq) (*db.Host, error) { + var res *db.Host + err := entx.WithTx2(ctx, r.db, func(tx *db.Tx) error { + th, err := tx.TeamHost.Query(). + Where(teamhost.HostID(req.HostID)). + Where(teamhost.TeamID(teamUser.Team.ID)). + First(ctx) + if err != nil { + return errcode.ErrNotFound.Wrap(err) + } + + // 更新宿主机备注 + upt := tx.Host.Update().Where(host.IDEQ(req.HostID)) + if req.Remark != "" { + upt.SetRemark(req.Remark) + } + if err = upt.Exec(ctx); err != nil { + return err + } + + if _, err := tx.TeamGroupHost.Delete(). + Where(teamgrouphost.HostID(th.HostID)). + Exec(ctx); err != nil { + return err + } + + creates := make([]*db.TeamGroupHostCreate, 0) + for _, id := range req.GroupIDs { + ct := tx.TeamGroupHost.Create(). + SetHostID(th.HostID). + SetGroupID(id) + creates = append(creates, ct) + } + if len(creates) > 0 { + if err := tx.TeamGroupHost.CreateBulk(creates...).Exec(ctx); err != nil { + return err + } + } + + res, err = tx.Host.Query(). + WithGroups(). + WithUser(). + WithVms(). + Where(host.ID(th.HostID)). + First(ctx) + if err != nil { + return errcode.ErrNotFound.Wrap(err) + } + return nil + }) + if err != nil { + return nil, err + } + return res, nil +} diff --git a/backend/biz/team/usecase/host.go b/backend/biz/team/usecase/host.go new file mode 100644 index 00000000..29ebaad4 --- /dev/null +++ b/backend/biz/team/usecase/host.go @@ -0,0 +1,136 @@ +package usecase + +import ( + "context" + "encoding/json" + "fmt" + "log/slog" + "net/url" + "time" + + "github.com/google/uuid" + "github.com/redis/go-redis/v9" + "github.com/samber/do" + + "github.com/chaitin/MonkeyCode/backend/config" + "github.com/chaitin/MonkeyCode/backend/consts" + "github.com/chaitin/MonkeyCode/backend/db" + "github.com/chaitin/MonkeyCode/backend/domain" + "github.com/chaitin/MonkeyCode/backend/pkg/cvt" + "github.com/chaitin/MonkeyCode/backend/pkg/taskflow" +) + +// TeamHostUsecase 团队宿主机业务逻辑层 +type TeamHostUsecase struct { + repo domain.TeamHostRepo + redis *redis.Client + logger *slog.Logger + cfg *config.Config + taskflow taskflow.Clienter +} + +// NewTeamHostUsecase 创建团队宿主机业务逻辑层实例 +func NewTeamHostUsecase(i *do.Injector) (domain.TeamHostUsecase, error) { + return &TeamHostUsecase{ + repo: do.MustInvoke[domain.TeamHostRepo](i), + redis: do.MustInvoke[*redis.Client](i), + cfg: do.MustInvoke[*config.Config](i), + taskflow: do.MustInvoke[taskflow.Clienter](i), + logger: do.MustInvoke[*slog.Logger](i).With("module", "usecase.team_host"), + }, nil +} + +// GetInstallCommand 获取宿主机安装命令 +func (u *TeamHostUsecase) GetInstallCommand(ctx context.Context, teamUser *domain.TeamUser) (string, error) { + token := uuid.NewString() + ub, err := json.Marshal(teamUser.User) + if err != nil { + return "", err + } + key := fmt.Sprintf("host:token:%s", token) + if err := u.redis.Set(ctx, key, string(ub), 15*time.Minute).Err(); err != nil { + return "", err + } + + baseurl, err := url.Parse(u.cfg.Server.BaseURL) + if err != nil { + return "", fmt.Errorf("failed to parse baseurl [%s]", u.cfg.Server.BaseURL) + } + baseurl = baseurl.JoinPath("/api/v1/users/hosts/install") + values := url.Values{} + values.Add("token", token) + baseurl.RawQuery = values.Encode() + + return fmt.Sprintf(`bash -c "$(curl -fsSL '%s')"`, baseurl.String()), nil +} + +// List 获取团队宿主机列表 +func (u *TeamHostUsecase) List(ctx context.Context, teamUser *domain.TeamUser) (*domain.ListTeamHostsResp, error) { + hosts, err := u.repo.List(ctx, teamUser.GetTeamID()) + if err != nil { + return nil, err + } + + resp, err := u.taskflow.Host().IsOnline(ctx, &taskflow.IsOnlineReq[string]{ + IDs: cvt.Iter(hosts, func(_ int, h *db.Host) string { + return h.ID + }), + }) + if err != nil { + return nil, err + } + vmids := make([]string, 0) + for _, host := range hosts { + for _, vm := range host.Edges.Vms { + vmids = append(vmids, vm.ID) + } + } + vmonline, err := u.taskflow.VirtualMachiner().IsOnline(ctx, &taskflow.IsOnlineReq[string]{ + IDs: vmids, + }) + if err != nil { + return nil, err + } + + res := make([]*domain.Host, len(hosts)) + for i, host := range hosts { + status := consts.HostStatusOffline + if resp.OnlineMap[host.ID] { + status = consts.HostStatusOnline + } + dHost := cvt.From(host, &domain.Host{ + Status: status, + }) + + dHost.VirtualMachines = cvt.Iter(host.Edges.Vms, func(_ int, vm *db.VirtualMachine) *domain.VirtualMachine { + status := taskflow.VirtualMachineStatusOffline + if vmonline.OnlineMap[vm.ID] { + status = taskflow.VirtualMachineStatusOnline + } + return cvt.From(vm, &domain.VirtualMachine{ + Status: status, + }) + }) + + res[i] = dHost + } + + return &domain.ListTeamHostsResp{ + Hosts: res, + }, nil +} + +// Delete 删除团队宿主机 +func (u *TeamHostUsecase) Delete(ctx context.Context, teamUser *domain.TeamUser, req *domain.DeleteTeamHostReq) error { + return u.repo.Delete(ctx, teamUser, req.HostID) +} + +// Update implements domain.TeamHostUsecase. +func (u *TeamHostUsecase) Update(ctx context.Context, teamUser *domain.TeamUser, req *domain.UpdateTeamHostReq) (*domain.Host, error) { + host, err := u.repo.Update(ctx, teamUser, req) + if err != nil { + return nil, err + } + + return cvt.From(host, &domain.Host{}), nil +} diff --git a/backend/bridge.go b/backend/bridge.go index a19af290..6aea47b5 100644 --- a/backend/bridge.go +++ b/backend/bridge.go @@ -6,6 +6,8 @@ import ( "github.com/samber/do" "github.com/chaitin/MonkeyCode/backend/biz" + hostrepo "github.com/chaitin/MonkeyCode/backend/biz/host/repo" + hostusecase "github.com/chaitin/MonkeyCode/backend/biz/host/usecase" "github.com/chaitin/MonkeyCode/backend/config" "github.com/chaitin/MonkeyCode/backend/domain" "github.com/chaitin/MonkeyCode/backend/pkg" @@ -21,6 +23,28 @@ func WithEmailSender(sender domain.EmailSender) BridgeOption { } } +// WithPublicHost 启用公共主机支持,注册 PublicHostRepo 和 PublicHostUsecase +func WithPublicHost() BridgeOption { + return func(i *do.Injector) { + do.Provide(i, hostrepo.NewPublicHostRepo) + do.Provide(i, hostusecase.NewPublicHostUsecase) + } +} + +// WithPrivilegeChecker 注入特权用户检查器 +func WithPrivilegeChecker(checker domain.PrivilegeChecker) BridgeOption { + return func(i *do.Injector) { + do.ProvideValue(i, checker) + } +} + +// WithInternalHook 注入内部 handler 回调(用于 taskflow 回调中与 task 系统耦合的逻辑) +func WithInternalHook(hook domain.InternalHook) BridgeOption { + return func(i *do.Injector) { + do.ProvideValue(i, hook) + } +} + func Register(e *echo.Echo, dir string, opts ...BridgeOption) error { cfg, err := config.Init(dir) if err != nil { diff --git a/backend/config/config.go b/backend/config/config.go index 95362a53..472d5f3f 100644 --- a/backend/config/config.go +++ b/backend/config/config.go @@ -32,6 +32,21 @@ type Config struct { Logger *logger.Config `mapstructure:"logger"` AdminToken string `mapstructure:"admin_token"` Proxies []string `mapstructure:"proxies"` + + TaskFlow TaskFlow `mapstructure:"taskflow"` + PublicHost PublicHost `mapstructure:"public_host"` +} + +type TaskFlow struct { + GrpcHost string `mapstructure:"grpc_host"` + GrpcPort int `mapstructure:"grpc_port"` + GrpcURL string `mapstructure:"grpc_url"` +} + +// PublicHost 公共主机配置(可选,内部项目通过 WithPublicHost 注入时生效) +type PublicHost struct { + CountLimit int `mapstructure:"count_limit"` // 每用户公共主机 VM 数量限制,0 表示不限制 + TTLLimit int64 `mapstructure:"ttl_limit"` // 公共主机 VM 续期上限(秒),0 表示不限制 } type Session struct { diff --git a/backend/consts/user.go b/backend/consts/user.go index 5a2efc05..5316c8f3 100644 --- a/backend/consts/user.go +++ b/backend/consts/user.go @@ -1,9 +1,5 @@ package consts -const ( - PRIVILEGED_USER_KEY = "privileged:user" -) - type UserPlatform string const ( diff --git a/backend/domain/domain.go b/backend/domain/domain.go new file mode 100644 index 00000000..2b1cfbb6 --- /dev/null +++ b/backend/domain/domain.go @@ -0,0 +1,32 @@ +package domain + +import ( + "context" + + "github.com/google/uuid" + + "github.com/chaitin/MonkeyCode/backend/pkg/taskflow" +) + +// IDReq 通用 ID 请求 +type IDReq[T any] struct { + ID T `json:"id" query:"id" param:"id" validate:"required"` +} + +// PrivilegeChecker 特权用户检查接口(可选,内部项目通过 WithPrivilegeChecker 注入) +type PrivilegeChecker interface { + IsPrivileged(ctx context.Context, uid uuid.UUID) (bool, error) +} + +// InternalHook 内部 handler 回调接口(可选,内部项目通过 WithInternalHook 注入) +// 用于扩展 taskflow 回调端点中与 task 系统耦合的逻辑 +type InternalHook interface { + // OnAgentAuth agent 认证成功后获取关联的 TaskID + OnAgentAuth(ctx context.Context, vmID string) uuid.UUID + // OnVmReady VM 就绪回调(如任务状态转换) + OnVmReady(ctx context.Context, vmID string) error + // OnVmConditionFailed VM 条件失败回调(如任务状态转换) + OnVmConditionFailed(ctx context.Context, vmID string) error + // GitCredential 获取 git 凭证(与内部 project/git identity 系统耦合) + GitCredential(ctx context.Context, req *taskflow.GitCredentialRequest) (*taskflow.GitCredentialResponse, error) +} diff --git a/backend/go.mod b/backend/go.mod index 3762062a..04b3db02 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -6,10 +6,12 @@ require ( entgo.io/ent v0.14.5 github.com/GoYoko/web v1.6.0 github.com/ackcoder/go-cap v1.1.3 + github.com/coder/websocket v1.8.14 github.com/golang-migrate/migrate/v4 v4.19.0 github.com/google/uuid v1.6.0 github.com/labstack/echo/v4 v4.15.1 github.com/lib/pq v1.10.9 + github.com/patrickmn/go-cache v2.1.0+incompatible github.com/redis/go-redis/v9 v9.18.0 github.com/samber/do v1.6.0 github.com/samber/lo v1.53.0 @@ -24,7 +26,6 @@ require ( github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect github.com/bmatcuk/doublestar v1.3.4 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect - github.com/coder/websocket v1.8.14 // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect github.com/gabriel-vasile/mimetype v1.4.13 // indirect diff --git a/backend/go.sum b/backend/go.sum index 003a177a..771f1255 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -124,6 +124,8 @@ github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8 github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/opencontainers/image-spec v1.1.0 h1:8SG7/vwALn54lVB/0yZ/MMwhFrPYtpEHQb2IpWsCzug= github.com/opencontainers/image-spec v1.1.0/go.mod h1:W4s4sFTMaBeK1BQLXbG4AdM2szdn85PY75RI83NrTrM= +github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc= +github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= diff --git a/backend/pkg/random/random.go b/backend/pkg/random/random.go new file mode 100644 index 00000000..77339eb3 --- /dev/null +++ b/backend/pkg/random/random.go @@ -0,0 +1,13 @@ +package random + +import ( + "crypto/rand" + "encoding/hex" +) + +// String 生成指定长度的随机字符串 +func String(n int) string { + b := make([]byte, (n+1)/2) + _, _ = rand.Read(b) + return hex.EncodeToString(b)[:n] +} diff --git a/backend/pkg/register.go b/backend/pkg/register.go index ecdc7997..f114dd50 100644 --- a/backend/pkg/register.go +++ b/backend/pkg/register.go @@ -12,10 +12,12 @@ import ( "github.com/chaitin/MonkeyCode/backend/domain" "github.com/chaitin/MonkeyCode/backend/middleware" "github.com/chaitin/MonkeyCode/backend/pkg/captcha" + "github.com/chaitin/MonkeyCode/backend/pkg/delayqueue" "github.com/chaitin/MonkeyCode/backend/pkg/email" "github.com/chaitin/MonkeyCode/backend/pkg/logger" "github.com/chaitin/MonkeyCode/backend/pkg/session" "github.com/chaitin/MonkeyCode/backend/pkg/store" + "github.com/chaitin/MonkeyCode/backend/pkg/taskflow" ) // RegisterInfra 注册基础设施依赖 @@ -86,5 +88,18 @@ func RegisterInfra(i *do.Injector, w ...*web.Web) error { return middleware.NewAuditMiddleware(l, auditUc, userUc), nil }) + // VM Expire Queue + do.Provide(i, func(i *do.Injector) (*delayqueue.VMExpireQueue, error) { + r := do.MustInvoke[*redis.Client](i) + l := do.MustInvoke[*slog.Logger](i) + return delayqueue.NewVMExpireQueue(r, l), nil + }) + + do.Provide(i, func(i *do.Injector) (taskflow.Clienter, error) { + cfg := do.MustInvoke[*config.Config](i) + l := do.MustInvoke[*slog.Logger](i) + return taskflow.NewClient(taskflow.WithDebug(cfg.Debug), taskflow.WithLogger(l)), nil + }) + return nil } diff --git a/backend/pkg/taskflow/types.go b/backend/pkg/taskflow/types.go index 0c6b5741..610d4eb7 100644 --- a/backend/pkg/taskflow/types.go +++ b/backend/pkg/taskflow/types.go @@ -260,3 +260,84 @@ type Stats struct { OnlineTerminalCount int `json:"online_terminal_count"` UsingTerminalUserCount int `json:"using_terminal_user_count"` } + +// ==================== Internal Callback 类型(taskflow → 本服务回调) ==================== + +// TokenKind token 类型 +type TokenKind string + +const ( + OrchestratorToken TokenKind = "orshcestrator" + AgentToken TokenKind = "agent" +) + +// CheckTokenReq 认证请求 +type CheckTokenReq struct { + Token string `json:"token" validate:"required"` + MachineID string `json:"machine_id"` +} + +// TokenUser token 中的用户信息 +type TokenUser struct { + ID string `json:"id"` + Name string `json:"name"` + AvatarURL string `json:"avatar_url"` + Email string `json:"email"` + Team *TokenTeam `json:"team"` +} + +// TokenTeam token 中的团队信息 +type TokenTeam struct { + ID string `json:"id"` + Name string `json:"name"` +} + +// Token 认证结果 +type Token struct { + Kind TokenKind `json:"kind"` + User *TokenUser `json:"user"` + ParentToken string `json:"parent_token"` + Token string `json:"token"` + TaskID uuid.UUID `json:"task_id"` + SessionID string `json:"session_id"` + RemoteIP string `json:"remote_ip"` + Version string `json:"version"` +} + +// ListLLMReq 列出 LLM 请求 +type ListLLMReq struct { + VmID string `json:"vm_id" validate:"required"` + HostID string `json:"host_id" validate:"required"` +} + +// LLMInfo LLM 信息 +type LLMInfo struct { + ApiKey string `json:"api_key"` + BaseURL string `json:"base_url"` + Model string `json:"model"` + Temperature *float32 `json:"temperature,omitempty"` +} + +// GetCodingConfigReq 获取编码配置请求 +type GetCodingConfigReq struct { + VmID string `json:"vm_id"` +} + +// CodingConfig 编码配置 +type CodingConfig struct{} + +// GitCredentialRequest git 凭证请求 +type GitCredentialRequest struct { + TaskID string `json:"task_id"` + VMID string `json:"vm_id"` + Protocol string `json:"protocol"` + Host string `json:"host"` + Path string `json:"path"` +} + +// GitCredentialResponse git 凭证响应 +type GitCredentialResponse struct { + Username *string `json:"username,omitempty"` + Password *string `json:"password,omitempty"` + Error *string `json:"error,omitempty"` +} diff --git a/backend/pkg/ws/ws.go b/backend/pkg/ws/ws.go new file mode 100644 index 00000000..2a9f7a30 --- /dev/null +++ b/backend/pkg/ws/ws.go @@ -0,0 +1,63 @@ +package ws + +import ( + "context" + "encoding/json" + "net/http" + "sync" + + "github.com/coder/websocket" +) + +// WebsocketManager 管理 coder/websocket 连接,提供并发安全的写入 +type WebsocketManager struct { + conn *websocket.Conn + ip string + mu sync.Mutex +} + +// Accept 从 HTTP 请求升级到 WebSocket 连接 +func Accept(w http.ResponseWriter, r *http.Request) (*WebsocketManager, error) { + conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{ + InsecureSkipVerify: true, + }) + if err != nil { + return nil, err + } + return &WebsocketManager{ + conn: conn, + ip: r.Header.Get("X-Real-IP"), + }, nil +} + +// WriteJSON 发送 JSON 消息 +func (w *WebsocketManager) WriteJSON(v any) error { + w.mu.Lock() + defer w.mu.Unlock() + b, err := json.Marshal(v) + if err != nil { + return err + } + return w.conn.Write(context.Background(), websocket.MessageText, b) +} + +// ReadMessage 读取消息,返回消息内容 +func (w *WebsocketManager) ReadMessage() ([]byte, error) { + _, data, err := w.conn.Read(context.Background()) + return data, err +} + +// Close 关闭 WebSocket 连接 +func (w *WebsocketManager) Close() error { + return w.conn.Close(websocket.StatusNormalClosure, "close") +} + +// Conn 返回底层连接 +func (w *WebsocketManager) Conn() *websocket.Conn { + return w.conn +} + +// IP 返回客户端 IP +func (w *WebsocketManager) IP() string { + return w.ip +}