diff --git a/api/agent_trace_handler.go b/api/agent_trace_handler.go new file mode 100644 index 0000000..4189e90 --- /dev/null +++ b/api/agent_trace_handler.go @@ -0,0 +1,126 @@ +package api + +import ( + "strconv" + + "github.com/gofiber/fiber/v2" + + "github.com/papercomputeco/tapes/pkg/agenttrace" + "github.com/papercomputeco/tapes/pkg/llm" + "github.com/papercomputeco/tapes/pkg/storage" +) + +// handleCreateAgentTrace handles POST /v1/agent-traces. +func (s *Server) handleCreateAgentTrace(c *fiber.Ctx) error { + var trace agenttrace.AgentTrace + if err := c.BodyParser(&trace); err != nil { + return c.Status(fiber.StatusBadRequest).JSON(llm.ErrorResponse{ + Error: "invalid request body", + }) + } + + // Validate required fields + if trace.Version == "" { + return c.Status(fiber.StatusBadRequest).JSON(llm.ErrorResponse{ + Error: "version is required", + }) + } + if trace.ID == "" { + return c.Status(fiber.StatusBadRequest).JSON(llm.ErrorResponse{ + Error: "id is required", + }) + } + if trace.Timestamp == "" { + return c.Status(fiber.StatusBadRequest).JSON(llm.ErrorResponse{ + Error: "timestamp is required", + }) + } + if len(trace.Files) == 0 { + return c.Status(fiber.StatusBadRequest).JSON(llm.ErrorResponse{ + Error: "at least one file is required", + }) + } + + for _, f := range trace.Files { + if f.Path == "" { + return c.Status(fiber.StatusBadRequest).JSON(llm.ErrorResponse{ + Error: "file path is required for all files", + }) + } + for _, conv := range f.Conversations { + for _, r := range conv.Ranges { + if r.StartLine < 0 || r.EndLine < 0 { + return c.Status(fiber.StatusBadRequest).JSON(llm.ErrorResponse{ + Error: "start_line and end_line must be non-negative", + }) + } + } + } + } + + created, err := s.agentTraceStore.CreateAgentTrace(c.Context(), &trace) + if err != nil { + return c.Status(fiber.StatusInternalServerError).JSON(llm.ErrorResponse{ + Error: "failed to create agent trace", + }) + } + + return c.Status(fiber.StatusCreated).JSON(created) +} + +// handleGetAgentTrace handles GET /v1/agent-traces/:id. +func (s *Server) handleGetAgentTrace(c *fiber.Ctx) error { + id := c.Params("id") + if id == "" { + return c.Status(fiber.StatusBadRequest).JSON(llm.ErrorResponse{ + Error: "id parameter is required", + }) + } + + trace, err := s.agentTraceStore.GetAgentTrace(c.Context(), id) + if err != nil { + return c.Status(fiber.StatusNotFound).JSON(llm.ErrorResponse{ + Error: "agent trace not found", + }) + } + + return c.JSON(trace) +} + +// handleQueryAgentTraces handles GET /v1/agent-traces. +func (s *Server) handleQueryAgentTraces(c *fiber.Ctx) error { + query := storage.AgentTraceQuery{ + FilePath: c.Query("file_path"), + Revision: c.Query("revision"), + ToolName: c.Query("tool_name"), + } + + if limitStr := c.Query("limit"); limitStr != "" { + limit, err := strconv.Atoi(limitStr) + if err != nil || limit < 0 { + return c.Status(fiber.StatusBadRequest).JSON(llm.ErrorResponse{ + Error: "limit must be a non-negative integer", + }) + } + query.Limit = limit + } + + if offsetStr := c.Query("offset"); offsetStr != "" { + offset, err := strconv.Atoi(offsetStr) + if err != nil || offset < 0 { + return c.Status(fiber.StatusBadRequest).JSON(llm.ErrorResponse{ + Error: "offset must be a non-negative integer", + }) + } + query.Offset = offset + } + + traces, err := s.agentTraceStore.QueryAgentTraces(c.Context(), query) + if err != nil { + return c.Status(fiber.StatusInternalServerError).JSON(llm.ErrorResponse{ + Error: "failed to query agent traces", + }) + } + + return c.JSON(traces) +} diff --git a/api/agent_trace_handler_test.go b/api/agent_trace_handler_test.go new file mode 100644 index 0000000..038b17d --- /dev/null +++ b/api/agent_trace_handler_test.go @@ -0,0 +1,416 @@ +package api + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + + "github.com/gofiber/fiber/v2" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + "go.uber.org/zap" + + "github.com/papercomputeco/tapes/pkg/agenttrace" + "github.com/papercomputeco/tapes/pkg/storage/inmemory" +) + +var _ = Describe("Agent Trace Handlers", func() { + var ( + server *Server + agentTraceStore *inmemory.AgentTraceStore + ) + + BeforeEach(func() { + logger, _ := zap.NewDevelopment() + inMem := inmemory.NewDriver() + agentTraceStore = inmemory.NewAgentTraceStore() + var err error + server, err = NewServer(Config{ListenAddr: ":0"}, inMem, inMem, agentTraceStore, logger) + Expect(err).NotTo(HaveOccurred()) + }) + + Describe("POST /v1/agent-traces", func() { + It("creates a valid agent trace and returns 201", func() { + trace := agenttrace.AgentTrace{ + Version: "0.1.0", + ID: "550e8400-e29b-41d4-a716-446655440000", + Timestamp: "2026-01-23T14:30:00Z", + Files: []agenttrace.File{ + { + Path: "src/app.ts", + Conversations: []agenttrace.Conversation{ + { + Contributor: &agenttrace.Contributor{Type: "ai"}, + Ranges: []agenttrace.Range{ + {StartLine: 1, EndLine: 50}, + }, + }, + }, + }, + }, + } + + body, err := json.Marshal(trace) + Expect(err).NotTo(HaveOccurred()) + + req, err := http.NewRequest(http.MethodPost, "/v1/agent-traces", bytes.NewReader(body)) + Expect(err).NotTo(HaveOccurred()) + req.Header.Set("Content-Type", "application/json") + + resp, err := server.app.Test(req) + Expect(err).NotTo(HaveOccurred()) + Expect(resp.StatusCode).To(Equal(fiber.StatusCreated)) + + var result agenttrace.AgentTrace + respBody, err := io.ReadAll(resp.Body) + Expect(err).NotTo(HaveOccurred()) + Expect(json.Unmarshal(respBody, &result)).To(Succeed()) + Expect(result.ID).To(Equal("550e8400-e29b-41d4-a716-446655440000")) + Expect(result.Version).To(Equal("0.1.0")) + Expect(result.Files).To(HaveLen(1)) + Expect(result.Files[0].Path).To(Equal("src/app.ts")) + }) + + It("creates a trace with VCS and Tool fields", func() { + trace := agenttrace.AgentTrace{ + Version: "0.1.0", + ID: "trace-with-extras", + Timestamp: "2026-01-23T14:30:00Z", + VCS: &agenttrace.VCS{Type: "git", Revision: "abc123"}, + Tool: &agenttrace.Tool{Name: "claude-code", Version: "1.0.0"}, + Files: []agenttrace.File{ + {Path: "main.go"}, + }, + } + + body, err := json.Marshal(trace) + Expect(err).NotTo(HaveOccurred()) + + req, err := http.NewRequest(http.MethodPost, "/v1/agent-traces", bytes.NewReader(body)) + Expect(err).NotTo(HaveOccurred()) + req.Header.Set("Content-Type", "application/json") + + resp, err := server.app.Test(req) + Expect(err).NotTo(HaveOccurred()) + Expect(resp.StatusCode).To(Equal(fiber.StatusCreated)) + + var result agenttrace.AgentTrace + respBody, err := io.ReadAll(resp.Body) + Expect(err).NotTo(HaveOccurred()) + Expect(json.Unmarshal(respBody, &result)).To(Succeed()) + Expect(result.VCS).NotTo(BeNil()) + Expect(result.VCS.Type).To(Equal("git")) + Expect(result.VCS.Revision).To(Equal("abc123")) + Expect(result.Tool).NotTo(BeNil()) + Expect(result.Tool.Name).To(Equal("claude-code")) + }) + + It("returns 400 when version is missing", func() { + trace := map[string]any{ + "id": "test-id", + "timestamp": "2026-01-23T14:30:00Z", + "files": []any{map[string]any{"path": "test.go"}}, + } + + body, err := json.Marshal(trace) + Expect(err).NotTo(HaveOccurred()) + + req, err := http.NewRequest(http.MethodPost, "/v1/agent-traces", bytes.NewReader(body)) + Expect(err).NotTo(HaveOccurred()) + req.Header.Set("Content-Type", "application/json") + + resp, err := server.app.Test(req) + Expect(err).NotTo(HaveOccurred()) + Expect(resp.StatusCode).To(Equal(fiber.StatusBadRequest)) + + respBody, err := io.ReadAll(resp.Body) + Expect(err).NotTo(HaveOccurred()) + Expect(string(respBody)).To(ContainSubstring("version is required")) + }) + + It("returns 400 when id is missing", func() { + trace := map[string]any{ + "version": "0.1.0", + "timestamp": "2026-01-23T14:30:00Z", + "files": []any{map[string]any{"path": "test.go"}}, + } + + body, err := json.Marshal(trace) + Expect(err).NotTo(HaveOccurred()) + + req, err := http.NewRequest(http.MethodPost, "/v1/agent-traces", bytes.NewReader(body)) + Expect(err).NotTo(HaveOccurred()) + req.Header.Set("Content-Type", "application/json") + + resp, err := server.app.Test(req) + Expect(err).NotTo(HaveOccurred()) + Expect(resp.StatusCode).To(Equal(fiber.StatusBadRequest)) + + respBody, err := io.ReadAll(resp.Body) + Expect(err).NotTo(HaveOccurred()) + Expect(string(respBody)).To(ContainSubstring("id is required")) + }) + + It("returns 400 when timestamp is missing", func() { + trace := map[string]any{ + "version": "0.1.0", + "id": "test-id", + "files": []any{map[string]any{"path": "test.go"}}, + } + + body, err := json.Marshal(trace) + Expect(err).NotTo(HaveOccurred()) + + req, err := http.NewRequest(http.MethodPost, "/v1/agent-traces", bytes.NewReader(body)) + Expect(err).NotTo(HaveOccurred()) + req.Header.Set("Content-Type", "application/json") + + resp, err := server.app.Test(req) + Expect(err).NotTo(HaveOccurred()) + Expect(resp.StatusCode).To(Equal(fiber.StatusBadRequest)) + + respBody, err := io.ReadAll(resp.Body) + Expect(err).NotTo(HaveOccurred()) + Expect(string(respBody)).To(ContainSubstring("timestamp is required")) + }) + + It("returns 400 when files is empty", func() { + trace := map[string]any{ + "version": "0.1.0", + "id": "test-id", + "timestamp": "2026-01-23T14:30:00Z", + "files": []any{}, + } + + body, err := json.Marshal(trace) + Expect(err).NotTo(HaveOccurred()) + + req, err := http.NewRequest(http.MethodPost, "/v1/agent-traces", bytes.NewReader(body)) + Expect(err).NotTo(HaveOccurred()) + req.Header.Set("Content-Type", "application/json") + + resp, err := server.app.Test(req) + Expect(err).NotTo(HaveOccurred()) + Expect(resp.StatusCode).To(Equal(fiber.StatusBadRequest)) + + respBody, err := io.ReadAll(resp.Body) + Expect(err).NotTo(HaveOccurred()) + Expect(string(respBody)).To(ContainSubstring("at least one file is required")) + }) + + It("returns 400 when file path is empty", func() { + trace := map[string]any{ + "version": "0.1.0", + "id": "test-id", + "timestamp": "2026-01-23T14:30:00Z", + "files": []any{map[string]any{"path": ""}}, + } + + body, err := json.Marshal(trace) + Expect(err).NotTo(HaveOccurred()) + + req, err := http.NewRequest(http.MethodPost, "/v1/agent-traces", bytes.NewReader(body)) + Expect(err).NotTo(HaveOccurred()) + req.Header.Set("Content-Type", "application/json") + + resp, err := server.app.Test(req) + Expect(err).NotTo(HaveOccurred()) + Expect(resp.StatusCode).To(Equal(fiber.StatusBadRequest)) + + respBody, err := io.ReadAll(resp.Body) + Expect(err).NotTo(HaveOccurred()) + Expect(string(respBody)).To(ContainSubstring("file path is required")) + }) + + It("returns 400 for invalid JSON body", func() { + req, err := http.NewRequest(http.MethodPost, "/v1/agent-traces", bytes.NewReader([]byte("not json"))) + Expect(err).NotTo(HaveOccurred()) + req.Header.Set("Content-Type", "application/json") + + resp, err := server.app.Test(req) + Expect(err).NotTo(HaveOccurred()) + Expect(resp.StatusCode).To(Equal(fiber.StatusBadRequest)) + }) + }) + + Describe("GET /v1/agent-traces/:id", func() { + It("returns the trace when it exists", func() { + trace := &agenttrace.AgentTrace{ + Version: "0.1.0", + ID: "get-test-id", + Timestamp: "2026-01-23T14:30:00Z", + Files: []agenttrace.File{ + {Path: "test.go"}, + }, + } + _, err := agentTraceStore.CreateAgentTrace(context.Background(), trace) + Expect(err).NotTo(HaveOccurred()) + + req, err := http.NewRequest(http.MethodGet, "/v1/agent-traces/get-test-id", nil) + Expect(err).NotTo(HaveOccurred()) + + resp, err := server.app.Test(req) + Expect(err).NotTo(HaveOccurred()) + Expect(resp.StatusCode).To(Equal(fiber.StatusOK)) + + var result agenttrace.AgentTrace + respBody, err := io.ReadAll(resp.Body) + Expect(err).NotTo(HaveOccurred()) + Expect(json.Unmarshal(respBody, &result)).To(Succeed()) + Expect(result.ID).To(Equal("get-test-id")) + Expect(result.Files).To(HaveLen(1)) + }) + + It("returns 404 when trace does not exist", func() { + req, err := http.NewRequest(http.MethodGet, "/v1/agent-traces/nonexistent", nil) + Expect(err).NotTo(HaveOccurred()) + + resp, err := server.app.Test(req) + Expect(err).NotTo(HaveOccurred()) + Expect(resp.StatusCode).To(Equal(fiber.StatusNotFound)) + + respBody, err := io.ReadAll(resp.Body) + Expect(err).NotTo(HaveOccurred()) + Expect(string(respBody)).To(ContainSubstring("agent trace not found")) + }) + }) + + Describe("GET /v1/agent-traces", func() { + BeforeEach(func() { + traces := []*agenttrace.AgentTrace{ + { + Version: "0.1.0", + ID: "trace-1", + Timestamp: "2026-01-23T14:30:00Z", + VCS: &agenttrace.VCS{Revision: "abc123"}, + Tool: &agenttrace.Tool{Name: "claude-code"}, + Files: []agenttrace.File{{Path: "src/app.ts"}}, + }, + { + Version: "0.1.0", + ID: "trace-2", + Timestamp: "2026-01-24T14:30:00Z", + VCS: &agenttrace.VCS{Revision: "def456"}, + Tool: &agenttrace.Tool{Name: "copilot"}, + Files: []agenttrace.File{{Path: "src/main.go"}}, + }, + { + Version: "0.1.0", + ID: "trace-3", + Timestamp: "2026-01-25T14:30:00Z", + VCS: &agenttrace.VCS{Revision: "abc123"}, + Tool: &agenttrace.Tool{Name: "claude-code"}, + Files: []agenttrace.File{{Path: "src/app.ts"}}, + }, + } + for _, t := range traces { + _, err := agentTraceStore.CreateAgentTrace(context.Background(), t) + Expect(err).NotTo(HaveOccurred()) + } + }) + + It("returns all traces when no filters", func() { + req, err := http.NewRequest(http.MethodGet, "/v1/agent-traces", nil) + Expect(err).NotTo(HaveOccurred()) + + resp, err := server.app.Test(req) + Expect(err).NotTo(HaveOccurred()) + Expect(resp.StatusCode).To(Equal(fiber.StatusOK)) + + var results []*agenttrace.AgentTrace + respBody, err := io.ReadAll(resp.Body) + Expect(err).NotTo(HaveOccurred()) + Expect(json.Unmarshal(respBody, &results)).To(Succeed()) + Expect(results).To(HaveLen(3)) + }) + + It("filters by file_path", func() { + req, err := http.NewRequest(http.MethodGet, "/v1/agent-traces?file_path=src/app.ts", nil) + Expect(err).NotTo(HaveOccurred()) + + resp, err := server.app.Test(req) + Expect(err).NotTo(HaveOccurred()) + Expect(resp.StatusCode).To(Equal(fiber.StatusOK)) + + var results []*agenttrace.AgentTrace + respBody, err := io.ReadAll(resp.Body) + Expect(err).NotTo(HaveOccurred()) + Expect(json.Unmarshal(respBody, &results)).To(Succeed()) + Expect(results).To(HaveLen(2)) + }) + + It("filters by revision", func() { + req, err := http.NewRequest(http.MethodGet, "/v1/agent-traces?revision=abc123", nil) + Expect(err).NotTo(HaveOccurred()) + + resp, err := server.app.Test(req) + Expect(err).NotTo(HaveOccurred()) + Expect(resp.StatusCode).To(Equal(fiber.StatusOK)) + + var results []*agenttrace.AgentTrace + respBody, err := io.ReadAll(resp.Body) + Expect(err).NotTo(HaveOccurred()) + Expect(json.Unmarshal(respBody, &results)).To(Succeed()) + Expect(results).To(HaveLen(2)) + }) + + It("filters by tool_name", func() { + req, err := http.NewRequest(http.MethodGet, "/v1/agent-traces?tool_name=copilot", nil) + Expect(err).NotTo(HaveOccurred()) + + resp, err := server.app.Test(req) + Expect(err).NotTo(HaveOccurred()) + Expect(resp.StatusCode).To(Equal(fiber.StatusOK)) + + var results []*agenttrace.AgentTrace + respBody, err := io.ReadAll(resp.Body) + Expect(err).NotTo(HaveOccurred()) + Expect(json.Unmarshal(respBody, &results)).To(Succeed()) + Expect(results).To(HaveLen(1)) + Expect(results[0].ID).To(Equal("trace-2")) + }) + + It("applies limit", func() { + req, err := http.NewRequest(http.MethodGet, "/v1/agent-traces?limit=2", nil) + Expect(err).NotTo(HaveOccurred()) + + resp, err := server.app.Test(req) + Expect(err).NotTo(HaveOccurred()) + Expect(resp.StatusCode).To(Equal(fiber.StatusOK)) + + var results []*agenttrace.AgentTrace + respBody, err := io.ReadAll(resp.Body) + Expect(err).NotTo(HaveOccurred()) + Expect(json.Unmarshal(respBody, &results)).To(Succeed()) + Expect(results).To(HaveLen(2)) + }) + + It("returns 400 for invalid limit", func() { + req, err := http.NewRequest(http.MethodGet, "/v1/agent-traces?limit=abc", nil) + Expect(err).NotTo(HaveOccurred()) + + resp, err := server.app.Test(req) + Expect(err).NotTo(HaveOccurred()) + Expect(resp.StatusCode).To(Equal(fiber.StatusBadRequest)) + + respBody, err := io.ReadAll(resp.Body) + Expect(err).NotTo(HaveOccurred()) + Expect(string(respBody)).To(ContainSubstring("limit must be a non-negative integer")) + }) + + It("returns 400 for invalid offset", func() { + req, err := http.NewRequest(http.MethodGet, "/v1/agent-traces?offset=xyz", nil) + Expect(err).NotTo(HaveOccurred()) + + resp, err := server.app.Test(req) + Expect(err).NotTo(HaveOccurred()) + Expect(resp.StatusCode).To(Equal(fiber.StatusBadRequest)) + + respBody, err := io.ReadAll(resp.Body) + Expect(err).NotTo(HaveOccurred()) + Expect(string(respBody)).To(ContainSubstring("offset must be a non-negative integer")) + }) + }) +}) diff --git a/api/api.go b/api/api.go index 63c70a6..96c88ed 100644 --- a/api/api.go +++ b/api/api.go @@ -14,29 +14,31 @@ import ( // Server is the API server for managing and querying the Tapes system type Server struct { - config Config - driver storage.Driver - dagLoader merkle.DagLoader - logger *zap.Logger - app *fiber.App - mcpServer *mcp.Server + config Config + driver storage.Driver + dagLoader merkle.DagLoader + agentTraceStore storage.AgentTraceStore + logger *zap.Logger + app *fiber.App + mcpServer *mcp.Server } // NewServer creates a new API server. // The storer is injected to allow sharing with other components // (e.g., the proxy when not run as a singleton). -func NewServer(config Config, driver storage.Driver, dagLoader merkle.DagLoader, logger *zap.Logger) (*Server, error) { +func NewServer(config Config, driver storage.Driver, dagLoader merkle.DagLoader, agentTraceStore storage.AgentTraceStore, logger *zap.Logger) (*Server, error) { var err error app := fiber.New(fiber.Config{ DisableStartupMessage: true, }) s := &Server{ - config: config, - driver: driver, - dagLoader: dagLoader, - logger: logger, - app: app, + config: config, + driver: driver, + dagLoader: dagLoader, + agentTraceStore: agentTraceStore, + logger: logger, + app: app, } app.Get("/ping", s.handlePing) @@ -46,6 +48,10 @@ func NewServer(config Config, driver storage.Driver, dagLoader merkle.DagLoader, app.Get("/dag/history/:hash", s.handleGetHistory) app.Get("/v1/search", s.handleSearchEndpoint) + app.Post("/v1/agent-traces", s.handleCreateAgentTrace) + app.Get("/v1/agent-traces/:id", s.handleGetAgentTrace) + app.Get("/v1/agent-traces", s.handleQueryAgentTraces) + // Register MCP server if vector driver and embedder are configured var mcpServer *mcp.Server if config.VectorDriver != nil && config.Embedder != nil { diff --git a/api/api_test.go b/api/api_test.go index f0e52bc..1c3305f 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -38,7 +38,7 @@ var _ = Describe("buildHistory", func() { inMem := inmemory.NewDriver() driver = inMem dagLoader = inMem - server, err = NewServer(Config{ListenAddr: ":0"}, driver, dagLoader, logger) + server, err = NewServer(Config{ListenAddr: ":0"}, driver, dagLoader, inmemory.NewAgentTraceStore(), logger) Expect(err).ToNot(HaveOccurred()) ctx = context.Background() }) diff --git a/api/search_handler_test.go b/api/search_handler_test.go index 0cd604a..ed87bf7 100644 --- a/api/search_handler_test.go +++ b/api/search_handler_test.go @@ -43,6 +43,7 @@ var _ = Describe("handleSearchEndpoint", func() { }, inMem, inMem, + inmemory.NewAgentTraceStore(), logger, ) Expect(err).NotTo(HaveOccurred()) @@ -55,6 +56,7 @@ var _ = Describe("handleSearchEndpoint", func() { Config{ListenAddr: ":0"}, inMem, inMem, + inmemory.NewAgentTraceStore(), logger, ) Expect(err).NotTo(HaveOccurred()) diff --git a/cmd/tapes/serve/api/api.go b/cmd/tapes/serve/api/api.go index 6e29960..4ce2844 100644 --- a/cmd/tapes/serve/api/api.go +++ b/cmd/tapes/serve/api/api.go @@ -93,7 +93,9 @@ func (c *apiCommander) run() error { ListenAddr: c.listen, } - server, err := api.NewServer(config, driver, dagLoader, c.logger) + agentTraceStore := c.newAgentTraceStore(driver) + + server, err := api.NewServer(config, driver, dagLoader, agentTraceStore, c.logger) if err != nil { return fmt.Errorf("could not build new api server: %w", err) } @@ -119,6 +121,13 @@ func (c *apiCommander) newStorageDriver() (storage.Driver, error) { return inmemory.NewDriver(), nil } +func (c *apiCommander) newAgentTraceStore(driver storage.Driver) storage.AgentTraceStore { + if sqliteDriver, ok := driver.(*sqlite.Driver); ok { + return sqliteDriver.AgentTraceStore + } + return inmemory.NewAgentTraceStore() +} + func (c *apiCommander) newDagLoader() (merkle.DagLoader, error) { if c.sqlitePath != "" { driver, err := sqlite.NewDriver(context.Background(), c.sqlitePath) diff --git a/cmd/tapes/serve/serve.go b/cmd/tapes/serve/serve.go index 1b76ee8..66af697 100644 --- a/cmd/tapes/serve/serve.go +++ b/cmd/tapes/serve/serve.go @@ -229,7 +229,10 @@ func (c *ServeCommander) run() error { VectorDriver: proxyConfig.VectorDriver, Embedder: proxyConfig.Embedder, } - apiServer, err := api.NewServer(apiConfig, driver, dagLoader, c.logger) + // Create agent trace store from the same storage driver + agentTraceStore := c.newAgentTraceStore(driver) + + apiServer, err := api.NewServer(apiConfig, driver, dagLoader, agentTraceStore, c.logger) if err != nil { return fmt.Errorf("could not build new api server: %w", err) } @@ -282,6 +285,13 @@ func (c *ServeCommander) newStorageDriver() (storage.Driver, error) { return inmemory.NewDriver(), nil } +func (c *ServeCommander) newAgentTraceStore(driver storage.Driver) storage.AgentTraceStore { + if sqliteDriver, ok := driver.(*sqlite.Driver); ok { + return sqliteDriver.AgentTraceStore + } + return inmemory.NewAgentTraceStore() +} + func (c *ServeCommander) newDagLoader() (merkle.DagLoader, error) { if c.sqlitePath != "" { driver, err := sqlite.NewDriver(context.Background(), c.sqlitePath) diff --git a/go.sum b/go.sum index 1326614..45c37fa 100644 --- a/go.sum +++ b/go.sum @@ -115,6 +115,8 @@ github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= +github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= github.com/onsi/ginkgo/v2 v2.27.4 h1:fcEcQW/A++6aZAZQNUmNjvA9PSOzefMJBerHJ4t8v8Y= github.com/onsi/ginkgo/v2 v2.27.4/go.mod h1:ArE1D/XhNXBXCBkKOLkbsb2c81dQHCRcF5zwn/ykDRo= github.com/onsi/gomega v1.39.0 h1:y2ROC3hKFmQZJNFeGAMeHZKkjBL65mIZcvrLQBF9k6Q= diff --git a/pkg/agenttrace/agenttrace.go b/pkg/agenttrace/agenttrace.go new file mode 100644 index 0000000..8cf558c --- /dev/null +++ b/pkg/agenttrace/agenttrace.go @@ -0,0 +1,60 @@ +// Package agenttrace defines domain types for the Agent Trace specification, +// an open specification for tracking AI-generated code attribution. +package agenttrace + +// AgentTrace is the root record for an agent trace. +type AgentTrace struct { + Version string `json:"version"` + ID string `json:"id"` + Timestamp string `json:"timestamp"` + VCS *VCS `json:"vcs,omitempty"` + Tool *Tool `json:"tool,omitempty"` + Files []File `json:"files"` + Metadata map[string]any `json:"metadata,omitempty"` +} + +// VCS describes the version control system context. +type VCS struct { + Type string `json:"type,omitempty"` + Revision string `json:"revision,omitempty"` +} + +// Tool describes the tool that generated the trace. +type Tool struct { + Name string `json:"name,omitempty"` + Version string `json:"version,omitempty"` +} + +// File describes a file with AI-attributed conversations. +type File struct { + Path string `json:"path"` + Conversations []Conversation `json:"conversations,omitempty"` +} + +// Conversation describes a conversation that contributed to a file. +type Conversation struct { + URL string `json:"url,omitempty"` + Contributor *Contributor `json:"contributor,omitempty"` + Ranges []Range `json:"ranges,omitempty"` + RelatedResources []RelatedResource `json:"related_resources,omitempty"` +} + +// Contributor describes who contributed to the code (AI or human). +type Contributor struct { + Type string `json:"type,omitempty"` + ModelID string `json:"model_id,omitempty"` +} + +// Range describes a range of lines attributed to AI generation. +type Range struct { + StartLine int `json:"start_line"` + EndLine int `json:"end_line"` + ContentHash string `json:"content_hash,omitempty"` + Contributor *Contributor `json:"contributor,omitempty"` +} + +// RelatedResource describes a resource related to the conversation. +type RelatedResource struct { + Type string `json:"type,omitempty"` + URL string `json:"url,omitempty"` +} diff --git a/pkg/storage/agent_trace_store.go b/pkg/storage/agent_trace_store.go new file mode 100644 index 0000000..462ed64 --- /dev/null +++ b/pkg/storage/agent_trace_store.go @@ -0,0 +1,24 @@ +package storage + +import ( + "context" + + "github.com/papercomputeco/tapes/pkg/agenttrace" +) + +// AgentTraceStore defines the interface for persisting and retrieving agent traces. +type AgentTraceStore interface { + CreateAgentTrace(ctx context.Context, trace *agenttrace.AgentTrace) (*agenttrace.AgentTrace, error) + GetAgentTrace(ctx context.Context, id string) (*agenttrace.AgentTrace, error) + QueryAgentTraces(ctx context.Context, query AgentTraceQuery) ([]*agenttrace.AgentTrace, error) + Close() error +} + +// AgentTraceQuery defines query parameters for filtering agent traces. +type AgentTraceQuery struct { + FilePath string + Revision string + ToolName string + Limit int + Offset int +} diff --git a/pkg/storage/ent/agenttrace.go b/pkg/storage/ent/agenttrace.go new file mode 100644 index 0000000..d6fc631 --- /dev/null +++ b/pkg/storage/ent/agenttrace.go @@ -0,0 +1,212 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "encoding/json" + "fmt" + "strings" + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttrace" +) + +// AgentTrace is the model entity for the AgentTrace schema. +type AgentTrace struct { + config `json:"-"` + // ID of the ent. + ID string `json:"id,omitempty"` + // Version holds the value of the "version" field. + Version string `json:"version,omitempty"` + // Timestamp holds the value of the "timestamp" field. + Timestamp string `json:"timestamp,omitempty"` + // VcsType holds the value of the "vcs_type" field. + VcsType string `json:"vcs_type,omitempty"` + // VcsRevision holds the value of the "vcs_revision" field. + VcsRevision string `json:"vcs_revision,omitempty"` + // ToolName holds the value of the "tool_name" field. + ToolName string `json:"tool_name,omitempty"` + // ToolVersion holds the value of the "tool_version" field. + ToolVersion string `json:"tool_version,omitempty"` + // Metadata holds the value of the "metadata" field. + Metadata map[string]interface{} `json:"metadata,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 AgentTraceQuery when eager-loading is set. + Edges AgentTraceEdges `json:"edges"` + selectValues sql.SelectValues +} + +// AgentTraceEdges holds the relations/edges for other nodes in the graph. +type AgentTraceEdges struct { + // Files holds the value of the files edge. + Files []*AgentTraceFile `json:"files,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// FilesOrErr returns the Files value or an error if the edge +// was not loaded in eager-loading. +func (e AgentTraceEdges) FilesOrErr() ([]*AgentTraceFile, error) { + if e.loadedTypes[0] { + return e.Files, nil + } + return nil, &NotLoadedError{edge: "files"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*AgentTrace) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case agenttrace.FieldMetadata: + values[i] = new([]byte) + case agenttrace.FieldID, agenttrace.FieldVersion, agenttrace.FieldTimestamp, agenttrace.FieldVcsType, agenttrace.FieldVcsRevision, agenttrace.FieldToolName, agenttrace.FieldToolVersion: + values[i] = new(sql.NullString) + case agenttrace.FieldCreatedAt: + values[i] = new(sql.NullTime) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the AgentTrace fields. +func (_m *AgentTrace) 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 agenttrace.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 agenttrace.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 agenttrace.FieldTimestamp: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field timestamp", values[i]) + } else if value.Valid { + _m.Timestamp = value.String + } + case agenttrace.FieldVcsType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field vcs_type", values[i]) + } else if value.Valid { + _m.VcsType = value.String + } + case agenttrace.FieldVcsRevision: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field vcs_revision", values[i]) + } else if value.Valid { + _m.VcsRevision = value.String + } + case agenttrace.FieldToolName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field tool_name", values[i]) + } else if value.Valid { + _m.ToolName = value.String + } + case agenttrace.FieldToolVersion: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field tool_version", values[i]) + } else if value.Valid { + _m.ToolVersion = value.String + } + case agenttrace.FieldMetadata: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field metadata", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Metadata); err != nil { + return fmt.Errorf("unmarshal field metadata: %w", err) + } + } + case agenttrace.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 AgentTrace. +// This includes values selected through modifiers, order, etc. +func (_m *AgentTrace) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryFiles queries the "files" edge of the AgentTrace entity. +func (_m *AgentTrace) QueryFiles() *AgentTraceFileQuery { + return NewAgentTraceClient(_m.config).QueryFiles(_m) +} + +// Update returns a builder for updating this AgentTrace. +// Note that you need to call AgentTrace.Unwrap() before calling this method if this AgentTrace +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *AgentTrace) Update() *AgentTraceUpdateOne { + return NewAgentTraceClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the AgentTrace 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 *AgentTrace) Unwrap() *AgentTrace { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: AgentTrace is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *AgentTrace) String() string { + var builder strings.Builder + builder.WriteString("AgentTrace(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("version=") + builder.WriteString(_m.Version) + builder.WriteString(", ") + builder.WriteString("timestamp=") + builder.WriteString(_m.Timestamp) + builder.WriteString(", ") + builder.WriteString("vcs_type=") + builder.WriteString(_m.VcsType) + builder.WriteString(", ") + builder.WriteString("vcs_revision=") + builder.WriteString(_m.VcsRevision) + builder.WriteString(", ") + builder.WriteString("tool_name=") + builder.WriteString(_m.ToolName) + builder.WriteString(", ") + builder.WriteString("tool_version=") + builder.WriteString(_m.ToolVersion) + builder.WriteString(", ") + builder.WriteString("metadata=") + builder.WriteString(fmt.Sprintf("%v", _m.Metadata)) + builder.WriteString(", ") + builder.WriteString("created_at=") + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) + builder.WriteByte(')') + return builder.String() +} + +// AgentTraces is a parsable slice of AgentTrace. +type AgentTraces []*AgentTrace diff --git a/pkg/storage/ent/agenttrace/agenttrace.go b/pkg/storage/ent/agenttrace/agenttrace.go new file mode 100644 index 0000000..8eeb189 --- /dev/null +++ b/pkg/storage/ent/agenttrace/agenttrace.go @@ -0,0 +1,142 @@ +// Code generated by ent, DO NOT EDIT. + +package agenttrace + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the agenttrace type in the database. + Label = "agent_trace" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldVersion holds the string denoting the version field in the database. + FieldVersion = "version" + // FieldTimestamp holds the string denoting the timestamp field in the database. + FieldTimestamp = "timestamp" + // FieldVcsType holds the string denoting the vcs_type field in the database. + FieldVcsType = "vcs_type" + // FieldVcsRevision holds the string denoting the vcs_revision field in the database. + FieldVcsRevision = "vcs_revision" + // FieldToolName holds the string denoting the tool_name field in the database. + FieldToolName = "tool_name" + // FieldToolVersion holds the string denoting the tool_version field in the database. + FieldToolVersion = "tool_version" + // FieldMetadata holds the string denoting the metadata field in the database. + FieldMetadata = "metadata" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // EdgeFiles holds the string denoting the files edge name in mutations. + EdgeFiles = "files" + // Table holds the table name of the agenttrace in the database. + Table = "agent_traces" + // FilesTable is the table that holds the files relation/edge. + FilesTable = "agent_trace_files" + // FilesInverseTable is the table name for the AgentTraceFile entity. + // It exists in this package in order to avoid circular dependency with the "agenttracefile" package. + FilesInverseTable = "agent_trace_files" + // FilesColumn is the table column denoting the files relation/edge. + FilesColumn = "agent_trace_files" +) + +// Columns holds all SQL columns for agenttrace fields. +var Columns = []string{ + FieldID, + FieldVersion, + FieldTimestamp, + FieldVcsType, + FieldVcsRevision, + FieldToolName, + FieldToolVersion, + FieldMetadata, + 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 ( + // VersionValidator is a validator for the "version" field. It is called by the builders before save. + VersionValidator func(string) error + // TimestampValidator is a validator for the "timestamp" field. It is called by the builders before save. + TimestampValidator func(string) error + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time + // IDValidator is a validator for the "id" field. It is called by the builders before save. + IDValidator func(string) error +) + +// OrderOption defines the ordering options for the AgentTrace 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() +} + +// ByVersion orders the results by the version field. +func ByVersion(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldVersion, opts...).ToFunc() +} + +// ByTimestamp orders the results by the timestamp field. +func ByTimestamp(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldTimestamp, opts...).ToFunc() +} + +// ByVcsType orders the results by the vcs_type field. +func ByVcsType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldVcsType, opts...).ToFunc() +} + +// ByVcsRevision orders the results by the vcs_revision field. +func ByVcsRevision(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldVcsRevision, opts...).ToFunc() +} + +// ByToolName orders the results by the tool_name field. +func ByToolName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldToolName, opts...).ToFunc() +} + +// ByToolVersion orders the results by the tool_version field. +func ByToolVersion(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldToolVersion, opts...).ToFunc() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByFilesCount orders the results by files count. +func ByFilesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newFilesStep(), opts...) + } +} + +// ByFiles orders the results by files terms. +func ByFiles(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newFilesStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newFilesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(FilesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, FilesTable, FilesColumn), + ) +} diff --git a/pkg/storage/ent/agenttrace/where.go b/pkg/storage/ent/agenttrace/where.go new file mode 100644 index 0000000..24ce691 --- /dev/null +++ b/pkg/storage/ent/agenttrace/where.go @@ -0,0 +1,619 @@ +// Code generated by ent, DO NOT EDIT. + +package agenttrace + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/papercomputeco/tapes/pkg/storage/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldLTE(FieldID, id)) +} + +// IDEqualFold applies the EqualFold predicate on the ID field. +func IDEqualFold(id string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldEqualFold(FieldID, id)) +} + +// IDContainsFold applies the ContainsFold predicate on the ID field. +func IDContainsFold(id string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldContainsFold(FieldID, id)) +} + +// Version applies equality check predicate on the "version" field. It's identical to VersionEQ. +func Version(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldEQ(FieldVersion, v)) +} + +// Timestamp applies equality check predicate on the "timestamp" field. It's identical to TimestampEQ. +func Timestamp(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldEQ(FieldTimestamp, v)) +} + +// VcsType applies equality check predicate on the "vcs_type" field. It's identical to VcsTypeEQ. +func VcsType(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldEQ(FieldVcsType, v)) +} + +// VcsRevision applies equality check predicate on the "vcs_revision" field. It's identical to VcsRevisionEQ. +func VcsRevision(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldEQ(FieldVcsRevision, v)) +} + +// ToolName applies equality check predicate on the "tool_name" field. It's identical to ToolNameEQ. +func ToolName(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldEQ(FieldToolName, v)) +} + +// ToolVersion applies equality check predicate on the "tool_version" field. It's identical to ToolVersionEQ. +func ToolVersion(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldEQ(FieldToolVersion, v)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldEQ(FieldCreatedAt, v)) +} + +// VersionEQ applies the EQ predicate on the "version" field. +func VersionEQ(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldEQ(FieldVersion, v)) +} + +// VersionNEQ applies the NEQ predicate on the "version" field. +func VersionNEQ(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldNEQ(FieldVersion, v)) +} + +// VersionIn applies the In predicate on the "version" field. +func VersionIn(vs ...string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldIn(FieldVersion, vs...)) +} + +// VersionNotIn applies the NotIn predicate on the "version" field. +func VersionNotIn(vs ...string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldNotIn(FieldVersion, vs...)) +} + +// VersionGT applies the GT predicate on the "version" field. +func VersionGT(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldGT(FieldVersion, v)) +} + +// VersionGTE applies the GTE predicate on the "version" field. +func VersionGTE(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldGTE(FieldVersion, v)) +} + +// VersionLT applies the LT predicate on the "version" field. +func VersionLT(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldLT(FieldVersion, v)) +} + +// VersionLTE applies the LTE predicate on the "version" field. +func VersionLTE(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldLTE(FieldVersion, v)) +} + +// VersionContains applies the Contains predicate on the "version" field. +func VersionContains(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldContains(FieldVersion, v)) +} + +// VersionHasPrefix applies the HasPrefix predicate on the "version" field. +func VersionHasPrefix(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldHasPrefix(FieldVersion, v)) +} + +// VersionHasSuffix applies the HasSuffix predicate on the "version" field. +func VersionHasSuffix(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldHasSuffix(FieldVersion, v)) +} + +// VersionEqualFold applies the EqualFold predicate on the "version" field. +func VersionEqualFold(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldEqualFold(FieldVersion, v)) +} + +// VersionContainsFold applies the ContainsFold predicate on the "version" field. +func VersionContainsFold(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldContainsFold(FieldVersion, v)) +} + +// TimestampEQ applies the EQ predicate on the "timestamp" field. +func TimestampEQ(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldEQ(FieldTimestamp, v)) +} + +// TimestampNEQ applies the NEQ predicate on the "timestamp" field. +func TimestampNEQ(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldNEQ(FieldTimestamp, v)) +} + +// TimestampIn applies the In predicate on the "timestamp" field. +func TimestampIn(vs ...string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldIn(FieldTimestamp, vs...)) +} + +// TimestampNotIn applies the NotIn predicate on the "timestamp" field. +func TimestampNotIn(vs ...string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldNotIn(FieldTimestamp, vs...)) +} + +// TimestampGT applies the GT predicate on the "timestamp" field. +func TimestampGT(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldGT(FieldTimestamp, v)) +} + +// TimestampGTE applies the GTE predicate on the "timestamp" field. +func TimestampGTE(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldGTE(FieldTimestamp, v)) +} + +// TimestampLT applies the LT predicate on the "timestamp" field. +func TimestampLT(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldLT(FieldTimestamp, v)) +} + +// TimestampLTE applies the LTE predicate on the "timestamp" field. +func TimestampLTE(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldLTE(FieldTimestamp, v)) +} + +// TimestampContains applies the Contains predicate on the "timestamp" field. +func TimestampContains(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldContains(FieldTimestamp, v)) +} + +// TimestampHasPrefix applies the HasPrefix predicate on the "timestamp" field. +func TimestampHasPrefix(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldHasPrefix(FieldTimestamp, v)) +} + +// TimestampHasSuffix applies the HasSuffix predicate on the "timestamp" field. +func TimestampHasSuffix(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldHasSuffix(FieldTimestamp, v)) +} + +// TimestampEqualFold applies the EqualFold predicate on the "timestamp" field. +func TimestampEqualFold(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldEqualFold(FieldTimestamp, v)) +} + +// TimestampContainsFold applies the ContainsFold predicate on the "timestamp" field. +func TimestampContainsFold(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldContainsFold(FieldTimestamp, v)) +} + +// VcsTypeEQ applies the EQ predicate on the "vcs_type" field. +func VcsTypeEQ(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldEQ(FieldVcsType, v)) +} + +// VcsTypeNEQ applies the NEQ predicate on the "vcs_type" field. +func VcsTypeNEQ(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldNEQ(FieldVcsType, v)) +} + +// VcsTypeIn applies the In predicate on the "vcs_type" field. +func VcsTypeIn(vs ...string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldIn(FieldVcsType, vs...)) +} + +// VcsTypeNotIn applies the NotIn predicate on the "vcs_type" field. +func VcsTypeNotIn(vs ...string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldNotIn(FieldVcsType, vs...)) +} + +// VcsTypeGT applies the GT predicate on the "vcs_type" field. +func VcsTypeGT(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldGT(FieldVcsType, v)) +} + +// VcsTypeGTE applies the GTE predicate on the "vcs_type" field. +func VcsTypeGTE(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldGTE(FieldVcsType, v)) +} + +// VcsTypeLT applies the LT predicate on the "vcs_type" field. +func VcsTypeLT(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldLT(FieldVcsType, v)) +} + +// VcsTypeLTE applies the LTE predicate on the "vcs_type" field. +func VcsTypeLTE(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldLTE(FieldVcsType, v)) +} + +// VcsTypeContains applies the Contains predicate on the "vcs_type" field. +func VcsTypeContains(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldContains(FieldVcsType, v)) +} + +// VcsTypeHasPrefix applies the HasPrefix predicate on the "vcs_type" field. +func VcsTypeHasPrefix(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldHasPrefix(FieldVcsType, v)) +} + +// VcsTypeHasSuffix applies the HasSuffix predicate on the "vcs_type" field. +func VcsTypeHasSuffix(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldHasSuffix(FieldVcsType, v)) +} + +// VcsTypeIsNil applies the IsNil predicate on the "vcs_type" field. +func VcsTypeIsNil() predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldIsNull(FieldVcsType)) +} + +// VcsTypeNotNil applies the NotNil predicate on the "vcs_type" field. +func VcsTypeNotNil() predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldNotNull(FieldVcsType)) +} + +// VcsTypeEqualFold applies the EqualFold predicate on the "vcs_type" field. +func VcsTypeEqualFold(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldEqualFold(FieldVcsType, v)) +} + +// VcsTypeContainsFold applies the ContainsFold predicate on the "vcs_type" field. +func VcsTypeContainsFold(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldContainsFold(FieldVcsType, v)) +} + +// VcsRevisionEQ applies the EQ predicate on the "vcs_revision" field. +func VcsRevisionEQ(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldEQ(FieldVcsRevision, v)) +} + +// VcsRevisionNEQ applies the NEQ predicate on the "vcs_revision" field. +func VcsRevisionNEQ(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldNEQ(FieldVcsRevision, v)) +} + +// VcsRevisionIn applies the In predicate on the "vcs_revision" field. +func VcsRevisionIn(vs ...string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldIn(FieldVcsRevision, vs...)) +} + +// VcsRevisionNotIn applies the NotIn predicate on the "vcs_revision" field. +func VcsRevisionNotIn(vs ...string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldNotIn(FieldVcsRevision, vs...)) +} + +// VcsRevisionGT applies the GT predicate on the "vcs_revision" field. +func VcsRevisionGT(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldGT(FieldVcsRevision, v)) +} + +// VcsRevisionGTE applies the GTE predicate on the "vcs_revision" field. +func VcsRevisionGTE(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldGTE(FieldVcsRevision, v)) +} + +// VcsRevisionLT applies the LT predicate on the "vcs_revision" field. +func VcsRevisionLT(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldLT(FieldVcsRevision, v)) +} + +// VcsRevisionLTE applies the LTE predicate on the "vcs_revision" field. +func VcsRevisionLTE(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldLTE(FieldVcsRevision, v)) +} + +// VcsRevisionContains applies the Contains predicate on the "vcs_revision" field. +func VcsRevisionContains(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldContains(FieldVcsRevision, v)) +} + +// VcsRevisionHasPrefix applies the HasPrefix predicate on the "vcs_revision" field. +func VcsRevisionHasPrefix(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldHasPrefix(FieldVcsRevision, v)) +} + +// VcsRevisionHasSuffix applies the HasSuffix predicate on the "vcs_revision" field. +func VcsRevisionHasSuffix(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldHasSuffix(FieldVcsRevision, v)) +} + +// VcsRevisionIsNil applies the IsNil predicate on the "vcs_revision" field. +func VcsRevisionIsNil() predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldIsNull(FieldVcsRevision)) +} + +// VcsRevisionNotNil applies the NotNil predicate on the "vcs_revision" field. +func VcsRevisionNotNil() predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldNotNull(FieldVcsRevision)) +} + +// VcsRevisionEqualFold applies the EqualFold predicate on the "vcs_revision" field. +func VcsRevisionEqualFold(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldEqualFold(FieldVcsRevision, v)) +} + +// VcsRevisionContainsFold applies the ContainsFold predicate on the "vcs_revision" field. +func VcsRevisionContainsFold(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldContainsFold(FieldVcsRevision, v)) +} + +// ToolNameEQ applies the EQ predicate on the "tool_name" field. +func ToolNameEQ(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldEQ(FieldToolName, v)) +} + +// ToolNameNEQ applies the NEQ predicate on the "tool_name" field. +func ToolNameNEQ(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldNEQ(FieldToolName, v)) +} + +// ToolNameIn applies the In predicate on the "tool_name" field. +func ToolNameIn(vs ...string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldIn(FieldToolName, vs...)) +} + +// ToolNameNotIn applies the NotIn predicate on the "tool_name" field. +func ToolNameNotIn(vs ...string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldNotIn(FieldToolName, vs...)) +} + +// ToolNameGT applies the GT predicate on the "tool_name" field. +func ToolNameGT(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldGT(FieldToolName, v)) +} + +// ToolNameGTE applies the GTE predicate on the "tool_name" field. +func ToolNameGTE(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldGTE(FieldToolName, v)) +} + +// ToolNameLT applies the LT predicate on the "tool_name" field. +func ToolNameLT(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldLT(FieldToolName, v)) +} + +// ToolNameLTE applies the LTE predicate on the "tool_name" field. +func ToolNameLTE(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldLTE(FieldToolName, v)) +} + +// ToolNameContains applies the Contains predicate on the "tool_name" field. +func ToolNameContains(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldContains(FieldToolName, v)) +} + +// ToolNameHasPrefix applies the HasPrefix predicate on the "tool_name" field. +func ToolNameHasPrefix(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldHasPrefix(FieldToolName, v)) +} + +// ToolNameHasSuffix applies the HasSuffix predicate on the "tool_name" field. +func ToolNameHasSuffix(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldHasSuffix(FieldToolName, v)) +} + +// ToolNameIsNil applies the IsNil predicate on the "tool_name" field. +func ToolNameIsNil() predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldIsNull(FieldToolName)) +} + +// ToolNameNotNil applies the NotNil predicate on the "tool_name" field. +func ToolNameNotNil() predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldNotNull(FieldToolName)) +} + +// ToolNameEqualFold applies the EqualFold predicate on the "tool_name" field. +func ToolNameEqualFold(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldEqualFold(FieldToolName, v)) +} + +// ToolNameContainsFold applies the ContainsFold predicate on the "tool_name" field. +func ToolNameContainsFold(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldContainsFold(FieldToolName, v)) +} + +// ToolVersionEQ applies the EQ predicate on the "tool_version" field. +func ToolVersionEQ(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldEQ(FieldToolVersion, v)) +} + +// ToolVersionNEQ applies the NEQ predicate on the "tool_version" field. +func ToolVersionNEQ(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldNEQ(FieldToolVersion, v)) +} + +// ToolVersionIn applies the In predicate on the "tool_version" field. +func ToolVersionIn(vs ...string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldIn(FieldToolVersion, vs...)) +} + +// ToolVersionNotIn applies the NotIn predicate on the "tool_version" field. +func ToolVersionNotIn(vs ...string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldNotIn(FieldToolVersion, vs...)) +} + +// ToolVersionGT applies the GT predicate on the "tool_version" field. +func ToolVersionGT(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldGT(FieldToolVersion, v)) +} + +// ToolVersionGTE applies the GTE predicate on the "tool_version" field. +func ToolVersionGTE(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldGTE(FieldToolVersion, v)) +} + +// ToolVersionLT applies the LT predicate on the "tool_version" field. +func ToolVersionLT(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldLT(FieldToolVersion, v)) +} + +// ToolVersionLTE applies the LTE predicate on the "tool_version" field. +func ToolVersionLTE(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldLTE(FieldToolVersion, v)) +} + +// ToolVersionContains applies the Contains predicate on the "tool_version" field. +func ToolVersionContains(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldContains(FieldToolVersion, v)) +} + +// ToolVersionHasPrefix applies the HasPrefix predicate on the "tool_version" field. +func ToolVersionHasPrefix(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldHasPrefix(FieldToolVersion, v)) +} + +// ToolVersionHasSuffix applies the HasSuffix predicate on the "tool_version" field. +func ToolVersionHasSuffix(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldHasSuffix(FieldToolVersion, v)) +} + +// ToolVersionIsNil applies the IsNil predicate on the "tool_version" field. +func ToolVersionIsNil() predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldIsNull(FieldToolVersion)) +} + +// ToolVersionNotNil applies the NotNil predicate on the "tool_version" field. +func ToolVersionNotNil() predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldNotNull(FieldToolVersion)) +} + +// ToolVersionEqualFold applies the EqualFold predicate on the "tool_version" field. +func ToolVersionEqualFold(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldEqualFold(FieldToolVersion, v)) +} + +// ToolVersionContainsFold applies the ContainsFold predicate on the "tool_version" field. +func ToolVersionContainsFold(v string) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldContainsFold(FieldToolVersion, v)) +} + +// MetadataIsNil applies the IsNil predicate on the "metadata" field. +func MetadataIsNil() predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldIsNull(FieldMetadata)) +} + +// MetadataNotNil applies the NotNil predicate on the "metadata" field. +func MetadataNotNil() predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldNotNull(FieldMetadata)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.AgentTrace { + return predicate.AgentTrace(sql.FieldLTE(FieldCreatedAt, v)) +} + +// HasFiles applies the HasEdge predicate on the "files" edge. +func HasFiles() predicate.AgentTrace { + return predicate.AgentTrace(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, FilesTable, FilesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasFilesWith applies the HasEdge predicate on the "files" edge with a given conditions (other predicates). +func HasFilesWith(preds ...predicate.AgentTraceFile) predicate.AgentTrace { + return predicate.AgentTrace(func(s *sql.Selector) { + step := newFilesStep() + 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.AgentTrace) predicate.AgentTrace { + return predicate.AgentTrace(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.AgentTrace) predicate.AgentTrace { + return predicate.AgentTrace(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.AgentTrace) predicate.AgentTrace { + return predicate.AgentTrace(sql.NotPredicates(p)) +} diff --git a/pkg/storage/ent/agenttrace_create.go b/pkg/storage/ent/agenttrace_create.go new file mode 100644 index 0000000..beca4bb --- /dev/null +++ b/pkg/storage/ent/agenttrace_create.go @@ -0,0 +1,368 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttrace" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttracefile" +) + +// AgentTraceCreate is the builder for creating a AgentTrace entity. +type AgentTraceCreate struct { + config + mutation *AgentTraceMutation + hooks []Hook +} + +// SetVersion sets the "version" field. +func (_c *AgentTraceCreate) SetVersion(v string) *AgentTraceCreate { + _c.mutation.SetVersion(v) + return _c +} + +// SetTimestamp sets the "timestamp" field. +func (_c *AgentTraceCreate) SetTimestamp(v string) *AgentTraceCreate { + _c.mutation.SetTimestamp(v) + return _c +} + +// SetVcsType sets the "vcs_type" field. +func (_c *AgentTraceCreate) SetVcsType(v string) *AgentTraceCreate { + _c.mutation.SetVcsType(v) + return _c +} + +// SetNillableVcsType sets the "vcs_type" field if the given value is not nil. +func (_c *AgentTraceCreate) SetNillableVcsType(v *string) *AgentTraceCreate { + if v != nil { + _c.SetVcsType(*v) + } + return _c +} + +// SetVcsRevision sets the "vcs_revision" field. +func (_c *AgentTraceCreate) SetVcsRevision(v string) *AgentTraceCreate { + _c.mutation.SetVcsRevision(v) + return _c +} + +// SetNillableVcsRevision sets the "vcs_revision" field if the given value is not nil. +func (_c *AgentTraceCreate) SetNillableVcsRevision(v *string) *AgentTraceCreate { + if v != nil { + _c.SetVcsRevision(*v) + } + return _c +} + +// SetToolName sets the "tool_name" field. +func (_c *AgentTraceCreate) SetToolName(v string) *AgentTraceCreate { + _c.mutation.SetToolName(v) + return _c +} + +// SetNillableToolName sets the "tool_name" field if the given value is not nil. +func (_c *AgentTraceCreate) SetNillableToolName(v *string) *AgentTraceCreate { + if v != nil { + _c.SetToolName(*v) + } + return _c +} + +// SetToolVersion sets the "tool_version" field. +func (_c *AgentTraceCreate) SetToolVersion(v string) *AgentTraceCreate { + _c.mutation.SetToolVersion(v) + return _c +} + +// SetNillableToolVersion sets the "tool_version" field if the given value is not nil. +func (_c *AgentTraceCreate) SetNillableToolVersion(v *string) *AgentTraceCreate { + if v != nil { + _c.SetToolVersion(*v) + } + return _c +} + +// SetMetadata sets the "metadata" field. +func (_c *AgentTraceCreate) SetMetadata(v map[string]interface{}) *AgentTraceCreate { + _c.mutation.SetMetadata(v) + return _c +} + +// SetCreatedAt sets the "created_at" field. +func (_c *AgentTraceCreate) SetCreatedAt(v time.Time) *AgentTraceCreate { + _c.mutation.SetCreatedAt(v) + return _c +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (_c *AgentTraceCreate) SetNillableCreatedAt(v *time.Time) *AgentTraceCreate { + if v != nil { + _c.SetCreatedAt(*v) + } + return _c +} + +// SetID sets the "id" field. +func (_c *AgentTraceCreate) SetID(v string) *AgentTraceCreate { + _c.mutation.SetID(v) + return _c +} + +// AddFileIDs adds the "files" edge to the AgentTraceFile entity by IDs. +func (_c *AgentTraceCreate) AddFileIDs(ids ...int) *AgentTraceCreate { + _c.mutation.AddFileIDs(ids...) + return _c +} + +// AddFiles adds the "files" edges to the AgentTraceFile entity. +func (_c *AgentTraceCreate) AddFiles(v ...*AgentTraceFile) *AgentTraceCreate { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddFileIDs(ids...) +} + +// Mutation returns the AgentTraceMutation object of the builder. +func (_c *AgentTraceCreate) Mutation() *AgentTraceMutation { + return _c.mutation +} + +// Save creates the AgentTrace in the database. +func (_c *AgentTraceCreate) Save(ctx context.Context) (*AgentTrace, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *AgentTraceCreate) SaveX(ctx context.Context) *AgentTrace { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *AgentTraceCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *AgentTraceCreate) 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 *AgentTraceCreate) defaults() { + if _, ok := _c.mutation.CreatedAt(); !ok { + v := agenttrace.DefaultCreatedAt() + _c.mutation.SetCreatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *AgentTraceCreate) check() error { + if _, ok := _c.mutation.Version(); !ok { + return &ValidationError{Name: "version", err: errors.New(`ent: missing required field "AgentTrace.version"`)} + } + if v, ok := _c.mutation.Version(); ok { + if err := agenttrace.VersionValidator(v); err != nil { + return &ValidationError{Name: "version", err: fmt.Errorf(`ent: validator failed for field "AgentTrace.version": %w`, err)} + } + } + if _, ok := _c.mutation.Timestamp(); !ok { + return &ValidationError{Name: "timestamp", err: errors.New(`ent: missing required field "AgentTrace.timestamp"`)} + } + if v, ok := _c.mutation.Timestamp(); ok { + if err := agenttrace.TimestampValidator(v); err != nil { + return &ValidationError{Name: "timestamp", err: fmt.Errorf(`ent: validator failed for field "AgentTrace.timestamp": %w`, err)} + } + } + if _, ok := _c.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "AgentTrace.created_at"`)} + } + if v, ok := _c.mutation.ID(); ok { + if err := agenttrace.IDValidator(v); err != nil { + return &ValidationError{Name: "id", err: fmt.Errorf(`ent: validator failed for field "AgentTrace.id": %w`, err)} + } + } + return nil +} + +func (_c *AgentTraceCreate) sqlSave(ctx context.Context) (*AgentTrace, 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 AgentTrace.ID type: %T", _spec.ID.Value) + } + } + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *AgentTraceCreate) createSpec() (*AgentTrace, *sqlgraph.CreateSpec) { + var ( + _node = &AgentTrace{config: _c.config} + _spec = sqlgraph.NewCreateSpec(agenttrace.Table, sqlgraph.NewFieldSpec(agenttrace.FieldID, field.TypeString)) + ) + if id, ok := _c.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := _c.mutation.Version(); ok { + _spec.SetField(agenttrace.FieldVersion, field.TypeString, value) + _node.Version = value + } + if value, ok := _c.mutation.Timestamp(); ok { + _spec.SetField(agenttrace.FieldTimestamp, field.TypeString, value) + _node.Timestamp = value + } + if value, ok := _c.mutation.VcsType(); ok { + _spec.SetField(agenttrace.FieldVcsType, field.TypeString, value) + _node.VcsType = value + } + if value, ok := _c.mutation.VcsRevision(); ok { + _spec.SetField(agenttrace.FieldVcsRevision, field.TypeString, value) + _node.VcsRevision = value + } + if value, ok := _c.mutation.ToolName(); ok { + _spec.SetField(agenttrace.FieldToolName, field.TypeString, value) + _node.ToolName = value + } + if value, ok := _c.mutation.ToolVersion(); ok { + _spec.SetField(agenttrace.FieldToolVersion, field.TypeString, value) + _node.ToolVersion = value + } + if value, ok := _c.mutation.Metadata(); ok { + _spec.SetField(agenttrace.FieldMetadata, field.TypeJSON, value) + _node.Metadata = value + } + if value, ok := _c.mutation.CreatedAt(); ok { + _spec.SetField(agenttrace.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if nodes := _c.mutation.FilesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agenttrace.FilesTable, + Columns: []string{agenttrace.FilesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttracefile.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// AgentTraceCreateBulk is the builder for creating many AgentTrace entities in bulk. +type AgentTraceCreateBulk struct { + config + err error + builders []*AgentTraceCreate +} + +// Save creates the AgentTrace entities in the database. +func (_c *AgentTraceCreateBulk) Save(ctx context.Context) ([]*AgentTrace, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*AgentTrace, 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.(*AgentTraceMutation) + 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} + // 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 *AgentTraceCreateBulk) SaveX(ctx context.Context) []*AgentTrace { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *AgentTraceCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *AgentTraceCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/pkg/storage/ent/agenttrace_delete.go b/pkg/storage/ent/agenttrace_delete.go new file mode 100644 index 0000000..68348ef --- /dev/null +++ b/pkg/storage/ent/agenttrace_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttrace" + "github.com/papercomputeco/tapes/pkg/storage/ent/predicate" +) + +// AgentTraceDelete is the builder for deleting a AgentTrace entity. +type AgentTraceDelete struct { + config + hooks []Hook + mutation *AgentTraceMutation +} + +// Where appends a list predicates to the AgentTraceDelete builder. +func (_d *AgentTraceDelete) Where(ps ...predicate.AgentTrace) *AgentTraceDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *AgentTraceDelete) 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 *AgentTraceDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *AgentTraceDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(agenttrace.Table, sqlgraph.NewFieldSpec(agenttrace.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 +} + +// AgentTraceDeleteOne is the builder for deleting a single AgentTrace entity. +type AgentTraceDeleteOne struct { + _d *AgentTraceDelete +} + +// Where appends a list predicates to the AgentTraceDelete builder. +func (_d *AgentTraceDeleteOne) Where(ps ...predicate.AgentTrace) *AgentTraceDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *AgentTraceDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{agenttrace.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *AgentTraceDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/pkg/storage/ent/agenttrace_query.go b/pkg/storage/ent/agenttrace_query.go new file mode 100644 index 0000000..0884b75 --- /dev/null +++ b/pkg/storage/ent/agenttrace_query.go @@ -0,0 +1,607 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "database/sql/driver" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttrace" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttracefile" + "github.com/papercomputeco/tapes/pkg/storage/ent/predicate" +) + +// AgentTraceQuery is the builder for querying AgentTrace entities. +type AgentTraceQuery struct { + config + ctx *QueryContext + order []agenttrace.OrderOption + inters []Interceptor + predicates []predicate.AgentTrace + withFiles *AgentTraceFileQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the AgentTraceQuery builder. +func (_q *AgentTraceQuery) Where(ps ...predicate.AgentTrace) *AgentTraceQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *AgentTraceQuery) Limit(limit int) *AgentTraceQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *AgentTraceQuery) Offset(offset int) *AgentTraceQuery { + _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 *AgentTraceQuery) Unique(unique bool) *AgentTraceQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *AgentTraceQuery) Order(o ...agenttrace.OrderOption) *AgentTraceQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryFiles chains the current query on the "files" edge. +func (_q *AgentTraceQuery) QueryFiles() *AgentTraceFileQuery { + query := (&AgentTraceFileClient{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(agenttrace.Table, agenttrace.FieldID, selector), + sqlgraph.To(agenttracefile.Table, agenttracefile.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, agenttrace.FilesTable, agenttrace.FilesColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first AgentTrace entity from the query. +// Returns a *NotFoundError when no AgentTrace was found. +func (_q *AgentTraceQuery) First(ctx context.Context) (*AgentTrace, 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{agenttrace.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *AgentTraceQuery) FirstX(ctx context.Context) *AgentTrace { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first AgentTrace ID from the query. +// Returns a *NotFoundError when no AgentTrace ID was found. +func (_q *AgentTraceQuery) 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{agenttrace.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *AgentTraceQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single AgentTrace entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one AgentTrace entity is found. +// Returns a *NotFoundError when no AgentTrace entities are found. +func (_q *AgentTraceQuery) Only(ctx context.Context) (*AgentTrace, 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{agenttrace.Label} + default: + return nil, &NotSingularError{agenttrace.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *AgentTraceQuery) OnlyX(ctx context.Context) *AgentTrace { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only AgentTrace ID in the query. +// Returns a *NotSingularError when more than one AgentTrace ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *AgentTraceQuery) 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{agenttrace.Label} + default: + err = &NotSingularError{agenttrace.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *AgentTraceQuery) 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 AgentTraces. +func (_q *AgentTraceQuery) All(ctx context.Context) ([]*AgentTrace, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*AgentTrace, *AgentTraceQuery]() + return withInterceptors[[]*AgentTrace](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *AgentTraceQuery) AllX(ctx context.Context) []*AgentTrace { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of AgentTrace IDs. +func (_q *AgentTraceQuery) 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(agenttrace.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *AgentTraceQuery) 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 *AgentTraceQuery) 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[*AgentTraceQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *AgentTraceQuery) 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 *AgentTraceQuery) 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("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *AgentTraceQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the AgentTraceQuery 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 *AgentTraceQuery) Clone() *AgentTraceQuery { + if _q == nil { + return nil + } + return &AgentTraceQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]agenttrace.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.AgentTrace{}, _q.predicates...), + withFiles: _q.withFiles.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithFiles tells the query-builder to eager-load the nodes that are connected to +// the "files" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *AgentTraceQuery) WithFiles(opts ...func(*AgentTraceFileQuery)) *AgentTraceQuery { + query := (&AgentTraceFileClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withFiles = 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 { +// Version string `json:"version,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.AgentTrace.Query(). +// GroupBy(agenttrace.FieldVersion). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *AgentTraceQuery) GroupBy(field string, fields ...string) *AgentTraceGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &AgentTraceGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = agenttrace.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 { +// Version string `json:"version,omitempty"` +// } +// +// client.AgentTrace.Query(). +// Select(agenttrace.FieldVersion). +// Scan(ctx, &v) +func (_q *AgentTraceQuery) Select(fields ...string) *AgentTraceSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &AgentTraceSelect{AgentTraceQuery: _q} + sbuild.label = agenttrace.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a AgentTraceSelect configured with the given aggregations. +func (_q *AgentTraceQuery) Aggregate(fns ...AggregateFunc) *AgentTraceSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *AgentTraceQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !agenttrace.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: 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 *AgentTraceQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AgentTrace, error) { + var ( + nodes = []*AgentTrace{} + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withFiles != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*AgentTrace).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &AgentTrace{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withFiles; query != nil { + if err := _q.loadFiles(ctx, query, nodes, + func(n *AgentTrace) { n.Edges.Files = []*AgentTraceFile{} }, + func(n *AgentTrace, e *AgentTraceFile) { n.Edges.Files = append(n.Edges.Files, e) }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *AgentTraceQuery) loadFiles(ctx context.Context, query *AgentTraceFileQuery, nodes []*AgentTrace, init func(*AgentTrace), assign func(*AgentTrace, *AgentTraceFile)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[string]*AgentTrace) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + query.withFKs = true + query.Where(predicate.AgentTraceFile(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(agenttrace.FilesColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.agent_trace_files + if fk == nil { + return fmt.Errorf(`foreign-key "agent_trace_files" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "agent_trace_files" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (_q *AgentTraceQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _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 *AgentTraceQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(agenttrace.Table, agenttrace.Columns, sqlgraph.NewFieldSpec(agenttrace.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, agenttrace.FieldID) + for i := range fields { + if fields[i] != agenttrace.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + 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 *AgentTraceQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(agenttrace.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = agenttrace.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 _, 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 +} + +// AgentTraceGroupBy is the group-by builder for AgentTrace entities. +type AgentTraceGroupBy struct { + selector + build *AgentTraceQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *AgentTraceGroupBy) Aggregate(fns ...AggregateFunc) *AgentTraceGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *AgentTraceGroupBy) 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[*AgentTraceQuery, *AgentTraceGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *AgentTraceGroupBy) sqlScan(ctx context.Context, root *AgentTraceQuery, 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) +} + +// AgentTraceSelect is the builder for selecting fields of AgentTrace entities. +type AgentTraceSelect struct { + *AgentTraceQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *AgentTraceSelect) Aggregate(fns ...AggregateFunc) *AgentTraceSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *AgentTraceSelect) 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[*AgentTraceQuery, *AgentTraceSelect](ctx, _s.AgentTraceQuery, _s, _s.inters, v) +} + +func (_s *AgentTraceSelect) sqlScan(ctx context.Context, root *AgentTraceQuery, 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) +} diff --git a/pkg/storage/ent/agenttrace_update.go b/pkg/storage/ent/agenttrace_update.go new file mode 100644 index 0000000..9817beb --- /dev/null +++ b/pkg/storage/ent/agenttrace_update.go @@ -0,0 +1,686 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttrace" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttracefile" + "github.com/papercomputeco/tapes/pkg/storage/ent/predicate" +) + +// AgentTraceUpdate is the builder for updating AgentTrace entities. +type AgentTraceUpdate struct { + config + hooks []Hook + mutation *AgentTraceMutation +} + +// Where appends a list predicates to the AgentTraceUpdate builder. +func (_u *AgentTraceUpdate) Where(ps ...predicate.AgentTrace) *AgentTraceUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetVersion sets the "version" field. +func (_u *AgentTraceUpdate) SetVersion(v string) *AgentTraceUpdate { + _u.mutation.SetVersion(v) + return _u +} + +// SetNillableVersion sets the "version" field if the given value is not nil. +func (_u *AgentTraceUpdate) SetNillableVersion(v *string) *AgentTraceUpdate { + if v != nil { + _u.SetVersion(*v) + } + return _u +} + +// SetTimestamp sets the "timestamp" field. +func (_u *AgentTraceUpdate) SetTimestamp(v string) *AgentTraceUpdate { + _u.mutation.SetTimestamp(v) + return _u +} + +// SetNillableTimestamp sets the "timestamp" field if the given value is not nil. +func (_u *AgentTraceUpdate) SetNillableTimestamp(v *string) *AgentTraceUpdate { + if v != nil { + _u.SetTimestamp(*v) + } + return _u +} + +// SetVcsType sets the "vcs_type" field. +func (_u *AgentTraceUpdate) SetVcsType(v string) *AgentTraceUpdate { + _u.mutation.SetVcsType(v) + return _u +} + +// SetNillableVcsType sets the "vcs_type" field if the given value is not nil. +func (_u *AgentTraceUpdate) SetNillableVcsType(v *string) *AgentTraceUpdate { + if v != nil { + _u.SetVcsType(*v) + } + return _u +} + +// ClearVcsType clears the value of the "vcs_type" field. +func (_u *AgentTraceUpdate) ClearVcsType() *AgentTraceUpdate { + _u.mutation.ClearVcsType() + return _u +} + +// SetVcsRevision sets the "vcs_revision" field. +func (_u *AgentTraceUpdate) SetVcsRevision(v string) *AgentTraceUpdate { + _u.mutation.SetVcsRevision(v) + return _u +} + +// SetNillableVcsRevision sets the "vcs_revision" field if the given value is not nil. +func (_u *AgentTraceUpdate) SetNillableVcsRevision(v *string) *AgentTraceUpdate { + if v != nil { + _u.SetVcsRevision(*v) + } + return _u +} + +// ClearVcsRevision clears the value of the "vcs_revision" field. +func (_u *AgentTraceUpdate) ClearVcsRevision() *AgentTraceUpdate { + _u.mutation.ClearVcsRevision() + return _u +} + +// SetToolName sets the "tool_name" field. +func (_u *AgentTraceUpdate) SetToolName(v string) *AgentTraceUpdate { + _u.mutation.SetToolName(v) + return _u +} + +// SetNillableToolName sets the "tool_name" field if the given value is not nil. +func (_u *AgentTraceUpdate) SetNillableToolName(v *string) *AgentTraceUpdate { + if v != nil { + _u.SetToolName(*v) + } + return _u +} + +// ClearToolName clears the value of the "tool_name" field. +func (_u *AgentTraceUpdate) ClearToolName() *AgentTraceUpdate { + _u.mutation.ClearToolName() + return _u +} + +// SetToolVersion sets the "tool_version" field. +func (_u *AgentTraceUpdate) SetToolVersion(v string) *AgentTraceUpdate { + _u.mutation.SetToolVersion(v) + return _u +} + +// SetNillableToolVersion sets the "tool_version" field if the given value is not nil. +func (_u *AgentTraceUpdate) SetNillableToolVersion(v *string) *AgentTraceUpdate { + if v != nil { + _u.SetToolVersion(*v) + } + return _u +} + +// ClearToolVersion clears the value of the "tool_version" field. +func (_u *AgentTraceUpdate) ClearToolVersion() *AgentTraceUpdate { + _u.mutation.ClearToolVersion() + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *AgentTraceUpdate) SetMetadata(v map[string]interface{}) *AgentTraceUpdate { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *AgentTraceUpdate) ClearMetadata() *AgentTraceUpdate { + _u.mutation.ClearMetadata() + return _u +} + +// AddFileIDs adds the "files" edge to the AgentTraceFile entity by IDs. +func (_u *AgentTraceUpdate) AddFileIDs(ids ...int) *AgentTraceUpdate { + _u.mutation.AddFileIDs(ids...) + return _u +} + +// AddFiles adds the "files" edges to the AgentTraceFile entity. +func (_u *AgentTraceUpdate) AddFiles(v ...*AgentTraceFile) *AgentTraceUpdate { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddFileIDs(ids...) +} + +// Mutation returns the AgentTraceMutation object of the builder. +func (_u *AgentTraceUpdate) Mutation() *AgentTraceMutation { + return _u.mutation +} + +// ClearFiles clears all "files" edges to the AgentTraceFile entity. +func (_u *AgentTraceUpdate) ClearFiles() *AgentTraceUpdate { + _u.mutation.ClearFiles() + return _u +} + +// RemoveFileIDs removes the "files" edge to AgentTraceFile entities by IDs. +func (_u *AgentTraceUpdate) RemoveFileIDs(ids ...int) *AgentTraceUpdate { + _u.mutation.RemoveFileIDs(ids...) + return _u +} + +// RemoveFiles removes "files" edges to AgentTraceFile entities. +func (_u *AgentTraceUpdate) RemoveFiles(v ...*AgentTraceFile) *AgentTraceUpdate { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveFileIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *AgentTraceUpdate) 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 *AgentTraceUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *AgentTraceUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *AgentTraceUpdate) 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 *AgentTraceUpdate) check() error { + if v, ok := _u.mutation.Version(); ok { + if err := agenttrace.VersionValidator(v); err != nil { + return &ValidationError{Name: "version", err: fmt.Errorf(`ent: validator failed for field "AgentTrace.version": %w`, err)} + } + } + if v, ok := _u.mutation.Timestamp(); ok { + if err := agenttrace.TimestampValidator(v); err != nil { + return &ValidationError{Name: "timestamp", err: fmt.Errorf(`ent: validator failed for field "AgentTrace.timestamp": %w`, err)} + } + } + return nil +} + +func (_u *AgentTraceUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(agenttrace.Table, agenttrace.Columns, sqlgraph.NewFieldSpec(agenttrace.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.Version(); ok { + _spec.SetField(agenttrace.FieldVersion, field.TypeString, value) + } + if value, ok := _u.mutation.Timestamp(); ok { + _spec.SetField(agenttrace.FieldTimestamp, field.TypeString, value) + } + if value, ok := _u.mutation.VcsType(); ok { + _spec.SetField(agenttrace.FieldVcsType, field.TypeString, value) + } + if _u.mutation.VcsTypeCleared() { + _spec.ClearField(agenttrace.FieldVcsType, field.TypeString) + } + if value, ok := _u.mutation.VcsRevision(); ok { + _spec.SetField(agenttrace.FieldVcsRevision, field.TypeString, value) + } + if _u.mutation.VcsRevisionCleared() { + _spec.ClearField(agenttrace.FieldVcsRevision, field.TypeString) + } + if value, ok := _u.mutation.ToolName(); ok { + _spec.SetField(agenttrace.FieldToolName, field.TypeString, value) + } + if _u.mutation.ToolNameCleared() { + _spec.ClearField(agenttrace.FieldToolName, field.TypeString) + } + if value, ok := _u.mutation.ToolVersion(); ok { + _spec.SetField(agenttrace.FieldToolVersion, field.TypeString, value) + } + if _u.mutation.ToolVersionCleared() { + _spec.ClearField(agenttrace.FieldToolVersion, field.TypeString) + } + if value, ok := _u.mutation.Metadata(); ok { + _spec.SetField(agenttrace.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(agenttrace.FieldMetadata, field.TypeJSON) + } + if _u.mutation.FilesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agenttrace.FilesTable, + Columns: []string{agenttrace.FilesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttracefile.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedFilesIDs(); len(nodes) > 0 && !_u.mutation.FilesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agenttrace.FilesTable, + Columns: []string{agenttrace.FilesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttracefile.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.FilesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agenttrace.FilesTable, + Columns: []string{agenttrace.FilesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttracefile.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{agenttrace.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// AgentTraceUpdateOne is the builder for updating a single AgentTrace entity. +type AgentTraceUpdateOne struct { + config + fields []string + hooks []Hook + mutation *AgentTraceMutation +} + +// SetVersion sets the "version" field. +func (_u *AgentTraceUpdateOne) SetVersion(v string) *AgentTraceUpdateOne { + _u.mutation.SetVersion(v) + return _u +} + +// SetNillableVersion sets the "version" field if the given value is not nil. +func (_u *AgentTraceUpdateOne) SetNillableVersion(v *string) *AgentTraceUpdateOne { + if v != nil { + _u.SetVersion(*v) + } + return _u +} + +// SetTimestamp sets the "timestamp" field. +func (_u *AgentTraceUpdateOne) SetTimestamp(v string) *AgentTraceUpdateOne { + _u.mutation.SetTimestamp(v) + return _u +} + +// SetNillableTimestamp sets the "timestamp" field if the given value is not nil. +func (_u *AgentTraceUpdateOne) SetNillableTimestamp(v *string) *AgentTraceUpdateOne { + if v != nil { + _u.SetTimestamp(*v) + } + return _u +} + +// SetVcsType sets the "vcs_type" field. +func (_u *AgentTraceUpdateOne) SetVcsType(v string) *AgentTraceUpdateOne { + _u.mutation.SetVcsType(v) + return _u +} + +// SetNillableVcsType sets the "vcs_type" field if the given value is not nil. +func (_u *AgentTraceUpdateOne) SetNillableVcsType(v *string) *AgentTraceUpdateOne { + if v != nil { + _u.SetVcsType(*v) + } + return _u +} + +// ClearVcsType clears the value of the "vcs_type" field. +func (_u *AgentTraceUpdateOne) ClearVcsType() *AgentTraceUpdateOne { + _u.mutation.ClearVcsType() + return _u +} + +// SetVcsRevision sets the "vcs_revision" field. +func (_u *AgentTraceUpdateOne) SetVcsRevision(v string) *AgentTraceUpdateOne { + _u.mutation.SetVcsRevision(v) + return _u +} + +// SetNillableVcsRevision sets the "vcs_revision" field if the given value is not nil. +func (_u *AgentTraceUpdateOne) SetNillableVcsRevision(v *string) *AgentTraceUpdateOne { + if v != nil { + _u.SetVcsRevision(*v) + } + return _u +} + +// ClearVcsRevision clears the value of the "vcs_revision" field. +func (_u *AgentTraceUpdateOne) ClearVcsRevision() *AgentTraceUpdateOne { + _u.mutation.ClearVcsRevision() + return _u +} + +// SetToolName sets the "tool_name" field. +func (_u *AgentTraceUpdateOne) SetToolName(v string) *AgentTraceUpdateOne { + _u.mutation.SetToolName(v) + return _u +} + +// SetNillableToolName sets the "tool_name" field if the given value is not nil. +func (_u *AgentTraceUpdateOne) SetNillableToolName(v *string) *AgentTraceUpdateOne { + if v != nil { + _u.SetToolName(*v) + } + return _u +} + +// ClearToolName clears the value of the "tool_name" field. +func (_u *AgentTraceUpdateOne) ClearToolName() *AgentTraceUpdateOne { + _u.mutation.ClearToolName() + return _u +} + +// SetToolVersion sets the "tool_version" field. +func (_u *AgentTraceUpdateOne) SetToolVersion(v string) *AgentTraceUpdateOne { + _u.mutation.SetToolVersion(v) + return _u +} + +// SetNillableToolVersion sets the "tool_version" field if the given value is not nil. +func (_u *AgentTraceUpdateOne) SetNillableToolVersion(v *string) *AgentTraceUpdateOne { + if v != nil { + _u.SetToolVersion(*v) + } + return _u +} + +// ClearToolVersion clears the value of the "tool_version" field. +func (_u *AgentTraceUpdateOne) ClearToolVersion() *AgentTraceUpdateOne { + _u.mutation.ClearToolVersion() + return _u +} + +// SetMetadata sets the "metadata" field. +func (_u *AgentTraceUpdateOne) SetMetadata(v map[string]interface{}) *AgentTraceUpdateOne { + _u.mutation.SetMetadata(v) + return _u +} + +// ClearMetadata clears the value of the "metadata" field. +func (_u *AgentTraceUpdateOne) ClearMetadata() *AgentTraceUpdateOne { + _u.mutation.ClearMetadata() + return _u +} + +// AddFileIDs adds the "files" edge to the AgentTraceFile entity by IDs. +func (_u *AgentTraceUpdateOne) AddFileIDs(ids ...int) *AgentTraceUpdateOne { + _u.mutation.AddFileIDs(ids...) + return _u +} + +// AddFiles adds the "files" edges to the AgentTraceFile entity. +func (_u *AgentTraceUpdateOne) AddFiles(v ...*AgentTraceFile) *AgentTraceUpdateOne { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddFileIDs(ids...) +} + +// Mutation returns the AgentTraceMutation object of the builder. +func (_u *AgentTraceUpdateOne) Mutation() *AgentTraceMutation { + return _u.mutation +} + +// ClearFiles clears all "files" edges to the AgentTraceFile entity. +func (_u *AgentTraceUpdateOne) ClearFiles() *AgentTraceUpdateOne { + _u.mutation.ClearFiles() + return _u +} + +// RemoveFileIDs removes the "files" edge to AgentTraceFile entities by IDs. +func (_u *AgentTraceUpdateOne) RemoveFileIDs(ids ...int) *AgentTraceUpdateOne { + _u.mutation.RemoveFileIDs(ids...) + return _u +} + +// RemoveFiles removes "files" edges to AgentTraceFile entities. +func (_u *AgentTraceUpdateOne) RemoveFiles(v ...*AgentTraceFile) *AgentTraceUpdateOne { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveFileIDs(ids...) +} + +// Where appends a list predicates to the AgentTraceUpdate builder. +func (_u *AgentTraceUpdateOne) Where(ps ...predicate.AgentTrace) *AgentTraceUpdateOne { + _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 *AgentTraceUpdateOne) Select(field string, fields ...string) *AgentTraceUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated AgentTrace entity. +func (_u *AgentTraceUpdateOne) Save(ctx context.Context) (*AgentTrace, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *AgentTraceUpdateOne) SaveX(ctx context.Context) *AgentTrace { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *AgentTraceUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *AgentTraceUpdateOne) 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 *AgentTraceUpdateOne) check() error { + if v, ok := _u.mutation.Version(); ok { + if err := agenttrace.VersionValidator(v); err != nil { + return &ValidationError{Name: "version", err: fmt.Errorf(`ent: validator failed for field "AgentTrace.version": %w`, err)} + } + } + if v, ok := _u.mutation.Timestamp(); ok { + if err := agenttrace.TimestampValidator(v); err != nil { + return &ValidationError{Name: "timestamp", err: fmt.Errorf(`ent: validator failed for field "AgentTrace.timestamp": %w`, err)} + } + } + return nil +} + +func (_u *AgentTraceUpdateOne) sqlSave(ctx context.Context) (_node *AgentTrace, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(agenttrace.Table, agenttrace.Columns, sqlgraph.NewFieldSpec(agenttrace.FieldID, field.TypeString)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "AgentTrace.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, agenttrace.FieldID) + for _, f := range fields { + if !agenttrace.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != agenttrace.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.Version(); ok { + _spec.SetField(agenttrace.FieldVersion, field.TypeString, value) + } + if value, ok := _u.mutation.Timestamp(); ok { + _spec.SetField(agenttrace.FieldTimestamp, field.TypeString, value) + } + if value, ok := _u.mutation.VcsType(); ok { + _spec.SetField(agenttrace.FieldVcsType, field.TypeString, value) + } + if _u.mutation.VcsTypeCleared() { + _spec.ClearField(agenttrace.FieldVcsType, field.TypeString) + } + if value, ok := _u.mutation.VcsRevision(); ok { + _spec.SetField(agenttrace.FieldVcsRevision, field.TypeString, value) + } + if _u.mutation.VcsRevisionCleared() { + _spec.ClearField(agenttrace.FieldVcsRevision, field.TypeString) + } + if value, ok := _u.mutation.ToolName(); ok { + _spec.SetField(agenttrace.FieldToolName, field.TypeString, value) + } + if _u.mutation.ToolNameCleared() { + _spec.ClearField(agenttrace.FieldToolName, field.TypeString) + } + if value, ok := _u.mutation.ToolVersion(); ok { + _spec.SetField(agenttrace.FieldToolVersion, field.TypeString, value) + } + if _u.mutation.ToolVersionCleared() { + _spec.ClearField(agenttrace.FieldToolVersion, field.TypeString) + } + if value, ok := _u.mutation.Metadata(); ok { + _spec.SetField(agenttrace.FieldMetadata, field.TypeJSON, value) + } + if _u.mutation.MetadataCleared() { + _spec.ClearField(agenttrace.FieldMetadata, field.TypeJSON) + } + if _u.mutation.FilesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agenttrace.FilesTable, + Columns: []string{agenttrace.FilesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttracefile.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedFilesIDs(); len(nodes) > 0 && !_u.mutation.FilesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agenttrace.FilesTable, + Columns: []string{agenttrace.FilesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttracefile.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.FilesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agenttrace.FilesTable, + Columns: []string{agenttrace.FilesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttracefile.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &AgentTrace{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{agenttrace.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/pkg/storage/ent/agenttraceconversation.go b/pkg/storage/ent/agenttraceconversation.go new file mode 100644 index 0000000..e47b359 --- /dev/null +++ b/pkg/storage/ent/agenttraceconversation.go @@ -0,0 +1,196 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "encoding/json" + "fmt" + "strings" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttraceconversation" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttracefile" +) + +// AgentTraceConversation is the model entity for the AgentTraceConversation schema. +type AgentTraceConversation struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // URL holds the value of the "url" field. + URL string `json:"url,omitempty"` + // ContributorType holds the value of the "contributor_type" field. + ContributorType string `json:"contributor_type,omitempty"` + // ContributorModelID holds the value of the "contributor_model_id" field. + ContributorModelID string `json:"contributor_model_id,omitempty"` + // Related holds the value of the "related" field. + Related []map[string]interface{} `json:"related,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the AgentTraceConversationQuery when eager-loading is set. + Edges AgentTraceConversationEdges `json:"edges"` + agent_trace_file_conversations *int + selectValues sql.SelectValues +} + +// AgentTraceConversationEdges holds the relations/edges for other nodes in the graph. +type AgentTraceConversationEdges struct { + // File holds the value of the file edge. + File *AgentTraceFile `json:"file,omitempty"` + // Ranges holds the value of the ranges edge. + Ranges []*AgentTraceRange `json:"ranges,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// FileOrErr returns the File value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e AgentTraceConversationEdges) FileOrErr() (*AgentTraceFile, error) { + if e.File != nil { + return e.File, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: agenttracefile.Label} + } + return nil, &NotLoadedError{edge: "file"} +} + +// RangesOrErr returns the Ranges value or an error if the edge +// was not loaded in eager-loading. +func (e AgentTraceConversationEdges) RangesOrErr() ([]*AgentTraceRange, error) { + if e.loadedTypes[1] { + return e.Ranges, nil + } + return nil, &NotLoadedError{edge: "ranges"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*AgentTraceConversation) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case agenttraceconversation.FieldRelated: + values[i] = new([]byte) + case agenttraceconversation.FieldID: + values[i] = new(sql.NullInt64) + case agenttraceconversation.FieldURL, agenttraceconversation.FieldContributorType, agenttraceconversation.FieldContributorModelID: + values[i] = new(sql.NullString) + case agenttraceconversation.ForeignKeys[0]: // agent_trace_file_conversations + values[i] = new(sql.NullInt64) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the AgentTraceConversation fields. +func (_m *AgentTraceConversation) 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 agenttraceconversation.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int(value.Int64) + case agenttraceconversation.FieldURL: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field url", values[i]) + } else if value.Valid { + _m.URL = value.String + } + case agenttraceconversation.FieldContributorType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field contributor_type", values[i]) + } else if value.Valid { + _m.ContributorType = value.String + } + case agenttraceconversation.FieldContributorModelID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field contributor_model_id", values[i]) + } else if value.Valid { + _m.ContributorModelID = value.String + } + case agenttraceconversation.FieldRelated: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field related", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &_m.Related); err != nil { + return fmt.Errorf("unmarshal field related: %w", err) + } + } + case agenttraceconversation.ForeignKeys[0]: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for edge-field agent_trace_file_conversations", value) + } else if value.Valid { + _m.agent_trace_file_conversations = new(int) + *_m.agent_trace_file_conversations = int(value.Int64) + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the AgentTraceConversation. +// This includes values selected through modifiers, order, etc. +func (_m *AgentTraceConversation) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryFile queries the "file" edge of the AgentTraceConversation entity. +func (_m *AgentTraceConversation) QueryFile() *AgentTraceFileQuery { + return NewAgentTraceConversationClient(_m.config).QueryFile(_m) +} + +// QueryRanges queries the "ranges" edge of the AgentTraceConversation entity. +func (_m *AgentTraceConversation) QueryRanges() *AgentTraceRangeQuery { + return NewAgentTraceConversationClient(_m.config).QueryRanges(_m) +} + +// Update returns a builder for updating this AgentTraceConversation. +// Note that you need to call AgentTraceConversation.Unwrap() before calling this method if this AgentTraceConversation +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *AgentTraceConversation) Update() *AgentTraceConversationUpdateOne { + return NewAgentTraceConversationClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the AgentTraceConversation 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 *AgentTraceConversation) Unwrap() *AgentTraceConversation { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: AgentTraceConversation is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *AgentTraceConversation) String() string { + var builder strings.Builder + builder.WriteString("AgentTraceConversation(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("url=") + builder.WriteString(_m.URL) + builder.WriteString(", ") + builder.WriteString("contributor_type=") + builder.WriteString(_m.ContributorType) + builder.WriteString(", ") + builder.WriteString("contributor_model_id=") + builder.WriteString(_m.ContributorModelID) + builder.WriteString(", ") + builder.WriteString("related=") + builder.WriteString(fmt.Sprintf("%v", _m.Related)) + builder.WriteByte(')') + return builder.String() +} + +// AgentTraceConversations is a parsable slice of AgentTraceConversation. +type AgentTraceConversations []*AgentTraceConversation diff --git a/pkg/storage/ent/agenttraceconversation/agenttraceconversation.go b/pkg/storage/ent/agenttraceconversation/agenttraceconversation.go new file mode 100644 index 0000000..5fe27aa --- /dev/null +++ b/pkg/storage/ent/agenttraceconversation/agenttraceconversation.go @@ -0,0 +1,131 @@ +// Code generated by ent, DO NOT EDIT. + +package agenttraceconversation + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the agenttraceconversation type in the database. + Label = "agent_trace_conversation" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldURL holds the string denoting the url field in the database. + FieldURL = "url" + // FieldContributorType holds the string denoting the contributor_type field in the database. + FieldContributorType = "contributor_type" + // FieldContributorModelID holds the string denoting the contributor_model_id field in the database. + FieldContributorModelID = "contributor_model_id" + // FieldRelated holds the string denoting the related field in the database. + FieldRelated = "related" + // EdgeFile holds the string denoting the file edge name in mutations. + EdgeFile = "file" + // EdgeRanges holds the string denoting the ranges edge name in mutations. + EdgeRanges = "ranges" + // Table holds the table name of the agenttraceconversation in the database. + Table = "agent_trace_conversations" + // FileTable is the table that holds the file relation/edge. + FileTable = "agent_trace_conversations" + // FileInverseTable is the table name for the AgentTraceFile entity. + // It exists in this package in order to avoid circular dependency with the "agenttracefile" package. + FileInverseTable = "agent_trace_files" + // FileColumn is the table column denoting the file relation/edge. + FileColumn = "agent_trace_file_conversations" + // RangesTable is the table that holds the ranges relation/edge. + RangesTable = "agent_trace_ranges" + // RangesInverseTable is the table name for the AgentTraceRange entity. + // It exists in this package in order to avoid circular dependency with the "agenttracerange" package. + RangesInverseTable = "agent_trace_ranges" + // RangesColumn is the table column denoting the ranges relation/edge. + RangesColumn = "agent_trace_conversation_ranges" +) + +// Columns holds all SQL columns for agenttraceconversation fields. +var Columns = []string{ + FieldID, + FieldURL, + FieldContributorType, + FieldContributorModelID, + FieldRelated, +} + +// ForeignKeys holds the SQL foreign-keys that are owned by the "agent_trace_conversations" +// table and are not defined as standalone fields in the schema. +var ForeignKeys = []string{ + "agent_trace_file_conversations", +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + for i := range ForeignKeys { + if column == ForeignKeys[i] { + return true + } + } + return false +} + +// OrderOption defines the ordering options for the AgentTraceConversation 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() +} + +// ByURL orders the results by the url field. +func ByURL(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldURL, opts...).ToFunc() +} + +// ByContributorType orders the results by the contributor_type field. +func ByContributorType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldContributorType, opts...).ToFunc() +} + +// ByContributorModelID orders the results by the contributor_model_id field. +func ByContributorModelID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldContributorModelID, opts...).ToFunc() +} + +// ByFileField orders the results by file field. +func ByFileField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newFileStep(), sql.OrderByField(field, opts...)) + } +} + +// ByRangesCount orders the results by ranges count. +func ByRangesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newRangesStep(), opts...) + } +} + +// ByRanges orders the results by ranges terms. +func ByRanges(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newRangesStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newFileStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(FileInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, FileTable, FileColumn), + ) +} +func newRangesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(RangesInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, RangesTable, RangesColumn), + ) +} diff --git a/pkg/storage/ent/agenttraceconversation/where.go b/pkg/storage/ent/agenttraceconversation/where.go new file mode 100644 index 0000000..b2251be --- /dev/null +++ b/pkg/storage/ent/agenttraceconversation/where.go @@ -0,0 +1,365 @@ +// Code generated by ent, DO NOT EDIT. + +package agenttraceconversation + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/papercomputeco/tapes/pkg/storage/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldLTE(FieldID, id)) +} + +// URL applies equality check predicate on the "url" field. It's identical to URLEQ. +func URL(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldEQ(FieldURL, v)) +} + +// ContributorType applies equality check predicate on the "contributor_type" field. It's identical to ContributorTypeEQ. +func ContributorType(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldEQ(FieldContributorType, v)) +} + +// ContributorModelID applies equality check predicate on the "contributor_model_id" field. It's identical to ContributorModelIDEQ. +func ContributorModelID(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldEQ(FieldContributorModelID, v)) +} + +// URLEQ applies the EQ predicate on the "url" field. +func URLEQ(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldEQ(FieldURL, v)) +} + +// URLNEQ applies the NEQ predicate on the "url" field. +func URLNEQ(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldNEQ(FieldURL, v)) +} + +// URLIn applies the In predicate on the "url" field. +func URLIn(vs ...string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldIn(FieldURL, vs...)) +} + +// URLNotIn applies the NotIn predicate on the "url" field. +func URLNotIn(vs ...string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldNotIn(FieldURL, vs...)) +} + +// URLGT applies the GT predicate on the "url" field. +func URLGT(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldGT(FieldURL, v)) +} + +// URLGTE applies the GTE predicate on the "url" field. +func URLGTE(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldGTE(FieldURL, v)) +} + +// URLLT applies the LT predicate on the "url" field. +func URLLT(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldLT(FieldURL, v)) +} + +// URLLTE applies the LTE predicate on the "url" field. +func URLLTE(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldLTE(FieldURL, v)) +} + +// URLContains applies the Contains predicate on the "url" field. +func URLContains(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldContains(FieldURL, v)) +} + +// URLHasPrefix applies the HasPrefix predicate on the "url" field. +func URLHasPrefix(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldHasPrefix(FieldURL, v)) +} + +// URLHasSuffix applies the HasSuffix predicate on the "url" field. +func URLHasSuffix(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldHasSuffix(FieldURL, v)) +} + +// URLIsNil applies the IsNil predicate on the "url" field. +func URLIsNil() predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldIsNull(FieldURL)) +} + +// URLNotNil applies the NotNil predicate on the "url" field. +func URLNotNil() predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldNotNull(FieldURL)) +} + +// URLEqualFold applies the EqualFold predicate on the "url" field. +func URLEqualFold(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldEqualFold(FieldURL, v)) +} + +// URLContainsFold applies the ContainsFold predicate on the "url" field. +func URLContainsFold(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldContainsFold(FieldURL, v)) +} + +// ContributorTypeEQ applies the EQ predicate on the "contributor_type" field. +func ContributorTypeEQ(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldEQ(FieldContributorType, v)) +} + +// ContributorTypeNEQ applies the NEQ predicate on the "contributor_type" field. +func ContributorTypeNEQ(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldNEQ(FieldContributorType, v)) +} + +// ContributorTypeIn applies the In predicate on the "contributor_type" field. +func ContributorTypeIn(vs ...string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldIn(FieldContributorType, vs...)) +} + +// ContributorTypeNotIn applies the NotIn predicate on the "contributor_type" field. +func ContributorTypeNotIn(vs ...string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldNotIn(FieldContributorType, vs...)) +} + +// ContributorTypeGT applies the GT predicate on the "contributor_type" field. +func ContributorTypeGT(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldGT(FieldContributorType, v)) +} + +// ContributorTypeGTE applies the GTE predicate on the "contributor_type" field. +func ContributorTypeGTE(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldGTE(FieldContributorType, v)) +} + +// ContributorTypeLT applies the LT predicate on the "contributor_type" field. +func ContributorTypeLT(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldLT(FieldContributorType, v)) +} + +// ContributorTypeLTE applies the LTE predicate on the "contributor_type" field. +func ContributorTypeLTE(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldLTE(FieldContributorType, v)) +} + +// ContributorTypeContains applies the Contains predicate on the "contributor_type" field. +func ContributorTypeContains(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldContains(FieldContributorType, v)) +} + +// ContributorTypeHasPrefix applies the HasPrefix predicate on the "contributor_type" field. +func ContributorTypeHasPrefix(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldHasPrefix(FieldContributorType, v)) +} + +// ContributorTypeHasSuffix applies the HasSuffix predicate on the "contributor_type" field. +func ContributorTypeHasSuffix(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldHasSuffix(FieldContributorType, v)) +} + +// ContributorTypeIsNil applies the IsNil predicate on the "contributor_type" field. +func ContributorTypeIsNil() predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldIsNull(FieldContributorType)) +} + +// ContributorTypeNotNil applies the NotNil predicate on the "contributor_type" field. +func ContributorTypeNotNil() predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldNotNull(FieldContributorType)) +} + +// ContributorTypeEqualFold applies the EqualFold predicate on the "contributor_type" field. +func ContributorTypeEqualFold(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldEqualFold(FieldContributorType, v)) +} + +// ContributorTypeContainsFold applies the ContainsFold predicate on the "contributor_type" field. +func ContributorTypeContainsFold(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldContainsFold(FieldContributorType, v)) +} + +// ContributorModelIDEQ applies the EQ predicate on the "contributor_model_id" field. +func ContributorModelIDEQ(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldEQ(FieldContributorModelID, v)) +} + +// ContributorModelIDNEQ applies the NEQ predicate on the "contributor_model_id" field. +func ContributorModelIDNEQ(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldNEQ(FieldContributorModelID, v)) +} + +// ContributorModelIDIn applies the In predicate on the "contributor_model_id" field. +func ContributorModelIDIn(vs ...string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldIn(FieldContributorModelID, vs...)) +} + +// ContributorModelIDNotIn applies the NotIn predicate on the "contributor_model_id" field. +func ContributorModelIDNotIn(vs ...string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldNotIn(FieldContributorModelID, vs...)) +} + +// ContributorModelIDGT applies the GT predicate on the "contributor_model_id" field. +func ContributorModelIDGT(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldGT(FieldContributorModelID, v)) +} + +// ContributorModelIDGTE applies the GTE predicate on the "contributor_model_id" field. +func ContributorModelIDGTE(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldGTE(FieldContributorModelID, v)) +} + +// ContributorModelIDLT applies the LT predicate on the "contributor_model_id" field. +func ContributorModelIDLT(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldLT(FieldContributorModelID, v)) +} + +// ContributorModelIDLTE applies the LTE predicate on the "contributor_model_id" field. +func ContributorModelIDLTE(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldLTE(FieldContributorModelID, v)) +} + +// ContributorModelIDContains applies the Contains predicate on the "contributor_model_id" field. +func ContributorModelIDContains(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldContains(FieldContributorModelID, v)) +} + +// ContributorModelIDHasPrefix applies the HasPrefix predicate on the "contributor_model_id" field. +func ContributorModelIDHasPrefix(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldHasPrefix(FieldContributorModelID, v)) +} + +// ContributorModelIDHasSuffix applies the HasSuffix predicate on the "contributor_model_id" field. +func ContributorModelIDHasSuffix(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldHasSuffix(FieldContributorModelID, v)) +} + +// ContributorModelIDIsNil applies the IsNil predicate on the "contributor_model_id" field. +func ContributorModelIDIsNil() predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldIsNull(FieldContributorModelID)) +} + +// ContributorModelIDNotNil applies the NotNil predicate on the "contributor_model_id" field. +func ContributorModelIDNotNil() predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldNotNull(FieldContributorModelID)) +} + +// ContributorModelIDEqualFold applies the EqualFold predicate on the "contributor_model_id" field. +func ContributorModelIDEqualFold(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldEqualFold(FieldContributorModelID, v)) +} + +// ContributorModelIDContainsFold applies the ContainsFold predicate on the "contributor_model_id" field. +func ContributorModelIDContainsFold(v string) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldContainsFold(FieldContributorModelID, v)) +} + +// RelatedIsNil applies the IsNil predicate on the "related" field. +func RelatedIsNil() predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldIsNull(FieldRelated)) +} + +// RelatedNotNil applies the NotNil predicate on the "related" field. +func RelatedNotNil() predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.FieldNotNull(FieldRelated)) +} + +// HasFile applies the HasEdge predicate on the "file" edge. +func HasFile() predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, FileTable, FileColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasFileWith applies the HasEdge predicate on the "file" edge with a given conditions (other predicates). +func HasFileWith(preds ...predicate.AgentTraceFile) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(func(s *sql.Selector) { + step := newFileStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasRanges applies the HasEdge predicate on the "ranges" edge. +func HasRanges() predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, RangesTable, RangesColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasRangesWith applies the HasEdge predicate on the "ranges" edge with a given conditions (other predicates). +func HasRangesWith(preds ...predicate.AgentTraceRange) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(func(s *sql.Selector) { + step := newRangesStep() + 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.AgentTraceConversation) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.AgentTraceConversation) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.AgentTraceConversation) predicate.AgentTraceConversation { + return predicate.AgentTraceConversation(sql.NotPredicates(p)) +} diff --git a/pkg/storage/ent/agenttraceconversation_create.go b/pkg/storage/ent/agenttraceconversation_create.go new file mode 100644 index 0000000..3eacc1e --- /dev/null +++ b/pkg/storage/ent/agenttraceconversation_create.go @@ -0,0 +1,298 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttraceconversation" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttracefile" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttracerange" +) + +// AgentTraceConversationCreate is the builder for creating a AgentTraceConversation entity. +type AgentTraceConversationCreate struct { + config + mutation *AgentTraceConversationMutation + hooks []Hook +} + +// SetURL sets the "url" field. +func (_c *AgentTraceConversationCreate) SetURL(v string) *AgentTraceConversationCreate { + _c.mutation.SetURL(v) + return _c +} + +// SetNillableURL sets the "url" field if the given value is not nil. +func (_c *AgentTraceConversationCreate) SetNillableURL(v *string) *AgentTraceConversationCreate { + if v != nil { + _c.SetURL(*v) + } + return _c +} + +// SetContributorType sets the "contributor_type" field. +func (_c *AgentTraceConversationCreate) SetContributorType(v string) *AgentTraceConversationCreate { + _c.mutation.SetContributorType(v) + return _c +} + +// SetNillableContributorType sets the "contributor_type" field if the given value is not nil. +func (_c *AgentTraceConversationCreate) SetNillableContributorType(v *string) *AgentTraceConversationCreate { + if v != nil { + _c.SetContributorType(*v) + } + return _c +} + +// SetContributorModelID sets the "contributor_model_id" field. +func (_c *AgentTraceConversationCreate) SetContributorModelID(v string) *AgentTraceConversationCreate { + _c.mutation.SetContributorModelID(v) + return _c +} + +// SetNillableContributorModelID sets the "contributor_model_id" field if the given value is not nil. +func (_c *AgentTraceConversationCreate) SetNillableContributorModelID(v *string) *AgentTraceConversationCreate { + if v != nil { + _c.SetContributorModelID(*v) + } + return _c +} + +// SetRelated sets the "related" field. +func (_c *AgentTraceConversationCreate) SetRelated(v []map[string]interface{}) *AgentTraceConversationCreate { + _c.mutation.SetRelated(v) + return _c +} + +// SetFileID sets the "file" edge to the AgentTraceFile entity by ID. +func (_c *AgentTraceConversationCreate) SetFileID(id int) *AgentTraceConversationCreate { + _c.mutation.SetFileID(id) + return _c +} + +// SetFile sets the "file" edge to the AgentTraceFile entity. +func (_c *AgentTraceConversationCreate) SetFile(v *AgentTraceFile) *AgentTraceConversationCreate { + return _c.SetFileID(v.ID) +} + +// AddRangeIDs adds the "ranges" edge to the AgentTraceRange entity by IDs. +func (_c *AgentTraceConversationCreate) AddRangeIDs(ids ...int) *AgentTraceConversationCreate { + _c.mutation.AddRangeIDs(ids...) + return _c +} + +// AddRanges adds the "ranges" edges to the AgentTraceRange entity. +func (_c *AgentTraceConversationCreate) AddRanges(v ...*AgentTraceRange) *AgentTraceConversationCreate { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddRangeIDs(ids...) +} + +// Mutation returns the AgentTraceConversationMutation object of the builder. +func (_c *AgentTraceConversationCreate) Mutation() *AgentTraceConversationMutation { + return _c.mutation +} + +// Save creates the AgentTraceConversation in the database. +func (_c *AgentTraceConversationCreate) Save(ctx context.Context) (*AgentTraceConversation, error) { + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *AgentTraceConversationCreate) SaveX(ctx context.Context) *AgentTraceConversation { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *AgentTraceConversationCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *AgentTraceConversationCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *AgentTraceConversationCreate) check() error { + if len(_c.mutation.FileIDs()) == 0 { + return &ValidationError{Name: "file", err: errors.New(`ent: missing required edge "AgentTraceConversation.file"`)} + } + return nil +} + +func (_c *AgentTraceConversationCreate) sqlSave(ctx context.Context) (*AgentTraceConversation, 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 + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *AgentTraceConversationCreate) createSpec() (*AgentTraceConversation, *sqlgraph.CreateSpec) { + var ( + _node = &AgentTraceConversation{config: _c.config} + _spec = sqlgraph.NewCreateSpec(agenttraceconversation.Table, sqlgraph.NewFieldSpec(agenttraceconversation.FieldID, field.TypeInt)) + ) + if value, ok := _c.mutation.URL(); ok { + _spec.SetField(agenttraceconversation.FieldURL, field.TypeString, value) + _node.URL = value + } + if value, ok := _c.mutation.ContributorType(); ok { + _spec.SetField(agenttraceconversation.FieldContributorType, field.TypeString, value) + _node.ContributorType = value + } + if value, ok := _c.mutation.ContributorModelID(); ok { + _spec.SetField(agenttraceconversation.FieldContributorModelID, field.TypeString, value) + _node.ContributorModelID = value + } + if value, ok := _c.mutation.Related(); ok { + _spec.SetField(agenttraceconversation.FieldRelated, field.TypeJSON, value) + _node.Related = value + } + if nodes := _c.mutation.FileIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agenttraceconversation.FileTable, + Columns: []string{agenttraceconversation.FileColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttracefile.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.agent_trace_file_conversations = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.RangesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agenttraceconversation.RangesTable, + Columns: []string{agenttraceconversation.RangesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttracerange.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// AgentTraceConversationCreateBulk is the builder for creating many AgentTraceConversation entities in bulk. +type AgentTraceConversationCreateBulk struct { + config + err error + builders []*AgentTraceConversationCreate +} + +// Save creates the AgentTraceConversation entities in the database. +func (_c *AgentTraceConversationCreateBulk) Save(ctx context.Context) ([]*AgentTraceConversation, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*AgentTraceConversation, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*AgentTraceConversationMutation) + 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} + // 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 + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(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 *AgentTraceConversationCreateBulk) SaveX(ctx context.Context) []*AgentTraceConversation { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *AgentTraceConversationCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *AgentTraceConversationCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/pkg/storage/ent/agenttraceconversation_delete.go b/pkg/storage/ent/agenttraceconversation_delete.go new file mode 100644 index 0000000..3e04654 --- /dev/null +++ b/pkg/storage/ent/agenttraceconversation_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttraceconversation" + "github.com/papercomputeco/tapes/pkg/storage/ent/predicate" +) + +// AgentTraceConversationDelete is the builder for deleting a AgentTraceConversation entity. +type AgentTraceConversationDelete struct { + config + hooks []Hook + mutation *AgentTraceConversationMutation +} + +// Where appends a list predicates to the AgentTraceConversationDelete builder. +func (_d *AgentTraceConversationDelete) Where(ps ...predicate.AgentTraceConversation) *AgentTraceConversationDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *AgentTraceConversationDelete) 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 *AgentTraceConversationDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *AgentTraceConversationDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(agenttraceconversation.Table, sqlgraph.NewFieldSpec(agenttraceconversation.FieldID, field.TypeInt)) + 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 +} + +// AgentTraceConversationDeleteOne is the builder for deleting a single AgentTraceConversation entity. +type AgentTraceConversationDeleteOne struct { + _d *AgentTraceConversationDelete +} + +// Where appends a list predicates to the AgentTraceConversationDelete builder. +func (_d *AgentTraceConversationDeleteOne) Where(ps ...predicate.AgentTraceConversation) *AgentTraceConversationDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *AgentTraceConversationDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{agenttraceconversation.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *AgentTraceConversationDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/pkg/storage/ent/agenttraceconversation_query.go b/pkg/storage/ent/agenttraceconversation_query.go new file mode 100644 index 0000000..27658a6 --- /dev/null +++ b/pkg/storage/ent/agenttraceconversation_query.go @@ -0,0 +1,690 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "database/sql/driver" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttraceconversation" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttracefile" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttracerange" + "github.com/papercomputeco/tapes/pkg/storage/ent/predicate" +) + +// AgentTraceConversationQuery is the builder for querying AgentTraceConversation entities. +type AgentTraceConversationQuery struct { + config + ctx *QueryContext + order []agenttraceconversation.OrderOption + inters []Interceptor + predicates []predicate.AgentTraceConversation + withFile *AgentTraceFileQuery + withRanges *AgentTraceRangeQuery + withFKs bool + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the AgentTraceConversationQuery builder. +func (_q *AgentTraceConversationQuery) Where(ps ...predicate.AgentTraceConversation) *AgentTraceConversationQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *AgentTraceConversationQuery) Limit(limit int) *AgentTraceConversationQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *AgentTraceConversationQuery) Offset(offset int) *AgentTraceConversationQuery { + _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 *AgentTraceConversationQuery) Unique(unique bool) *AgentTraceConversationQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *AgentTraceConversationQuery) Order(o ...agenttraceconversation.OrderOption) *AgentTraceConversationQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryFile chains the current query on the "file" edge. +func (_q *AgentTraceConversationQuery) QueryFile() *AgentTraceFileQuery { + query := (&AgentTraceFileClient{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(agenttraceconversation.Table, agenttraceconversation.FieldID, selector), + sqlgraph.To(agenttracefile.Table, agenttracefile.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, agenttraceconversation.FileTable, agenttraceconversation.FileColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryRanges chains the current query on the "ranges" edge. +func (_q *AgentTraceConversationQuery) QueryRanges() *AgentTraceRangeQuery { + query := (&AgentTraceRangeClient{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(agenttraceconversation.Table, agenttraceconversation.FieldID, selector), + sqlgraph.To(agenttracerange.Table, agenttracerange.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, agenttraceconversation.RangesTable, agenttraceconversation.RangesColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first AgentTraceConversation entity from the query. +// Returns a *NotFoundError when no AgentTraceConversation was found. +func (_q *AgentTraceConversationQuery) First(ctx context.Context) (*AgentTraceConversation, 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{agenttraceconversation.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *AgentTraceConversationQuery) FirstX(ctx context.Context) *AgentTraceConversation { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first AgentTraceConversation ID from the query. +// Returns a *NotFoundError when no AgentTraceConversation ID was found. +func (_q *AgentTraceConversationQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{agenttraceconversation.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *AgentTraceConversationQuery) FirstIDX(ctx context.Context) int { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single AgentTraceConversation entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one AgentTraceConversation entity is found. +// Returns a *NotFoundError when no AgentTraceConversation entities are found. +func (_q *AgentTraceConversationQuery) Only(ctx context.Context) (*AgentTraceConversation, 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{agenttraceconversation.Label} + default: + return nil, &NotSingularError{agenttraceconversation.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *AgentTraceConversationQuery) OnlyX(ctx context.Context) *AgentTraceConversation { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only AgentTraceConversation ID in the query. +// Returns a *NotSingularError when more than one AgentTraceConversation ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *AgentTraceConversationQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + 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{agenttraceconversation.Label} + default: + err = &NotSingularError{agenttraceconversation.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *AgentTraceConversationQuery) OnlyIDX(ctx context.Context) int { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of AgentTraceConversations. +func (_q *AgentTraceConversationQuery) All(ctx context.Context) ([]*AgentTraceConversation, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*AgentTraceConversation, *AgentTraceConversationQuery]() + return withInterceptors[[]*AgentTraceConversation](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *AgentTraceConversationQuery) AllX(ctx context.Context) []*AgentTraceConversation { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of AgentTraceConversation IDs. +func (_q *AgentTraceConversationQuery) IDs(ctx context.Context) (ids []int, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(agenttraceconversation.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *AgentTraceConversationQuery) IDsX(ctx context.Context) []int { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *AgentTraceConversationQuery) 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[*AgentTraceConversationQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *AgentTraceConversationQuery) 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 *AgentTraceConversationQuery) 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("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *AgentTraceConversationQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the AgentTraceConversationQuery 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 *AgentTraceConversationQuery) Clone() *AgentTraceConversationQuery { + if _q == nil { + return nil + } + return &AgentTraceConversationQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]agenttraceconversation.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.AgentTraceConversation{}, _q.predicates...), + withFile: _q.withFile.Clone(), + withRanges: _q.withRanges.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithFile tells the query-builder to eager-load the nodes that are connected to +// the "file" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *AgentTraceConversationQuery) WithFile(opts ...func(*AgentTraceFileQuery)) *AgentTraceConversationQuery { + query := (&AgentTraceFileClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withFile = query + return _q +} + +// WithRanges tells the query-builder to eager-load the nodes that are connected to +// the "ranges" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *AgentTraceConversationQuery) WithRanges(opts ...func(*AgentTraceRangeQuery)) *AgentTraceConversationQuery { + query := (&AgentTraceRangeClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withRanges = 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 { +// URL string `json:"url,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.AgentTraceConversation.Query(). +// GroupBy(agenttraceconversation.FieldURL). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *AgentTraceConversationQuery) GroupBy(field string, fields ...string) *AgentTraceConversationGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &AgentTraceConversationGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = agenttraceconversation.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 { +// URL string `json:"url,omitempty"` +// } +// +// client.AgentTraceConversation.Query(). +// Select(agenttraceconversation.FieldURL). +// Scan(ctx, &v) +func (_q *AgentTraceConversationQuery) Select(fields ...string) *AgentTraceConversationSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &AgentTraceConversationSelect{AgentTraceConversationQuery: _q} + sbuild.label = agenttraceconversation.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a AgentTraceConversationSelect configured with the given aggregations. +func (_q *AgentTraceConversationQuery) Aggregate(fns ...AggregateFunc) *AgentTraceConversationSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *AgentTraceConversationQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !agenttraceconversation.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: 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 *AgentTraceConversationQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AgentTraceConversation, error) { + var ( + nodes = []*AgentTraceConversation{} + withFKs = _q.withFKs + _spec = _q.querySpec() + loadedTypes = [2]bool{ + _q.withFile != nil, + _q.withRanges != nil, + } + ) + if _q.withFile != nil { + withFKs = true + } + if withFKs { + _spec.Node.Columns = append(_spec.Node.Columns, agenttraceconversation.ForeignKeys...) + } + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*AgentTraceConversation).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &AgentTraceConversation{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withFile; query != nil { + if err := _q.loadFile(ctx, query, nodes, nil, + func(n *AgentTraceConversation, e *AgentTraceFile) { n.Edges.File = e }); err != nil { + return nil, err + } + } + if query := _q.withRanges; query != nil { + if err := _q.loadRanges(ctx, query, nodes, + func(n *AgentTraceConversation) { n.Edges.Ranges = []*AgentTraceRange{} }, + func(n *AgentTraceConversation, e *AgentTraceRange) { n.Edges.Ranges = append(n.Edges.Ranges, e) }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *AgentTraceConversationQuery) loadFile(ctx context.Context, query *AgentTraceFileQuery, nodes []*AgentTraceConversation, init func(*AgentTraceConversation), assign func(*AgentTraceConversation, *AgentTraceFile)) error { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*AgentTraceConversation) + for i := range nodes { + if nodes[i].agent_trace_file_conversations == nil { + continue + } + fk := *nodes[i].agent_trace_file_conversations + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(agenttracefile.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 "agent_trace_file_conversations" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *AgentTraceConversationQuery) loadRanges(ctx context.Context, query *AgentTraceRangeQuery, nodes []*AgentTraceConversation, init func(*AgentTraceConversation), assign func(*AgentTraceConversation, *AgentTraceRange)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*AgentTraceConversation) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + query.withFKs = true + query.Where(predicate.AgentTraceRange(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(agenttraceconversation.RangesColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.agent_trace_conversation_ranges + if fk == nil { + return fmt.Errorf(`foreign-key "agent_trace_conversation_ranges" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "agent_trace_conversation_ranges" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (_q *AgentTraceConversationQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _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 *AgentTraceConversationQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(agenttraceconversation.Table, agenttraceconversation.Columns, sqlgraph.NewFieldSpec(agenttraceconversation.FieldID, field.TypeInt)) + _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, agenttraceconversation.FieldID) + for i := range fields { + if fields[i] != agenttraceconversation.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + 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 *AgentTraceConversationQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(agenttraceconversation.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = agenttraceconversation.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 _, 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 +} + +// AgentTraceConversationGroupBy is the group-by builder for AgentTraceConversation entities. +type AgentTraceConversationGroupBy struct { + selector + build *AgentTraceConversationQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *AgentTraceConversationGroupBy) Aggregate(fns ...AggregateFunc) *AgentTraceConversationGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *AgentTraceConversationGroupBy) 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[*AgentTraceConversationQuery, *AgentTraceConversationGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *AgentTraceConversationGroupBy) sqlScan(ctx context.Context, root *AgentTraceConversationQuery, 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) +} + +// AgentTraceConversationSelect is the builder for selecting fields of AgentTraceConversation entities. +type AgentTraceConversationSelect struct { + *AgentTraceConversationQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *AgentTraceConversationSelect) Aggregate(fns ...AggregateFunc) *AgentTraceConversationSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *AgentTraceConversationSelect) 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[*AgentTraceConversationQuery, *AgentTraceConversationSelect](ctx, _s.AgentTraceConversationQuery, _s, _s.inters, v) +} + +func (_s *AgentTraceConversationSelect) sqlScan(ctx context.Context, root *AgentTraceConversationQuery, 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) +} diff --git a/pkg/storage/ent/agenttraceconversation_update.go b/pkg/storage/ent/agenttraceconversation_update.go new file mode 100644 index 0000000..9baea77 --- /dev/null +++ b/pkg/storage/ent/agenttraceconversation_update.go @@ -0,0 +1,668 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/sql/sqljson" + "entgo.io/ent/schema/field" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttraceconversation" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttracefile" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttracerange" + "github.com/papercomputeco/tapes/pkg/storage/ent/predicate" +) + +// AgentTraceConversationUpdate is the builder for updating AgentTraceConversation entities. +type AgentTraceConversationUpdate struct { + config + hooks []Hook + mutation *AgentTraceConversationMutation +} + +// Where appends a list predicates to the AgentTraceConversationUpdate builder. +func (_u *AgentTraceConversationUpdate) Where(ps ...predicate.AgentTraceConversation) *AgentTraceConversationUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetURL sets the "url" field. +func (_u *AgentTraceConversationUpdate) SetURL(v string) *AgentTraceConversationUpdate { + _u.mutation.SetURL(v) + return _u +} + +// SetNillableURL sets the "url" field if the given value is not nil. +func (_u *AgentTraceConversationUpdate) SetNillableURL(v *string) *AgentTraceConversationUpdate { + if v != nil { + _u.SetURL(*v) + } + return _u +} + +// ClearURL clears the value of the "url" field. +func (_u *AgentTraceConversationUpdate) ClearURL() *AgentTraceConversationUpdate { + _u.mutation.ClearURL() + return _u +} + +// SetContributorType sets the "contributor_type" field. +func (_u *AgentTraceConversationUpdate) SetContributorType(v string) *AgentTraceConversationUpdate { + _u.mutation.SetContributorType(v) + return _u +} + +// SetNillableContributorType sets the "contributor_type" field if the given value is not nil. +func (_u *AgentTraceConversationUpdate) SetNillableContributorType(v *string) *AgentTraceConversationUpdate { + if v != nil { + _u.SetContributorType(*v) + } + return _u +} + +// ClearContributorType clears the value of the "contributor_type" field. +func (_u *AgentTraceConversationUpdate) ClearContributorType() *AgentTraceConversationUpdate { + _u.mutation.ClearContributorType() + return _u +} + +// SetContributorModelID sets the "contributor_model_id" field. +func (_u *AgentTraceConversationUpdate) SetContributorModelID(v string) *AgentTraceConversationUpdate { + _u.mutation.SetContributorModelID(v) + return _u +} + +// SetNillableContributorModelID sets the "contributor_model_id" field if the given value is not nil. +func (_u *AgentTraceConversationUpdate) SetNillableContributorModelID(v *string) *AgentTraceConversationUpdate { + if v != nil { + _u.SetContributorModelID(*v) + } + return _u +} + +// ClearContributorModelID clears the value of the "contributor_model_id" field. +func (_u *AgentTraceConversationUpdate) ClearContributorModelID() *AgentTraceConversationUpdate { + _u.mutation.ClearContributorModelID() + return _u +} + +// SetRelated sets the "related" field. +func (_u *AgentTraceConversationUpdate) SetRelated(v []map[string]interface{}) *AgentTraceConversationUpdate { + _u.mutation.SetRelated(v) + return _u +} + +// AppendRelated appends value to the "related" field. +func (_u *AgentTraceConversationUpdate) AppendRelated(v []map[string]interface{}) *AgentTraceConversationUpdate { + _u.mutation.AppendRelated(v) + return _u +} + +// ClearRelated clears the value of the "related" field. +func (_u *AgentTraceConversationUpdate) ClearRelated() *AgentTraceConversationUpdate { + _u.mutation.ClearRelated() + return _u +} + +// SetFileID sets the "file" edge to the AgentTraceFile entity by ID. +func (_u *AgentTraceConversationUpdate) SetFileID(id int) *AgentTraceConversationUpdate { + _u.mutation.SetFileID(id) + return _u +} + +// SetFile sets the "file" edge to the AgentTraceFile entity. +func (_u *AgentTraceConversationUpdate) SetFile(v *AgentTraceFile) *AgentTraceConversationUpdate { + return _u.SetFileID(v.ID) +} + +// AddRangeIDs adds the "ranges" edge to the AgentTraceRange entity by IDs. +func (_u *AgentTraceConversationUpdate) AddRangeIDs(ids ...int) *AgentTraceConversationUpdate { + _u.mutation.AddRangeIDs(ids...) + return _u +} + +// AddRanges adds the "ranges" edges to the AgentTraceRange entity. +func (_u *AgentTraceConversationUpdate) AddRanges(v ...*AgentTraceRange) *AgentTraceConversationUpdate { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddRangeIDs(ids...) +} + +// Mutation returns the AgentTraceConversationMutation object of the builder. +func (_u *AgentTraceConversationUpdate) Mutation() *AgentTraceConversationMutation { + return _u.mutation +} + +// ClearFile clears the "file" edge to the AgentTraceFile entity. +func (_u *AgentTraceConversationUpdate) ClearFile() *AgentTraceConversationUpdate { + _u.mutation.ClearFile() + return _u +} + +// ClearRanges clears all "ranges" edges to the AgentTraceRange entity. +func (_u *AgentTraceConversationUpdate) ClearRanges() *AgentTraceConversationUpdate { + _u.mutation.ClearRanges() + return _u +} + +// RemoveRangeIDs removes the "ranges" edge to AgentTraceRange entities by IDs. +func (_u *AgentTraceConversationUpdate) RemoveRangeIDs(ids ...int) *AgentTraceConversationUpdate { + _u.mutation.RemoveRangeIDs(ids...) + return _u +} + +// RemoveRanges removes "ranges" edges to AgentTraceRange entities. +func (_u *AgentTraceConversationUpdate) RemoveRanges(v ...*AgentTraceRange) *AgentTraceConversationUpdate { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveRangeIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *AgentTraceConversationUpdate) 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 *AgentTraceConversationUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *AgentTraceConversationUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *AgentTraceConversationUpdate) 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 *AgentTraceConversationUpdate) check() error { + if _u.mutation.FileCleared() && len(_u.mutation.FileIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "AgentTraceConversation.file"`) + } + return nil +} + +func (_u *AgentTraceConversationUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(agenttraceconversation.Table, agenttraceconversation.Columns, sqlgraph.NewFieldSpec(agenttraceconversation.FieldID, field.TypeInt)) + 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.URL(); ok { + _spec.SetField(agenttraceconversation.FieldURL, field.TypeString, value) + } + if _u.mutation.URLCleared() { + _spec.ClearField(agenttraceconversation.FieldURL, field.TypeString) + } + if value, ok := _u.mutation.ContributorType(); ok { + _spec.SetField(agenttraceconversation.FieldContributorType, field.TypeString, value) + } + if _u.mutation.ContributorTypeCleared() { + _spec.ClearField(agenttraceconversation.FieldContributorType, field.TypeString) + } + if value, ok := _u.mutation.ContributorModelID(); ok { + _spec.SetField(agenttraceconversation.FieldContributorModelID, field.TypeString, value) + } + if _u.mutation.ContributorModelIDCleared() { + _spec.ClearField(agenttraceconversation.FieldContributorModelID, field.TypeString) + } + if value, ok := _u.mutation.Related(); ok { + _spec.SetField(agenttraceconversation.FieldRelated, field.TypeJSON, value) + } + if value, ok := _u.mutation.AppendedRelated(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, agenttraceconversation.FieldRelated, value) + }) + } + if _u.mutation.RelatedCleared() { + _spec.ClearField(agenttraceconversation.FieldRelated, field.TypeJSON) + } + if _u.mutation.FileCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agenttraceconversation.FileTable, + Columns: []string{agenttraceconversation.FileColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttracefile.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.FileIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agenttraceconversation.FileTable, + Columns: []string{agenttraceconversation.FileColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttracefile.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.RangesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agenttraceconversation.RangesTable, + Columns: []string{agenttraceconversation.RangesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttracerange.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedRangesIDs(); len(nodes) > 0 && !_u.mutation.RangesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agenttraceconversation.RangesTable, + Columns: []string{agenttraceconversation.RangesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttracerange.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RangesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agenttraceconversation.RangesTable, + Columns: []string{agenttraceconversation.RangesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttracerange.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{agenttraceconversation.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// AgentTraceConversationUpdateOne is the builder for updating a single AgentTraceConversation entity. +type AgentTraceConversationUpdateOne struct { + config + fields []string + hooks []Hook + mutation *AgentTraceConversationMutation +} + +// SetURL sets the "url" field. +func (_u *AgentTraceConversationUpdateOne) SetURL(v string) *AgentTraceConversationUpdateOne { + _u.mutation.SetURL(v) + return _u +} + +// SetNillableURL sets the "url" field if the given value is not nil. +func (_u *AgentTraceConversationUpdateOne) SetNillableURL(v *string) *AgentTraceConversationUpdateOne { + if v != nil { + _u.SetURL(*v) + } + return _u +} + +// ClearURL clears the value of the "url" field. +func (_u *AgentTraceConversationUpdateOne) ClearURL() *AgentTraceConversationUpdateOne { + _u.mutation.ClearURL() + return _u +} + +// SetContributorType sets the "contributor_type" field. +func (_u *AgentTraceConversationUpdateOne) SetContributorType(v string) *AgentTraceConversationUpdateOne { + _u.mutation.SetContributorType(v) + return _u +} + +// SetNillableContributorType sets the "contributor_type" field if the given value is not nil. +func (_u *AgentTraceConversationUpdateOne) SetNillableContributorType(v *string) *AgentTraceConversationUpdateOne { + if v != nil { + _u.SetContributorType(*v) + } + return _u +} + +// ClearContributorType clears the value of the "contributor_type" field. +func (_u *AgentTraceConversationUpdateOne) ClearContributorType() *AgentTraceConversationUpdateOne { + _u.mutation.ClearContributorType() + return _u +} + +// SetContributorModelID sets the "contributor_model_id" field. +func (_u *AgentTraceConversationUpdateOne) SetContributorModelID(v string) *AgentTraceConversationUpdateOne { + _u.mutation.SetContributorModelID(v) + return _u +} + +// SetNillableContributorModelID sets the "contributor_model_id" field if the given value is not nil. +func (_u *AgentTraceConversationUpdateOne) SetNillableContributorModelID(v *string) *AgentTraceConversationUpdateOne { + if v != nil { + _u.SetContributorModelID(*v) + } + return _u +} + +// ClearContributorModelID clears the value of the "contributor_model_id" field. +func (_u *AgentTraceConversationUpdateOne) ClearContributorModelID() *AgentTraceConversationUpdateOne { + _u.mutation.ClearContributorModelID() + return _u +} + +// SetRelated sets the "related" field. +func (_u *AgentTraceConversationUpdateOne) SetRelated(v []map[string]interface{}) *AgentTraceConversationUpdateOne { + _u.mutation.SetRelated(v) + return _u +} + +// AppendRelated appends value to the "related" field. +func (_u *AgentTraceConversationUpdateOne) AppendRelated(v []map[string]interface{}) *AgentTraceConversationUpdateOne { + _u.mutation.AppendRelated(v) + return _u +} + +// ClearRelated clears the value of the "related" field. +func (_u *AgentTraceConversationUpdateOne) ClearRelated() *AgentTraceConversationUpdateOne { + _u.mutation.ClearRelated() + return _u +} + +// SetFileID sets the "file" edge to the AgentTraceFile entity by ID. +func (_u *AgentTraceConversationUpdateOne) SetFileID(id int) *AgentTraceConversationUpdateOne { + _u.mutation.SetFileID(id) + return _u +} + +// SetFile sets the "file" edge to the AgentTraceFile entity. +func (_u *AgentTraceConversationUpdateOne) SetFile(v *AgentTraceFile) *AgentTraceConversationUpdateOne { + return _u.SetFileID(v.ID) +} + +// AddRangeIDs adds the "ranges" edge to the AgentTraceRange entity by IDs. +func (_u *AgentTraceConversationUpdateOne) AddRangeIDs(ids ...int) *AgentTraceConversationUpdateOne { + _u.mutation.AddRangeIDs(ids...) + return _u +} + +// AddRanges adds the "ranges" edges to the AgentTraceRange entity. +func (_u *AgentTraceConversationUpdateOne) AddRanges(v ...*AgentTraceRange) *AgentTraceConversationUpdateOne { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddRangeIDs(ids...) +} + +// Mutation returns the AgentTraceConversationMutation object of the builder. +func (_u *AgentTraceConversationUpdateOne) Mutation() *AgentTraceConversationMutation { + return _u.mutation +} + +// ClearFile clears the "file" edge to the AgentTraceFile entity. +func (_u *AgentTraceConversationUpdateOne) ClearFile() *AgentTraceConversationUpdateOne { + _u.mutation.ClearFile() + return _u +} + +// ClearRanges clears all "ranges" edges to the AgentTraceRange entity. +func (_u *AgentTraceConversationUpdateOne) ClearRanges() *AgentTraceConversationUpdateOne { + _u.mutation.ClearRanges() + return _u +} + +// RemoveRangeIDs removes the "ranges" edge to AgentTraceRange entities by IDs. +func (_u *AgentTraceConversationUpdateOne) RemoveRangeIDs(ids ...int) *AgentTraceConversationUpdateOne { + _u.mutation.RemoveRangeIDs(ids...) + return _u +} + +// RemoveRanges removes "ranges" edges to AgentTraceRange entities. +func (_u *AgentTraceConversationUpdateOne) RemoveRanges(v ...*AgentTraceRange) *AgentTraceConversationUpdateOne { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveRangeIDs(ids...) +} + +// Where appends a list predicates to the AgentTraceConversationUpdate builder. +func (_u *AgentTraceConversationUpdateOne) Where(ps ...predicate.AgentTraceConversation) *AgentTraceConversationUpdateOne { + _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 *AgentTraceConversationUpdateOne) Select(field string, fields ...string) *AgentTraceConversationUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated AgentTraceConversation entity. +func (_u *AgentTraceConversationUpdateOne) Save(ctx context.Context) (*AgentTraceConversation, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *AgentTraceConversationUpdateOne) SaveX(ctx context.Context) *AgentTraceConversation { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *AgentTraceConversationUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *AgentTraceConversationUpdateOne) 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 *AgentTraceConversationUpdateOne) check() error { + if _u.mutation.FileCleared() && len(_u.mutation.FileIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "AgentTraceConversation.file"`) + } + return nil +} + +func (_u *AgentTraceConversationUpdateOne) sqlSave(ctx context.Context) (_node *AgentTraceConversation, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(agenttraceconversation.Table, agenttraceconversation.Columns, sqlgraph.NewFieldSpec(agenttraceconversation.FieldID, field.TypeInt)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "AgentTraceConversation.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, agenttraceconversation.FieldID) + for _, f := range fields { + if !agenttraceconversation.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != agenttraceconversation.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.URL(); ok { + _spec.SetField(agenttraceconversation.FieldURL, field.TypeString, value) + } + if _u.mutation.URLCleared() { + _spec.ClearField(agenttraceconversation.FieldURL, field.TypeString) + } + if value, ok := _u.mutation.ContributorType(); ok { + _spec.SetField(agenttraceconversation.FieldContributorType, field.TypeString, value) + } + if _u.mutation.ContributorTypeCleared() { + _spec.ClearField(agenttraceconversation.FieldContributorType, field.TypeString) + } + if value, ok := _u.mutation.ContributorModelID(); ok { + _spec.SetField(agenttraceconversation.FieldContributorModelID, field.TypeString, value) + } + if _u.mutation.ContributorModelIDCleared() { + _spec.ClearField(agenttraceconversation.FieldContributorModelID, field.TypeString) + } + if value, ok := _u.mutation.Related(); ok { + _spec.SetField(agenttraceconversation.FieldRelated, field.TypeJSON, value) + } + if value, ok := _u.mutation.AppendedRelated(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, agenttraceconversation.FieldRelated, value) + }) + } + if _u.mutation.RelatedCleared() { + _spec.ClearField(agenttraceconversation.FieldRelated, field.TypeJSON) + } + if _u.mutation.FileCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agenttraceconversation.FileTable, + Columns: []string{agenttraceconversation.FileColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttracefile.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.FileIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agenttraceconversation.FileTable, + Columns: []string{agenttraceconversation.FileColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttracefile.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _u.mutation.RangesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agenttraceconversation.RangesTable, + Columns: []string{agenttraceconversation.RangesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttracerange.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedRangesIDs(); len(nodes) > 0 && !_u.mutation.RangesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agenttraceconversation.RangesTable, + Columns: []string{agenttraceconversation.RangesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttracerange.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RangesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agenttraceconversation.RangesTable, + Columns: []string{agenttraceconversation.RangesColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttracerange.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &AgentTraceConversation{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{agenttraceconversation.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/pkg/storage/ent/agenttracefile.go b/pkg/storage/ent/agenttracefile.go new file mode 100644 index 0000000..d3e4406 --- /dev/null +++ b/pkg/storage/ent/agenttracefile.go @@ -0,0 +1,158 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttrace" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttracefile" +) + +// AgentTraceFile is the model entity for the AgentTraceFile schema. +type AgentTraceFile struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Path holds the value of the "path" field. + Path string `json:"path,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the AgentTraceFileQuery when eager-loading is set. + Edges AgentTraceFileEdges `json:"edges"` + agent_trace_files *string + selectValues sql.SelectValues +} + +// AgentTraceFileEdges holds the relations/edges for other nodes in the graph. +type AgentTraceFileEdges struct { + // Trace holds the value of the trace edge. + Trace *AgentTrace `json:"trace,omitempty"` + // Conversations holds the value of the conversations edge. + Conversations []*AgentTraceConversation `json:"conversations,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool +} + +// TraceOrErr returns the Trace value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e AgentTraceFileEdges) TraceOrErr() (*AgentTrace, error) { + if e.Trace != nil { + return e.Trace, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: agenttrace.Label} + } + return nil, &NotLoadedError{edge: "trace"} +} + +// ConversationsOrErr returns the Conversations value or an error if the edge +// was not loaded in eager-loading. +func (e AgentTraceFileEdges) ConversationsOrErr() ([]*AgentTraceConversation, error) { + if e.loadedTypes[1] { + return e.Conversations, nil + } + return nil, &NotLoadedError{edge: "conversations"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*AgentTraceFile) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case agenttracefile.FieldID: + values[i] = new(sql.NullInt64) + case agenttracefile.FieldPath: + values[i] = new(sql.NullString) + case agenttracefile.ForeignKeys[0]: // agent_trace_files + values[i] = new(sql.NullString) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the AgentTraceFile fields. +func (_m *AgentTraceFile) 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 agenttracefile.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int(value.Int64) + case agenttracefile.FieldPath: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field path", values[i]) + } else if value.Valid { + _m.Path = value.String + } + case agenttracefile.ForeignKeys[0]: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field agent_trace_files", values[i]) + } else if value.Valid { + _m.agent_trace_files = new(string) + *_m.agent_trace_files = value.String + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the AgentTraceFile. +// This includes values selected through modifiers, order, etc. +func (_m *AgentTraceFile) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryTrace queries the "trace" edge of the AgentTraceFile entity. +func (_m *AgentTraceFile) QueryTrace() *AgentTraceQuery { + return NewAgentTraceFileClient(_m.config).QueryTrace(_m) +} + +// QueryConversations queries the "conversations" edge of the AgentTraceFile entity. +func (_m *AgentTraceFile) QueryConversations() *AgentTraceConversationQuery { + return NewAgentTraceFileClient(_m.config).QueryConversations(_m) +} + +// Update returns a builder for updating this AgentTraceFile. +// Note that you need to call AgentTraceFile.Unwrap() before calling this method if this AgentTraceFile +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *AgentTraceFile) Update() *AgentTraceFileUpdateOne { + return NewAgentTraceFileClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the AgentTraceFile 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 *AgentTraceFile) Unwrap() *AgentTraceFile { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: AgentTraceFile is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *AgentTraceFile) String() string { + var builder strings.Builder + builder.WriteString("AgentTraceFile(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("path=") + builder.WriteString(_m.Path) + builder.WriteByte(')') + return builder.String() +} + +// AgentTraceFiles is a parsable slice of AgentTraceFile. +type AgentTraceFiles []*AgentTraceFile diff --git a/pkg/storage/ent/agenttracefile/agenttracefile.go b/pkg/storage/ent/agenttracefile/agenttracefile.go new file mode 100644 index 0000000..e05ba19 --- /dev/null +++ b/pkg/storage/ent/agenttracefile/agenttracefile.go @@ -0,0 +1,117 @@ +// Code generated by ent, DO NOT EDIT. + +package agenttracefile + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the agenttracefile type in the database. + Label = "agent_trace_file" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldPath holds the string denoting the path field in the database. + FieldPath = "path" + // EdgeTrace holds the string denoting the trace edge name in mutations. + EdgeTrace = "trace" + // EdgeConversations holds the string denoting the conversations edge name in mutations. + EdgeConversations = "conversations" + // Table holds the table name of the agenttracefile in the database. + Table = "agent_trace_files" + // TraceTable is the table that holds the trace relation/edge. + TraceTable = "agent_trace_files" + // TraceInverseTable is the table name for the AgentTrace entity. + // It exists in this package in order to avoid circular dependency with the "agenttrace" package. + TraceInverseTable = "agent_traces" + // TraceColumn is the table column denoting the trace relation/edge. + TraceColumn = "agent_trace_files" + // ConversationsTable is the table that holds the conversations relation/edge. + ConversationsTable = "agent_trace_conversations" + // ConversationsInverseTable is the table name for the AgentTraceConversation entity. + // It exists in this package in order to avoid circular dependency with the "agenttraceconversation" package. + ConversationsInverseTable = "agent_trace_conversations" + // ConversationsColumn is the table column denoting the conversations relation/edge. + ConversationsColumn = "agent_trace_file_conversations" +) + +// Columns holds all SQL columns for agenttracefile fields. +var Columns = []string{ + FieldID, + FieldPath, +} + +// ForeignKeys holds the SQL foreign-keys that are owned by the "agent_trace_files" +// table and are not defined as standalone fields in the schema. +var ForeignKeys = []string{ + "agent_trace_files", +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + for i := range ForeignKeys { + if column == ForeignKeys[i] { + return true + } + } + return false +} + +var ( + // PathValidator is a validator for the "path" field. It is called by the builders before save. + PathValidator func(string) error +) + +// OrderOption defines the ordering options for the AgentTraceFile 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() +} + +// ByPath orders the results by the path field. +func ByPath(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPath, opts...).ToFunc() +} + +// ByTraceField orders the results by trace field. +func ByTraceField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newTraceStep(), sql.OrderByField(field, opts...)) + } +} + +// ByConversationsCount orders the results by conversations count. +func ByConversationsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newConversationsStep(), opts...) + } +} + +// ByConversations orders the results by conversations terms. +func ByConversations(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newConversationsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newTraceStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TraceInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, TraceTable, TraceColumn), + ) +} +func newConversationsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ConversationsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ConversationsTable, ConversationsColumn), + ) +} diff --git a/pkg/storage/ent/agenttracefile/where.go b/pkg/storage/ent/agenttracefile/where.go new file mode 100644 index 0000000..d5fe389 --- /dev/null +++ b/pkg/storage/ent/agenttracefile/where.go @@ -0,0 +1,185 @@ +// Code generated by ent, DO NOT EDIT. + +package agenttracefile + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/papercomputeco/tapes/pkg/storage/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.AgentTraceFile { + return predicate.AgentTraceFile(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.AgentTraceFile { + return predicate.AgentTraceFile(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.AgentTraceFile { + return predicate.AgentTraceFile(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.AgentTraceFile { + return predicate.AgentTraceFile(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.AgentTraceFile { + return predicate.AgentTraceFile(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.AgentTraceFile { + return predicate.AgentTraceFile(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.AgentTraceFile { + return predicate.AgentTraceFile(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.AgentTraceFile { + return predicate.AgentTraceFile(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.AgentTraceFile { + return predicate.AgentTraceFile(sql.FieldLTE(FieldID, id)) +} + +// Path applies equality check predicate on the "path" field. It's identical to PathEQ. +func Path(v string) predicate.AgentTraceFile { + return predicate.AgentTraceFile(sql.FieldEQ(FieldPath, v)) +} + +// PathEQ applies the EQ predicate on the "path" field. +func PathEQ(v string) predicate.AgentTraceFile { + return predicate.AgentTraceFile(sql.FieldEQ(FieldPath, v)) +} + +// PathNEQ applies the NEQ predicate on the "path" field. +func PathNEQ(v string) predicate.AgentTraceFile { + return predicate.AgentTraceFile(sql.FieldNEQ(FieldPath, v)) +} + +// PathIn applies the In predicate on the "path" field. +func PathIn(vs ...string) predicate.AgentTraceFile { + return predicate.AgentTraceFile(sql.FieldIn(FieldPath, vs...)) +} + +// PathNotIn applies the NotIn predicate on the "path" field. +func PathNotIn(vs ...string) predicate.AgentTraceFile { + return predicate.AgentTraceFile(sql.FieldNotIn(FieldPath, vs...)) +} + +// PathGT applies the GT predicate on the "path" field. +func PathGT(v string) predicate.AgentTraceFile { + return predicate.AgentTraceFile(sql.FieldGT(FieldPath, v)) +} + +// PathGTE applies the GTE predicate on the "path" field. +func PathGTE(v string) predicate.AgentTraceFile { + return predicate.AgentTraceFile(sql.FieldGTE(FieldPath, v)) +} + +// PathLT applies the LT predicate on the "path" field. +func PathLT(v string) predicate.AgentTraceFile { + return predicate.AgentTraceFile(sql.FieldLT(FieldPath, v)) +} + +// PathLTE applies the LTE predicate on the "path" field. +func PathLTE(v string) predicate.AgentTraceFile { + return predicate.AgentTraceFile(sql.FieldLTE(FieldPath, v)) +} + +// PathContains applies the Contains predicate on the "path" field. +func PathContains(v string) predicate.AgentTraceFile { + return predicate.AgentTraceFile(sql.FieldContains(FieldPath, v)) +} + +// PathHasPrefix applies the HasPrefix predicate on the "path" field. +func PathHasPrefix(v string) predicate.AgentTraceFile { + return predicate.AgentTraceFile(sql.FieldHasPrefix(FieldPath, v)) +} + +// PathHasSuffix applies the HasSuffix predicate on the "path" field. +func PathHasSuffix(v string) predicate.AgentTraceFile { + return predicate.AgentTraceFile(sql.FieldHasSuffix(FieldPath, v)) +} + +// PathEqualFold applies the EqualFold predicate on the "path" field. +func PathEqualFold(v string) predicate.AgentTraceFile { + return predicate.AgentTraceFile(sql.FieldEqualFold(FieldPath, v)) +} + +// PathContainsFold applies the ContainsFold predicate on the "path" field. +func PathContainsFold(v string) predicate.AgentTraceFile { + return predicate.AgentTraceFile(sql.FieldContainsFold(FieldPath, v)) +} + +// HasTrace applies the HasEdge predicate on the "trace" edge. +func HasTrace() predicate.AgentTraceFile { + return predicate.AgentTraceFile(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, TraceTable, TraceColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasTraceWith applies the HasEdge predicate on the "trace" edge with a given conditions (other predicates). +func HasTraceWith(preds ...predicate.AgentTrace) predicate.AgentTraceFile { + return predicate.AgentTraceFile(func(s *sql.Selector) { + step := newTraceStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasConversations applies the HasEdge predicate on the "conversations" edge. +func HasConversations() predicate.AgentTraceFile { + return predicate.AgentTraceFile(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ConversationsTable, ConversationsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasConversationsWith applies the HasEdge predicate on the "conversations" edge with a given conditions (other predicates). +func HasConversationsWith(preds ...predicate.AgentTraceConversation) predicate.AgentTraceFile { + return predicate.AgentTraceFile(func(s *sql.Selector) { + step := newConversationsStep() + 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.AgentTraceFile) predicate.AgentTraceFile { + return predicate.AgentTraceFile(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.AgentTraceFile) predicate.AgentTraceFile { + return predicate.AgentTraceFile(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.AgentTraceFile) predicate.AgentTraceFile { + return predicate.AgentTraceFile(sql.NotPredicates(p)) +} diff --git a/pkg/storage/ent/agenttracefile_create.go b/pkg/storage/ent/agenttracefile_create.go new file mode 100644 index 0000000..60360c6 --- /dev/null +++ b/pkg/storage/ent/agenttracefile_create.go @@ -0,0 +1,252 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttrace" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttraceconversation" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttracefile" +) + +// AgentTraceFileCreate is the builder for creating a AgentTraceFile entity. +type AgentTraceFileCreate struct { + config + mutation *AgentTraceFileMutation + hooks []Hook +} + +// SetPath sets the "path" field. +func (_c *AgentTraceFileCreate) SetPath(v string) *AgentTraceFileCreate { + _c.mutation.SetPath(v) + return _c +} + +// SetTraceID sets the "trace" edge to the AgentTrace entity by ID. +func (_c *AgentTraceFileCreate) SetTraceID(id string) *AgentTraceFileCreate { + _c.mutation.SetTraceID(id) + return _c +} + +// SetTrace sets the "trace" edge to the AgentTrace entity. +func (_c *AgentTraceFileCreate) SetTrace(v *AgentTrace) *AgentTraceFileCreate { + return _c.SetTraceID(v.ID) +} + +// AddConversationIDs adds the "conversations" edge to the AgentTraceConversation entity by IDs. +func (_c *AgentTraceFileCreate) AddConversationIDs(ids ...int) *AgentTraceFileCreate { + _c.mutation.AddConversationIDs(ids...) + return _c +} + +// AddConversations adds the "conversations" edges to the AgentTraceConversation entity. +func (_c *AgentTraceFileCreate) AddConversations(v ...*AgentTraceConversation) *AgentTraceFileCreate { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _c.AddConversationIDs(ids...) +} + +// Mutation returns the AgentTraceFileMutation object of the builder. +func (_c *AgentTraceFileCreate) Mutation() *AgentTraceFileMutation { + return _c.mutation +} + +// Save creates the AgentTraceFile in the database. +func (_c *AgentTraceFileCreate) Save(ctx context.Context) (*AgentTraceFile, error) { + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *AgentTraceFileCreate) SaveX(ctx context.Context) *AgentTraceFile { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *AgentTraceFileCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *AgentTraceFileCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *AgentTraceFileCreate) check() error { + if _, ok := _c.mutation.Path(); !ok { + return &ValidationError{Name: "path", err: errors.New(`ent: missing required field "AgentTraceFile.path"`)} + } + if v, ok := _c.mutation.Path(); ok { + if err := agenttracefile.PathValidator(v); err != nil { + return &ValidationError{Name: "path", err: fmt.Errorf(`ent: validator failed for field "AgentTraceFile.path": %w`, err)} + } + } + if len(_c.mutation.TraceIDs()) == 0 { + return &ValidationError{Name: "trace", err: errors.New(`ent: missing required edge "AgentTraceFile.trace"`)} + } + return nil +} + +func (_c *AgentTraceFileCreate) sqlSave(ctx context.Context) (*AgentTraceFile, 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 + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *AgentTraceFileCreate) createSpec() (*AgentTraceFile, *sqlgraph.CreateSpec) { + var ( + _node = &AgentTraceFile{config: _c.config} + _spec = sqlgraph.NewCreateSpec(agenttracefile.Table, sqlgraph.NewFieldSpec(agenttracefile.FieldID, field.TypeInt)) + ) + if value, ok := _c.mutation.Path(); ok { + _spec.SetField(agenttracefile.FieldPath, field.TypeString, value) + _node.Path = value + } + if nodes := _c.mutation.TraceIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agenttracefile.TraceTable, + Columns: []string{agenttracefile.TraceColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttrace.FieldID, field.TypeString), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.agent_trace_files = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := _c.mutation.ConversationsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agenttracefile.ConversationsTable, + Columns: []string{agenttracefile.ConversationsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttraceconversation.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// AgentTraceFileCreateBulk is the builder for creating many AgentTraceFile entities in bulk. +type AgentTraceFileCreateBulk struct { + config + err error + builders []*AgentTraceFileCreate +} + +// Save creates the AgentTraceFile entities in the database. +func (_c *AgentTraceFileCreateBulk) Save(ctx context.Context) ([]*AgentTraceFile, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*AgentTraceFile, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*AgentTraceFileMutation) + 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} + // 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 + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(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 *AgentTraceFileCreateBulk) SaveX(ctx context.Context) []*AgentTraceFile { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *AgentTraceFileCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *AgentTraceFileCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/pkg/storage/ent/agenttracefile_delete.go b/pkg/storage/ent/agenttracefile_delete.go new file mode 100644 index 0000000..2f67c60 --- /dev/null +++ b/pkg/storage/ent/agenttracefile_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttracefile" + "github.com/papercomputeco/tapes/pkg/storage/ent/predicate" +) + +// AgentTraceFileDelete is the builder for deleting a AgentTraceFile entity. +type AgentTraceFileDelete struct { + config + hooks []Hook + mutation *AgentTraceFileMutation +} + +// Where appends a list predicates to the AgentTraceFileDelete builder. +func (_d *AgentTraceFileDelete) Where(ps ...predicate.AgentTraceFile) *AgentTraceFileDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *AgentTraceFileDelete) 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 *AgentTraceFileDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *AgentTraceFileDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(agenttracefile.Table, sqlgraph.NewFieldSpec(agenttracefile.FieldID, field.TypeInt)) + 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 +} + +// AgentTraceFileDeleteOne is the builder for deleting a single AgentTraceFile entity. +type AgentTraceFileDeleteOne struct { + _d *AgentTraceFileDelete +} + +// Where appends a list predicates to the AgentTraceFileDelete builder. +func (_d *AgentTraceFileDeleteOne) Where(ps ...predicate.AgentTraceFile) *AgentTraceFileDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *AgentTraceFileDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{agenttracefile.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *AgentTraceFileDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/pkg/storage/ent/agenttracefile_query.go b/pkg/storage/ent/agenttracefile_query.go new file mode 100644 index 0000000..e74eb18 --- /dev/null +++ b/pkg/storage/ent/agenttracefile_query.go @@ -0,0 +1,692 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "database/sql/driver" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttrace" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttraceconversation" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttracefile" + "github.com/papercomputeco/tapes/pkg/storage/ent/predicate" +) + +// AgentTraceFileQuery is the builder for querying AgentTraceFile entities. +type AgentTraceFileQuery struct { + config + ctx *QueryContext + order []agenttracefile.OrderOption + inters []Interceptor + predicates []predicate.AgentTraceFile + withTrace *AgentTraceQuery + withConversations *AgentTraceConversationQuery + withFKs bool + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the AgentTraceFileQuery builder. +func (_q *AgentTraceFileQuery) Where(ps ...predicate.AgentTraceFile) *AgentTraceFileQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *AgentTraceFileQuery) Limit(limit int) *AgentTraceFileQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *AgentTraceFileQuery) Offset(offset int) *AgentTraceFileQuery { + _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 *AgentTraceFileQuery) Unique(unique bool) *AgentTraceFileQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *AgentTraceFileQuery) Order(o ...agenttracefile.OrderOption) *AgentTraceFileQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryTrace chains the current query on the "trace" edge. +func (_q *AgentTraceFileQuery) QueryTrace() *AgentTraceQuery { + query := (&AgentTraceClient{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(agenttracefile.Table, agenttracefile.FieldID, selector), + sqlgraph.To(agenttrace.Table, agenttrace.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, agenttracefile.TraceTable, agenttracefile.TraceColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryConversations chains the current query on the "conversations" edge. +func (_q *AgentTraceFileQuery) QueryConversations() *AgentTraceConversationQuery { + query := (&AgentTraceConversationClient{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(agenttracefile.Table, agenttracefile.FieldID, selector), + sqlgraph.To(agenttraceconversation.Table, agenttraceconversation.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, agenttracefile.ConversationsTable, agenttracefile.ConversationsColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first AgentTraceFile entity from the query. +// Returns a *NotFoundError when no AgentTraceFile was found. +func (_q *AgentTraceFileQuery) First(ctx context.Context) (*AgentTraceFile, 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{agenttracefile.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *AgentTraceFileQuery) FirstX(ctx context.Context) *AgentTraceFile { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first AgentTraceFile ID from the query. +// Returns a *NotFoundError when no AgentTraceFile ID was found. +func (_q *AgentTraceFileQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{agenttracefile.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *AgentTraceFileQuery) FirstIDX(ctx context.Context) int { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single AgentTraceFile entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one AgentTraceFile entity is found. +// Returns a *NotFoundError when no AgentTraceFile entities are found. +func (_q *AgentTraceFileQuery) Only(ctx context.Context) (*AgentTraceFile, 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{agenttracefile.Label} + default: + return nil, &NotSingularError{agenttracefile.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *AgentTraceFileQuery) OnlyX(ctx context.Context) *AgentTraceFile { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only AgentTraceFile ID in the query. +// Returns a *NotSingularError when more than one AgentTraceFile ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *AgentTraceFileQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + 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{agenttracefile.Label} + default: + err = &NotSingularError{agenttracefile.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *AgentTraceFileQuery) OnlyIDX(ctx context.Context) int { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of AgentTraceFiles. +func (_q *AgentTraceFileQuery) All(ctx context.Context) ([]*AgentTraceFile, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*AgentTraceFile, *AgentTraceFileQuery]() + return withInterceptors[[]*AgentTraceFile](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *AgentTraceFileQuery) AllX(ctx context.Context) []*AgentTraceFile { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of AgentTraceFile IDs. +func (_q *AgentTraceFileQuery) IDs(ctx context.Context) (ids []int, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(agenttracefile.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *AgentTraceFileQuery) IDsX(ctx context.Context) []int { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *AgentTraceFileQuery) 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[*AgentTraceFileQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *AgentTraceFileQuery) 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 *AgentTraceFileQuery) 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("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *AgentTraceFileQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the AgentTraceFileQuery 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 *AgentTraceFileQuery) Clone() *AgentTraceFileQuery { + if _q == nil { + return nil + } + return &AgentTraceFileQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]agenttracefile.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.AgentTraceFile{}, _q.predicates...), + withTrace: _q.withTrace.Clone(), + withConversations: _q.withConversations.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithTrace tells the query-builder to eager-load the nodes that are connected to +// the "trace" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *AgentTraceFileQuery) WithTrace(opts ...func(*AgentTraceQuery)) *AgentTraceFileQuery { + query := (&AgentTraceClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withTrace = query + return _q +} + +// WithConversations tells the query-builder to eager-load the nodes that are connected to +// the "conversations" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *AgentTraceFileQuery) WithConversations(opts ...func(*AgentTraceConversationQuery)) *AgentTraceFileQuery { + query := (&AgentTraceConversationClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withConversations = 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 { +// Path string `json:"path,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.AgentTraceFile.Query(). +// GroupBy(agenttracefile.FieldPath). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *AgentTraceFileQuery) GroupBy(field string, fields ...string) *AgentTraceFileGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &AgentTraceFileGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = agenttracefile.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 { +// Path string `json:"path,omitempty"` +// } +// +// client.AgentTraceFile.Query(). +// Select(agenttracefile.FieldPath). +// Scan(ctx, &v) +func (_q *AgentTraceFileQuery) Select(fields ...string) *AgentTraceFileSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &AgentTraceFileSelect{AgentTraceFileQuery: _q} + sbuild.label = agenttracefile.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a AgentTraceFileSelect configured with the given aggregations. +func (_q *AgentTraceFileQuery) Aggregate(fns ...AggregateFunc) *AgentTraceFileSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *AgentTraceFileQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !agenttracefile.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: 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 *AgentTraceFileQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AgentTraceFile, error) { + var ( + nodes = []*AgentTraceFile{} + withFKs = _q.withFKs + _spec = _q.querySpec() + loadedTypes = [2]bool{ + _q.withTrace != nil, + _q.withConversations != nil, + } + ) + if _q.withTrace != nil { + withFKs = true + } + if withFKs { + _spec.Node.Columns = append(_spec.Node.Columns, agenttracefile.ForeignKeys...) + } + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*AgentTraceFile).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &AgentTraceFile{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withTrace; query != nil { + if err := _q.loadTrace(ctx, query, nodes, nil, + func(n *AgentTraceFile, e *AgentTrace) { n.Edges.Trace = e }); err != nil { + return nil, err + } + } + if query := _q.withConversations; query != nil { + if err := _q.loadConversations(ctx, query, nodes, + func(n *AgentTraceFile) { n.Edges.Conversations = []*AgentTraceConversation{} }, + func(n *AgentTraceFile, e *AgentTraceConversation) { + n.Edges.Conversations = append(n.Edges.Conversations, e) + }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *AgentTraceFileQuery) loadTrace(ctx context.Context, query *AgentTraceQuery, nodes []*AgentTraceFile, init func(*AgentTraceFile), assign func(*AgentTraceFile, *AgentTrace)) error { + ids := make([]string, 0, len(nodes)) + nodeids := make(map[string][]*AgentTraceFile) + for i := range nodes { + if nodes[i].agent_trace_files == nil { + continue + } + fk := *nodes[i].agent_trace_files + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(agenttrace.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 "agent_trace_files" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (_q *AgentTraceFileQuery) loadConversations(ctx context.Context, query *AgentTraceConversationQuery, nodes []*AgentTraceFile, init func(*AgentTraceFile), assign func(*AgentTraceFile, *AgentTraceConversation)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*AgentTraceFile) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + query.withFKs = true + query.Where(predicate.AgentTraceConversation(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(agenttracefile.ConversationsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.agent_trace_file_conversations + if fk == nil { + return fmt.Errorf(`foreign-key "agent_trace_file_conversations" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "agent_trace_file_conversations" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (_q *AgentTraceFileQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _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 *AgentTraceFileQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(agenttracefile.Table, agenttracefile.Columns, sqlgraph.NewFieldSpec(agenttracefile.FieldID, field.TypeInt)) + _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, agenttracefile.FieldID) + for i := range fields { + if fields[i] != agenttracefile.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + 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 *AgentTraceFileQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(agenttracefile.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = agenttracefile.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 _, 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 +} + +// AgentTraceFileGroupBy is the group-by builder for AgentTraceFile entities. +type AgentTraceFileGroupBy struct { + selector + build *AgentTraceFileQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *AgentTraceFileGroupBy) Aggregate(fns ...AggregateFunc) *AgentTraceFileGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *AgentTraceFileGroupBy) 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[*AgentTraceFileQuery, *AgentTraceFileGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *AgentTraceFileGroupBy) sqlScan(ctx context.Context, root *AgentTraceFileQuery, 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) +} + +// AgentTraceFileSelect is the builder for selecting fields of AgentTraceFile entities. +type AgentTraceFileSelect struct { + *AgentTraceFileQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *AgentTraceFileSelect) Aggregate(fns ...AggregateFunc) *AgentTraceFileSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *AgentTraceFileSelect) 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[*AgentTraceFileQuery, *AgentTraceFileSelect](ctx, _s.AgentTraceFileQuery, _s, _s.inters, v) +} + +func (_s *AgentTraceFileSelect) sqlScan(ctx context.Context, root *AgentTraceFileQuery, 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) +} diff --git a/pkg/storage/ent/agenttracefile_update.go b/pkg/storage/ent/agenttracefile_update.go new file mode 100644 index 0000000..d01c866 --- /dev/null +++ b/pkg/storage/ent/agenttracefile_update.go @@ -0,0 +1,497 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttrace" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttraceconversation" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttracefile" + "github.com/papercomputeco/tapes/pkg/storage/ent/predicate" +) + +// AgentTraceFileUpdate is the builder for updating AgentTraceFile entities. +type AgentTraceFileUpdate struct { + config + hooks []Hook + mutation *AgentTraceFileMutation +} + +// Where appends a list predicates to the AgentTraceFileUpdate builder. +func (_u *AgentTraceFileUpdate) Where(ps ...predicate.AgentTraceFile) *AgentTraceFileUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetPath sets the "path" field. +func (_u *AgentTraceFileUpdate) SetPath(v string) *AgentTraceFileUpdate { + _u.mutation.SetPath(v) + return _u +} + +// SetNillablePath sets the "path" field if the given value is not nil. +func (_u *AgentTraceFileUpdate) SetNillablePath(v *string) *AgentTraceFileUpdate { + if v != nil { + _u.SetPath(*v) + } + return _u +} + +// SetTraceID sets the "trace" edge to the AgentTrace entity by ID. +func (_u *AgentTraceFileUpdate) SetTraceID(id string) *AgentTraceFileUpdate { + _u.mutation.SetTraceID(id) + return _u +} + +// SetTrace sets the "trace" edge to the AgentTrace entity. +func (_u *AgentTraceFileUpdate) SetTrace(v *AgentTrace) *AgentTraceFileUpdate { + return _u.SetTraceID(v.ID) +} + +// AddConversationIDs adds the "conversations" edge to the AgentTraceConversation entity by IDs. +func (_u *AgentTraceFileUpdate) AddConversationIDs(ids ...int) *AgentTraceFileUpdate { + _u.mutation.AddConversationIDs(ids...) + return _u +} + +// AddConversations adds the "conversations" edges to the AgentTraceConversation entity. +func (_u *AgentTraceFileUpdate) AddConversations(v ...*AgentTraceConversation) *AgentTraceFileUpdate { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddConversationIDs(ids...) +} + +// Mutation returns the AgentTraceFileMutation object of the builder. +func (_u *AgentTraceFileUpdate) Mutation() *AgentTraceFileMutation { + return _u.mutation +} + +// ClearTrace clears the "trace" edge to the AgentTrace entity. +func (_u *AgentTraceFileUpdate) ClearTrace() *AgentTraceFileUpdate { + _u.mutation.ClearTrace() + return _u +} + +// ClearConversations clears all "conversations" edges to the AgentTraceConversation entity. +func (_u *AgentTraceFileUpdate) ClearConversations() *AgentTraceFileUpdate { + _u.mutation.ClearConversations() + return _u +} + +// RemoveConversationIDs removes the "conversations" edge to AgentTraceConversation entities by IDs. +func (_u *AgentTraceFileUpdate) RemoveConversationIDs(ids ...int) *AgentTraceFileUpdate { + _u.mutation.RemoveConversationIDs(ids...) + return _u +} + +// RemoveConversations removes "conversations" edges to AgentTraceConversation entities. +func (_u *AgentTraceFileUpdate) RemoveConversations(v ...*AgentTraceConversation) *AgentTraceFileUpdate { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveConversationIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *AgentTraceFileUpdate) 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 *AgentTraceFileUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *AgentTraceFileUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *AgentTraceFileUpdate) 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 *AgentTraceFileUpdate) check() error { + if v, ok := _u.mutation.Path(); ok { + if err := agenttracefile.PathValidator(v); err != nil { + return &ValidationError{Name: "path", err: fmt.Errorf(`ent: validator failed for field "AgentTraceFile.path": %w`, err)} + } + } + if _u.mutation.TraceCleared() && len(_u.mutation.TraceIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "AgentTraceFile.trace"`) + } + return nil +} + +func (_u *AgentTraceFileUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(agenttracefile.Table, agenttracefile.Columns, sqlgraph.NewFieldSpec(agenttracefile.FieldID, field.TypeInt)) + 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.Path(); ok { + _spec.SetField(agenttracefile.FieldPath, field.TypeString, value) + } + if _u.mutation.TraceCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agenttracefile.TraceTable, + Columns: []string{agenttracefile.TraceColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttrace.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.TraceIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agenttracefile.TraceTable, + Columns: []string{agenttracefile.TraceColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttrace.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.ConversationsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agenttracefile.ConversationsTable, + Columns: []string{agenttracefile.ConversationsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttraceconversation.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedConversationsIDs(); len(nodes) > 0 && !_u.mutation.ConversationsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agenttracefile.ConversationsTable, + Columns: []string{agenttracefile.ConversationsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttraceconversation.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ConversationsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agenttracefile.ConversationsTable, + Columns: []string{agenttracefile.ConversationsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttraceconversation.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{agenttracefile.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// AgentTraceFileUpdateOne is the builder for updating a single AgentTraceFile entity. +type AgentTraceFileUpdateOne struct { + config + fields []string + hooks []Hook + mutation *AgentTraceFileMutation +} + +// SetPath sets the "path" field. +func (_u *AgentTraceFileUpdateOne) SetPath(v string) *AgentTraceFileUpdateOne { + _u.mutation.SetPath(v) + return _u +} + +// SetNillablePath sets the "path" field if the given value is not nil. +func (_u *AgentTraceFileUpdateOne) SetNillablePath(v *string) *AgentTraceFileUpdateOne { + if v != nil { + _u.SetPath(*v) + } + return _u +} + +// SetTraceID sets the "trace" edge to the AgentTrace entity by ID. +func (_u *AgentTraceFileUpdateOne) SetTraceID(id string) *AgentTraceFileUpdateOne { + _u.mutation.SetTraceID(id) + return _u +} + +// SetTrace sets the "trace" edge to the AgentTrace entity. +func (_u *AgentTraceFileUpdateOne) SetTrace(v *AgentTrace) *AgentTraceFileUpdateOne { + return _u.SetTraceID(v.ID) +} + +// AddConversationIDs adds the "conversations" edge to the AgentTraceConversation entity by IDs. +func (_u *AgentTraceFileUpdateOne) AddConversationIDs(ids ...int) *AgentTraceFileUpdateOne { + _u.mutation.AddConversationIDs(ids...) + return _u +} + +// AddConversations adds the "conversations" edges to the AgentTraceConversation entity. +func (_u *AgentTraceFileUpdateOne) AddConversations(v ...*AgentTraceConversation) *AgentTraceFileUpdateOne { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.AddConversationIDs(ids...) +} + +// Mutation returns the AgentTraceFileMutation object of the builder. +func (_u *AgentTraceFileUpdateOne) Mutation() *AgentTraceFileMutation { + return _u.mutation +} + +// ClearTrace clears the "trace" edge to the AgentTrace entity. +func (_u *AgentTraceFileUpdateOne) ClearTrace() *AgentTraceFileUpdateOne { + _u.mutation.ClearTrace() + return _u +} + +// ClearConversations clears all "conversations" edges to the AgentTraceConversation entity. +func (_u *AgentTraceFileUpdateOne) ClearConversations() *AgentTraceFileUpdateOne { + _u.mutation.ClearConversations() + return _u +} + +// RemoveConversationIDs removes the "conversations" edge to AgentTraceConversation entities by IDs. +func (_u *AgentTraceFileUpdateOne) RemoveConversationIDs(ids ...int) *AgentTraceFileUpdateOne { + _u.mutation.RemoveConversationIDs(ids...) + return _u +} + +// RemoveConversations removes "conversations" edges to AgentTraceConversation entities. +func (_u *AgentTraceFileUpdateOne) RemoveConversations(v ...*AgentTraceConversation) *AgentTraceFileUpdateOne { + ids := make([]int, len(v)) + for i := range v { + ids[i] = v[i].ID + } + return _u.RemoveConversationIDs(ids...) +} + +// Where appends a list predicates to the AgentTraceFileUpdate builder. +func (_u *AgentTraceFileUpdateOne) Where(ps ...predicate.AgentTraceFile) *AgentTraceFileUpdateOne { + _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 *AgentTraceFileUpdateOne) Select(field string, fields ...string) *AgentTraceFileUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated AgentTraceFile entity. +func (_u *AgentTraceFileUpdateOne) Save(ctx context.Context) (*AgentTraceFile, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *AgentTraceFileUpdateOne) SaveX(ctx context.Context) *AgentTraceFile { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *AgentTraceFileUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *AgentTraceFileUpdateOne) 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 *AgentTraceFileUpdateOne) check() error { + if v, ok := _u.mutation.Path(); ok { + if err := agenttracefile.PathValidator(v); err != nil { + return &ValidationError{Name: "path", err: fmt.Errorf(`ent: validator failed for field "AgentTraceFile.path": %w`, err)} + } + } + if _u.mutation.TraceCleared() && len(_u.mutation.TraceIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "AgentTraceFile.trace"`) + } + return nil +} + +func (_u *AgentTraceFileUpdateOne) sqlSave(ctx context.Context) (_node *AgentTraceFile, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(agenttracefile.Table, agenttracefile.Columns, sqlgraph.NewFieldSpec(agenttracefile.FieldID, field.TypeInt)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "AgentTraceFile.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, agenttracefile.FieldID) + for _, f := range fields { + if !agenttracefile.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != agenttracefile.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.Path(); ok { + _spec.SetField(agenttracefile.FieldPath, field.TypeString, value) + } + if _u.mutation.TraceCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agenttracefile.TraceTable, + Columns: []string{agenttracefile.TraceColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttrace.FieldID, field.TypeString), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.TraceIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agenttracefile.TraceTable, + Columns: []string{agenttracefile.TraceColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttrace.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.ConversationsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agenttracefile.ConversationsTable, + Columns: []string{agenttracefile.ConversationsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttraceconversation.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.RemovedConversationsIDs(); len(nodes) > 0 && !_u.mutation.ConversationsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agenttracefile.ConversationsTable, + Columns: []string{agenttracefile.ConversationsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttraceconversation.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ConversationsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: agenttracefile.ConversationsTable, + Columns: []string{agenttracefile.ConversationsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttraceconversation.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &AgentTraceFile{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{agenttracefile.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/pkg/storage/ent/agenttracerange.go b/pkg/storage/ent/agenttracerange.go new file mode 100644 index 0000000..eb92641 --- /dev/null +++ b/pkg/storage/ent/agenttracerange.go @@ -0,0 +1,186 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttraceconversation" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttracerange" +) + +// AgentTraceRange is the model entity for the AgentTraceRange schema. +type AgentTraceRange struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // StartLine holds the value of the "start_line" field. + StartLine int `json:"start_line,omitempty"` + // EndLine holds the value of the "end_line" field. + EndLine int `json:"end_line,omitempty"` + // ContentHash holds the value of the "content_hash" field. + ContentHash string `json:"content_hash,omitempty"` + // ContributorType holds the value of the "contributor_type" field. + ContributorType string `json:"contributor_type,omitempty"` + // ContributorModelID holds the value of the "contributor_model_id" field. + ContributorModelID string `json:"contributor_model_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the AgentTraceRangeQuery when eager-loading is set. + Edges AgentTraceRangeEdges `json:"edges"` + agent_trace_conversation_ranges *int + selectValues sql.SelectValues +} + +// AgentTraceRangeEdges holds the relations/edges for other nodes in the graph. +type AgentTraceRangeEdges struct { + // Conversation holds the value of the conversation edge. + Conversation *AgentTraceConversation `json:"conversation,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool +} + +// ConversationOrErr returns the Conversation value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e AgentTraceRangeEdges) ConversationOrErr() (*AgentTraceConversation, error) { + if e.Conversation != nil { + return e.Conversation, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: agenttraceconversation.Label} + } + return nil, &NotLoadedError{edge: "conversation"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*AgentTraceRange) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case agenttracerange.FieldID, agenttracerange.FieldStartLine, agenttracerange.FieldEndLine: + values[i] = new(sql.NullInt64) + case agenttracerange.FieldContentHash, agenttracerange.FieldContributorType, agenttracerange.FieldContributorModelID: + values[i] = new(sql.NullString) + case agenttracerange.ForeignKeys[0]: // agent_trace_conversation_ranges + values[i] = new(sql.NullInt64) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the AgentTraceRange fields. +func (_m *AgentTraceRange) 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 agenttracerange.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + _m.ID = int(value.Int64) + case agenttracerange.FieldStartLine: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field start_line", values[i]) + } else if value.Valid { + _m.StartLine = int(value.Int64) + } + case agenttracerange.FieldEndLine: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field end_line", values[i]) + } else if value.Valid { + _m.EndLine = int(value.Int64) + } + case agenttracerange.FieldContentHash: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field content_hash", values[i]) + } else if value.Valid { + _m.ContentHash = value.String + } + case agenttracerange.FieldContributorType: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field contributor_type", values[i]) + } else if value.Valid { + _m.ContributorType = value.String + } + case agenttracerange.FieldContributorModelID: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field contributor_model_id", values[i]) + } else if value.Valid { + _m.ContributorModelID = value.String + } + case agenttracerange.ForeignKeys[0]: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for edge-field agent_trace_conversation_ranges", value) + } else if value.Valid { + _m.agent_trace_conversation_ranges = new(int) + *_m.agent_trace_conversation_ranges = int(value.Int64) + } + default: + _m.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the AgentTraceRange. +// This includes values selected through modifiers, order, etc. +func (_m *AgentTraceRange) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) +} + +// QueryConversation queries the "conversation" edge of the AgentTraceRange entity. +func (_m *AgentTraceRange) QueryConversation() *AgentTraceConversationQuery { + return NewAgentTraceRangeClient(_m.config).QueryConversation(_m) +} + +// Update returns a builder for updating this AgentTraceRange. +// Note that you need to call AgentTraceRange.Unwrap() before calling this method if this AgentTraceRange +// was returned from a transaction, and the transaction was committed or rolled back. +func (_m *AgentTraceRange) Update() *AgentTraceRangeUpdateOne { + return NewAgentTraceRangeClient(_m.config).UpdateOne(_m) +} + +// Unwrap unwraps the AgentTraceRange 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 *AgentTraceRange) Unwrap() *AgentTraceRange { + _tx, ok := _m.config.driver.(*txDriver) + if !ok { + panic("ent: AgentTraceRange is not a transactional entity") + } + _m.config.driver = _tx.drv + return _m +} + +// String implements the fmt.Stringer. +func (_m *AgentTraceRange) String() string { + var builder strings.Builder + builder.WriteString("AgentTraceRange(") + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) + builder.WriteString("start_line=") + builder.WriteString(fmt.Sprintf("%v", _m.StartLine)) + builder.WriteString(", ") + builder.WriteString("end_line=") + builder.WriteString(fmt.Sprintf("%v", _m.EndLine)) + builder.WriteString(", ") + builder.WriteString("content_hash=") + builder.WriteString(_m.ContentHash) + builder.WriteString(", ") + builder.WriteString("contributor_type=") + builder.WriteString(_m.ContributorType) + builder.WriteString(", ") + builder.WriteString("contributor_model_id=") + builder.WriteString(_m.ContributorModelID) + builder.WriteByte(')') + return builder.String() +} + +// AgentTraceRanges is a parsable slice of AgentTraceRange. +type AgentTraceRanges []*AgentTraceRange diff --git a/pkg/storage/ent/agenttracerange/agenttracerange.go b/pkg/storage/ent/agenttracerange/agenttracerange.go new file mode 100644 index 0000000..b6c8ff4 --- /dev/null +++ b/pkg/storage/ent/agenttracerange/agenttracerange.go @@ -0,0 +1,114 @@ +// Code generated by ent, DO NOT EDIT. + +package agenttracerange + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the agenttracerange type in the database. + Label = "agent_trace_range" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldStartLine holds the string denoting the start_line field in the database. + FieldStartLine = "start_line" + // FieldEndLine holds the string denoting the end_line field in the database. + FieldEndLine = "end_line" + // FieldContentHash holds the string denoting the content_hash field in the database. + FieldContentHash = "content_hash" + // FieldContributorType holds the string denoting the contributor_type field in the database. + FieldContributorType = "contributor_type" + // FieldContributorModelID holds the string denoting the contributor_model_id field in the database. + FieldContributorModelID = "contributor_model_id" + // EdgeConversation holds the string denoting the conversation edge name in mutations. + EdgeConversation = "conversation" + // Table holds the table name of the agenttracerange in the database. + Table = "agent_trace_ranges" + // ConversationTable is the table that holds the conversation relation/edge. + ConversationTable = "agent_trace_ranges" + // ConversationInverseTable is the table name for the AgentTraceConversation entity. + // It exists in this package in order to avoid circular dependency with the "agenttraceconversation" package. + ConversationInverseTable = "agent_trace_conversations" + // ConversationColumn is the table column denoting the conversation relation/edge. + ConversationColumn = "agent_trace_conversation_ranges" +) + +// Columns holds all SQL columns for agenttracerange fields. +var Columns = []string{ + FieldID, + FieldStartLine, + FieldEndLine, + FieldContentHash, + FieldContributorType, + FieldContributorModelID, +} + +// ForeignKeys holds the SQL foreign-keys that are owned by the "agent_trace_ranges" +// table and are not defined as standalone fields in the schema. +var ForeignKeys = []string{ + "agent_trace_conversation_ranges", +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + for i := range ForeignKeys { + if column == ForeignKeys[i] { + return true + } + } + return false +} + +// OrderOption defines the ordering options for the AgentTraceRange 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() +} + +// ByStartLine orders the results by the start_line field. +func ByStartLine(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStartLine, opts...).ToFunc() +} + +// ByEndLine orders the results by the end_line field. +func ByEndLine(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldEndLine, opts...).ToFunc() +} + +// ByContentHash orders the results by the content_hash field. +func ByContentHash(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldContentHash, opts...).ToFunc() +} + +// ByContributorType orders the results by the contributor_type field. +func ByContributorType(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldContributorType, opts...).ToFunc() +} + +// ByContributorModelID orders the results by the contributor_model_id field. +func ByContributorModelID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldContributorModelID, opts...).ToFunc() +} + +// ByConversationField orders the results by conversation field. +func ByConversationField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newConversationStep(), sql.OrderByField(field, opts...)) + } +} +func newConversationStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(ConversationInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ConversationTable, ConversationColumn), + ) +} diff --git a/pkg/storage/ent/agenttracerange/where.go b/pkg/storage/ent/agenttracerange/where.go new file mode 100644 index 0000000..b706d5d --- /dev/null +++ b/pkg/storage/ent/agenttracerange/where.go @@ -0,0 +1,422 @@ +// Code generated by ent, DO NOT EDIT. + +package agenttracerange + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/papercomputeco/tapes/pkg/storage/ent/predicate" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldLTE(FieldID, id)) +} + +// StartLine applies equality check predicate on the "start_line" field. It's identical to StartLineEQ. +func StartLine(v int) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldEQ(FieldStartLine, v)) +} + +// EndLine applies equality check predicate on the "end_line" field. It's identical to EndLineEQ. +func EndLine(v int) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldEQ(FieldEndLine, v)) +} + +// ContentHash applies equality check predicate on the "content_hash" field. It's identical to ContentHashEQ. +func ContentHash(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldEQ(FieldContentHash, v)) +} + +// ContributorType applies equality check predicate on the "contributor_type" field. It's identical to ContributorTypeEQ. +func ContributorType(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldEQ(FieldContributorType, v)) +} + +// ContributorModelID applies equality check predicate on the "contributor_model_id" field. It's identical to ContributorModelIDEQ. +func ContributorModelID(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldEQ(FieldContributorModelID, v)) +} + +// StartLineEQ applies the EQ predicate on the "start_line" field. +func StartLineEQ(v int) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldEQ(FieldStartLine, v)) +} + +// StartLineNEQ applies the NEQ predicate on the "start_line" field. +func StartLineNEQ(v int) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldNEQ(FieldStartLine, v)) +} + +// StartLineIn applies the In predicate on the "start_line" field. +func StartLineIn(vs ...int) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldIn(FieldStartLine, vs...)) +} + +// StartLineNotIn applies the NotIn predicate on the "start_line" field. +func StartLineNotIn(vs ...int) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldNotIn(FieldStartLine, vs...)) +} + +// StartLineGT applies the GT predicate on the "start_line" field. +func StartLineGT(v int) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldGT(FieldStartLine, v)) +} + +// StartLineGTE applies the GTE predicate on the "start_line" field. +func StartLineGTE(v int) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldGTE(FieldStartLine, v)) +} + +// StartLineLT applies the LT predicate on the "start_line" field. +func StartLineLT(v int) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldLT(FieldStartLine, v)) +} + +// StartLineLTE applies the LTE predicate on the "start_line" field. +func StartLineLTE(v int) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldLTE(FieldStartLine, v)) +} + +// EndLineEQ applies the EQ predicate on the "end_line" field. +func EndLineEQ(v int) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldEQ(FieldEndLine, v)) +} + +// EndLineNEQ applies the NEQ predicate on the "end_line" field. +func EndLineNEQ(v int) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldNEQ(FieldEndLine, v)) +} + +// EndLineIn applies the In predicate on the "end_line" field. +func EndLineIn(vs ...int) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldIn(FieldEndLine, vs...)) +} + +// EndLineNotIn applies the NotIn predicate on the "end_line" field. +func EndLineNotIn(vs ...int) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldNotIn(FieldEndLine, vs...)) +} + +// EndLineGT applies the GT predicate on the "end_line" field. +func EndLineGT(v int) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldGT(FieldEndLine, v)) +} + +// EndLineGTE applies the GTE predicate on the "end_line" field. +func EndLineGTE(v int) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldGTE(FieldEndLine, v)) +} + +// EndLineLT applies the LT predicate on the "end_line" field. +func EndLineLT(v int) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldLT(FieldEndLine, v)) +} + +// EndLineLTE applies the LTE predicate on the "end_line" field. +func EndLineLTE(v int) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldLTE(FieldEndLine, v)) +} + +// ContentHashEQ applies the EQ predicate on the "content_hash" field. +func ContentHashEQ(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldEQ(FieldContentHash, v)) +} + +// ContentHashNEQ applies the NEQ predicate on the "content_hash" field. +func ContentHashNEQ(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldNEQ(FieldContentHash, v)) +} + +// ContentHashIn applies the In predicate on the "content_hash" field. +func ContentHashIn(vs ...string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldIn(FieldContentHash, vs...)) +} + +// ContentHashNotIn applies the NotIn predicate on the "content_hash" field. +func ContentHashNotIn(vs ...string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldNotIn(FieldContentHash, vs...)) +} + +// ContentHashGT applies the GT predicate on the "content_hash" field. +func ContentHashGT(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldGT(FieldContentHash, v)) +} + +// ContentHashGTE applies the GTE predicate on the "content_hash" field. +func ContentHashGTE(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldGTE(FieldContentHash, v)) +} + +// ContentHashLT applies the LT predicate on the "content_hash" field. +func ContentHashLT(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldLT(FieldContentHash, v)) +} + +// ContentHashLTE applies the LTE predicate on the "content_hash" field. +func ContentHashLTE(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldLTE(FieldContentHash, v)) +} + +// ContentHashContains applies the Contains predicate on the "content_hash" field. +func ContentHashContains(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldContains(FieldContentHash, v)) +} + +// ContentHashHasPrefix applies the HasPrefix predicate on the "content_hash" field. +func ContentHashHasPrefix(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldHasPrefix(FieldContentHash, v)) +} + +// ContentHashHasSuffix applies the HasSuffix predicate on the "content_hash" field. +func ContentHashHasSuffix(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldHasSuffix(FieldContentHash, v)) +} + +// ContentHashIsNil applies the IsNil predicate on the "content_hash" field. +func ContentHashIsNil() predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldIsNull(FieldContentHash)) +} + +// ContentHashNotNil applies the NotNil predicate on the "content_hash" field. +func ContentHashNotNil() predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldNotNull(FieldContentHash)) +} + +// ContentHashEqualFold applies the EqualFold predicate on the "content_hash" field. +func ContentHashEqualFold(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldEqualFold(FieldContentHash, v)) +} + +// ContentHashContainsFold applies the ContainsFold predicate on the "content_hash" field. +func ContentHashContainsFold(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldContainsFold(FieldContentHash, v)) +} + +// ContributorTypeEQ applies the EQ predicate on the "contributor_type" field. +func ContributorTypeEQ(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldEQ(FieldContributorType, v)) +} + +// ContributorTypeNEQ applies the NEQ predicate on the "contributor_type" field. +func ContributorTypeNEQ(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldNEQ(FieldContributorType, v)) +} + +// ContributorTypeIn applies the In predicate on the "contributor_type" field. +func ContributorTypeIn(vs ...string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldIn(FieldContributorType, vs...)) +} + +// ContributorTypeNotIn applies the NotIn predicate on the "contributor_type" field. +func ContributorTypeNotIn(vs ...string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldNotIn(FieldContributorType, vs...)) +} + +// ContributorTypeGT applies the GT predicate on the "contributor_type" field. +func ContributorTypeGT(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldGT(FieldContributorType, v)) +} + +// ContributorTypeGTE applies the GTE predicate on the "contributor_type" field. +func ContributorTypeGTE(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldGTE(FieldContributorType, v)) +} + +// ContributorTypeLT applies the LT predicate on the "contributor_type" field. +func ContributorTypeLT(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldLT(FieldContributorType, v)) +} + +// ContributorTypeLTE applies the LTE predicate on the "contributor_type" field. +func ContributorTypeLTE(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldLTE(FieldContributorType, v)) +} + +// ContributorTypeContains applies the Contains predicate on the "contributor_type" field. +func ContributorTypeContains(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldContains(FieldContributorType, v)) +} + +// ContributorTypeHasPrefix applies the HasPrefix predicate on the "contributor_type" field. +func ContributorTypeHasPrefix(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldHasPrefix(FieldContributorType, v)) +} + +// ContributorTypeHasSuffix applies the HasSuffix predicate on the "contributor_type" field. +func ContributorTypeHasSuffix(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldHasSuffix(FieldContributorType, v)) +} + +// ContributorTypeIsNil applies the IsNil predicate on the "contributor_type" field. +func ContributorTypeIsNil() predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldIsNull(FieldContributorType)) +} + +// ContributorTypeNotNil applies the NotNil predicate on the "contributor_type" field. +func ContributorTypeNotNil() predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldNotNull(FieldContributorType)) +} + +// ContributorTypeEqualFold applies the EqualFold predicate on the "contributor_type" field. +func ContributorTypeEqualFold(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldEqualFold(FieldContributorType, v)) +} + +// ContributorTypeContainsFold applies the ContainsFold predicate on the "contributor_type" field. +func ContributorTypeContainsFold(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldContainsFold(FieldContributorType, v)) +} + +// ContributorModelIDEQ applies the EQ predicate on the "contributor_model_id" field. +func ContributorModelIDEQ(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldEQ(FieldContributorModelID, v)) +} + +// ContributorModelIDNEQ applies the NEQ predicate on the "contributor_model_id" field. +func ContributorModelIDNEQ(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldNEQ(FieldContributorModelID, v)) +} + +// ContributorModelIDIn applies the In predicate on the "contributor_model_id" field. +func ContributorModelIDIn(vs ...string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldIn(FieldContributorModelID, vs...)) +} + +// ContributorModelIDNotIn applies the NotIn predicate on the "contributor_model_id" field. +func ContributorModelIDNotIn(vs ...string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldNotIn(FieldContributorModelID, vs...)) +} + +// ContributorModelIDGT applies the GT predicate on the "contributor_model_id" field. +func ContributorModelIDGT(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldGT(FieldContributorModelID, v)) +} + +// ContributorModelIDGTE applies the GTE predicate on the "contributor_model_id" field. +func ContributorModelIDGTE(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldGTE(FieldContributorModelID, v)) +} + +// ContributorModelIDLT applies the LT predicate on the "contributor_model_id" field. +func ContributorModelIDLT(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldLT(FieldContributorModelID, v)) +} + +// ContributorModelIDLTE applies the LTE predicate on the "contributor_model_id" field. +func ContributorModelIDLTE(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldLTE(FieldContributorModelID, v)) +} + +// ContributorModelIDContains applies the Contains predicate on the "contributor_model_id" field. +func ContributorModelIDContains(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldContains(FieldContributorModelID, v)) +} + +// ContributorModelIDHasPrefix applies the HasPrefix predicate on the "contributor_model_id" field. +func ContributorModelIDHasPrefix(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldHasPrefix(FieldContributorModelID, v)) +} + +// ContributorModelIDHasSuffix applies the HasSuffix predicate on the "contributor_model_id" field. +func ContributorModelIDHasSuffix(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldHasSuffix(FieldContributorModelID, v)) +} + +// ContributorModelIDIsNil applies the IsNil predicate on the "contributor_model_id" field. +func ContributorModelIDIsNil() predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldIsNull(FieldContributorModelID)) +} + +// ContributorModelIDNotNil applies the NotNil predicate on the "contributor_model_id" field. +func ContributorModelIDNotNil() predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldNotNull(FieldContributorModelID)) +} + +// ContributorModelIDEqualFold applies the EqualFold predicate on the "contributor_model_id" field. +func ContributorModelIDEqualFold(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldEqualFold(FieldContributorModelID, v)) +} + +// ContributorModelIDContainsFold applies the ContainsFold predicate on the "contributor_model_id" field. +func ContributorModelIDContainsFold(v string) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.FieldContainsFold(FieldContributorModelID, v)) +} + +// HasConversation applies the HasEdge predicate on the "conversation" edge. +func HasConversation() predicate.AgentTraceRange { + return predicate.AgentTraceRange(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ConversationTable, ConversationColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasConversationWith applies the HasEdge predicate on the "conversation" edge with a given conditions (other predicates). +func HasConversationWith(preds ...predicate.AgentTraceConversation) predicate.AgentTraceRange { + return predicate.AgentTraceRange(func(s *sql.Selector) { + step := newConversationStep() + 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.AgentTraceRange) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.AgentTraceRange) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.AgentTraceRange) predicate.AgentTraceRange { + return predicate.AgentTraceRange(sql.NotPredicates(p)) +} diff --git a/pkg/storage/ent/agenttracerange_create.go b/pkg/storage/ent/agenttracerange_create.go new file mode 100644 index 0000000..9960987 --- /dev/null +++ b/pkg/storage/ent/agenttracerange_create.go @@ -0,0 +1,282 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttraceconversation" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttracerange" +) + +// AgentTraceRangeCreate is the builder for creating a AgentTraceRange entity. +type AgentTraceRangeCreate struct { + config + mutation *AgentTraceRangeMutation + hooks []Hook +} + +// SetStartLine sets the "start_line" field. +func (_c *AgentTraceRangeCreate) SetStartLine(v int) *AgentTraceRangeCreate { + _c.mutation.SetStartLine(v) + return _c +} + +// SetEndLine sets the "end_line" field. +func (_c *AgentTraceRangeCreate) SetEndLine(v int) *AgentTraceRangeCreate { + _c.mutation.SetEndLine(v) + return _c +} + +// SetContentHash sets the "content_hash" field. +func (_c *AgentTraceRangeCreate) SetContentHash(v string) *AgentTraceRangeCreate { + _c.mutation.SetContentHash(v) + return _c +} + +// SetNillableContentHash sets the "content_hash" field if the given value is not nil. +func (_c *AgentTraceRangeCreate) SetNillableContentHash(v *string) *AgentTraceRangeCreate { + if v != nil { + _c.SetContentHash(*v) + } + return _c +} + +// SetContributorType sets the "contributor_type" field. +func (_c *AgentTraceRangeCreate) SetContributorType(v string) *AgentTraceRangeCreate { + _c.mutation.SetContributorType(v) + return _c +} + +// SetNillableContributorType sets the "contributor_type" field if the given value is not nil. +func (_c *AgentTraceRangeCreate) SetNillableContributorType(v *string) *AgentTraceRangeCreate { + if v != nil { + _c.SetContributorType(*v) + } + return _c +} + +// SetContributorModelID sets the "contributor_model_id" field. +func (_c *AgentTraceRangeCreate) SetContributorModelID(v string) *AgentTraceRangeCreate { + _c.mutation.SetContributorModelID(v) + return _c +} + +// SetNillableContributorModelID sets the "contributor_model_id" field if the given value is not nil. +func (_c *AgentTraceRangeCreate) SetNillableContributorModelID(v *string) *AgentTraceRangeCreate { + if v != nil { + _c.SetContributorModelID(*v) + } + return _c +} + +// SetConversationID sets the "conversation" edge to the AgentTraceConversation entity by ID. +func (_c *AgentTraceRangeCreate) SetConversationID(id int) *AgentTraceRangeCreate { + _c.mutation.SetConversationID(id) + return _c +} + +// SetConversation sets the "conversation" edge to the AgentTraceConversation entity. +func (_c *AgentTraceRangeCreate) SetConversation(v *AgentTraceConversation) *AgentTraceRangeCreate { + return _c.SetConversationID(v.ID) +} + +// Mutation returns the AgentTraceRangeMutation object of the builder. +func (_c *AgentTraceRangeCreate) Mutation() *AgentTraceRangeMutation { + return _c.mutation +} + +// Save creates the AgentTraceRange in the database. +func (_c *AgentTraceRangeCreate) Save(ctx context.Context) (*AgentTraceRange, error) { + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (_c *AgentTraceRangeCreate) SaveX(ctx context.Context) *AgentTraceRange { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *AgentTraceRangeCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *AgentTraceRangeCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (_c *AgentTraceRangeCreate) check() error { + if _, ok := _c.mutation.StartLine(); !ok { + return &ValidationError{Name: "start_line", err: errors.New(`ent: missing required field "AgentTraceRange.start_line"`)} + } + if _, ok := _c.mutation.EndLine(); !ok { + return &ValidationError{Name: "end_line", err: errors.New(`ent: missing required field "AgentTraceRange.end_line"`)} + } + if len(_c.mutation.ConversationIDs()) == 0 { + return &ValidationError{Name: "conversation", err: errors.New(`ent: missing required edge "AgentTraceRange.conversation"`)} + } + return nil +} + +func (_c *AgentTraceRangeCreate) sqlSave(ctx context.Context) (*AgentTraceRange, 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 + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + _c.mutation.id = &_node.ID + _c.mutation.done = true + return _node, nil +} + +func (_c *AgentTraceRangeCreate) createSpec() (*AgentTraceRange, *sqlgraph.CreateSpec) { + var ( + _node = &AgentTraceRange{config: _c.config} + _spec = sqlgraph.NewCreateSpec(agenttracerange.Table, sqlgraph.NewFieldSpec(agenttracerange.FieldID, field.TypeInt)) + ) + if value, ok := _c.mutation.StartLine(); ok { + _spec.SetField(agenttracerange.FieldStartLine, field.TypeInt, value) + _node.StartLine = value + } + if value, ok := _c.mutation.EndLine(); ok { + _spec.SetField(agenttracerange.FieldEndLine, field.TypeInt, value) + _node.EndLine = value + } + if value, ok := _c.mutation.ContentHash(); ok { + _spec.SetField(agenttracerange.FieldContentHash, field.TypeString, value) + _node.ContentHash = value + } + if value, ok := _c.mutation.ContributorType(); ok { + _spec.SetField(agenttracerange.FieldContributorType, field.TypeString, value) + _node.ContributorType = value + } + if value, ok := _c.mutation.ContributorModelID(); ok { + _spec.SetField(agenttracerange.FieldContributorModelID, field.TypeString, value) + _node.ContributorModelID = value + } + if nodes := _c.mutation.ConversationIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agenttracerange.ConversationTable, + Columns: []string{agenttracerange.ConversationColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttraceconversation.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.agent_trace_conversation_ranges = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// AgentTraceRangeCreateBulk is the builder for creating many AgentTraceRange entities in bulk. +type AgentTraceRangeCreateBulk struct { + config + err error + builders []*AgentTraceRangeCreate +} + +// Save creates the AgentTraceRange entities in the database. +func (_c *AgentTraceRangeCreateBulk) Save(ctx context.Context) ([]*AgentTraceRange, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*AgentTraceRange, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { + func(i int, root context.Context) { + builder := _c.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*AgentTraceRangeMutation) + 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} + // 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 + if specs[i].ID.Value != nil { + id := specs[i].ID.Value.(int64) + nodes[i].ID = int(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 *AgentTraceRangeCreateBulk) SaveX(ctx context.Context) []*AgentTraceRange { + v, err := _c.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (_c *AgentTraceRangeCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_c *AgentTraceRangeCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/pkg/storage/ent/agenttracerange_delete.go b/pkg/storage/ent/agenttracerange_delete.go new file mode 100644 index 0000000..31918eb --- /dev/null +++ b/pkg/storage/ent/agenttracerange_delete.go @@ -0,0 +1,88 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttracerange" + "github.com/papercomputeco/tapes/pkg/storage/ent/predicate" +) + +// AgentTraceRangeDelete is the builder for deleting a AgentTraceRange entity. +type AgentTraceRangeDelete struct { + config + hooks []Hook + mutation *AgentTraceRangeMutation +} + +// Where appends a list predicates to the AgentTraceRangeDelete builder. +func (_d *AgentTraceRangeDelete) Where(ps ...predicate.AgentTraceRange) *AgentTraceRangeDelete { + _d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (_d *AgentTraceRangeDelete) 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 *AgentTraceRangeDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (_d *AgentTraceRangeDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(agenttracerange.Table, sqlgraph.NewFieldSpec(agenttracerange.FieldID, field.TypeInt)) + 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 +} + +// AgentTraceRangeDeleteOne is the builder for deleting a single AgentTraceRange entity. +type AgentTraceRangeDeleteOne struct { + _d *AgentTraceRangeDelete +} + +// Where appends a list predicates to the AgentTraceRangeDelete builder. +func (_d *AgentTraceRangeDeleteOne) Where(ps ...predicate.AgentTraceRange) *AgentTraceRangeDeleteOne { + _d._d.mutation.Where(ps...) + return _d +} + +// Exec executes the deletion query. +func (_d *AgentTraceRangeDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{agenttracerange.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (_d *AgentTraceRangeDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/pkg/storage/ent/agenttracerange_query.go b/pkg/storage/ent/agenttracerange_query.go new file mode 100644 index 0000000..2ef84c8 --- /dev/null +++ b/pkg/storage/ent/agenttracerange_query.go @@ -0,0 +1,614 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttraceconversation" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttracerange" + "github.com/papercomputeco/tapes/pkg/storage/ent/predicate" +) + +// AgentTraceRangeQuery is the builder for querying AgentTraceRange entities. +type AgentTraceRangeQuery struct { + config + ctx *QueryContext + order []agenttracerange.OrderOption + inters []Interceptor + predicates []predicate.AgentTraceRange + withConversation *AgentTraceConversationQuery + withFKs bool + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the AgentTraceRangeQuery builder. +func (_q *AgentTraceRangeQuery) Where(ps ...predicate.AgentTraceRange) *AgentTraceRangeQuery { + _q.predicates = append(_q.predicates, ps...) + return _q +} + +// Limit the number of records to be returned by this query. +func (_q *AgentTraceRangeQuery) Limit(limit int) *AgentTraceRangeQuery { + _q.ctx.Limit = &limit + return _q +} + +// Offset to start from. +func (_q *AgentTraceRangeQuery) Offset(offset int) *AgentTraceRangeQuery { + _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 *AgentTraceRangeQuery) Unique(unique bool) *AgentTraceRangeQuery { + _q.ctx.Unique = &unique + return _q +} + +// Order specifies how the records should be ordered. +func (_q *AgentTraceRangeQuery) Order(o ...agenttracerange.OrderOption) *AgentTraceRangeQuery { + _q.order = append(_q.order, o...) + return _q +} + +// QueryConversation chains the current query on the "conversation" edge. +func (_q *AgentTraceRangeQuery) QueryConversation() *AgentTraceConversationQuery { + query := (&AgentTraceConversationClient{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(agenttracerange.Table, agenttracerange.FieldID, selector), + sqlgraph.To(agenttraceconversation.Table, agenttraceconversation.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, agenttracerange.ConversationTable, agenttracerange.ConversationColumn), + ) + fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first AgentTraceRange entity from the query. +// Returns a *NotFoundError when no AgentTraceRange was found. +func (_q *AgentTraceRangeQuery) First(ctx context.Context) (*AgentTraceRange, 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{agenttracerange.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (_q *AgentTraceRangeQuery) FirstX(ctx context.Context) *AgentTraceRange { + node, err := _q.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first AgentTraceRange ID from the query. +// Returns a *NotFoundError when no AgentTraceRange ID was found. +func (_q *AgentTraceRangeQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{agenttracerange.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (_q *AgentTraceRangeQuery) FirstIDX(ctx context.Context) int { + id, err := _q.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single AgentTraceRange entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one AgentTraceRange entity is found. +// Returns a *NotFoundError when no AgentTraceRange entities are found. +func (_q *AgentTraceRangeQuery) Only(ctx context.Context) (*AgentTraceRange, 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{agenttracerange.Label} + default: + return nil, &NotSingularError{agenttracerange.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (_q *AgentTraceRangeQuery) OnlyX(ctx context.Context) *AgentTraceRange { + node, err := _q.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only AgentTraceRange ID in the query. +// Returns a *NotSingularError when more than one AgentTraceRange ID is found. +// Returns a *NotFoundError when no entities are found. +func (_q *AgentTraceRangeQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + 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{agenttracerange.Label} + default: + err = &NotSingularError{agenttracerange.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (_q *AgentTraceRangeQuery) OnlyIDX(ctx context.Context) int { + id, err := _q.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of AgentTraceRanges. +func (_q *AgentTraceRangeQuery) All(ctx context.Context) ([]*AgentTraceRange, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*AgentTraceRange, *AgentTraceRangeQuery]() + return withInterceptors[[]*AgentTraceRange](ctx, _q, qr, _q.inters) +} + +// AllX is like All, but panics if an error occurs. +func (_q *AgentTraceRangeQuery) AllX(ctx context.Context) []*AgentTraceRange { + nodes, err := _q.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of AgentTraceRange IDs. +func (_q *AgentTraceRangeQuery) IDs(ctx context.Context) (ids []int, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) + } + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(agenttracerange.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (_q *AgentTraceRangeQuery) IDsX(ctx context.Context) []int { + ids, err := _q.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (_q *AgentTraceRangeQuery) 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[*AgentTraceRangeQuery](), _q.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (_q *AgentTraceRangeQuery) 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 *AgentTraceRangeQuery) 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("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (_q *AgentTraceRangeQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the AgentTraceRangeQuery 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 *AgentTraceRangeQuery) Clone() *AgentTraceRangeQuery { + if _q == nil { + return nil + } + return &AgentTraceRangeQuery{ + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]agenttracerange.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.AgentTraceRange{}, _q.predicates...), + withConversation: _q.withConversation.Clone(), + // clone intermediate query. + sql: _q.sql.Clone(), + path: _q.path, + } +} + +// WithConversation tells the query-builder to eager-load the nodes that are connected to +// the "conversation" edge. The optional arguments are used to configure the query builder of the edge. +func (_q *AgentTraceRangeQuery) WithConversation(opts ...func(*AgentTraceConversationQuery)) *AgentTraceRangeQuery { + query := (&AgentTraceConversationClient{config: _q.config}).Query() + for _, opt := range opts { + opt(query) + } + _q.withConversation = 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 { +// StartLine int `json:"start_line,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.AgentTraceRange.Query(). +// GroupBy(agenttracerange.FieldStartLine). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (_q *AgentTraceRangeQuery) GroupBy(field string, fields ...string) *AgentTraceRangeGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &AgentTraceRangeGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields + grbuild.label = agenttracerange.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 { +// StartLine int `json:"start_line,omitempty"` +// } +// +// client.AgentTraceRange.Query(). +// Select(agenttracerange.FieldStartLine). +// Scan(ctx, &v) +func (_q *AgentTraceRangeQuery) Select(fields ...string) *AgentTraceRangeSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &AgentTraceRangeSelect{AgentTraceRangeQuery: _q} + sbuild.label = agenttracerange.Label + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a AgentTraceRangeSelect configured with the given aggregations. +func (_q *AgentTraceRangeQuery) Aggregate(fns ...AggregateFunc) *AgentTraceRangeSelect { + return _q.Select().Aggregate(fns...) +} + +func (_q *AgentTraceRangeQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { + if inter == nil { + return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") + } + if trv, ok := inter.(Traverser); ok { + if err := trv.Traverse(ctx, _q); err != nil { + return err + } + } + } + for _, f := range _q.ctx.Fields { + if !agenttracerange.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: 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 *AgentTraceRangeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AgentTraceRange, error) { + var ( + nodes = []*AgentTraceRange{} + withFKs = _q.withFKs + _spec = _q.querySpec() + loadedTypes = [1]bool{ + _q.withConversation != nil, + } + ) + if _q.withConversation != nil { + withFKs = true + } + if withFKs { + _spec.Node.Columns = append(_spec.Node.Columns, agenttracerange.ForeignKeys...) + } + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*AgentTraceRange).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &AgentTraceRange{config: _q.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := _q.withConversation; query != nil { + if err := _q.loadConversation(ctx, query, nodes, nil, + func(n *AgentTraceRange, e *AgentTraceConversation) { n.Edges.Conversation = e }); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (_q *AgentTraceRangeQuery) loadConversation(ctx context.Context, query *AgentTraceConversationQuery, nodes []*AgentTraceRange, init func(*AgentTraceRange), assign func(*AgentTraceRange, *AgentTraceConversation)) error { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*AgentTraceRange) + for i := range nodes { + if nodes[i].agent_trace_conversation_ranges == nil { + continue + } + fk := *nodes[i].agent_trace_conversation_ranges + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(agenttraceconversation.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 "agent_trace_conversation_ranges" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (_q *AgentTraceRangeQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _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 *AgentTraceRangeQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(agenttracerange.Table, agenttracerange.Columns, sqlgraph.NewFieldSpec(agenttracerange.FieldID, field.TypeInt)) + _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, agenttracerange.FieldID) + for i := range fields { + if fields[i] != agenttracerange.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + 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 *AgentTraceRangeQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) + t1 := builder.Table(agenttracerange.Table) + columns := _q.ctx.Fields + if len(columns) == 0 { + columns = agenttracerange.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 _, 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 +} + +// AgentTraceRangeGroupBy is the group-by builder for AgentTraceRange entities. +type AgentTraceRangeGroupBy struct { + selector + build *AgentTraceRangeQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (_g *AgentTraceRangeGroupBy) Aggregate(fns ...AggregateFunc) *AgentTraceRangeGroupBy { + _g.fns = append(_g.fns, fns...) + return _g +} + +// Scan applies the selector query and scans the result into the given value. +func (_g *AgentTraceRangeGroupBy) 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[*AgentTraceRangeQuery, *AgentTraceRangeGroupBy](ctx, _g.build, _g, _g.build.inters, v) +} + +func (_g *AgentTraceRangeGroupBy) sqlScan(ctx context.Context, root *AgentTraceRangeQuery, 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) +} + +// AgentTraceRangeSelect is the builder for selecting fields of AgentTraceRange entities. +type AgentTraceRangeSelect struct { + *AgentTraceRangeQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (_s *AgentTraceRangeSelect) Aggregate(fns ...AggregateFunc) *AgentTraceRangeSelect { + _s.fns = append(_s.fns, fns...) + return _s +} + +// Scan applies the selector query and scans the result into the given value. +func (_s *AgentTraceRangeSelect) 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[*AgentTraceRangeQuery, *AgentTraceRangeSelect](ctx, _s.AgentTraceRangeQuery, _s, _s.inters, v) +} + +func (_s *AgentTraceRangeSelect) sqlScan(ctx context.Context, root *AgentTraceRangeQuery, 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) +} diff --git a/pkg/storage/ent/agenttracerange_update.go b/pkg/storage/ent/agenttracerange_update.go new file mode 100644 index 0000000..5106088 --- /dev/null +++ b/pkg/storage/ent/agenttracerange_update.go @@ -0,0 +1,554 @@ +// Code generated by ent, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttraceconversation" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttracerange" + "github.com/papercomputeco/tapes/pkg/storage/ent/predicate" +) + +// AgentTraceRangeUpdate is the builder for updating AgentTraceRange entities. +type AgentTraceRangeUpdate struct { + config + hooks []Hook + mutation *AgentTraceRangeMutation +} + +// Where appends a list predicates to the AgentTraceRangeUpdate builder. +func (_u *AgentTraceRangeUpdate) Where(ps ...predicate.AgentTraceRange) *AgentTraceRangeUpdate { + _u.mutation.Where(ps...) + return _u +} + +// SetStartLine sets the "start_line" field. +func (_u *AgentTraceRangeUpdate) SetStartLine(v int) *AgentTraceRangeUpdate { + _u.mutation.ResetStartLine() + _u.mutation.SetStartLine(v) + return _u +} + +// SetNillableStartLine sets the "start_line" field if the given value is not nil. +func (_u *AgentTraceRangeUpdate) SetNillableStartLine(v *int) *AgentTraceRangeUpdate { + if v != nil { + _u.SetStartLine(*v) + } + return _u +} + +// AddStartLine adds value to the "start_line" field. +func (_u *AgentTraceRangeUpdate) AddStartLine(v int) *AgentTraceRangeUpdate { + _u.mutation.AddStartLine(v) + return _u +} + +// SetEndLine sets the "end_line" field. +func (_u *AgentTraceRangeUpdate) SetEndLine(v int) *AgentTraceRangeUpdate { + _u.mutation.ResetEndLine() + _u.mutation.SetEndLine(v) + return _u +} + +// SetNillableEndLine sets the "end_line" field if the given value is not nil. +func (_u *AgentTraceRangeUpdate) SetNillableEndLine(v *int) *AgentTraceRangeUpdate { + if v != nil { + _u.SetEndLine(*v) + } + return _u +} + +// AddEndLine adds value to the "end_line" field. +func (_u *AgentTraceRangeUpdate) AddEndLine(v int) *AgentTraceRangeUpdate { + _u.mutation.AddEndLine(v) + return _u +} + +// SetContentHash sets the "content_hash" field. +func (_u *AgentTraceRangeUpdate) SetContentHash(v string) *AgentTraceRangeUpdate { + _u.mutation.SetContentHash(v) + return _u +} + +// SetNillableContentHash sets the "content_hash" field if the given value is not nil. +func (_u *AgentTraceRangeUpdate) SetNillableContentHash(v *string) *AgentTraceRangeUpdate { + if v != nil { + _u.SetContentHash(*v) + } + return _u +} + +// ClearContentHash clears the value of the "content_hash" field. +func (_u *AgentTraceRangeUpdate) ClearContentHash() *AgentTraceRangeUpdate { + _u.mutation.ClearContentHash() + return _u +} + +// SetContributorType sets the "contributor_type" field. +func (_u *AgentTraceRangeUpdate) SetContributorType(v string) *AgentTraceRangeUpdate { + _u.mutation.SetContributorType(v) + return _u +} + +// SetNillableContributorType sets the "contributor_type" field if the given value is not nil. +func (_u *AgentTraceRangeUpdate) SetNillableContributorType(v *string) *AgentTraceRangeUpdate { + if v != nil { + _u.SetContributorType(*v) + } + return _u +} + +// ClearContributorType clears the value of the "contributor_type" field. +func (_u *AgentTraceRangeUpdate) ClearContributorType() *AgentTraceRangeUpdate { + _u.mutation.ClearContributorType() + return _u +} + +// SetContributorModelID sets the "contributor_model_id" field. +func (_u *AgentTraceRangeUpdate) SetContributorModelID(v string) *AgentTraceRangeUpdate { + _u.mutation.SetContributorModelID(v) + return _u +} + +// SetNillableContributorModelID sets the "contributor_model_id" field if the given value is not nil. +func (_u *AgentTraceRangeUpdate) SetNillableContributorModelID(v *string) *AgentTraceRangeUpdate { + if v != nil { + _u.SetContributorModelID(*v) + } + return _u +} + +// ClearContributorModelID clears the value of the "contributor_model_id" field. +func (_u *AgentTraceRangeUpdate) ClearContributorModelID() *AgentTraceRangeUpdate { + _u.mutation.ClearContributorModelID() + return _u +} + +// SetConversationID sets the "conversation" edge to the AgentTraceConversation entity by ID. +func (_u *AgentTraceRangeUpdate) SetConversationID(id int) *AgentTraceRangeUpdate { + _u.mutation.SetConversationID(id) + return _u +} + +// SetConversation sets the "conversation" edge to the AgentTraceConversation entity. +func (_u *AgentTraceRangeUpdate) SetConversation(v *AgentTraceConversation) *AgentTraceRangeUpdate { + return _u.SetConversationID(v.ID) +} + +// Mutation returns the AgentTraceRangeMutation object of the builder. +func (_u *AgentTraceRangeUpdate) Mutation() *AgentTraceRangeMutation { + return _u.mutation +} + +// ClearConversation clears the "conversation" edge to the AgentTraceConversation entity. +func (_u *AgentTraceRangeUpdate) ClearConversation() *AgentTraceRangeUpdate { + _u.mutation.ClearConversation() + return _u +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (_u *AgentTraceRangeUpdate) 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 *AgentTraceRangeUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (_u *AgentTraceRangeUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *AgentTraceRangeUpdate) 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 *AgentTraceRangeUpdate) check() error { + if _u.mutation.ConversationCleared() && len(_u.mutation.ConversationIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "AgentTraceRange.conversation"`) + } + return nil +} + +func (_u *AgentTraceRangeUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(agenttracerange.Table, agenttracerange.Columns, sqlgraph.NewFieldSpec(agenttracerange.FieldID, field.TypeInt)) + 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.StartLine(); ok { + _spec.SetField(agenttracerange.FieldStartLine, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedStartLine(); ok { + _spec.AddField(agenttracerange.FieldStartLine, field.TypeInt, value) + } + if value, ok := _u.mutation.EndLine(); ok { + _spec.SetField(agenttracerange.FieldEndLine, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedEndLine(); ok { + _spec.AddField(agenttracerange.FieldEndLine, field.TypeInt, value) + } + if value, ok := _u.mutation.ContentHash(); ok { + _spec.SetField(agenttracerange.FieldContentHash, field.TypeString, value) + } + if _u.mutation.ContentHashCleared() { + _spec.ClearField(agenttracerange.FieldContentHash, field.TypeString) + } + if value, ok := _u.mutation.ContributorType(); ok { + _spec.SetField(agenttracerange.FieldContributorType, field.TypeString, value) + } + if _u.mutation.ContributorTypeCleared() { + _spec.ClearField(agenttracerange.FieldContributorType, field.TypeString) + } + if value, ok := _u.mutation.ContributorModelID(); ok { + _spec.SetField(agenttracerange.FieldContributorModelID, field.TypeString, value) + } + if _u.mutation.ContributorModelIDCleared() { + _spec.ClearField(agenttracerange.FieldContributorModelID, field.TypeString) + } + if _u.mutation.ConversationCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agenttracerange.ConversationTable, + Columns: []string{agenttracerange.ConversationColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttraceconversation.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ConversationIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agenttracerange.ConversationTable, + Columns: []string{agenttracerange.ConversationColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttraceconversation.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{agenttracerange.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + _u.mutation.done = true + return _node, nil +} + +// AgentTraceRangeUpdateOne is the builder for updating a single AgentTraceRange entity. +type AgentTraceRangeUpdateOne struct { + config + fields []string + hooks []Hook + mutation *AgentTraceRangeMutation +} + +// SetStartLine sets the "start_line" field. +func (_u *AgentTraceRangeUpdateOne) SetStartLine(v int) *AgentTraceRangeUpdateOne { + _u.mutation.ResetStartLine() + _u.mutation.SetStartLine(v) + return _u +} + +// SetNillableStartLine sets the "start_line" field if the given value is not nil. +func (_u *AgentTraceRangeUpdateOne) SetNillableStartLine(v *int) *AgentTraceRangeUpdateOne { + if v != nil { + _u.SetStartLine(*v) + } + return _u +} + +// AddStartLine adds value to the "start_line" field. +func (_u *AgentTraceRangeUpdateOne) AddStartLine(v int) *AgentTraceRangeUpdateOne { + _u.mutation.AddStartLine(v) + return _u +} + +// SetEndLine sets the "end_line" field. +func (_u *AgentTraceRangeUpdateOne) SetEndLine(v int) *AgentTraceRangeUpdateOne { + _u.mutation.ResetEndLine() + _u.mutation.SetEndLine(v) + return _u +} + +// SetNillableEndLine sets the "end_line" field if the given value is not nil. +func (_u *AgentTraceRangeUpdateOne) SetNillableEndLine(v *int) *AgentTraceRangeUpdateOne { + if v != nil { + _u.SetEndLine(*v) + } + return _u +} + +// AddEndLine adds value to the "end_line" field. +func (_u *AgentTraceRangeUpdateOne) AddEndLine(v int) *AgentTraceRangeUpdateOne { + _u.mutation.AddEndLine(v) + return _u +} + +// SetContentHash sets the "content_hash" field. +func (_u *AgentTraceRangeUpdateOne) SetContentHash(v string) *AgentTraceRangeUpdateOne { + _u.mutation.SetContentHash(v) + return _u +} + +// SetNillableContentHash sets the "content_hash" field if the given value is not nil. +func (_u *AgentTraceRangeUpdateOne) SetNillableContentHash(v *string) *AgentTraceRangeUpdateOne { + if v != nil { + _u.SetContentHash(*v) + } + return _u +} + +// ClearContentHash clears the value of the "content_hash" field. +func (_u *AgentTraceRangeUpdateOne) ClearContentHash() *AgentTraceRangeUpdateOne { + _u.mutation.ClearContentHash() + return _u +} + +// SetContributorType sets the "contributor_type" field. +func (_u *AgentTraceRangeUpdateOne) SetContributorType(v string) *AgentTraceRangeUpdateOne { + _u.mutation.SetContributorType(v) + return _u +} + +// SetNillableContributorType sets the "contributor_type" field if the given value is not nil. +func (_u *AgentTraceRangeUpdateOne) SetNillableContributorType(v *string) *AgentTraceRangeUpdateOne { + if v != nil { + _u.SetContributorType(*v) + } + return _u +} + +// ClearContributorType clears the value of the "contributor_type" field. +func (_u *AgentTraceRangeUpdateOne) ClearContributorType() *AgentTraceRangeUpdateOne { + _u.mutation.ClearContributorType() + return _u +} + +// SetContributorModelID sets the "contributor_model_id" field. +func (_u *AgentTraceRangeUpdateOne) SetContributorModelID(v string) *AgentTraceRangeUpdateOne { + _u.mutation.SetContributorModelID(v) + return _u +} + +// SetNillableContributorModelID sets the "contributor_model_id" field if the given value is not nil. +func (_u *AgentTraceRangeUpdateOne) SetNillableContributorModelID(v *string) *AgentTraceRangeUpdateOne { + if v != nil { + _u.SetContributorModelID(*v) + } + return _u +} + +// ClearContributorModelID clears the value of the "contributor_model_id" field. +func (_u *AgentTraceRangeUpdateOne) ClearContributorModelID() *AgentTraceRangeUpdateOne { + _u.mutation.ClearContributorModelID() + return _u +} + +// SetConversationID sets the "conversation" edge to the AgentTraceConversation entity by ID. +func (_u *AgentTraceRangeUpdateOne) SetConversationID(id int) *AgentTraceRangeUpdateOne { + _u.mutation.SetConversationID(id) + return _u +} + +// SetConversation sets the "conversation" edge to the AgentTraceConversation entity. +func (_u *AgentTraceRangeUpdateOne) SetConversation(v *AgentTraceConversation) *AgentTraceRangeUpdateOne { + return _u.SetConversationID(v.ID) +} + +// Mutation returns the AgentTraceRangeMutation object of the builder. +func (_u *AgentTraceRangeUpdateOne) Mutation() *AgentTraceRangeMutation { + return _u.mutation +} + +// ClearConversation clears the "conversation" edge to the AgentTraceConversation entity. +func (_u *AgentTraceRangeUpdateOne) ClearConversation() *AgentTraceRangeUpdateOne { + _u.mutation.ClearConversation() + return _u +} + +// Where appends a list predicates to the AgentTraceRangeUpdate builder. +func (_u *AgentTraceRangeUpdateOne) Where(ps ...predicate.AgentTraceRange) *AgentTraceRangeUpdateOne { + _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 *AgentTraceRangeUpdateOne) Select(field string, fields ...string) *AgentTraceRangeUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u +} + +// Save executes the query and returns the updated AgentTraceRange entity. +func (_u *AgentTraceRangeUpdateOne) Save(ctx context.Context) (*AgentTraceRange, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (_u *AgentTraceRangeUpdateOne) SaveX(ctx context.Context) *AgentTraceRange { + node, err := _u.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (_u *AgentTraceRangeUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (_u *AgentTraceRangeUpdateOne) 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 *AgentTraceRangeUpdateOne) check() error { + if _u.mutation.ConversationCleared() && len(_u.mutation.ConversationIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "AgentTraceRange.conversation"`) + } + return nil +} + +func (_u *AgentTraceRangeUpdateOne) sqlSave(ctx context.Context) (_node *AgentTraceRange, err error) { + if err := _u.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(agenttracerange.Table, agenttracerange.Columns, sqlgraph.NewFieldSpec(agenttracerange.FieldID, field.TypeInt)) + id, ok := _u.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "AgentTraceRange.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, agenttracerange.FieldID) + for _, f := range fields { + if !agenttracerange.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != agenttracerange.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.StartLine(); ok { + _spec.SetField(agenttracerange.FieldStartLine, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedStartLine(); ok { + _spec.AddField(agenttracerange.FieldStartLine, field.TypeInt, value) + } + if value, ok := _u.mutation.EndLine(); ok { + _spec.SetField(agenttracerange.FieldEndLine, field.TypeInt, value) + } + if value, ok := _u.mutation.AddedEndLine(); ok { + _spec.AddField(agenttracerange.FieldEndLine, field.TypeInt, value) + } + if value, ok := _u.mutation.ContentHash(); ok { + _spec.SetField(agenttracerange.FieldContentHash, field.TypeString, value) + } + if _u.mutation.ContentHashCleared() { + _spec.ClearField(agenttracerange.FieldContentHash, field.TypeString) + } + if value, ok := _u.mutation.ContributorType(); ok { + _spec.SetField(agenttracerange.FieldContributorType, field.TypeString, value) + } + if _u.mutation.ContributorTypeCleared() { + _spec.ClearField(agenttracerange.FieldContributorType, field.TypeString) + } + if value, ok := _u.mutation.ContributorModelID(); ok { + _spec.SetField(agenttracerange.FieldContributorModelID, field.TypeString, value) + } + if _u.mutation.ContributorModelIDCleared() { + _spec.ClearField(agenttracerange.FieldContributorModelID, field.TypeString) + } + if _u.mutation.ConversationCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agenttracerange.ConversationTable, + Columns: []string{agenttracerange.ConversationColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttraceconversation.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := _u.mutation.ConversationIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: agenttracerange.ConversationTable, + Columns: []string{agenttracerange.ConversationColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(agenttraceconversation.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _node = &AgentTraceRange{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{agenttracerange.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/pkg/storage/ent/client.go b/pkg/storage/ent/client.go index e772d4a..9cddeb7 100644 --- a/pkg/storage/ent/client.go +++ b/pkg/storage/ent/client.go @@ -15,7 +15,10 @@ import ( "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" - + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttrace" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttraceconversation" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttracefile" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttracerange" "github.com/papercomputeco/tapes/pkg/storage/ent/node" ) @@ -24,6 +27,14 @@ type Client struct { config // Schema is the client for creating, migrating and dropping schema. Schema *migrate.Schema + // AgentTrace is the client for interacting with the AgentTrace builders. + AgentTrace *AgentTraceClient + // AgentTraceConversation is the client for interacting with the AgentTraceConversation builders. + AgentTraceConversation *AgentTraceConversationClient + // AgentTraceFile is the client for interacting with the AgentTraceFile builders. + AgentTraceFile *AgentTraceFileClient + // AgentTraceRange is the client for interacting with the AgentTraceRange builders. + AgentTraceRange *AgentTraceRangeClient // Node is the client for interacting with the Node builders. Node *NodeClient } @@ -37,6 +48,10 @@ func NewClient(opts ...Option) *Client { func (c *Client) init() { c.Schema = migrate.NewSchema(c.driver) + c.AgentTrace = NewAgentTraceClient(c.config) + c.AgentTraceConversation = NewAgentTraceConversationClient(c.config) + c.AgentTraceFile = NewAgentTraceFileClient(c.config) + c.AgentTraceRange = NewAgentTraceRangeClient(c.config) c.Node = NewNodeClient(c.config) } @@ -128,9 +143,13 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) { cfg := c.config cfg.driver = tx return &Tx{ - ctx: ctx, - config: cfg, - Node: NewNodeClient(cfg), + ctx: ctx, + config: cfg, + AgentTrace: NewAgentTraceClient(cfg), + AgentTraceConversation: NewAgentTraceConversationClient(cfg), + AgentTraceFile: NewAgentTraceFileClient(cfg), + AgentTraceRange: NewAgentTraceRangeClient(cfg), + Node: NewNodeClient(cfg), }, nil } @@ -148,16 +167,20 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) cfg := c.config cfg.driver = &txDriver{tx: tx, drv: c.driver} return &Tx{ - ctx: ctx, - config: cfg, - Node: NewNodeClient(cfg), + ctx: ctx, + config: cfg, + AgentTrace: NewAgentTraceClient(cfg), + AgentTraceConversation: NewAgentTraceConversationClient(cfg), + AgentTraceFile: NewAgentTraceFileClient(cfg), + AgentTraceRange: NewAgentTraceRangeClient(cfg), + Node: NewNodeClient(cfg), }, nil } // Debug returns a new debug-client. It's used to get verbose logging on specific operations. // // client.Debug(). -// Node. +// AgentTrace. // Query(). // Count(ctx) func (c *Client) Debug() *Client { @@ -179,18 +202,34 @@ func (c *Client) Close() error { // Use adds the mutation hooks to all the entity clients. // In order to add hooks to a specific client, call: `client.Node.Use(...)`. func (c *Client) Use(hooks ...Hook) { + c.AgentTrace.Use(hooks...) + c.AgentTraceConversation.Use(hooks...) + c.AgentTraceFile.Use(hooks...) + c.AgentTraceRange.Use(hooks...) c.Node.Use(hooks...) } // Intercept adds the query interceptors to all the entity clients. // In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. func (c *Client) Intercept(interceptors ...Interceptor) { + c.AgentTrace.Intercept(interceptors...) + c.AgentTraceConversation.Intercept(interceptors...) + c.AgentTraceFile.Intercept(interceptors...) + c.AgentTraceRange.Intercept(interceptors...) c.Node.Intercept(interceptors...) } // Mutate implements the ent.Mutator interface. func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { switch m := m.(type) { + case *AgentTraceMutation: + return c.AgentTrace.mutate(ctx, m) + case *AgentTraceConversationMutation: + return c.AgentTraceConversation.mutate(ctx, m) + case *AgentTraceFileMutation: + return c.AgentTraceFile.mutate(ctx, m) + case *AgentTraceRangeMutation: + return c.AgentTraceRange.mutate(ctx, m) case *NodeMutation: return c.Node.mutate(ctx, m) default: @@ -198,6 +237,634 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { } } +// AgentTraceClient is a client for the AgentTrace schema. +type AgentTraceClient struct { + config +} + +// NewAgentTraceClient returns a client for the AgentTrace from the given config. +func NewAgentTraceClient(c config) *AgentTraceClient { + return &AgentTraceClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `agenttrace.Hooks(f(g(h())))`. +func (c *AgentTraceClient) Use(hooks ...Hook) { + c.hooks.AgentTrace = append(c.hooks.AgentTrace, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `agenttrace.Intercept(f(g(h())))`. +func (c *AgentTraceClient) Intercept(interceptors ...Interceptor) { + c.inters.AgentTrace = append(c.inters.AgentTrace, interceptors...) +} + +// Create returns a builder for creating a AgentTrace entity. +func (c *AgentTraceClient) Create() *AgentTraceCreate { + mutation := newAgentTraceMutation(c.config, OpCreate) + return &AgentTraceCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of AgentTrace entities. +func (c *AgentTraceClient) CreateBulk(builders ...*AgentTraceCreate) *AgentTraceCreateBulk { + return &AgentTraceCreateBulk{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 *AgentTraceClient) MapCreateBulk(slice any, setFunc func(*AgentTraceCreate, int)) *AgentTraceCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &AgentTraceCreateBulk{err: fmt.Errorf("calling to AgentTraceClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*AgentTraceCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &AgentTraceCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for AgentTrace. +func (c *AgentTraceClient) Update() *AgentTraceUpdate { + mutation := newAgentTraceMutation(c.config, OpUpdate) + return &AgentTraceUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *AgentTraceClient) UpdateOne(_m *AgentTrace) *AgentTraceUpdateOne { + mutation := newAgentTraceMutation(c.config, OpUpdateOne, withAgentTrace(_m)) + return &AgentTraceUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *AgentTraceClient) UpdateOneID(id string) *AgentTraceUpdateOne { + mutation := newAgentTraceMutation(c.config, OpUpdateOne, withAgentTraceID(id)) + return &AgentTraceUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for AgentTrace. +func (c *AgentTraceClient) Delete() *AgentTraceDelete { + mutation := newAgentTraceMutation(c.config, OpDelete) + return &AgentTraceDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *AgentTraceClient) DeleteOne(_m *AgentTrace) *AgentTraceDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *AgentTraceClient) DeleteOneID(id string) *AgentTraceDeleteOne { + builder := c.Delete().Where(agenttrace.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &AgentTraceDeleteOne{builder} +} + +// Query returns a query builder for AgentTrace. +func (c *AgentTraceClient) Query() *AgentTraceQuery { + return &AgentTraceQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeAgentTrace}, + inters: c.Interceptors(), + } +} + +// Get returns a AgentTrace entity by its id. +func (c *AgentTraceClient) Get(ctx context.Context, id string) (*AgentTrace, error) { + return c.Query().Where(agenttrace.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *AgentTraceClient) GetX(ctx context.Context, id string) *AgentTrace { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryFiles queries the files edge of a AgentTrace. +func (c *AgentTraceClient) QueryFiles(_m *AgentTrace) *AgentTraceFileQuery { + query := (&AgentTraceFileClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(agenttrace.Table, agenttrace.FieldID, id), + sqlgraph.To(agenttracefile.Table, agenttracefile.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, agenttrace.FilesTable, agenttrace.FilesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *AgentTraceClient) Hooks() []Hook { + return c.hooks.AgentTrace +} + +// Interceptors returns the client interceptors. +func (c *AgentTraceClient) Interceptors() []Interceptor { + return c.inters.AgentTrace +} + +func (c *AgentTraceClient) mutate(ctx context.Context, m *AgentTraceMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&AgentTraceCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&AgentTraceUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&AgentTraceUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&AgentTraceDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown AgentTrace mutation op: %q", m.Op()) + } +} + +// AgentTraceConversationClient is a client for the AgentTraceConversation schema. +type AgentTraceConversationClient struct { + config +} + +// NewAgentTraceConversationClient returns a client for the AgentTraceConversation from the given config. +func NewAgentTraceConversationClient(c config) *AgentTraceConversationClient { + return &AgentTraceConversationClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `agenttraceconversation.Hooks(f(g(h())))`. +func (c *AgentTraceConversationClient) Use(hooks ...Hook) { + c.hooks.AgentTraceConversation = append(c.hooks.AgentTraceConversation, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `agenttraceconversation.Intercept(f(g(h())))`. +func (c *AgentTraceConversationClient) Intercept(interceptors ...Interceptor) { + c.inters.AgentTraceConversation = append(c.inters.AgentTraceConversation, interceptors...) +} + +// Create returns a builder for creating a AgentTraceConversation entity. +func (c *AgentTraceConversationClient) Create() *AgentTraceConversationCreate { + mutation := newAgentTraceConversationMutation(c.config, OpCreate) + return &AgentTraceConversationCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of AgentTraceConversation entities. +func (c *AgentTraceConversationClient) CreateBulk(builders ...*AgentTraceConversationCreate) *AgentTraceConversationCreateBulk { + return &AgentTraceConversationCreateBulk{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 *AgentTraceConversationClient) MapCreateBulk(slice any, setFunc func(*AgentTraceConversationCreate, int)) *AgentTraceConversationCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &AgentTraceConversationCreateBulk{err: fmt.Errorf("calling to AgentTraceConversationClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*AgentTraceConversationCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &AgentTraceConversationCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for AgentTraceConversation. +func (c *AgentTraceConversationClient) Update() *AgentTraceConversationUpdate { + mutation := newAgentTraceConversationMutation(c.config, OpUpdate) + return &AgentTraceConversationUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *AgentTraceConversationClient) UpdateOne(_m *AgentTraceConversation) *AgentTraceConversationUpdateOne { + mutation := newAgentTraceConversationMutation(c.config, OpUpdateOne, withAgentTraceConversation(_m)) + return &AgentTraceConversationUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *AgentTraceConversationClient) UpdateOneID(id int) *AgentTraceConversationUpdateOne { + mutation := newAgentTraceConversationMutation(c.config, OpUpdateOne, withAgentTraceConversationID(id)) + return &AgentTraceConversationUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for AgentTraceConversation. +func (c *AgentTraceConversationClient) Delete() *AgentTraceConversationDelete { + mutation := newAgentTraceConversationMutation(c.config, OpDelete) + return &AgentTraceConversationDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *AgentTraceConversationClient) DeleteOne(_m *AgentTraceConversation) *AgentTraceConversationDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *AgentTraceConversationClient) DeleteOneID(id int) *AgentTraceConversationDeleteOne { + builder := c.Delete().Where(agenttraceconversation.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &AgentTraceConversationDeleteOne{builder} +} + +// Query returns a query builder for AgentTraceConversation. +func (c *AgentTraceConversationClient) Query() *AgentTraceConversationQuery { + return &AgentTraceConversationQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeAgentTraceConversation}, + inters: c.Interceptors(), + } +} + +// Get returns a AgentTraceConversation entity by its id. +func (c *AgentTraceConversationClient) Get(ctx context.Context, id int) (*AgentTraceConversation, error) { + return c.Query().Where(agenttraceconversation.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *AgentTraceConversationClient) GetX(ctx context.Context, id int) *AgentTraceConversation { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryFile queries the file edge of a AgentTraceConversation. +func (c *AgentTraceConversationClient) QueryFile(_m *AgentTraceConversation) *AgentTraceFileQuery { + query := (&AgentTraceFileClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(agenttraceconversation.Table, agenttraceconversation.FieldID, id), + sqlgraph.To(agenttracefile.Table, agenttracefile.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, agenttraceconversation.FileTable, agenttraceconversation.FileColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryRanges queries the ranges edge of a AgentTraceConversation. +func (c *AgentTraceConversationClient) QueryRanges(_m *AgentTraceConversation) *AgentTraceRangeQuery { + query := (&AgentTraceRangeClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(agenttraceconversation.Table, agenttraceconversation.FieldID, id), + sqlgraph.To(agenttracerange.Table, agenttracerange.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, agenttraceconversation.RangesTable, agenttraceconversation.RangesColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *AgentTraceConversationClient) Hooks() []Hook { + return c.hooks.AgentTraceConversation +} + +// Interceptors returns the client interceptors. +func (c *AgentTraceConversationClient) Interceptors() []Interceptor { + return c.inters.AgentTraceConversation +} + +func (c *AgentTraceConversationClient) mutate(ctx context.Context, m *AgentTraceConversationMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&AgentTraceConversationCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&AgentTraceConversationUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&AgentTraceConversationUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&AgentTraceConversationDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown AgentTraceConversation mutation op: %q", m.Op()) + } +} + +// AgentTraceFileClient is a client for the AgentTraceFile schema. +type AgentTraceFileClient struct { + config +} + +// NewAgentTraceFileClient returns a client for the AgentTraceFile from the given config. +func NewAgentTraceFileClient(c config) *AgentTraceFileClient { + return &AgentTraceFileClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `agenttracefile.Hooks(f(g(h())))`. +func (c *AgentTraceFileClient) Use(hooks ...Hook) { + c.hooks.AgentTraceFile = append(c.hooks.AgentTraceFile, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `agenttracefile.Intercept(f(g(h())))`. +func (c *AgentTraceFileClient) Intercept(interceptors ...Interceptor) { + c.inters.AgentTraceFile = append(c.inters.AgentTraceFile, interceptors...) +} + +// Create returns a builder for creating a AgentTraceFile entity. +func (c *AgentTraceFileClient) Create() *AgentTraceFileCreate { + mutation := newAgentTraceFileMutation(c.config, OpCreate) + return &AgentTraceFileCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of AgentTraceFile entities. +func (c *AgentTraceFileClient) CreateBulk(builders ...*AgentTraceFileCreate) *AgentTraceFileCreateBulk { + return &AgentTraceFileCreateBulk{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 *AgentTraceFileClient) MapCreateBulk(slice any, setFunc func(*AgentTraceFileCreate, int)) *AgentTraceFileCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &AgentTraceFileCreateBulk{err: fmt.Errorf("calling to AgentTraceFileClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*AgentTraceFileCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &AgentTraceFileCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for AgentTraceFile. +func (c *AgentTraceFileClient) Update() *AgentTraceFileUpdate { + mutation := newAgentTraceFileMutation(c.config, OpUpdate) + return &AgentTraceFileUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *AgentTraceFileClient) UpdateOne(_m *AgentTraceFile) *AgentTraceFileUpdateOne { + mutation := newAgentTraceFileMutation(c.config, OpUpdateOne, withAgentTraceFile(_m)) + return &AgentTraceFileUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *AgentTraceFileClient) UpdateOneID(id int) *AgentTraceFileUpdateOne { + mutation := newAgentTraceFileMutation(c.config, OpUpdateOne, withAgentTraceFileID(id)) + return &AgentTraceFileUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for AgentTraceFile. +func (c *AgentTraceFileClient) Delete() *AgentTraceFileDelete { + mutation := newAgentTraceFileMutation(c.config, OpDelete) + return &AgentTraceFileDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *AgentTraceFileClient) DeleteOne(_m *AgentTraceFile) *AgentTraceFileDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *AgentTraceFileClient) DeleteOneID(id int) *AgentTraceFileDeleteOne { + builder := c.Delete().Where(agenttracefile.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &AgentTraceFileDeleteOne{builder} +} + +// Query returns a query builder for AgentTraceFile. +func (c *AgentTraceFileClient) Query() *AgentTraceFileQuery { + return &AgentTraceFileQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeAgentTraceFile}, + inters: c.Interceptors(), + } +} + +// Get returns a AgentTraceFile entity by its id. +func (c *AgentTraceFileClient) Get(ctx context.Context, id int) (*AgentTraceFile, error) { + return c.Query().Where(agenttracefile.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *AgentTraceFileClient) GetX(ctx context.Context, id int) *AgentTraceFile { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryTrace queries the trace edge of a AgentTraceFile. +func (c *AgentTraceFileClient) QueryTrace(_m *AgentTraceFile) *AgentTraceQuery { + query := (&AgentTraceClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(agenttracefile.Table, agenttracefile.FieldID, id), + sqlgraph.To(agenttrace.Table, agenttrace.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, agenttracefile.TraceTable, agenttracefile.TraceColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryConversations queries the conversations edge of a AgentTraceFile. +func (c *AgentTraceFileClient) QueryConversations(_m *AgentTraceFile) *AgentTraceConversationQuery { + query := (&AgentTraceConversationClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(agenttracefile.Table, agenttracefile.FieldID, id), + sqlgraph.To(agenttraceconversation.Table, agenttraceconversation.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, agenttracefile.ConversationsTable, agenttracefile.ConversationsColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *AgentTraceFileClient) Hooks() []Hook { + return c.hooks.AgentTraceFile +} + +// Interceptors returns the client interceptors. +func (c *AgentTraceFileClient) Interceptors() []Interceptor { + return c.inters.AgentTraceFile +} + +func (c *AgentTraceFileClient) mutate(ctx context.Context, m *AgentTraceFileMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&AgentTraceFileCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&AgentTraceFileUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&AgentTraceFileUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&AgentTraceFileDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown AgentTraceFile mutation op: %q", m.Op()) + } +} + +// AgentTraceRangeClient is a client for the AgentTraceRange schema. +type AgentTraceRangeClient struct { + config +} + +// NewAgentTraceRangeClient returns a client for the AgentTraceRange from the given config. +func NewAgentTraceRangeClient(c config) *AgentTraceRangeClient { + return &AgentTraceRangeClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `agenttracerange.Hooks(f(g(h())))`. +func (c *AgentTraceRangeClient) Use(hooks ...Hook) { + c.hooks.AgentTraceRange = append(c.hooks.AgentTraceRange, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `agenttracerange.Intercept(f(g(h())))`. +func (c *AgentTraceRangeClient) Intercept(interceptors ...Interceptor) { + c.inters.AgentTraceRange = append(c.inters.AgentTraceRange, interceptors...) +} + +// Create returns a builder for creating a AgentTraceRange entity. +func (c *AgentTraceRangeClient) Create() *AgentTraceRangeCreate { + mutation := newAgentTraceRangeMutation(c.config, OpCreate) + return &AgentTraceRangeCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of AgentTraceRange entities. +func (c *AgentTraceRangeClient) CreateBulk(builders ...*AgentTraceRangeCreate) *AgentTraceRangeCreateBulk { + return &AgentTraceRangeCreateBulk{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 *AgentTraceRangeClient) MapCreateBulk(slice any, setFunc func(*AgentTraceRangeCreate, int)) *AgentTraceRangeCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &AgentTraceRangeCreateBulk{err: fmt.Errorf("calling to AgentTraceRangeClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*AgentTraceRangeCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &AgentTraceRangeCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for AgentTraceRange. +func (c *AgentTraceRangeClient) Update() *AgentTraceRangeUpdate { + mutation := newAgentTraceRangeMutation(c.config, OpUpdate) + return &AgentTraceRangeUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *AgentTraceRangeClient) UpdateOne(_m *AgentTraceRange) *AgentTraceRangeUpdateOne { + mutation := newAgentTraceRangeMutation(c.config, OpUpdateOne, withAgentTraceRange(_m)) + return &AgentTraceRangeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *AgentTraceRangeClient) UpdateOneID(id int) *AgentTraceRangeUpdateOne { + mutation := newAgentTraceRangeMutation(c.config, OpUpdateOne, withAgentTraceRangeID(id)) + return &AgentTraceRangeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for AgentTraceRange. +func (c *AgentTraceRangeClient) Delete() *AgentTraceRangeDelete { + mutation := newAgentTraceRangeMutation(c.config, OpDelete) + return &AgentTraceRangeDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *AgentTraceRangeClient) DeleteOne(_m *AgentTraceRange) *AgentTraceRangeDeleteOne { + return c.DeleteOneID(_m.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *AgentTraceRangeClient) DeleteOneID(id int) *AgentTraceRangeDeleteOne { + builder := c.Delete().Where(agenttracerange.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &AgentTraceRangeDeleteOne{builder} +} + +// Query returns a query builder for AgentTraceRange. +func (c *AgentTraceRangeClient) Query() *AgentTraceRangeQuery { + return &AgentTraceRangeQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeAgentTraceRange}, + inters: c.Interceptors(), + } +} + +// Get returns a AgentTraceRange entity by its id. +func (c *AgentTraceRangeClient) Get(ctx context.Context, id int) (*AgentTraceRange, error) { + return c.Query().Where(agenttracerange.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *AgentTraceRangeClient) GetX(ctx context.Context, id int) *AgentTraceRange { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryConversation queries the conversation edge of a AgentTraceRange. +func (c *AgentTraceRangeClient) QueryConversation(_m *AgentTraceRange) *AgentTraceConversationQuery { + query := (&AgentTraceConversationClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := _m.ID + step := sqlgraph.NewStep( + sqlgraph.From(agenttracerange.Table, agenttracerange.FieldID, id), + sqlgraph.To(agenttraceconversation.Table, agenttraceconversation.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, agenttracerange.ConversationTable, agenttracerange.ConversationColumn), + ) + fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *AgentTraceRangeClient) Hooks() []Hook { + return c.hooks.AgentTraceRange +} + +// Interceptors returns the client interceptors. +func (c *AgentTraceRangeClient) Interceptors() []Interceptor { + return c.inters.AgentTraceRange +} + +func (c *AgentTraceRangeClient) mutate(ctx context.Context, m *AgentTraceRangeMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&AgentTraceRangeCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&AgentTraceRangeUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&AgentTraceRangeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&AgentTraceRangeDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown AgentTraceRange mutation op: %q", m.Op()) + } +} + // NodeClient is a client for the Node schema. type NodeClient struct { config @@ -366,9 +1033,11 @@ func (c *NodeClient) mutate(ctx context.Context, m *NodeMutation) (Value, error) // hooks and interceptors per client, for fast access. type ( hooks struct { + AgentTrace, AgentTraceConversation, AgentTraceFile, AgentTraceRange, Node []ent.Hook } inters struct { + AgentTrace, AgentTraceConversation, AgentTraceFile, AgentTraceRange, Node []ent.Interceptor } ) diff --git a/pkg/storage/ent/driver/agent_trace_driver.go b/pkg/storage/ent/driver/agent_trace_driver.go new file mode 100644 index 0000000..dc24220 --- /dev/null +++ b/pkg/storage/ent/driver/agent_trace_driver.go @@ -0,0 +1,314 @@ +package entdriver + +import ( + "context" + "fmt" + + "github.com/papercomputeco/tapes/pkg/agenttrace" + "github.com/papercomputeco/tapes/pkg/storage" + "github.com/papercomputeco/tapes/pkg/storage/ent" + entagenttrace "github.com/papercomputeco/tapes/pkg/storage/ent/agenttrace" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttracefile" + "github.com/papercomputeco/tapes/pkg/storage/ent/predicate" +) + +// EntAgentTraceDriver provides agent trace storage operations using an ent client. +type EntAgentTraceDriver struct { + Client *ent.Client +} + +// CreateAgentTrace stores an agent trace using a transaction for atomic multi-table insert. +func (d *EntAgentTraceDriver) CreateAgentTrace(ctx context.Context, trace *agenttrace.AgentTrace) (*agenttrace.AgentTrace, error) { + tx, err := d.Client.Tx(ctx) + if err != nil { + return nil, fmt.Errorf("starting transaction: %w", err) + } + + // Create the root trace record + traceCreate := tx.AgentTrace.Create(). + SetID(trace.ID). + SetVersion(trace.Version). + SetTimestamp(trace.Timestamp) + + if trace.VCS != nil { + if trace.VCS.Type != "" { + traceCreate.SetVcsType(trace.VCS.Type) + } + if trace.VCS.Revision != "" { + traceCreate.SetVcsRevision(trace.VCS.Revision) + } + } + + if trace.Tool != nil { + if trace.Tool.Name != "" { + traceCreate.SetToolName(trace.Tool.Name) + } + if trace.Tool.Version != "" { + traceCreate.SetToolVersion(trace.Tool.Version) + } + } + + if trace.Metadata != nil { + traceCreate.SetMetadata(trace.Metadata) + } + + entTrace, err := traceCreate.Save(ctx) + if err != nil { + _ = tx.Rollback() + return nil, fmt.Errorf("creating agent trace: %w", err) + } + + // Create files and their nested entities + for _, f := range trace.Files { + fileCreate := tx.AgentTraceFile.Create(). + SetPath(f.Path). + SetTrace(entTrace) + + entFile, err := fileCreate.Save(ctx) + if err != nil { + _ = tx.Rollback() + return nil, fmt.Errorf("creating agent trace file: %w", err) + } + + for _, conv := range f.Conversations { + convCreate := tx.AgentTraceConversation.Create(). + SetFile(entFile) + + if conv.URL != "" { + convCreate.SetURL(conv.URL) + } + if conv.Contributor != nil { + if conv.Contributor.Type != "" { + convCreate.SetContributorType(conv.Contributor.Type) + } + if conv.Contributor.ModelID != "" { + convCreate.SetContributorModelID(conv.Contributor.ModelID) + } + } + if len(conv.RelatedResources) > 0 { + related := make([]map[string]any, len(conv.RelatedResources)) + for i, r := range conv.RelatedResources { + related[i] = map[string]any{ + "type": r.Type, + "url": r.URL, + } + } + convCreate.SetRelated(related) + } + + entConv, err := convCreate.Save(ctx) + if err != nil { + _ = tx.Rollback() + return nil, fmt.Errorf("creating agent trace conversation: %w", err) + } + + for _, r := range conv.Ranges { + rangeCreate := tx.AgentTraceRange.Create(). + SetStartLine(r.StartLine). + SetEndLine(r.EndLine). + SetConversation(entConv) + + if r.ContentHash != "" { + rangeCreate.SetContentHash(r.ContentHash) + } + if r.Contributor != nil { + if r.Contributor.Type != "" { + rangeCreate.SetContributorType(r.Contributor.Type) + } + if r.Contributor.ModelID != "" { + rangeCreate.SetContributorModelID(r.Contributor.ModelID) + } + } + + if _, err := rangeCreate.Save(ctx); err != nil { + _ = tx.Rollback() + return nil, fmt.Errorf("creating agent trace range: %w", err) + } + } + } + } + + if err := tx.Commit(); err != nil { + return nil, fmt.Errorf("committing transaction: %w", err) + } + + return d.GetAgentTrace(ctx, trace.ID) +} + +// GetAgentTrace retrieves an agent trace by ID with eager loading 3 levels deep. +func (d *EntAgentTraceDriver) GetAgentTrace(ctx context.Context, id string) (*agenttrace.AgentTrace, error) { + entTrace, err := d.Client.AgentTrace.Query(). + Where(entagenttrace.ID(id)). + WithFiles(func(q *ent.AgentTraceFileQuery) { + q.WithConversations(func(q *ent.AgentTraceConversationQuery) { + q.WithRanges() + }) + }). + Only(ctx) + if err != nil { + if ent.IsNotFound(err) { + return nil, fmt.Errorf("agent trace not found: %s", id) + } + return nil, fmt.Errorf("querying agent trace: %w", err) + } + + return entAgentTraceToAgentTrace(entTrace), nil +} + +// QueryAgentTraces queries agent traces with dynamic filtering. +func (d *EntAgentTraceDriver) QueryAgentTraces(ctx context.Context, query storage.AgentTraceQuery) ([]*agenttrace.AgentTrace, error) { + q := d.Client.AgentTrace.Query() + + // Apply filters + var predicates []predicate.AgentTrace + + if query.FilePath != "" { + predicates = append(predicates, entagenttrace.HasFilesWith(agenttracefile.PathEQ(query.FilePath))) + } + if query.Revision != "" { + predicates = append(predicates, entagenttrace.VcsRevisionEQ(query.Revision)) + } + if query.ToolName != "" { + predicates = append(predicates, entagenttrace.ToolNameEQ(query.ToolName)) + } + + if len(predicates) > 0 { + q.Where(predicates...) + } + + // Apply ordering + q.Order(ent.Desc(entagenttrace.FieldCreatedAt)) + + // Apply pagination + if query.Limit > 0 { + q.Limit(query.Limit) + } + if query.Offset > 0 { + q.Offset(query.Offset) + } + + // Eager load all nested entities + q.WithFiles(func(fq *ent.AgentTraceFileQuery) { + fq.WithConversations(func(cq *ent.AgentTraceConversationQuery) { + cq.WithRanges() + }) + }) + + entTraces, err := q.All(ctx) + if err != nil { + return nil, fmt.Errorf("querying agent traces: %w", err) + } + + traces := make([]*agenttrace.AgentTrace, 0, len(entTraces)) + for _, et := range entTraces { + traces = append(traces, entAgentTraceToAgentTrace(et)) + } + + return traces, nil +} + +// Close closes the ent client. +func (d *EntAgentTraceDriver) Close() error { + return d.Client.Close() +} + +// entAgentTraceToAgentTrace converts an ent AgentTrace entity to a domain AgentTrace. +func entAgentTraceToAgentTrace(et *ent.AgentTrace) *agenttrace.AgentTrace { + trace := &agenttrace.AgentTrace{ + Version: et.Version, + ID: et.ID, + Timestamp: et.Timestamp, + Metadata: et.Metadata, + } + + if et.VcsType != "" || et.VcsRevision != "" { + trace.VCS = &agenttrace.VCS{ + Type: et.VcsType, + Revision: et.VcsRevision, + } + } + + if et.ToolName != "" || et.ToolVersion != "" { + trace.Tool = &agenttrace.Tool{ + Name: et.ToolName, + Version: et.ToolVersion, + } + } + + if et.Edges.Files != nil { + trace.Files = make([]agenttrace.File, len(et.Edges.Files)) + for i, ef := range et.Edges.Files { + trace.Files[i] = entAgentTraceFileToFile(ef) + } + } + + return trace +} + +func entAgentTraceFileToFile(ef *ent.AgentTraceFile) agenttrace.File { + file := agenttrace.File{ + Path: ef.Path, + } + + if ef.Edges.Conversations != nil { + file.Conversations = make([]agenttrace.Conversation, len(ef.Edges.Conversations)) + for i, ec := range ef.Edges.Conversations { + file.Conversations[i] = entAgentTraceConversationToConversation(ec) + } + } + + return file +} + +func entAgentTraceConversationToConversation(ec *ent.AgentTraceConversation) agenttrace.Conversation { + conv := agenttrace.Conversation{ + URL: ec.URL, + } + + if ec.ContributorType != "" || ec.ContributorModelID != "" { + conv.Contributor = &agenttrace.Contributor{ + Type: ec.ContributorType, + ModelID: ec.ContributorModelID, + } + } + + if ec.Related != nil { + conv.RelatedResources = make([]agenttrace.RelatedResource, len(ec.Related)) + for i, r := range ec.Related { + rr := agenttrace.RelatedResource{} + if t, ok := r["type"].(string); ok { + rr.Type = t + } + if u, ok := r["url"].(string); ok { + rr.URL = u + } + conv.RelatedResources[i] = rr + } + } + + if ec.Edges.Ranges != nil { + conv.Ranges = make([]agenttrace.Range, len(ec.Edges.Ranges)) + for i, er := range ec.Edges.Ranges { + conv.Ranges[i] = entAgentTraceRangeToRange(er) + } + } + + return conv +} + +func entAgentTraceRangeToRange(er *ent.AgentTraceRange) agenttrace.Range { + r := agenttrace.Range{ + StartLine: er.StartLine, + EndLine: er.EndLine, + ContentHash: er.ContentHash, + } + + if er.ContributorType != "" || er.ContributorModelID != "" { + r.Contributor = &agenttrace.Contributor{ + Type: er.ContributorType, + ModelID: er.ContributorModelID, + } + } + + return r +} diff --git a/pkg/storage/ent/ent.go b/pkg/storage/ent/ent.go index 597ab46..699acea 100644 --- a/pkg/storage/ent/ent.go +++ b/pkg/storage/ent/ent.go @@ -12,7 +12,10 @@ import ( "entgo.io/ent" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" - + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttrace" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttraceconversation" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttracefile" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttracerange" "github.com/papercomputeco/tapes/pkg/storage/ent/node" ) @@ -74,7 +77,11 @@ var ( func checkColumn(t, c string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ - node.Table: node.ValidColumn, + agenttrace.Table: agenttrace.ValidColumn, + agenttraceconversation.Table: agenttraceconversation.ValidColumn, + agenttracefile.Table: agenttracefile.ValidColumn, + agenttracerange.Table: agenttracerange.ValidColumn, + node.Table: node.ValidColumn, }) }) return columnCheck(t, c) diff --git a/pkg/storage/ent/enttest/enttest.go b/pkg/storage/ent/enttest/enttest.go index 9cd515a..8cf4caf 100644 --- a/pkg/storage/ent/enttest/enttest.go +++ b/pkg/storage/ent/enttest/enttest.go @@ -10,7 +10,6 @@ import ( _ "github.com/papercomputeco/tapes/pkg/storage/ent/runtime" "entgo.io/ent/dialect/sql/schema" - "github.com/papercomputeco/tapes/pkg/storage/ent/migrate" ) diff --git a/pkg/storage/ent/hook/hook.go b/pkg/storage/ent/hook/hook.go index cc7d58f..141a77f 100644 --- a/pkg/storage/ent/hook/hook.go +++ b/pkg/storage/ent/hook/hook.go @@ -9,6 +9,54 @@ import ( "github.com/papercomputeco/tapes/pkg/storage/ent" ) +// The AgentTraceFunc type is an adapter to allow the use of ordinary +// function as AgentTrace mutator. +type AgentTraceFunc func(context.Context, *ent.AgentTraceMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f AgentTraceFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.AgentTraceMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.AgentTraceMutation", m) +} + +// The AgentTraceConversationFunc type is an adapter to allow the use of ordinary +// function as AgentTraceConversation mutator. +type AgentTraceConversationFunc func(context.Context, *ent.AgentTraceConversationMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f AgentTraceConversationFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.AgentTraceConversationMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.AgentTraceConversationMutation", m) +} + +// The AgentTraceFileFunc type is an adapter to allow the use of ordinary +// function as AgentTraceFile mutator. +type AgentTraceFileFunc func(context.Context, *ent.AgentTraceFileMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f AgentTraceFileFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.AgentTraceFileMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.AgentTraceFileMutation", m) +} + +// The AgentTraceRangeFunc type is an adapter to allow the use of ordinary +// function as AgentTraceRange mutator. +type AgentTraceRangeFunc func(context.Context, *ent.AgentTraceRangeMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f AgentTraceRangeFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.AgentTraceRangeMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.AgentTraceRangeMutation", m) +} + // The NodeFunc type is an adapter to allow the use of ordinary // function as Node mutator. type NodeFunc func(context.Context, *ent.NodeMutation) (ent.Value, error) diff --git a/pkg/storage/ent/migrate/schema.go b/pkg/storage/ent/migrate/schema.go index 1800346..771bdae 100644 --- a/pkg/storage/ent/migrate/schema.go +++ b/pkg/storage/ent/migrate/schema.go @@ -8,6 +8,134 @@ import ( ) var ( + // AgentTracesColumns holds the columns for the "agent_traces" table. + AgentTracesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeString, Unique: true}, + {Name: "version", Type: field.TypeString}, + {Name: "timestamp", Type: field.TypeString}, + {Name: "vcs_type", Type: field.TypeString, Nullable: true}, + {Name: "vcs_revision", Type: field.TypeString, Nullable: true}, + {Name: "tool_name", Type: field.TypeString, Nullable: true}, + {Name: "tool_version", Type: field.TypeString, Nullable: true}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true}, + {Name: "created_at", Type: field.TypeTime, Default: "CURRENT_TIMESTAMP"}, + } + // AgentTracesTable holds the schema information for the "agent_traces" table. + AgentTracesTable = &schema.Table{ + Name: "agent_traces", + Columns: AgentTracesColumns, + PrimaryKey: []*schema.Column{AgentTracesColumns[0]}, + Indexes: []*schema.Index{ + { + Name: "agenttrace_vcs_revision", + Unique: false, + Columns: []*schema.Column{AgentTracesColumns[4]}, + }, + { + Name: "agenttrace_tool_name", + Unique: false, + Columns: []*schema.Column{AgentTracesColumns[5]}, + }, + { + Name: "agenttrace_timestamp", + Unique: false, + Columns: []*schema.Column{AgentTracesColumns[2]}, + }, + }, + } + // AgentTraceConversationsColumns holds the columns for the "agent_trace_conversations" table. + AgentTraceConversationsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "url", Type: field.TypeString, Nullable: true}, + {Name: "contributor_type", Type: field.TypeString, Nullable: true}, + {Name: "contributor_model_id", Type: field.TypeString, Nullable: true}, + {Name: "related", Type: field.TypeJSON, Nullable: true}, + {Name: "agent_trace_file_conversations", Type: field.TypeInt}, + } + // AgentTraceConversationsTable holds the schema information for the "agent_trace_conversations" table. + AgentTraceConversationsTable = &schema.Table{ + Name: "agent_trace_conversations", + Columns: AgentTraceConversationsColumns, + PrimaryKey: []*schema.Column{AgentTraceConversationsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "agent_trace_conversations_agent_trace_files_conversations", + Columns: []*schema.Column{AgentTraceConversationsColumns[5]}, + RefColumns: []*schema.Column{AgentTraceFilesColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "agenttraceconversation_contributor_type", + Unique: false, + Columns: []*schema.Column{AgentTraceConversationsColumns[2]}, + }, + { + Name: "agenttraceconversation_contributor_model_id", + Unique: false, + Columns: []*schema.Column{AgentTraceConversationsColumns[3]}, + }, + }, + } + // AgentTraceFilesColumns holds the columns for the "agent_trace_files" table. + AgentTraceFilesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "path", Type: field.TypeString}, + {Name: "agent_trace_files", Type: field.TypeString}, + } + // AgentTraceFilesTable holds the schema information for the "agent_trace_files" table. + AgentTraceFilesTable = &schema.Table{ + Name: "agent_trace_files", + Columns: AgentTraceFilesColumns, + PrimaryKey: []*schema.Column{AgentTraceFilesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "agent_trace_files_agent_traces_files", + Columns: []*schema.Column{AgentTraceFilesColumns[2]}, + RefColumns: []*schema.Column{AgentTracesColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "agenttracefile_path", + Unique: false, + Columns: []*schema.Column{AgentTraceFilesColumns[1]}, + }, + }, + } + // AgentTraceRangesColumns holds the columns for the "agent_trace_ranges" table. + AgentTraceRangesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "start_line", Type: field.TypeInt}, + {Name: "end_line", Type: field.TypeInt}, + {Name: "content_hash", Type: field.TypeString, Nullable: true}, + {Name: "contributor_type", Type: field.TypeString, Nullable: true}, + {Name: "contributor_model_id", Type: field.TypeString, Nullable: true}, + {Name: "agent_trace_conversation_ranges", Type: field.TypeInt}, + } + // AgentTraceRangesTable holds the schema information for the "agent_trace_ranges" table. + AgentTraceRangesTable = &schema.Table{ + Name: "agent_trace_ranges", + Columns: AgentTraceRangesColumns, + PrimaryKey: []*schema.Column{AgentTraceRangesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "agent_trace_ranges_agent_trace_conversations_ranges", + Columns: []*schema.Column{AgentTraceRangesColumns[6]}, + RefColumns: []*schema.Column{AgentTraceConversationsColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "agenttracerange_start_line_end_line", + Unique: false, + Columns: []*schema.Column{AgentTraceRangesColumns[1], AgentTraceRangesColumns[2]}, + }, + }, + } // NodesColumns holds the columns for the "nodes" table. NodesColumns = []*schema.Column{ {Name: "hash", Type: field.TypeString, Unique: true}, @@ -69,10 +197,17 @@ var ( } // Tables holds all the tables in the schema. Tables = []*schema.Table{ + AgentTracesTable, + AgentTraceConversationsTable, + AgentTraceFilesTable, + AgentTraceRangesTable, NodesTable, } ) func init() { + AgentTraceConversationsTable.ForeignKeys[0].RefTable = AgentTraceFilesTable + AgentTraceFilesTable.ForeignKeys[0].RefTable = AgentTracesTable + AgentTraceRangesTable.ForeignKeys[0].RefTable = AgentTraceConversationsTable NodesTable.ForeignKeys[0].RefTable = NodesTable } diff --git a/pkg/storage/ent/mutation.go b/pkg/storage/ent/mutation.go index 294d058..328205f 100644 --- a/pkg/storage/ent/mutation.go +++ b/pkg/storage/ent/mutation.go @@ -11,7 +11,10 @@ import ( "entgo.io/ent" "entgo.io/ent/dialect/sql" - + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttrace" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttraceconversation" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttracefile" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttracerange" "github.com/papercomputeco/tapes/pkg/storage/ent/node" "github.com/papercomputeco/tapes/pkg/storage/ent/predicate" ) @@ -25,9 +28,2866 @@ const ( OpUpdateOne = ent.OpUpdateOne // Node types. - TypeNode = "Node" + TypeAgentTrace = "AgentTrace" + TypeAgentTraceConversation = "AgentTraceConversation" + TypeAgentTraceFile = "AgentTraceFile" + TypeAgentTraceRange = "AgentTraceRange" + TypeNode = "Node" ) +// AgentTraceMutation represents an operation that mutates the AgentTrace nodes in the graph. +type AgentTraceMutation struct { + config + op Op + typ string + id *string + version *string + timestamp *string + vcs_type *string + vcs_revision *string + tool_name *string + tool_version *string + metadata *map[string]interface{} + created_at *time.Time + clearedFields map[string]struct{} + files map[int]struct{} + removedfiles map[int]struct{} + clearedfiles bool + done bool + oldValue func(context.Context) (*AgentTrace, error) + predicates []predicate.AgentTrace +} + +var _ ent.Mutation = (*AgentTraceMutation)(nil) + +// agenttraceOption allows management of the mutation configuration using functional options. +type agenttraceOption func(*AgentTraceMutation) + +// newAgentTraceMutation creates new mutation for the AgentTrace entity. +func newAgentTraceMutation(c config, op Op, opts ...agenttraceOption) *AgentTraceMutation { + m := &AgentTraceMutation{ + config: c, + op: op, + typ: TypeAgentTrace, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withAgentTraceID sets the ID field of the mutation. +func withAgentTraceID(id string) agenttraceOption { + return func(m *AgentTraceMutation) { + var ( + err error + once sync.Once + value *AgentTrace + ) + m.oldValue = func(ctx context.Context) (*AgentTrace, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().AgentTrace.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withAgentTrace sets the old AgentTrace of the mutation. +func withAgentTrace(node *AgentTrace) agenttraceOption { + return func(m *AgentTraceMutation) { + m.oldValue = func(context.Context) (*AgentTrace, 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 AgentTraceMutation) 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 AgentTraceMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// SetID sets the value of the id field. Note that this +// operation is only accepted on creation of AgentTrace entities. +func (m *AgentTraceMutation) 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 *AgentTraceMutation) ID() (id string, 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 *AgentTraceMutation) 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().AgentTrace.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetVersion sets the "version" field. +func (m *AgentTraceMutation) SetVersion(s string) { + m.version = &s +} + +// Version returns the value of the "version" field in the mutation. +func (m *AgentTraceMutation) Version() (r string, exists bool) { + v := m.version + if v == nil { + return + } + return *v, true +} + +// OldVersion returns the old "version" field's value of the AgentTrace entity. +// If the AgentTrace 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 *AgentTraceMutation) 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 +} + +// ResetVersion resets all changes to the "version" field. +func (m *AgentTraceMutation) ResetVersion() { + m.version = nil +} + +// SetTimestamp sets the "timestamp" field. +func (m *AgentTraceMutation) SetTimestamp(s string) { + m.timestamp = &s +} + +// Timestamp returns the value of the "timestamp" field in the mutation. +func (m *AgentTraceMutation) Timestamp() (r string, exists bool) { + v := m.timestamp + if v == nil { + return + } + return *v, true +} + +// OldTimestamp returns the old "timestamp" field's value of the AgentTrace entity. +// If the AgentTrace 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 *AgentTraceMutation) OldTimestamp(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTimestamp is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTimestamp requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTimestamp: %w", err) + } + return oldValue.Timestamp, nil +} + +// ResetTimestamp resets all changes to the "timestamp" field. +func (m *AgentTraceMutation) ResetTimestamp() { + m.timestamp = nil +} + +// SetVcsType sets the "vcs_type" field. +func (m *AgentTraceMutation) SetVcsType(s string) { + m.vcs_type = &s +} + +// VcsType returns the value of the "vcs_type" field in the mutation. +func (m *AgentTraceMutation) VcsType() (r string, exists bool) { + v := m.vcs_type + if v == nil { + return + } + return *v, true +} + +// OldVcsType returns the old "vcs_type" field's value of the AgentTrace entity. +// If the AgentTrace 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 *AgentTraceMutation) OldVcsType(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldVcsType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldVcsType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldVcsType: %w", err) + } + return oldValue.VcsType, nil +} + +// ClearVcsType clears the value of the "vcs_type" field. +func (m *AgentTraceMutation) ClearVcsType() { + m.vcs_type = nil + m.clearedFields[agenttrace.FieldVcsType] = struct{}{} +} + +// VcsTypeCleared returns if the "vcs_type" field was cleared in this mutation. +func (m *AgentTraceMutation) VcsTypeCleared() bool { + _, ok := m.clearedFields[agenttrace.FieldVcsType] + return ok +} + +// ResetVcsType resets all changes to the "vcs_type" field. +func (m *AgentTraceMutation) ResetVcsType() { + m.vcs_type = nil + delete(m.clearedFields, agenttrace.FieldVcsType) +} + +// SetVcsRevision sets the "vcs_revision" field. +func (m *AgentTraceMutation) SetVcsRevision(s string) { + m.vcs_revision = &s +} + +// VcsRevision returns the value of the "vcs_revision" field in the mutation. +func (m *AgentTraceMutation) VcsRevision() (r string, exists bool) { + v := m.vcs_revision + if v == nil { + return + } + return *v, true +} + +// OldVcsRevision returns the old "vcs_revision" field's value of the AgentTrace entity. +// If the AgentTrace 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 *AgentTraceMutation) OldVcsRevision(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldVcsRevision is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldVcsRevision requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldVcsRevision: %w", err) + } + return oldValue.VcsRevision, nil +} + +// ClearVcsRevision clears the value of the "vcs_revision" field. +func (m *AgentTraceMutation) ClearVcsRevision() { + m.vcs_revision = nil + m.clearedFields[agenttrace.FieldVcsRevision] = struct{}{} +} + +// VcsRevisionCleared returns if the "vcs_revision" field was cleared in this mutation. +func (m *AgentTraceMutation) VcsRevisionCleared() bool { + _, ok := m.clearedFields[agenttrace.FieldVcsRevision] + return ok +} + +// ResetVcsRevision resets all changes to the "vcs_revision" field. +func (m *AgentTraceMutation) ResetVcsRevision() { + m.vcs_revision = nil + delete(m.clearedFields, agenttrace.FieldVcsRevision) +} + +// SetToolName sets the "tool_name" field. +func (m *AgentTraceMutation) SetToolName(s string) { + m.tool_name = &s +} + +// ToolName returns the value of the "tool_name" field in the mutation. +func (m *AgentTraceMutation) ToolName() (r string, exists bool) { + v := m.tool_name + if v == nil { + return + } + return *v, true +} + +// OldToolName returns the old "tool_name" field's value of the AgentTrace entity. +// If the AgentTrace 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 *AgentTraceMutation) OldToolName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldToolName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldToolName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldToolName: %w", err) + } + return oldValue.ToolName, nil +} + +// ClearToolName clears the value of the "tool_name" field. +func (m *AgentTraceMutation) ClearToolName() { + m.tool_name = nil + m.clearedFields[agenttrace.FieldToolName] = struct{}{} +} + +// ToolNameCleared returns if the "tool_name" field was cleared in this mutation. +func (m *AgentTraceMutation) ToolNameCleared() bool { + _, ok := m.clearedFields[agenttrace.FieldToolName] + return ok +} + +// ResetToolName resets all changes to the "tool_name" field. +func (m *AgentTraceMutation) ResetToolName() { + m.tool_name = nil + delete(m.clearedFields, agenttrace.FieldToolName) +} + +// SetToolVersion sets the "tool_version" field. +func (m *AgentTraceMutation) SetToolVersion(s string) { + m.tool_version = &s +} + +// ToolVersion returns the value of the "tool_version" field in the mutation. +func (m *AgentTraceMutation) ToolVersion() (r string, exists bool) { + v := m.tool_version + if v == nil { + return + } + return *v, true +} + +// OldToolVersion returns the old "tool_version" field's value of the AgentTrace entity. +// If the AgentTrace 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 *AgentTraceMutation) OldToolVersion(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldToolVersion is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldToolVersion requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldToolVersion: %w", err) + } + return oldValue.ToolVersion, nil +} + +// ClearToolVersion clears the value of the "tool_version" field. +func (m *AgentTraceMutation) ClearToolVersion() { + m.tool_version = nil + m.clearedFields[agenttrace.FieldToolVersion] = struct{}{} +} + +// ToolVersionCleared returns if the "tool_version" field was cleared in this mutation. +func (m *AgentTraceMutation) ToolVersionCleared() bool { + _, ok := m.clearedFields[agenttrace.FieldToolVersion] + return ok +} + +// ResetToolVersion resets all changes to the "tool_version" field. +func (m *AgentTraceMutation) ResetToolVersion() { + m.tool_version = nil + delete(m.clearedFields, agenttrace.FieldToolVersion) +} + +// SetMetadata sets the "metadata" field. +func (m *AgentTraceMutation) SetMetadata(value map[string]interface{}) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *AgentTraceMutation) Metadata() (r map[string]interface{}, exists bool) { + v := m.metadata + if v == nil { + return + } + return *v, true +} + +// OldMetadata returns the old "metadata" field's value of the AgentTrace entity. +// If the AgentTrace 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 *AgentTraceMutation) OldMetadata(ctx context.Context) (v map[string]interface{}, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldMetadata: %w", err) + } + return oldValue.Metadata, nil +} + +// ClearMetadata clears the value of the "metadata" field. +func (m *AgentTraceMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[agenttrace.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *AgentTraceMutation) MetadataCleared() bool { + _, ok := m.clearedFields[agenttrace.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *AgentTraceMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, agenttrace.FieldMetadata) +} + +// SetCreatedAt sets the "created_at" field. +func (m *AgentTraceMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *AgentTraceMutation) 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 AgentTrace entity. +// If the AgentTrace 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 *AgentTraceMutation) 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 *AgentTraceMutation) ResetCreatedAt() { + m.created_at = nil +} + +// AddFileIDs adds the "files" edge to the AgentTraceFile entity by ids. +func (m *AgentTraceMutation) AddFileIDs(ids ...int) { + if m.files == nil { + m.files = make(map[int]struct{}) + } + for i := range ids { + m.files[ids[i]] = struct{}{} + } +} + +// ClearFiles clears the "files" edge to the AgentTraceFile entity. +func (m *AgentTraceMutation) ClearFiles() { + m.clearedfiles = true +} + +// FilesCleared reports if the "files" edge to the AgentTraceFile entity was cleared. +func (m *AgentTraceMutation) FilesCleared() bool { + return m.clearedfiles +} + +// RemoveFileIDs removes the "files" edge to the AgentTraceFile entity by IDs. +func (m *AgentTraceMutation) RemoveFileIDs(ids ...int) { + if m.removedfiles == nil { + m.removedfiles = make(map[int]struct{}) + } + for i := range ids { + delete(m.files, ids[i]) + m.removedfiles[ids[i]] = struct{}{} + } +} + +// RemovedFiles returns the removed IDs of the "files" edge to the AgentTraceFile entity. +func (m *AgentTraceMutation) RemovedFilesIDs() (ids []int) { + for id := range m.removedfiles { + ids = append(ids, id) + } + return +} + +// FilesIDs returns the "files" edge IDs in the mutation. +func (m *AgentTraceMutation) FilesIDs() (ids []int) { + for id := range m.files { + ids = append(ids, id) + } + return +} + +// ResetFiles resets all changes to the "files" edge. +func (m *AgentTraceMutation) ResetFiles() { + m.files = nil + m.clearedfiles = false + m.removedfiles = nil +} + +// Where appends a list predicates to the AgentTraceMutation builder. +func (m *AgentTraceMutation) Where(ps ...predicate.AgentTrace) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the AgentTraceMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *AgentTraceMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.AgentTrace, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *AgentTraceMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *AgentTraceMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (AgentTrace). +func (m *AgentTraceMutation) 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 *AgentTraceMutation) Fields() []string { + fields := make([]string, 0, 8) + if m.version != nil { + fields = append(fields, agenttrace.FieldVersion) + } + if m.timestamp != nil { + fields = append(fields, agenttrace.FieldTimestamp) + } + if m.vcs_type != nil { + fields = append(fields, agenttrace.FieldVcsType) + } + if m.vcs_revision != nil { + fields = append(fields, agenttrace.FieldVcsRevision) + } + if m.tool_name != nil { + fields = append(fields, agenttrace.FieldToolName) + } + if m.tool_version != nil { + fields = append(fields, agenttrace.FieldToolVersion) + } + if m.metadata != nil { + fields = append(fields, agenttrace.FieldMetadata) + } + if m.created_at != nil { + fields = append(fields, agenttrace.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 *AgentTraceMutation) Field(name string) (ent.Value, bool) { + switch name { + case agenttrace.FieldVersion: + return m.Version() + case agenttrace.FieldTimestamp: + return m.Timestamp() + case agenttrace.FieldVcsType: + return m.VcsType() + case agenttrace.FieldVcsRevision: + return m.VcsRevision() + case agenttrace.FieldToolName: + return m.ToolName() + case agenttrace.FieldToolVersion: + return m.ToolVersion() + case agenttrace.FieldMetadata: + return m.Metadata() + case agenttrace.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 *AgentTraceMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case agenttrace.FieldVersion: + return m.OldVersion(ctx) + case agenttrace.FieldTimestamp: + return m.OldTimestamp(ctx) + case agenttrace.FieldVcsType: + return m.OldVcsType(ctx) + case agenttrace.FieldVcsRevision: + return m.OldVcsRevision(ctx) + case agenttrace.FieldToolName: + return m.OldToolName(ctx) + case agenttrace.FieldToolVersion: + return m.OldToolVersion(ctx) + case agenttrace.FieldMetadata: + return m.OldMetadata(ctx) + case agenttrace.FieldCreatedAt: + return m.OldCreatedAt(ctx) + } + return nil, fmt.Errorf("unknown AgentTrace 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 *AgentTraceMutation) SetField(name string, value ent.Value) error { + switch name { + case agenttrace.FieldVersion: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetVersion(v) + return nil + case agenttrace.FieldTimestamp: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTimestamp(v) + return nil + case agenttrace.FieldVcsType: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetVcsType(v) + return nil + case agenttrace.FieldVcsRevision: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetVcsRevision(v) + return nil + case agenttrace.FieldToolName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetToolName(v) + return nil + case agenttrace.FieldToolVersion: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetToolVersion(v) + return nil + case agenttrace.FieldMetadata: + v, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetMetadata(v) + return nil + case agenttrace.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 AgentTrace field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *AgentTraceMutation) 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 *AgentTraceMutation) 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 *AgentTraceMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown AgentTrace numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *AgentTraceMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(agenttrace.FieldVcsType) { + fields = append(fields, agenttrace.FieldVcsType) + } + if m.FieldCleared(agenttrace.FieldVcsRevision) { + fields = append(fields, agenttrace.FieldVcsRevision) + } + if m.FieldCleared(agenttrace.FieldToolName) { + fields = append(fields, agenttrace.FieldToolName) + } + if m.FieldCleared(agenttrace.FieldToolVersion) { + fields = append(fields, agenttrace.FieldToolVersion) + } + if m.FieldCleared(agenttrace.FieldMetadata) { + fields = append(fields, agenttrace.FieldMetadata) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *AgentTraceMutation) 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 *AgentTraceMutation) ClearField(name string) error { + switch name { + case agenttrace.FieldVcsType: + m.ClearVcsType() + return nil + case agenttrace.FieldVcsRevision: + m.ClearVcsRevision() + return nil + case agenttrace.FieldToolName: + m.ClearToolName() + return nil + case agenttrace.FieldToolVersion: + m.ClearToolVersion() + return nil + case agenttrace.FieldMetadata: + m.ClearMetadata() + return nil + } + return fmt.Errorf("unknown AgentTrace 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 *AgentTraceMutation) ResetField(name string) error { + switch name { + case agenttrace.FieldVersion: + m.ResetVersion() + return nil + case agenttrace.FieldTimestamp: + m.ResetTimestamp() + return nil + case agenttrace.FieldVcsType: + m.ResetVcsType() + return nil + case agenttrace.FieldVcsRevision: + m.ResetVcsRevision() + return nil + case agenttrace.FieldToolName: + m.ResetToolName() + return nil + case agenttrace.FieldToolVersion: + m.ResetToolVersion() + return nil + case agenttrace.FieldMetadata: + m.ResetMetadata() + return nil + case agenttrace.FieldCreatedAt: + m.ResetCreatedAt() + return nil + } + return fmt.Errorf("unknown AgentTrace field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *AgentTraceMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.files != nil { + edges = append(edges, agenttrace.EdgeFiles) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *AgentTraceMutation) AddedIDs(name string) []ent.Value { + switch name { + case agenttrace.EdgeFiles: + ids := make([]ent.Value, 0, len(m.files)) + for id := range m.files { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *AgentTraceMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + if m.removedfiles != nil { + edges = append(edges, agenttrace.EdgeFiles) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *AgentTraceMutation) RemovedIDs(name string) []ent.Value { + switch name { + case agenttrace.EdgeFiles: + ids := make([]ent.Value, 0, len(m.removedfiles)) + for id := range m.removedfiles { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *AgentTraceMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedfiles { + edges = append(edges, agenttrace.EdgeFiles) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *AgentTraceMutation) EdgeCleared(name string) bool { + switch name { + case agenttrace.EdgeFiles: + return m.clearedfiles + } + 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 *AgentTraceMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown AgentTrace 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 *AgentTraceMutation) ResetEdge(name string) error { + switch name { + case agenttrace.EdgeFiles: + m.ResetFiles() + return nil + } + return fmt.Errorf("unknown AgentTrace edge %s", name) +} + +// AgentTraceConversationMutation represents an operation that mutates the AgentTraceConversation nodes in the graph. +type AgentTraceConversationMutation struct { + config + op Op + typ string + id *int + url *string + contributor_type *string + contributor_model_id *string + related *[]map[string]interface{} + appendrelated []map[string]interface{} + clearedFields map[string]struct{} + file *int + clearedfile bool + ranges map[int]struct{} + removedranges map[int]struct{} + clearedranges bool + done bool + oldValue func(context.Context) (*AgentTraceConversation, error) + predicates []predicate.AgentTraceConversation +} + +var _ ent.Mutation = (*AgentTraceConversationMutation)(nil) + +// agenttraceconversationOption allows management of the mutation configuration using functional options. +type agenttraceconversationOption func(*AgentTraceConversationMutation) + +// newAgentTraceConversationMutation creates new mutation for the AgentTraceConversation entity. +func newAgentTraceConversationMutation(c config, op Op, opts ...agenttraceconversationOption) *AgentTraceConversationMutation { + m := &AgentTraceConversationMutation{ + config: c, + op: op, + typ: TypeAgentTraceConversation, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withAgentTraceConversationID sets the ID field of the mutation. +func withAgentTraceConversationID(id int) agenttraceconversationOption { + return func(m *AgentTraceConversationMutation) { + var ( + err error + once sync.Once + value *AgentTraceConversation + ) + m.oldValue = func(ctx context.Context) (*AgentTraceConversation, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().AgentTraceConversation.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withAgentTraceConversation sets the old AgentTraceConversation of the mutation. +func withAgentTraceConversation(node *AgentTraceConversation) agenttraceconversationOption { + return func(m *AgentTraceConversationMutation) { + m.oldValue = func(context.Context) (*AgentTraceConversation, 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 AgentTraceConversationMutation) 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 AgentTraceConversationMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// 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 *AgentTraceConversationMutation) ID() (id int, 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 *AgentTraceConversationMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().AgentTraceConversation.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetURL sets the "url" field. +func (m *AgentTraceConversationMutation) SetURL(s string) { + m.url = &s +} + +// URL returns the value of the "url" field in the mutation. +func (m *AgentTraceConversationMutation) URL() (r string, exists bool) { + v := m.url + if v == nil { + return + } + return *v, true +} + +// OldURL returns the old "url" field's value of the AgentTraceConversation entity. +// If the AgentTraceConversation 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 *AgentTraceConversationMutation) OldURL(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldURL is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldURL requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldURL: %w", err) + } + return oldValue.URL, nil +} + +// ClearURL clears the value of the "url" field. +func (m *AgentTraceConversationMutation) ClearURL() { + m.url = nil + m.clearedFields[agenttraceconversation.FieldURL] = struct{}{} +} + +// URLCleared returns if the "url" field was cleared in this mutation. +func (m *AgentTraceConversationMutation) URLCleared() bool { + _, ok := m.clearedFields[agenttraceconversation.FieldURL] + return ok +} + +// ResetURL resets all changes to the "url" field. +func (m *AgentTraceConversationMutation) ResetURL() { + m.url = nil + delete(m.clearedFields, agenttraceconversation.FieldURL) +} + +// SetContributorType sets the "contributor_type" field. +func (m *AgentTraceConversationMutation) SetContributorType(s string) { + m.contributor_type = &s +} + +// ContributorType returns the value of the "contributor_type" field in the mutation. +func (m *AgentTraceConversationMutation) ContributorType() (r string, exists bool) { + v := m.contributor_type + if v == nil { + return + } + return *v, true +} + +// OldContributorType returns the old "contributor_type" field's value of the AgentTraceConversation entity. +// If the AgentTraceConversation 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 *AgentTraceConversationMutation) OldContributorType(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldContributorType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldContributorType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldContributorType: %w", err) + } + return oldValue.ContributorType, nil +} + +// ClearContributorType clears the value of the "contributor_type" field. +func (m *AgentTraceConversationMutation) ClearContributorType() { + m.contributor_type = nil + m.clearedFields[agenttraceconversation.FieldContributorType] = struct{}{} +} + +// ContributorTypeCleared returns if the "contributor_type" field was cleared in this mutation. +func (m *AgentTraceConversationMutation) ContributorTypeCleared() bool { + _, ok := m.clearedFields[agenttraceconversation.FieldContributorType] + return ok +} + +// ResetContributorType resets all changes to the "contributor_type" field. +func (m *AgentTraceConversationMutation) ResetContributorType() { + m.contributor_type = nil + delete(m.clearedFields, agenttraceconversation.FieldContributorType) +} + +// SetContributorModelID sets the "contributor_model_id" field. +func (m *AgentTraceConversationMutation) SetContributorModelID(s string) { + m.contributor_model_id = &s +} + +// ContributorModelID returns the value of the "contributor_model_id" field in the mutation. +func (m *AgentTraceConversationMutation) ContributorModelID() (r string, exists bool) { + v := m.contributor_model_id + if v == nil { + return + } + return *v, true +} + +// OldContributorModelID returns the old "contributor_model_id" field's value of the AgentTraceConversation entity. +// If the AgentTraceConversation 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 *AgentTraceConversationMutation) OldContributorModelID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldContributorModelID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldContributorModelID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldContributorModelID: %w", err) + } + return oldValue.ContributorModelID, nil +} + +// ClearContributorModelID clears the value of the "contributor_model_id" field. +func (m *AgentTraceConversationMutation) ClearContributorModelID() { + m.contributor_model_id = nil + m.clearedFields[agenttraceconversation.FieldContributorModelID] = struct{}{} +} + +// ContributorModelIDCleared returns if the "contributor_model_id" field was cleared in this mutation. +func (m *AgentTraceConversationMutation) ContributorModelIDCleared() bool { + _, ok := m.clearedFields[agenttraceconversation.FieldContributorModelID] + return ok +} + +// ResetContributorModelID resets all changes to the "contributor_model_id" field. +func (m *AgentTraceConversationMutation) ResetContributorModelID() { + m.contributor_model_id = nil + delete(m.clearedFields, agenttraceconversation.FieldContributorModelID) +} + +// SetRelated sets the "related" field. +func (m *AgentTraceConversationMutation) SetRelated(value []map[string]interface{}) { + m.related = &value + m.appendrelated = nil +} + +// Related returns the value of the "related" field in the mutation. +func (m *AgentTraceConversationMutation) Related() (r []map[string]interface{}, exists bool) { + v := m.related + if v == nil { + return + } + return *v, true +} + +// OldRelated returns the old "related" field's value of the AgentTraceConversation entity. +// If the AgentTraceConversation 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 *AgentTraceConversationMutation) OldRelated(ctx context.Context) (v []map[string]interface{}, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRelated is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRelated requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRelated: %w", err) + } + return oldValue.Related, nil +} + +// AppendRelated adds value to the "related" field. +func (m *AgentTraceConversationMutation) AppendRelated(value []map[string]interface{}) { + m.appendrelated = append(m.appendrelated, value...) +} + +// AppendedRelated returns the list of values that were appended to the "related" field in this mutation. +func (m *AgentTraceConversationMutation) AppendedRelated() ([]map[string]interface{}, bool) { + if len(m.appendrelated) == 0 { + return nil, false + } + return m.appendrelated, true +} + +// ClearRelated clears the value of the "related" field. +func (m *AgentTraceConversationMutation) ClearRelated() { + m.related = nil + m.appendrelated = nil + m.clearedFields[agenttraceconversation.FieldRelated] = struct{}{} +} + +// RelatedCleared returns if the "related" field was cleared in this mutation. +func (m *AgentTraceConversationMutation) RelatedCleared() bool { + _, ok := m.clearedFields[agenttraceconversation.FieldRelated] + return ok +} + +// ResetRelated resets all changes to the "related" field. +func (m *AgentTraceConversationMutation) ResetRelated() { + m.related = nil + m.appendrelated = nil + delete(m.clearedFields, agenttraceconversation.FieldRelated) +} + +// SetFileID sets the "file" edge to the AgentTraceFile entity by id. +func (m *AgentTraceConversationMutation) SetFileID(id int) { + m.file = &id +} + +// ClearFile clears the "file" edge to the AgentTraceFile entity. +func (m *AgentTraceConversationMutation) ClearFile() { + m.clearedfile = true +} + +// FileCleared reports if the "file" edge to the AgentTraceFile entity was cleared. +func (m *AgentTraceConversationMutation) FileCleared() bool { + return m.clearedfile +} + +// FileID returns the "file" edge ID in the mutation. +func (m *AgentTraceConversationMutation) FileID() (id int, exists bool) { + if m.file != nil { + return *m.file, true + } + return +} + +// FileIDs returns the "file" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// FileID instead. It exists only for internal usage by the builders. +func (m *AgentTraceConversationMutation) FileIDs() (ids []int) { + if id := m.file; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetFile resets all changes to the "file" edge. +func (m *AgentTraceConversationMutation) ResetFile() { + m.file = nil + m.clearedfile = false +} + +// AddRangeIDs adds the "ranges" edge to the AgentTraceRange entity by ids. +func (m *AgentTraceConversationMutation) AddRangeIDs(ids ...int) { + if m.ranges == nil { + m.ranges = make(map[int]struct{}) + } + for i := range ids { + m.ranges[ids[i]] = struct{}{} + } +} + +// ClearRanges clears the "ranges" edge to the AgentTraceRange entity. +func (m *AgentTraceConversationMutation) ClearRanges() { + m.clearedranges = true +} + +// RangesCleared reports if the "ranges" edge to the AgentTraceRange entity was cleared. +func (m *AgentTraceConversationMutation) RangesCleared() bool { + return m.clearedranges +} + +// RemoveRangeIDs removes the "ranges" edge to the AgentTraceRange entity by IDs. +func (m *AgentTraceConversationMutation) RemoveRangeIDs(ids ...int) { + if m.removedranges == nil { + m.removedranges = make(map[int]struct{}) + } + for i := range ids { + delete(m.ranges, ids[i]) + m.removedranges[ids[i]] = struct{}{} + } +} + +// RemovedRanges returns the removed IDs of the "ranges" edge to the AgentTraceRange entity. +func (m *AgentTraceConversationMutation) RemovedRangesIDs() (ids []int) { + for id := range m.removedranges { + ids = append(ids, id) + } + return +} + +// RangesIDs returns the "ranges" edge IDs in the mutation. +func (m *AgentTraceConversationMutation) RangesIDs() (ids []int) { + for id := range m.ranges { + ids = append(ids, id) + } + return +} + +// ResetRanges resets all changes to the "ranges" edge. +func (m *AgentTraceConversationMutation) ResetRanges() { + m.ranges = nil + m.clearedranges = false + m.removedranges = nil +} + +// Where appends a list predicates to the AgentTraceConversationMutation builder. +func (m *AgentTraceConversationMutation) Where(ps ...predicate.AgentTraceConversation) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the AgentTraceConversationMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *AgentTraceConversationMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.AgentTraceConversation, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *AgentTraceConversationMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *AgentTraceConversationMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (AgentTraceConversation). +func (m *AgentTraceConversationMutation) 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 *AgentTraceConversationMutation) Fields() []string { + fields := make([]string, 0, 4) + if m.url != nil { + fields = append(fields, agenttraceconversation.FieldURL) + } + if m.contributor_type != nil { + fields = append(fields, agenttraceconversation.FieldContributorType) + } + if m.contributor_model_id != nil { + fields = append(fields, agenttraceconversation.FieldContributorModelID) + } + if m.related != nil { + fields = append(fields, agenttraceconversation.FieldRelated) + } + 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 *AgentTraceConversationMutation) Field(name string) (ent.Value, bool) { + switch name { + case agenttraceconversation.FieldURL: + return m.URL() + case agenttraceconversation.FieldContributorType: + return m.ContributorType() + case agenttraceconversation.FieldContributorModelID: + return m.ContributorModelID() + case agenttraceconversation.FieldRelated: + return m.Related() + } + 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 *AgentTraceConversationMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case agenttraceconversation.FieldURL: + return m.OldURL(ctx) + case agenttraceconversation.FieldContributorType: + return m.OldContributorType(ctx) + case agenttraceconversation.FieldContributorModelID: + return m.OldContributorModelID(ctx) + case agenttraceconversation.FieldRelated: + return m.OldRelated(ctx) + } + return nil, fmt.Errorf("unknown AgentTraceConversation 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 *AgentTraceConversationMutation) SetField(name string, value ent.Value) error { + switch name { + case agenttraceconversation.FieldURL: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetURL(v) + return nil + case agenttraceconversation.FieldContributorType: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetContributorType(v) + return nil + case agenttraceconversation.FieldContributorModelID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetContributorModelID(v) + return nil + case agenttraceconversation.FieldRelated: + v, ok := value.([]map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRelated(v) + return nil + } + return fmt.Errorf("unknown AgentTraceConversation field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *AgentTraceConversationMutation) 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 *AgentTraceConversationMutation) 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 *AgentTraceConversationMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown AgentTraceConversation numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *AgentTraceConversationMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(agenttraceconversation.FieldURL) { + fields = append(fields, agenttraceconversation.FieldURL) + } + if m.FieldCleared(agenttraceconversation.FieldContributorType) { + fields = append(fields, agenttraceconversation.FieldContributorType) + } + if m.FieldCleared(agenttraceconversation.FieldContributorModelID) { + fields = append(fields, agenttraceconversation.FieldContributorModelID) + } + if m.FieldCleared(agenttraceconversation.FieldRelated) { + fields = append(fields, agenttraceconversation.FieldRelated) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *AgentTraceConversationMutation) 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 *AgentTraceConversationMutation) ClearField(name string) error { + switch name { + case agenttraceconversation.FieldURL: + m.ClearURL() + return nil + case agenttraceconversation.FieldContributorType: + m.ClearContributorType() + return nil + case agenttraceconversation.FieldContributorModelID: + m.ClearContributorModelID() + return nil + case agenttraceconversation.FieldRelated: + m.ClearRelated() + return nil + } + return fmt.Errorf("unknown AgentTraceConversation 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 *AgentTraceConversationMutation) ResetField(name string) error { + switch name { + case agenttraceconversation.FieldURL: + m.ResetURL() + return nil + case agenttraceconversation.FieldContributorType: + m.ResetContributorType() + return nil + case agenttraceconversation.FieldContributorModelID: + m.ResetContributorModelID() + return nil + case agenttraceconversation.FieldRelated: + m.ResetRelated() + return nil + } + return fmt.Errorf("unknown AgentTraceConversation field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *AgentTraceConversationMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.file != nil { + edges = append(edges, agenttraceconversation.EdgeFile) + } + if m.ranges != nil { + edges = append(edges, agenttraceconversation.EdgeRanges) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *AgentTraceConversationMutation) AddedIDs(name string) []ent.Value { + switch name { + case agenttraceconversation.EdgeFile: + if id := m.file; id != nil { + return []ent.Value{*id} + } + case agenttraceconversation.EdgeRanges: + ids := make([]ent.Value, 0, len(m.ranges)) + for id := range m.ranges { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *AgentTraceConversationMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + if m.removedranges != nil { + edges = append(edges, agenttraceconversation.EdgeRanges) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *AgentTraceConversationMutation) RemovedIDs(name string) []ent.Value { + switch name { + case agenttraceconversation.EdgeRanges: + ids := make([]ent.Value, 0, len(m.removedranges)) + for id := range m.removedranges { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *AgentTraceConversationMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedfile { + edges = append(edges, agenttraceconversation.EdgeFile) + } + if m.clearedranges { + edges = append(edges, agenttraceconversation.EdgeRanges) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *AgentTraceConversationMutation) EdgeCleared(name string) bool { + switch name { + case agenttraceconversation.EdgeFile: + return m.clearedfile + case agenttraceconversation.EdgeRanges: + return m.clearedranges + } + 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 *AgentTraceConversationMutation) ClearEdge(name string) error { + switch name { + case agenttraceconversation.EdgeFile: + m.ClearFile() + return nil + } + return fmt.Errorf("unknown AgentTraceConversation 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 *AgentTraceConversationMutation) ResetEdge(name string) error { + switch name { + case agenttraceconversation.EdgeFile: + m.ResetFile() + return nil + case agenttraceconversation.EdgeRanges: + m.ResetRanges() + return nil + } + return fmt.Errorf("unknown AgentTraceConversation edge %s", name) +} + +// AgentTraceFileMutation represents an operation that mutates the AgentTraceFile nodes in the graph. +type AgentTraceFileMutation struct { + config + op Op + typ string + id *int + _path *string + clearedFields map[string]struct{} + trace *string + clearedtrace bool + conversations map[int]struct{} + removedconversations map[int]struct{} + clearedconversations bool + done bool + oldValue func(context.Context) (*AgentTraceFile, error) + predicates []predicate.AgentTraceFile +} + +var _ ent.Mutation = (*AgentTraceFileMutation)(nil) + +// agenttracefileOption allows management of the mutation configuration using functional options. +type agenttracefileOption func(*AgentTraceFileMutation) + +// newAgentTraceFileMutation creates new mutation for the AgentTraceFile entity. +func newAgentTraceFileMutation(c config, op Op, opts ...agenttracefileOption) *AgentTraceFileMutation { + m := &AgentTraceFileMutation{ + config: c, + op: op, + typ: TypeAgentTraceFile, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withAgentTraceFileID sets the ID field of the mutation. +func withAgentTraceFileID(id int) agenttracefileOption { + return func(m *AgentTraceFileMutation) { + var ( + err error + once sync.Once + value *AgentTraceFile + ) + m.oldValue = func(ctx context.Context) (*AgentTraceFile, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().AgentTraceFile.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withAgentTraceFile sets the old AgentTraceFile of the mutation. +func withAgentTraceFile(node *AgentTraceFile) agenttracefileOption { + return func(m *AgentTraceFileMutation) { + m.oldValue = func(context.Context) (*AgentTraceFile, 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 AgentTraceFileMutation) 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 AgentTraceFileMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// 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 *AgentTraceFileMutation) ID() (id int, 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 *AgentTraceFileMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().AgentTraceFile.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetPath sets the "path" field. +func (m *AgentTraceFileMutation) SetPath(s string) { + m._path = &s +} + +// Path returns the value of the "path" field in the mutation. +func (m *AgentTraceFileMutation) Path() (r string, exists bool) { + v := m._path + if v == nil { + return + } + return *v, true +} + +// OldPath returns the old "path" field's value of the AgentTraceFile entity. +// If the AgentTraceFile 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 *AgentTraceFileMutation) OldPath(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPath is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPath requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPath: %w", err) + } + return oldValue.Path, nil +} + +// ResetPath resets all changes to the "path" field. +func (m *AgentTraceFileMutation) ResetPath() { + m._path = nil +} + +// SetTraceID sets the "trace" edge to the AgentTrace entity by id. +func (m *AgentTraceFileMutation) SetTraceID(id string) { + m.trace = &id +} + +// ClearTrace clears the "trace" edge to the AgentTrace entity. +func (m *AgentTraceFileMutation) ClearTrace() { + m.clearedtrace = true +} + +// TraceCleared reports if the "trace" edge to the AgentTrace entity was cleared. +func (m *AgentTraceFileMutation) TraceCleared() bool { + return m.clearedtrace +} + +// TraceID returns the "trace" edge ID in the mutation. +func (m *AgentTraceFileMutation) TraceID() (id string, exists bool) { + if m.trace != nil { + return *m.trace, true + } + return +} + +// TraceIDs returns the "trace" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// TraceID instead. It exists only for internal usage by the builders. +func (m *AgentTraceFileMutation) TraceIDs() (ids []string) { + if id := m.trace; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetTrace resets all changes to the "trace" edge. +func (m *AgentTraceFileMutation) ResetTrace() { + m.trace = nil + m.clearedtrace = false +} + +// AddConversationIDs adds the "conversations" edge to the AgentTraceConversation entity by ids. +func (m *AgentTraceFileMutation) AddConversationIDs(ids ...int) { + if m.conversations == nil { + m.conversations = make(map[int]struct{}) + } + for i := range ids { + m.conversations[ids[i]] = struct{}{} + } +} + +// ClearConversations clears the "conversations" edge to the AgentTraceConversation entity. +func (m *AgentTraceFileMutation) ClearConversations() { + m.clearedconversations = true +} + +// ConversationsCleared reports if the "conversations" edge to the AgentTraceConversation entity was cleared. +func (m *AgentTraceFileMutation) ConversationsCleared() bool { + return m.clearedconversations +} + +// RemoveConversationIDs removes the "conversations" edge to the AgentTraceConversation entity by IDs. +func (m *AgentTraceFileMutation) RemoveConversationIDs(ids ...int) { + if m.removedconversations == nil { + m.removedconversations = make(map[int]struct{}) + } + for i := range ids { + delete(m.conversations, ids[i]) + m.removedconversations[ids[i]] = struct{}{} + } +} + +// RemovedConversations returns the removed IDs of the "conversations" edge to the AgentTraceConversation entity. +func (m *AgentTraceFileMutation) RemovedConversationsIDs() (ids []int) { + for id := range m.removedconversations { + ids = append(ids, id) + } + return +} + +// ConversationsIDs returns the "conversations" edge IDs in the mutation. +func (m *AgentTraceFileMutation) ConversationsIDs() (ids []int) { + for id := range m.conversations { + ids = append(ids, id) + } + return +} + +// ResetConversations resets all changes to the "conversations" edge. +func (m *AgentTraceFileMutation) ResetConversations() { + m.conversations = nil + m.clearedconversations = false + m.removedconversations = nil +} + +// Where appends a list predicates to the AgentTraceFileMutation builder. +func (m *AgentTraceFileMutation) Where(ps ...predicate.AgentTraceFile) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the AgentTraceFileMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *AgentTraceFileMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.AgentTraceFile, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *AgentTraceFileMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *AgentTraceFileMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (AgentTraceFile). +func (m *AgentTraceFileMutation) 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 *AgentTraceFileMutation) Fields() []string { + fields := make([]string, 0, 1) + if m._path != nil { + fields = append(fields, agenttracefile.FieldPath) + } + 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 *AgentTraceFileMutation) Field(name string) (ent.Value, bool) { + switch name { + case agenttracefile.FieldPath: + return m.Path() + } + 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 *AgentTraceFileMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case agenttracefile.FieldPath: + return m.OldPath(ctx) + } + return nil, fmt.Errorf("unknown AgentTraceFile 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 *AgentTraceFileMutation) SetField(name string, value ent.Value) error { + switch name { + case agenttracefile.FieldPath: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPath(v) + return nil + } + return fmt.Errorf("unknown AgentTraceFile field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *AgentTraceFileMutation) 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 *AgentTraceFileMutation) 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 *AgentTraceFileMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown AgentTraceFile numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *AgentTraceFileMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *AgentTraceFileMutation) 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 *AgentTraceFileMutation) ClearField(name string) error { + return fmt.Errorf("unknown AgentTraceFile 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 *AgentTraceFileMutation) ResetField(name string) error { + switch name { + case agenttracefile.FieldPath: + m.ResetPath() + return nil + } + return fmt.Errorf("unknown AgentTraceFile field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *AgentTraceFileMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.trace != nil { + edges = append(edges, agenttracefile.EdgeTrace) + } + if m.conversations != nil { + edges = append(edges, agenttracefile.EdgeConversations) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *AgentTraceFileMutation) AddedIDs(name string) []ent.Value { + switch name { + case agenttracefile.EdgeTrace: + if id := m.trace; id != nil { + return []ent.Value{*id} + } + case agenttracefile.EdgeConversations: + ids := make([]ent.Value, 0, len(m.conversations)) + for id := range m.conversations { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *AgentTraceFileMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + if m.removedconversations != nil { + edges = append(edges, agenttracefile.EdgeConversations) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *AgentTraceFileMutation) RemovedIDs(name string) []ent.Value { + switch name { + case agenttracefile.EdgeConversations: + ids := make([]ent.Value, 0, len(m.removedconversations)) + for id := range m.removedconversations { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *AgentTraceFileMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedtrace { + edges = append(edges, agenttracefile.EdgeTrace) + } + if m.clearedconversations { + edges = append(edges, agenttracefile.EdgeConversations) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *AgentTraceFileMutation) EdgeCleared(name string) bool { + switch name { + case agenttracefile.EdgeTrace: + return m.clearedtrace + case agenttracefile.EdgeConversations: + return m.clearedconversations + } + 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 *AgentTraceFileMutation) ClearEdge(name string) error { + switch name { + case agenttracefile.EdgeTrace: + m.ClearTrace() + return nil + } + return fmt.Errorf("unknown AgentTraceFile 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 *AgentTraceFileMutation) ResetEdge(name string) error { + switch name { + case agenttracefile.EdgeTrace: + m.ResetTrace() + return nil + case agenttracefile.EdgeConversations: + m.ResetConversations() + return nil + } + return fmt.Errorf("unknown AgentTraceFile edge %s", name) +} + +// AgentTraceRangeMutation represents an operation that mutates the AgentTraceRange nodes in the graph. +type AgentTraceRangeMutation struct { + config + op Op + typ string + id *int + start_line *int + addstart_line *int + end_line *int + addend_line *int + content_hash *string + contributor_type *string + contributor_model_id *string + clearedFields map[string]struct{} + conversation *int + clearedconversation bool + done bool + oldValue func(context.Context) (*AgentTraceRange, error) + predicates []predicate.AgentTraceRange +} + +var _ ent.Mutation = (*AgentTraceRangeMutation)(nil) + +// agenttracerangeOption allows management of the mutation configuration using functional options. +type agenttracerangeOption func(*AgentTraceRangeMutation) + +// newAgentTraceRangeMutation creates new mutation for the AgentTraceRange entity. +func newAgentTraceRangeMutation(c config, op Op, opts ...agenttracerangeOption) *AgentTraceRangeMutation { + m := &AgentTraceRangeMutation{ + config: c, + op: op, + typ: TypeAgentTraceRange, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withAgentTraceRangeID sets the ID field of the mutation. +func withAgentTraceRangeID(id int) agenttracerangeOption { + return func(m *AgentTraceRangeMutation) { + var ( + err error + once sync.Once + value *AgentTraceRange + ) + m.oldValue = func(ctx context.Context) (*AgentTraceRange, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().AgentTraceRange.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withAgentTraceRange sets the old AgentTraceRange of the mutation. +func withAgentTraceRange(node *AgentTraceRange) agenttracerangeOption { + return func(m *AgentTraceRangeMutation) { + m.oldValue = func(context.Context) (*AgentTraceRange, 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 AgentTraceRangeMutation) 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 AgentTraceRangeMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("ent: mutation is not running in a transaction") + } + tx := &Tx{config: m.config} + tx.init() + return tx, nil +} + +// 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 *AgentTraceRangeMutation) ID() (id int, 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 *AgentTraceRangeMutation) IDs(ctx context.Context) ([]int, error) { + switch { + case m.op.Is(OpUpdateOne | OpDeleteOne): + id, exists := m.ID() + if exists { + return []int{id}, nil + } + fallthrough + case m.op.Is(OpUpdate | OpDelete): + return m.Client().AgentTraceRange.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetStartLine sets the "start_line" field. +func (m *AgentTraceRangeMutation) SetStartLine(i int) { + m.start_line = &i + m.addstart_line = nil +} + +// StartLine returns the value of the "start_line" field in the mutation. +func (m *AgentTraceRangeMutation) StartLine() (r int, exists bool) { + v := m.start_line + if v == nil { + return + } + return *v, true +} + +// OldStartLine returns the old "start_line" field's value of the AgentTraceRange entity. +// If the AgentTraceRange 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 *AgentTraceRangeMutation) OldStartLine(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStartLine is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStartLine requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStartLine: %w", err) + } + return oldValue.StartLine, nil +} + +// AddStartLine adds i to the "start_line" field. +func (m *AgentTraceRangeMutation) AddStartLine(i int) { + if m.addstart_line != nil { + *m.addstart_line += i + } else { + m.addstart_line = &i + } +} + +// AddedStartLine returns the value that was added to the "start_line" field in this mutation. +func (m *AgentTraceRangeMutation) AddedStartLine() (r int, exists bool) { + v := m.addstart_line + if v == nil { + return + } + return *v, true +} + +// ResetStartLine resets all changes to the "start_line" field. +func (m *AgentTraceRangeMutation) ResetStartLine() { + m.start_line = nil + m.addstart_line = nil +} + +// SetEndLine sets the "end_line" field. +func (m *AgentTraceRangeMutation) SetEndLine(i int) { + m.end_line = &i + m.addend_line = nil +} + +// EndLine returns the value of the "end_line" field in the mutation. +func (m *AgentTraceRangeMutation) EndLine() (r int, exists bool) { + v := m.end_line + if v == nil { + return + } + return *v, true +} + +// OldEndLine returns the old "end_line" field's value of the AgentTraceRange entity. +// If the AgentTraceRange 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 *AgentTraceRangeMutation) OldEndLine(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldEndLine is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldEndLine requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldEndLine: %w", err) + } + return oldValue.EndLine, nil +} + +// AddEndLine adds i to the "end_line" field. +func (m *AgentTraceRangeMutation) AddEndLine(i int) { + if m.addend_line != nil { + *m.addend_line += i + } else { + m.addend_line = &i + } +} + +// AddedEndLine returns the value that was added to the "end_line" field in this mutation. +func (m *AgentTraceRangeMutation) AddedEndLine() (r int, exists bool) { + v := m.addend_line + if v == nil { + return + } + return *v, true +} + +// ResetEndLine resets all changes to the "end_line" field. +func (m *AgentTraceRangeMutation) ResetEndLine() { + m.end_line = nil + m.addend_line = nil +} + +// SetContentHash sets the "content_hash" field. +func (m *AgentTraceRangeMutation) SetContentHash(s string) { + m.content_hash = &s +} + +// ContentHash returns the value of the "content_hash" field in the mutation. +func (m *AgentTraceRangeMutation) ContentHash() (r string, exists bool) { + v := m.content_hash + if v == nil { + return + } + return *v, true +} + +// OldContentHash returns the old "content_hash" field's value of the AgentTraceRange entity. +// If the AgentTraceRange 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 *AgentTraceRangeMutation) OldContentHash(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldContentHash is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldContentHash requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldContentHash: %w", err) + } + return oldValue.ContentHash, nil +} + +// ClearContentHash clears the value of the "content_hash" field. +func (m *AgentTraceRangeMutation) ClearContentHash() { + m.content_hash = nil + m.clearedFields[agenttracerange.FieldContentHash] = struct{}{} +} + +// ContentHashCleared returns if the "content_hash" field was cleared in this mutation. +func (m *AgentTraceRangeMutation) ContentHashCleared() bool { + _, ok := m.clearedFields[agenttracerange.FieldContentHash] + return ok +} + +// ResetContentHash resets all changes to the "content_hash" field. +func (m *AgentTraceRangeMutation) ResetContentHash() { + m.content_hash = nil + delete(m.clearedFields, agenttracerange.FieldContentHash) +} + +// SetContributorType sets the "contributor_type" field. +func (m *AgentTraceRangeMutation) SetContributorType(s string) { + m.contributor_type = &s +} + +// ContributorType returns the value of the "contributor_type" field in the mutation. +func (m *AgentTraceRangeMutation) ContributorType() (r string, exists bool) { + v := m.contributor_type + if v == nil { + return + } + return *v, true +} + +// OldContributorType returns the old "contributor_type" field's value of the AgentTraceRange entity. +// If the AgentTraceRange 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 *AgentTraceRangeMutation) OldContributorType(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldContributorType is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldContributorType requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldContributorType: %w", err) + } + return oldValue.ContributorType, nil +} + +// ClearContributorType clears the value of the "contributor_type" field. +func (m *AgentTraceRangeMutation) ClearContributorType() { + m.contributor_type = nil + m.clearedFields[agenttracerange.FieldContributorType] = struct{}{} +} + +// ContributorTypeCleared returns if the "contributor_type" field was cleared in this mutation. +func (m *AgentTraceRangeMutation) ContributorTypeCleared() bool { + _, ok := m.clearedFields[agenttracerange.FieldContributorType] + return ok +} + +// ResetContributorType resets all changes to the "contributor_type" field. +func (m *AgentTraceRangeMutation) ResetContributorType() { + m.contributor_type = nil + delete(m.clearedFields, agenttracerange.FieldContributorType) +} + +// SetContributorModelID sets the "contributor_model_id" field. +func (m *AgentTraceRangeMutation) SetContributorModelID(s string) { + m.contributor_model_id = &s +} + +// ContributorModelID returns the value of the "contributor_model_id" field in the mutation. +func (m *AgentTraceRangeMutation) ContributorModelID() (r string, exists bool) { + v := m.contributor_model_id + if v == nil { + return + } + return *v, true +} + +// OldContributorModelID returns the old "contributor_model_id" field's value of the AgentTraceRange entity. +// If the AgentTraceRange 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 *AgentTraceRangeMutation) OldContributorModelID(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldContributorModelID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldContributorModelID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldContributorModelID: %w", err) + } + return oldValue.ContributorModelID, nil +} + +// ClearContributorModelID clears the value of the "contributor_model_id" field. +func (m *AgentTraceRangeMutation) ClearContributorModelID() { + m.contributor_model_id = nil + m.clearedFields[agenttracerange.FieldContributorModelID] = struct{}{} +} + +// ContributorModelIDCleared returns if the "contributor_model_id" field was cleared in this mutation. +func (m *AgentTraceRangeMutation) ContributorModelIDCleared() bool { + _, ok := m.clearedFields[agenttracerange.FieldContributorModelID] + return ok +} + +// ResetContributorModelID resets all changes to the "contributor_model_id" field. +func (m *AgentTraceRangeMutation) ResetContributorModelID() { + m.contributor_model_id = nil + delete(m.clearedFields, agenttracerange.FieldContributorModelID) +} + +// SetConversationID sets the "conversation" edge to the AgentTraceConversation entity by id. +func (m *AgentTraceRangeMutation) SetConversationID(id int) { + m.conversation = &id +} + +// ClearConversation clears the "conversation" edge to the AgentTraceConversation entity. +func (m *AgentTraceRangeMutation) ClearConversation() { + m.clearedconversation = true +} + +// ConversationCleared reports if the "conversation" edge to the AgentTraceConversation entity was cleared. +func (m *AgentTraceRangeMutation) ConversationCleared() bool { + return m.clearedconversation +} + +// ConversationID returns the "conversation" edge ID in the mutation. +func (m *AgentTraceRangeMutation) ConversationID() (id int, exists bool) { + if m.conversation != nil { + return *m.conversation, true + } + return +} + +// ConversationIDs returns the "conversation" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// ConversationID instead. It exists only for internal usage by the builders. +func (m *AgentTraceRangeMutation) ConversationIDs() (ids []int) { + if id := m.conversation; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetConversation resets all changes to the "conversation" edge. +func (m *AgentTraceRangeMutation) ResetConversation() { + m.conversation = nil + m.clearedconversation = false +} + +// Where appends a list predicates to the AgentTraceRangeMutation builder. +func (m *AgentTraceRangeMutation) Where(ps ...predicate.AgentTraceRange) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the AgentTraceRangeMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *AgentTraceRangeMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.AgentTraceRange, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *AgentTraceRangeMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *AgentTraceRangeMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (AgentTraceRange). +func (m *AgentTraceRangeMutation) 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 *AgentTraceRangeMutation) Fields() []string { + fields := make([]string, 0, 5) + if m.start_line != nil { + fields = append(fields, agenttracerange.FieldStartLine) + } + if m.end_line != nil { + fields = append(fields, agenttracerange.FieldEndLine) + } + if m.content_hash != nil { + fields = append(fields, agenttracerange.FieldContentHash) + } + if m.contributor_type != nil { + fields = append(fields, agenttracerange.FieldContributorType) + } + if m.contributor_model_id != nil { + fields = append(fields, agenttracerange.FieldContributorModelID) + } + 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 *AgentTraceRangeMutation) Field(name string) (ent.Value, bool) { + switch name { + case agenttracerange.FieldStartLine: + return m.StartLine() + case agenttracerange.FieldEndLine: + return m.EndLine() + case agenttracerange.FieldContentHash: + return m.ContentHash() + case agenttracerange.FieldContributorType: + return m.ContributorType() + case agenttracerange.FieldContributorModelID: + return m.ContributorModelID() + } + 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 *AgentTraceRangeMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case agenttracerange.FieldStartLine: + return m.OldStartLine(ctx) + case agenttracerange.FieldEndLine: + return m.OldEndLine(ctx) + case agenttracerange.FieldContentHash: + return m.OldContentHash(ctx) + case agenttracerange.FieldContributorType: + return m.OldContributorType(ctx) + case agenttracerange.FieldContributorModelID: + return m.OldContributorModelID(ctx) + } + return nil, fmt.Errorf("unknown AgentTraceRange 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 *AgentTraceRangeMutation) SetField(name string, value ent.Value) error { + switch name { + case agenttracerange.FieldStartLine: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStartLine(v) + return nil + case agenttracerange.FieldEndLine: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetEndLine(v) + return nil + case agenttracerange.FieldContentHash: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetContentHash(v) + return nil + case agenttracerange.FieldContributorType: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetContributorType(v) + return nil + case agenttracerange.FieldContributorModelID: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetContributorModelID(v) + return nil + } + return fmt.Errorf("unknown AgentTraceRange field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *AgentTraceRangeMutation) AddedFields() []string { + var fields []string + if m.addstart_line != nil { + fields = append(fields, agenttracerange.FieldStartLine) + } + if m.addend_line != nil { + fields = append(fields, agenttracerange.FieldEndLine) + } + 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 *AgentTraceRangeMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case agenttracerange.FieldStartLine: + return m.AddedStartLine() + case agenttracerange.FieldEndLine: + return m.AddedEndLine() + } + 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 *AgentTraceRangeMutation) AddField(name string, value ent.Value) error { + switch name { + case agenttracerange.FieldStartLine: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddStartLine(v) + return nil + case agenttracerange.FieldEndLine: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddEndLine(v) + return nil + } + return fmt.Errorf("unknown AgentTraceRange numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *AgentTraceRangeMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(agenttracerange.FieldContentHash) { + fields = append(fields, agenttracerange.FieldContentHash) + } + if m.FieldCleared(agenttracerange.FieldContributorType) { + fields = append(fields, agenttracerange.FieldContributorType) + } + if m.FieldCleared(agenttracerange.FieldContributorModelID) { + fields = append(fields, agenttracerange.FieldContributorModelID) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *AgentTraceRangeMutation) 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 *AgentTraceRangeMutation) ClearField(name string) error { + switch name { + case agenttracerange.FieldContentHash: + m.ClearContentHash() + return nil + case agenttracerange.FieldContributorType: + m.ClearContributorType() + return nil + case agenttracerange.FieldContributorModelID: + m.ClearContributorModelID() + return nil + } + return fmt.Errorf("unknown AgentTraceRange 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 *AgentTraceRangeMutation) ResetField(name string) error { + switch name { + case agenttracerange.FieldStartLine: + m.ResetStartLine() + return nil + case agenttracerange.FieldEndLine: + m.ResetEndLine() + return nil + case agenttracerange.FieldContentHash: + m.ResetContentHash() + return nil + case agenttracerange.FieldContributorType: + m.ResetContributorType() + return nil + case agenttracerange.FieldContributorModelID: + m.ResetContributorModelID() + return nil + } + return fmt.Errorf("unknown AgentTraceRange field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *AgentTraceRangeMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.conversation != nil { + edges = append(edges, agenttracerange.EdgeConversation) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *AgentTraceRangeMutation) AddedIDs(name string) []ent.Value { + switch name { + case agenttracerange.EdgeConversation: + if id := m.conversation; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *AgentTraceRangeMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *AgentTraceRangeMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *AgentTraceRangeMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedconversation { + edges = append(edges, agenttracerange.EdgeConversation) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *AgentTraceRangeMutation) EdgeCleared(name string) bool { + switch name { + case agenttracerange.EdgeConversation: + return m.clearedconversation + } + 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 *AgentTraceRangeMutation) ClearEdge(name string) error { + switch name { + case agenttracerange.EdgeConversation: + m.ClearConversation() + return nil + } + return fmt.Errorf("unknown AgentTraceRange 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 *AgentTraceRangeMutation) ResetEdge(name string) error { + switch name { + case agenttracerange.EdgeConversation: + m.ResetConversation() + return nil + } + return fmt.Errorf("unknown AgentTraceRange edge %s", name) +} + // NodeMutation represents an operation that mutates the Node nodes in the graph. type NodeMutation struct { config diff --git a/pkg/storage/ent/node.go b/pkg/storage/ent/node.go index df9737b..cd61298 100644 --- a/pkg/storage/ent/node.go +++ b/pkg/storage/ent/node.go @@ -10,7 +10,6 @@ import ( "entgo.io/ent" "entgo.io/ent/dialect/sql" - "github.com/papercomputeco/tapes/pkg/storage/ent/node" ) diff --git a/pkg/storage/ent/node/where.go b/pkg/storage/ent/node/where.go index fa238ef..adfb314 100644 --- a/pkg/storage/ent/node/where.go +++ b/pkg/storage/ent/node/where.go @@ -7,7 +7,6 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" - "github.com/papercomputeco/tapes/pkg/storage/ent/predicate" ) diff --git a/pkg/storage/ent/node_create.go b/pkg/storage/ent/node_create.go index 47392c3..d04755d 100644 --- a/pkg/storage/ent/node_create.go +++ b/pkg/storage/ent/node_create.go @@ -10,7 +10,6 @@ import ( "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" - "github.com/papercomputeco/tapes/pkg/storage/ent/node" ) diff --git a/pkg/storage/ent/node_delete.go b/pkg/storage/ent/node_delete.go index a703eb4..981000f 100644 --- a/pkg/storage/ent/node_delete.go +++ b/pkg/storage/ent/node_delete.go @@ -8,7 +8,6 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" - "github.com/papercomputeco/tapes/pkg/storage/ent/node" "github.com/papercomputeco/tapes/pkg/storage/ent/predicate" ) diff --git a/pkg/storage/ent/node_query.go b/pkg/storage/ent/node_query.go index 1a86788..f6611ab 100644 --- a/pkg/storage/ent/node_query.go +++ b/pkg/storage/ent/node_query.go @@ -12,7 +12,6 @@ import ( "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" - "github.com/papercomputeco/tapes/pkg/storage/ent/node" "github.com/papercomputeco/tapes/pkg/storage/ent/predicate" ) diff --git a/pkg/storage/ent/node_update.go b/pkg/storage/ent/node_update.go index a799285..423719b 100644 --- a/pkg/storage/ent/node_update.go +++ b/pkg/storage/ent/node_update.go @@ -11,7 +11,6 @@ import ( "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/dialect/sql/sqljson" "entgo.io/ent/schema/field" - "github.com/papercomputeco/tapes/pkg/storage/ent/node" "github.com/papercomputeco/tapes/pkg/storage/ent/predicate" ) diff --git a/pkg/storage/ent/predicate/predicate.go b/pkg/storage/ent/predicate/predicate.go index bdd2503..33e212a 100644 --- a/pkg/storage/ent/predicate/predicate.go +++ b/pkg/storage/ent/predicate/predicate.go @@ -6,5 +6,17 @@ import ( "entgo.io/ent/dialect/sql" ) +// AgentTrace is the predicate function for agenttrace builders. +type AgentTrace func(*sql.Selector) + +// AgentTraceConversation is the predicate function for agenttraceconversation builders. +type AgentTraceConversation func(*sql.Selector) + +// AgentTraceFile is the predicate function for agenttracefile builders. +type AgentTraceFile func(*sql.Selector) + +// AgentTraceRange is the predicate function for agenttracerange builders. +type AgentTraceRange func(*sql.Selector) + // Node is the predicate function for node builders. type Node func(*sql.Selector) diff --git a/pkg/storage/ent/runtime.go b/pkg/storage/ent/runtime.go index b73213a..52e388f 100644 --- a/pkg/storage/ent/runtime.go +++ b/pkg/storage/ent/runtime.go @@ -5,6 +5,8 @@ package ent import ( "time" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttrace" + "github.com/papercomputeco/tapes/pkg/storage/ent/agenttracefile" "github.com/papercomputeco/tapes/pkg/storage/ent/node" "github.com/papercomputeco/tapes/pkg/storage/ent/schema" ) @@ -13,6 +15,30 @@ import ( // (default values, validators, hooks and policies) and stitches it // to their package variables. func init() { + agenttraceFields := schema.AgentTrace{}.Fields() + _ = agenttraceFields + // agenttraceDescVersion is the schema descriptor for version field. + agenttraceDescVersion := agenttraceFields[1].Descriptor() + // agenttrace.VersionValidator is a validator for the "version" field. It is called by the builders before save. + agenttrace.VersionValidator = agenttraceDescVersion.Validators[0].(func(string) error) + // agenttraceDescTimestamp is the schema descriptor for timestamp field. + agenttraceDescTimestamp := agenttraceFields[2].Descriptor() + // agenttrace.TimestampValidator is a validator for the "timestamp" field. It is called by the builders before save. + agenttrace.TimestampValidator = agenttraceDescTimestamp.Validators[0].(func(string) error) + // agenttraceDescCreatedAt is the schema descriptor for created_at field. + agenttraceDescCreatedAt := agenttraceFields[8].Descriptor() + // agenttrace.DefaultCreatedAt holds the default value on creation for the created_at field. + agenttrace.DefaultCreatedAt = agenttraceDescCreatedAt.Default.(func() time.Time) + // agenttraceDescID is the schema descriptor for id field. + agenttraceDescID := agenttraceFields[0].Descriptor() + // agenttrace.IDValidator is a validator for the "id" field. It is called by the builders before save. + agenttrace.IDValidator = agenttraceDescID.Validators[0].(func(string) error) + agenttracefileFields := schema.AgentTraceFile{}.Fields() + _ = agenttracefileFields + // agenttracefileDescPath is the schema descriptor for path field. + agenttracefileDescPath := agenttracefileFields[0].Descriptor() + // agenttracefile.PathValidator is a validator for the "path" field. It is called by the builders before save. + agenttracefile.PathValidator = agenttracefileDescPath.Validators[0].(func(string) error) nodeFields := schema.Node{}.Fields() _ = nodeFields // nodeDescCreatedAt is the schema descriptor for created_at field. diff --git a/pkg/storage/ent/schema/agent_trace.go b/pkg/storage/ent/schema/agent_trace.go new file mode 100644 index 0000000..ed41d45 --- /dev/null +++ b/pkg/storage/ent/schema/agent_trace.go @@ -0,0 +1,69 @@ +package schema + +import ( + "time" + + "entgo.io/ent" + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" +) + +// AgentTrace holds the schema definition for the AgentTrace entity. +// This is the root record for an agent trace. +type AgentTrace struct { + ent.Schema +} + +// Fields of the AgentTrace. +func (AgentTrace) Fields() []ent.Field { + return []ent.Field{ + field.String("id"). + Unique(). + Immutable(). + NotEmpty(), + + field.String("version"). + NotEmpty(), + + field.String("timestamp"). + NotEmpty(), + + field.String("vcs_type"). + Optional(), + + field.String("vcs_revision"). + Optional(), + + field.String("tool_name"). + Optional(), + + field.String("tool_version"). + Optional(), + + field.JSON("metadata", map[string]any{}). + Optional(), + + field.Time("created_at"). + Default(time.Now). + Immutable(). + Annotations(entsql.Default("CURRENT_TIMESTAMP")), + } +} + +// Indexes of the AgentTrace. +func (AgentTrace) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("vcs_revision"), + index.Fields("tool_name"), + index.Fields("timestamp"), + } +} + +// Edges of the AgentTrace. +func (AgentTrace) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("files", AgentTraceFile.Type), + } +} diff --git a/pkg/storage/ent/schema/agent_trace_conversation.go b/pkg/storage/ent/schema/agent_trace_conversation.go new file mode 100644 index 0000000..25531a7 --- /dev/null +++ b/pkg/storage/ent/schema/agent_trace_conversation.go @@ -0,0 +1,50 @@ +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" +) + +// AgentTraceConversation holds the schema definition for the AgentTraceConversation entity. +type AgentTraceConversation struct { + ent.Schema +} + +// Fields of the AgentTraceConversation. +func (AgentTraceConversation) Fields() []ent.Field { + return []ent.Field{ + field.String("url"). + Optional(), + + field.String("contributor_type"). + Optional(), + + field.String("contributor_model_id"). + Optional(), + + field.JSON("related", []map[string]any{}). + Optional(), + } +} + +// Indexes of the AgentTraceConversation. +func (AgentTraceConversation) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("contributor_type"), + index.Fields("contributor_model_id"), + } +} + +// Edges of the AgentTraceConversation. +func (AgentTraceConversation) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("file", AgentTraceFile.Type). + Ref("conversations"). + Unique(). + Required(), + + edge.To("ranges", AgentTraceRange.Type), + } +} diff --git a/pkg/storage/ent/schema/agent_trace_file.go b/pkg/storage/ent/schema/agent_trace_file.go new file mode 100644 index 0000000..49c4da5 --- /dev/null +++ b/pkg/storage/ent/schema/agent_trace_file.go @@ -0,0 +1,40 @@ +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" +) + +// AgentTraceFile holds the schema definition for the AgentTraceFile entity. +type AgentTraceFile struct { + ent.Schema +} + +// Fields of the AgentTraceFile. +func (AgentTraceFile) Fields() []ent.Field { + return []ent.Field{ + field.String("path"). + NotEmpty(), + } +} + +// Indexes of the AgentTraceFile. +func (AgentTraceFile) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("path"), + } +} + +// Edges of the AgentTraceFile. +func (AgentTraceFile) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("trace", AgentTrace.Type). + Ref("files"). + Unique(). + Required(), + + edge.To("conversations", AgentTraceConversation.Type), + } +} diff --git a/pkg/storage/ent/schema/agent_trace_range.go b/pkg/storage/ent/schema/agent_trace_range.go new file mode 100644 index 0000000..11952f2 --- /dev/null +++ b/pkg/storage/ent/schema/agent_trace_range.go @@ -0,0 +1,48 @@ +package schema + +import ( + "entgo.io/ent" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "entgo.io/ent/schema/index" +) + +// AgentTraceRange holds the schema definition for the AgentTraceRange entity. +type AgentTraceRange struct { + ent.Schema +} + +// Fields of the AgentTraceRange. +func (AgentTraceRange) Fields() []ent.Field { + return []ent.Field{ + field.Int("start_line"), + + field.Int("end_line"), + + field.String("content_hash"). + Optional(), + + field.String("contributor_type"). + Optional(), + + field.String("contributor_model_id"). + Optional(), + } +} + +// Indexes of the AgentTraceRange. +func (AgentTraceRange) Indexes() []ent.Index { + return []ent.Index{ + index.Fields("start_line", "end_line"), + } +} + +// Edges of the AgentTraceRange. +func (AgentTraceRange) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("conversation", AgentTraceConversation.Type). + Ref("ranges"). + Unique(). + Required(), + } +} diff --git a/pkg/storage/ent/tx.go b/pkg/storage/ent/tx.go index 27b9ee6..c1f7dae 100644 --- a/pkg/storage/ent/tx.go +++ b/pkg/storage/ent/tx.go @@ -12,6 +12,14 @@ import ( // Tx is a transactional client that is created by calling Client.Tx(). type Tx struct { config + // AgentTrace is the client for interacting with the AgentTrace builders. + AgentTrace *AgentTraceClient + // AgentTraceConversation is the client for interacting with the AgentTraceConversation builders. + AgentTraceConversation *AgentTraceConversationClient + // AgentTraceFile is the client for interacting with the AgentTraceFile builders. + AgentTraceFile *AgentTraceFileClient + // AgentTraceRange is the client for interacting with the AgentTraceRange builders. + AgentTraceRange *AgentTraceRangeClient // Node is the client for interacting with the Node builders. Node *NodeClient @@ -145,6 +153,10 @@ func (tx *Tx) Client() *Client { } func (tx *Tx) init() { + tx.AgentTrace = NewAgentTraceClient(tx.config) + tx.AgentTraceConversation = NewAgentTraceConversationClient(tx.config) + tx.AgentTraceFile = NewAgentTraceFileClient(tx.config) + tx.AgentTraceRange = NewAgentTraceRangeClient(tx.config) tx.Node = NewNodeClient(tx.config) } @@ -155,7 +167,7 @@ func (tx *Tx) init() { // of them in order to commit or rollback the transaction. // // If a closed transaction is embedded in one of the generated entities, and the entity -// applies a query, for example: Node.QueryXXX(), the query will be executed +// applies a query, for example: AgentTrace.QueryXXX(), the query will be executed // through the driver which created this transaction. // // Note that txDriver is not goroutine safe. diff --git a/pkg/storage/inmemory/agent_trace_store.go b/pkg/storage/inmemory/agent_trace_store.go new file mode 100644 index 0000000..fd6cf7d --- /dev/null +++ b/pkg/storage/inmemory/agent_trace_store.go @@ -0,0 +1,113 @@ +package inmemory + +import ( + "context" + "errors" + "fmt" + "strings" + "sync" + + "github.com/papercomputeco/tapes/pkg/agenttrace" + "github.com/papercomputeco/tapes/pkg/storage" +) + +// AgentTraceStore implements storage.AgentTraceStore using an in-memory map. +type AgentTraceStore struct { + mu sync.RWMutex + traces map[string]*agenttrace.AgentTrace +} + +// NewAgentTraceStore creates a new in-memory agent trace store. +func NewAgentTraceStore() *AgentTraceStore { + return &AgentTraceStore{ + traces: make(map[string]*agenttrace.AgentTrace), + } +} + +// CreateAgentTrace stores an agent trace. +func (s *AgentTraceStore) CreateAgentTrace(_ context.Context, trace *agenttrace.AgentTrace) (*agenttrace.AgentTrace, error) { + if trace == nil { + return nil, errors.New("cannot store nil agent trace") + } + + s.mu.Lock() + defer s.mu.Unlock() + + s.traces[trace.ID] = trace + return trace, nil +} + +// GetAgentTrace retrieves an agent trace by ID. +func (s *AgentTraceStore) GetAgentTrace(_ context.Context, id string) (*agenttrace.AgentTrace, error) { + s.mu.RLock() + defer s.mu.RUnlock() + + trace, ok := s.traces[id] + if !ok { + return nil, fmt.Errorf("agent trace not found: %s", id) + } + return trace, nil +} + +// QueryAgentTraces queries agent traces with filtering. +func (s *AgentTraceStore) QueryAgentTraces(_ context.Context, query storage.AgentTraceQuery) ([]*agenttrace.AgentTrace, error) { + s.mu.RLock() + defer s.mu.RUnlock() + + var results []*agenttrace.AgentTrace + + for _, trace := range s.traces { + if !matchesQuery(trace, query) { + continue + } + results = append(results, trace) + } + + // Apply offset + if query.Offset > 0 && query.Offset < len(results) { + results = results[query.Offset:] + } else if query.Offset >= len(results) { + return []*agenttrace.AgentTrace{}, nil + } + + // Apply limit + if query.Limit > 0 && query.Limit < len(results) { + results = results[:query.Limit] + } + + return results, nil +} + +// Close is a no-op for the in-memory store. +func (s *AgentTraceStore) Close() error { + return nil +} + +func matchesQuery(trace *agenttrace.AgentTrace, query storage.AgentTraceQuery) bool { + if query.FilePath != "" { + found := false + for _, f := range trace.Files { + if strings.EqualFold(f.Path, query.FilePath) { + found = true + break + } + } + if !found { + return false + } + } + + if query.Revision != "" { + if trace.VCS == nil || trace.VCS.Revision != query.Revision { + return false + } + } + + if query.ToolName != "" { + if trace.Tool == nil || trace.Tool.Name != query.ToolName { + return false + } + } + + return true +} diff --git a/pkg/storage/sqlite/sqlite.go b/pkg/storage/sqlite/sqlite.go index 16a528f..ba3cbbf 100644 --- a/pkg/storage/sqlite/sqlite.go +++ b/pkg/storage/sqlite/sqlite.go @@ -17,6 +17,9 @@ import ( // Driver implements storage.Driver using SQLite via the ent driver type Driver struct { *entdriver.EntDriver + + // AgentTraceStore provides agent trace storage using the same ent client. + AgentTraceStore *entdriver.EntAgentTraceDriver } // NewDriver creates a new SQLite-backed storer. @@ -49,5 +52,8 @@ func NewDriver(ctx context.Context, dbPath string) (*Driver, error) { EntDriver: &entdriver.EntDriver{ Client: client, }, + AgentTraceStore: &entdriver.EntAgentTraceDriver{ + Client: client, + }, }, nil }