From 7b898266a940affaec0c4322ab1e3611ee9542a9 Mon Sep 17 00:00:00 2001 From: Jannik Clausen <12862103+masseelch@users.noreply.github.com> Date: Thu, 16 Jan 2025 16:57:13 +0100 Subject: [PATCH] entgql: support global id feature from ent (#611) --- entgql/internal/todo/ent/billproduct_query.go | 5 +- entgql/internal/todo/ent/category_query.go | 5 +- entgql/internal/todo/ent/ent.go | 2 +- entgql/internal/todo/ent/friendship_query.go | 5 +- entgql/internal/todo/ent/group_query.go | 5 +- entgql/internal/todo/ent/onetomany_query.go | 5 +- entgql/internal/todo/ent/project_query.go | 5 +- entgql/internal/todo/ent/runtime/runtime.go | 4 +- entgql/internal/todo/ent/todo_query.go | 5 +- entgql/internal/todo/ent/user_query.go | 5 +- entgql/internal/todo/ent/verysecret_query.go | 5 +- entgql/internal/todo/ent/workspace_query.go | 5 +- entgql/internal/todofed/ent/ent.go | 2 +- .../internal/todofed/ent/runtime/runtime.go | 4 +- entgql/internal/todoglobalid/ent.graphql | 1452 ++ entgql/internal/todoglobalid/ent.resolvers.go | 106 + .../internal/todoglobalid/ent/billproduct.go | 139 + .../ent/billproduct/billproduct.go | 77 + .../todoglobalid/ent/billproduct/where.go | 267 + .../todoglobalid/ent/billproduct_create.go | 223 + .../todoglobalid/ent/billproduct_delete.go | 102 + .../todoglobalid/ent/billproduct_query.go | 570 + .../todoglobalid/ent/billproduct_update.go | 327 + entgql/internal/todoglobalid/ent/category.go | 291 + .../todoglobalid/ent/category/category.go | 215 + .../todoglobalid/ent/category/where.go | 422 + .../todoglobalid/ent/category_create.go | 363 + .../todoglobalid/ent/category_delete.go | 102 + .../todoglobalid/ent/category_query.go | 798 + .../todoglobalid/ent/category_update.go | 911 + entgql/internal/todoglobalid/ent/client.go | 1876 ++ entgql/internal/todoglobalid/ent/ent.go | 640 + entgql/internal/todoglobalid/ent/entc.go | 58 + .../todoglobalid/ent/enttest/enttest.go | 98 + .../internal/todoglobalid/ent/friendship.go | 189 + .../todoglobalid/ent/friendship/friendship.go | 131 + .../todoglobalid/ent/friendship/where.go | 226 + .../todoglobalid/ent/friendship_create.go | 285 + .../todoglobalid/ent/friendship_delete.go | 102 + .../todoglobalid/ent/friendship_query.go | 723 + .../todoglobalid/ent/friendship_update.go | 485 + .../todoglobalid/ent/gql_collection.go | 1711 ++ entgql/internal/todoglobalid/ent/gql_edge.go | 241 + .../todoglobalid/ent/gql_mutation_input.go | 432 + entgql/internal/todoglobalid/ent/gql_node.go | 472 + .../todoglobalid/ent/gql_node_descriptor.go | 558 + .../todoglobalid/ent/gql_pagination.go | 2921 +++ .../todoglobalid/ent/gql_transaction.go | 44 + .../todoglobalid/ent/gql_where_input.go | 2444 ++ entgql/internal/todoglobalid/ent/group.go | 171 + .../internal/todoglobalid/ent/group/group.go | 101 + .../internal/todoglobalid/ent/group/where.go | 176 + .../internal/todoglobalid/ent/group_create.go | 247 + .../internal/todoglobalid/ent/group_delete.go | 102 + .../internal/todoglobalid/ent/group_query.go | 702 + .../internal/todoglobalid/ent/group_update.go | 402 + entgql/internal/todoglobalid/ent/hook/hook.go | 321 + .../todoglobalid/ent/internal/globalid.go | 19 + .../todoglobalid/ent/migrate/migrate.go | 78 + .../todoglobalid/ent/migrate/schema.go | 327 + entgql/internal/todoglobalid/ent/mutation.go | 6245 +++++ entgql/internal/todoglobalid/ent/onetomany.go | 211 + .../todoglobalid/ent/onetomany/onetomany.go | 130 + .../todoglobalid/ent/onetomany/where.go | 314 + .../todoglobalid/ent/onetomany_create.go | 287 + .../todoglobalid/ent/onetomany_delete.go | 102 + .../todoglobalid/ent/onetomany_query.go | 744 + .../todoglobalid/ent/onetomany_update.go | 599 + .../todoglobalid/ent/predicate/predicate.go | 51 + entgql/internal/todoglobalid/ent/project.go | 159 + .../todoglobalid/ent/project/project.go | 84 + .../todoglobalid/ent/project/where.go | 106 + .../todoglobalid/ent/project_create.go | 215 + .../todoglobalid/ent/project_delete.go | 102 + .../todoglobalid/ent/project_query.go | 650 + .../todoglobalid/ent/project_update.go | 368 + entgql/internal/todoglobalid/ent/runtime.go | 88 + .../todoglobalid/ent/runtime/runtime.go | 24 + .../ent/schema/annotation/has_permissions.go | 42 + .../todoglobalid/ent/schema/billproduct.go | 43 + .../todoglobalid/ent/schema/category.go | 105 + .../ent/schema/customstruct/custom.go | 19 + .../ent/schema/durationgql/durationgql.go | 48 + .../todoglobalid/ent/schema/friendship.go | 64 + .../internal/todoglobalid/ent/schema/group.go | 59 + .../internal/todoglobalid/ent/schema/mixin.go | 69 + .../todoglobalid/ent/schema/onetomany.go | 63 + .../todoglobalid/ent/schema/project.go | 36 + .../ent/schema/schematype/schematype.go | 45 + .../internal/todoglobalid/ent/schema/todo.go | 132 + .../internal/todoglobalid/ent/schema/user.go | 72 + .../todoglobalid/ent/schema/verysecret.go | 40 + .../todoglobalid/ent/schema/workspace.go | 42 + entgql/internal/todoglobalid/ent/todo.go | 369 + entgql/internal/todoglobalid/ent/todo/todo.go | 278 + .../internal/todoglobalid/ent/todo/where.go | 522 + .../internal/todoglobalid/ent/todo_create.go | 484 + .../internal/todoglobalid/ent/todo_delete.go | 102 + .../internal/todoglobalid/ent/todo_query.go | 903 + .../internal/todoglobalid/ent/todo_update.go | 986 + entgql/internal/todoglobalid/ent/tx.go | 251 + entgql/internal/todoglobalid/ent/user.go | 306 + entgql/internal/todoglobalid/ent/user/user.go | 184 + .../internal/todoglobalid/ent/user/where.go | 358 + .../internal/todoglobalid/ent/user_create.go | 381 + .../internal/todoglobalid/ent/user_delete.go | 102 + .../internal/todoglobalid/ent/user_query.go | 924 + .../internal/todoglobalid/ent/user_update.go | 892 + .../internal/todoglobalid/ent/verysecret.go | 117 + .../todoglobalid/ent/verysecret/verysecret.go | 61 + .../todoglobalid/ent/verysecret/where.go | 152 + .../todoglobalid/ent/verysecret_create.go | 197 + .../todoglobalid/ent/verysecret_delete.go | 102 + .../todoglobalid/ent/verysecret_query.go | 570 + .../todoglobalid/ent/verysecret_update.go | 239 + entgql/internal/todoglobalid/ent/workspace.go | 117 + .../todoglobalid/ent/workspace/where.go | 152 + .../todoglobalid/ent/workspace/workspace.go | 61 + .../todoglobalid/ent/workspace_create.go | 197 + .../todoglobalid/ent/workspace_delete.go | 102 + .../todoglobalid/ent/workspace_query.go | 570 + .../todoglobalid/ent/workspace_update.go | 239 + entgql/internal/todoglobalid/gen.go | 19 + entgql/internal/todoglobalid/gen_test.go | 54 + entgql/internal/todoglobalid/generated.go | 19423 ++++++++++++++++ entgql/internal/todoglobalid/gqlgen.yml | 57 + .../internal/todoglobalid/has_permission.go | 33 + entgql/internal/todoglobalid/models_gen.go | 7 + entgql/internal/todoglobalid/resolver.go | 33 + .../schema/annotation/has_permissions.go | 42 + .../todoglobalid/schema/billproduct.go | 43 + .../internal/todoglobalid/schema/category.go | 105 + .../schema/customstruct/custom.go | 19 + .../schema/durationgql/durationgql.go | 48 + .../todoglobalid/schema/friendship.go | 64 + entgql/internal/todoglobalid/schema/group.go | 59 + entgql/internal/todoglobalid/schema/mixin.go | 69 + .../internal/todoglobalid/schema/onetomany.go | 63 + .../internal/todoglobalid/schema/project.go | 36 + .../schema/schematype/schematype.go | 45 + entgql/internal/todoglobalid/schema/todo.go | 132 + entgql/internal/todoglobalid/schema/user.go | 72 + .../todoglobalid/schema/verysecret.go | 40 + .../internal/todoglobalid/schema/workspace.go | 42 + entgql/internal/todoglobalid/server/server.go | 77 + entgql/internal/todoglobalid/todo.graphql | 83 + .../internal/todoglobalid/todo.resolvers.go | 147 + entgql/internal/todoglobalid/todo_test.go | 3094 +++ entgql/internal/todogotype/ent/ent.go | 2 +- .../todogotype/ent/runtime/runtime.go | 4 +- entgql/internal/todopulid/ent/ent.go | 2 +- .../internal/todopulid/ent/runtime/runtime.go | 4 +- entgql/internal/todouuid/ent/ent.go | 2 +- .../internal/todouuid/ent/runtime/runtime.go | 4 +- entgql/template/node.tmpl | 42 +- entoas/internal/cycle/ent.go | 2 +- entoas/internal/cycle/runtime/runtime.go | 4 +- entoas/internal/oastypes/ent.go | 2 +- entoas/internal/oastypes/runtime/runtime.go | 4 +- entoas/internal/pets/ent.go | 2 +- entoas/internal/pets/runtime/runtime.go | 4 +- entoas/internal/simple/ent.go | 2 +- entoas/internal/simple/runtime/runtime.go | 4 +- entproto/Dockerfile | 2 +- entproto/README.md | 6 +- .../protoc-gen-ent/internal/todo/ent/ent.go | 2 +- .../internal/todo/ent/runtime/runtime.go | 4 +- entproto/internal/altdir/ent/ent.go | 2 +- .../internal/altdir/ent/runtime/runtime.go | 4 +- entproto/internal/bare/ent/ent.go | 2 +- entproto/internal/bare/ent/runtime/runtime.go | 4 +- entproto/internal/entprototest/ent/ent.go | 2 +- .../entprototest/ent/runtime/runtime.go | 4 +- entproto/internal/todo/ent/ent.go | 2 +- entproto/internal/todo/ent/runtime/runtime.go | 4 +- go.mod | 4 +- go.sum | 8 +- schemast/internal/loadtest/ent/ent.go | 2 +- .../internal/loadtest/ent/runtime/runtime.go | 4 +- schemast/internal/mutatetest/ent/ent.go | 2 +- .../mutatetest/ent/runtime/runtime.go | 4 +- schemast/internal/printtest/ent/ent.go | 2 +- .../internal/printtest/ent/runtime/runtime.go | 4 +- 183 files changed, 67957 insertions(+), 86 deletions(-) create mode 100644 entgql/internal/todoglobalid/ent.graphql create mode 100644 entgql/internal/todoglobalid/ent.resolvers.go create mode 100644 entgql/internal/todoglobalid/ent/billproduct.go create mode 100644 entgql/internal/todoglobalid/ent/billproduct/billproduct.go create mode 100644 entgql/internal/todoglobalid/ent/billproduct/where.go create mode 100644 entgql/internal/todoglobalid/ent/billproduct_create.go create mode 100644 entgql/internal/todoglobalid/ent/billproduct_delete.go create mode 100644 entgql/internal/todoglobalid/ent/billproduct_query.go create mode 100644 entgql/internal/todoglobalid/ent/billproduct_update.go create mode 100644 entgql/internal/todoglobalid/ent/category.go create mode 100644 entgql/internal/todoglobalid/ent/category/category.go create mode 100644 entgql/internal/todoglobalid/ent/category/where.go create mode 100644 entgql/internal/todoglobalid/ent/category_create.go create mode 100644 entgql/internal/todoglobalid/ent/category_delete.go create mode 100644 entgql/internal/todoglobalid/ent/category_query.go create mode 100644 entgql/internal/todoglobalid/ent/category_update.go create mode 100644 entgql/internal/todoglobalid/ent/client.go create mode 100644 entgql/internal/todoglobalid/ent/ent.go create mode 100644 entgql/internal/todoglobalid/ent/entc.go create mode 100644 entgql/internal/todoglobalid/ent/enttest/enttest.go create mode 100644 entgql/internal/todoglobalid/ent/friendship.go create mode 100644 entgql/internal/todoglobalid/ent/friendship/friendship.go create mode 100644 entgql/internal/todoglobalid/ent/friendship/where.go create mode 100644 entgql/internal/todoglobalid/ent/friendship_create.go create mode 100644 entgql/internal/todoglobalid/ent/friendship_delete.go create mode 100644 entgql/internal/todoglobalid/ent/friendship_query.go create mode 100644 entgql/internal/todoglobalid/ent/friendship_update.go create mode 100644 entgql/internal/todoglobalid/ent/gql_collection.go create mode 100644 entgql/internal/todoglobalid/ent/gql_edge.go create mode 100644 entgql/internal/todoglobalid/ent/gql_mutation_input.go create mode 100644 entgql/internal/todoglobalid/ent/gql_node.go create mode 100644 entgql/internal/todoglobalid/ent/gql_node_descriptor.go create mode 100644 entgql/internal/todoglobalid/ent/gql_pagination.go create mode 100644 entgql/internal/todoglobalid/ent/gql_transaction.go create mode 100644 entgql/internal/todoglobalid/ent/gql_where_input.go create mode 100644 entgql/internal/todoglobalid/ent/group.go create mode 100644 entgql/internal/todoglobalid/ent/group/group.go create mode 100644 entgql/internal/todoglobalid/ent/group/where.go create mode 100644 entgql/internal/todoglobalid/ent/group_create.go create mode 100644 entgql/internal/todoglobalid/ent/group_delete.go create mode 100644 entgql/internal/todoglobalid/ent/group_query.go create mode 100644 entgql/internal/todoglobalid/ent/group_update.go create mode 100644 entgql/internal/todoglobalid/ent/hook/hook.go create mode 100644 entgql/internal/todoglobalid/ent/internal/globalid.go create mode 100644 entgql/internal/todoglobalid/ent/migrate/migrate.go create mode 100644 entgql/internal/todoglobalid/ent/migrate/schema.go create mode 100644 entgql/internal/todoglobalid/ent/mutation.go create mode 100644 entgql/internal/todoglobalid/ent/onetomany.go create mode 100644 entgql/internal/todoglobalid/ent/onetomany/onetomany.go create mode 100644 entgql/internal/todoglobalid/ent/onetomany/where.go create mode 100644 entgql/internal/todoglobalid/ent/onetomany_create.go create mode 100644 entgql/internal/todoglobalid/ent/onetomany_delete.go create mode 100644 entgql/internal/todoglobalid/ent/onetomany_query.go create mode 100644 entgql/internal/todoglobalid/ent/onetomany_update.go create mode 100644 entgql/internal/todoglobalid/ent/predicate/predicate.go create mode 100644 entgql/internal/todoglobalid/ent/project.go create mode 100644 entgql/internal/todoglobalid/ent/project/project.go create mode 100644 entgql/internal/todoglobalid/ent/project/where.go create mode 100644 entgql/internal/todoglobalid/ent/project_create.go create mode 100644 entgql/internal/todoglobalid/ent/project_delete.go create mode 100644 entgql/internal/todoglobalid/ent/project_query.go create mode 100644 entgql/internal/todoglobalid/ent/project_update.go create mode 100644 entgql/internal/todoglobalid/ent/runtime.go create mode 100644 entgql/internal/todoglobalid/ent/runtime/runtime.go create mode 100644 entgql/internal/todoglobalid/ent/schema/annotation/has_permissions.go create mode 100644 entgql/internal/todoglobalid/ent/schema/billproduct.go create mode 100644 entgql/internal/todoglobalid/ent/schema/category.go create mode 100644 entgql/internal/todoglobalid/ent/schema/customstruct/custom.go create mode 100644 entgql/internal/todoglobalid/ent/schema/durationgql/durationgql.go create mode 100644 entgql/internal/todoglobalid/ent/schema/friendship.go create mode 100644 entgql/internal/todoglobalid/ent/schema/group.go create mode 100644 entgql/internal/todoglobalid/ent/schema/mixin.go create mode 100644 entgql/internal/todoglobalid/ent/schema/onetomany.go create mode 100644 entgql/internal/todoglobalid/ent/schema/project.go create mode 100644 entgql/internal/todoglobalid/ent/schema/schematype/schematype.go create mode 100644 entgql/internal/todoglobalid/ent/schema/todo.go create mode 100644 entgql/internal/todoglobalid/ent/schema/user.go create mode 100644 entgql/internal/todoglobalid/ent/schema/verysecret.go create mode 100644 entgql/internal/todoglobalid/ent/schema/workspace.go create mode 100644 entgql/internal/todoglobalid/ent/todo.go create mode 100644 entgql/internal/todoglobalid/ent/todo/todo.go create mode 100644 entgql/internal/todoglobalid/ent/todo/where.go create mode 100644 entgql/internal/todoglobalid/ent/todo_create.go create mode 100644 entgql/internal/todoglobalid/ent/todo_delete.go create mode 100644 entgql/internal/todoglobalid/ent/todo_query.go create mode 100644 entgql/internal/todoglobalid/ent/todo_update.go create mode 100644 entgql/internal/todoglobalid/ent/tx.go create mode 100644 entgql/internal/todoglobalid/ent/user.go create mode 100644 entgql/internal/todoglobalid/ent/user/user.go create mode 100644 entgql/internal/todoglobalid/ent/user/where.go create mode 100644 entgql/internal/todoglobalid/ent/user_create.go create mode 100644 entgql/internal/todoglobalid/ent/user_delete.go create mode 100644 entgql/internal/todoglobalid/ent/user_query.go create mode 100644 entgql/internal/todoglobalid/ent/user_update.go create mode 100644 entgql/internal/todoglobalid/ent/verysecret.go create mode 100644 entgql/internal/todoglobalid/ent/verysecret/verysecret.go create mode 100644 entgql/internal/todoglobalid/ent/verysecret/where.go create mode 100644 entgql/internal/todoglobalid/ent/verysecret_create.go create mode 100644 entgql/internal/todoglobalid/ent/verysecret_delete.go create mode 100644 entgql/internal/todoglobalid/ent/verysecret_query.go create mode 100644 entgql/internal/todoglobalid/ent/verysecret_update.go create mode 100644 entgql/internal/todoglobalid/ent/workspace.go create mode 100644 entgql/internal/todoglobalid/ent/workspace/where.go create mode 100644 entgql/internal/todoglobalid/ent/workspace/workspace.go create mode 100644 entgql/internal/todoglobalid/ent/workspace_create.go create mode 100644 entgql/internal/todoglobalid/ent/workspace_delete.go create mode 100644 entgql/internal/todoglobalid/ent/workspace_query.go create mode 100644 entgql/internal/todoglobalid/ent/workspace_update.go create mode 100644 entgql/internal/todoglobalid/gen.go create mode 100644 entgql/internal/todoglobalid/gen_test.go create mode 100644 entgql/internal/todoglobalid/generated.go create mode 100644 entgql/internal/todoglobalid/gqlgen.yml create mode 100644 entgql/internal/todoglobalid/has_permission.go create mode 100644 entgql/internal/todoglobalid/models_gen.go create mode 100644 entgql/internal/todoglobalid/resolver.go create mode 100644 entgql/internal/todoglobalid/schema/annotation/has_permissions.go create mode 100644 entgql/internal/todoglobalid/schema/billproduct.go create mode 100644 entgql/internal/todoglobalid/schema/category.go create mode 100644 entgql/internal/todoglobalid/schema/customstruct/custom.go create mode 100644 entgql/internal/todoglobalid/schema/durationgql/durationgql.go create mode 100644 entgql/internal/todoglobalid/schema/friendship.go create mode 100644 entgql/internal/todoglobalid/schema/group.go create mode 100644 entgql/internal/todoglobalid/schema/mixin.go create mode 100644 entgql/internal/todoglobalid/schema/onetomany.go create mode 100644 entgql/internal/todoglobalid/schema/project.go create mode 100644 entgql/internal/todoglobalid/schema/schematype/schematype.go create mode 100644 entgql/internal/todoglobalid/schema/todo.go create mode 100644 entgql/internal/todoglobalid/schema/user.go create mode 100644 entgql/internal/todoglobalid/schema/verysecret.go create mode 100644 entgql/internal/todoglobalid/schema/workspace.go create mode 100644 entgql/internal/todoglobalid/server/server.go create mode 100644 entgql/internal/todoglobalid/todo.graphql create mode 100644 entgql/internal/todoglobalid/todo.resolvers.go create mode 100644 entgql/internal/todoglobalid/todo_test.go diff --git a/entgql/internal/todo/ent/billproduct_query.go b/entgql/internal/todo/ent/billproduct_query.go index 4f84ee55a..14d85e02f 100644 --- a/entgql/internal/todo/ent/billproduct_query.go +++ b/entgql/internal/todo/ent/billproduct_query.go @@ -267,8 +267,9 @@ func (bpq *BillProductQuery) Clone() *BillProductQuery { inters: append([]Interceptor{}, bpq.inters...), predicates: append([]predicate.BillProduct{}, bpq.predicates...), // clone intermediate query. - sql: bpq.sql.Clone(), - path: bpq.path, + sql: bpq.sql.Clone(), + path: bpq.path, + modifiers: append([]func(*sql.Selector){}, bpq.modifiers...), } } diff --git a/entgql/internal/todo/ent/category_query.go b/entgql/internal/todo/ent/category_query.go index e17c887af..9989f7db6 100644 --- a/entgql/internal/todo/ent/category_query.go +++ b/entgql/internal/todo/ent/category_query.go @@ -319,8 +319,9 @@ func (cq *CategoryQuery) Clone() *CategoryQuery { withTodos: cq.withTodos.Clone(), withSubCategories: cq.withSubCategories.Clone(), // clone intermediate query. - sql: cq.sql.Clone(), - path: cq.path, + sql: cq.sql.Clone(), + path: cq.path, + modifiers: append([]func(*sql.Selector){}, cq.modifiers...), } } diff --git a/entgql/internal/todo/ent/ent.go b/entgql/internal/todo/ent/ent.go index 82cdcdbdd..def4b72c2 100644 --- a/entgql/internal/todo/ent/ent.go +++ b/entgql/internal/todo/ent/ent.go @@ -92,7 +92,7 @@ var ( columnCheck sql.ColumnCheck ) -// columnChecker checks if the column exists in the given table. +// checkColumn checks if the column exists in the given table. func checkColumn(table, column string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ diff --git a/entgql/internal/todo/ent/friendship_query.go b/entgql/internal/todo/ent/friendship_query.go index 74a5e718e..2746733fa 100644 --- a/entgql/internal/todo/ent/friendship_query.go +++ b/entgql/internal/todo/ent/friendship_query.go @@ -316,8 +316,9 @@ func (fq *FriendshipQuery) Clone() *FriendshipQuery { withUser: fq.withUser.Clone(), withFriend: fq.withFriend.Clone(), // clone intermediate query. - sql: fq.sql.Clone(), - path: fq.path, + sql: fq.sql.Clone(), + path: fq.path, + modifiers: append([]func(*sql.Selector){}, fq.modifiers...), } } diff --git a/entgql/internal/todo/ent/group_query.go b/entgql/internal/todo/ent/group_query.go index 48f00d202..6011d8948 100644 --- a/entgql/internal/todo/ent/group_query.go +++ b/entgql/internal/todo/ent/group_query.go @@ -294,8 +294,9 @@ func (gq *GroupQuery) Clone() *GroupQuery { predicates: append([]predicate.Group{}, gq.predicates...), withUsers: gq.withUsers.Clone(), // clone intermediate query. - sql: gq.sql.Clone(), - path: gq.path, + sql: gq.sql.Clone(), + path: gq.path, + modifiers: append([]func(*sql.Selector){}, gq.modifiers...), } } diff --git a/entgql/internal/todo/ent/onetomany_query.go b/entgql/internal/todo/ent/onetomany_query.go index c6d4f66e4..e3510af09 100644 --- a/entgql/internal/todo/ent/onetomany_query.go +++ b/entgql/internal/todo/ent/onetomany_query.go @@ -317,8 +317,9 @@ func (otmq *OneToManyQuery) Clone() *OneToManyQuery { withParent: otmq.withParent.Clone(), withChildren: otmq.withChildren.Clone(), // clone intermediate query. - sql: otmq.sql.Clone(), - path: otmq.path, + sql: otmq.sql.Clone(), + path: otmq.path, + modifiers: append([]func(*sql.Selector){}, otmq.modifiers...), } } diff --git a/entgql/internal/todo/ent/project_query.go b/entgql/internal/todo/ent/project_query.go index 994f6f40a..7bbcd56b7 100644 --- a/entgql/internal/todo/ent/project_query.go +++ b/entgql/internal/todo/ent/project_query.go @@ -294,8 +294,9 @@ func (pq *ProjectQuery) Clone() *ProjectQuery { predicates: append([]predicate.Project{}, pq.predicates...), withTodos: pq.withTodos.Clone(), // clone intermediate query. - sql: pq.sql.Clone(), - path: pq.path, + sql: pq.sql.Clone(), + path: pq.path, + modifiers: append([]func(*sql.Selector){}, pq.modifiers...), } } diff --git a/entgql/internal/todo/ent/runtime/runtime.go b/entgql/internal/todo/ent/runtime/runtime.go index bba24df76..7aa3dd29d 100644 --- a/entgql/internal/todo/ent/runtime/runtime.go +++ b/entgql/internal/todo/ent/runtime/runtime.go @@ -19,6 +19,6 @@ package runtime // The schema-stitching logic is generated in entgo.io/contrib/entgql/internal/todo/ent/runtime.go const ( - Version = "v0.13.2-0.20240717044502-34158f2c129b" // Version of ent codegen. - Sum = "h1:kC+uzL8UFWwtXQ+yY0wUdvVUgPlJPGU3Fx1uttM8PJA=" // Sum of ent codegen. + Version = "v0.14.2-0.20250116103911-b91f8daf0e32" // Version of ent codegen. + Sum = "h1:caGPxY54QfxAj6W9Msw3vgOPDved92NoZjHXYiTRFHI=" // Sum of ent codegen. ) diff --git a/entgql/internal/todo/ent/todo_query.go b/entgql/internal/todo/ent/todo_query.go index 2d028d41d..e5949b047 100644 --- a/entgql/internal/todo/ent/todo_query.go +++ b/entgql/internal/todo/ent/todo_query.go @@ -368,8 +368,9 @@ func (tq *TodoQuery) Clone() *TodoQuery { withCategory: tq.withCategory.Clone(), withSecret: tq.withSecret.Clone(), // clone intermediate query. - sql: tq.sql.Clone(), - path: tq.path, + sql: tq.sql.Clone(), + path: tq.path, + modifiers: append([]func(*sql.Selector){}, tq.modifiers...), } } diff --git a/entgql/internal/todo/ent/user_query.go b/entgql/internal/todo/ent/user_query.go index 62e2b45ce..e3e3be64c 100644 --- a/entgql/internal/todo/ent/user_query.go +++ b/entgql/internal/todo/ent/user_query.go @@ -345,8 +345,9 @@ func (uq *UserQuery) Clone() *UserQuery { withFriends: uq.withFriends.Clone(), withFriendships: uq.withFriendships.Clone(), // clone intermediate query. - sql: uq.sql.Clone(), - path: uq.path, + sql: uq.sql.Clone(), + path: uq.path, + modifiers: append([]func(*sql.Selector){}, uq.modifiers...), } } diff --git a/entgql/internal/todo/ent/verysecret_query.go b/entgql/internal/todo/ent/verysecret_query.go index 8c4d4ed2d..dfbc245d3 100644 --- a/entgql/internal/todo/ent/verysecret_query.go +++ b/entgql/internal/todo/ent/verysecret_query.go @@ -267,8 +267,9 @@ func (vsq *VerySecretQuery) Clone() *VerySecretQuery { inters: append([]Interceptor{}, vsq.inters...), predicates: append([]predicate.VerySecret{}, vsq.predicates...), // clone intermediate query. - sql: vsq.sql.Clone(), - path: vsq.path, + sql: vsq.sql.Clone(), + path: vsq.path, + modifiers: append([]func(*sql.Selector){}, vsq.modifiers...), } } diff --git a/entgql/internal/todo/ent/workspace_query.go b/entgql/internal/todo/ent/workspace_query.go index 879bbe287..776d7689f 100644 --- a/entgql/internal/todo/ent/workspace_query.go +++ b/entgql/internal/todo/ent/workspace_query.go @@ -267,8 +267,9 @@ func (wq *WorkspaceQuery) Clone() *WorkspaceQuery { inters: append([]Interceptor{}, wq.inters...), predicates: append([]predicate.Workspace{}, wq.predicates...), // clone intermediate query. - sql: wq.sql.Clone(), - path: wq.path, + sql: wq.sql.Clone(), + path: wq.path, + modifiers: append([]func(*sql.Selector){}, wq.modifiers...), } } diff --git a/entgql/internal/todofed/ent/ent.go b/entgql/internal/todofed/ent/ent.go index 5e935e2f9..baeb10b6a 100644 --- a/entgql/internal/todofed/ent/ent.go +++ b/entgql/internal/todofed/ent/ent.go @@ -85,7 +85,7 @@ var ( columnCheck sql.ColumnCheck ) -// columnChecker checks if the column exists in the given table. +// checkColumn checks if the column exists in the given table. func checkColumn(table, column string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ diff --git a/entgql/internal/todofed/ent/runtime/runtime.go b/entgql/internal/todofed/ent/runtime/runtime.go index c3b652b68..24f6129af 100644 --- a/entgql/internal/todofed/ent/runtime/runtime.go +++ b/entgql/internal/todofed/ent/runtime/runtime.go @@ -19,6 +19,6 @@ package runtime // The schema-stitching logic is generated in entgo.io/contrib/entgql/internal/todofed/ent/runtime.go const ( - Version = "v0.13.2-0.20240717044502-34158f2c129b" // Version of ent codegen. - Sum = "h1:kC+uzL8UFWwtXQ+yY0wUdvVUgPlJPGU3Fx1uttM8PJA=" // Sum of ent codegen. + Version = "v0.14.2-0.20250116103911-b91f8daf0e32" // Version of ent codegen. + Sum = "h1:caGPxY54QfxAj6W9Msw3vgOPDved92NoZjHXYiTRFHI=" // Sum of ent codegen. ) diff --git a/entgql/internal/todoglobalid/ent.graphql b/entgql/internal/todoglobalid/ent.graphql new file mode 100644 index 000000000..8a75944e5 --- /dev/null +++ b/entgql/internal/todoglobalid/ent.graphql @@ -0,0 +1,1452 @@ +directive @goField(forceResolver: Boolean, name: String, omittable: Boolean) on FIELD_DEFINITION | INPUT_FIELD_DEFINITION +directive @goModel(model: String, models: [String!], forceGenerate: Boolean) on OBJECT | INPUT_OBJECT | SCALAR | ENUM | INTERFACE | UNION +type BillProduct implements Node { + id: ID! + name: String! + sku: String! + quantity: Uint64! +} +""" +BillProductWhereInput is used for filtering BillProduct objects. +Input was generated by ent. +""" +input BillProductWhereInput { + not: BillProductWhereInput + and: [BillProductWhereInput!] + or: [BillProductWhereInput!] + """ + id field predicates + """ + id: ID + idNEQ: ID + idIn: [ID!] + idNotIn: [ID!] + idGT: ID + idGTE: ID + idLT: ID + idLTE: ID + """ + name field predicates + """ + name: String + nameNEQ: String + nameIn: [String!] + nameNotIn: [String!] + nameGT: String + nameGTE: String + nameLT: String + nameLTE: String + nameContains: String + nameHasPrefix: String + nameHasSuffix: String + nameEqualFold: String + nameContainsFold: String + """ + sku field predicates + """ + sku: String + skuNEQ: String + skuIn: [String!] + skuNotIn: [String!] + skuGT: String + skuGTE: String + skuLT: String + skuLTE: String + skuContains: String + skuHasPrefix: String + skuHasSuffix: String + skuEqualFold: String + skuContainsFold: String + """ + quantity field predicates + """ + quantity: Uint64 + quantityNEQ: Uint64 + quantityIn: [Uint64!] + quantityNotIn: [Uint64!] + quantityGT: Uint64 + quantityGTE: Uint64 + quantityLT: Uint64 + quantityLTE: Uint64 +} +type Category implements Node { + id: ID! + text: String! + status: CategoryStatus! + config: CategoryConfig + types: CategoryTypes + duration: Duration + count: Uint64 + strings: [String!] @deprecated(reason: "use `string` instead") + todos( + """ + Returns the elements in the list that come after the specified cursor. + """ + after: Cursor + + """ + Returns the first _n_ elements from the list. + """ + first: Int + + """ + Returns the elements in the list that come before the specified cursor. + """ + before: Cursor + + """ + Returns the last _n_ elements from the list. + """ + last: Int + + """ + Ordering options for Todos returned from the connection. + """ + orderBy: [TodoOrder!] + + """ + Filtering options for Todos returned from the connection. + """ + where: TodoWhereInput + ): TodoConnection! + subCategories( + """ + Returns the elements in the list that come after the specified cursor. + """ + after: Cursor + + """ + Returns the first _n_ elements from the list. + """ + first: Int + + """ + Returns the elements in the list that come before the specified cursor. + """ + before: Cursor + + """ + Returns the last _n_ elements from the list. + """ + last: Int + + """ + Ordering options for Categories returned from the connection. + """ + orderBy: [CategoryOrder!] + + """ + Filtering options for Categories returned from the connection. + """ + where: CategoryWhereInput + ): CategoryConnection! +} +""" +A connection to a list of items. +""" +type CategoryConnection { + """ + A list of edges. + """ + edges: [CategoryEdge] + """ + Information to aid in pagination. + """ + pageInfo: PageInfo! + """ + Identifies the total count of items in the connection. + """ + totalCount: Int! +} +""" +An edge in a connection. +""" +type CategoryEdge { + """ + The item at the end of the edge. + """ + node: Category + """ + A cursor for use in pagination. + """ + cursor: Cursor! +} +""" +Ordering options for Category connections +""" +input CategoryOrder { + """ + The ordering direction. + """ + direction: OrderDirection! = ASC + """ + The field by which to order Categories. + """ + field: CategoryOrderField! +} +""" +Properties by which Category connections can be ordered. +""" +enum CategoryOrderField { + ID + TEXT + STATUS + DURATION + COUNT + TODOS_COUNT +} +""" +CategoryStatus is enum for the field status +""" +enum CategoryStatus @goModel(model: "entgo.io/contrib/entgql/internal/todoglobalid/ent/category.Status") { + ENABLED + DISABLED +} +""" +CategoryWhereInput is used for filtering Category objects. +Input was generated by ent. +""" +input CategoryWhereInput { + not: CategoryWhereInput + and: [CategoryWhereInput!] + or: [CategoryWhereInput!] + """ + id field predicates + """ + id: ID + idNEQ: ID + idIn: [ID!] + idNotIn: [ID!] + idGT: ID + idGTE: ID + idLT: ID + idLTE: ID + """ + text field predicates + """ + text: String + textNEQ: String + textIn: [String!] + textNotIn: [String!] + textGT: String + textGTE: String + textLT: String + textLTE: String + textContains: String + textHasPrefix: String + textHasSuffix: String + textEqualFold: String + textContainsFold: String + """ + status field predicates + """ + status: CategoryStatus + statusNEQ: CategoryStatus + statusIn: [CategoryStatus!] + statusNotIn: [CategoryStatus!] + """ + config field predicates + """ + config: CategoryConfigInput + configNEQ: CategoryConfigInput + configIn: [CategoryConfigInput!] + configNotIn: [CategoryConfigInput!] + configGT: CategoryConfigInput + configGTE: CategoryConfigInput + configLT: CategoryConfigInput + configLTE: CategoryConfigInput + configIsNil: Boolean + configNotNil: Boolean + """ + duration field predicates + """ + duration: Duration + durationNEQ: Duration + durationIn: [Duration!] + durationNotIn: [Duration!] + durationGT: Duration + durationGTE: Duration + durationLT: Duration + durationLTE: Duration + durationIsNil: Boolean + durationNotNil: Boolean + """ + count field predicates + """ + count: Uint64 + countNEQ: Uint64 + countIn: [Uint64!] + countNotIn: [Uint64!] + countGT: Uint64 + countGTE: Uint64 + countLT: Uint64 + countLTE: Uint64 + countIsNil: Boolean + countNotNil: Boolean + """ + todos edge predicates + """ + hasTodos: Boolean + hasTodosWith: [TodoWhereInput!] + """ + sub_categories edge predicates + """ + hasSubCategories: Boolean + hasSubCategoriesWith: [CategoryWhereInput!] +} +""" +CreateCategoryInput is used for create Category object. +Input was generated by ent. +""" +input CreateCategoryInput { + text: String! + status: CategoryStatus! + config: CategoryConfigInput + types: CategoryTypesInput + duration: Duration + count: Uint64 + strings: [String!] + todoIDs: [ID!] + subCategoryIDs: [ID!] +} +""" +CreateTodoInput is used for create Todo object. +Input was generated by ent. +""" +input CreateTodoInput { + status: TodoStatus! + priority: Int + text: String! + init: Map + value: Int + parentID: ID + childIDs: [ID!] + categoryID: ID + secretID: ID +} +""" +CreateUserInput is used for create User object. +Input was generated by ent. +""" +input CreateUserInput { + name: String + username: UUID + password: String + requiredMetadata: Map! + metadata: Map + groupIDs: [ID!] + friendIDs: [ID!] +} +""" +Define a Relay Cursor type: +https://relay.dev/graphql/connections.htm#sec-Cursor +""" +scalar Cursor +type Friendship implements Node { + id: ID! + createdAt: Time! + userID: ID! + friendID: ID! + user: User! + friend: User! +} +""" +A connection to a list of items. +""" +type FriendshipConnection { + """ + A list of edges. + """ + edges: [FriendshipEdge] + """ + Information to aid in pagination. + """ + pageInfo: PageInfo! + """ + Identifies the total count of items in the connection. + """ + totalCount: Int! +} +""" +An edge in a connection. +""" +type FriendshipEdge { + """ + The item at the end of the edge. + """ + node: Friendship + """ + A cursor for use in pagination. + """ + cursor: Cursor! +} +""" +FriendshipWhereInput is used for filtering Friendship objects. +Input was generated by ent. +""" +input FriendshipWhereInput { + not: FriendshipWhereInput + and: [FriendshipWhereInput!] + or: [FriendshipWhereInput!] + """ + id field predicates + """ + id: ID + idNEQ: ID + idIn: [ID!] + idNotIn: [ID!] + idGT: ID + idGTE: ID + idLT: ID + idLTE: ID + """ + created_at field predicates + """ + createdAt: Time + createdAtNEQ: Time + createdAtIn: [Time!] + createdAtNotIn: [Time!] + createdAtGT: Time + createdAtGTE: Time + createdAtLT: Time + createdAtLTE: Time +} +type Group implements Node & NamedNode @hasPermissions(permissions: ["ADMIN","MODERATOR"]) { + id: ID! + name: String! + users( + """ + Returns the elements in the list that come after the specified cursor. + """ + after: Cursor + + """ + Returns the first _n_ elements from the list. + """ + first: Int + + """ + Returns the elements in the list that come before the specified cursor. + """ + before: Cursor + + """ + Returns the last _n_ elements from the list. + """ + last: Int + + """ + Ordering options for Users returned from the connection. + """ + orderBy: UserOrder + + """ + Filtering options for Users returned from the connection. + """ + where: UserWhereInput + ): UserConnection! +} +""" +A connection to a list of items. +""" +type GroupConnection { + """ + A list of edges. + """ + edges: [GroupEdge] + """ + Information to aid in pagination. + """ + pageInfo: PageInfo! + """ + Identifies the total count of items in the connection. + """ + totalCount: Int! +} +""" +An edge in a connection. +""" +type GroupEdge { + """ + The item at the end of the edge. + """ + node: Group + """ + A cursor for use in pagination. + """ + cursor: Cursor! +} +""" +GroupWhereInput is used for filtering Group objects. +Input was generated by ent. +""" +input GroupWhereInput { + not: GroupWhereInput + and: [GroupWhereInput!] + or: [GroupWhereInput!] + """ + id field predicates + """ + id: ID + idNEQ: ID + idIn: [ID!] + idNotIn: [ID!] + idGT: ID + idGTE: ID + idLT: ID + idLTE: ID + """ + name field predicates + """ + name: String + nameNEQ: String + nameIn: [String!] + nameNotIn: [String!] + nameGT: String + nameGTE: String + nameLT: String + nameLTE: String + nameContains: String + nameHasPrefix: String + nameHasSuffix: String + nameEqualFold: String + nameContainsFold: String + """ + users edge predicates + """ + hasUsers: Boolean + hasUsersWith: [UserWhereInput!] +} +""" +The builtin Map type +""" +scalar Map +""" +An object with an ID. +Follows the [Relay Global Object Identification Specification](https://relay.dev/graphql/objectidentification.htm) +""" +interface Node @goModel(model: "entgo.io/contrib/entgql/internal/todoglobalid/ent.Noder") { + """ + The id of the object. + """ + id: ID! +} +type OneToMany implements Node { + id: ID! + name: String! + field2: String + parent: OneToMany + children: [OneToMany!] +} +""" +A connection to a list of items. +""" +type OneToManyConnection { + """ + A list of edges. + """ + edges: [OneToManyEdge] + """ + Information to aid in pagination. + """ + pageInfo: PageInfo! + """ + Identifies the total count of items in the connection. + """ + totalCount: Int! +} +""" +An edge in a connection. +""" +type OneToManyEdge { + """ + The item at the end of the edge. + """ + node: OneToMany + """ + A cursor for use in pagination. + """ + cursor: Cursor! +} +""" +Ordering options for OneToMany connections +""" +input OneToManyOrder { + """ + The ordering direction. + """ + direction: OrderDirection! = ASC + """ + The field by which to order OneToManies. + """ + field: OneToManyOrderField! +} +""" +Properties by which OneToMany connections can be ordered. +""" +enum OneToManyOrderField { + NAME +} +""" +OneToManyWhereInput is used for filtering OneToMany objects. +Input was generated by ent. +""" +input OneToManyWhereInput { + not: OneToManyWhereInput + and: [OneToManyWhereInput!] + or: [OneToManyWhereInput!] + """ + id field predicates + """ + id: ID + idNEQ: ID + idIn: [ID!] + idNotIn: [ID!] + idGT: ID + idGTE: ID + idLT: ID + idLTE: ID + """ + name field predicates + """ + name: String + nameNEQ: String + nameIn: [String!] + nameNotIn: [String!] + nameGT: String + nameGTE: String + nameLT: String + nameLTE: String + nameContains: String + nameHasPrefix: String + nameHasSuffix: String + nameEqualFold: String + nameContainsFold: String + """ + field2 field predicates + """ + field2: String + field2NEQ: String + field2In: [String!] + field2NotIn: [String!] + field2GT: String + field2GTE: String + field2LT: String + field2LTE: String + field2Contains: String + field2HasPrefix: String + field2HasSuffix: String + field2IsNil: Boolean + field2NotNil: Boolean + field2EqualFold: String + field2ContainsFold: String + """ + parent edge predicates + """ + hasParent: Boolean + hasParentWith: [OneToManyWhereInput!] + """ + children edge predicates + """ + hasChildren: Boolean + hasChildrenWith: [OneToManyWhereInput!] +} +""" +Possible directions in which to order a list of items when provided an `orderBy` argument. +""" +enum OrderDirection { + """ + Specifies an ascending order for a given `orderBy` argument. + """ + ASC + """ + Specifies a descending order for a given `orderBy` argument. + """ + DESC +} +type Organization implements Node @goModel(model: "entgo.io/contrib/entgql/internal/todoglobalid/ent.Workspace") { + id: ID! + name: String! +} +""" +OrganizationWhereInput is used for filtering Workspace objects. +Input was generated by ent. +""" +input OrganizationWhereInput { + not: OrganizationWhereInput + and: [OrganizationWhereInput!] + or: [OrganizationWhereInput!] + """ + id field predicates + """ + id: ID + idNEQ: ID + idIn: [ID!] + idNotIn: [ID!] + idGT: ID + idGTE: ID + idLT: ID + idLTE: ID + """ + name field predicates + """ + name: String + nameNEQ: String + nameIn: [String!] + nameNotIn: [String!] + nameGT: String + nameGTE: String + nameLT: String + nameLTE: String + nameContains: String + nameHasPrefix: String + nameHasSuffix: String + nameEqualFold: String + nameContainsFold: String +} +""" +Information about pagination in a connection. +https://relay.dev/graphql/connections.htm#sec-undefined.PageInfo +""" +type PageInfo { + """ + When paginating forwards, are there more items? + """ + hasNextPage: Boolean! + """ + When paginating backwards, are there more items? + """ + hasPreviousPage: Boolean! + """ + When paginating backwards, the cursor to continue. + """ + startCursor: Cursor + """ + When paginating forwards, the cursor to continue. + """ + endCursor: Cursor +} +type Project implements Node { + id: ID! + todos( + """ + Returns the elements in the list that come after the specified cursor. + """ + after: Cursor + + """ + Returns the first _n_ elements from the list. + """ + first: Int + + """ + Returns the elements in the list that come before the specified cursor. + """ + before: Cursor + + """ + Returns the last _n_ elements from the list. + """ + last: Int + + """ + Ordering options for Todos returned from the connection. + """ + orderBy: [TodoOrder!] + + """ + Filtering options for Todos returned from the connection. + """ + where: TodoWhereInput + ): TodoConnection! +} +""" +ProjectWhereInput is used for filtering Project objects. +Input was generated by ent. +""" +input ProjectWhereInput { + not: ProjectWhereInput + and: [ProjectWhereInput!] + or: [ProjectWhereInput!] + """ + id field predicates + """ + id: ID + idNEQ: ID + idIn: [ID!] + idNotIn: [ID!] + idGT: ID + idGTE: ID + idLT: ID + idLTE: ID + """ + todos edge predicates + """ + hasTodos: Boolean + hasTodosWith: [TodoWhereInput!] +} +type Query { + """ + Fetches an object given its ID. + """ + node( + """ + ID of the object. + """ + id: ID! + ): Node + """ + Lookup nodes by a list of IDs. + """ + nodes( + """ + The list of node IDs. + """ + ids: [ID!]! + ): [Node]! + billProducts: [BillProduct!]! + categories( + """ + Returns the elements in the list that come after the specified cursor. + """ + after: Cursor + + """ + Returns the first _n_ elements from the list. + """ + first: Int + + """ + Returns the elements in the list that come before the specified cursor. + """ + before: Cursor + + """ + Returns the last _n_ elements from the list. + """ + last: Int + + """ + Ordering options for Categories returned from the connection. + """ + orderBy: [CategoryOrder!] + + """ + Filtering options for Categories returned from the connection. + """ + where: CategoryWhereInput + ): CategoryConnection! + groups( + """ + Returns the elements in the list that come after the specified cursor. + """ + after: Cursor + + """ + Returns the first _n_ elements from the list. + """ + first: Int + + """ + Returns the elements in the list that come before the specified cursor. + """ + before: Cursor + + """ + Returns the last _n_ elements from the list. + """ + last: Int + + """ + Filtering options for Groups returned from the connection. + """ + where: GroupWhereInput + ): GroupConnection! + oneToMany( + """ + Returns the elements in the list that come after the specified cursor. + """ + after: Cursor + + """ + Returns the first _n_ elements from the list. + """ + first: Int + + """ + Returns the elements in the list that come before the specified cursor. + """ + before: Cursor + + """ + Returns the last _n_ elements from the list. + """ + last: Int + + """ + Ordering options for OneToManies returned from the connection. + """ + orderBy: OneToManyOrder + + """ + Filtering options for OneToManies returned from the connection. + """ + where: OneToManyWhereInput + ): OneToManyConnection! + """ + This is the todo item + """ + todos( + """ + Returns the elements in the list that come after the specified cursor. + """ + after: Cursor + + """ + Returns the first _n_ elements from the list. + """ + first: Int + + """ + Returns the elements in the list that come before the specified cursor. + """ + before: Cursor + + """ + Returns the last _n_ elements from the list. + """ + last: Int + + """ + Ordering options for Todos returned from the connection. + """ + orderBy: [TodoOrder!] + + """ + Filtering options for Todos returned from the connection. + """ + where: TodoWhereInput + ): TodoConnection! + users( + """ + Returns the elements in the list that come after the specified cursor. + """ + after: Cursor + + """ + Returns the first _n_ elements from the list. + """ + first: Int + + """ + Returns the elements in the list that come before the specified cursor. + """ + before: Cursor + + """ + Returns the last _n_ elements from the list. + """ + last: Int + + """ + Ordering options for Users returned from the connection. + """ + orderBy: UserOrder + + """ + Filtering options for Users returned from the connection. + """ + where: UserWhereInput + ): UserConnection! +} +""" +The builtin Time type +""" +scalar Time +type Todo implements Node { + id: ID! + createdAt: Time! + status: TodoStatus! + priorityOrder: Int! @goField(name: "Priority", forceResolver: false) + text: String! + categoryID: ID + category_id: ID + categoryX: ID @goField(name: "CategoryID", forceResolver: false) + init: Map + custom: [Custom!] + customp: [Custom] + value: Int! + parent: Todo + children( + """ + Returns the elements in the list that come after the specified cursor. + """ + after: Cursor + + """ + Returns the first _n_ elements from the list. + """ + first: Int + + """ + Returns the elements in the list that come before the specified cursor. + """ + before: Cursor + + """ + Returns the last _n_ elements from the list. + """ + last: Int + + """ + Ordering options for Todos returned from the connection. + """ + orderBy: [TodoOrder!] + + """ + Filtering options for Todos returned from the connection. + """ + where: TodoWhereInput + ): TodoConnection! + category: Category +} +""" +A connection to a list of items. +""" +type TodoConnection { + """ + A list of edges. + """ + edges: [TodoEdge] + """ + Information to aid in pagination. + """ + pageInfo: PageInfo! + """ + Identifies the total count of items in the connection. + """ + totalCount: Int! +} +""" +An edge in a connection. +""" +type TodoEdge { + """ + The item at the end of the edge. + """ + node: Todo + """ + A cursor for use in pagination. + """ + cursor: Cursor! +} +""" +Ordering options for Todo connections +""" +input TodoOrder { + """ + The ordering direction. + """ + direction: OrderDirection! = ASC + """ + The field by which to order Todos. + """ + field: TodoOrderField! +} +""" +Properties by which Todo connections can be ordered. +""" +enum TodoOrderField { + CREATED_AT + STATUS + PRIORITY_ORDER + TEXT + PARENT_STATUS + CHILDREN_COUNT + CATEGORY_TEXT +} +""" +TodoStatus is enum for the field status +""" +enum TodoStatus @goModel(model: "entgo.io/contrib/entgql/internal/todoglobalid/ent/todo.Status") { + IN_PROGRESS + COMPLETED + PENDING +} +""" +TodoWhereInput is used for filtering Todo objects. +Input was generated by ent. +""" +input TodoWhereInput { + not: TodoWhereInput + and: [TodoWhereInput!] + or: [TodoWhereInput!] + """ + id field predicates + """ + id: ID + idNEQ: ID + idIn: [ID!] + idNotIn: [ID!] + idGT: ID + idGTE: ID + idLT: ID + idLTE: ID + """ + created_at field predicates + """ + createdAt: Time + createdAtNEQ: Time + createdAtIn: [Time!] + createdAtNotIn: [Time!] + createdAtGT: Time + createdAtGTE: Time + createdAtLT: Time + createdAtLTE: Time + """ + status field predicates + """ + status: TodoStatus + statusNEQ: TodoStatus + statusIn: [TodoStatus!] + statusNotIn: [TodoStatus!] + """ + priority field predicates + """ + priority: Int + priorityNEQ: Int + priorityIn: [Int!] + priorityNotIn: [Int!] + priorityGT: Int + priorityGTE: Int + priorityLT: Int + priorityLTE: Int + """ + text field predicates + """ + text: String + textNEQ: String + textIn: [String!] + textNotIn: [String!] + textGT: String + textGTE: String + textLT: String + textLTE: String + textContains: String + textHasPrefix: String + textHasSuffix: String + textEqualFold: String + textContainsFold: String + """ + category_id field predicates + """ + categoryID: ID + categoryIDNEQ: ID + categoryIDIn: [ID!] + categoryIDNotIn: [ID!] + categoryIDIsNil: Boolean + categoryIDNotNil: Boolean + """ + value field predicates + """ + value: Int + valueNEQ: Int + valueIn: [Int!] + valueNotIn: [Int!] + valueGT: Int + valueGTE: Int + valueLT: Int + valueLTE: Int + """ + parent edge predicates + """ + hasParent: Boolean + hasParentWith: [TodoWhereInput!] + """ + children edge predicates + """ + hasChildren: Boolean + hasChildrenWith: [TodoWhereInput!] + """ + category edge predicates + """ + hasCategory: Boolean + hasCategoryWith: [CategoryWhereInput!] +} +""" +The builtin Uint64 type +""" +scalar Uint64 +""" +UpdateCategoryInput is used for update Category object. +Input was generated by ent. +""" +input UpdateCategoryInput { + text: String + status: CategoryStatus + config: CategoryConfigInput + clearConfig: Boolean + types: CategoryTypesInput + clearTypes: Boolean + duration: Duration + clearDuration: Boolean + count: Uint64 + clearCount: Boolean + strings: [String!] + appendStrings: [String!] + clearStrings: Boolean + addTodoIDs: [ID!] + removeTodoIDs: [ID!] + clearTodos: Boolean + addSubCategoryIDs: [ID!] + removeSubCategoryIDs: [ID!] + clearSubCategories: Boolean +} +""" +UpdateFriendshipInput is used for update Friendship object. +Input was generated by ent. +""" +input UpdateFriendshipInput { + createdAt: Time + userID: ID + friendID: ID +} +""" +UpdateTodoInput is used for update Todo object. +Input was generated by ent. +""" +input UpdateTodoInput { + status: TodoStatus + priority: Int + text: String + init: Map + clearInit: Boolean + value: Int + parentID: ID + clearParent: Boolean + addChildIDs: [ID!] + removeChildIDs: [ID!] + clearChildren: Boolean + secretID: ID + clearSecret: Boolean +} +""" +UpdateUserInput is used for update User object. +Input was generated by ent. +""" +input UpdateUserInput { + name: String + username: UUID + password: String + clearPassword: Boolean + requiredMetadata: Map + metadata: Map + clearMetadata: Boolean + addGroupIDs: [ID!] + removeGroupIDs: [ID!] + clearGroups: Boolean + addFriendIDs: [ID!] + removeFriendIDs: [ID!] + clearFriends: Boolean +} +type User implements Node { + id: ID! + name: String! + username: UUID! + requiredMetadata: Map! + metadata: Map + groups( + """ + Returns the elements in the list that come after the specified cursor. + """ + after: Cursor + + """ + Returns the first _n_ elements from the list. + """ + first: Int + + """ + Returns the elements in the list that come before the specified cursor. + """ + before: Cursor + + """ + Returns the last _n_ elements from the list. + """ + last: Int + + """ + Filtering options for Groups returned from the connection. + """ + where: GroupWhereInput + ): GroupConnection! + friends( + """ + Returns the elements in the list that come after the specified cursor. + """ + after: Cursor + + """ + Returns the first _n_ elements from the list. + """ + first: Int + + """ + Returns the elements in the list that come before the specified cursor. + """ + before: Cursor + + """ + Returns the last _n_ elements from the list. + """ + last: Int + + """ + Ordering options for Users returned from the connection. + """ + orderBy: UserOrder + + """ + Filtering options for Users returned from the connection. + """ + where: UserWhereInput + ): UserConnection! + friendships( + """ + Returns the elements in the list that come after the specified cursor. + """ + after: Cursor + + """ + Returns the first _n_ elements from the list. + """ + first: Int + + """ + Returns the elements in the list that come before the specified cursor. + """ + before: Cursor + + """ + Returns the last _n_ elements from the list. + """ + last: Int + + """ + Filtering options for Friendships returned from the connection. + """ + where: FriendshipWhereInput + ): FriendshipConnection! +} +""" +A connection to a list of items. +""" +type UserConnection { + """ + A list of edges. + """ + edges: [UserEdge] + """ + Information to aid in pagination. + """ + pageInfo: PageInfo! + """ + Identifies the total count of items in the connection. + """ + totalCount: Int! +} +""" +An edge in a connection. +""" +type UserEdge { + """ + The item at the end of the edge. + """ + node: User + """ + A cursor for use in pagination. + """ + cursor: Cursor! +} +""" +Ordering options for User connections +""" +input UserOrder { + """ + The ordering direction. + """ + direction: OrderDirection! = ASC + """ + The field by which to order Users. + """ + field: UserOrderField! +} +""" +Properties by which User connections can be ordered. +""" +enum UserOrderField { + GROUPS_COUNT +} +""" +UserWhereInput is used for filtering User objects. +Input was generated by ent. +""" +input UserWhereInput { + not: UserWhereInput + and: [UserWhereInput!] + or: [UserWhereInput!] + """ + id field predicates + """ + id: ID + idNEQ: ID + idIn: [ID!] + idNotIn: [ID!] + idGT: ID + idGTE: ID + idLT: ID + idLTE: ID + """ + name field predicates + """ + name: String + nameNEQ: String + nameIn: [String!] + nameNotIn: [String!] + nameGT: String + nameGTE: String + nameLT: String + nameLTE: String + nameContains: String + nameHasPrefix: String + nameHasSuffix: String + nameEqualFold: String + nameContainsFold: String + """ + username field predicates + """ + username: UUID + usernameNEQ: UUID + usernameIn: [UUID!] + usernameNotIn: [UUID!] + usernameGT: UUID + usernameGTE: UUID + usernameLT: UUID + usernameLTE: UUID + """ + groups edge predicates + """ + hasGroups: Boolean + hasGroupsWith: [GroupWhereInput!] + """ + friends edge predicates + """ + hasFriends: Boolean + hasFriendsWith: [UserWhereInput!] + """ + friendships edge predicates + """ + hasFriendships: Boolean + hasFriendshipsWith: [FriendshipWhereInput!] +} diff --git a/entgql/internal/todoglobalid/ent.resolvers.go b/entgql/internal/todoglobalid/ent.resolvers.go new file mode 100644 index 000000000..e915f5606 --- /dev/null +++ b/entgql/internal/todoglobalid/ent.resolvers.go @@ -0,0 +1,106 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package todo + +// This file will be automatically regenerated based on the schema, any resolver implementations +// will be copied through when generating and any unknown code will be moved to the end. +// Code generated by github.com/99designs/gqlgen version v0.17.63 + +import ( + "context" + + "entgo.io/contrib/entgql" + "entgo.io/contrib/entgql/internal/todoglobalid/ent" +) + +// Node is the resolver for the node field. +func (r *queryResolver) Node(ctx context.Context, id int) (ent.Noder, error) { + return r.client.Noder(ctx, id) +} + +// Nodes is the resolver for the nodes field. +func (r *queryResolver) Nodes(ctx context.Context, ids []int) ([]ent.Noder, error) { + return r.client.Noders(ctx, ids) +} + +// BillProducts is the resolver for the billProducts field. +func (r *queryResolver) BillProducts(ctx context.Context) ([]*ent.BillProduct, error) { + return r.client.BillProduct.Query().All(ctx) +} + +// Categories is the resolver for the categories field. +func (r *queryResolver) Categories(ctx context.Context, after *entgql.Cursor[int], first *int, before *entgql.Cursor[int], last *int, orderBy []*ent.CategoryOrder, where *ent.CategoryWhereInput) (*ent.CategoryConnection, error) { + return r.client.Category.Query(). + Paginate(ctx, after, first, before, last, + ent.WithCategoryOrder(orderBy), + ent.WithCategoryFilter(where.Filter), + ) +} + +// Groups is the resolver for the groups field. +func (r *queryResolver) Groups(ctx context.Context, after *entgql.Cursor[int], first *int, before *entgql.Cursor[int], last *int, where *ent.GroupWhereInput) (*ent.GroupConnection, error) { + return r.client.Group.Query(). + Paginate(ctx, after, first, before, last, + ent.WithGroupFilter(where.Filter), + ) +} + +// OneToMany is the resolver for the oneToMany field. +func (r *queryResolver) OneToMany(ctx context.Context, after *entgql.Cursor[int], first *int, before *entgql.Cursor[int], last *int, orderBy *ent.OneToManyOrder, where *ent.OneToManyWhereInput) (*ent.OneToManyConnection, error) { + return r.client.OneToMany.Query(). + Paginate(ctx, after, first, before, last, + ent.WithOneToManyFilter(where.Filter), + ) +} + +// Todos is the resolver for the todos field. +func (r *queryResolver) Todos(ctx context.Context, after *entgql.Cursor[int], first *int, before *entgql.Cursor[int], last *int, orderBy []*ent.TodoOrder, where *ent.TodoWhereInput) (*ent.TodoConnection, error) { + return r.client.Todo.Query(). + Paginate(ctx, after, first, before, last, + ent.WithTodoOrder(orderBy), + ent.WithTodoFilter(where.Filter), + ) +} + +// Users is the resolver for the users field. +func (r *queryResolver) Users(ctx context.Context, after *entgql.Cursor[int], first *int, before *entgql.Cursor[int], last *int, orderBy *ent.UserOrder, where *ent.UserWhereInput) (*ent.UserConnection, error) { + return r.client.User.Query(). + Paginate(ctx, after, first, before, last, + ent.WithUserFilter(where.Filter), + ) +} + +// Category returns CategoryResolver implementation. +func (r *Resolver) Category() CategoryResolver { return &categoryResolver{r} } + +// Query returns QueryResolver implementation. +func (r *Resolver) Query() QueryResolver { return &queryResolver{r} } + +// Todo returns TodoResolver implementation. +func (r *Resolver) Todo() TodoResolver { return &todoResolver{r} } + +// CreateCategoryInput returns CreateCategoryInputResolver implementation. +func (r *Resolver) CreateCategoryInput() CreateCategoryInputResolver { + return &createCategoryInputResolver{r} +} + +// TodoWhereInput returns TodoWhereInputResolver implementation. +func (r *Resolver) TodoWhereInput() TodoWhereInputResolver { return &todoWhereInputResolver{r} } + +type categoryResolver struct{ *Resolver } +type queryResolver struct{ *Resolver } +type todoResolver struct{ *Resolver } +type createCategoryInputResolver struct{ *Resolver } +type todoWhereInputResolver struct{ *Resolver } diff --git a/entgql/internal/todoglobalid/ent/billproduct.go b/entgql/internal/todoglobalid/ent/billproduct.go new file mode 100644 index 000000000..64b38c88d --- /dev/null +++ b/entgql/internal/todoglobalid/ent/billproduct.go @@ -0,0 +1,139 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/billproduct" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// BillProduct is the model entity for the BillProduct schema. +type BillProduct struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Sku holds the value of the "sku" field. + Sku string `json:"sku,omitempty"` + // Quantity holds the value of the "quantity" field. + Quantity uint64 `json:"quantity,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*BillProduct) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case billproduct.FieldID, billproduct.FieldQuantity: + values[i] = new(sql.NullInt64) + case billproduct.FieldName, billproduct.FieldSku: + 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 BillProduct fields. +func (bp *BillProduct) 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 billproduct.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + bp.ID = int(value.Int64) + case billproduct.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + bp.Name = value.String + } + case billproduct.FieldSku: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field sku", values[i]) + } else if value.Valid { + bp.Sku = value.String + } + case billproduct.FieldQuantity: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field quantity", values[i]) + } else if value.Valid { + bp.Quantity = uint64(value.Int64) + } + default: + bp.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the BillProduct. +// This includes values selected through modifiers, order, etc. +func (bp *BillProduct) Value(name string) (ent.Value, error) { + return bp.selectValues.Get(name) +} + +// Update returns a builder for updating this BillProduct. +// Note that you need to call BillProduct.Unwrap() before calling this method if this BillProduct +// was returned from a transaction, and the transaction was committed or rolled back. +func (bp *BillProduct) Update() *BillProductUpdateOne { + return NewBillProductClient(bp.config).UpdateOne(bp) +} + +// Unwrap unwraps the BillProduct 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 (bp *BillProduct) Unwrap() *BillProduct { + _tx, ok := bp.config.driver.(*txDriver) + if !ok { + panic("ent: BillProduct is not a transactional entity") + } + bp.config.driver = _tx.drv + return bp +} + +// String implements the fmt.Stringer. +func (bp *BillProduct) String() string { + var builder strings.Builder + builder.WriteString("BillProduct(") + builder.WriteString(fmt.Sprintf("id=%v, ", bp.ID)) + builder.WriteString("name=") + builder.WriteString(bp.Name) + builder.WriteString(", ") + builder.WriteString("sku=") + builder.WriteString(bp.Sku) + builder.WriteString(", ") + builder.WriteString("quantity=") + builder.WriteString(fmt.Sprintf("%v", bp.Quantity)) + builder.WriteByte(')') + return builder.String() +} + +// BillProducts is a parsable slice of BillProduct. +type BillProducts []*BillProduct diff --git a/entgql/internal/todoglobalid/ent/billproduct/billproduct.go b/entgql/internal/todoglobalid/ent/billproduct/billproduct.go new file mode 100644 index 000000000..56b261698 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/billproduct/billproduct.go @@ -0,0 +1,77 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package billproduct + +import ( + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the billproduct type in the database. + Label = "bill_product" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldSku holds the string denoting the sku field in the database. + FieldSku = "sku" + // FieldQuantity holds the string denoting the quantity field in the database. + FieldQuantity = "quantity" + // Table holds the table name of the billproduct in the database. + Table = "bill_products" +) + +// Columns holds all SQL columns for billproduct fields. +var Columns = []string{ + FieldID, + FieldName, + FieldSku, + FieldQuantity, +} + +// 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 +} + +// OrderOption defines the ordering options for the BillProduct 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() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// BySku orders the results by the sku field. +func BySku(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldSku, opts...).ToFunc() +} + +// ByQuantity orders the results by the quantity field. +func ByQuantity(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldQuantity, opts...).ToFunc() +} diff --git a/entgql/internal/todoglobalid/ent/billproduct/where.go b/entgql/internal/todoglobalid/ent/billproduct/where.go new file mode 100644 index 000000000..333cf075a --- /dev/null +++ b/entgql/internal/todoglobalid/ent/billproduct/where.go @@ -0,0 +1,267 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package billproduct + +import ( + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.BillProduct { + return predicate.BillProduct(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.BillProduct { + return predicate.BillProduct(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.BillProduct { + return predicate.BillProduct(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.BillProduct { + return predicate.BillProduct(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.BillProduct { + return predicate.BillProduct(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.BillProduct { + return predicate.BillProduct(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.BillProduct { + return predicate.BillProduct(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.BillProduct { + return predicate.BillProduct(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.BillProduct { + return predicate.BillProduct(sql.FieldLTE(FieldID, id)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.BillProduct { + return predicate.BillProduct(sql.FieldEQ(FieldName, v)) +} + +// Sku applies equality check predicate on the "sku" field. It's identical to SkuEQ. +func Sku(v string) predicate.BillProduct { + return predicate.BillProduct(sql.FieldEQ(FieldSku, v)) +} + +// Quantity applies equality check predicate on the "quantity" field. It's identical to QuantityEQ. +func Quantity(v uint64) predicate.BillProduct { + return predicate.BillProduct(sql.FieldEQ(FieldQuantity, v)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.BillProduct { + return predicate.BillProduct(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.BillProduct { + return predicate.BillProduct(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.BillProduct { + return predicate.BillProduct(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.BillProduct { + return predicate.BillProduct(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.BillProduct { + return predicate.BillProduct(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.BillProduct { + return predicate.BillProduct(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.BillProduct { + return predicate.BillProduct(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.BillProduct { + return predicate.BillProduct(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.BillProduct { + return predicate.BillProduct(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.BillProduct { + return predicate.BillProduct(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.BillProduct { + return predicate.BillProduct(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.BillProduct { + return predicate.BillProduct(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.BillProduct { + return predicate.BillProduct(sql.FieldContainsFold(FieldName, v)) +} + +// SkuEQ applies the EQ predicate on the "sku" field. +func SkuEQ(v string) predicate.BillProduct { + return predicate.BillProduct(sql.FieldEQ(FieldSku, v)) +} + +// SkuNEQ applies the NEQ predicate on the "sku" field. +func SkuNEQ(v string) predicate.BillProduct { + return predicate.BillProduct(sql.FieldNEQ(FieldSku, v)) +} + +// SkuIn applies the In predicate on the "sku" field. +func SkuIn(vs ...string) predicate.BillProduct { + return predicate.BillProduct(sql.FieldIn(FieldSku, vs...)) +} + +// SkuNotIn applies the NotIn predicate on the "sku" field. +func SkuNotIn(vs ...string) predicate.BillProduct { + return predicate.BillProduct(sql.FieldNotIn(FieldSku, vs...)) +} + +// SkuGT applies the GT predicate on the "sku" field. +func SkuGT(v string) predicate.BillProduct { + return predicate.BillProduct(sql.FieldGT(FieldSku, v)) +} + +// SkuGTE applies the GTE predicate on the "sku" field. +func SkuGTE(v string) predicate.BillProduct { + return predicate.BillProduct(sql.FieldGTE(FieldSku, v)) +} + +// SkuLT applies the LT predicate on the "sku" field. +func SkuLT(v string) predicate.BillProduct { + return predicate.BillProduct(sql.FieldLT(FieldSku, v)) +} + +// SkuLTE applies the LTE predicate on the "sku" field. +func SkuLTE(v string) predicate.BillProduct { + return predicate.BillProduct(sql.FieldLTE(FieldSku, v)) +} + +// SkuContains applies the Contains predicate on the "sku" field. +func SkuContains(v string) predicate.BillProduct { + return predicate.BillProduct(sql.FieldContains(FieldSku, v)) +} + +// SkuHasPrefix applies the HasPrefix predicate on the "sku" field. +func SkuHasPrefix(v string) predicate.BillProduct { + return predicate.BillProduct(sql.FieldHasPrefix(FieldSku, v)) +} + +// SkuHasSuffix applies the HasSuffix predicate on the "sku" field. +func SkuHasSuffix(v string) predicate.BillProduct { + return predicate.BillProduct(sql.FieldHasSuffix(FieldSku, v)) +} + +// SkuEqualFold applies the EqualFold predicate on the "sku" field. +func SkuEqualFold(v string) predicate.BillProduct { + return predicate.BillProduct(sql.FieldEqualFold(FieldSku, v)) +} + +// SkuContainsFold applies the ContainsFold predicate on the "sku" field. +func SkuContainsFold(v string) predicate.BillProduct { + return predicate.BillProduct(sql.FieldContainsFold(FieldSku, v)) +} + +// QuantityEQ applies the EQ predicate on the "quantity" field. +func QuantityEQ(v uint64) predicate.BillProduct { + return predicate.BillProduct(sql.FieldEQ(FieldQuantity, v)) +} + +// QuantityNEQ applies the NEQ predicate on the "quantity" field. +func QuantityNEQ(v uint64) predicate.BillProduct { + return predicate.BillProduct(sql.FieldNEQ(FieldQuantity, v)) +} + +// QuantityIn applies the In predicate on the "quantity" field. +func QuantityIn(vs ...uint64) predicate.BillProduct { + return predicate.BillProduct(sql.FieldIn(FieldQuantity, vs...)) +} + +// QuantityNotIn applies the NotIn predicate on the "quantity" field. +func QuantityNotIn(vs ...uint64) predicate.BillProduct { + return predicate.BillProduct(sql.FieldNotIn(FieldQuantity, vs...)) +} + +// QuantityGT applies the GT predicate on the "quantity" field. +func QuantityGT(v uint64) predicate.BillProduct { + return predicate.BillProduct(sql.FieldGT(FieldQuantity, v)) +} + +// QuantityGTE applies the GTE predicate on the "quantity" field. +func QuantityGTE(v uint64) predicate.BillProduct { + return predicate.BillProduct(sql.FieldGTE(FieldQuantity, v)) +} + +// QuantityLT applies the LT predicate on the "quantity" field. +func QuantityLT(v uint64) predicate.BillProduct { + return predicate.BillProduct(sql.FieldLT(FieldQuantity, v)) +} + +// QuantityLTE applies the LTE predicate on the "quantity" field. +func QuantityLTE(v uint64) predicate.BillProduct { + return predicate.BillProduct(sql.FieldLTE(FieldQuantity, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.BillProduct) predicate.BillProduct { + return predicate.BillProduct(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.BillProduct) predicate.BillProduct { + return predicate.BillProduct(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.BillProduct) predicate.BillProduct { + return predicate.BillProduct(sql.NotPredicates(p)) +} diff --git a/entgql/internal/todoglobalid/ent/billproduct_create.go b/entgql/internal/todoglobalid/ent/billproduct_create.go new file mode 100644 index 000000000..7fe81649f --- /dev/null +++ b/entgql/internal/todoglobalid/ent/billproduct_create.go @@ -0,0 +1,223 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/billproduct" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// BillProductCreate is the builder for creating a BillProduct entity. +type BillProductCreate struct { + config + mutation *BillProductMutation + hooks []Hook +} + +// SetName sets the "name" field. +func (bpc *BillProductCreate) SetName(s string) *BillProductCreate { + bpc.mutation.SetName(s) + return bpc +} + +// SetSku sets the "sku" field. +func (bpc *BillProductCreate) SetSku(s string) *BillProductCreate { + bpc.mutation.SetSku(s) + return bpc +} + +// SetQuantity sets the "quantity" field. +func (bpc *BillProductCreate) SetQuantity(u uint64) *BillProductCreate { + bpc.mutation.SetQuantity(u) + return bpc +} + +// Mutation returns the BillProductMutation object of the builder. +func (bpc *BillProductCreate) Mutation() *BillProductMutation { + return bpc.mutation +} + +// Save creates the BillProduct in the database. +func (bpc *BillProductCreate) Save(ctx context.Context) (*BillProduct, error) { + return withHooks(ctx, bpc.sqlSave, bpc.mutation, bpc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (bpc *BillProductCreate) SaveX(ctx context.Context) *BillProduct { + v, err := bpc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (bpc *BillProductCreate) Exec(ctx context.Context) error { + _, err := bpc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (bpc *BillProductCreate) ExecX(ctx context.Context) { + if err := bpc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (bpc *BillProductCreate) check() error { + if _, ok := bpc.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "BillProduct.name"`)} + } + if _, ok := bpc.mutation.Sku(); !ok { + return &ValidationError{Name: "sku", err: errors.New(`ent: missing required field "BillProduct.sku"`)} + } + if _, ok := bpc.mutation.Quantity(); !ok { + return &ValidationError{Name: "quantity", err: errors.New(`ent: missing required field "BillProduct.quantity"`)} + } + return nil +} + +func (bpc *BillProductCreate) sqlSave(ctx context.Context) (*BillProduct, error) { + if err := bpc.check(); err != nil { + return nil, err + } + _node, _spec := bpc.createSpec() + if err := sqlgraph.CreateNode(ctx, bpc.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) + bpc.mutation.id = &_node.ID + bpc.mutation.done = true + return _node, nil +} + +func (bpc *BillProductCreate) createSpec() (*BillProduct, *sqlgraph.CreateSpec) { + var ( + _node = &BillProduct{config: bpc.config} + _spec = sqlgraph.NewCreateSpec(billproduct.Table, sqlgraph.NewFieldSpec(billproduct.FieldID, field.TypeInt)) + ) + if value, ok := bpc.mutation.Name(); ok { + _spec.SetField(billproduct.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := bpc.mutation.Sku(); ok { + _spec.SetField(billproduct.FieldSku, field.TypeString, value) + _node.Sku = value + } + if value, ok := bpc.mutation.Quantity(); ok { + _spec.SetField(billproduct.FieldQuantity, field.TypeUint64, value) + _node.Quantity = value + } + return _node, _spec +} + +// BillProductCreateBulk is the builder for creating many BillProduct entities in bulk. +type BillProductCreateBulk struct { + config + err error + builders []*BillProductCreate +} + +// Save creates the BillProduct entities in the database. +func (bpcb *BillProductCreateBulk) Save(ctx context.Context) ([]*BillProduct, error) { + if bpcb.err != nil { + return nil, bpcb.err + } + specs := make([]*sqlgraph.CreateSpec, len(bpcb.builders)) + nodes := make([]*BillProduct, len(bpcb.builders)) + mutators := make([]Mutator, len(bpcb.builders)) + for i := range bpcb.builders { + func(i int, root context.Context) { + builder := bpcb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*BillProductMutation) + 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, bpcb.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, bpcb.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, bpcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (bpcb *BillProductCreateBulk) SaveX(ctx context.Context) []*BillProduct { + v, err := bpcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (bpcb *BillProductCreateBulk) Exec(ctx context.Context) error { + _, err := bpcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (bpcb *BillProductCreateBulk) ExecX(ctx context.Context) { + if err := bpcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entgql/internal/todoglobalid/ent/billproduct_delete.go b/entgql/internal/todoglobalid/ent/billproduct_delete.go new file mode 100644 index 000000000..eafa6dbb4 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/billproduct_delete.go @@ -0,0 +1,102 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/billproduct" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// BillProductDelete is the builder for deleting a BillProduct entity. +type BillProductDelete struct { + config + hooks []Hook + mutation *BillProductMutation +} + +// Where appends a list predicates to the BillProductDelete builder. +func (bpd *BillProductDelete) Where(ps ...predicate.BillProduct) *BillProductDelete { + bpd.mutation.Where(ps...) + return bpd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (bpd *BillProductDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, bpd.sqlExec, bpd.mutation, bpd.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (bpd *BillProductDelete) ExecX(ctx context.Context) int { + n, err := bpd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (bpd *BillProductDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(billproduct.Table, sqlgraph.NewFieldSpec(billproduct.FieldID, field.TypeInt)) + if ps := bpd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, bpd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + bpd.mutation.done = true + return affected, err +} + +// BillProductDeleteOne is the builder for deleting a single BillProduct entity. +type BillProductDeleteOne struct { + bpd *BillProductDelete +} + +// Where appends a list predicates to the BillProductDelete builder. +func (bpdo *BillProductDeleteOne) Where(ps ...predicate.BillProduct) *BillProductDeleteOne { + bpdo.bpd.mutation.Where(ps...) + return bpdo +} + +// Exec executes the deletion query. +func (bpdo *BillProductDeleteOne) Exec(ctx context.Context) error { + n, err := bpdo.bpd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{billproduct.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (bpdo *BillProductDeleteOne) ExecX(ctx context.Context) { + if err := bpdo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entgql/internal/todoglobalid/ent/billproduct_query.go b/entgql/internal/todoglobalid/ent/billproduct_query.go new file mode 100644 index 000000000..6abc145d9 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/billproduct_query.go @@ -0,0 +1,570 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/billproduct" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// BillProductQuery is the builder for querying BillProduct entities. +type BillProductQuery struct { + config + ctx *QueryContext + order []billproduct.OrderOption + inters []Interceptor + predicates []predicate.BillProduct + loadTotal []func(context.Context, []*BillProduct) error + modifiers []func(*sql.Selector) + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the BillProductQuery builder. +func (bpq *BillProductQuery) Where(ps ...predicate.BillProduct) *BillProductQuery { + bpq.predicates = append(bpq.predicates, ps...) + return bpq +} + +// Limit the number of records to be returned by this query. +func (bpq *BillProductQuery) Limit(limit int) *BillProductQuery { + bpq.ctx.Limit = &limit + return bpq +} + +// Offset to start from. +func (bpq *BillProductQuery) Offset(offset int) *BillProductQuery { + bpq.ctx.Offset = &offset + return bpq +} + +// 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 (bpq *BillProductQuery) Unique(unique bool) *BillProductQuery { + bpq.ctx.Unique = &unique + return bpq +} + +// Order specifies how the records should be ordered. +func (bpq *BillProductQuery) Order(o ...billproduct.OrderOption) *BillProductQuery { + bpq.order = append(bpq.order, o...) + return bpq +} + +// First returns the first BillProduct entity from the query. +// Returns a *NotFoundError when no BillProduct was found. +func (bpq *BillProductQuery) First(ctx context.Context) (*BillProduct, error) { + nodes, err := bpq.Limit(1).All(setContextOp(ctx, bpq.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{billproduct.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (bpq *BillProductQuery) FirstX(ctx context.Context) *BillProduct { + node, err := bpq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first BillProduct ID from the query. +// Returns a *NotFoundError when no BillProduct ID was found. +func (bpq *BillProductQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = bpq.Limit(1).IDs(setContextOp(ctx, bpq.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{billproduct.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (bpq *BillProductQuery) FirstIDX(ctx context.Context) int { + id, err := bpq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single BillProduct entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one BillProduct entity is found. +// Returns a *NotFoundError when no BillProduct entities are found. +func (bpq *BillProductQuery) Only(ctx context.Context) (*BillProduct, error) { + nodes, err := bpq.Limit(2).All(setContextOp(ctx, bpq.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{billproduct.Label} + default: + return nil, &NotSingularError{billproduct.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (bpq *BillProductQuery) OnlyX(ctx context.Context) *BillProduct { + node, err := bpq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only BillProduct ID in the query. +// Returns a *NotSingularError when more than one BillProduct ID is found. +// Returns a *NotFoundError when no entities are found. +func (bpq *BillProductQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = bpq.Limit(2).IDs(setContextOp(ctx, bpq.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{billproduct.Label} + default: + err = &NotSingularError{billproduct.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (bpq *BillProductQuery) OnlyIDX(ctx context.Context) int { + id, err := bpq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of BillProducts. +func (bpq *BillProductQuery) All(ctx context.Context) ([]*BillProduct, error) { + ctx = setContextOp(ctx, bpq.ctx, ent.OpQueryAll) + if err := bpq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*BillProduct, *BillProductQuery]() + return withInterceptors[[]*BillProduct](ctx, bpq, qr, bpq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (bpq *BillProductQuery) AllX(ctx context.Context) []*BillProduct { + nodes, err := bpq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of BillProduct IDs. +func (bpq *BillProductQuery) IDs(ctx context.Context) (ids []int, err error) { + if bpq.ctx.Unique == nil && bpq.path != nil { + bpq.Unique(true) + } + ctx = setContextOp(ctx, bpq.ctx, ent.OpQueryIDs) + if err = bpq.Select(billproduct.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (bpq *BillProductQuery) IDsX(ctx context.Context) []int { + ids, err := bpq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (bpq *BillProductQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, bpq.ctx, ent.OpQueryCount) + if err := bpq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, bpq, querierCount[*BillProductQuery](), bpq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (bpq *BillProductQuery) CountX(ctx context.Context) int { + count, err := bpq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (bpq *BillProductQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, bpq.ctx, ent.OpQueryExist) + switch _, err := bpq.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 (bpq *BillProductQuery) ExistX(ctx context.Context) bool { + exist, err := bpq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the BillProductQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (bpq *BillProductQuery) Clone() *BillProductQuery { + if bpq == nil { + return nil + } + return &BillProductQuery{ + config: bpq.config, + ctx: bpq.ctx.Clone(), + order: append([]billproduct.OrderOption{}, bpq.order...), + inters: append([]Interceptor{}, bpq.inters...), + predicates: append([]predicate.BillProduct{}, bpq.predicates...), + // clone intermediate query. + sql: bpq.sql.Clone(), + path: bpq.path, + modifiers: append([]func(*sql.Selector){}, bpq.modifiers...), + } +} + +// 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 { +// Name string `json:"name,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.BillProduct.Query(). +// GroupBy(billproduct.FieldName). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (bpq *BillProductQuery) GroupBy(field string, fields ...string) *BillProductGroupBy { + bpq.ctx.Fields = append([]string{field}, fields...) + grbuild := &BillProductGroupBy{build: bpq} + grbuild.flds = &bpq.ctx.Fields + grbuild.label = billproduct.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 { +// Name string `json:"name,omitempty"` +// } +// +// client.BillProduct.Query(). +// Select(billproduct.FieldName). +// Scan(ctx, &v) +func (bpq *BillProductQuery) Select(fields ...string) *BillProductSelect { + bpq.ctx.Fields = append(bpq.ctx.Fields, fields...) + sbuild := &BillProductSelect{BillProductQuery: bpq} + sbuild.label = billproduct.Label + sbuild.flds, sbuild.scan = &bpq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a BillProductSelect configured with the given aggregations. +func (bpq *BillProductQuery) Aggregate(fns ...AggregateFunc) *BillProductSelect { + return bpq.Select().Aggregate(fns...) +} + +func (bpq *BillProductQuery) prepareQuery(ctx context.Context) error { + for _, inter := range bpq.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, bpq); err != nil { + return err + } + } + } + for _, f := range bpq.ctx.Fields { + if !billproduct.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if bpq.path != nil { + prev, err := bpq.path(ctx) + if err != nil { + return err + } + bpq.sql = prev + } + return nil +} + +func (bpq *BillProductQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*BillProduct, error) { + var ( + nodes = []*BillProduct{} + _spec = bpq.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*BillProduct).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &BillProduct{config: bpq.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + if len(bpq.modifiers) > 0 { + _spec.Modifiers = bpq.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, bpq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + for i := range bpq.loadTotal { + if err := bpq.loadTotal[i](ctx, nodes); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (bpq *BillProductQuery) sqlCount(ctx context.Context) (int, error) { + _spec := bpq.querySpec() + if len(bpq.modifiers) > 0 { + _spec.Modifiers = bpq.modifiers + } + _spec.Node.Columns = bpq.ctx.Fields + if len(bpq.ctx.Fields) > 0 { + _spec.Unique = bpq.ctx.Unique != nil && *bpq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, bpq.driver, _spec) +} + +func (bpq *BillProductQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(billproduct.Table, billproduct.Columns, sqlgraph.NewFieldSpec(billproduct.FieldID, field.TypeInt)) + _spec.From = bpq.sql + if unique := bpq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if bpq.path != nil { + _spec.Unique = true + } + if fields := bpq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, billproduct.FieldID) + for i := range fields { + if fields[i] != billproduct.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := bpq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := bpq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := bpq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := bpq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (bpq *BillProductQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(bpq.driver.Dialect()) + t1 := builder.Table(billproduct.Table) + columns := bpq.ctx.Fields + if len(columns) == 0 { + columns = billproduct.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if bpq.sql != nil { + selector = bpq.sql + selector.Select(selector.Columns(columns...)...) + } + if bpq.ctx.Unique != nil && *bpq.ctx.Unique { + selector.Distinct() + } + for _, m := range bpq.modifiers { + m(selector) + } + for _, p := range bpq.predicates { + p(selector) + } + for _, p := range bpq.order { + p(selector) + } + if offset := bpq.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 := bpq.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (bpq *BillProductQuery) Modify(modifiers ...func(s *sql.Selector)) *BillProductSelect { + bpq.modifiers = append(bpq.modifiers, modifiers...) + return bpq.Select() +} + +// BillProductGroupBy is the group-by builder for BillProduct entities. +type BillProductGroupBy struct { + selector + build *BillProductQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (bpgb *BillProductGroupBy) Aggregate(fns ...AggregateFunc) *BillProductGroupBy { + bpgb.fns = append(bpgb.fns, fns...) + return bpgb +} + +// Scan applies the selector query and scans the result into the given value. +func (bpgb *BillProductGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, bpgb.build.ctx, ent.OpQueryGroupBy) + if err := bpgb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*BillProductQuery, *BillProductGroupBy](ctx, bpgb.build, bpgb, bpgb.build.inters, v) +} + +func (bpgb *BillProductGroupBy) sqlScan(ctx context.Context, root *BillProductQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(bpgb.fns)) + for _, fn := range bpgb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*bpgb.flds)+len(bpgb.fns)) + for _, f := range *bpgb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*bpgb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := bpgb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// BillProductSelect is the builder for selecting fields of BillProduct entities. +type BillProductSelect struct { + *BillProductQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (bps *BillProductSelect) Aggregate(fns ...AggregateFunc) *BillProductSelect { + bps.fns = append(bps.fns, fns...) + return bps +} + +// Scan applies the selector query and scans the result into the given value. +func (bps *BillProductSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, bps.ctx, ent.OpQuerySelect) + if err := bps.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*BillProductQuery, *BillProductSelect](ctx, bps.BillProductQuery, bps, bps.inters, v) +} + +func (bps *BillProductSelect) sqlScan(ctx context.Context, root *BillProductQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(bps.fns)) + for _, fn := range bps.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*bps.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 := bps.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (bps *BillProductSelect) Modify(modifiers ...func(s *sql.Selector)) *BillProductSelect { + bps.modifiers = append(bps.modifiers, modifiers...) + return bps +} diff --git a/entgql/internal/todoglobalid/ent/billproduct_update.go b/entgql/internal/todoglobalid/ent/billproduct_update.go new file mode 100644 index 000000000..25af4aa5f --- /dev/null +++ b/entgql/internal/todoglobalid/ent/billproduct_update.go @@ -0,0 +1,327 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/billproduct" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// BillProductUpdate is the builder for updating BillProduct entities. +type BillProductUpdate struct { + config + hooks []Hook + mutation *BillProductMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the BillProductUpdate builder. +func (bpu *BillProductUpdate) Where(ps ...predicate.BillProduct) *BillProductUpdate { + bpu.mutation.Where(ps...) + return bpu +} + +// SetName sets the "name" field. +func (bpu *BillProductUpdate) SetName(s string) *BillProductUpdate { + bpu.mutation.SetName(s) + return bpu +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (bpu *BillProductUpdate) SetNillableName(s *string) *BillProductUpdate { + if s != nil { + bpu.SetName(*s) + } + return bpu +} + +// SetSku sets the "sku" field. +func (bpu *BillProductUpdate) SetSku(s string) *BillProductUpdate { + bpu.mutation.SetSku(s) + return bpu +} + +// SetNillableSku sets the "sku" field if the given value is not nil. +func (bpu *BillProductUpdate) SetNillableSku(s *string) *BillProductUpdate { + if s != nil { + bpu.SetSku(*s) + } + return bpu +} + +// SetQuantity sets the "quantity" field. +func (bpu *BillProductUpdate) SetQuantity(u uint64) *BillProductUpdate { + bpu.mutation.ResetQuantity() + bpu.mutation.SetQuantity(u) + return bpu +} + +// SetNillableQuantity sets the "quantity" field if the given value is not nil. +func (bpu *BillProductUpdate) SetNillableQuantity(u *uint64) *BillProductUpdate { + if u != nil { + bpu.SetQuantity(*u) + } + return bpu +} + +// AddQuantity adds u to the "quantity" field. +func (bpu *BillProductUpdate) AddQuantity(u int64) *BillProductUpdate { + bpu.mutation.AddQuantity(u) + return bpu +} + +// Mutation returns the BillProductMutation object of the builder. +func (bpu *BillProductUpdate) Mutation() *BillProductMutation { + return bpu.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (bpu *BillProductUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, bpu.sqlSave, bpu.mutation, bpu.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (bpu *BillProductUpdate) SaveX(ctx context.Context) int { + affected, err := bpu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (bpu *BillProductUpdate) Exec(ctx context.Context) error { + _, err := bpu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (bpu *BillProductUpdate) ExecX(ctx context.Context) { + if err := bpu.Exec(ctx); err != nil { + panic(err) + } +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (bpu *BillProductUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *BillProductUpdate { + bpu.modifiers = append(bpu.modifiers, modifiers...) + return bpu +} + +func (bpu *BillProductUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := sqlgraph.NewUpdateSpec(billproduct.Table, billproduct.Columns, sqlgraph.NewFieldSpec(billproduct.FieldID, field.TypeInt)) + if ps := bpu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := bpu.mutation.Name(); ok { + _spec.SetField(billproduct.FieldName, field.TypeString, value) + } + if value, ok := bpu.mutation.Sku(); ok { + _spec.SetField(billproduct.FieldSku, field.TypeString, value) + } + if value, ok := bpu.mutation.Quantity(); ok { + _spec.SetField(billproduct.FieldQuantity, field.TypeUint64, value) + } + if value, ok := bpu.mutation.AddedQuantity(); ok { + _spec.AddField(billproduct.FieldQuantity, field.TypeUint64, value) + } + _spec.AddModifiers(bpu.modifiers...) + if n, err = sqlgraph.UpdateNodes(ctx, bpu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{billproduct.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + bpu.mutation.done = true + return n, nil +} + +// BillProductUpdateOne is the builder for updating a single BillProduct entity. +type BillProductUpdateOne struct { + config + fields []string + hooks []Hook + mutation *BillProductMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetName sets the "name" field. +func (bpuo *BillProductUpdateOne) SetName(s string) *BillProductUpdateOne { + bpuo.mutation.SetName(s) + return bpuo +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (bpuo *BillProductUpdateOne) SetNillableName(s *string) *BillProductUpdateOne { + if s != nil { + bpuo.SetName(*s) + } + return bpuo +} + +// SetSku sets the "sku" field. +func (bpuo *BillProductUpdateOne) SetSku(s string) *BillProductUpdateOne { + bpuo.mutation.SetSku(s) + return bpuo +} + +// SetNillableSku sets the "sku" field if the given value is not nil. +func (bpuo *BillProductUpdateOne) SetNillableSku(s *string) *BillProductUpdateOne { + if s != nil { + bpuo.SetSku(*s) + } + return bpuo +} + +// SetQuantity sets the "quantity" field. +func (bpuo *BillProductUpdateOne) SetQuantity(u uint64) *BillProductUpdateOne { + bpuo.mutation.ResetQuantity() + bpuo.mutation.SetQuantity(u) + return bpuo +} + +// SetNillableQuantity sets the "quantity" field if the given value is not nil. +func (bpuo *BillProductUpdateOne) SetNillableQuantity(u *uint64) *BillProductUpdateOne { + if u != nil { + bpuo.SetQuantity(*u) + } + return bpuo +} + +// AddQuantity adds u to the "quantity" field. +func (bpuo *BillProductUpdateOne) AddQuantity(u int64) *BillProductUpdateOne { + bpuo.mutation.AddQuantity(u) + return bpuo +} + +// Mutation returns the BillProductMutation object of the builder. +func (bpuo *BillProductUpdateOne) Mutation() *BillProductMutation { + return bpuo.mutation +} + +// Where appends a list predicates to the BillProductUpdate builder. +func (bpuo *BillProductUpdateOne) Where(ps ...predicate.BillProduct) *BillProductUpdateOne { + bpuo.mutation.Where(ps...) + return bpuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (bpuo *BillProductUpdateOne) Select(field string, fields ...string) *BillProductUpdateOne { + bpuo.fields = append([]string{field}, fields...) + return bpuo +} + +// Save executes the query and returns the updated BillProduct entity. +func (bpuo *BillProductUpdateOne) Save(ctx context.Context) (*BillProduct, error) { + return withHooks(ctx, bpuo.sqlSave, bpuo.mutation, bpuo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (bpuo *BillProductUpdateOne) SaveX(ctx context.Context) *BillProduct { + node, err := bpuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (bpuo *BillProductUpdateOne) Exec(ctx context.Context) error { + _, err := bpuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (bpuo *BillProductUpdateOne) ExecX(ctx context.Context) { + if err := bpuo.Exec(ctx); err != nil { + panic(err) + } +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (bpuo *BillProductUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *BillProductUpdateOne { + bpuo.modifiers = append(bpuo.modifiers, modifiers...) + return bpuo +} + +func (bpuo *BillProductUpdateOne) sqlSave(ctx context.Context) (_node *BillProduct, err error) { + _spec := sqlgraph.NewUpdateSpec(billproduct.Table, billproduct.Columns, sqlgraph.NewFieldSpec(billproduct.FieldID, field.TypeInt)) + id, ok := bpuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "BillProduct.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := bpuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, billproduct.FieldID) + for _, f := range fields { + if !billproduct.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != billproduct.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := bpuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := bpuo.mutation.Name(); ok { + _spec.SetField(billproduct.FieldName, field.TypeString, value) + } + if value, ok := bpuo.mutation.Sku(); ok { + _spec.SetField(billproduct.FieldSku, field.TypeString, value) + } + if value, ok := bpuo.mutation.Quantity(); ok { + _spec.SetField(billproduct.FieldQuantity, field.TypeUint64, value) + } + if value, ok := bpuo.mutation.AddedQuantity(); ok { + _spec.AddField(billproduct.FieldQuantity, field.TypeUint64, value) + } + _spec.AddModifiers(bpuo.modifiers...) + _node = &BillProduct{config: bpuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, bpuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{billproduct.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + bpuo.mutation.done = true + return _node, nil +} diff --git a/entgql/internal/todoglobalid/ent/category.go b/entgql/internal/todoglobalid/ent/category.go new file mode 100644 index 000000000..12e5024e1 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/category.go @@ -0,0 +1,291 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "encoding/json" + "fmt" + "strings" + "time" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/category" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/schema/schematype" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// Category is the model entity for the Category schema. +type Category struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Text holds the value of the "text" field. + Text string `json:"text,omitempty"` + // Status holds the value of the "status" field. + Status category.Status `json:"status,omitempty"` + // Config holds the value of the "config" field. + Config *schematype.CategoryConfig `json:"config,omitempty"` + // Types holds the value of the "types" field. + Types *schematype.CategoryTypes `json:"types,omitempty"` + // Duration holds the value of the "duration" field. + Duration time.Duration `json:"duration,omitempty"` + // Count holds the value of the "count" field. + Count uint64 `json:"count,omitempty"` + // Strings holds the value of the "strings" field. + // + // Deprecated: use `string` instead + Strings []string `json:"strings,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the CategoryQuery when eager-loading is set. + Edges CategoryEdges `json:"edges"` + selectValues sql.SelectValues +} + +// CategoryEdges holds the relations/edges for other nodes in the graph. +type CategoryEdges struct { + // Todos holds the value of the todos edge. + Todos []*Todo `json:"todos,omitempty"` + // SubCategories holds the value of the sub_categories edge. + SubCategories []*Category `json:"sub_categories,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool + // totalCount holds the count of the edges above. + totalCount [2]map[string]int + + namedTodos map[string][]*Todo + namedSubCategories map[string][]*Category +} + +// TodosOrErr returns the Todos value or an error if the edge +// was not loaded in eager-loading. +func (e CategoryEdges) TodosOrErr() ([]*Todo, error) { + if e.loadedTypes[0] { + return e.Todos, nil + } + return nil, &NotLoadedError{edge: "todos"} +} + +// SubCategoriesOrErr returns the SubCategories value or an error if the edge +// was not loaded in eager-loading. +func (e CategoryEdges) SubCategoriesOrErr() ([]*Category, error) { + if e.loadedTypes[1] { + return e.SubCategories, nil + } + return nil, &NotLoadedError{edge: "sub_categories"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Category) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case category.FieldTypes, category.FieldStrings: + values[i] = new([]byte) + case category.FieldConfig: + values[i] = new(schematype.CategoryConfig) + case category.FieldID, category.FieldDuration, category.FieldCount: + values[i] = new(sql.NullInt64) + case category.FieldText, category.FieldStatus: + 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 Category fields. +func (c *Category) 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 category.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + c.ID = int(value.Int64) + case category.FieldText: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field text", values[i]) + } else if value.Valid { + c.Text = value.String + } + case category.FieldStatus: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field status", values[i]) + } else if value.Valid { + c.Status = category.Status(value.String) + } + case category.FieldConfig: + if value, ok := values[i].(*schematype.CategoryConfig); !ok { + return fmt.Errorf("unexpected type %T for field config", values[i]) + } else if value != nil { + c.Config = value + } + case category.FieldTypes: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field types", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &c.Types); err != nil { + return fmt.Errorf("unmarshal field types: %w", err) + } + } + case category.FieldDuration: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field duration", values[i]) + } else if value.Valid { + c.Duration = time.Duration(value.Int64) + } + case category.FieldCount: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field count", values[i]) + } else if value.Valid { + c.Count = uint64(value.Int64) + } + case category.FieldStrings: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field strings", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &c.Strings); err != nil { + return fmt.Errorf("unmarshal field strings: %w", err) + } + } + default: + c.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Category. +// This includes values selected through modifiers, order, etc. +func (c *Category) Value(name string) (ent.Value, error) { + return c.selectValues.Get(name) +} + +// QueryTodos queries the "todos" edge of the Category entity. +func (c *Category) QueryTodos() *TodoQuery { + return NewCategoryClient(c.config).QueryTodos(c) +} + +// QuerySubCategories queries the "sub_categories" edge of the Category entity. +func (c *Category) QuerySubCategories() *CategoryQuery { + return NewCategoryClient(c.config).QuerySubCategories(c) +} + +// Update returns a builder for updating this Category. +// Note that you need to call Category.Unwrap() before calling this method if this Category +// was returned from a transaction, and the transaction was committed or rolled back. +func (c *Category) Update() *CategoryUpdateOne { + return NewCategoryClient(c.config).UpdateOne(c) +} + +// Unwrap unwraps the Category 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 (c *Category) Unwrap() *Category { + _tx, ok := c.config.driver.(*txDriver) + if !ok { + panic("ent: Category is not a transactional entity") + } + c.config.driver = _tx.drv + return c +} + +// String implements the fmt.Stringer. +func (c *Category) String() string { + var builder strings.Builder + builder.WriteString("Category(") + builder.WriteString(fmt.Sprintf("id=%v, ", c.ID)) + builder.WriteString("text=") + builder.WriteString(c.Text) + builder.WriteString(", ") + builder.WriteString("status=") + builder.WriteString(fmt.Sprintf("%v", c.Status)) + builder.WriteString(", ") + builder.WriteString("config=") + builder.WriteString(fmt.Sprintf("%v", c.Config)) + builder.WriteString(", ") + builder.WriteString("types=") + builder.WriteString(fmt.Sprintf("%v", c.Types)) + builder.WriteString(", ") + builder.WriteString("duration=") + builder.WriteString(fmt.Sprintf("%v", c.Duration)) + builder.WriteString(", ") + builder.WriteString("count=") + builder.WriteString(fmt.Sprintf("%v", c.Count)) + builder.WriteString(", ") + builder.WriteString("strings=") + builder.WriteString(fmt.Sprintf("%v", c.Strings)) + builder.WriteByte(')') + return builder.String() +} + +// NamedTodos returns the Todos named value or an error if the edge was not +// loaded in eager-loading with this name. +func (c *Category) NamedTodos(name string) ([]*Todo, error) { + if c.Edges.namedTodos == nil { + return nil, &NotLoadedError{edge: name} + } + nodes, ok := c.Edges.namedTodos[name] + if !ok { + return nil, &NotLoadedError{edge: name} + } + return nodes, nil +} + +func (c *Category) appendNamedTodos(name string, edges ...*Todo) { + if c.Edges.namedTodos == nil { + c.Edges.namedTodos = make(map[string][]*Todo) + } + if len(edges) == 0 { + c.Edges.namedTodos[name] = []*Todo{} + } else { + c.Edges.namedTodos[name] = append(c.Edges.namedTodos[name], edges...) + } +} + +// NamedSubCategories returns the SubCategories named value or an error if the edge was not +// loaded in eager-loading with this name. +func (c *Category) NamedSubCategories(name string) ([]*Category, error) { + if c.Edges.namedSubCategories == nil { + return nil, &NotLoadedError{edge: name} + } + nodes, ok := c.Edges.namedSubCategories[name] + if !ok { + return nil, &NotLoadedError{edge: name} + } + return nodes, nil +} + +func (c *Category) appendNamedSubCategories(name string, edges ...*Category) { + if c.Edges.namedSubCategories == nil { + c.Edges.namedSubCategories = make(map[string][]*Category) + } + if len(edges) == 0 { + c.Edges.namedSubCategories[name] = []*Category{} + } else { + c.Edges.namedSubCategories[name] = append(c.Edges.namedSubCategories[name], edges...) + } +} + +// Categories is a parsable slice of Category. +type Categories []*Category diff --git a/entgql/internal/todoglobalid/ent/category/category.go b/entgql/internal/todoglobalid/ent/category/category.go new file mode 100644 index 000000000..3bc62e10d --- /dev/null +++ b/entgql/internal/todoglobalid/ent/category/category.go @@ -0,0 +1,215 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package category + +import ( + "fmt" + "io" + "strconv" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the category type in the database. + Label = "category" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldText holds the string denoting the text field in the database. + FieldText = "text" + // FieldStatus holds the string denoting the status field in the database. + FieldStatus = "status" + // FieldConfig holds the string denoting the config field in the database. + FieldConfig = "config" + // FieldTypes holds the string denoting the types field in the database. + FieldTypes = "types" + // FieldDuration holds the string denoting the duration field in the database. + FieldDuration = "duration" + // FieldCount holds the string denoting the count field in the database. + FieldCount = "count" + // FieldStrings holds the string denoting the strings field in the database. + FieldStrings = "strings" + // EdgeTodos holds the string denoting the todos edge name in mutations. + EdgeTodos = "todos" + // EdgeSubCategories holds the string denoting the sub_categories edge name in mutations. + EdgeSubCategories = "sub_categories" + // Table holds the table name of the category in the database. + Table = "categories" + // TodosTable is the table that holds the todos relation/edge. + TodosTable = "todos" + // TodosInverseTable is the table name for the Todo entity. + // It exists in this package in order to avoid circular dependency with the "todo" package. + TodosInverseTable = "todos" + // TodosColumn is the table column denoting the todos relation/edge. + TodosColumn = "category_id" + // SubCategoriesTable is the table that holds the sub_categories relation/edge. The primary key declared below. + SubCategoriesTable = "category_sub_categories" +) + +// Columns holds all SQL columns for category fields. +var Columns = []string{ + FieldID, + FieldText, + FieldStatus, + FieldConfig, + FieldTypes, + FieldDuration, + FieldCount, +} + +var ( + // SubCategoriesPrimaryKey and SubCategoriesColumn2 are the table columns denoting the + // primary key for the sub_categories relation (M2M). + SubCategoriesPrimaryKey = []string{"category_id", "sub_category_id"} +) + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + for _, f := range [...]string{FieldStrings} { + if column == f { + return true + } + } + return false +} + +var ( + // TextValidator is a validator for the "text" field. It is called by the builders before save. + TextValidator func(string) error +) + +// Status defines the type for the "status" enum field. +type Status string + +// Status values. +const ( + StatusEnabled Status = "ENABLED" + StatusDisabled Status = "DISABLED" +) + +func (s Status) String() string { + return string(s) +} + +// StatusValidator is a validator for the "status" field enum values. It is called by the builders before save. +func StatusValidator(s Status) error { + switch s { + case StatusEnabled, StatusDisabled: + return nil + default: + return fmt.Errorf("category: invalid enum value for status field: %q", s) + } +} + +// OrderOption defines the ordering options for the Category 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() +} + +// ByText orders the results by the text field. +func ByText(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldText, opts...).ToFunc() +} + +// ByStatus orders the results by the status field. +func ByStatus(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStatus, opts...).ToFunc() +} + +// ByConfig orders the results by the config field. +func ByConfig(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldConfig, opts...).ToFunc() +} + +// ByDuration orders the results by the duration field. +func ByDuration(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldDuration, opts...).ToFunc() +} + +// ByCount orders the results by the count field. +func ByCount(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCount, opts...).ToFunc() +} + +// ByTodosCount orders the results by todos count. +func ByTodosCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newTodosStep(), opts...) + } +} + +// ByTodos orders the results by todos terms. +func ByTodos(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newTodosStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// BySubCategoriesCount orders the results by sub_categories count. +func BySubCategoriesCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newSubCategoriesStep(), opts...) + } +} + +// BySubCategories orders the results by sub_categories terms. +func BySubCategories(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSubCategoriesStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newTodosStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TodosInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, TodosTable, TodosColumn), + ) +} +func newSubCategoriesStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, SubCategoriesTable, SubCategoriesPrimaryKey...), + ) +} + +// MarshalGQL implements graphql.Marshaler interface. +func (e Status) MarshalGQL(w io.Writer) { + io.WriteString(w, strconv.Quote(e.String())) +} + +// UnmarshalGQL implements graphql.Unmarshaler interface. +func (e *Status) UnmarshalGQL(val interface{}) error { + str, ok := val.(string) + if !ok { + return fmt.Errorf("enum %T must be a string", val) + } + *e = Status(str) + if err := StatusValidator(*e); err != nil { + return fmt.Errorf("%s is not a valid Status", str) + } + return nil +} diff --git a/entgql/internal/todoglobalid/ent/category/where.go b/entgql/internal/todoglobalid/ent/category/where.go new file mode 100644 index 000000000..31793c629 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/category/where.go @@ -0,0 +1,422 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package category + +import ( + "time" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/schema/schematype" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.Category { + return predicate.Category(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.Category { + return predicate.Category(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.Category { + return predicate.Category(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.Category { + return predicate.Category(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.Category { + return predicate.Category(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.Category { + return predicate.Category(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.Category { + return predicate.Category(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.Category { + return predicate.Category(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.Category { + return predicate.Category(sql.FieldLTE(FieldID, id)) +} + +// Text applies equality check predicate on the "text" field. It's identical to TextEQ. +func Text(v string) predicate.Category { + return predicate.Category(sql.FieldEQ(FieldText, v)) +} + +// Config applies equality check predicate on the "config" field. It's identical to ConfigEQ. +func Config(v *schematype.CategoryConfig) predicate.Category { + return predicate.Category(sql.FieldEQ(FieldConfig, v)) +} + +// Duration applies equality check predicate on the "duration" field. It's identical to DurationEQ. +func Duration(v time.Duration) predicate.Category { + vc := int64(v) + return predicate.Category(sql.FieldEQ(FieldDuration, vc)) +} + +// Count applies equality check predicate on the "count" field. It's identical to CountEQ. +func Count(v uint64) predicate.Category { + return predicate.Category(sql.FieldEQ(FieldCount, v)) +} + +// TextEQ applies the EQ predicate on the "text" field. +func TextEQ(v string) predicate.Category { + return predicate.Category(sql.FieldEQ(FieldText, v)) +} + +// TextNEQ applies the NEQ predicate on the "text" field. +func TextNEQ(v string) predicate.Category { + return predicate.Category(sql.FieldNEQ(FieldText, v)) +} + +// TextIn applies the In predicate on the "text" field. +func TextIn(vs ...string) predicate.Category { + return predicate.Category(sql.FieldIn(FieldText, vs...)) +} + +// TextNotIn applies the NotIn predicate on the "text" field. +func TextNotIn(vs ...string) predicate.Category { + return predicate.Category(sql.FieldNotIn(FieldText, vs...)) +} + +// TextGT applies the GT predicate on the "text" field. +func TextGT(v string) predicate.Category { + return predicate.Category(sql.FieldGT(FieldText, v)) +} + +// TextGTE applies the GTE predicate on the "text" field. +func TextGTE(v string) predicate.Category { + return predicate.Category(sql.FieldGTE(FieldText, v)) +} + +// TextLT applies the LT predicate on the "text" field. +func TextLT(v string) predicate.Category { + return predicate.Category(sql.FieldLT(FieldText, v)) +} + +// TextLTE applies the LTE predicate on the "text" field. +func TextLTE(v string) predicate.Category { + return predicate.Category(sql.FieldLTE(FieldText, v)) +} + +// TextContains applies the Contains predicate on the "text" field. +func TextContains(v string) predicate.Category { + return predicate.Category(sql.FieldContains(FieldText, v)) +} + +// TextHasPrefix applies the HasPrefix predicate on the "text" field. +func TextHasPrefix(v string) predicate.Category { + return predicate.Category(sql.FieldHasPrefix(FieldText, v)) +} + +// TextHasSuffix applies the HasSuffix predicate on the "text" field. +func TextHasSuffix(v string) predicate.Category { + return predicate.Category(sql.FieldHasSuffix(FieldText, v)) +} + +// TextEqualFold applies the EqualFold predicate on the "text" field. +func TextEqualFold(v string) predicate.Category { + return predicate.Category(sql.FieldEqualFold(FieldText, v)) +} + +// TextContainsFold applies the ContainsFold predicate on the "text" field. +func TextContainsFold(v string) predicate.Category { + return predicate.Category(sql.FieldContainsFold(FieldText, v)) +} + +// StatusEQ applies the EQ predicate on the "status" field. +func StatusEQ(v Status) predicate.Category { + return predicate.Category(sql.FieldEQ(FieldStatus, v)) +} + +// StatusNEQ applies the NEQ predicate on the "status" field. +func StatusNEQ(v Status) predicate.Category { + return predicate.Category(sql.FieldNEQ(FieldStatus, v)) +} + +// StatusIn applies the In predicate on the "status" field. +func StatusIn(vs ...Status) predicate.Category { + return predicate.Category(sql.FieldIn(FieldStatus, vs...)) +} + +// StatusNotIn applies the NotIn predicate on the "status" field. +func StatusNotIn(vs ...Status) predicate.Category { + return predicate.Category(sql.FieldNotIn(FieldStatus, vs...)) +} + +// ConfigEQ applies the EQ predicate on the "config" field. +func ConfigEQ(v *schematype.CategoryConfig) predicate.Category { + return predicate.Category(sql.FieldEQ(FieldConfig, v)) +} + +// ConfigNEQ applies the NEQ predicate on the "config" field. +func ConfigNEQ(v *schematype.CategoryConfig) predicate.Category { + return predicate.Category(sql.FieldNEQ(FieldConfig, v)) +} + +// ConfigIn applies the In predicate on the "config" field. +func ConfigIn(vs ...*schematype.CategoryConfig) predicate.Category { + return predicate.Category(sql.FieldIn(FieldConfig, vs...)) +} + +// ConfigNotIn applies the NotIn predicate on the "config" field. +func ConfigNotIn(vs ...*schematype.CategoryConfig) predicate.Category { + return predicate.Category(sql.FieldNotIn(FieldConfig, vs...)) +} + +// ConfigGT applies the GT predicate on the "config" field. +func ConfigGT(v *schematype.CategoryConfig) predicate.Category { + return predicate.Category(sql.FieldGT(FieldConfig, v)) +} + +// ConfigGTE applies the GTE predicate on the "config" field. +func ConfigGTE(v *schematype.CategoryConfig) predicate.Category { + return predicate.Category(sql.FieldGTE(FieldConfig, v)) +} + +// ConfigLT applies the LT predicate on the "config" field. +func ConfigLT(v *schematype.CategoryConfig) predicate.Category { + return predicate.Category(sql.FieldLT(FieldConfig, v)) +} + +// ConfigLTE applies the LTE predicate on the "config" field. +func ConfigLTE(v *schematype.CategoryConfig) predicate.Category { + return predicate.Category(sql.FieldLTE(FieldConfig, v)) +} + +// ConfigIsNil applies the IsNil predicate on the "config" field. +func ConfigIsNil() predicate.Category { + return predicate.Category(sql.FieldIsNull(FieldConfig)) +} + +// ConfigNotNil applies the NotNil predicate on the "config" field. +func ConfigNotNil() predicate.Category { + return predicate.Category(sql.FieldNotNull(FieldConfig)) +} + +// TypesIsNil applies the IsNil predicate on the "types" field. +func TypesIsNil() predicate.Category { + return predicate.Category(sql.FieldIsNull(FieldTypes)) +} + +// TypesNotNil applies the NotNil predicate on the "types" field. +func TypesNotNil() predicate.Category { + return predicate.Category(sql.FieldNotNull(FieldTypes)) +} + +// DurationEQ applies the EQ predicate on the "duration" field. +func DurationEQ(v time.Duration) predicate.Category { + vc := int64(v) + return predicate.Category(sql.FieldEQ(FieldDuration, vc)) +} + +// DurationNEQ applies the NEQ predicate on the "duration" field. +func DurationNEQ(v time.Duration) predicate.Category { + vc := int64(v) + return predicate.Category(sql.FieldNEQ(FieldDuration, vc)) +} + +// DurationIn applies the In predicate on the "duration" field. +func DurationIn(vs ...time.Duration) predicate.Category { + v := make([]any, len(vs)) + for i := range v { + v[i] = int64(vs[i]) + } + return predicate.Category(sql.FieldIn(FieldDuration, v...)) +} + +// DurationNotIn applies the NotIn predicate on the "duration" field. +func DurationNotIn(vs ...time.Duration) predicate.Category { + v := make([]any, len(vs)) + for i := range v { + v[i] = int64(vs[i]) + } + return predicate.Category(sql.FieldNotIn(FieldDuration, v...)) +} + +// DurationGT applies the GT predicate on the "duration" field. +func DurationGT(v time.Duration) predicate.Category { + vc := int64(v) + return predicate.Category(sql.FieldGT(FieldDuration, vc)) +} + +// DurationGTE applies the GTE predicate on the "duration" field. +func DurationGTE(v time.Duration) predicate.Category { + vc := int64(v) + return predicate.Category(sql.FieldGTE(FieldDuration, vc)) +} + +// DurationLT applies the LT predicate on the "duration" field. +func DurationLT(v time.Duration) predicate.Category { + vc := int64(v) + return predicate.Category(sql.FieldLT(FieldDuration, vc)) +} + +// DurationLTE applies the LTE predicate on the "duration" field. +func DurationLTE(v time.Duration) predicate.Category { + vc := int64(v) + return predicate.Category(sql.FieldLTE(FieldDuration, vc)) +} + +// DurationIsNil applies the IsNil predicate on the "duration" field. +func DurationIsNil() predicate.Category { + return predicate.Category(sql.FieldIsNull(FieldDuration)) +} + +// DurationNotNil applies the NotNil predicate on the "duration" field. +func DurationNotNil() predicate.Category { + return predicate.Category(sql.FieldNotNull(FieldDuration)) +} + +// CountEQ applies the EQ predicate on the "count" field. +func CountEQ(v uint64) predicate.Category { + return predicate.Category(sql.FieldEQ(FieldCount, v)) +} + +// CountNEQ applies the NEQ predicate on the "count" field. +func CountNEQ(v uint64) predicate.Category { + return predicate.Category(sql.FieldNEQ(FieldCount, v)) +} + +// CountIn applies the In predicate on the "count" field. +func CountIn(vs ...uint64) predicate.Category { + return predicate.Category(sql.FieldIn(FieldCount, vs...)) +} + +// CountNotIn applies the NotIn predicate on the "count" field. +func CountNotIn(vs ...uint64) predicate.Category { + return predicate.Category(sql.FieldNotIn(FieldCount, vs...)) +} + +// CountGT applies the GT predicate on the "count" field. +func CountGT(v uint64) predicate.Category { + return predicate.Category(sql.FieldGT(FieldCount, v)) +} + +// CountGTE applies the GTE predicate on the "count" field. +func CountGTE(v uint64) predicate.Category { + return predicate.Category(sql.FieldGTE(FieldCount, v)) +} + +// CountLT applies the LT predicate on the "count" field. +func CountLT(v uint64) predicate.Category { + return predicate.Category(sql.FieldLT(FieldCount, v)) +} + +// CountLTE applies the LTE predicate on the "count" field. +func CountLTE(v uint64) predicate.Category { + return predicate.Category(sql.FieldLTE(FieldCount, v)) +} + +// CountIsNil applies the IsNil predicate on the "count" field. +func CountIsNil() predicate.Category { + return predicate.Category(sql.FieldIsNull(FieldCount)) +} + +// CountNotNil applies the NotNil predicate on the "count" field. +func CountNotNil() predicate.Category { + return predicate.Category(sql.FieldNotNull(FieldCount)) +} + +// StringsIsNil applies the IsNil predicate on the "strings" field. +func StringsIsNil() predicate.Category { + return predicate.Category(sql.FieldIsNull(FieldStrings)) +} + +// StringsNotNil applies the NotNil predicate on the "strings" field. +func StringsNotNil() predicate.Category { + return predicate.Category(sql.FieldNotNull(FieldStrings)) +} + +// HasTodos applies the HasEdge predicate on the "todos" edge. +func HasTodos() predicate.Category { + return predicate.Category(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, TodosTable, TodosColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasTodosWith applies the HasEdge predicate on the "todos" edge with a given conditions (other predicates). +func HasTodosWith(preds ...predicate.Todo) predicate.Category { + return predicate.Category(func(s *sql.Selector) { + step := newTodosStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasSubCategories applies the HasEdge predicate on the "sub_categories" edge. +func HasSubCategories() predicate.Category { + return predicate.Category(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, SubCategoriesTable, SubCategoriesPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSubCategoriesWith applies the HasEdge predicate on the "sub_categories" edge with a given conditions (other predicates). +func HasSubCategoriesWith(preds ...predicate.Category) predicate.Category { + return predicate.Category(func(s *sql.Selector) { + step := newSubCategoriesStep() + 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.Category) predicate.Category { + return predicate.Category(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Category) predicate.Category { + return predicate.Category(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Category) predicate.Category { + return predicate.Category(sql.NotPredicates(p)) +} diff --git a/entgql/internal/todoglobalid/ent/category_create.go b/entgql/internal/todoglobalid/ent/category_create.go new file mode 100644 index 000000000..9c080eb1d --- /dev/null +++ b/entgql/internal/todoglobalid/ent/category_create.go @@ -0,0 +1,363 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/category" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/schema/schematype" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/todo" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// CategoryCreate is the builder for creating a Category entity. +type CategoryCreate struct { + config + mutation *CategoryMutation + hooks []Hook +} + +// SetText sets the "text" field. +func (cc *CategoryCreate) SetText(s string) *CategoryCreate { + cc.mutation.SetText(s) + return cc +} + +// SetStatus sets the "status" field. +func (cc *CategoryCreate) SetStatus(c category.Status) *CategoryCreate { + cc.mutation.SetStatus(c) + return cc +} + +// SetConfig sets the "config" field. +func (cc *CategoryCreate) SetConfig(sc *schematype.CategoryConfig) *CategoryCreate { + cc.mutation.SetConfig(sc) + return cc +} + +// SetTypes sets the "types" field. +func (cc *CategoryCreate) SetTypes(st *schematype.CategoryTypes) *CategoryCreate { + cc.mutation.SetTypes(st) + return cc +} + +// SetDuration sets the "duration" field. +func (cc *CategoryCreate) SetDuration(t time.Duration) *CategoryCreate { + cc.mutation.SetDuration(t) + return cc +} + +// SetNillableDuration sets the "duration" field if the given value is not nil. +func (cc *CategoryCreate) SetNillableDuration(t *time.Duration) *CategoryCreate { + if t != nil { + cc.SetDuration(*t) + } + return cc +} + +// SetCount sets the "count" field. +func (cc *CategoryCreate) SetCount(u uint64) *CategoryCreate { + cc.mutation.SetCount(u) + return cc +} + +// SetNillableCount sets the "count" field if the given value is not nil. +func (cc *CategoryCreate) SetNillableCount(u *uint64) *CategoryCreate { + if u != nil { + cc.SetCount(*u) + } + return cc +} + +// SetStrings sets the "strings" field. +func (cc *CategoryCreate) SetStrings(s []string) *CategoryCreate { + cc.mutation.SetStrings(s) + return cc +} + +// SetID sets the "id" field. +func (cc *CategoryCreate) SetID(i int) *CategoryCreate { + cc.mutation.SetID(i) + return cc +} + +// AddTodoIDs adds the "todos" edge to the Todo entity by IDs. +func (cc *CategoryCreate) AddTodoIDs(ids ...int) *CategoryCreate { + cc.mutation.AddTodoIDs(ids...) + return cc +} + +// AddTodos adds the "todos" edges to the Todo entity. +func (cc *CategoryCreate) AddTodos(t ...*Todo) *CategoryCreate { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return cc.AddTodoIDs(ids...) +} + +// AddSubCategoryIDs adds the "sub_categories" edge to the Category entity by IDs. +func (cc *CategoryCreate) AddSubCategoryIDs(ids ...int) *CategoryCreate { + cc.mutation.AddSubCategoryIDs(ids...) + return cc +} + +// AddSubCategories adds the "sub_categories" edges to the Category entity. +func (cc *CategoryCreate) AddSubCategories(c ...*Category) *CategoryCreate { + ids := make([]int, len(c)) + for i := range c { + ids[i] = c[i].ID + } + return cc.AddSubCategoryIDs(ids...) +} + +// Mutation returns the CategoryMutation object of the builder. +func (cc *CategoryCreate) Mutation() *CategoryMutation { + return cc.mutation +} + +// Save creates the Category in the database. +func (cc *CategoryCreate) Save(ctx context.Context) (*Category, error) { + return withHooks(ctx, cc.sqlSave, cc.mutation, cc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (cc *CategoryCreate) SaveX(ctx context.Context) *Category { + v, err := cc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (cc *CategoryCreate) Exec(ctx context.Context) error { + _, err := cc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (cc *CategoryCreate) ExecX(ctx context.Context) { + if err := cc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (cc *CategoryCreate) check() error { + if _, ok := cc.mutation.Text(); !ok { + return &ValidationError{Name: "text", err: errors.New(`ent: missing required field "Category.text"`)} + } + if v, ok := cc.mutation.Text(); ok { + if err := category.TextValidator(v); err != nil { + return &ValidationError{Name: "text", err: fmt.Errorf(`ent: validator failed for field "Category.text": %w`, err)} + } + } + if _, ok := cc.mutation.Status(); !ok { + return &ValidationError{Name: "status", err: errors.New(`ent: missing required field "Category.status"`)} + } + if v, ok := cc.mutation.Status(); ok { + if err := category.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "Category.status": %w`, err)} + } + } + return nil +} + +func (cc *CategoryCreate) sqlSave(ctx context.Context) (*Category, error) { + if err := cc.check(); err != nil { + return nil, err + } + _node, _spec := cc.createSpec() + if err := sqlgraph.CreateNode(ctx, cc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + if _spec.ID.Value != _node.ID { + id := _spec.ID.Value.(int64) + _node.ID = int(id) + } + cc.mutation.id = &_node.ID + cc.mutation.done = true + return _node, nil +} + +func (cc *CategoryCreate) createSpec() (*Category, *sqlgraph.CreateSpec) { + var ( + _node = &Category{config: cc.config} + _spec = sqlgraph.NewCreateSpec(category.Table, sqlgraph.NewFieldSpec(category.FieldID, field.TypeInt)) + ) + if id, ok := cc.mutation.ID(); ok { + _node.ID = id + _spec.ID.Value = id + } + if value, ok := cc.mutation.Text(); ok { + _spec.SetField(category.FieldText, field.TypeString, value) + _node.Text = value + } + if value, ok := cc.mutation.Status(); ok { + _spec.SetField(category.FieldStatus, field.TypeEnum, value) + _node.Status = value + } + if value, ok := cc.mutation.Config(); ok { + _spec.SetField(category.FieldConfig, field.TypeOther, value) + _node.Config = value + } + if value, ok := cc.mutation.Types(); ok { + _spec.SetField(category.FieldTypes, field.TypeJSON, value) + _node.Types = value + } + if value, ok := cc.mutation.Duration(); ok { + _spec.SetField(category.FieldDuration, field.TypeInt64, value) + _node.Duration = value + } + if value, ok := cc.mutation.Count(); ok { + _spec.SetField(category.FieldCount, field.TypeUint64, value) + _node.Count = value + } + if value, ok := cc.mutation.Strings(); ok { + _spec.SetField(category.FieldStrings, field.TypeJSON, value) + _node.Strings = value + } + if nodes := cc.mutation.TodosIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: category.TodosTable, + Columns: []string{category.TodosColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := cc.mutation.SubCategoriesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: category.SubCategoriesTable, + Columns: category.SubCategoriesPrimaryKey, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(category.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// CategoryCreateBulk is the builder for creating many Category entities in bulk. +type CategoryCreateBulk struct { + config + err error + builders []*CategoryCreate +} + +// Save creates the Category entities in the database. +func (ccb *CategoryCreateBulk) Save(ctx context.Context) ([]*Category, error) { + if ccb.err != nil { + return nil, ccb.err + } + specs := make([]*sqlgraph.CreateSpec, len(ccb.builders)) + nodes := make([]*Category, len(ccb.builders)) + mutators := make([]Mutator, len(ccb.builders)) + for i := range ccb.builders { + func(i int, root context.Context) { + builder := ccb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*CategoryMutation) + 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, ccb.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, ccb.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 && nodes[i].ID == 0 { + 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, ccb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (ccb *CategoryCreateBulk) SaveX(ctx context.Context) []*Category { + v, err := ccb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ccb *CategoryCreateBulk) Exec(ctx context.Context) error { + _, err := ccb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ccb *CategoryCreateBulk) ExecX(ctx context.Context) { + if err := ccb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entgql/internal/todoglobalid/ent/category_delete.go b/entgql/internal/todoglobalid/ent/category_delete.go new file mode 100644 index 000000000..1845ca681 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/category_delete.go @@ -0,0 +1,102 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/category" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// CategoryDelete is the builder for deleting a Category entity. +type CategoryDelete struct { + config + hooks []Hook + mutation *CategoryMutation +} + +// Where appends a list predicates to the CategoryDelete builder. +func (cd *CategoryDelete) Where(ps ...predicate.Category) *CategoryDelete { + cd.mutation.Where(ps...) + return cd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (cd *CategoryDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, cd.sqlExec, cd.mutation, cd.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (cd *CategoryDelete) ExecX(ctx context.Context) int { + n, err := cd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (cd *CategoryDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(category.Table, sqlgraph.NewFieldSpec(category.FieldID, field.TypeInt)) + if ps := cd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, cd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + cd.mutation.done = true + return affected, err +} + +// CategoryDeleteOne is the builder for deleting a single Category entity. +type CategoryDeleteOne struct { + cd *CategoryDelete +} + +// Where appends a list predicates to the CategoryDelete builder. +func (cdo *CategoryDeleteOne) Where(ps ...predicate.Category) *CategoryDeleteOne { + cdo.cd.mutation.Where(ps...) + return cdo +} + +// Exec executes the deletion query. +func (cdo *CategoryDeleteOne) Exec(ctx context.Context) error { + n, err := cdo.cd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{category.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (cdo *CategoryDeleteOne) ExecX(ctx context.Context) { + if err := cdo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entgql/internal/todoglobalid/ent/category_query.go b/entgql/internal/todoglobalid/ent/category_query.go new file mode 100644 index 000000000..bf796ebb0 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/category_query.go @@ -0,0 +1,798 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "database/sql/driver" + "fmt" + "math" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/category" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/todo" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// CategoryQuery is the builder for querying Category entities. +type CategoryQuery struct { + config + ctx *QueryContext + order []category.OrderOption + inters []Interceptor + predicates []predicate.Category + withTodos *TodoQuery + withSubCategories *CategoryQuery + loadTotal []func(context.Context, []*Category) error + modifiers []func(*sql.Selector) + withNamedTodos map[string]*TodoQuery + withNamedSubCategories map[string]*CategoryQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the CategoryQuery builder. +func (cq *CategoryQuery) Where(ps ...predicate.Category) *CategoryQuery { + cq.predicates = append(cq.predicates, ps...) + return cq +} + +// Limit the number of records to be returned by this query. +func (cq *CategoryQuery) Limit(limit int) *CategoryQuery { + cq.ctx.Limit = &limit + return cq +} + +// Offset to start from. +func (cq *CategoryQuery) Offset(offset int) *CategoryQuery { + cq.ctx.Offset = &offset + return cq +} + +// 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 (cq *CategoryQuery) Unique(unique bool) *CategoryQuery { + cq.ctx.Unique = &unique + return cq +} + +// Order specifies how the records should be ordered. +func (cq *CategoryQuery) Order(o ...category.OrderOption) *CategoryQuery { + cq.order = append(cq.order, o...) + return cq +} + +// QueryTodos chains the current query on the "todos" edge. +func (cq *CategoryQuery) QueryTodos() *TodoQuery { + query := (&TodoClient{config: cq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := cq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := cq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(category.Table, category.FieldID, selector), + sqlgraph.To(todo.Table, todo.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, category.TodosTable, category.TodosColumn), + ) + fromU = sqlgraph.SetNeighbors(cq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QuerySubCategories chains the current query on the "sub_categories" edge. +func (cq *CategoryQuery) QuerySubCategories() *CategoryQuery { + query := (&CategoryClient{config: cq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := cq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := cq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(category.Table, category.FieldID, selector), + sqlgraph.To(category.Table, category.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, category.SubCategoriesTable, category.SubCategoriesPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(cq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Category entity from the query. +// Returns a *NotFoundError when no Category was found. +func (cq *CategoryQuery) First(ctx context.Context) (*Category, error) { + nodes, err := cq.Limit(1).All(setContextOp(ctx, cq.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{category.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (cq *CategoryQuery) FirstX(ctx context.Context) *Category { + node, err := cq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Category ID from the query. +// Returns a *NotFoundError when no Category ID was found. +func (cq *CategoryQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = cq.Limit(1).IDs(setContextOp(ctx, cq.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{category.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (cq *CategoryQuery) FirstIDX(ctx context.Context) int { + id, err := cq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Category entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Category entity is found. +// Returns a *NotFoundError when no Category entities are found. +func (cq *CategoryQuery) Only(ctx context.Context) (*Category, error) { + nodes, err := cq.Limit(2).All(setContextOp(ctx, cq.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{category.Label} + default: + return nil, &NotSingularError{category.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (cq *CategoryQuery) OnlyX(ctx context.Context) *Category { + node, err := cq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Category ID in the query. +// Returns a *NotSingularError when more than one Category ID is found. +// Returns a *NotFoundError when no entities are found. +func (cq *CategoryQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = cq.Limit(2).IDs(setContextOp(ctx, cq.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{category.Label} + default: + err = &NotSingularError{category.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (cq *CategoryQuery) OnlyIDX(ctx context.Context) int { + id, err := cq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Categories. +func (cq *CategoryQuery) All(ctx context.Context) ([]*Category, error) { + ctx = setContextOp(ctx, cq.ctx, ent.OpQueryAll) + if err := cq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Category, *CategoryQuery]() + return withInterceptors[[]*Category](ctx, cq, qr, cq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (cq *CategoryQuery) AllX(ctx context.Context) []*Category { + nodes, err := cq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Category IDs. +func (cq *CategoryQuery) IDs(ctx context.Context) (ids []int, err error) { + if cq.ctx.Unique == nil && cq.path != nil { + cq.Unique(true) + } + ctx = setContextOp(ctx, cq.ctx, ent.OpQueryIDs) + if err = cq.Select(category.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (cq *CategoryQuery) IDsX(ctx context.Context) []int { + ids, err := cq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (cq *CategoryQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, cq.ctx, ent.OpQueryCount) + if err := cq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, cq, querierCount[*CategoryQuery](), cq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (cq *CategoryQuery) CountX(ctx context.Context) int { + count, err := cq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (cq *CategoryQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, cq.ctx, ent.OpQueryExist) + switch _, err := cq.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 (cq *CategoryQuery) ExistX(ctx context.Context) bool { + exist, err := cq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the CategoryQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (cq *CategoryQuery) Clone() *CategoryQuery { + if cq == nil { + return nil + } + return &CategoryQuery{ + config: cq.config, + ctx: cq.ctx.Clone(), + order: append([]category.OrderOption{}, cq.order...), + inters: append([]Interceptor{}, cq.inters...), + predicates: append([]predicate.Category{}, cq.predicates...), + withTodos: cq.withTodos.Clone(), + withSubCategories: cq.withSubCategories.Clone(), + // clone intermediate query. + sql: cq.sql.Clone(), + path: cq.path, + modifiers: append([]func(*sql.Selector){}, cq.modifiers...), + } +} + +// WithTodos tells the query-builder to eager-load the nodes that are connected to +// the "todos" edge. The optional arguments are used to configure the query builder of the edge. +func (cq *CategoryQuery) WithTodos(opts ...func(*TodoQuery)) *CategoryQuery { + query := (&TodoClient{config: cq.config}).Query() + for _, opt := range opts { + opt(query) + } + cq.withTodos = query + return cq +} + +// WithSubCategories tells the query-builder to eager-load the nodes that are connected to +// the "sub_categories" edge. The optional arguments are used to configure the query builder of the edge. +func (cq *CategoryQuery) WithSubCategories(opts ...func(*CategoryQuery)) *CategoryQuery { + query := (&CategoryClient{config: cq.config}).Query() + for _, opt := range opts { + opt(query) + } + cq.withSubCategories = query + return cq +} + +// 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 { +// Text string `json:"text,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Category.Query(). +// GroupBy(category.FieldText). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (cq *CategoryQuery) GroupBy(field string, fields ...string) *CategoryGroupBy { + cq.ctx.Fields = append([]string{field}, fields...) + grbuild := &CategoryGroupBy{build: cq} + grbuild.flds = &cq.ctx.Fields + grbuild.label = category.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 { +// Text string `json:"text,omitempty"` +// } +// +// client.Category.Query(). +// Select(category.FieldText). +// Scan(ctx, &v) +func (cq *CategoryQuery) Select(fields ...string) *CategorySelect { + cq.ctx.Fields = append(cq.ctx.Fields, fields...) + sbuild := &CategorySelect{CategoryQuery: cq} + sbuild.label = category.Label + sbuild.flds, sbuild.scan = &cq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a CategorySelect configured with the given aggregations. +func (cq *CategoryQuery) Aggregate(fns ...AggregateFunc) *CategorySelect { + return cq.Select().Aggregate(fns...) +} + +func (cq *CategoryQuery) prepareQuery(ctx context.Context) error { + for _, inter := range cq.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, cq); err != nil { + return err + } + } + } + for _, f := range cq.ctx.Fields { + if !category.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if cq.path != nil { + prev, err := cq.path(ctx) + if err != nil { + return err + } + cq.sql = prev + } + return nil +} + +func (cq *CategoryQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Category, error) { + var ( + nodes = []*Category{} + _spec = cq.querySpec() + loadedTypes = [2]bool{ + cq.withTodos != nil, + cq.withSubCategories != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Category).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Category{config: cq.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(cq.modifiers) > 0 { + _spec.Modifiers = cq.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, cq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := cq.withTodos; query != nil { + if err := cq.loadTodos(ctx, query, nodes, + func(n *Category) { n.Edges.Todos = []*Todo{} }, + func(n *Category, e *Todo) { n.Edges.Todos = append(n.Edges.Todos, e) }); err != nil { + return nil, err + } + } + if query := cq.withSubCategories; query != nil { + if err := cq.loadSubCategories(ctx, query, nodes, + func(n *Category) { n.Edges.SubCategories = []*Category{} }, + func(n *Category, e *Category) { n.Edges.SubCategories = append(n.Edges.SubCategories, e) }); err != nil { + return nil, err + } + } + for name, query := range cq.withNamedTodos { + if err := cq.loadTodos(ctx, query, nodes, + func(n *Category) { n.appendNamedTodos(name) }, + func(n *Category, e *Todo) { n.appendNamedTodos(name, e) }); err != nil { + return nil, err + } + } + for name, query := range cq.withNamedSubCategories { + if err := cq.loadSubCategories(ctx, query, nodes, + func(n *Category) { n.appendNamedSubCategories(name) }, + func(n *Category, e *Category) { n.appendNamedSubCategories(name, e) }); err != nil { + return nil, err + } + } + for i := range cq.loadTotal { + if err := cq.loadTotal[i](ctx, nodes); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (cq *CategoryQuery) loadTodos(ctx context.Context, query *TodoQuery, nodes []*Category, init func(*Category), assign func(*Category, *Todo)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*Category) + 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 + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(todo.FieldCategoryID) + } + query.Where(predicate.Todo(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(category.TodosColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.CategoryID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "category_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} +func (cq *CategoryQuery) loadSubCategories(ctx context.Context, query *CategoryQuery, nodes []*Category, init func(*Category), assign func(*Category, *Category)) error { + edgeIDs := make([]driver.Value, len(nodes)) + byID := make(map[int]*Category) + nids := make(map[int]map[*Category]struct{}) + for i, node := range nodes { + edgeIDs[i] = node.ID + byID[node.ID] = node + if init != nil { + init(node) + } + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(category.SubCategoriesTable) + s.Join(joinT).On(s.C(category.FieldID), joinT.C(category.SubCategoriesPrimaryKey[1])) + s.Where(sql.InValues(joinT.C(category.SubCategoriesPrimaryKey[0]), edgeIDs...)) + columns := s.SelectedColumns() + s.Select(joinT.C(category.SubCategoriesPrimaryKey[0])) + s.AppendSelect(columns...) + s.SetDistinct(false) + }) + if err := query.prepareQuery(ctx); err != nil { + return err + } + qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) { + assign := spec.Assign + values := spec.ScanValues + spec.ScanValues = func(columns []string) ([]any, error) { + values, err := values(columns[1:]) + if err != nil { + return nil, err + } + return append([]any{new(sql.NullInt64)}, values...), nil + } + spec.Assign = func(columns []string, values []any) error { + outValue := int(values[0].(*sql.NullInt64).Int64) + inValue := int(values[1].(*sql.NullInt64).Int64) + if nids[inValue] == nil { + nids[inValue] = map[*Category]struct{}{byID[outValue]: {}} + return assign(columns[1:], values[1:]) + } + nids[inValue][byID[outValue]] = struct{}{} + return nil + } + }) + }) + neighbors, err := withInterceptors[[]*Category](ctx, query, qr, query.inters) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nids[n.ID] + if !ok { + return fmt.Errorf(`unexpected "sub_categories" node returned %v`, n.ID) + } + for kn := range nodes { + assign(kn, n) + } + } + return nil +} + +func (cq *CategoryQuery) sqlCount(ctx context.Context) (int, error) { + _spec := cq.querySpec() + if len(cq.modifiers) > 0 { + _spec.Modifiers = cq.modifiers + } + _spec.Node.Columns = cq.ctx.Fields + if len(cq.ctx.Fields) > 0 { + _spec.Unique = cq.ctx.Unique != nil && *cq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, cq.driver, _spec) +} + +func (cq *CategoryQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(category.Table, category.Columns, sqlgraph.NewFieldSpec(category.FieldID, field.TypeInt)) + _spec.From = cq.sql + if unique := cq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if cq.path != nil { + _spec.Unique = true + } + if fields := cq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, category.FieldID) + for i := range fields { + if fields[i] != category.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := cq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := cq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := cq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := cq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (cq *CategoryQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(cq.driver.Dialect()) + t1 := builder.Table(category.Table) + columns := cq.ctx.Fields + if len(columns) == 0 { + columns = category.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if cq.sql != nil { + selector = cq.sql + selector.Select(selector.Columns(columns...)...) + } + if cq.ctx.Unique != nil && *cq.ctx.Unique { + selector.Distinct() + } + for _, m := range cq.modifiers { + m(selector) + } + for _, p := range cq.predicates { + p(selector) + } + for _, p := range cq.order { + p(selector) + } + if offset := cq.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 := cq.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (cq *CategoryQuery) Modify(modifiers ...func(s *sql.Selector)) *CategorySelect { + cq.modifiers = append(cq.modifiers, modifiers...) + return cq.Select() +} + +// WithNamedTodos tells the query-builder to eager-load the nodes that are connected to the "todos" +// edge with the given name. The optional arguments are used to configure the query builder of the edge. +func (cq *CategoryQuery) WithNamedTodos(name string, opts ...func(*TodoQuery)) *CategoryQuery { + query := (&TodoClient{config: cq.config}).Query() + for _, opt := range opts { + opt(query) + } + if cq.withNamedTodos == nil { + cq.withNamedTodos = make(map[string]*TodoQuery) + } + cq.withNamedTodos[name] = query + return cq +} + +// WithNamedSubCategories tells the query-builder to eager-load the nodes that are connected to the "sub_categories" +// edge with the given name. The optional arguments are used to configure the query builder of the edge. +func (cq *CategoryQuery) WithNamedSubCategories(name string, opts ...func(*CategoryQuery)) *CategoryQuery { + query := (&CategoryClient{config: cq.config}).Query() + for _, opt := range opts { + opt(query) + } + if cq.withNamedSubCategories == nil { + cq.withNamedSubCategories = make(map[string]*CategoryQuery) + } + cq.withNamedSubCategories[name] = query + return cq +} + +// CategoryGroupBy is the group-by builder for Category entities. +type CategoryGroupBy struct { + selector + build *CategoryQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (cgb *CategoryGroupBy) Aggregate(fns ...AggregateFunc) *CategoryGroupBy { + cgb.fns = append(cgb.fns, fns...) + return cgb +} + +// Scan applies the selector query and scans the result into the given value. +func (cgb *CategoryGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, cgb.build.ctx, ent.OpQueryGroupBy) + if err := cgb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*CategoryQuery, *CategoryGroupBy](ctx, cgb.build, cgb, cgb.build.inters, v) +} + +func (cgb *CategoryGroupBy) sqlScan(ctx context.Context, root *CategoryQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(cgb.fns)) + for _, fn := range cgb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*cgb.flds)+len(cgb.fns)) + for _, f := range *cgb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*cgb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := cgb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// CategorySelect is the builder for selecting fields of Category entities. +type CategorySelect struct { + *CategoryQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (cs *CategorySelect) Aggregate(fns ...AggregateFunc) *CategorySelect { + cs.fns = append(cs.fns, fns...) + return cs +} + +// Scan applies the selector query and scans the result into the given value. +func (cs *CategorySelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, cs.ctx, ent.OpQuerySelect) + if err := cs.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*CategoryQuery, *CategorySelect](ctx, cs.CategoryQuery, cs, cs.inters, v) +} + +func (cs *CategorySelect) sqlScan(ctx context.Context, root *CategoryQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(cs.fns)) + for _, fn := range cs.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*cs.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 := cs.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (cs *CategorySelect) Modify(modifiers ...func(s *sql.Selector)) *CategorySelect { + cs.modifiers = append(cs.modifiers, modifiers...) + return cs +} diff --git a/entgql/internal/todoglobalid/ent/category_update.go b/entgql/internal/todoglobalid/ent/category_update.go new file mode 100644 index 000000000..15f9fd051 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/category_update.go @@ -0,0 +1,911 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/category" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/schema/schematype" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/todo" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/sql/sqljson" + "entgo.io/ent/schema/field" +) + +// CategoryUpdate is the builder for updating Category entities. +type CategoryUpdate struct { + config + hooks []Hook + mutation *CategoryMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the CategoryUpdate builder. +func (cu *CategoryUpdate) Where(ps ...predicate.Category) *CategoryUpdate { + cu.mutation.Where(ps...) + return cu +} + +// SetText sets the "text" field. +func (cu *CategoryUpdate) SetText(s string) *CategoryUpdate { + cu.mutation.SetText(s) + return cu +} + +// SetNillableText sets the "text" field if the given value is not nil. +func (cu *CategoryUpdate) SetNillableText(s *string) *CategoryUpdate { + if s != nil { + cu.SetText(*s) + } + return cu +} + +// SetStatus sets the "status" field. +func (cu *CategoryUpdate) SetStatus(c category.Status) *CategoryUpdate { + cu.mutation.SetStatus(c) + return cu +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (cu *CategoryUpdate) SetNillableStatus(c *category.Status) *CategoryUpdate { + if c != nil { + cu.SetStatus(*c) + } + return cu +} + +// SetConfig sets the "config" field. +func (cu *CategoryUpdate) SetConfig(sc *schematype.CategoryConfig) *CategoryUpdate { + cu.mutation.SetConfig(sc) + return cu +} + +// ClearConfig clears the value of the "config" field. +func (cu *CategoryUpdate) ClearConfig() *CategoryUpdate { + cu.mutation.ClearConfig() + return cu +} + +// SetTypes sets the "types" field. +func (cu *CategoryUpdate) SetTypes(st *schematype.CategoryTypes) *CategoryUpdate { + cu.mutation.SetTypes(st) + return cu +} + +// ClearTypes clears the value of the "types" field. +func (cu *CategoryUpdate) ClearTypes() *CategoryUpdate { + cu.mutation.ClearTypes() + return cu +} + +// SetDuration sets the "duration" field. +func (cu *CategoryUpdate) SetDuration(t time.Duration) *CategoryUpdate { + cu.mutation.ResetDuration() + cu.mutation.SetDuration(t) + return cu +} + +// SetNillableDuration sets the "duration" field if the given value is not nil. +func (cu *CategoryUpdate) SetNillableDuration(t *time.Duration) *CategoryUpdate { + if t != nil { + cu.SetDuration(*t) + } + return cu +} + +// AddDuration adds t to the "duration" field. +func (cu *CategoryUpdate) AddDuration(t time.Duration) *CategoryUpdate { + cu.mutation.AddDuration(t) + return cu +} + +// ClearDuration clears the value of the "duration" field. +func (cu *CategoryUpdate) ClearDuration() *CategoryUpdate { + cu.mutation.ClearDuration() + return cu +} + +// SetCount sets the "count" field. +func (cu *CategoryUpdate) SetCount(u uint64) *CategoryUpdate { + cu.mutation.ResetCount() + cu.mutation.SetCount(u) + return cu +} + +// SetNillableCount sets the "count" field if the given value is not nil. +func (cu *CategoryUpdate) SetNillableCount(u *uint64) *CategoryUpdate { + if u != nil { + cu.SetCount(*u) + } + return cu +} + +// AddCount adds u to the "count" field. +func (cu *CategoryUpdate) AddCount(u int64) *CategoryUpdate { + cu.mutation.AddCount(u) + return cu +} + +// ClearCount clears the value of the "count" field. +func (cu *CategoryUpdate) ClearCount() *CategoryUpdate { + cu.mutation.ClearCount() + return cu +} + +// SetStrings sets the "strings" field. +func (cu *CategoryUpdate) SetStrings(s []string) *CategoryUpdate { + cu.mutation.SetStrings(s) + return cu +} + +// AppendStrings appends s to the "strings" field. +func (cu *CategoryUpdate) AppendStrings(s []string) *CategoryUpdate { + cu.mutation.AppendStrings(s) + return cu +} + +// ClearStrings clears the value of the "strings" field. +func (cu *CategoryUpdate) ClearStrings() *CategoryUpdate { + cu.mutation.ClearStrings() + return cu +} + +// AddTodoIDs adds the "todos" edge to the Todo entity by IDs. +func (cu *CategoryUpdate) AddTodoIDs(ids ...int) *CategoryUpdate { + cu.mutation.AddTodoIDs(ids...) + return cu +} + +// AddTodos adds the "todos" edges to the Todo entity. +func (cu *CategoryUpdate) AddTodos(t ...*Todo) *CategoryUpdate { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return cu.AddTodoIDs(ids...) +} + +// AddSubCategoryIDs adds the "sub_categories" edge to the Category entity by IDs. +func (cu *CategoryUpdate) AddSubCategoryIDs(ids ...int) *CategoryUpdate { + cu.mutation.AddSubCategoryIDs(ids...) + return cu +} + +// AddSubCategories adds the "sub_categories" edges to the Category entity. +func (cu *CategoryUpdate) AddSubCategories(c ...*Category) *CategoryUpdate { + ids := make([]int, len(c)) + for i := range c { + ids[i] = c[i].ID + } + return cu.AddSubCategoryIDs(ids...) +} + +// Mutation returns the CategoryMutation object of the builder. +func (cu *CategoryUpdate) Mutation() *CategoryMutation { + return cu.mutation +} + +// ClearTodos clears all "todos" edges to the Todo entity. +func (cu *CategoryUpdate) ClearTodos() *CategoryUpdate { + cu.mutation.ClearTodos() + return cu +} + +// RemoveTodoIDs removes the "todos" edge to Todo entities by IDs. +func (cu *CategoryUpdate) RemoveTodoIDs(ids ...int) *CategoryUpdate { + cu.mutation.RemoveTodoIDs(ids...) + return cu +} + +// RemoveTodos removes "todos" edges to Todo entities. +func (cu *CategoryUpdate) RemoveTodos(t ...*Todo) *CategoryUpdate { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return cu.RemoveTodoIDs(ids...) +} + +// ClearSubCategories clears all "sub_categories" edges to the Category entity. +func (cu *CategoryUpdate) ClearSubCategories() *CategoryUpdate { + cu.mutation.ClearSubCategories() + return cu +} + +// RemoveSubCategoryIDs removes the "sub_categories" edge to Category entities by IDs. +func (cu *CategoryUpdate) RemoveSubCategoryIDs(ids ...int) *CategoryUpdate { + cu.mutation.RemoveSubCategoryIDs(ids...) + return cu +} + +// RemoveSubCategories removes "sub_categories" edges to Category entities. +func (cu *CategoryUpdate) RemoveSubCategories(c ...*Category) *CategoryUpdate { + ids := make([]int, len(c)) + for i := range c { + ids[i] = c[i].ID + } + return cu.RemoveSubCategoryIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (cu *CategoryUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, cu.sqlSave, cu.mutation, cu.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (cu *CategoryUpdate) SaveX(ctx context.Context) int { + affected, err := cu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (cu *CategoryUpdate) Exec(ctx context.Context) error { + _, err := cu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (cu *CategoryUpdate) ExecX(ctx context.Context) { + if err := cu.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (cu *CategoryUpdate) check() error { + if v, ok := cu.mutation.Text(); ok { + if err := category.TextValidator(v); err != nil { + return &ValidationError{Name: "text", err: fmt.Errorf(`ent: validator failed for field "Category.text": %w`, err)} + } + } + if v, ok := cu.mutation.Status(); ok { + if err := category.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "Category.status": %w`, err)} + } + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (cu *CategoryUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *CategoryUpdate { + cu.modifiers = append(cu.modifiers, modifiers...) + return cu +} + +func (cu *CategoryUpdate) sqlSave(ctx context.Context) (n int, err error) { + if err := cu.check(); err != nil { + return n, err + } + _spec := sqlgraph.NewUpdateSpec(category.Table, category.Columns, sqlgraph.NewFieldSpec(category.FieldID, field.TypeInt)) + if ps := cu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := cu.mutation.Text(); ok { + _spec.SetField(category.FieldText, field.TypeString, value) + } + if value, ok := cu.mutation.Status(); ok { + _spec.SetField(category.FieldStatus, field.TypeEnum, value) + } + if value, ok := cu.mutation.Config(); ok { + _spec.SetField(category.FieldConfig, field.TypeOther, value) + } + if cu.mutation.ConfigCleared() { + _spec.ClearField(category.FieldConfig, field.TypeOther) + } + if value, ok := cu.mutation.Types(); ok { + _spec.SetField(category.FieldTypes, field.TypeJSON, value) + } + if cu.mutation.TypesCleared() { + _spec.ClearField(category.FieldTypes, field.TypeJSON) + } + if value, ok := cu.mutation.Duration(); ok { + _spec.SetField(category.FieldDuration, field.TypeInt64, value) + } + if value, ok := cu.mutation.AddedDuration(); ok { + _spec.AddField(category.FieldDuration, field.TypeInt64, value) + } + if cu.mutation.DurationCleared() { + _spec.ClearField(category.FieldDuration, field.TypeInt64) + } + if value, ok := cu.mutation.Count(); ok { + _spec.SetField(category.FieldCount, field.TypeUint64, value) + } + if value, ok := cu.mutation.AddedCount(); ok { + _spec.AddField(category.FieldCount, field.TypeUint64, value) + } + if cu.mutation.CountCleared() { + _spec.ClearField(category.FieldCount, field.TypeUint64) + } + if value, ok := cu.mutation.Strings(); ok { + _spec.SetField(category.FieldStrings, field.TypeJSON, value) + } + if value, ok := cu.mutation.AppendedStrings(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, category.FieldStrings, value) + }) + } + if cu.mutation.StringsCleared() { + _spec.ClearField(category.FieldStrings, field.TypeJSON) + } + if cu.mutation.TodosCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: category.TodosTable, + Columns: []string{category.TodosColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := cu.mutation.RemovedTodosIDs(); len(nodes) > 0 && !cu.mutation.TodosCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: category.TodosTable, + Columns: []string{category.TodosColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(todo.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 := cu.mutation.TodosIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: category.TodosTable, + Columns: []string{category.TodosColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if cu.mutation.SubCategoriesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: category.SubCategoriesTable, + Columns: category.SubCategoriesPrimaryKey, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(category.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := cu.mutation.RemovedSubCategoriesIDs(); len(nodes) > 0 && !cu.mutation.SubCategoriesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: category.SubCategoriesTable, + Columns: category.SubCategoriesPrimaryKey, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(category.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 := cu.mutation.SubCategoriesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: category.SubCategoriesTable, + Columns: category.SubCategoriesPrimaryKey, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(category.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(cu.modifiers...) + if n, err = sqlgraph.UpdateNodes(ctx, cu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{category.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + cu.mutation.done = true + return n, nil +} + +// CategoryUpdateOne is the builder for updating a single Category entity. +type CategoryUpdateOne struct { + config + fields []string + hooks []Hook + mutation *CategoryMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetText sets the "text" field. +func (cuo *CategoryUpdateOne) SetText(s string) *CategoryUpdateOne { + cuo.mutation.SetText(s) + return cuo +} + +// SetNillableText sets the "text" field if the given value is not nil. +func (cuo *CategoryUpdateOne) SetNillableText(s *string) *CategoryUpdateOne { + if s != nil { + cuo.SetText(*s) + } + return cuo +} + +// SetStatus sets the "status" field. +func (cuo *CategoryUpdateOne) SetStatus(c category.Status) *CategoryUpdateOne { + cuo.mutation.SetStatus(c) + return cuo +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (cuo *CategoryUpdateOne) SetNillableStatus(c *category.Status) *CategoryUpdateOne { + if c != nil { + cuo.SetStatus(*c) + } + return cuo +} + +// SetConfig sets the "config" field. +func (cuo *CategoryUpdateOne) SetConfig(sc *schematype.CategoryConfig) *CategoryUpdateOne { + cuo.mutation.SetConfig(sc) + return cuo +} + +// ClearConfig clears the value of the "config" field. +func (cuo *CategoryUpdateOne) ClearConfig() *CategoryUpdateOne { + cuo.mutation.ClearConfig() + return cuo +} + +// SetTypes sets the "types" field. +func (cuo *CategoryUpdateOne) SetTypes(st *schematype.CategoryTypes) *CategoryUpdateOne { + cuo.mutation.SetTypes(st) + return cuo +} + +// ClearTypes clears the value of the "types" field. +func (cuo *CategoryUpdateOne) ClearTypes() *CategoryUpdateOne { + cuo.mutation.ClearTypes() + return cuo +} + +// SetDuration sets the "duration" field. +func (cuo *CategoryUpdateOne) SetDuration(t time.Duration) *CategoryUpdateOne { + cuo.mutation.ResetDuration() + cuo.mutation.SetDuration(t) + return cuo +} + +// SetNillableDuration sets the "duration" field if the given value is not nil. +func (cuo *CategoryUpdateOne) SetNillableDuration(t *time.Duration) *CategoryUpdateOne { + if t != nil { + cuo.SetDuration(*t) + } + return cuo +} + +// AddDuration adds t to the "duration" field. +func (cuo *CategoryUpdateOne) AddDuration(t time.Duration) *CategoryUpdateOne { + cuo.mutation.AddDuration(t) + return cuo +} + +// ClearDuration clears the value of the "duration" field. +func (cuo *CategoryUpdateOne) ClearDuration() *CategoryUpdateOne { + cuo.mutation.ClearDuration() + return cuo +} + +// SetCount sets the "count" field. +func (cuo *CategoryUpdateOne) SetCount(u uint64) *CategoryUpdateOne { + cuo.mutation.ResetCount() + cuo.mutation.SetCount(u) + return cuo +} + +// SetNillableCount sets the "count" field if the given value is not nil. +func (cuo *CategoryUpdateOne) SetNillableCount(u *uint64) *CategoryUpdateOne { + if u != nil { + cuo.SetCount(*u) + } + return cuo +} + +// AddCount adds u to the "count" field. +func (cuo *CategoryUpdateOne) AddCount(u int64) *CategoryUpdateOne { + cuo.mutation.AddCount(u) + return cuo +} + +// ClearCount clears the value of the "count" field. +func (cuo *CategoryUpdateOne) ClearCount() *CategoryUpdateOne { + cuo.mutation.ClearCount() + return cuo +} + +// SetStrings sets the "strings" field. +func (cuo *CategoryUpdateOne) SetStrings(s []string) *CategoryUpdateOne { + cuo.mutation.SetStrings(s) + return cuo +} + +// AppendStrings appends s to the "strings" field. +func (cuo *CategoryUpdateOne) AppendStrings(s []string) *CategoryUpdateOne { + cuo.mutation.AppendStrings(s) + return cuo +} + +// ClearStrings clears the value of the "strings" field. +func (cuo *CategoryUpdateOne) ClearStrings() *CategoryUpdateOne { + cuo.mutation.ClearStrings() + return cuo +} + +// AddTodoIDs adds the "todos" edge to the Todo entity by IDs. +func (cuo *CategoryUpdateOne) AddTodoIDs(ids ...int) *CategoryUpdateOne { + cuo.mutation.AddTodoIDs(ids...) + return cuo +} + +// AddTodos adds the "todos" edges to the Todo entity. +func (cuo *CategoryUpdateOne) AddTodos(t ...*Todo) *CategoryUpdateOne { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return cuo.AddTodoIDs(ids...) +} + +// AddSubCategoryIDs adds the "sub_categories" edge to the Category entity by IDs. +func (cuo *CategoryUpdateOne) AddSubCategoryIDs(ids ...int) *CategoryUpdateOne { + cuo.mutation.AddSubCategoryIDs(ids...) + return cuo +} + +// AddSubCategories adds the "sub_categories" edges to the Category entity. +func (cuo *CategoryUpdateOne) AddSubCategories(c ...*Category) *CategoryUpdateOne { + ids := make([]int, len(c)) + for i := range c { + ids[i] = c[i].ID + } + return cuo.AddSubCategoryIDs(ids...) +} + +// Mutation returns the CategoryMutation object of the builder. +func (cuo *CategoryUpdateOne) Mutation() *CategoryMutation { + return cuo.mutation +} + +// ClearTodos clears all "todos" edges to the Todo entity. +func (cuo *CategoryUpdateOne) ClearTodos() *CategoryUpdateOne { + cuo.mutation.ClearTodos() + return cuo +} + +// RemoveTodoIDs removes the "todos" edge to Todo entities by IDs. +func (cuo *CategoryUpdateOne) RemoveTodoIDs(ids ...int) *CategoryUpdateOne { + cuo.mutation.RemoveTodoIDs(ids...) + return cuo +} + +// RemoveTodos removes "todos" edges to Todo entities. +func (cuo *CategoryUpdateOne) RemoveTodos(t ...*Todo) *CategoryUpdateOne { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return cuo.RemoveTodoIDs(ids...) +} + +// ClearSubCategories clears all "sub_categories" edges to the Category entity. +func (cuo *CategoryUpdateOne) ClearSubCategories() *CategoryUpdateOne { + cuo.mutation.ClearSubCategories() + return cuo +} + +// RemoveSubCategoryIDs removes the "sub_categories" edge to Category entities by IDs. +func (cuo *CategoryUpdateOne) RemoveSubCategoryIDs(ids ...int) *CategoryUpdateOne { + cuo.mutation.RemoveSubCategoryIDs(ids...) + return cuo +} + +// RemoveSubCategories removes "sub_categories" edges to Category entities. +func (cuo *CategoryUpdateOne) RemoveSubCategories(c ...*Category) *CategoryUpdateOne { + ids := make([]int, len(c)) + for i := range c { + ids[i] = c[i].ID + } + return cuo.RemoveSubCategoryIDs(ids...) +} + +// Where appends a list predicates to the CategoryUpdate builder. +func (cuo *CategoryUpdateOne) Where(ps ...predicate.Category) *CategoryUpdateOne { + cuo.mutation.Where(ps...) + return cuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (cuo *CategoryUpdateOne) Select(field string, fields ...string) *CategoryUpdateOne { + cuo.fields = append([]string{field}, fields...) + return cuo +} + +// Save executes the query and returns the updated Category entity. +func (cuo *CategoryUpdateOne) Save(ctx context.Context) (*Category, error) { + return withHooks(ctx, cuo.sqlSave, cuo.mutation, cuo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (cuo *CategoryUpdateOne) SaveX(ctx context.Context) *Category { + node, err := cuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (cuo *CategoryUpdateOne) Exec(ctx context.Context) error { + _, err := cuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (cuo *CategoryUpdateOne) ExecX(ctx context.Context) { + if err := cuo.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (cuo *CategoryUpdateOne) check() error { + if v, ok := cuo.mutation.Text(); ok { + if err := category.TextValidator(v); err != nil { + return &ValidationError{Name: "text", err: fmt.Errorf(`ent: validator failed for field "Category.text": %w`, err)} + } + } + if v, ok := cuo.mutation.Status(); ok { + if err := category.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "Category.status": %w`, err)} + } + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (cuo *CategoryUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *CategoryUpdateOne { + cuo.modifiers = append(cuo.modifiers, modifiers...) + return cuo +} + +func (cuo *CategoryUpdateOne) sqlSave(ctx context.Context) (_node *Category, err error) { + if err := cuo.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(category.Table, category.Columns, sqlgraph.NewFieldSpec(category.FieldID, field.TypeInt)) + id, ok := cuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Category.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := cuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, category.FieldID) + for _, f := range fields { + if !category.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != category.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := cuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := cuo.mutation.Text(); ok { + _spec.SetField(category.FieldText, field.TypeString, value) + } + if value, ok := cuo.mutation.Status(); ok { + _spec.SetField(category.FieldStatus, field.TypeEnum, value) + } + if value, ok := cuo.mutation.Config(); ok { + _spec.SetField(category.FieldConfig, field.TypeOther, value) + } + if cuo.mutation.ConfigCleared() { + _spec.ClearField(category.FieldConfig, field.TypeOther) + } + if value, ok := cuo.mutation.Types(); ok { + _spec.SetField(category.FieldTypes, field.TypeJSON, value) + } + if cuo.mutation.TypesCleared() { + _spec.ClearField(category.FieldTypes, field.TypeJSON) + } + if value, ok := cuo.mutation.Duration(); ok { + _spec.SetField(category.FieldDuration, field.TypeInt64, value) + } + if value, ok := cuo.mutation.AddedDuration(); ok { + _spec.AddField(category.FieldDuration, field.TypeInt64, value) + } + if cuo.mutation.DurationCleared() { + _spec.ClearField(category.FieldDuration, field.TypeInt64) + } + if value, ok := cuo.mutation.Count(); ok { + _spec.SetField(category.FieldCount, field.TypeUint64, value) + } + if value, ok := cuo.mutation.AddedCount(); ok { + _spec.AddField(category.FieldCount, field.TypeUint64, value) + } + if cuo.mutation.CountCleared() { + _spec.ClearField(category.FieldCount, field.TypeUint64) + } + if value, ok := cuo.mutation.Strings(); ok { + _spec.SetField(category.FieldStrings, field.TypeJSON, value) + } + if value, ok := cuo.mutation.AppendedStrings(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, category.FieldStrings, value) + }) + } + if cuo.mutation.StringsCleared() { + _spec.ClearField(category.FieldStrings, field.TypeJSON) + } + if cuo.mutation.TodosCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: category.TodosTable, + Columns: []string{category.TodosColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := cuo.mutation.RemovedTodosIDs(); len(nodes) > 0 && !cuo.mutation.TodosCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: category.TodosTable, + Columns: []string{category.TodosColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(todo.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 := cuo.mutation.TodosIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: category.TodosTable, + Columns: []string{category.TodosColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if cuo.mutation.SubCategoriesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: category.SubCategoriesTable, + Columns: category.SubCategoriesPrimaryKey, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(category.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := cuo.mutation.RemovedSubCategoriesIDs(); len(nodes) > 0 && !cuo.mutation.SubCategoriesCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: category.SubCategoriesTable, + Columns: category.SubCategoriesPrimaryKey, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(category.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 := cuo.mutation.SubCategoriesIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: category.SubCategoriesTable, + Columns: category.SubCategoriesPrimaryKey, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(category.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(cuo.modifiers...) + _node = &Category{config: cuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, cuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{category.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + cuo.mutation.done = true + return _node, nil +} diff --git a/entgql/internal/todoglobalid/ent/client.go b/entgql/internal/todoglobalid/ent/client.go new file mode 100644 index 000000000..82de99c31 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/client.go @@ -0,0 +1,1876 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "log" + "reflect" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/migrate" + "entgo.io/ent" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/billproduct" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/category" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/friendship" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/group" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/onetomany" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/project" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/todo" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/user" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/verysecret" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/workspace" + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// Client is the client that holds all ent builders. +type Client struct { + config + // Schema is the client for creating, migrating and dropping schema. + Schema *migrate.Schema + // BillProduct is the client for interacting with the BillProduct builders. + BillProduct *BillProductClient + // Category is the client for interacting with the Category builders. + Category *CategoryClient + // Friendship is the client for interacting with the Friendship builders. + Friendship *FriendshipClient + // Group is the client for interacting with the Group builders. + Group *GroupClient + // OneToMany is the client for interacting with the OneToMany builders. + OneToMany *OneToManyClient + // Project is the client for interacting with the Project builders. + Project *ProjectClient + // Todo is the client for interacting with the Todo builders. + Todo *TodoClient + // User is the client for interacting with the User builders. + User *UserClient + // VerySecret is the client for interacting with the VerySecret builders. + VerySecret *VerySecretClient + // Workspace is the client for interacting with the Workspace builders. + Workspace *WorkspaceClient +} + +// NewClient creates a new client configured with the given options. +func NewClient(opts ...Option) *Client { + client := &Client{config: newConfig(opts...)} + client.init() + return client +} + +func (c *Client) init() { + c.Schema = migrate.NewSchema(c.driver) + c.BillProduct = NewBillProductClient(c.config) + c.Category = NewCategoryClient(c.config) + c.Friendship = NewFriendshipClient(c.config) + c.Group = NewGroupClient(c.config) + c.OneToMany = NewOneToManyClient(c.config) + c.Project = NewProjectClient(c.config) + c.Todo = NewTodoClient(c.config) + c.User = NewUserClient(c.config) + c.VerySecret = NewVerySecretClient(c.config) + c.Workspace = NewWorkspaceClient(c.config) +} + +type ( + // config is the configuration for the client and its builder. + config struct { + // driver used for executing database requests. + driver dialect.Driver + // debug enable a debug logging. + debug bool + // log used for logging on debug mode. + log func(...any) + // hooks to execute on mutations. + hooks *hooks + // interceptors to execute on queries. + inters *inters + } + // Option function to configure the client. + Option func(*config) +) + +// newConfig creates a new config for the client. +func newConfig(opts ...Option) config { + cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}} + cfg.options(opts...) + return cfg +} + +// options applies the options on the config object. +func (c *config) options(opts ...Option) { + for _, opt := range opts { + opt(c) + } + if c.debug { + c.driver = dialect.Debug(c.driver, c.log) + } +} + +// Debug enables debug logging on the ent.Driver. +func Debug() Option { + return func(c *config) { + c.debug = true + } +} + +// Log sets the logging function for debug mode. +func Log(fn func(...any)) Option { + return func(c *config) { + c.log = fn + } +} + +// Driver configures the client driver. +func Driver(driver dialect.Driver) Option { + return func(c *config) { + c.driver = driver + } +} + +// Open opens a database/sql.DB specified by the driver name and +// the data source name, and returns a new client attached to it. +// Optional parameters can be added for configuring the client. +func Open(driverName, dataSourceName string, options ...Option) (*Client, error) { + switch driverName { + case dialect.MySQL, dialect.Postgres, dialect.SQLite: + drv, err := sql.Open(driverName, dataSourceName) + if err != nil { + return nil, err + } + return NewClient(append(options, Driver(drv))...), nil + default: + return nil, fmt.Errorf("unsupported driver: %q", driverName) + } +} + +// ErrTxStarted is returned when trying to start a new transaction from a transactional client. +var ErrTxStarted = errors.New("ent: cannot start a transaction within a transaction") + +// Tx returns a new transactional client. The provided context +// is used until the transaction is committed or rolled back. +func (c *Client) Tx(ctx context.Context) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, ErrTxStarted + } + tx, err := newTx(ctx, c.driver) + if err != nil { + return nil, fmt.Errorf("ent: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = tx + return &Tx{ + ctx: ctx, + config: cfg, + BillProduct: NewBillProductClient(cfg), + Category: NewCategoryClient(cfg), + Friendship: NewFriendshipClient(cfg), + Group: NewGroupClient(cfg), + OneToMany: NewOneToManyClient(cfg), + Project: NewProjectClient(cfg), + Todo: NewTodoClient(cfg), + User: NewUserClient(cfg), + VerySecret: NewVerySecretClient(cfg), + Workspace: NewWorkspaceClient(cfg), + }, nil +} + +// BeginTx returns a transactional client with specified options. +func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) { + if _, ok := c.driver.(*txDriver); ok { + return nil, errors.New("ent: cannot start a transaction within a transaction") + } + tx, err := c.driver.(interface { + BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error) + }).BeginTx(ctx, opts) + if err != nil { + return nil, fmt.Errorf("ent: starting a transaction: %w", err) + } + cfg := c.config + cfg.driver = &txDriver{tx: tx, drv: c.driver} + return &Tx{ + ctx: ctx, + config: cfg, + BillProduct: NewBillProductClient(cfg), + Category: NewCategoryClient(cfg), + Friendship: NewFriendshipClient(cfg), + Group: NewGroupClient(cfg), + OneToMany: NewOneToManyClient(cfg), + Project: NewProjectClient(cfg), + Todo: NewTodoClient(cfg), + User: NewUserClient(cfg), + VerySecret: NewVerySecretClient(cfg), + Workspace: NewWorkspaceClient(cfg), + }, nil +} + +// Debug returns a new debug-client. It's used to get verbose logging on specific operations. +// +// client.Debug(). +// BillProduct. +// Query(). +// Count(ctx) +func (c *Client) Debug() *Client { + if c.debug { + return c + } + cfg := c.config + cfg.driver = dialect.Debug(c.driver, c.log) + client := &Client{config: cfg} + client.init() + return client +} + +// Close closes the database connection and prevents new queries from starting. +func (c *Client) Close() error { + return c.driver.Close() +} + +// 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) { + for _, n := range []interface{ Use(...Hook) }{ + c.BillProduct, c.Category, c.Friendship, c.Group, c.OneToMany, c.Project, + c.Todo, c.User, c.VerySecret, c.Workspace, + } { + n.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) { + for _, n := range []interface{ Intercept(...Interceptor) }{ + c.BillProduct, c.Category, c.Friendship, c.Group, c.OneToMany, c.Project, + c.Todo, c.User, c.VerySecret, c.Workspace, + } { + n.Intercept(interceptors...) + } +} + +// Mutate implements the ent.Mutator interface. +func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { + switch m := m.(type) { + case *BillProductMutation: + return c.BillProduct.mutate(ctx, m) + case *CategoryMutation: + return c.Category.mutate(ctx, m) + case *FriendshipMutation: + return c.Friendship.mutate(ctx, m) + case *GroupMutation: + return c.Group.mutate(ctx, m) + case *OneToManyMutation: + return c.OneToMany.mutate(ctx, m) + case *ProjectMutation: + return c.Project.mutate(ctx, m) + case *TodoMutation: + return c.Todo.mutate(ctx, m) + case *UserMutation: + return c.User.mutate(ctx, m) + case *VerySecretMutation: + return c.VerySecret.mutate(ctx, m) + case *WorkspaceMutation: + return c.Workspace.mutate(ctx, m) + default: + return nil, fmt.Errorf("ent: unknown mutation type %T", m) + } +} + +// BillProductClient is a client for the BillProduct schema. +type BillProductClient struct { + config +} + +// NewBillProductClient returns a client for the BillProduct from the given config. +func NewBillProductClient(c config) *BillProductClient { + return &BillProductClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `billproduct.Hooks(f(g(h())))`. +func (c *BillProductClient) Use(hooks ...Hook) { + c.hooks.BillProduct = append(c.hooks.BillProduct, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `billproduct.Intercept(f(g(h())))`. +func (c *BillProductClient) Intercept(interceptors ...Interceptor) { + c.inters.BillProduct = append(c.inters.BillProduct, interceptors...) +} + +// Create returns a builder for creating a BillProduct entity. +func (c *BillProductClient) Create() *BillProductCreate { + mutation := newBillProductMutation(c.config, OpCreate) + return &BillProductCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of BillProduct entities. +func (c *BillProductClient) CreateBulk(builders ...*BillProductCreate) *BillProductCreateBulk { + return &BillProductCreateBulk{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 *BillProductClient) MapCreateBulk(slice any, setFunc func(*BillProductCreate, int)) *BillProductCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &BillProductCreateBulk{err: fmt.Errorf("calling to BillProductClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*BillProductCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &BillProductCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for BillProduct. +func (c *BillProductClient) Update() *BillProductUpdate { + mutation := newBillProductMutation(c.config, OpUpdate) + return &BillProductUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *BillProductClient) UpdateOne(bp *BillProduct) *BillProductUpdateOne { + mutation := newBillProductMutation(c.config, OpUpdateOne, withBillProduct(bp)) + return &BillProductUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *BillProductClient) UpdateOneID(id int) *BillProductUpdateOne { + mutation := newBillProductMutation(c.config, OpUpdateOne, withBillProductID(id)) + return &BillProductUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for BillProduct. +func (c *BillProductClient) Delete() *BillProductDelete { + mutation := newBillProductMutation(c.config, OpDelete) + return &BillProductDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *BillProductClient) DeleteOne(bp *BillProduct) *BillProductDeleteOne { + return c.DeleteOneID(bp.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *BillProductClient) DeleteOneID(id int) *BillProductDeleteOne { + builder := c.Delete().Where(billproduct.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &BillProductDeleteOne{builder} +} + +// Query returns a query builder for BillProduct. +func (c *BillProductClient) Query() *BillProductQuery { + return &BillProductQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeBillProduct}, + inters: c.Interceptors(), + } +} + +// Get returns a BillProduct entity by its id. +func (c *BillProductClient) Get(ctx context.Context, id int) (*BillProduct, error) { + return c.Query().Where(billproduct.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *BillProductClient) GetX(ctx context.Context, id int) *BillProduct { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *BillProductClient) Hooks() []Hook { + return c.hooks.BillProduct +} + +// Interceptors returns the client interceptors. +func (c *BillProductClient) Interceptors() []Interceptor { + return c.inters.BillProduct +} + +func (c *BillProductClient) mutate(ctx context.Context, m *BillProductMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&BillProductCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&BillProductUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&BillProductUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&BillProductDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown BillProduct mutation op: %q", m.Op()) + } +} + +// CategoryClient is a client for the Category schema. +type CategoryClient struct { + config +} + +// NewCategoryClient returns a client for the Category from the given config. +func NewCategoryClient(c config) *CategoryClient { + return &CategoryClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `category.Hooks(f(g(h())))`. +func (c *CategoryClient) Use(hooks ...Hook) { + c.hooks.Category = append(c.hooks.Category, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `category.Intercept(f(g(h())))`. +func (c *CategoryClient) Intercept(interceptors ...Interceptor) { + c.inters.Category = append(c.inters.Category, interceptors...) +} + +// Create returns a builder for creating a Category entity. +func (c *CategoryClient) Create() *CategoryCreate { + mutation := newCategoryMutation(c.config, OpCreate) + return &CategoryCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Category entities. +func (c *CategoryClient) CreateBulk(builders ...*CategoryCreate) *CategoryCreateBulk { + return &CategoryCreateBulk{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 *CategoryClient) MapCreateBulk(slice any, setFunc func(*CategoryCreate, int)) *CategoryCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &CategoryCreateBulk{err: fmt.Errorf("calling to CategoryClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*CategoryCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &CategoryCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Category. +func (c *CategoryClient) Update() *CategoryUpdate { + mutation := newCategoryMutation(c.config, OpUpdate) + return &CategoryUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *CategoryClient) UpdateOne(ca *Category) *CategoryUpdateOne { + mutation := newCategoryMutation(c.config, OpUpdateOne, withCategory(ca)) + return &CategoryUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *CategoryClient) UpdateOneID(id int) *CategoryUpdateOne { + mutation := newCategoryMutation(c.config, OpUpdateOne, withCategoryID(id)) + return &CategoryUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Category. +func (c *CategoryClient) Delete() *CategoryDelete { + mutation := newCategoryMutation(c.config, OpDelete) + return &CategoryDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *CategoryClient) DeleteOne(ca *Category) *CategoryDeleteOne { + return c.DeleteOneID(ca.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *CategoryClient) DeleteOneID(id int) *CategoryDeleteOne { + builder := c.Delete().Where(category.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &CategoryDeleteOne{builder} +} + +// Query returns a query builder for Category. +func (c *CategoryClient) Query() *CategoryQuery { + return &CategoryQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeCategory}, + inters: c.Interceptors(), + } +} + +// Get returns a Category entity by its id. +func (c *CategoryClient) Get(ctx context.Context, id int) (*Category, error) { + return c.Query().Where(category.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *CategoryClient) GetX(ctx context.Context, id int) *Category { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryTodos queries the todos edge of a Category. +func (c *CategoryClient) QueryTodos(ca *Category) *TodoQuery { + query := (&TodoClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := ca.ID + step := sqlgraph.NewStep( + sqlgraph.From(category.Table, category.FieldID, id), + sqlgraph.To(todo.Table, todo.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, category.TodosTable, category.TodosColumn), + ) + fromV = sqlgraph.Neighbors(ca.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySubCategories queries the sub_categories edge of a Category. +func (c *CategoryClient) QuerySubCategories(ca *Category) *CategoryQuery { + query := (&CategoryClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := ca.ID + step := sqlgraph.NewStep( + sqlgraph.From(category.Table, category.FieldID, id), + sqlgraph.To(category.Table, category.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, category.SubCategoriesTable, category.SubCategoriesPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(ca.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *CategoryClient) Hooks() []Hook { + return c.hooks.Category +} + +// Interceptors returns the client interceptors. +func (c *CategoryClient) Interceptors() []Interceptor { + return c.inters.Category +} + +func (c *CategoryClient) mutate(ctx context.Context, m *CategoryMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&CategoryCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&CategoryUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&CategoryUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&CategoryDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Category mutation op: %q", m.Op()) + } +} + +// FriendshipClient is a client for the Friendship schema. +type FriendshipClient struct { + config +} + +// NewFriendshipClient returns a client for the Friendship from the given config. +func NewFriendshipClient(c config) *FriendshipClient { + return &FriendshipClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `friendship.Hooks(f(g(h())))`. +func (c *FriendshipClient) Use(hooks ...Hook) { + c.hooks.Friendship = append(c.hooks.Friendship, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `friendship.Intercept(f(g(h())))`. +func (c *FriendshipClient) Intercept(interceptors ...Interceptor) { + c.inters.Friendship = append(c.inters.Friendship, interceptors...) +} + +// Create returns a builder for creating a Friendship entity. +func (c *FriendshipClient) Create() *FriendshipCreate { + mutation := newFriendshipMutation(c.config, OpCreate) + return &FriendshipCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Friendship entities. +func (c *FriendshipClient) CreateBulk(builders ...*FriendshipCreate) *FriendshipCreateBulk { + return &FriendshipCreateBulk{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 *FriendshipClient) MapCreateBulk(slice any, setFunc func(*FriendshipCreate, int)) *FriendshipCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &FriendshipCreateBulk{err: fmt.Errorf("calling to FriendshipClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*FriendshipCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &FriendshipCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Friendship. +func (c *FriendshipClient) Update() *FriendshipUpdate { + mutation := newFriendshipMutation(c.config, OpUpdate) + return &FriendshipUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *FriendshipClient) UpdateOne(f *Friendship) *FriendshipUpdateOne { + mutation := newFriendshipMutation(c.config, OpUpdateOne, withFriendship(f)) + return &FriendshipUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *FriendshipClient) UpdateOneID(id int) *FriendshipUpdateOne { + mutation := newFriendshipMutation(c.config, OpUpdateOne, withFriendshipID(id)) + return &FriendshipUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Friendship. +func (c *FriendshipClient) Delete() *FriendshipDelete { + mutation := newFriendshipMutation(c.config, OpDelete) + return &FriendshipDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *FriendshipClient) DeleteOne(f *Friendship) *FriendshipDeleteOne { + return c.DeleteOneID(f.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *FriendshipClient) DeleteOneID(id int) *FriendshipDeleteOne { + builder := c.Delete().Where(friendship.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &FriendshipDeleteOne{builder} +} + +// Query returns a query builder for Friendship. +func (c *FriendshipClient) Query() *FriendshipQuery { + return &FriendshipQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeFriendship}, + inters: c.Interceptors(), + } +} + +// Get returns a Friendship entity by its id. +func (c *FriendshipClient) Get(ctx context.Context, id int) (*Friendship, error) { + return c.Query().Where(friendship.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *FriendshipClient) GetX(ctx context.Context, id int) *Friendship { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryUser queries the user edge of a Friendship. +func (c *FriendshipClient) QueryUser(f *Friendship) *UserQuery { + query := (&UserClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := f.ID + step := sqlgraph.NewStep( + sqlgraph.From(friendship.Table, friendship.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, friendship.UserTable, friendship.UserColumn), + ) + fromV = sqlgraph.Neighbors(f.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryFriend queries the friend edge of a Friendship. +func (c *FriendshipClient) QueryFriend(f *Friendship) *UserQuery { + query := (&UserClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := f.ID + step := sqlgraph.NewStep( + sqlgraph.From(friendship.Table, friendship.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, friendship.FriendTable, friendship.FriendColumn), + ) + fromV = sqlgraph.Neighbors(f.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *FriendshipClient) Hooks() []Hook { + return c.hooks.Friendship +} + +// Interceptors returns the client interceptors. +func (c *FriendshipClient) Interceptors() []Interceptor { + return c.inters.Friendship +} + +func (c *FriendshipClient) mutate(ctx context.Context, m *FriendshipMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&FriendshipCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&FriendshipUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&FriendshipUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&FriendshipDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Friendship mutation op: %q", m.Op()) + } +} + +// GroupClient is a client for the Group schema. +type GroupClient struct { + config +} + +// NewGroupClient returns a client for the Group from the given config. +func NewGroupClient(c config) *GroupClient { + return &GroupClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `group.Hooks(f(g(h())))`. +func (c *GroupClient) Use(hooks ...Hook) { + c.hooks.Group = append(c.hooks.Group, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `group.Intercept(f(g(h())))`. +func (c *GroupClient) Intercept(interceptors ...Interceptor) { + c.inters.Group = append(c.inters.Group, interceptors...) +} + +// Create returns a builder for creating a Group entity. +func (c *GroupClient) Create() *GroupCreate { + mutation := newGroupMutation(c.config, OpCreate) + return &GroupCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Group entities. +func (c *GroupClient) CreateBulk(builders ...*GroupCreate) *GroupCreateBulk { + return &GroupCreateBulk{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 *GroupClient) MapCreateBulk(slice any, setFunc func(*GroupCreate, int)) *GroupCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &GroupCreateBulk{err: fmt.Errorf("calling to GroupClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*GroupCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &GroupCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Group. +func (c *GroupClient) Update() *GroupUpdate { + mutation := newGroupMutation(c.config, OpUpdate) + return &GroupUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *GroupClient) UpdateOne(gr *Group) *GroupUpdateOne { + mutation := newGroupMutation(c.config, OpUpdateOne, withGroup(gr)) + return &GroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *GroupClient) UpdateOneID(id int) *GroupUpdateOne { + mutation := newGroupMutation(c.config, OpUpdateOne, withGroupID(id)) + return &GroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Group. +func (c *GroupClient) Delete() *GroupDelete { + mutation := newGroupMutation(c.config, OpDelete) + return &GroupDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *GroupClient) DeleteOne(gr *Group) *GroupDeleteOne { + return c.DeleteOneID(gr.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *GroupClient) DeleteOneID(id int) *GroupDeleteOne { + builder := c.Delete().Where(group.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &GroupDeleteOne{builder} +} + +// Query returns a query builder for Group. +func (c *GroupClient) Query() *GroupQuery { + return &GroupQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeGroup}, + inters: c.Interceptors(), + } +} + +// Get returns a Group entity by its id. +func (c *GroupClient) Get(ctx context.Context, id int) (*Group, error) { + return c.Query().Where(group.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *GroupClient) GetX(ctx context.Context, id int) *Group { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryUsers queries the users edge of a Group. +func (c *GroupClient) QueryUsers(gr *Group) *UserQuery { + query := (&UserClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := gr.ID + step := sqlgraph.NewStep( + sqlgraph.From(group.Table, group.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, group.UsersTable, group.UsersPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(gr.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *GroupClient) Hooks() []Hook { + return c.hooks.Group +} + +// Interceptors returns the client interceptors. +func (c *GroupClient) Interceptors() []Interceptor { + return c.inters.Group +} + +func (c *GroupClient) mutate(ctx context.Context, m *GroupMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&GroupCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&GroupUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&GroupUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&GroupDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Group mutation op: %q", m.Op()) + } +} + +// OneToManyClient is a client for the OneToMany schema. +type OneToManyClient struct { + config +} + +// NewOneToManyClient returns a client for the OneToMany from the given config. +func NewOneToManyClient(c config) *OneToManyClient { + return &OneToManyClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `onetomany.Hooks(f(g(h())))`. +func (c *OneToManyClient) Use(hooks ...Hook) { + c.hooks.OneToMany = append(c.hooks.OneToMany, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `onetomany.Intercept(f(g(h())))`. +func (c *OneToManyClient) Intercept(interceptors ...Interceptor) { + c.inters.OneToMany = append(c.inters.OneToMany, interceptors...) +} + +// Create returns a builder for creating a OneToMany entity. +func (c *OneToManyClient) Create() *OneToManyCreate { + mutation := newOneToManyMutation(c.config, OpCreate) + return &OneToManyCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of OneToMany entities. +func (c *OneToManyClient) CreateBulk(builders ...*OneToManyCreate) *OneToManyCreateBulk { + return &OneToManyCreateBulk{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 *OneToManyClient) MapCreateBulk(slice any, setFunc func(*OneToManyCreate, int)) *OneToManyCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &OneToManyCreateBulk{err: fmt.Errorf("calling to OneToManyClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*OneToManyCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &OneToManyCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for OneToMany. +func (c *OneToManyClient) Update() *OneToManyUpdate { + mutation := newOneToManyMutation(c.config, OpUpdate) + return &OneToManyUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *OneToManyClient) UpdateOne(otm *OneToMany) *OneToManyUpdateOne { + mutation := newOneToManyMutation(c.config, OpUpdateOne, withOneToMany(otm)) + return &OneToManyUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *OneToManyClient) UpdateOneID(id int) *OneToManyUpdateOne { + mutation := newOneToManyMutation(c.config, OpUpdateOne, withOneToManyID(id)) + return &OneToManyUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for OneToMany. +func (c *OneToManyClient) Delete() *OneToManyDelete { + mutation := newOneToManyMutation(c.config, OpDelete) + return &OneToManyDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *OneToManyClient) DeleteOne(otm *OneToMany) *OneToManyDeleteOne { + return c.DeleteOneID(otm.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *OneToManyClient) DeleteOneID(id int) *OneToManyDeleteOne { + builder := c.Delete().Where(onetomany.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &OneToManyDeleteOne{builder} +} + +// Query returns a query builder for OneToMany. +func (c *OneToManyClient) Query() *OneToManyQuery { + return &OneToManyQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeOneToMany}, + inters: c.Interceptors(), + } +} + +// Get returns a OneToMany entity by its id. +func (c *OneToManyClient) Get(ctx context.Context, id int) (*OneToMany, error) { + return c.Query().Where(onetomany.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *OneToManyClient) GetX(ctx context.Context, id int) *OneToMany { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryParent queries the parent edge of a OneToMany. +func (c *OneToManyClient) QueryParent(otm *OneToMany) *OneToManyQuery { + query := (&OneToManyClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := otm.ID + step := sqlgraph.NewStep( + sqlgraph.From(onetomany.Table, onetomany.FieldID, id), + sqlgraph.To(onetomany.Table, onetomany.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, onetomany.ParentTable, onetomany.ParentColumn), + ) + fromV = sqlgraph.Neighbors(otm.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChildren queries the children edge of a OneToMany. +func (c *OneToManyClient) QueryChildren(otm *OneToMany) *OneToManyQuery { + query := (&OneToManyClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := otm.ID + step := sqlgraph.NewStep( + sqlgraph.From(onetomany.Table, onetomany.FieldID, id), + sqlgraph.To(onetomany.Table, onetomany.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, onetomany.ChildrenTable, onetomany.ChildrenColumn), + ) + fromV = sqlgraph.Neighbors(otm.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *OneToManyClient) Hooks() []Hook { + return c.hooks.OneToMany +} + +// Interceptors returns the client interceptors. +func (c *OneToManyClient) Interceptors() []Interceptor { + return c.inters.OneToMany +} + +func (c *OneToManyClient) mutate(ctx context.Context, m *OneToManyMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&OneToManyCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&OneToManyUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&OneToManyUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&OneToManyDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown OneToMany mutation op: %q", m.Op()) + } +} + +// ProjectClient is a client for the Project schema. +type ProjectClient struct { + config +} + +// NewProjectClient returns a client for the Project from the given config. +func NewProjectClient(c config) *ProjectClient { + return &ProjectClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `project.Hooks(f(g(h())))`. +func (c *ProjectClient) Use(hooks ...Hook) { + c.hooks.Project = append(c.hooks.Project, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `project.Intercept(f(g(h())))`. +func (c *ProjectClient) Intercept(interceptors ...Interceptor) { + c.inters.Project = append(c.inters.Project, interceptors...) +} + +// Create returns a builder for creating a Project entity. +func (c *ProjectClient) Create() *ProjectCreate { + mutation := newProjectMutation(c.config, OpCreate) + return &ProjectCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Project entities. +func (c *ProjectClient) CreateBulk(builders ...*ProjectCreate) *ProjectCreateBulk { + return &ProjectCreateBulk{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 *ProjectClient) MapCreateBulk(slice any, setFunc func(*ProjectCreate, int)) *ProjectCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &ProjectCreateBulk{err: fmt.Errorf("calling to ProjectClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*ProjectCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &ProjectCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Project. +func (c *ProjectClient) Update() *ProjectUpdate { + mutation := newProjectMutation(c.config, OpUpdate) + return &ProjectUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *ProjectClient) UpdateOne(pr *Project) *ProjectUpdateOne { + mutation := newProjectMutation(c.config, OpUpdateOne, withProject(pr)) + return &ProjectUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *ProjectClient) UpdateOneID(id int) *ProjectUpdateOne { + mutation := newProjectMutation(c.config, OpUpdateOne, withProjectID(id)) + return &ProjectUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Project. +func (c *ProjectClient) Delete() *ProjectDelete { + mutation := newProjectMutation(c.config, OpDelete) + return &ProjectDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *ProjectClient) DeleteOne(pr *Project) *ProjectDeleteOne { + return c.DeleteOneID(pr.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *ProjectClient) DeleteOneID(id int) *ProjectDeleteOne { + builder := c.Delete().Where(project.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &ProjectDeleteOne{builder} +} + +// Query returns a query builder for Project. +func (c *ProjectClient) Query() *ProjectQuery { + return &ProjectQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeProject}, + inters: c.Interceptors(), + } +} + +// Get returns a Project entity by its id. +func (c *ProjectClient) Get(ctx context.Context, id int) (*Project, error) { + return c.Query().Where(project.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *ProjectClient) GetX(ctx context.Context, id int) *Project { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryTodos queries the todos edge of a Project. +func (c *ProjectClient) QueryTodos(pr *Project) *TodoQuery { + query := (&TodoClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := pr.ID + step := sqlgraph.NewStep( + sqlgraph.From(project.Table, project.FieldID, id), + sqlgraph.To(todo.Table, todo.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, project.TodosTable, project.TodosColumn), + ) + fromV = sqlgraph.Neighbors(pr.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *ProjectClient) Hooks() []Hook { + return c.hooks.Project +} + +// Interceptors returns the client interceptors. +func (c *ProjectClient) Interceptors() []Interceptor { + return c.inters.Project +} + +func (c *ProjectClient) mutate(ctx context.Context, m *ProjectMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&ProjectCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&ProjectUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&ProjectUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&ProjectDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Project mutation op: %q", m.Op()) + } +} + +// TodoClient is a client for the Todo schema. +type TodoClient struct { + config +} + +// NewTodoClient returns a client for the Todo from the given config. +func NewTodoClient(c config) *TodoClient { + return &TodoClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `todo.Hooks(f(g(h())))`. +func (c *TodoClient) Use(hooks ...Hook) { + c.hooks.Todo = append(c.hooks.Todo, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `todo.Intercept(f(g(h())))`. +func (c *TodoClient) Intercept(interceptors ...Interceptor) { + c.inters.Todo = append(c.inters.Todo, interceptors...) +} + +// Create returns a builder for creating a Todo entity. +func (c *TodoClient) Create() *TodoCreate { + mutation := newTodoMutation(c.config, OpCreate) + return &TodoCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Todo entities. +func (c *TodoClient) CreateBulk(builders ...*TodoCreate) *TodoCreateBulk { + return &TodoCreateBulk{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 *TodoClient) MapCreateBulk(slice any, setFunc func(*TodoCreate, int)) *TodoCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &TodoCreateBulk{err: fmt.Errorf("calling to TodoClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*TodoCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &TodoCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Todo. +func (c *TodoClient) Update() *TodoUpdate { + mutation := newTodoMutation(c.config, OpUpdate) + return &TodoUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *TodoClient) UpdateOne(t *Todo) *TodoUpdateOne { + mutation := newTodoMutation(c.config, OpUpdateOne, withTodo(t)) + return &TodoUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *TodoClient) UpdateOneID(id int) *TodoUpdateOne { + mutation := newTodoMutation(c.config, OpUpdateOne, withTodoID(id)) + return &TodoUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Todo. +func (c *TodoClient) Delete() *TodoDelete { + mutation := newTodoMutation(c.config, OpDelete) + return &TodoDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *TodoClient) DeleteOne(t *Todo) *TodoDeleteOne { + return c.DeleteOneID(t.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *TodoClient) DeleteOneID(id int) *TodoDeleteOne { + builder := c.Delete().Where(todo.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &TodoDeleteOne{builder} +} + +// Query returns a query builder for Todo. +func (c *TodoClient) Query() *TodoQuery { + return &TodoQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeTodo}, + inters: c.Interceptors(), + } +} + +// Get returns a Todo entity by its id. +func (c *TodoClient) Get(ctx context.Context, id int) (*Todo, error) { + return c.Query().Where(todo.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *TodoClient) GetX(ctx context.Context, id int) *Todo { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryParent queries the parent edge of a Todo. +func (c *TodoClient) QueryParent(t *Todo) *TodoQuery { + query := (&TodoClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := t.ID + step := sqlgraph.NewStep( + sqlgraph.From(todo.Table, todo.FieldID, id), + sqlgraph.To(todo.Table, todo.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, todo.ParentTable, todo.ParentColumn), + ) + fromV = sqlgraph.Neighbors(t.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryChildren queries the children edge of a Todo. +func (c *TodoClient) QueryChildren(t *Todo) *TodoQuery { + query := (&TodoClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := t.ID + step := sqlgraph.NewStep( + sqlgraph.From(todo.Table, todo.FieldID, id), + sqlgraph.To(todo.Table, todo.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, todo.ChildrenTable, todo.ChildrenColumn), + ) + fromV = sqlgraph.Neighbors(t.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryCategory queries the category edge of a Todo. +func (c *TodoClient) QueryCategory(t *Todo) *CategoryQuery { + query := (&CategoryClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := t.ID + step := sqlgraph.NewStep( + sqlgraph.From(todo.Table, todo.FieldID, id), + sqlgraph.To(category.Table, category.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, todo.CategoryTable, todo.CategoryColumn), + ) + fromV = sqlgraph.Neighbors(t.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QuerySecret queries the secret edge of a Todo. +func (c *TodoClient) QuerySecret(t *Todo) *VerySecretQuery { + query := (&VerySecretClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := t.ID + step := sqlgraph.NewStep( + sqlgraph.From(todo.Table, todo.FieldID, id), + sqlgraph.To(verysecret.Table, verysecret.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, todo.SecretTable, todo.SecretColumn), + ) + fromV = sqlgraph.Neighbors(t.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *TodoClient) Hooks() []Hook { + return c.hooks.Todo +} + +// Interceptors returns the client interceptors. +func (c *TodoClient) Interceptors() []Interceptor { + return c.inters.Todo +} + +func (c *TodoClient) mutate(ctx context.Context, m *TodoMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&TodoCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&TodoUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&TodoUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&TodoDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Todo mutation op: %q", m.Op()) + } +} + +// UserClient is a client for the User schema. +type UserClient struct { + config +} + +// NewUserClient returns a client for the User from the given config. +func NewUserClient(c config) *UserClient { + return &UserClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `user.Hooks(f(g(h())))`. +func (c *UserClient) Use(hooks ...Hook) { + c.hooks.User = append(c.hooks.User, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `user.Intercept(f(g(h())))`. +func (c *UserClient) Intercept(interceptors ...Interceptor) { + c.inters.User = append(c.inters.User, interceptors...) +} + +// Create returns a builder for creating a User entity. +func (c *UserClient) Create() *UserCreate { + mutation := newUserMutation(c.config, OpCreate) + return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of User entities. +func (c *UserClient) CreateBulk(builders ...*UserCreate) *UserCreateBulk { + return &UserCreateBulk{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 *UserClient) MapCreateBulk(slice any, setFunc func(*UserCreate, int)) *UserCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &UserCreateBulk{err: fmt.Errorf("calling to UserClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*UserCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &UserCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for User. +func (c *UserClient) Update() *UserUpdate { + mutation := newUserMutation(c.config, OpUpdate) + return &UserUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *UserClient) UpdateOne(u *User) *UserUpdateOne { + mutation := newUserMutation(c.config, OpUpdateOne, withUser(u)) + return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *UserClient) UpdateOneID(id int) *UserUpdateOne { + mutation := newUserMutation(c.config, OpUpdateOne, withUserID(id)) + return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for User. +func (c *UserClient) Delete() *UserDelete { + mutation := newUserMutation(c.config, OpDelete) + return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { + return c.DeleteOneID(u.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { + builder := c.Delete().Where(user.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &UserDeleteOne{builder} +} + +// Query returns a query builder for User. +func (c *UserClient) Query() *UserQuery { + return &UserQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeUser}, + inters: c.Interceptors(), + } +} + +// Get returns a User entity by its id. +func (c *UserClient) Get(ctx context.Context, id int) (*User, error) { + return c.Query().Where(user.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *UserClient) GetX(ctx context.Context, id int) *User { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// QueryGroups queries the groups edge of a User. +func (c *UserClient) QueryGroups(u *User) *GroupQuery { + query := (&GroupClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := u.ID + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, id), + sqlgraph.To(group.Table, group.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, user.GroupsTable, user.GroupsPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(u.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryFriends queries the friends edge of a User. +func (c *UserClient) QueryFriends(u *User) *UserQuery { + query := (&UserClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := u.ID + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, id), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, user.FriendsTable, user.FriendsPrimaryKey...), + ) + fromV = sqlgraph.Neighbors(u.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// QueryFriendships queries the friendships edge of a User. +func (c *UserClient) QueryFriendships(u *User) *FriendshipQuery { + query := (&FriendshipClient{config: c.config}).Query() + query.path = func(context.Context) (fromV *sql.Selector, _ error) { + id := u.ID + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, id), + sqlgraph.To(friendship.Table, friendship.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, user.FriendshipsTable, user.FriendshipsColumn), + ) + fromV = sqlgraph.Neighbors(u.driver.Dialect(), step) + return fromV, nil + } + return query +} + +// Hooks returns the client hooks. +func (c *UserClient) Hooks() []Hook { + return c.hooks.User +} + +// Interceptors returns the client interceptors. +func (c *UserClient) Interceptors() []Interceptor { + return c.inters.User +} + +func (c *UserClient) mutate(ctx context.Context, m *UserMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&UserCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&UserUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&UserDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown User mutation op: %q", m.Op()) + } +} + +// VerySecretClient is a client for the VerySecret schema. +type VerySecretClient struct { + config +} + +// NewVerySecretClient returns a client for the VerySecret from the given config. +func NewVerySecretClient(c config) *VerySecretClient { + return &VerySecretClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `verysecret.Hooks(f(g(h())))`. +func (c *VerySecretClient) Use(hooks ...Hook) { + c.hooks.VerySecret = append(c.hooks.VerySecret, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `verysecret.Intercept(f(g(h())))`. +func (c *VerySecretClient) Intercept(interceptors ...Interceptor) { + c.inters.VerySecret = append(c.inters.VerySecret, interceptors...) +} + +// Create returns a builder for creating a VerySecret entity. +func (c *VerySecretClient) Create() *VerySecretCreate { + mutation := newVerySecretMutation(c.config, OpCreate) + return &VerySecretCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of VerySecret entities. +func (c *VerySecretClient) CreateBulk(builders ...*VerySecretCreate) *VerySecretCreateBulk { + return &VerySecretCreateBulk{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 *VerySecretClient) MapCreateBulk(slice any, setFunc func(*VerySecretCreate, int)) *VerySecretCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &VerySecretCreateBulk{err: fmt.Errorf("calling to VerySecretClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*VerySecretCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &VerySecretCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for VerySecret. +func (c *VerySecretClient) Update() *VerySecretUpdate { + mutation := newVerySecretMutation(c.config, OpUpdate) + return &VerySecretUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *VerySecretClient) UpdateOne(vs *VerySecret) *VerySecretUpdateOne { + mutation := newVerySecretMutation(c.config, OpUpdateOne, withVerySecret(vs)) + return &VerySecretUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *VerySecretClient) UpdateOneID(id int) *VerySecretUpdateOne { + mutation := newVerySecretMutation(c.config, OpUpdateOne, withVerySecretID(id)) + return &VerySecretUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for VerySecret. +func (c *VerySecretClient) Delete() *VerySecretDelete { + mutation := newVerySecretMutation(c.config, OpDelete) + return &VerySecretDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *VerySecretClient) DeleteOne(vs *VerySecret) *VerySecretDeleteOne { + return c.DeleteOneID(vs.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *VerySecretClient) DeleteOneID(id int) *VerySecretDeleteOne { + builder := c.Delete().Where(verysecret.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &VerySecretDeleteOne{builder} +} + +// Query returns a query builder for VerySecret. +func (c *VerySecretClient) Query() *VerySecretQuery { + return &VerySecretQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeVerySecret}, + inters: c.Interceptors(), + } +} + +// Get returns a VerySecret entity by its id. +func (c *VerySecretClient) Get(ctx context.Context, id int) (*VerySecret, error) { + return c.Query().Where(verysecret.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *VerySecretClient) GetX(ctx context.Context, id int) *VerySecret { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *VerySecretClient) Hooks() []Hook { + return c.hooks.VerySecret +} + +// Interceptors returns the client interceptors. +func (c *VerySecretClient) Interceptors() []Interceptor { + return c.inters.VerySecret +} + +func (c *VerySecretClient) mutate(ctx context.Context, m *VerySecretMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&VerySecretCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&VerySecretUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&VerySecretUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&VerySecretDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown VerySecret mutation op: %q", m.Op()) + } +} + +// WorkspaceClient is a client for the Workspace schema. +type WorkspaceClient struct { + config +} + +// NewWorkspaceClient returns a client for the Workspace from the given config. +func NewWorkspaceClient(c config) *WorkspaceClient { + return &WorkspaceClient{config: c} +} + +// Use adds a list of mutation hooks to the hooks stack. +// A call to `Use(f, g, h)` equals to `workspace.Hooks(f(g(h())))`. +func (c *WorkspaceClient) Use(hooks ...Hook) { + c.hooks.Workspace = append(c.hooks.Workspace, hooks...) +} + +// Intercept adds a list of query interceptors to the interceptors stack. +// A call to `Intercept(f, g, h)` equals to `workspace.Intercept(f(g(h())))`. +func (c *WorkspaceClient) Intercept(interceptors ...Interceptor) { + c.inters.Workspace = append(c.inters.Workspace, interceptors...) +} + +// Create returns a builder for creating a Workspace entity. +func (c *WorkspaceClient) Create() *WorkspaceCreate { + mutation := newWorkspaceMutation(c.config, OpCreate) + return &WorkspaceCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// CreateBulk returns a builder for creating a bulk of Workspace entities. +func (c *WorkspaceClient) CreateBulk(builders ...*WorkspaceCreate) *WorkspaceCreateBulk { + return &WorkspaceCreateBulk{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 *WorkspaceClient) MapCreateBulk(slice any, setFunc func(*WorkspaceCreate, int)) *WorkspaceCreateBulk { + rv := reflect.ValueOf(slice) + if rv.Kind() != reflect.Slice { + return &WorkspaceCreateBulk{err: fmt.Errorf("calling to WorkspaceClient.MapCreateBulk with wrong type %T, need slice", slice)} + } + builders := make([]*WorkspaceCreate, rv.Len()) + for i := 0; i < rv.Len(); i++ { + builders[i] = c.Create() + setFunc(builders[i], i) + } + return &WorkspaceCreateBulk{config: c.config, builders: builders} +} + +// Update returns an update builder for Workspace. +func (c *WorkspaceClient) Update() *WorkspaceUpdate { + mutation := newWorkspaceMutation(c.config, OpUpdate) + return &WorkspaceUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOne returns an update builder for the given entity. +func (c *WorkspaceClient) UpdateOne(w *Workspace) *WorkspaceUpdateOne { + mutation := newWorkspaceMutation(c.config, OpUpdateOne, withWorkspace(w)) + return &WorkspaceUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// UpdateOneID returns an update builder for the given id. +func (c *WorkspaceClient) UpdateOneID(id int) *WorkspaceUpdateOne { + mutation := newWorkspaceMutation(c.config, OpUpdateOne, withWorkspaceID(id)) + return &WorkspaceUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// Delete returns a delete builder for Workspace. +func (c *WorkspaceClient) Delete() *WorkspaceDelete { + mutation := newWorkspaceMutation(c.config, OpDelete) + return &WorkspaceDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} +} + +// DeleteOne returns a builder for deleting the given entity. +func (c *WorkspaceClient) DeleteOne(w *Workspace) *WorkspaceDeleteOne { + return c.DeleteOneID(w.ID) +} + +// DeleteOneID returns a builder for deleting the given entity by its id. +func (c *WorkspaceClient) DeleteOneID(id int) *WorkspaceDeleteOne { + builder := c.Delete().Where(workspace.ID(id)) + builder.mutation.id = &id + builder.mutation.op = OpDeleteOne + return &WorkspaceDeleteOne{builder} +} + +// Query returns a query builder for Workspace. +func (c *WorkspaceClient) Query() *WorkspaceQuery { + return &WorkspaceQuery{ + config: c.config, + ctx: &QueryContext{Type: TypeWorkspace}, + inters: c.Interceptors(), + } +} + +// Get returns a Workspace entity by its id. +func (c *WorkspaceClient) Get(ctx context.Context, id int) (*Workspace, error) { + return c.Query().Where(workspace.ID(id)).Only(ctx) +} + +// GetX is like Get, but panics if an error occurs. +func (c *WorkspaceClient) GetX(ctx context.Context, id int) *Workspace { + obj, err := c.Get(ctx, id) + if err != nil { + panic(err) + } + return obj +} + +// Hooks returns the client hooks. +func (c *WorkspaceClient) Hooks() []Hook { + return c.hooks.Workspace +} + +// Interceptors returns the client interceptors. +func (c *WorkspaceClient) Interceptors() []Interceptor { + return c.inters.Workspace +} + +func (c *WorkspaceClient) mutate(ctx context.Context, m *WorkspaceMutation) (Value, error) { + switch m.Op() { + case OpCreate: + return (&WorkspaceCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdate: + return (&WorkspaceUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpUpdateOne: + return (&WorkspaceUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) + case OpDelete, OpDeleteOne: + return (&WorkspaceDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) + default: + return nil, fmt.Errorf("ent: unknown Workspace mutation op: %q", m.Op()) + } +} + +// hooks and interceptors per client, for fast access. +type ( + hooks struct { + BillProduct, Category, Friendship, Group, OneToMany, Project, Todo, User, + VerySecret, Workspace []ent.Hook + } + inters struct { + BillProduct, Category, Friendship, Group, OneToMany, Project, Todo, User, + VerySecret, Workspace []ent.Interceptor + } +) diff --git a/entgql/internal/todoglobalid/ent/ent.go b/entgql/internal/todoglobalid/ent/ent.go new file mode 100644 index 000000000..9be1dc0fc --- /dev/null +++ b/entgql/internal/todoglobalid/ent/ent.go @@ -0,0 +1,640 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "reflect" + "sync" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/billproduct" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/category" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/friendship" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/group" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/onetomany" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/project" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/todo" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/user" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/verysecret" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/workspace" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// ent aliases to avoid import conflicts in user's code. +type ( + Op = ent.Op + Hook = ent.Hook + Value = ent.Value + Query = ent.Query + QueryContext = ent.QueryContext + Querier = ent.Querier + QuerierFunc = ent.QuerierFunc + Interceptor = ent.Interceptor + InterceptFunc = ent.InterceptFunc + Traverser = ent.Traverser + TraverseFunc = ent.TraverseFunc + Policy = ent.Policy + Mutator = ent.Mutator + Mutation = ent.Mutation + MutateFunc = ent.MutateFunc +) + +type clientCtxKey struct{} + +// FromContext returns a Client stored inside a context, or nil if there isn't one. +func FromContext(ctx context.Context) *Client { + c, _ := ctx.Value(clientCtxKey{}).(*Client) + return c +} + +// NewContext returns a new context with the given Client attached. +func NewContext(parent context.Context, c *Client) context.Context { + return context.WithValue(parent, clientCtxKey{}, c) +} + +type txCtxKey struct{} + +// TxFromContext returns a Tx stored inside a context, or nil if there isn't one. +func TxFromContext(ctx context.Context) *Tx { + tx, _ := ctx.Value(txCtxKey{}).(*Tx) + return tx +} + +// NewTxContext returns a new context with the given Tx attached. +func NewTxContext(parent context.Context, tx *Tx) context.Context { + return context.WithValue(parent, txCtxKey{}, tx) +} + +// OrderFunc applies an ordering on the sql selector. +// Deprecated: Use Asc/Desc functions or the package builders instead. +type OrderFunc func(*sql.Selector) + +var ( + initCheck sync.Once + columnCheck sql.ColumnCheck +) + +// checkColumn checks if the column exists in the given table. +func checkColumn(table, column string) error { + initCheck.Do(func() { + columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ + billproduct.Table: billproduct.ValidColumn, + category.Table: category.ValidColumn, + friendship.Table: friendship.ValidColumn, + group.Table: group.ValidColumn, + onetomany.Table: onetomany.ValidColumn, + project.Table: project.ValidColumn, + todo.Table: todo.ValidColumn, + user.Table: user.ValidColumn, + verysecret.Table: verysecret.ValidColumn, + workspace.Table: workspace.ValidColumn, + }) + }) + return columnCheck(table, column) +} + +// Asc applies the given fields in ASC order. +func Asc(fields ...string) func(*sql.Selector) { + return func(s *sql.Selector) { + for _, f := range fields { + if err := checkColumn(s.TableName(), f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)}) + } + s.OrderBy(sql.Asc(s.C(f))) + } + } +} + +// Desc applies the given fields in DESC order. +func Desc(fields ...string) func(*sql.Selector) { + return func(s *sql.Selector) { + for _, f := range fields { + if err := checkColumn(s.TableName(), f); err != nil { + s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)}) + } + s.OrderBy(sql.Desc(s.C(f))) + } + } +} + +// AggregateFunc applies an aggregation step on the group-by traversal/selector. +type AggregateFunc func(*sql.Selector) string + +// As is a pseudo aggregation function for renaming another other functions with custom names. For example: +// +// GroupBy(field1, field2). +// Aggregate(ent.As(ent.Sum(field1), "sum_field1"), (ent.As(ent.Sum(field2), "sum_field2")). +// Scan(ctx, &v) +func As(fn AggregateFunc, end string) AggregateFunc { + return func(s *sql.Selector) string { + return sql.As(fn(s), end) + } +} + +// Count applies the "count" aggregation function on each group. +func Count() AggregateFunc { + return func(s *sql.Selector) string { + return sql.Count("*") + } +} + +// Max applies the "max" aggregation function on the given field of each group. +func Max(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) + return "" + } + return sql.Max(s.C(field)) + } +} + +// Mean applies the "mean" aggregation function on the given field of each group. +func Mean(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) + return "" + } + return sql.Avg(s.C(field)) + } +} + +// Min applies the "min" aggregation function on the given field of each group. +func Min(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) + return "" + } + return sql.Min(s.C(field)) + } +} + +// Sum applies the "sum" aggregation function on the given field of each group. +func Sum(field string) AggregateFunc { + return func(s *sql.Selector) string { + if err := checkColumn(s.TableName(), field); err != nil { + s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) + return "" + } + return sql.Sum(s.C(field)) + } +} + +// ValidationError returns when validating a field or edge fails. +type ValidationError struct { + Name string // Field or edge name. + err error +} + +// Error implements the error interface. +func (e *ValidationError) Error() string { + return e.err.Error() +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ValidationError) Unwrap() error { + return e.err +} + +// IsValidationError returns a boolean indicating whether the error is a validation error. +func IsValidationError(err error) bool { + if err == nil { + return false + } + var e *ValidationError + return errors.As(err, &e) +} + +// NotFoundError returns when trying to fetch a specific entity and it was not found in the database. +type NotFoundError struct { + label string +} + +// Error implements the error interface. +func (e *NotFoundError) Error() string { + return "ent: " + e.label + " not found" +} + +// IsNotFound returns a boolean indicating whether the error is a not found error. +func IsNotFound(err error) bool { + if err == nil { + return false + } + var e *NotFoundError + return errors.As(err, &e) +} + +// MaskNotFound masks not found error. +func MaskNotFound(err error) error { + if IsNotFound(err) { + return nil + } + return err +} + +// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database. +type NotSingularError struct { + label string +} + +// Error implements the error interface. +func (e *NotSingularError) Error() string { + return "ent: " + e.label + " not singular" +} + +// IsNotSingular returns a boolean indicating whether the error is a not singular error. +func IsNotSingular(err error) bool { + if err == nil { + return false + } + var e *NotSingularError + return errors.As(err, &e) +} + +// NotLoadedError returns when trying to get a node that was not loaded by the query. +type NotLoadedError struct { + edge string +} + +// Error implements the error interface. +func (e *NotLoadedError) Error() string { + return "ent: " + e.edge + " edge was not loaded" +} + +// IsNotLoaded returns a boolean indicating whether the error is a not loaded error. +func IsNotLoaded(err error) bool { + if err == nil { + return false + } + var e *NotLoadedError + return errors.As(err, &e) +} + +// ConstraintError returns when trying to create/update one or more entities and +// one or more of their constraints failed. For example, violation of edge or +// field uniqueness. +type ConstraintError struct { + msg string + wrap error +} + +// Error implements the error interface. +func (e ConstraintError) Error() string { + return "ent: constraint failed: " + e.msg +} + +// Unwrap implements the errors.Wrapper interface. +func (e *ConstraintError) Unwrap() error { + return e.wrap +} + +// IsConstraintError returns a boolean indicating whether the error is a constraint failure. +func IsConstraintError(err error) bool { + if err == nil { + return false + } + var e *ConstraintError + return errors.As(err, &e) +} + +// selector embedded by the different Select/GroupBy builders. +type selector struct { + label string + flds *[]string + fns []AggregateFunc + scan func(context.Context, any) error +} + +// ScanX is like Scan, but panics if an error occurs. +func (s *selector) ScanX(ctx context.Context, v any) { + if err := s.scan(ctx, v); err != nil { + panic(err) + } +} + +// Strings returns list of strings from a selector. It is only allowed when selecting one field. +func (s *selector) Strings(ctx context.Context) ([]string, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Strings is not achievable when selecting more than 1 field") + } + var v []string + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// StringsX is like Strings, but panics if an error occurs. +func (s *selector) StringsX(ctx context.Context) []string { + v, err := s.Strings(ctx) + if err != nil { + panic(err) + } + return v +} + +// String returns a single string from a selector. It is only allowed when selecting one field. +func (s *selector) String(ctx context.Context) (_ string, err error) { + var v []string + if v, err = s.Strings(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Strings returned %d results when one was expected", len(v)) + } + return +} + +// StringX is like String, but panics if an error occurs. +func (s *selector) StringX(ctx context.Context) string { + v, err := s.String(ctx) + if err != nil { + panic(err) + } + return v +} + +// Ints returns list of ints from a selector. It is only allowed when selecting one field. +func (s *selector) Ints(ctx context.Context) ([]int, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Ints is not achievable when selecting more than 1 field") + } + var v []int + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// IntsX is like Ints, but panics if an error occurs. +func (s *selector) IntsX(ctx context.Context) []int { + v, err := s.Ints(ctx) + if err != nil { + panic(err) + } + return v +} + +// Int returns a single int from a selector. It is only allowed when selecting one field. +func (s *selector) Int(ctx context.Context) (_ int, err error) { + var v []int + if v, err = s.Ints(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Ints returned %d results when one was expected", len(v)) + } + return +} + +// IntX is like Int, but panics if an error occurs. +func (s *selector) IntX(ctx context.Context) int { + v, err := s.Int(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. +func (s *selector) Float64s(ctx context.Context) ([]float64, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Float64s is not achievable when selecting more than 1 field") + } + var v []float64 + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// Float64sX is like Float64s, but panics if an error occurs. +func (s *selector) Float64sX(ctx context.Context) []float64 { + v, err := s.Float64s(ctx) + if err != nil { + panic(err) + } + return v +} + +// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. +func (s *selector) Float64(ctx context.Context) (_ float64, err error) { + var v []float64 + if v, err = s.Float64s(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Float64s returned %d results when one was expected", len(v)) + } + return +} + +// Float64X is like Float64, but panics if an error occurs. +func (s *selector) Float64X(ctx context.Context) float64 { + v, err := s.Float64(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bools returns list of bools from a selector. It is only allowed when selecting one field. +func (s *selector) Bools(ctx context.Context) ([]bool, error) { + if len(*s.flds) > 1 { + return nil, errors.New("ent: Bools is not achievable when selecting more than 1 field") + } + var v []bool + if err := s.scan(ctx, &v); err != nil { + return nil, err + } + return v, nil +} + +// BoolsX is like Bools, but panics if an error occurs. +func (s *selector) BoolsX(ctx context.Context) []bool { + v, err := s.Bools(ctx) + if err != nil { + panic(err) + } + return v +} + +// Bool returns a single bool from a selector. It is only allowed when selecting one field. +func (s *selector) Bool(ctx context.Context) (_ bool, err error) { + var v []bool + if v, err = s.Bools(ctx); err != nil { + return + } + switch len(v) { + case 1: + return v[0], nil + case 0: + err = &NotFoundError{s.label} + default: + err = fmt.Errorf("ent: Bools returned %d results when one was expected", len(v)) + } + return +} + +// BoolX is like Bool, but panics if an error occurs. +func (s *selector) BoolX(ctx context.Context) bool { + v, err := s.Bool(ctx) + if err != nil { + panic(err) + } + return v +} + +// withHooks invokes the builder operation with the given hooks, if any. +func withHooks[V Value, M any, PM interface { + *M + Mutation +}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) { + if len(hooks) == 0 { + return exec(ctx) + } + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutationT, ok := any(m).(PM) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + // Set the mutation to the builder. + *mutation = *mutationT + return exec(ctx) + }) + for i := len(hooks) - 1; i >= 0; i-- { + if hooks[i] == nil { + return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") + } + mut = hooks[i](mut) + } + v, err := mut.Mutate(ctx, mutation) + if err != nil { + return value, err + } + nv, ok := v.(V) + if !ok { + return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation) + } + return nv, nil +} + +// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist. +func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context { + if ent.QueryFromContext(ctx) == nil { + qc.Op = op + ctx = ent.NewQueryContext(ctx, qc) + } + return ctx +} + +func querierAll[V Value, Q interface { + sqlAll(context.Context, ...queryHook) (V, error) +}]() Querier { + return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + return query.sqlAll(ctx) + }) +} + +func querierCount[Q interface { + sqlCount(context.Context) (int, error) +}]() Querier { + return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + return query.sqlCount(ctx) + }) +} + +func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) { + for i := len(inters) - 1; i >= 0; i-- { + qr = inters[i].Intercept(qr) + } + rv, err := qr.Query(ctx, q) + if err != nil { + return v, err + } + vt, ok := rv.(V) + if !ok { + return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v) + } + return vt, nil +} + +func scanWithInterceptors[Q1 ent.Query, Q2 interface { + sqlScan(context.Context, Q1, any) error +}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error { + rv := reflect.ValueOf(v) + var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + query, ok := q.(Q1) + if !ok { + return nil, fmt.Errorf("unexpected query type %T", q) + } + if err := selectOrGroup.sqlScan(ctx, query, v); err != nil { + return nil, err + } + if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() { + return rv.Elem().Interface(), nil + } + return v, nil + }) + for i := len(inters) - 1; i >= 0; i-- { + qr = inters[i].Intercept(qr) + } + vv, err := qr.Query(ctx, rootQuery) + if err != nil { + return err + } + switch rv2 := reflect.ValueOf(vv); { + case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer: + case rv.Type() == rv2.Type(): + rv.Elem().Set(rv2.Elem()) + case rv.Elem().Type() == rv2.Type(): + rv.Elem().Set(rv2) + } + return nil +} + +// queryHook describes an internal hook for the different sqlAll methods. +type queryHook func(context.Context, *sqlgraph.QuerySpec) diff --git a/entgql/internal/todoglobalid/ent/entc.go b/entgql/internal/todoglobalid/ent/entc.go new file mode 100644 index 000000000..81ac0ed3d --- /dev/null +++ b/entgql/internal/todoglobalid/ent/entc.go @@ -0,0 +1,58 @@ +// Copyright 2019-present Facebook Inc. All rights reserved. +// This source code is licensed under the Apache 2.0 license found +// in the LICENSE file in the root directory of this source tree. + +//go:build ignore +// +build ignore + +package main + +import ( + "log" + + "entgo.io/contrib/entgql" + "entgo.io/ent/entc" + "entgo.io/ent/entc/gen" +) + +func main() { + // The codegen is executed from internal/todoglobalid/gen.go. + // So the path for the config file, ent schema, and the GQL schema + // starts from internal/todoglobalid. + ex, err := entgql.NewExtension( + entgql.WithConfigPath("./gqlgen.yml"), + entgql.WithSchemaGenerator(), + entgql.WithSchemaPath("./ent.graphql"), + entgql.WithWhereInputs(true), + entgql.WithNodeDescriptor(true), + ) + if err != nil { + log.Fatalf("creating entgql extension: %v", err) + } + err = entc.Generate("./ent/schema", &gen.Config{ + Header: ` + // Copyright 2019-present Facebook + // + // Licensed under the Apache License, Version 2.0 (the "License"); + // you may not use this file except in compliance with the License. + // You may obtain a copy of the License at + // + // http://www.apache.org/licenses/LICENSE-2.0 + // + // Unless required by applicable law or agreed to in writing, software + // distributed under the License is distributed on an "AS IS" BASIS, + // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + // See the License for the specific language governing permissions and + // limitations under the License. + // + // Code generated by entc, DO NOT EDIT. + `, + Features: []gen.Feature{ + gen.FeatureModifier, + gen.FeatureGlobalID, + }, + }, entc.Extensions(ex)) + if err != nil { + log.Fatalf("running ent codegen: %v", err) + } +} diff --git a/entgql/internal/todoglobalid/ent/enttest/enttest.go b/entgql/internal/todoglobalid/ent/enttest/enttest.go new file mode 100644 index 000000000..f8de831dd --- /dev/null +++ b/entgql/internal/todoglobalid/ent/enttest/enttest.go @@ -0,0 +1,98 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package enttest + +import ( + "context" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent" + // required by schema hooks. + _ "entgo.io/contrib/entgql/internal/todoglobalid/ent/runtime" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/migrate" + "entgo.io/ent/dialect/sql/schema" +) + +type ( + // TestingT is the interface that is shared between + // testing.T and testing.B and used by enttest. + TestingT interface { + FailNow() + Error(...any) + } + + // Option configures client creation. + Option func(*options) + + options struct { + opts []ent.Option + migrateOpts []schema.MigrateOption + } +) + +// WithOptions forwards options to client creation. +func WithOptions(opts ...ent.Option) Option { + return func(o *options) { + o.opts = append(o.opts, opts...) + } +} + +// WithMigrateOptions forwards options to auto migration. +func WithMigrateOptions(opts ...schema.MigrateOption) Option { + return func(o *options) { + o.migrateOpts = append(o.migrateOpts, opts...) + } +} + +func newOptions(opts []Option) *options { + o := &options{} + for _, opt := range opts { + opt(o) + } + return o +} + +// Open calls ent.Open and auto-run migration. +func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *ent.Client { + o := newOptions(opts) + c, err := ent.Open(driverName, dataSourceName, o.opts...) + if err != nil { + t.Error(err) + t.FailNow() + } + migrateSchema(t, c, o) + return c +} + +// NewClient calls ent.NewClient and auto-run migration. +func NewClient(t TestingT, opts ...Option) *ent.Client { + o := newOptions(opts) + c := ent.NewClient(o.opts...) + migrateSchema(t, c, o) + return c +} +func migrateSchema(t TestingT, c *ent.Client, o *options) { + tables, err := schema.CopyTables(migrate.Tables) + if err != nil { + t.Error(err) + t.FailNow() + } + if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil { + t.Error(err) + t.FailNow() + } +} diff --git a/entgql/internal/todoglobalid/ent/friendship.go b/entgql/internal/todoglobalid/ent/friendship.go new file mode 100644 index 000000000..2aa93b257 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/friendship.go @@ -0,0 +1,189 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + "time" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/friendship" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/user" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// Friendship is the model entity for the Friendship schema. +type Friendship struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // UserID holds the value of the "user_id" field. + UserID int `json:"user_id,omitempty"` + // FriendID holds the value of the "friend_id" field. + FriendID int `json:"friend_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the FriendshipQuery when eager-loading is set. + Edges FriendshipEdges `json:"edges"` + selectValues sql.SelectValues +} + +// FriendshipEdges holds the relations/edges for other nodes in the graph. +type FriendshipEdges struct { + // User holds the value of the user edge. + User *User `json:"user,omitempty"` + // Friend holds the value of the friend edge. + Friend *User `json:"friend,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool + // totalCount holds the count of the edges above. + totalCount [2]map[string]int +} + +// UserOrErr returns the User value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e FriendshipEdges) UserOrErr() (*User, error) { + if e.User != nil { + return e.User, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: user.Label} + } + return nil, &NotLoadedError{edge: "user"} +} + +// FriendOrErr returns the Friend value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e FriendshipEdges) FriendOrErr() (*User, error) { + if e.Friend != nil { + return e.Friend, nil + } else if e.loadedTypes[1] { + return nil, &NotFoundError{label: user.Label} + } + return nil, &NotLoadedError{edge: "friend"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Friendship) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case friendship.FieldID, friendship.FieldUserID, friendship.FieldFriendID: + values[i] = new(sql.NullInt64) + case friendship.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 Friendship fields. +func (f *Friendship) 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 friendship.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + f.ID = int(value.Int64) + case friendship.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 { + f.CreatedAt = value.Time + } + case friendship.FieldUserID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field user_id", values[i]) + } else if value.Valid { + f.UserID = int(value.Int64) + } + case friendship.FieldFriendID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field friend_id", values[i]) + } else if value.Valid { + f.FriendID = int(value.Int64) + } + default: + f.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Friendship. +// This includes values selected through modifiers, order, etc. +func (f *Friendship) Value(name string) (ent.Value, error) { + return f.selectValues.Get(name) +} + +// QueryUser queries the "user" edge of the Friendship entity. +func (f *Friendship) QueryUser() *UserQuery { + return NewFriendshipClient(f.config).QueryUser(f) +} + +// QueryFriend queries the "friend" edge of the Friendship entity. +func (f *Friendship) QueryFriend() *UserQuery { + return NewFriendshipClient(f.config).QueryFriend(f) +} + +// Update returns a builder for updating this Friendship. +// Note that you need to call Friendship.Unwrap() before calling this method if this Friendship +// was returned from a transaction, and the transaction was committed or rolled back. +func (f *Friendship) Update() *FriendshipUpdateOne { + return NewFriendshipClient(f.config).UpdateOne(f) +} + +// Unwrap unwraps the Friendship 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 (f *Friendship) Unwrap() *Friendship { + _tx, ok := f.config.driver.(*txDriver) + if !ok { + panic("ent: Friendship is not a transactional entity") + } + f.config.driver = _tx.drv + return f +} + +// String implements the fmt.Stringer. +func (f *Friendship) String() string { + var builder strings.Builder + builder.WriteString("Friendship(") + builder.WriteString(fmt.Sprintf("id=%v, ", f.ID)) + builder.WriteString("created_at=") + builder.WriteString(f.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("user_id=") + builder.WriteString(fmt.Sprintf("%v", f.UserID)) + builder.WriteString(", ") + builder.WriteString("friend_id=") + builder.WriteString(fmt.Sprintf("%v", f.FriendID)) + builder.WriteByte(')') + return builder.String() +} + +// Friendships is a parsable slice of Friendship. +type Friendships []*Friendship diff --git a/entgql/internal/todoglobalid/ent/friendship/friendship.go b/entgql/internal/todoglobalid/ent/friendship/friendship.go new file mode 100644 index 000000000..dd6c6a3d6 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/friendship/friendship.go @@ -0,0 +1,131 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package friendship + +import ( + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the friendship type in the database. + Label = "friendship" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldUserID holds the string denoting the user_id field in the database. + FieldUserID = "user_id" + // FieldFriendID holds the string denoting the friend_id field in the database. + FieldFriendID = "friend_id" + // EdgeUser holds the string denoting the user edge name in mutations. + EdgeUser = "user" + // EdgeFriend holds the string denoting the friend edge name in mutations. + EdgeFriend = "friend" + // Table holds the table name of the friendship in the database. + Table = "friendships" + // UserTable is the table that holds the user relation/edge. + UserTable = "friendships" + // UserInverseTable is the table name for the User entity. + // It exists in this package in order to avoid circular dependency with the "user" package. + UserInverseTable = "users" + // UserColumn is the table column denoting the user relation/edge. + UserColumn = "user_id" + // FriendTable is the table that holds the friend relation/edge. + FriendTable = "friendships" + // FriendInverseTable is the table name for the User entity. + // It exists in this package in order to avoid circular dependency with the "user" package. + FriendInverseTable = "users" + // FriendColumn is the table column denoting the friend relation/edge. + FriendColumn = "friend_id" +) + +// Columns holds all SQL columns for friendship fields. +var Columns = []string{ + FieldID, + FieldCreatedAt, + FieldUserID, + FieldFriendID, +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time +) + +// OrderOption defines the ordering options for the Friendship 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() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByUserID orders the results by the user_id field. +func ByUserID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUserID, opts...).ToFunc() +} + +// ByFriendID orders the results by the friend_id field. +func ByFriendID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldFriendID, opts...).ToFunc() +} + +// ByUserField orders the results by user field. +func ByUserField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newUserStep(), sql.OrderByField(field, opts...)) + } +} + +// ByFriendField orders the results by friend field. +func ByFriendField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newFriendStep(), sql.OrderByField(field, opts...)) + } +} +func newUserStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UserInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn), + ) +} +func newFriendStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(FriendInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, FriendTable, FriendColumn), + ) +} diff --git a/entgql/internal/todoglobalid/ent/friendship/where.go b/entgql/internal/todoglobalid/ent/friendship/where.go new file mode 100644 index 000000000..72a869a8a --- /dev/null +++ b/entgql/internal/todoglobalid/ent/friendship/where.go @@ -0,0 +1,226 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package friendship + +import ( + "time" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.Friendship { + return predicate.Friendship(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.Friendship { + return predicate.Friendship(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.Friendship { + return predicate.Friendship(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.Friendship { + return predicate.Friendship(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.Friendship { + return predicate.Friendship(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.Friendship { + return predicate.Friendship(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.Friendship { + return predicate.Friendship(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.Friendship { + return predicate.Friendship(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.Friendship { + return predicate.Friendship(sql.FieldLTE(FieldID, id)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.Friendship { + return predicate.Friendship(sql.FieldEQ(FieldCreatedAt, v)) +} + +// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. +func UserID(v int) predicate.Friendship { + return predicate.Friendship(sql.FieldEQ(FieldUserID, v)) +} + +// FriendID applies equality check predicate on the "friend_id" field. It's identical to FriendIDEQ. +func FriendID(v int) predicate.Friendship { + return predicate.Friendship(sql.FieldEQ(FieldFriendID, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.Friendship { + return predicate.Friendship(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.Friendship { + return predicate.Friendship(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.Friendship { + return predicate.Friendship(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.Friendship { + return predicate.Friendship(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.Friendship { + return predicate.Friendship(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.Friendship { + return predicate.Friendship(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.Friendship { + return predicate.Friendship(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.Friendship { + return predicate.Friendship(sql.FieldLTE(FieldCreatedAt, v)) +} + +// UserIDEQ applies the EQ predicate on the "user_id" field. +func UserIDEQ(v int) predicate.Friendship { + return predicate.Friendship(sql.FieldEQ(FieldUserID, v)) +} + +// UserIDNEQ applies the NEQ predicate on the "user_id" field. +func UserIDNEQ(v int) predicate.Friendship { + return predicate.Friendship(sql.FieldNEQ(FieldUserID, v)) +} + +// UserIDIn applies the In predicate on the "user_id" field. +func UserIDIn(vs ...int) predicate.Friendship { + return predicate.Friendship(sql.FieldIn(FieldUserID, vs...)) +} + +// UserIDNotIn applies the NotIn predicate on the "user_id" field. +func UserIDNotIn(vs ...int) predicate.Friendship { + return predicate.Friendship(sql.FieldNotIn(FieldUserID, vs...)) +} + +// FriendIDEQ applies the EQ predicate on the "friend_id" field. +func FriendIDEQ(v int) predicate.Friendship { + return predicate.Friendship(sql.FieldEQ(FieldFriendID, v)) +} + +// FriendIDNEQ applies the NEQ predicate on the "friend_id" field. +func FriendIDNEQ(v int) predicate.Friendship { + return predicate.Friendship(sql.FieldNEQ(FieldFriendID, v)) +} + +// FriendIDIn applies the In predicate on the "friend_id" field. +func FriendIDIn(vs ...int) predicate.Friendship { + return predicate.Friendship(sql.FieldIn(FieldFriendID, vs...)) +} + +// FriendIDNotIn applies the NotIn predicate on the "friend_id" field. +func FriendIDNotIn(vs ...int) predicate.Friendship { + return predicate.Friendship(sql.FieldNotIn(FieldFriendID, vs...)) +} + +// HasUser applies the HasEdge predicate on the "user" edge. +func HasUser() predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates). +func HasUserWith(preds ...predicate.User) predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + step := newUserStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasFriend applies the HasEdge predicate on the "friend" edge. +func HasFriend() predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, FriendTable, FriendColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasFriendWith applies the HasEdge predicate on the "friend" edge with a given conditions (other predicates). +func HasFriendWith(preds ...predicate.User) predicate.Friendship { + return predicate.Friendship(func(s *sql.Selector) { + step := newFriendStep() + 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.Friendship) predicate.Friendship { + return predicate.Friendship(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Friendship) predicate.Friendship { + return predicate.Friendship(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Friendship) predicate.Friendship { + return predicate.Friendship(sql.NotPredicates(p)) +} diff --git a/entgql/internal/todoglobalid/ent/friendship_create.go b/entgql/internal/todoglobalid/ent/friendship_create.go new file mode 100644 index 000000000..5342e07e9 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/friendship_create.go @@ -0,0 +1,285 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/friendship" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/user" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// FriendshipCreate is the builder for creating a Friendship entity. +type FriendshipCreate struct { + config + mutation *FriendshipMutation + hooks []Hook +} + +// SetCreatedAt sets the "created_at" field. +func (fc *FriendshipCreate) SetCreatedAt(t time.Time) *FriendshipCreate { + fc.mutation.SetCreatedAt(t) + return fc +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (fc *FriendshipCreate) SetNillableCreatedAt(t *time.Time) *FriendshipCreate { + if t != nil { + fc.SetCreatedAt(*t) + } + return fc +} + +// SetUserID sets the "user_id" field. +func (fc *FriendshipCreate) SetUserID(i int) *FriendshipCreate { + fc.mutation.SetUserID(i) + return fc +} + +// SetFriendID sets the "friend_id" field. +func (fc *FriendshipCreate) SetFriendID(i int) *FriendshipCreate { + fc.mutation.SetFriendID(i) + return fc +} + +// SetUser sets the "user" edge to the User entity. +func (fc *FriendshipCreate) SetUser(u *User) *FriendshipCreate { + return fc.SetUserID(u.ID) +} + +// SetFriend sets the "friend" edge to the User entity. +func (fc *FriendshipCreate) SetFriend(u *User) *FriendshipCreate { + return fc.SetFriendID(u.ID) +} + +// Mutation returns the FriendshipMutation object of the builder. +func (fc *FriendshipCreate) Mutation() *FriendshipMutation { + return fc.mutation +} + +// Save creates the Friendship in the database. +func (fc *FriendshipCreate) Save(ctx context.Context) (*Friendship, error) { + fc.defaults() + return withHooks(ctx, fc.sqlSave, fc.mutation, fc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (fc *FriendshipCreate) SaveX(ctx context.Context) *Friendship { + v, err := fc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (fc *FriendshipCreate) Exec(ctx context.Context) error { + _, err := fc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (fc *FriendshipCreate) ExecX(ctx context.Context) { + if err := fc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (fc *FriendshipCreate) defaults() { + if _, ok := fc.mutation.CreatedAt(); !ok { + v := friendship.DefaultCreatedAt() + fc.mutation.SetCreatedAt(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (fc *FriendshipCreate) check() error { + if _, ok := fc.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Friendship.created_at"`)} + } + if _, ok := fc.mutation.UserID(); !ok { + return &ValidationError{Name: "user_id", err: errors.New(`ent: missing required field "Friendship.user_id"`)} + } + if _, ok := fc.mutation.FriendID(); !ok { + return &ValidationError{Name: "friend_id", err: errors.New(`ent: missing required field "Friendship.friend_id"`)} + } + if len(fc.mutation.UserIDs()) == 0 { + return &ValidationError{Name: "user", err: errors.New(`ent: missing required edge "Friendship.user"`)} + } + if len(fc.mutation.FriendIDs()) == 0 { + return &ValidationError{Name: "friend", err: errors.New(`ent: missing required edge "Friendship.friend"`)} + } + return nil +} + +func (fc *FriendshipCreate) sqlSave(ctx context.Context) (*Friendship, error) { + if err := fc.check(); err != nil { + return nil, err + } + _node, _spec := fc.createSpec() + if err := sqlgraph.CreateNode(ctx, fc.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) + fc.mutation.id = &_node.ID + fc.mutation.done = true + return _node, nil +} + +func (fc *FriendshipCreate) createSpec() (*Friendship, *sqlgraph.CreateSpec) { + var ( + _node = &Friendship{config: fc.config} + _spec = sqlgraph.NewCreateSpec(friendship.Table, sqlgraph.NewFieldSpec(friendship.FieldID, field.TypeInt)) + ) + if value, ok := fc.mutation.CreatedAt(); ok { + _spec.SetField(friendship.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if nodes := fc.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: friendship.UserTable, + Columns: []string{friendship.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.UserID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := fc.mutation.FriendIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: friendship.FriendTable, + Columns: []string{friendship.FriendColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.FriendID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// FriendshipCreateBulk is the builder for creating many Friendship entities in bulk. +type FriendshipCreateBulk struct { + config + err error + builders []*FriendshipCreate +} + +// Save creates the Friendship entities in the database. +func (fcb *FriendshipCreateBulk) Save(ctx context.Context) ([]*Friendship, error) { + if fcb.err != nil { + return nil, fcb.err + } + specs := make([]*sqlgraph.CreateSpec, len(fcb.builders)) + nodes := make([]*Friendship, len(fcb.builders)) + mutators := make([]Mutator, len(fcb.builders)) + for i := range fcb.builders { + func(i int, root context.Context) { + builder := fcb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*FriendshipMutation) + 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, fcb.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, fcb.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, fcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (fcb *FriendshipCreateBulk) SaveX(ctx context.Context) []*Friendship { + v, err := fcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (fcb *FriendshipCreateBulk) Exec(ctx context.Context) error { + _, err := fcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (fcb *FriendshipCreateBulk) ExecX(ctx context.Context) { + if err := fcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entgql/internal/todoglobalid/ent/friendship_delete.go b/entgql/internal/todoglobalid/ent/friendship_delete.go new file mode 100644 index 000000000..a1a7d64c9 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/friendship_delete.go @@ -0,0 +1,102 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/friendship" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// FriendshipDelete is the builder for deleting a Friendship entity. +type FriendshipDelete struct { + config + hooks []Hook + mutation *FriendshipMutation +} + +// Where appends a list predicates to the FriendshipDelete builder. +func (fd *FriendshipDelete) Where(ps ...predicate.Friendship) *FriendshipDelete { + fd.mutation.Where(ps...) + return fd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (fd *FriendshipDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, fd.sqlExec, fd.mutation, fd.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (fd *FriendshipDelete) ExecX(ctx context.Context) int { + n, err := fd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (fd *FriendshipDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(friendship.Table, sqlgraph.NewFieldSpec(friendship.FieldID, field.TypeInt)) + if ps := fd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, fd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + fd.mutation.done = true + return affected, err +} + +// FriendshipDeleteOne is the builder for deleting a single Friendship entity. +type FriendshipDeleteOne struct { + fd *FriendshipDelete +} + +// Where appends a list predicates to the FriendshipDelete builder. +func (fdo *FriendshipDeleteOne) Where(ps ...predicate.Friendship) *FriendshipDeleteOne { + fdo.fd.mutation.Where(ps...) + return fdo +} + +// Exec executes the deletion query. +func (fdo *FriendshipDeleteOne) Exec(ctx context.Context) error { + n, err := fdo.fd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{friendship.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (fdo *FriendshipDeleteOne) ExecX(ctx context.Context) { + if err := fdo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entgql/internal/todoglobalid/ent/friendship_query.go b/entgql/internal/todoglobalid/ent/friendship_query.go new file mode 100644 index 000000000..dfa46899e --- /dev/null +++ b/entgql/internal/todoglobalid/ent/friendship_query.go @@ -0,0 +1,723 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/friendship" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/user" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// FriendshipQuery is the builder for querying Friendship entities. +type FriendshipQuery struct { + config + ctx *QueryContext + order []friendship.OrderOption + inters []Interceptor + predicates []predicate.Friendship + withUser *UserQuery + withFriend *UserQuery + loadTotal []func(context.Context, []*Friendship) error + modifiers []func(*sql.Selector) + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the FriendshipQuery builder. +func (fq *FriendshipQuery) Where(ps ...predicate.Friendship) *FriendshipQuery { + fq.predicates = append(fq.predicates, ps...) + return fq +} + +// Limit the number of records to be returned by this query. +func (fq *FriendshipQuery) Limit(limit int) *FriendshipQuery { + fq.ctx.Limit = &limit + return fq +} + +// Offset to start from. +func (fq *FriendshipQuery) Offset(offset int) *FriendshipQuery { + fq.ctx.Offset = &offset + return fq +} + +// 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 (fq *FriendshipQuery) Unique(unique bool) *FriendshipQuery { + fq.ctx.Unique = &unique + return fq +} + +// Order specifies how the records should be ordered. +func (fq *FriendshipQuery) Order(o ...friendship.OrderOption) *FriendshipQuery { + fq.order = append(fq.order, o...) + return fq +} + +// QueryUser chains the current query on the "user" edge. +func (fq *FriendshipQuery) QueryUser() *UserQuery { + query := (&UserClient{config: fq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := fq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := fq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(friendship.Table, friendship.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, friendship.UserTable, friendship.UserColumn), + ) + fromU = sqlgraph.SetNeighbors(fq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryFriend chains the current query on the "friend" edge. +func (fq *FriendshipQuery) QueryFriend() *UserQuery { + query := (&UserClient{config: fq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := fq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := fq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(friendship.Table, friendship.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, friendship.FriendTable, friendship.FriendColumn), + ) + fromU = sqlgraph.SetNeighbors(fq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Friendship entity from the query. +// Returns a *NotFoundError when no Friendship was found. +func (fq *FriendshipQuery) First(ctx context.Context) (*Friendship, error) { + nodes, err := fq.Limit(1).All(setContextOp(ctx, fq.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{friendship.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (fq *FriendshipQuery) FirstX(ctx context.Context) *Friendship { + node, err := fq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Friendship ID from the query. +// Returns a *NotFoundError when no Friendship ID was found. +func (fq *FriendshipQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = fq.Limit(1).IDs(setContextOp(ctx, fq.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{friendship.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (fq *FriendshipQuery) FirstIDX(ctx context.Context) int { + id, err := fq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Friendship entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Friendship entity is found. +// Returns a *NotFoundError when no Friendship entities are found. +func (fq *FriendshipQuery) Only(ctx context.Context) (*Friendship, error) { + nodes, err := fq.Limit(2).All(setContextOp(ctx, fq.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{friendship.Label} + default: + return nil, &NotSingularError{friendship.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (fq *FriendshipQuery) OnlyX(ctx context.Context) *Friendship { + node, err := fq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Friendship ID in the query. +// Returns a *NotSingularError when more than one Friendship ID is found. +// Returns a *NotFoundError when no entities are found. +func (fq *FriendshipQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = fq.Limit(2).IDs(setContextOp(ctx, fq.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{friendship.Label} + default: + err = &NotSingularError{friendship.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (fq *FriendshipQuery) OnlyIDX(ctx context.Context) int { + id, err := fq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Friendships. +func (fq *FriendshipQuery) All(ctx context.Context) ([]*Friendship, error) { + ctx = setContextOp(ctx, fq.ctx, ent.OpQueryAll) + if err := fq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Friendship, *FriendshipQuery]() + return withInterceptors[[]*Friendship](ctx, fq, qr, fq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (fq *FriendshipQuery) AllX(ctx context.Context) []*Friendship { + nodes, err := fq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Friendship IDs. +func (fq *FriendshipQuery) IDs(ctx context.Context) (ids []int, err error) { + if fq.ctx.Unique == nil && fq.path != nil { + fq.Unique(true) + } + ctx = setContextOp(ctx, fq.ctx, ent.OpQueryIDs) + if err = fq.Select(friendship.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (fq *FriendshipQuery) IDsX(ctx context.Context) []int { + ids, err := fq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (fq *FriendshipQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, fq.ctx, ent.OpQueryCount) + if err := fq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, fq, querierCount[*FriendshipQuery](), fq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (fq *FriendshipQuery) CountX(ctx context.Context) int { + count, err := fq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (fq *FriendshipQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, fq.ctx, ent.OpQueryExist) + switch _, err := fq.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 (fq *FriendshipQuery) ExistX(ctx context.Context) bool { + exist, err := fq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the FriendshipQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (fq *FriendshipQuery) Clone() *FriendshipQuery { + if fq == nil { + return nil + } + return &FriendshipQuery{ + config: fq.config, + ctx: fq.ctx.Clone(), + order: append([]friendship.OrderOption{}, fq.order...), + inters: append([]Interceptor{}, fq.inters...), + predicates: append([]predicate.Friendship{}, fq.predicates...), + withUser: fq.withUser.Clone(), + withFriend: fq.withFriend.Clone(), + // clone intermediate query. + sql: fq.sql.Clone(), + path: fq.path, + modifiers: append([]func(*sql.Selector){}, fq.modifiers...), + } +} + +// WithUser tells the query-builder to eager-load the nodes that are connected to +// the "user" edge. The optional arguments are used to configure the query builder of the edge. +func (fq *FriendshipQuery) WithUser(opts ...func(*UserQuery)) *FriendshipQuery { + query := (&UserClient{config: fq.config}).Query() + for _, opt := range opts { + opt(query) + } + fq.withUser = query + return fq +} + +// WithFriend tells the query-builder to eager-load the nodes that are connected to +// the "friend" edge. The optional arguments are used to configure the query builder of the edge. +func (fq *FriendshipQuery) WithFriend(opts ...func(*UserQuery)) *FriendshipQuery { + query := (&UserClient{config: fq.config}).Query() + for _, opt := range opts { + opt(query) + } + fq.withFriend = query + return fq +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// CreatedAt time.Time `json:"created_at,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Friendship.Query(). +// GroupBy(friendship.FieldCreatedAt). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (fq *FriendshipQuery) GroupBy(field string, fields ...string) *FriendshipGroupBy { + fq.ctx.Fields = append([]string{field}, fields...) + grbuild := &FriendshipGroupBy{build: fq} + grbuild.flds = &fq.ctx.Fields + grbuild.label = friendship.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 { +// CreatedAt time.Time `json:"created_at,omitempty"` +// } +// +// client.Friendship.Query(). +// Select(friendship.FieldCreatedAt). +// Scan(ctx, &v) +func (fq *FriendshipQuery) Select(fields ...string) *FriendshipSelect { + fq.ctx.Fields = append(fq.ctx.Fields, fields...) + sbuild := &FriendshipSelect{FriendshipQuery: fq} + sbuild.label = friendship.Label + sbuild.flds, sbuild.scan = &fq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a FriendshipSelect configured with the given aggregations. +func (fq *FriendshipQuery) Aggregate(fns ...AggregateFunc) *FriendshipSelect { + return fq.Select().Aggregate(fns...) +} + +func (fq *FriendshipQuery) prepareQuery(ctx context.Context) error { + for _, inter := range fq.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, fq); err != nil { + return err + } + } + } + for _, f := range fq.ctx.Fields { + if !friendship.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if fq.path != nil { + prev, err := fq.path(ctx) + if err != nil { + return err + } + fq.sql = prev + } + return nil +} + +func (fq *FriendshipQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Friendship, error) { + var ( + nodes = []*Friendship{} + _spec = fq.querySpec() + loadedTypes = [2]bool{ + fq.withUser != nil, + fq.withFriend != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Friendship).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Friendship{config: fq.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(fq.modifiers) > 0 { + _spec.Modifiers = fq.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, fq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := fq.withUser; query != nil { + if err := fq.loadUser(ctx, query, nodes, nil, + func(n *Friendship, e *User) { n.Edges.User = e }); err != nil { + return nil, err + } + } + if query := fq.withFriend; query != nil { + if err := fq.loadFriend(ctx, query, nodes, nil, + func(n *Friendship, e *User) { n.Edges.Friend = e }); err != nil { + return nil, err + } + } + for i := range fq.loadTotal { + if err := fq.loadTotal[i](ctx, nodes); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (fq *FriendshipQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*Friendship, init func(*Friendship), assign func(*Friendship, *User)) error { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*Friendship) + for i := range nodes { + fk := nodes[i].UserID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(user.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "user_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (fq *FriendshipQuery) loadFriend(ctx context.Context, query *UserQuery, nodes []*Friendship, init func(*Friendship), assign func(*Friendship, *User)) error { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*Friendship) + for i := range nodes { + fk := nodes[i].FriendID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(user.IDIn(ids...)) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nodeids[n.ID] + if !ok { + return fmt.Errorf(`unexpected foreign-key "friend_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (fq *FriendshipQuery) sqlCount(ctx context.Context) (int, error) { + _spec := fq.querySpec() + if len(fq.modifiers) > 0 { + _spec.Modifiers = fq.modifiers + } + _spec.Node.Columns = fq.ctx.Fields + if len(fq.ctx.Fields) > 0 { + _spec.Unique = fq.ctx.Unique != nil && *fq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, fq.driver, _spec) +} + +func (fq *FriendshipQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(friendship.Table, friendship.Columns, sqlgraph.NewFieldSpec(friendship.FieldID, field.TypeInt)) + _spec.From = fq.sql + if unique := fq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if fq.path != nil { + _spec.Unique = true + } + if fields := fq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, friendship.FieldID) + for i := range fields { + if fields[i] != friendship.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if fq.withUser != nil { + _spec.Node.AddColumnOnce(friendship.FieldUserID) + } + if fq.withFriend != nil { + _spec.Node.AddColumnOnce(friendship.FieldFriendID) + } + } + if ps := fq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := fq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := fq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := fq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (fq *FriendshipQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(fq.driver.Dialect()) + t1 := builder.Table(friendship.Table) + columns := fq.ctx.Fields + if len(columns) == 0 { + columns = friendship.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if fq.sql != nil { + selector = fq.sql + selector.Select(selector.Columns(columns...)...) + } + if fq.ctx.Unique != nil && *fq.ctx.Unique { + selector.Distinct() + } + for _, m := range fq.modifiers { + m(selector) + } + for _, p := range fq.predicates { + p(selector) + } + for _, p := range fq.order { + p(selector) + } + if offset := fq.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 := fq.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (fq *FriendshipQuery) Modify(modifiers ...func(s *sql.Selector)) *FriendshipSelect { + fq.modifiers = append(fq.modifiers, modifiers...) + return fq.Select() +} + +// FriendshipGroupBy is the group-by builder for Friendship entities. +type FriendshipGroupBy struct { + selector + build *FriendshipQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (fgb *FriendshipGroupBy) Aggregate(fns ...AggregateFunc) *FriendshipGroupBy { + fgb.fns = append(fgb.fns, fns...) + return fgb +} + +// Scan applies the selector query and scans the result into the given value. +func (fgb *FriendshipGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, fgb.build.ctx, ent.OpQueryGroupBy) + if err := fgb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*FriendshipQuery, *FriendshipGroupBy](ctx, fgb.build, fgb, fgb.build.inters, v) +} + +func (fgb *FriendshipGroupBy) sqlScan(ctx context.Context, root *FriendshipQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(fgb.fns)) + for _, fn := range fgb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*fgb.flds)+len(fgb.fns)) + for _, f := range *fgb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*fgb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := fgb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// FriendshipSelect is the builder for selecting fields of Friendship entities. +type FriendshipSelect struct { + *FriendshipQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (fs *FriendshipSelect) Aggregate(fns ...AggregateFunc) *FriendshipSelect { + fs.fns = append(fs.fns, fns...) + return fs +} + +// Scan applies the selector query and scans the result into the given value. +func (fs *FriendshipSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, fs.ctx, ent.OpQuerySelect) + if err := fs.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*FriendshipQuery, *FriendshipSelect](ctx, fs.FriendshipQuery, fs, fs.inters, v) +} + +func (fs *FriendshipSelect) sqlScan(ctx context.Context, root *FriendshipQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(fs.fns)) + for _, fn := range fs.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*fs.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 := fs.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (fs *FriendshipSelect) Modify(modifiers ...func(s *sql.Selector)) *FriendshipSelect { + fs.modifiers = append(fs.modifiers, modifiers...) + return fs +} diff --git a/entgql/internal/todoglobalid/ent/friendship_update.go b/entgql/internal/todoglobalid/ent/friendship_update.go new file mode 100644 index 000000000..1ba2bf015 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/friendship_update.go @@ -0,0 +1,485 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/friendship" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/user" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// FriendshipUpdate is the builder for updating Friendship entities. +type FriendshipUpdate struct { + config + hooks []Hook + mutation *FriendshipMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the FriendshipUpdate builder. +func (fu *FriendshipUpdate) Where(ps ...predicate.Friendship) *FriendshipUpdate { + fu.mutation.Where(ps...) + return fu +} + +// SetCreatedAt sets the "created_at" field. +func (fu *FriendshipUpdate) SetCreatedAt(t time.Time) *FriendshipUpdate { + fu.mutation.SetCreatedAt(t) + return fu +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (fu *FriendshipUpdate) SetNillableCreatedAt(t *time.Time) *FriendshipUpdate { + if t != nil { + fu.SetCreatedAt(*t) + } + return fu +} + +// SetUserID sets the "user_id" field. +func (fu *FriendshipUpdate) SetUserID(i int) *FriendshipUpdate { + fu.mutation.SetUserID(i) + return fu +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (fu *FriendshipUpdate) SetNillableUserID(i *int) *FriendshipUpdate { + if i != nil { + fu.SetUserID(*i) + } + return fu +} + +// SetFriendID sets the "friend_id" field. +func (fu *FriendshipUpdate) SetFriendID(i int) *FriendshipUpdate { + fu.mutation.SetFriendID(i) + return fu +} + +// SetNillableFriendID sets the "friend_id" field if the given value is not nil. +func (fu *FriendshipUpdate) SetNillableFriendID(i *int) *FriendshipUpdate { + if i != nil { + fu.SetFriendID(*i) + } + return fu +} + +// SetUser sets the "user" edge to the User entity. +func (fu *FriendshipUpdate) SetUser(u *User) *FriendshipUpdate { + return fu.SetUserID(u.ID) +} + +// SetFriend sets the "friend" edge to the User entity. +func (fu *FriendshipUpdate) SetFriend(u *User) *FriendshipUpdate { + return fu.SetFriendID(u.ID) +} + +// Mutation returns the FriendshipMutation object of the builder. +func (fu *FriendshipUpdate) Mutation() *FriendshipMutation { + return fu.mutation +} + +// ClearUser clears the "user" edge to the User entity. +func (fu *FriendshipUpdate) ClearUser() *FriendshipUpdate { + fu.mutation.ClearUser() + return fu +} + +// ClearFriend clears the "friend" edge to the User entity. +func (fu *FriendshipUpdate) ClearFriend() *FriendshipUpdate { + fu.mutation.ClearFriend() + return fu +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (fu *FriendshipUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, fu.sqlSave, fu.mutation, fu.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (fu *FriendshipUpdate) SaveX(ctx context.Context) int { + affected, err := fu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (fu *FriendshipUpdate) Exec(ctx context.Context) error { + _, err := fu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (fu *FriendshipUpdate) ExecX(ctx context.Context) { + if err := fu.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (fu *FriendshipUpdate) check() error { + if fu.mutation.UserCleared() && len(fu.mutation.UserIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "Friendship.user"`) + } + if fu.mutation.FriendCleared() && len(fu.mutation.FriendIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "Friendship.friend"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (fu *FriendshipUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *FriendshipUpdate { + fu.modifiers = append(fu.modifiers, modifiers...) + return fu +} + +func (fu *FriendshipUpdate) sqlSave(ctx context.Context) (n int, err error) { + if err := fu.check(); err != nil { + return n, err + } + _spec := sqlgraph.NewUpdateSpec(friendship.Table, friendship.Columns, sqlgraph.NewFieldSpec(friendship.FieldID, field.TypeInt)) + if ps := fu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := fu.mutation.CreatedAt(); ok { + _spec.SetField(friendship.FieldCreatedAt, field.TypeTime, value) + } + if fu.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: friendship.UserTable, + Columns: []string{friendship.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := fu.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: friendship.UserTable, + Columns: []string{friendship.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if fu.mutation.FriendCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: friendship.FriendTable, + Columns: []string{friendship.FriendColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := fu.mutation.FriendIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: friendship.FriendTable, + Columns: []string{friendship.FriendColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(fu.modifiers...) + if n, err = sqlgraph.UpdateNodes(ctx, fu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{friendship.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + fu.mutation.done = true + return n, nil +} + +// FriendshipUpdateOne is the builder for updating a single Friendship entity. +type FriendshipUpdateOne struct { + config + fields []string + hooks []Hook + mutation *FriendshipMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetCreatedAt sets the "created_at" field. +func (fuo *FriendshipUpdateOne) SetCreatedAt(t time.Time) *FriendshipUpdateOne { + fuo.mutation.SetCreatedAt(t) + return fuo +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (fuo *FriendshipUpdateOne) SetNillableCreatedAt(t *time.Time) *FriendshipUpdateOne { + if t != nil { + fuo.SetCreatedAt(*t) + } + return fuo +} + +// SetUserID sets the "user_id" field. +func (fuo *FriendshipUpdateOne) SetUserID(i int) *FriendshipUpdateOne { + fuo.mutation.SetUserID(i) + return fuo +} + +// SetNillableUserID sets the "user_id" field if the given value is not nil. +func (fuo *FriendshipUpdateOne) SetNillableUserID(i *int) *FriendshipUpdateOne { + if i != nil { + fuo.SetUserID(*i) + } + return fuo +} + +// SetFriendID sets the "friend_id" field. +func (fuo *FriendshipUpdateOne) SetFriendID(i int) *FriendshipUpdateOne { + fuo.mutation.SetFriendID(i) + return fuo +} + +// SetNillableFriendID sets the "friend_id" field if the given value is not nil. +func (fuo *FriendshipUpdateOne) SetNillableFriendID(i *int) *FriendshipUpdateOne { + if i != nil { + fuo.SetFriendID(*i) + } + return fuo +} + +// SetUser sets the "user" edge to the User entity. +func (fuo *FriendshipUpdateOne) SetUser(u *User) *FriendshipUpdateOne { + return fuo.SetUserID(u.ID) +} + +// SetFriend sets the "friend" edge to the User entity. +func (fuo *FriendshipUpdateOne) SetFriend(u *User) *FriendshipUpdateOne { + return fuo.SetFriendID(u.ID) +} + +// Mutation returns the FriendshipMutation object of the builder. +func (fuo *FriendshipUpdateOne) Mutation() *FriendshipMutation { + return fuo.mutation +} + +// ClearUser clears the "user" edge to the User entity. +func (fuo *FriendshipUpdateOne) ClearUser() *FriendshipUpdateOne { + fuo.mutation.ClearUser() + return fuo +} + +// ClearFriend clears the "friend" edge to the User entity. +func (fuo *FriendshipUpdateOne) ClearFriend() *FriendshipUpdateOne { + fuo.mutation.ClearFriend() + return fuo +} + +// Where appends a list predicates to the FriendshipUpdate builder. +func (fuo *FriendshipUpdateOne) Where(ps ...predicate.Friendship) *FriendshipUpdateOne { + fuo.mutation.Where(ps...) + return fuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (fuo *FriendshipUpdateOne) Select(field string, fields ...string) *FriendshipUpdateOne { + fuo.fields = append([]string{field}, fields...) + return fuo +} + +// Save executes the query and returns the updated Friendship entity. +func (fuo *FriendshipUpdateOne) Save(ctx context.Context) (*Friendship, error) { + return withHooks(ctx, fuo.sqlSave, fuo.mutation, fuo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (fuo *FriendshipUpdateOne) SaveX(ctx context.Context) *Friendship { + node, err := fuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (fuo *FriendshipUpdateOne) Exec(ctx context.Context) error { + _, err := fuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (fuo *FriendshipUpdateOne) ExecX(ctx context.Context) { + if err := fuo.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (fuo *FriendshipUpdateOne) check() error { + if fuo.mutation.UserCleared() && len(fuo.mutation.UserIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "Friendship.user"`) + } + if fuo.mutation.FriendCleared() && len(fuo.mutation.FriendIDs()) > 0 { + return errors.New(`ent: clearing a required unique edge "Friendship.friend"`) + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (fuo *FriendshipUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *FriendshipUpdateOne { + fuo.modifiers = append(fuo.modifiers, modifiers...) + return fuo +} + +func (fuo *FriendshipUpdateOne) sqlSave(ctx context.Context) (_node *Friendship, err error) { + if err := fuo.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(friendship.Table, friendship.Columns, sqlgraph.NewFieldSpec(friendship.FieldID, field.TypeInt)) + id, ok := fuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Friendship.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := fuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, friendship.FieldID) + for _, f := range fields { + if !friendship.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != friendship.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := fuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := fuo.mutation.CreatedAt(); ok { + _spec.SetField(friendship.FieldCreatedAt, field.TypeTime, value) + } + if fuo.mutation.UserCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: friendship.UserTable, + Columns: []string{friendship.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := fuo.mutation.UserIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: friendship.UserTable, + Columns: []string{friendship.UserColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if fuo.mutation.FriendCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: friendship.FriendTable, + Columns: []string{friendship.FriendColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := fuo.mutation.FriendIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: friendship.FriendTable, + Columns: []string{friendship.FriendColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(fuo.modifiers...) + _node = &Friendship{config: fuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, fuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{friendship.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + fuo.mutation.done = true + return _node, nil +} diff --git a/entgql/internal/todoglobalid/ent/gql_collection.go b/entgql/internal/todoglobalid/ent/gql_collection.go new file mode 100644 index 000000000..2cbd53e8e --- /dev/null +++ b/entgql/internal/todoglobalid/ent/gql_collection.go @@ -0,0 +1,1711 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "database/sql/driver" + "fmt" + + "entgo.io/contrib/entgql" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/billproduct" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/category" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/friendship" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/group" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/onetomany" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/project" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/todo" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/user" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/workspace" + "entgo.io/ent/dialect/sql" + "github.com/99designs/gqlgen/graphql" +) + +// CollectFields tells the query-builder to eagerly load connected nodes by resolver context. +func (bp *BillProductQuery) CollectFields(ctx context.Context, satisfies ...string) (*BillProductQuery, error) { + fc := graphql.GetFieldContext(ctx) + if fc == nil { + return bp, nil + } + if err := bp.collectField(ctx, false, graphql.GetOperationContext(ctx), fc.Field, nil, satisfies...); err != nil { + return nil, err + } + return bp, nil +} + +func (bp *BillProductQuery) collectField(ctx context.Context, oneNode bool, opCtx *graphql.OperationContext, collected graphql.CollectedField, path []string, satisfies ...string) error { + path = append([]string(nil), path...) + var ( + unknownSeen bool + fieldSeen = make(map[string]struct{}, len(billproduct.Columns)) + selectedFields = []string{billproduct.FieldID} + ) + for _, field := range graphql.CollectFields(opCtx, collected.Selections, satisfies) { + switch field.Name { + case "name": + if _, ok := fieldSeen[billproduct.FieldName]; !ok { + selectedFields = append(selectedFields, billproduct.FieldName) + fieldSeen[billproduct.FieldName] = struct{}{} + } + case "sku": + if _, ok := fieldSeen[billproduct.FieldSku]; !ok { + selectedFields = append(selectedFields, billproduct.FieldSku) + fieldSeen[billproduct.FieldSku] = struct{}{} + } + case "quantity": + if _, ok := fieldSeen[billproduct.FieldQuantity]; !ok { + selectedFields = append(selectedFields, billproduct.FieldQuantity) + fieldSeen[billproduct.FieldQuantity] = struct{}{} + } + case "id": + case "__typename": + default: + unknownSeen = true + } + } + if !unknownSeen { + bp.Select(selectedFields...) + } + return nil +} + +type billproductPaginateArgs struct { + first, last *int + after, before *Cursor + opts []BillProductPaginateOption +} + +func newBillProductPaginateArgs(rv map[string]any) *billproductPaginateArgs { + args := &billproductPaginateArgs{} + if rv == nil { + return args + } + if v := rv[firstField]; v != nil { + args.first = v.(*int) + } + if v := rv[lastField]; v != nil { + args.last = v.(*int) + } + if v := rv[afterField]; v != nil { + args.after = v.(*Cursor) + } + if v := rv[beforeField]; v != nil { + args.before = v.(*Cursor) + } + if v, ok := rv[whereField].(*BillProductWhereInput); ok { + args.opts = append(args.opts, WithBillProductFilter(v.Filter)) + } + return args +} + +// CollectFields tells the query-builder to eagerly load connected nodes by resolver context. +func (c *CategoryQuery) CollectFields(ctx context.Context, satisfies ...string) (*CategoryQuery, error) { + fc := graphql.GetFieldContext(ctx) + if fc == nil { + return c, nil + } + if err := c.collectField(ctx, false, graphql.GetOperationContext(ctx), fc.Field, nil, satisfies...); err != nil { + return nil, err + } + return c, nil +} + +func (c *CategoryQuery) collectField(ctx context.Context, oneNode bool, opCtx *graphql.OperationContext, collected graphql.CollectedField, path []string, satisfies ...string) error { + path = append([]string(nil), path...) + var ( + unknownSeen bool + fieldSeen = make(map[string]struct{}, len(category.Columns)) + selectedFields = []string{category.FieldID} + ) + for _, field := range graphql.CollectFields(opCtx, collected.Selections, satisfies) { + switch field.Name { + + case "todos": + var ( + alias = field.Alias + path = append(path, alias) + query = (&TodoClient{config: c.config}).Query() + ) + args := newTodoPaginateArgs(fieldArgs(ctx, new(TodoWhereInput), path...)) + if err := validateFirstLast(args.first, args.last); err != nil { + return fmt.Errorf("validate first and last in path %q: %w", path, err) + } + pager, err := newTodoPager(args.opts, args.last != nil) + if err != nil { + return fmt.Errorf("create new pager in path %q: %w", path, err) + } + if query, err = pager.applyFilter(query); err != nil { + return err + } + ignoredEdges := !hasCollectedField(ctx, append(path, edgesField)...) + if hasCollectedField(ctx, append(path, totalCountField)...) || hasCollectedField(ctx, append(path, pageInfoField)...) { + hasPagination := args.after != nil || args.first != nil || args.before != nil || args.last != nil + if hasPagination || ignoredEdges { + query := query.Clone() + c.loadTotal = append(c.loadTotal, func(ctx context.Context, nodes []*Category) error { + ids := make([]driver.Value, len(nodes)) + for i := range nodes { + ids[i] = nodes[i].ID + } + var v []struct { + NodeID int `sql:"category_id"` + Count int `sql:"count"` + } + query.Where(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(category.TodosColumn), ids...)) + }) + if err := query.GroupBy(category.TodosColumn).Aggregate(Count()).Scan(ctx, &v); err != nil { + return err + } + m := make(map[int]int, len(v)) + for i := range v { + m[v[i].NodeID] = v[i].Count + } + for i := range nodes { + n := m[nodes[i].ID] + if nodes[i].Edges.totalCount[0] == nil { + nodes[i].Edges.totalCount[0] = make(map[string]int) + } + nodes[i].Edges.totalCount[0][alias] = n + } + return nil + }) + } else { + c.loadTotal = append(c.loadTotal, func(_ context.Context, nodes []*Category) error { + for i := range nodes { + n := len(nodes[i].Edges.Todos) + if nodes[i].Edges.totalCount[0] == nil { + nodes[i].Edges.totalCount[0] = make(map[string]int) + } + nodes[i].Edges.totalCount[0][alias] = n + } + return nil + }) + } + } + if ignoredEdges || (args.first != nil && *args.first == 0) || (args.last != nil && *args.last == 0) { + continue + } + if query, err = pager.applyCursors(query, args.after, args.before); err != nil { + return err + } + path = append(path, edgesField, nodeField) + if field := collectedField(ctx, path...); field != nil { + if err := query.collectField(ctx, false, opCtx, *field, path, mayAddCondition(satisfies, todoImplementors)...); err != nil { + return err + } + } + if limit := paginateLimit(args.first, args.last); limit > 0 { + if oneNode { + pager.applyOrder(query.Limit(limit)) + } else { + modify := entgql.LimitPerRow(category.TodosColumn, limit, pager.orderExpr(query)) + query.modifiers = append(query.modifiers, modify) + } + } else { + query = pager.applyOrder(query) + } + c.WithNamedTodos(alias, func(wq *TodoQuery) { + *wq = *query + }) + + case "subCategories": + var ( + alias = field.Alias + path = append(path, alias) + query = (&CategoryClient{config: c.config}).Query() + ) + args := newCategoryPaginateArgs(fieldArgs(ctx, new(CategoryWhereInput), path...)) + if err := validateFirstLast(args.first, args.last); err != nil { + return fmt.Errorf("validate first and last in path %q: %w", path, err) + } + pager, err := newCategoryPager(args.opts, args.last != nil) + if err != nil { + return fmt.Errorf("create new pager in path %q: %w", path, err) + } + if query, err = pager.applyFilter(query); err != nil { + return err + } + ignoredEdges := !hasCollectedField(ctx, append(path, edgesField)...) + if hasCollectedField(ctx, append(path, totalCountField)...) || hasCollectedField(ctx, append(path, pageInfoField)...) { + hasPagination := args.after != nil || args.first != nil || args.before != nil || args.last != nil + if hasPagination || ignoredEdges { + query := query.Clone() + c.loadTotal = append(c.loadTotal, func(ctx context.Context, nodes []*Category) error { + ids := make([]driver.Value, len(nodes)) + for i := range nodes { + ids[i] = nodes[i].ID + } + var v []struct { + NodeID int `sql:"category_id"` + Count int `sql:"count"` + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(category.SubCategoriesTable) + s.Join(joinT).On(s.C(category.FieldID), joinT.C(category.SubCategoriesPrimaryKey[1])) + s.Where(sql.InValues(joinT.C(category.SubCategoriesPrimaryKey[0]), ids...)) + s.Select(joinT.C(category.SubCategoriesPrimaryKey[0]), sql.Count("*")) + s.GroupBy(joinT.C(category.SubCategoriesPrimaryKey[0])) + }) + if err := query.Select().Scan(ctx, &v); err != nil { + return err + } + m := make(map[int]int, len(v)) + for i := range v { + m[v[i].NodeID] = v[i].Count + } + for i := range nodes { + n := m[nodes[i].ID] + if nodes[i].Edges.totalCount[1] == nil { + nodes[i].Edges.totalCount[1] = make(map[string]int) + } + nodes[i].Edges.totalCount[1][alias] = n + } + return nil + }) + } else { + c.loadTotal = append(c.loadTotal, func(_ context.Context, nodes []*Category) error { + for i := range nodes { + n := len(nodes[i].Edges.SubCategories) + if nodes[i].Edges.totalCount[1] == nil { + nodes[i].Edges.totalCount[1] = make(map[string]int) + } + nodes[i].Edges.totalCount[1][alias] = n + } + return nil + }) + } + } + if ignoredEdges || (args.first != nil && *args.first == 0) || (args.last != nil && *args.last == 0) { + continue + } + if query, err = pager.applyCursors(query, args.after, args.before); err != nil { + return err + } + path = append(path, edgesField, nodeField) + if field := collectedField(ctx, path...); field != nil { + if err := query.collectField(ctx, false, opCtx, *field, path, mayAddCondition(satisfies, categoryImplementors)...); err != nil { + return err + } + } + if limit := paginateLimit(args.first, args.last); limit > 0 { + if oneNode { + pager.applyOrder(query.Limit(limit)) + } else { + modify := entgql.LimitPerRow(category.SubCategoriesPrimaryKey[0], limit, pager.orderExpr(query)) + query.modifiers = append(query.modifiers, modify) + } + } else { + query = pager.applyOrder(query) + } + c.WithNamedSubCategories(alias, func(wq *CategoryQuery) { + *wq = *query + }) + case "text": + if _, ok := fieldSeen[category.FieldText]; !ok { + selectedFields = append(selectedFields, category.FieldText) + fieldSeen[category.FieldText] = struct{}{} + } + case "status": + if _, ok := fieldSeen[category.FieldStatus]; !ok { + selectedFields = append(selectedFields, category.FieldStatus) + fieldSeen[category.FieldStatus] = struct{}{} + } + case "config": + if _, ok := fieldSeen[category.FieldConfig]; !ok { + selectedFields = append(selectedFields, category.FieldConfig) + fieldSeen[category.FieldConfig] = struct{}{} + } + case "types": + if _, ok := fieldSeen[category.FieldTypes]; !ok { + selectedFields = append(selectedFields, category.FieldTypes) + fieldSeen[category.FieldTypes] = struct{}{} + } + case "duration": + if _, ok := fieldSeen[category.FieldDuration]; !ok { + selectedFields = append(selectedFields, category.FieldDuration) + fieldSeen[category.FieldDuration] = struct{}{} + } + case "count": + if _, ok := fieldSeen[category.FieldCount]; !ok { + selectedFields = append(selectedFields, category.FieldCount) + fieldSeen[category.FieldCount] = struct{}{} + } + case "strings": + if _, ok := fieldSeen[category.FieldStrings]; !ok { + selectedFields = append(selectedFields, category.FieldStrings) + fieldSeen[category.FieldStrings] = struct{}{} + } + case "id": + case "__typename": + default: + unknownSeen = true + } + } + if !unknownSeen { + c.Select(selectedFields...) + } + return nil +} + +type categoryPaginateArgs struct { + first, last *int + after, before *Cursor + opts []CategoryPaginateOption +} + +func newCategoryPaginateArgs(rv map[string]any) *categoryPaginateArgs { + args := &categoryPaginateArgs{} + if rv == nil { + return args + } + if v := rv[firstField]; v != nil { + args.first = v.(*int) + } + if v := rv[lastField]; v != nil { + args.last = v.(*int) + } + if v := rv[afterField]; v != nil { + args.after = v.(*Cursor) + } + if v := rv[beforeField]; v != nil { + args.before = v.(*Cursor) + } + if v, ok := rv[orderByField]; ok { + switch v := v.(type) { + case []*CategoryOrder: + args.opts = append(args.opts, WithCategoryOrder(v)) + case []any: + var orders []*CategoryOrder + for i := range v { + mv, ok := v[i].(map[string]any) + if !ok { + continue + } + var ( + err1, err2 error + order = &CategoryOrder{Field: &CategoryOrderField{}, Direction: entgql.OrderDirectionAsc} + ) + if d, ok := mv[directionField]; ok { + err1 = order.Direction.UnmarshalGQL(d) + } + if f, ok := mv[fieldField]; ok { + err2 = order.Field.UnmarshalGQL(f) + } + if err1 == nil && err2 == nil { + orders = append(orders, order) + } + } + args.opts = append(args.opts, WithCategoryOrder(orders)) + } + } + if v, ok := rv[whereField].(*CategoryWhereInput); ok { + args.opts = append(args.opts, WithCategoryFilter(v.Filter)) + } + return args +} + +// CollectFields tells the query-builder to eagerly load connected nodes by resolver context. +func (f *FriendshipQuery) CollectFields(ctx context.Context, satisfies ...string) (*FriendshipQuery, error) { + fc := graphql.GetFieldContext(ctx) + if fc == nil { + return f, nil + } + if err := f.collectField(ctx, false, graphql.GetOperationContext(ctx), fc.Field, nil, satisfies...); err != nil { + return nil, err + } + return f, nil +} + +func (f *FriendshipQuery) collectField(ctx context.Context, oneNode bool, opCtx *graphql.OperationContext, collected graphql.CollectedField, path []string, satisfies ...string) error { + path = append([]string(nil), path...) + var ( + unknownSeen bool + fieldSeen = make(map[string]struct{}, len(friendship.Columns)) + selectedFields = []string{friendship.FieldID} + ) + for _, field := range graphql.CollectFields(opCtx, collected.Selections, satisfies) { + switch field.Name { + + case "user": + var ( + alias = field.Alias + path = append(path, alias) + query = (&UserClient{config: f.config}).Query() + ) + if err := query.collectField(ctx, oneNode, opCtx, field, path, mayAddCondition(satisfies, userImplementors)...); err != nil { + return err + } + f.withUser = query + if _, ok := fieldSeen[friendship.FieldUserID]; !ok { + selectedFields = append(selectedFields, friendship.FieldUserID) + fieldSeen[friendship.FieldUserID] = struct{}{} + } + + case "friend": + var ( + alias = field.Alias + path = append(path, alias) + query = (&UserClient{config: f.config}).Query() + ) + if err := query.collectField(ctx, oneNode, opCtx, field, path, mayAddCondition(satisfies, userImplementors)...); err != nil { + return err + } + f.withFriend = query + if _, ok := fieldSeen[friendship.FieldFriendID]; !ok { + selectedFields = append(selectedFields, friendship.FieldFriendID) + fieldSeen[friendship.FieldFriendID] = struct{}{} + } + case "createdAt": + if _, ok := fieldSeen[friendship.FieldCreatedAt]; !ok { + selectedFields = append(selectedFields, friendship.FieldCreatedAt) + fieldSeen[friendship.FieldCreatedAt] = struct{}{} + } + case "userID": + if _, ok := fieldSeen[friendship.FieldUserID]; !ok { + selectedFields = append(selectedFields, friendship.FieldUserID) + fieldSeen[friendship.FieldUserID] = struct{}{} + } + case "friendID": + if _, ok := fieldSeen[friendship.FieldFriendID]; !ok { + selectedFields = append(selectedFields, friendship.FieldFriendID) + fieldSeen[friendship.FieldFriendID] = struct{}{} + } + case "id": + case "__typename": + default: + unknownSeen = true + } + } + if !unknownSeen { + f.Select(selectedFields...) + } + return nil +} + +type friendshipPaginateArgs struct { + first, last *int + after, before *Cursor + opts []FriendshipPaginateOption +} + +func newFriendshipPaginateArgs(rv map[string]any) *friendshipPaginateArgs { + args := &friendshipPaginateArgs{} + if rv == nil { + return args + } + if v := rv[firstField]; v != nil { + args.first = v.(*int) + } + if v := rv[lastField]; v != nil { + args.last = v.(*int) + } + if v := rv[afterField]; v != nil { + args.after = v.(*Cursor) + } + if v := rv[beforeField]; v != nil { + args.before = v.(*Cursor) + } + if v, ok := rv[whereField].(*FriendshipWhereInput); ok { + args.opts = append(args.opts, WithFriendshipFilter(v.Filter)) + } + return args +} + +// CollectFields tells the query-builder to eagerly load connected nodes by resolver context. +func (gr *GroupQuery) CollectFields(ctx context.Context, satisfies ...string) (*GroupQuery, error) { + fc := graphql.GetFieldContext(ctx) + if fc == nil { + return gr, nil + } + if err := gr.collectField(ctx, false, graphql.GetOperationContext(ctx), fc.Field, nil, satisfies...); err != nil { + return nil, err + } + return gr, nil +} + +func (gr *GroupQuery) collectField(ctx context.Context, oneNode bool, opCtx *graphql.OperationContext, collected graphql.CollectedField, path []string, satisfies ...string) error { + path = append([]string(nil), path...) + var ( + unknownSeen bool + fieldSeen = make(map[string]struct{}, len(group.Columns)) + selectedFields = []string{group.FieldID} + ) + for _, field := range graphql.CollectFields(opCtx, collected.Selections, satisfies) { + switch field.Name { + + case "users": + var ( + alias = field.Alias + path = append(path, alias) + query = (&UserClient{config: gr.config}).Query() + ) + args := newUserPaginateArgs(fieldArgs(ctx, new(UserWhereInput), path...)) + if err := validateFirstLast(args.first, args.last); err != nil { + return fmt.Errorf("validate first and last in path %q: %w", path, err) + } + pager, err := newUserPager(args.opts, args.last != nil) + if err != nil { + return fmt.Errorf("create new pager in path %q: %w", path, err) + } + if query, err = pager.applyFilter(query); err != nil { + return err + } + ignoredEdges := !hasCollectedField(ctx, append(path, edgesField)...) + if hasCollectedField(ctx, append(path, totalCountField)...) || hasCollectedField(ctx, append(path, pageInfoField)...) { + hasPagination := args.after != nil || args.first != nil || args.before != nil || args.last != nil + if hasPagination || ignoredEdges { + query := query.Clone() + gr.loadTotal = append(gr.loadTotal, func(ctx context.Context, nodes []*Group) error { + ids := make([]driver.Value, len(nodes)) + for i := range nodes { + ids[i] = nodes[i].ID + } + var v []struct { + NodeID int `sql:"group_id"` + Count int `sql:"count"` + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(group.UsersTable) + s.Join(joinT).On(s.C(user.FieldID), joinT.C(group.UsersPrimaryKey[0])) + s.Where(sql.InValues(joinT.C(group.UsersPrimaryKey[1]), ids...)) + s.Select(joinT.C(group.UsersPrimaryKey[1]), sql.Count("*")) + s.GroupBy(joinT.C(group.UsersPrimaryKey[1])) + }) + if err := query.Select().Scan(ctx, &v); err != nil { + return err + } + m := make(map[int]int, len(v)) + for i := range v { + m[v[i].NodeID] = v[i].Count + } + for i := range nodes { + n := m[nodes[i].ID] + if nodes[i].Edges.totalCount[0] == nil { + nodes[i].Edges.totalCount[0] = make(map[string]int) + } + nodes[i].Edges.totalCount[0][alias] = n + } + return nil + }) + } else { + gr.loadTotal = append(gr.loadTotal, func(_ context.Context, nodes []*Group) error { + for i := range nodes { + n := len(nodes[i].Edges.Users) + if nodes[i].Edges.totalCount[0] == nil { + nodes[i].Edges.totalCount[0] = make(map[string]int) + } + nodes[i].Edges.totalCount[0][alias] = n + } + return nil + }) + } + } + if ignoredEdges || (args.first != nil && *args.first == 0) || (args.last != nil && *args.last == 0) { + continue + } + if query, err = pager.applyCursors(query, args.after, args.before); err != nil { + return err + } + path = append(path, edgesField, nodeField) + if field := collectedField(ctx, path...); field != nil { + if err := query.collectField(ctx, false, opCtx, *field, path, mayAddCondition(satisfies, userImplementors)...); err != nil { + return err + } + } + if limit := paginateLimit(args.first, args.last); limit > 0 { + if oneNode { + pager.applyOrder(query.Limit(limit)) + } else { + modify := entgql.LimitPerRow(group.UsersPrimaryKey[1], limit, pager.orderExpr(query)) + query.modifiers = append(query.modifiers, modify) + } + } else { + query = pager.applyOrder(query) + } + gr.WithNamedUsers(alias, func(wq *UserQuery) { + *wq = *query + }) + case "name": + if _, ok := fieldSeen[group.FieldName]; !ok { + selectedFields = append(selectedFields, group.FieldName) + fieldSeen[group.FieldName] = struct{}{} + } + case "id": + case "__typename": + default: + unknownSeen = true + } + } + if !unknownSeen { + gr.Select(selectedFields...) + } + return nil +} + +type groupPaginateArgs struct { + first, last *int + after, before *Cursor + opts []GroupPaginateOption +} + +func newGroupPaginateArgs(rv map[string]any) *groupPaginateArgs { + args := &groupPaginateArgs{} + if rv == nil { + return args + } + if v := rv[firstField]; v != nil { + args.first = v.(*int) + } + if v := rv[lastField]; v != nil { + args.last = v.(*int) + } + if v := rv[afterField]; v != nil { + args.after = v.(*Cursor) + } + if v := rv[beforeField]; v != nil { + args.before = v.(*Cursor) + } + if v, ok := rv[whereField].(*GroupWhereInput); ok { + args.opts = append(args.opts, WithGroupFilter(v.Filter)) + } + return args +} + +// CollectFields tells the query-builder to eagerly load connected nodes by resolver context. +func (otm *OneToManyQuery) CollectFields(ctx context.Context, satisfies ...string) (*OneToManyQuery, error) { + fc := graphql.GetFieldContext(ctx) + if fc == nil { + return otm, nil + } + if err := otm.collectField(ctx, false, graphql.GetOperationContext(ctx), fc.Field, nil, satisfies...); err != nil { + return nil, err + } + return otm, nil +} + +func (otm *OneToManyQuery) collectField(ctx context.Context, oneNode bool, opCtx *graphql.OperationContext, collected graphql.CollectedField, path []string, satisfies ...string) error { + path = append([]string(nil), path...) + var ( + unknownSeen bool + fieldSeen = make(map[string]struct{}, len(onetomany.Columns)) + selectedFields = []string{onetomany.FieldID} + ) + for _, field := range graphql.CollectFields(opCtx, collected.Selections, satisfies) { + switch field.Name { + + case "parent": + var ( + alias = field.Alias + path = append(path, alias) + query = (&OneToManyClient{config: otm.config}).Query() + ) + if err := query.collectField(ctx, oneNode, opCtx, field, path, mayAddCondition(satisfies, onetomanyImplementors)...); err != nil { + return err + } + otm.withParent = query + if _, ok := fieldSeen[onetomany.FieldParentID]; !ok { + selectedFields = append(selectedFields, onetomany.FieldParentID) + fieldSeen[onetomany.FieldParentID] = struct{}{} + } + + case "children": + var ( + alias = field.Alias + path = append(path, alias) + query = (&OneToManyClient{config: otm.config}).Query() + ) + if err := query.collectField(ctx, false, opCtx, field, path, mayAddCondition(satisfies, onetomanyImplementors)...); err != nil { + return err + } + otm.WithNamedChildren(alias, func(wq *OneToManyQuery) { + *wq = *query + }) + case "name": + if _, ok := fieldSeen[onetomany.FieldName]; !ok { + selectedFields = append(selectedFields, onetomany.FieldName) + fieldSeen[onetomany.FieldName] = struct{}{} + } + case "field2": + if _, ok := fieldSeen[onetomany.FieldField2]; !ok { + selectedFields = append(selectedFields, onetomany.FieldField2) + fieldSeen[onetomany.FieldField2] = struct{}{} + } + case "id": + case "__typename": + default: + unknownSeen = true + } + } + if !unknownSeen { + otm.Select(selectedFields...) + } + return nil +} + +type onetomanyPaginateArgs struct { + first, last *int + after, before *Cursor + opts []OneToManyPaginateOption +} + +func newOneToManyPaginateArgs(rv map[string]any) *onetomanyPaginateArgs { + args := &onetomanyPaginateArgs{} + if rv == nil { + return args + } + if v := rv[firstField]; v != nil { + args.first = v.(*int) + } + if v := rv[lastField]; v != nil { + args.last = v.(*int) + } + if v := rv[afterField]; v != nil { + args.after = v.(*Cursor) + } + if v := rv[beforeField]; v != nil { + args.before = v.(*Cursor) + } + if v, ok := rv[orderByField]; ok { + switch v := v.(type) { + case map[string]any: + var ( + err1, err2 error + order = &OneToManyOrder{Field: &OneToManyOrderField{}, Direction: entgql.OrderDirectionAsc} + ) + if d, ok := v[directionField]; ok { + err1 = order.Direction.UnmarshalGQL(d) + } + if f, ok := v[fieldField]; ok { + err2 = order.Field.UnmarshalGQL(f) + } + if err1 == nil && err2 == nil { + args.opts = append(args.opts, WithOneToManyOrder(order)) + } + case *OneToManyOrder: + if v != nil { + args.opts = append(args.opts, WithOneToManyOrder(v)) + } + } + } + if v, ok := rv[whereField].(*OneToManyWhereInput); ok { + args.opts = append(args.opts, WithOneToManyFilter(v.Filter)) + } + return args +} + +// CollectFields tells the query-builder to eagerly load connected nodes by resolver context. +func (pr *ProjectQuery) CollectFields(ctx context.Context, satisfies ...string) (*ProjectQuery, error) { + fc := graphql.GetFieldContext(ctx) + if fc == nil { + return pr, nil + } + if err := pr.collectField(ctx, false, graphql.GetOperationContext(ctx), fc.Field, nil, satisfies...); err != nil { + return nil, err + } + return pr, nil +} + +func (pr *ProjectQuery) collectField(ctx context.Context, oneNode bool, opCtx *graphql.OperationContext, collected graphql.CollectedField, path []string, satisfies ...string) error { + path = append([]string(nil), path...) + for _, field := range graphql.CollectFields(opCtx, collected.Selections, satisfies) { + switch field.Name { + + case "todos": + var ( + alias = field.Alias + path = append(path, alias) + query = (&TodoClient{config: pr.config}).Query() + ) + args := newTodoPaginateArgs(fieldArgs(ctx, new(TodoWhereInput), path...)) + if err := validateFirstLast(args.first, args.last); err != nil { + return fmt.Errorf("validate first and last in path %q: %w", path, err) + } + pager, err := newTodoPager(args.opts, args.last != nil) + if err != nil { + return fmt.Errorf("create new pager in path %q: %w", path, err) + } + if query, err = pager.applyFilter(query); err != nil { + return err + } + ignoredEdges := !hasCollectedField(ctx, append(path, edgesField)...) + if hasCollectedField(ctx, append(path, totalCountField)...) || hasCollectedField(ctx, append(path, pageInfoField)...) { + hasPagination := args.after != nil || args.first != nil || args.before != nil || args.last != nil + if hasPagination || ignoredEdges { + query := query.Clone() + pr.loadTotal = append(pr.loadTotal, func(ctx context.Context, nodes []*Project) error { + ids := make([]driver.Value, len(nodes)) + for i := range nodes { + ids[i] = nodes[i].ID + } + var v []struct { + NodeID int `sql:"project_todos"` + Count int `sql:"count"` + } + query.Where(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(project.TodosColumn), ids...)) + }) + if err := query.GroupBy(project.TodosColumn).Aggregate(Count()).Scan(ctx, &v); err != nil { + return err + } + m := make(map[int]int, len(v)) + for i := range v { + m[v[i].NodeID] = v[i].Count + } + for i := range nodes { + n := m[nodes[i].ID] + if nodes[i].Edges.totalCount[0] == nil { + nodes[i].Edges.totalCount[0] = make(map[string]int) + } + nodes[i].Edges.totalCount[0][alias] = n + } + return nil + }) + } else { + pr.loadTotal = append(pr.loadTotal, func(_ context.Context, nodes []*Project) error { + for i := range nodes { + n := len(nodes[i].Edges.Todos) + if nodes[i].Edges.totalCount[0] == nil { + nodes[i].Edges.totalCount[0] = make(map[string]int) + } + nodes[i].Edges.totalCount[0][alias] = n + } + return nil + }) + } + } + if ignoredEdges || (args.first != nil && *args.first == 0) || (args.last != nil && *args.last == 0) { + continue + } + if query, err = pager.applyCursors(query, args.after, args.before); err != nil { + return err + } + path = append(path, edgesField, nodeField) + if field := collectedField(ctx, path...); field != nil { + if err := query.collectField(ctx, false, opCtx, *field, path, mayAddCondition(satisfies, todoImplementors)...); err != nil { + return err + } + } + if limit := paginateLimit(args.first, args.last); limit > 0 { + if oneNode { + pager.applyOrder(query.Limit(limit)) + } else { + modify := entgql.LimitPerRow(project.TodosColumn, limit, pager.orderExpr(query)) + query.modifiers = append(query.modifiers, modify) + } + } else { + query = pager.applyOrder(query) + } + pr.WithNamedTodos(alias, func(wq *TodoQuery) { + *wq = *query + }) + } + } + return nil +} + +type projectPaginateArgs struct { + first, last *int + after, before *Cursor + opts []ProjectPaginateOption +} + +func newProjectPaginateArgs(rv map[string]any) *projectPaginateArgs { + args := &projectPaginateArgs{} + if rv == nil { + return args + } + if v := rv[firstField]; v != nil { + args.first = v.(*int) + } + if v := rv[lastField]; v != nil { + args.last = v.(*int) + } + if v := rv[afterField]; v != nil { + args.after = v.(*Cursor) + } + if v := rv[beforeField]; v != nil { + args.before = v.(*Cursor) + } + if v, ok := rv[whereField].(*ProjectWhereInput); ok { + args.opts = append(args.opts, WithProjectFilter(v.Filter)) + } + return args +} + +// CollectFields tells the query-builder to eagerly load connected nodes by resolver context. +func (t *TodoQuery) CollectFields(ctx context.Context, satisfies ...string) (*TodoQuery, error) { + fc := graphql.GetFieldContext(ctx) + if fc == nil { + return t, nil + } + if err := t.collectField(ctx, false, graphql.GetOperationContext(ctx), fc.Field, nil, satisfies...); err != nil { + return nil, err + } + return t, nil +} + +func (t *TodoQuery) collectField(ctx context.Context, oneNode bool, opCtx *graphql.OperationContext, collected graphql.CollectedField, path []string, satisfies ...string) error { + path = append([]string(nil), path...) + var ( + unknownSeen bool + fieldSeen = make(map[string]struct{}, len(todo.Columns)) + selectedFields = []string{todo.FieldID} + ) + for _, field := range graphql.CollectFields(opCtx, collected.Selections, satisfies) { + switch field.Name { + + case "parent": + var ( + alias = field.Alias + path = append(path, alias) + query = (&TodoClient{config: t.config}).Query() + ) + if err := query.collectField(ctx, oneNode, opCtx, field, path, mayAddCondition(satisfies, todoImplementors)...); err != nil { + return err + } + t.withParent = query + + case "children": + var ( + alias = field.Alias + path = append(path, alias) + query = (&TodoClient{config: t.config}).Query() + ) + args := newTodoPaginateArgs(fieldArgs(ctx, new(TodoWhereInput), path...)) + if err := validateFirstLast(args.first, args.last); err != nil { + return fmt.Errorf("validate first and last in path %q: %w", path, err) + } + pager, err := newTodoPager(args.opts, args.last != nil) + if err != nil { + return fmt.Errorf("create new pager in path %q: %w", path, err) + } + if query, err = pager.applyFilter(query); err != nil { + return err + } + ignoredEdges := !hasCollectedField(ctx, append(path, edgesField)...) + if hasCollectedField(ctx, append(path, totalCountField)...) || hasCollectedField(ctx, append(path, pageInfoField)...) { + hasPagination := args.after != nil || args.first != nil || args.before != nil || args.last != nil + if hasPagination || ignoredEdges { + query := query.Clone() + t.loadTotal = append(t.loadTotal, func(ctx context.Context, nodes []*Todo) error { + ids := make([]driver.Value, len(nodes)) + for i := range nodes { + ids[i] = nodes[i].ID + } + var v []struct { + NodeID int `sql:"todo_children"` + Count int `sql:"count"` + } + query.Where(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(todo.ChildrenColumn), ids...)) + }) + if err := query.GroupBy(todo.ChildrenColumn).Aggregate(Count()).Scan(ctx, &v); err != nil { + return err + } + m := make(map[int]int, len(v)) + for i := range v { + m[v[i].NodeID] = v[i].Count + } + for i := range nodes { + n := m[nodes[i].ID] + if nodes[i].Edges.totalCount[1] == nil { + nodes[i].Edges.totalCount[1] = make(map[string]int) + } + nodes[i].Edges.totalCount[1][alias] = n + } + return nil + }) + } else { + t.loadTotal = append(t.loadTotal, func(_ context.Context, nodes []*Todo) error { + for i := range nodes { + n := len(nodes[i].Edges.Children) + if nodes[i].Edges.totalCount[1] == nil { + nodes[i].Edges.totalCount[1] = make(map[string]int) + } + nodes[i].Edges.totalCount[1][alias] = n + } + return nil + }) + } + } + if ignoredEdges || (args.first != nil && *args.first == 0) || (args.last != nil && *args.last == 0) { + continue + } + if query, err = pager.applyCursors(query, args.after, args.before); err != nil { + return err + } + path = append(path, edgesField, nodeField) + if field := collectedField(ctx, path...); field != nil { + if err := query.collectField(ctx, false, opCtx, *field, path, mayAddCondition(satisfies, todoImplementors)...); err != nil { + return err + } + } + if limit := paginateLimit(args.first, args.last); limit > 0 { + if oneNode { + pager.applyOrder(query.Limit(limit)) + } else { + modify := entgql.LimitPerRow(todo.ChildrenColumn, limit, pager.orderExpr(query)) + query.modifiers = append(query.modifiers, modify) + } + } else { + query = pager.applyOrder(query) + } + t.WithNamedChildren(alias, func(wq *TodoQuery) { + *wq = *query + }) + + case "category": + var ( + alias = field.Alias + path = append(path, alias) + query = (&CategoryClient{config: t.config}).Query() + ) + if err := query.collectField(ctx, oneNode, opCtx, field, path, mayAddCondition(satisfies, categoryImplementors)...); err != nil { + return err + } + t.withCategory = query + if _, ok := fieldSeen[todo.FieldCategoryID]; !ok { + selectedFields = append(selectedFields, todo.FieldCategoryID) + fieldSeen[todo.FieldCategoryID] = struct{}{} + } + case "createdAt": + if _, ok := fieldSeen[todo.FieldCreatedAt]; !ok { + selectedFields = append(selectedFields, todo.FieldCreatedAt) + fieldSeen[todo.FieldCreatedAt] = struct{}{} + } + case "status": + if _, ok := fieldSeen[todo.FieldStatus]; !ok { + selectedFields = append(selectedFields, todo.FieldStatus) + fieldSeen[todo.FieldStatus] = struct{}{} + } + case "priorityOrder": + if _, ok := fieldSeen[todo.FieldPriority]; !ok { + selectedFields = append(selectedFields, todo.FieldPriority) + fieldSeen[todo.FieldPriority] = struct{}{} + } + case "text": + if _, ok := fieldSeen[todo.FieldText]; !ok { + selectedFields = append(selectedFields, todo.FieldText) + fieldSeen[todo.FieldText] = struct{}{} + } + case "categoryID", "category_id", "categoryX": + if _, ok := fieldSeen[todo.FieldCategoryID]; !ok { + selectedFields = append(selectedFields, todo.FieldCategoryID) + fieldSeen[todo.FieldCategoryID] = struct{}{} + } + case "init": + if _, ok := fieldSeen[todo.FieldInit]; !ok { + selectedFields = append(selectedFields, todo.FieldInit) + fieldSeen[todo.FieldInit] = struct{}{} + } + case "custom": + if _, ok := fieldSeen[todo.FieldCustom]; !ok { + selectedFields = append(selectedFields, todo.FieldCustom) + fieldSeen[todo.FieldCustom] = struct{}{} + } + case "customp": + if _, ok := fieldSeen[todo.FieldCustomp]; !ok { + selectedFields = append(selectedFields, todo.FieldCustomp) + fieldSeen[todo.FieldCustomp] = struct{}{} + } + case "value": + if _, ok := fieldSeen[todo.FieldValue]; !ok { + selectedFields = append(selectedFields, todo.FieldValue) + fieldSeen[todo.FieldValue] = struct{}{} + } + case "id": + case "__typename": + default: + unknownSeen = true + } + } + if !unknownSeen { + t.Select(selectedFields...) + } + return nil +} + +type todoPaginateArgs struct { + first, last *int + after, before *Cursor + opts []TodoPaginateOption +} + +func newTodoPaginateArgs(rv map[string]any) *todoPaginateArgs { + args := &todoPaginateArgs{} + if rv == nil { + return args + } + if v := rv[firstField]; v != nil { + args.first = v.(*int) + } + if v := rv[lastField]; v != nil { + args.last = v.(*int) + } + if v := rv[afterField]; v != nil { + args.after = v.(*Cursor) + } + if v := rv[beforeField]; v != nil { + args.before = v.(*Cursor) + } + if v, ok := rv[orderByField]; ok { + switch v := v.(type) { + case []*TodoOrder: + args.opts = append(args.opts, WithTodoOrder(v)) + case []any: + var orders []*TodoOrder + for i := range v { + mv, ok := v[i].(map[string]any) + if !ok { + continue + } + var ( + err1, err2 error + order = &TodoOrder{Field: &TodoOrderField{}, Direction: entgql.OrderDirectionAsc} + ) + if d, ok := mv[directionField]; ok { + err1 = order.Direction.UnmarshalGQL(d) + } + if f, ok := mv[fieldField]; ok { + err2 = order.Field.UnmarshalGQL(f) + } + if err1 == nil && err2 == nil { + orders = append(orders, order) + } + } + args.opts = append(args.opts, WithTodoOrder(orders)) + } + } + if v, ok := rv[whereField].(*TodoWhereInput); ok { + args.opts = append(args.opts, WithTodoFilter(v.Filter)) + } + return args +} + +// CollectFields tells the query-builder to eagerly load connected nodes by resolver context. +func (u *UserQuery) CollectFields(ctx context.Context, satisfies ...string) (*UserQuery, error) { + fc := graphql.GetFieldContext(ctx) + if fc == nil { + return u, nil + } + if err := u.collectField(ctx, false, graphql.GetOperationContext(ctx), fc.Field, nil, satisfies...); err != nil { + return nil, err + } + return u, nil +} + +func (u *UserQuery) collectField(ctx context.Context, oneNode bool, opCtx *graphql.OperationContext, collected graphql.CollectedField, path []string, satisfies ...string) error { + path = append([]string(nil), path...) + var ( + unknownSeen bool + fieldSeen = make(map[string]struct{}, len(user.Columns)) + selectedFields = []string{user.FieldID} + ) + for _, field := range graphql.CollectFields(opCtx, collected.Selections, satisfies) { + switch field.Name { + + case "groups": + var ( + alias = field.Alias + path = append(path, alias) + query = (&GroupClient{config: u.config}).Query() + ) + args := newGroupPaginateArgs(fieldArgs(ctx, new(GroupWhereInput), path...)) + if err := validateFirstLast(args.first, args.last); err != nil { + return fmt.Errorf("validate first and last in path %q: %w", path, err) + } + pager, err := newGroupPager(args.opts, args.last != nil) + if err != nil { + return fmt.Errorf("create new pager in path %q: %w", path, err) + } + if query, err = pager.applyFilter(query); err != nil { + return err + } + ignoredEdges := !hasCollectedField(ctx, append(path, edgesField)...) + if hasCollectedField(ctx, append(path, totalCountField)...) || hasCollectedField(ctx, append(path, pageInfoField)...) { + hasPagination := args.after != nil || args.first != nil || args.before != nil || args.last != nil + if hasPagination || ignoredEdges { + query := query.Clone() + u.loadTotal = append(u.loadTotal, func(ctx context.Context, nodes []*User) error { + ids := make([]driver.Value, len(nodes)) + for i := range nodes { + ids[i] = nodes[i].ID + } + var v []struct { + NodeID int `sql:"user_id"` + Count int `sql:"count"` + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(user.GroupsTable) + s.Join(joinT).On(s.C(group.FieldID), joinT.C(user.GroupsPrimaryKey[1])) + s.Where(sql.InValues(joinT.C(user.GroupsPrimaryKey[0]), ids...)) + s.Select(joinT.C(user.GroupsPrimaryKey[0]), sql.Count("*")) + s.GroupBy(joinT.C(user.GroupsPrimaryKey[0])) + }) + if err := query.Select().Scan(ctx, &v); err != nil { + return err + } + m := make(map[int]int, len(v)) + for i := range v { + m[v[i].NodeID] = v[i].Count + } + for i := range nodes { + n := m[nodes[i].ID] + if nodes[i].Edges.totalCount[0] == nil { + nodes[i].Edges.totalCount[0] = make(map[string]int) + } + nodes[i].Edges.totalCount[0][alias] = n + } + return nil + }) + } else { + u.loadTotal = append(u.loadTotal, func(_ context.Context, nodes []*User) error { + for i := range nodes { + n := len(nodes[i].Edges.Groups) + if nodes[i].Edges.totalCount[0] == nil { + nodes[i].Edges.totalCount[0] = make(map[string]int) + } + nodes[i].Edges.totalCount[0][alias] = n + } + return nil + }) + } + } + if ignoredEdges || (args.first != nil && *args.first == 0) || (args.last != nil && *args.last == 0) { + continue + } + if query, err = pager.applyCursors(query, args.after, args.before); err != nil { + return err + } + path = append(path, edgesField, nodeField) + if field := collectedField(ctx, path...); field != nil { + if err := query.collectField(ctx, false, opCtx, *field, path, mayAddCondition(satisfies, groupImplementors)...); err != nil { + return err + } + } + if limit := paginateLimit(args.first, args.last); limit > 0 { + if oneNode { + pager.applyOrder(query.Limit(limit)) + } else { + modify := entgql.LimitPerRow(user.GroupsPrimaryKey[0], limit, pager.orderExpr(query)) + query.modifiers = append(query.modifiers, modify) + } + } else { + query = pager.applyOrder(query) + } + u.WithNamedGroups(alias, func(wq *GroupQuery) { + *wq = *query + }) + + case "friends": + var ( + alias = field.Alias + path = append(path, alias) + query = (&UserClient{config: u.config}).Query() + ) + args := newUserPaginateArgs(fieldArgs(ctx, new(UserWhereInput), path...)) + if err := validateFirstLast(args.first, args.last); err != nil { + return fmt.Errorf("validate first and last in path %q: %w", path, err) + } + pager, err := newUserPager(args.opts, args.last != nil) + if err != nil { + return fmt.Errorf("create new pager in path %q: %w", path, err) + } + if query, err = pager.applyFilter(query); err != nil { + return err + } + ignoredEdges := !hasCollectedField(ctx, append(path, edgesField)...) + if hasCollectedField(ctx, append(path, totalCountField)...) || hasCollectedField(ctx, append(path, pageInfoField)...) { + hasPagination := args.after != nil || args.first != nil || args.before != nil || args.last != nil + if hasPagination || ignoredEdges { + query := query.Clone() + u.loadTotal = append(u.loadTotal, func(ctx context.Context, nodes []*User) error { + ids := make([]driver.Value, len(nodes)) + for i := range nodes { + ids[i] = nodes[i].ID + } + var v []struct { + NodeID int `sql:"user_id"` + Count int `sql:"count"` + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(user.FriendsTable) + s.Join(joinT).On(s.C(user.FieldID), joinT.C(user.FriendsPrimaryKey[1])) + s.Where(sql.InValues(joinT.C(user.FriendsPrimaryKey[0]), ids...)) + s.Select(joinT.C(user.FriendsPrimaryKey[0]), sql.Count("*")) + s.GroupBy(joinT.C(user.FriendsPrimaryKey[0])) + }) + if err := query.Select().Scan(ctx, &v); err != nil { + return err + } + m := make(map[int]int, len(v)) + for i := range v { + m[v[i].NodeID] = v[i].Count + } + for i := range nodes { + n := m[nodes[i].ID] + if nodes[i].Edges.totalCount[1] == nil { + nodes[i].Edges.totalCount[1] = make(map[string]int) + } + nodes[i].Edges.totalCount[1][alias] = n + } + return nil + }) + } else { + u.loadTotal = append(u.loadTotal, func(_ context.Context, nodes []*User) error { + for i := range nodes { + n := len(nodes[i].Edges.Friends) + if nodes[i].Edges.totalCount[1] == nil { + nodes[i].Edges.totalCount[1] = make(map[string]int) + } + nodes[i].Edges.totalCount[1][alias] = n + } + return nil + }) + } + } + if ignoredEdges || (args.first != nil && *args.first == 0) || (args.last != nil && *args.last == 0) { + continue + } + if query, err = pager.applyCursors(query, args.after, args.before); err != nil { + return err + } + path = append(path, edgesField, nodeField) + if field := collectedField(ctx, path...); field != nil { + if err := query.collectField(ctx, false, opCtx, *field, path, mayAddCondition(satisfies, userImplementors)...); err != nil { + return err + } + } + if limit := paginateLimit(args.first, args.last); limit > 0 { + if oneNode { + pager.applyOrder(query.Limit(limit)) + } else { + modify := entgql.LimitPerRow(user.FriendsPrimaryKey[0], limit, pager.orderExpr(query)) + query.modifiers = append(query.modifiers, modify) + } + } else { + query = pager.applyOrder(query) + } + u.WithNamedFriends(alias, func(wq *UserQuery) { + *wq = *query + }) + + case "friendships": + var ( + alias = field.Alias + path = append(path, alias) + query = (&FriendshipClient{config: u.config}).Query() + ) + args := newFriendshipPaginateArgs(fieldArgs(ctx, new(FriendshipWhereInput), path...)) + if err := validateFirstLast(args.first, args.last); err != nil { + return fmt.Errorf("validate first and last in path %q: %w", path, err) + } + pager, err := newFriendshipPager(args.opts, args.last != nil) + if err != nil { + return fmt.Errorf("create new pager in path %q: %w", path, err) + } + if query, err = pager.applyFilter(query); err != nil { + return err + } + ignoredEdges := !hasCollectedField(ctx, append(path, edgesField)...) + if hasCollectedField(ctx, append(path, totalCountField)...) || hasCollectedField(ctx, append(path, pageInfoField)...) { + hasPagination := args.after != nil || args.first != nil || args.before != nil || args.last != nil + if hasPagination || ignoredEdges { + query := query.Clone() + u.loadTotal = append(u.loadTotal, func(ctx context.Context, nodes []*User) error { + ids := make([]driver.Value, len(nodes)) + for i := range nodes { + ids[i] = nodes[i].ID + } + var v []struct { + NodeID int `sql:"user_id"` + Count int `sql:"count"` + } + query.Where(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(user.FriendshipsColumn), ids...)) + }) + if err := query.GroupBy(user.FriendshipsColumn).Aggregate(Count()).Scan(ctx, &v); err != nil { + return err + } + m := make(map[int]int, len(v)) + for i := range v { + m[v[i].NodeID] = v[i].Count + } + for i := range nodes { + n := m[nodes[i].ID] + if nodes[i].Edges.totalCount[2] == nil { + nodes[i].Edges.totalCount[2] = make(map[string]int) + } + nodes[i].Edges.totalCount[2][alias] = n + } + return nil + }) + } else { + u.loadTotal = append(u.loadTotal, func(_ context.Context, nodes []*User) error { + for i := range nodes { + n := len(nodes[i].Edges.Friendships) + if nodes[i].Edges.totalCount[2] == nil { + nodes[i].Edges.totalCount[2] = make(map[string]int) + } + nodes[i].Edges.totalCount[2][alias] = n + } + return nil + }) + } + } + if ignoredEdges || (args.first != nil && *args.first == 0) || (args.last != nil && *args.last == 0) { + continue + } + if query, err = pager.applyCursors(query, args.after, args.before); err != nil { + return err + } + path = append(path, edgesField, nodeField) + if field := collectedField(ctx, path...); field != nil { + if err := query.collectField(ctx, false, opCtx, *field, path, mayAddCondition(satisfies, friendshipImplementors)...); err != nil { + return err + } + } + if limit := paginateLimit(args.first, args.last); limit > 0 { + if oneNode { + pager.applyOrder(query.Limit(limit)) + } else { + modify := entgql.LimitPerRow(user.FriendshipsColumn, limit, pager.orderExpr(query)) + query.modifiers = append(query.modifiers, modify) + } + } else { + query = pager.applyOrder(query) + } + u.WithNamedFriendships(alias, func(wq *FriendshipQuery) { + *wq = *query + }) + case "name": + if _, ok := fieldSeen[user.FieldName]; !ok { + selectedFields = append(selectedFields, user.FieldName) + fieldSeen[user.FieldName] = struct{}{} + } + case "username": + if _, ok := fieldSeen[user.FieldUsername]; !ok { + selectedFields = append(selectedFields, user.FieldUsername) + fieldSeen[user.FieldUsername] = struct{}{} + } + case "requiredMetadata": + if _, ok := fieldSeen[user.FieldRequiredMetadata]; !ok { + selectedFields = append(selectedFields, user.FieldRequiredMetadata) + fieldSeen[user.FieldRequiredMetadata] = struct{}{} + } + case "metadata": + if _, ok := fieldSeen[user.FieldMetadata]; !ok { + selectedFields = append(selectedFields, user.FieldMetadata) + fieldSeen[user.FieldMetadata] = struct{}{} + } + case "id": + case "__typename": + default: + unknownSeen = true + } + } + if !unknownSeen { + u.Select(selectedFields...) + } + return nil +} + +type userPaginateArgs struct { + first, last *int + after, before *Cursor + opts []UserPaginateOption +} + +func newUserPaginateArgs(rv map[string]any) *userPaginateArgs { + args := &userPaginateArgs{} + if rv == nil { + return args + } + if v := rv[firstField]; v != nil { + args.first = v.(*int) + } + if v := rv[lastField]; v != nil { + args.last = v.(*int) + } + if v := rv[afterField]; v != nil { + args.after = v.(*Cursor) + } + if v := rv[beforeField]; v != nil { + args.before = v.(*Cursor) + } + if v, ok := rv[orderByField]; ok { + switch v := v.(type) { + case map[string]any: + var ( + err1, err2 error + order = &UserOrder{Field: &UserOrderField{}, Direction: entgql.OrderDirectionAsc} + ) + if d, ok := v[directionField]; ok { + err1 = order.Direction.UnmarshalGQL(d) + } + if f, ok := v[fieldField]; ok { + err2 = order.Field.UnmarshalGQL(f) + } + if err1 == nil && err2 == nil { + args.opts = append(args.opts, WithUserOrder(order)) + } + case *UserOrder: + if v != nil { + args.opts = append(args.opts, WithUserOrder(v)) + } + } + } + if v, ok := rv[whereField].(*UserWhereInput); ok { + args.opts = append(args.opts, WithUserFilter(v.Filter)) + } + return args +} + +// CollectFields tells the query-builder to eagerly load connected nodes by resolver context. +func (w *WorkspaceQuery) CollectFields(ctx context.Context, satisfies ...string) (*WorkspaceQuery, error) { + fc := graphql.GetFieldContext(ctx) + if fc == nil { + return w, nil + } + if err := w.collectField(ctx, false, graphql.GetOperationContext(ctx), fc.Field, nil, satisfies...); err != nil { + return nil, err + } + return w, nil +} + +func (w *WorkspaceQuery) collectField(ctx context.Context, oneNode bool, opCtx *graphql.OperationContext, collected graphql.CollectedField, path []string, satisfies ...string) error { + path = append([]string(nil), path...) + var ( + unknownSeen bool + fieldSeen = make(map[string]struct{}, len(workspace.Columns)) + selectedFields = []string{workspace.FieldID} + ) + for _, field := range graphql.CollectFields(opCtx, collected.Selections, satisfies) { + switch field.Name { + case "name": + if _, ok := fieldSeen[workspace.FieldName]; !ok { + selectedFields = append(selectedFields, workspace.FieldName) + fieldSeen[workspace.FieldName] = struct{}{} + } + case "id": + case "__typename": + default: + unknownSeen = true + } + } + if !unknownSeen { + w.Select(selectedFields...) + } + return nil +} + +type organizationPaginateArgs struct { + first, last *int + after, before *Cursor + opts []OrganizationPaginateOption +} + +func newOrganizationPaginateArgs(rv map[string]any) *organizationPaginateArgs { + args := &organizationPaginateArgs{} + if rv == nil { + return args + } + if v := rv[firstField]; v != nil { + args.first = v.(*int) + } + if v := rv[lastField]; v != nil { + args.last = v.(*int) + } + if v := rv[afterField]; v != nil { + args.after = v.(*Cursor) + } + if v := rv[beforeField]; v != nil { + args.before = v.(*Cursor) + } + if v, ok := rv[whereField].(*OrganizationWhereInput); ok { + args.opts = append(args.opts, WithOrganizationFilter(v.Filter)) + } + return args +} + +const ( + afterField = "after" + firstField = "first" + beforeField = "before" + lastField = "last" + orderByField = "orderBy" + directionField = "direction" + fieldField = "field" + whereField = "where" +) + +func fieldArgs(ctx context.Context, whereInput any, path ...string) map[string]any { + field := collectedField(ctx, path...) + if field == nil || field.Arguments == nil { + return nil + } + oc := graphql.GetOperationContext(ctx) + args := field.ArgumentMap(oc.Variables) + return unmarshalArgs(ctx, whereInput, args) +} + +// unmarshalArgs allows extracting the field arguments from their raw representation. +func unmarshalArgs(ctx context.Context, whereInput any, args map[string]any) map[string]any { + for _, k := range []string{firstField, lastField} { + v, ok := args[k] + if !ok || v == nil { + continue + } + i, err := graphql.UnmarshalInt(v) + if err == nil { + args[k] = &i + } + } + for _, k := range []string{beforeField, afterField} { + v, ok := args[k] + if !ok { + continue + } + c := &Cursor{} + if c.UnmarshalGQL(v) == nil { + args[k] = c + } + } + if v, ok := args[whereField]; ok && whereInput != nil { + if err := graphql.UnmarshalInputFromContext(ctx, v, whereInput); err == nil { + args[whereField] = whereInput + } + } + + return args +} + +// mayAddCondition appends another type condition to the satisfies list +// if it does not exist in the list. +func mayAddCondition(satisfies []string, typeCond []string) []string { +Cond: + for _, c := range typeCond { + for _, s := range satisfies { + if c == s { + continue Cond + } + } + satisfies = append(satisfies, c) + } + return satisfies +} diff --git a/entgql/internal/todoglobalid/ent/gql_edge.go b/entgql/internal/todoglobalid/ent/gql_edge.go new file mode 100644 index 000000000..3de432c4f --- /dev/null +++ b/entgql/internal/todoglobalid/ent/gql_edge.go @@ -0,0 +1,241 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + + "github.com/99designs/gqlgen/graphql" +) + +func (c *Category) Todos( + ctx context.Context, after *Cursor, first *int, before *Cursor, last *int, orderBy []*TodoOrder, where *TodoWhereInput, +) (*TodoConnection, error) { + opts := []TodoPaginateOption{ + WithTodoOrder(orderBy), + WithTodoFilter(where.Filter), + } + alias := graphql.GetFieldContext(ctx).Field.Alias + totalCount, hasTotalCount := c.Edges.totalCount[0][alias] + if nodes, err := c.NamedTodos(alias); err == nil || hasTotalCount { + pager, err := newTodoPager(opts, last != nil) + if err != nil { + return nil, err + } + conn := &TodoConnection{Edges: []*TodoEdge{}, TotalCount: totalCount} + conn.build(nodes, pager, after, first, before, last) + return conn, nil + } + return c.QueryTodos().Paginate(ctx, after, first, before, last, opts...) +} + +func (c *Category) SubCategories( + ctx context.Context, after *Cursor, first *int, before *Cursor, last *int, orderBy []*CategoryOrder, where *CategoryWhereInput, +) (*CategoryConnection, error) { + opts := []CategoryPaginateOption{ + WithCategoryOrder(orderBy), + WithCategoryFilter(where.Filter), + } + alias := graphql.GetFieldContext(ctx).Field.Alias + totalCount, hasTotalCount := c.Edges.totalCount[1][alias] + if nodes, err := c.NamedSubCategories(alias); err == nil || hasTotalCount { + pager, err := newCategoryPager(opts, last != nil) + if err != nil { + return nil, err + } + conn := &CategoryConnection{Edges: []*CategoryEdge{}, TotalCount: totalCount} + conn.build(nodes, pager, after, first, before, last) + return conn, nil + } + return c.QuerySubCategories().Paginate(ctx, after, first, before, last, opts...) +} + +func (f *Friendship) User(ctx context.Context) (*User, error) { + result, err := f.Edges.UserOrErr() + if IsNotLoaded(err) { + result, err = f.QueryUser().Only(ctx) + } + return result, err +} + +func (f *Friendship) Friend(ctx context.Context) (*User, error) { + result, err := f.Edges.FriendOrErr() + if IsNotLoaded(err) { + result, err = f.QueryFriend().Only(ctx) + } + return result, err +} + +func (gr *Group) Users( + ctx context.Context, after *Cursor, first *int, before *Cursor, last *int, orderBy *UserOrder, where *UserWhereInput, +) (*UserConnection, error) { + opts := []UserPaginateOption{ + WithUserOrder(orderBy), + WithUserFilter(where.Filter), + } + alias := graphql.GetFieldContext(ctx).Field.Alias + totalCount, hasTotalCount := gr.Edges.totalCount[0][alias] + if nodes, err := gr.NamedUsers(alias); err == nil || hasTotalCount { + pager, err := newUserPager(opts, last != nil) + if err != nil { + return nil, err + } + conn := &UserConnection{Edges: []*UserEdge{}, TotalCount: totalCount} + conn.build(nodes, pager, after, first, before, last) + return conn, nil + } + return gr.QueryUsers().Paginate(ctx, after, first, before, last, opts...) +} + +func (otm *OneToMany) Parent(ctx context.Context) (*OneToMany, error) { + result, err := otm.Edges.ParentOrErr() + if IsNotLoaded(err) { + result, err = otm.QueryParent().Only(ctx) + } + return result, MaskNotFound(err) +} + +func (otm *OneToMany) Children(ctx context.Context) (result []*OneToMany, err error) { + if fc := graphql.GetFieldContext(ctx); fc != nil && fc.Field.Alias != "" { + result, err = otm.NamedChildren(graphql.GetFieldContext(ctx).Field.Alias) + } else { + result, err = otm.Edges.ChildrenOrErr() + } + if IsNotLoaded(err) { + result, err = otm.QueryChildren().All(ctx) + } + return result, err +} + +func (pr *Project) Todos( + ctx context.Context, after *Cursor, first *int, before *Cursor, last *int, orderBy []*TodoOrder, where *TodoWhereInput, +) (*TodoConnection, error) { + opts := []TodoPaginateOption{ + WithTodoOrder(orderBy), + WithTodoFilter(where.Filter), + } + alias := graphql.GetFieldContext(ctx).Field.Alias + totalCount, hasTotalCount := pr.Edges.totalCount[0][alias] + if nodes, err := pr.NamedTodos(alias); err == nil || hasTotalCount { + pager, err := newTodoPager(opts, last != nil) + if err != nil { + return nil, err + } + conn := &TodoConnection{Edges: []*TodoEdge{}, TotalCount: totalCount} + conn.build(nodes, pager, after, first, before, last) + return conn, nil + } + return pr.QueryTodos().Paginate(ctx, after, first, before, last, opts...) +} + +func (t *Todo) Parent(ctx context.Context) (*Todo, error) { + result, err := t.Edges.ParentOrErr() + if IsNotLoaded(err) { + result, err = t.QueryParent().Only(ctx) + } + return result, MaskNotFound(err) +} + +func (t *Todo) Children( + ctx context.Context, after *Cursor, first *int, before *Cursor, last *int, orderBy []*TodoOrder, where *TodoWhereInput, +) (*TodoConnection, error) { + opts := []TodoPaginateOption{ + WithTodoOrder(orderBy), + WithTodoFilter(where.Filter), + } + alias := graphql.GetFieldContext(ctx).Field.Alias + totalCount, hasTotalCount := t.Edges.totalCount[1][alias] + if nodes, err := t.NamedChildren(alias); err == nil || hasTotalCount { + pager, err := newTodoPager(opts, last != nil) + if err != nil { + return nil, err + } + conn := &TodoConnection{Edges: []*TodoEdge{}, TotalCount: totalCount} + conn.build(nodes, pager, after, first, before, last) + return conn, nil + } + return t.QueryChildren().Paginate(ctx, after, first, before, last, opts...) +} + +func (t *Todo) Category(ctx context.Context) (*Category, error) { + result, err := t.Edges.CategoryOrErr() + if IsNotLoaded(err) { + result, err = t.QueryCategory().Only(ctx) + } + return result, MaskNotFound(err) +} + +func (u *User) Groups( + ctx context.Context, after *Cursor, first *int, before *Cursor, last *int, where *GroupWhereInput, +) (*GroupConnection, error) { + opts := []GroupPaginateOption{ + WithGroupFilter(where.Filter), + } + alias := graphql.GetFieldContext(ctx).Field.Alias + totalCount, hasTotalCount := u.Edges.totalCount[0][alias] + if nodes, err := u.NamedGroups(alias); err == nil || hasTotalCount { + pager, err := newGroupPager(opts, last != nil) + if err != nil { + return nil, err + } + conn := &GroupConnection{Edges: []*GroupEdge{}, TotalCount: totalCount} + conn.build(nodes, pager, after, first, before, last) + return conn, nil + } + return u.QueryGroups().Paginate(ctx, after, first, before, last, opts...) +} + +func (u *User) Friends( + ctx context.Context, after *Cursor, first *int, before *Cursor, last *int, orderBy *UserOrder, where *UserWhereInput, +) (*UserConnection, error) { + opts := []UserPaginateOption{ + WithUserOrder(orderBy), + WithUserFilter(where.Filter), + } + alias := graphql.GetFieldContext(ctx).Field.Alias + totalCount, hasTotalCount := u.Edges.totalCount[1][alias] + if nodes, err := u.NamedFriends(alias); err == nil || hasTotalCount { + pager, err := newUserPager(opts, last != nil) + if err != nil { + return nil, err + } + conn := &UserConnection{Edges: []*UserEdge{}, TotalCount: totalCount} + conn.build(nodes, pager, after, first, before, last) + return conn, nil + } + return u.QueryFriends().Paginate(ctx, after, first, before, last, opts...) +} + +func (u *User) Friendships( + ctx context.Context, after *Cursor, first *int, before *Cursor, last *int, where *FriendshipWhereInput, +) (*FriendshipConnection, error) { + opts := []FriendshipPaginateOption{ + WithFriendshipFilter(where.Filter), + } + alias := graphql.GetFieldContext(ctx).Field.Alias + totalCount, hasTotalCount := u.Edges.totalCount[2][alias] + if nodes, err := u.NamedFriendships(alias); err == nil || hasTotalCount { + pager, err := newFriendshipPager(opts, last != nil) + if err != nil { + return nil, err + } + conn := &FriendshipConnection{Edges: []*FriendshipEdge{}, TotalCount: totalCount} + conn.build(nodes, pager, after, first, before, last) + return conn, nil + } + return u.QueryFriendships().Paginate(ctx, after, first, before, last, opts...) +} diff --git a/entgql/internal/todoglobalid/ent/gql_mutation_input.go b/entgql/internal/todoglobalid/ent/gql_mutation_input.go new file mode 100644 index 000000000..5c0c1b22c --- /dev/null +++ b/entgql/internal/todoglobalid/ent/gql_mutation_input.go @@ -0,0 +1,432 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "time" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/category" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/schema/schematype" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/todo" + "github.com/google/uuid" +) + +// CreateCategoryInput represents a mutation input for creating categories. +type CreateCategoryInput struct { + Text string + Status category.Status + Config *schematype.CategoryConfig + Types *schematype.CategoryTypes + Duration *time.Duration + Count *uint64 + Strings []string + TodoIDs []int + SubCategoryIDs []int +} + +// Mutate applies the CreateCategoryInput on the CategoryMutation builder. +func (i *CreateCategoryInput) Mutate(m *CategoryMutation) { + m.SetText(i.Text) + m.SetStatus(i.Status) + if v := i.Config; v != nil { + m.SetConfig(v) + } + if v := i.Types; v != nil { + m.SetTypes(v) + } + if v := i.Duration; v != nil { + m.SetDuration(*v) + } + if v := i.Count; v != nil { + m.SetCount(*v) + } + if v := i.Strings; v != nil { + m.SetStrings(v) + } + if v := i.TodoIDs; len(v) > 0 { + m.AddTodoIDs(v...) + } + if v := i.SubCategoryIDs; len(v) > 0 { + m.AddSubCategoryIDs(v...) + } +} + +// SetInput applies the change-set in the CreateCategoryInput on the CategoryCreate builder. +func (c *CategoryCreate) SetInput(i CreateCategoryInput) *CategoryCreate { + i.Mutate(c.Mutation()) + return c +} + +// UpdateCategoryInput represents a mutation input for updating categories. +type UpdateCategoryInput struct { + Text *string + Status *category.Status + ClearConfig bool + Config *schematype.CategoryConfig + ClearTypes bool + Types *schematype.CategoryTypes + ClearDuration bool + Duration *time.Duration + ClearCount bool + Count *uint64 + ClearStrings bool + Strings []string + AppendStrings []string + ClearTodos bool + AddTodoIDs []int + RemoveTodoIDs []int + ClearSubCategories bool + AddSubCategoryIDs []int + RemoveSubCategoryIDs []int +} + +// Mutate applies the UpdateCategoryInput on the CategoryMutation builder. +func (i *UpdateCategoryInput) Mutate(m *CategoryMutation) { + if v := i.Text; v != nil { + m.SetText(*v) + } + if v := i.Status; v != nil { + m.SetStatus(*v) + } + if i.ClearConfig { + m.ClearConfig() + } + if v := i.Config; v != nil { + m.SetConfig(v) + } + if i.ClearTypes { + m.ClearTypes() + } + if v := i.Types; v != nil { + m.SetTypes(v) + } + if i.ClearDuration { + m.ClearDuration() + } + if v := i.Duration; v != nil { + m.SetDuration(*v) + } + if i.ClearCount { + m.ClearCount() + } + if v := i.Count; v != nil { + m.SetCount(*v) + } + if i.ClearStrings { + m.ClearStrings() + } + if v := i.Strings; v != nil { + m.SetStrings(v) + } + if i.AppendStrings != nil { + m.AppendStrings(i.Strings) + } + if i.ClearTodos { + m.ClearTodos() + } + if v := i.AddTodoIDs; len(v) > 0 { + m.AddTodoIDs(v...) + } + if v := i.RemoveTodoIDs; len(v) > 0 { + m.RemoveTodoIDs(v...) + } + if i.ClearSubCategories { + m.ClearSubCategories() + } + if v := i.AddSubCategoryIDs; len(v) > 0 { + m.AddSubCategoryIDs(v...) + } + if v := i.RemoveSubCategoryIDs; len(v) > 0 { + m.RemoveSubCategoryIDs(v...) + } +} + +// SetInput applies the change-set in the UpdateCategoryInput on the CategoryUpdate builder. +func (c *CategoryUpdate) SetInput(i UpdateCategoryInput) *CategoryUpdate { + i.Mutate(c.Mutation()) + return c +} + +// SetInput applies the change-set in the UpdateCategoryInput on the CategoryUpdateOne builder. +func (c *CategoryUpdateOne) SetInput(i UpdateCategoryInput) *CategoryUpdateOne { + i.Mutate(c.Mutation()) + return c +} + +// UpdateFriendshipInput represents a mutation input for updating friendships. +type UpdateFriendshipInput struct { + CreatedAt *time.Time + UserID *int + FriendID *int +} + +// Mutate applies the UpdateFriendshipInput on the FriendshipMutation builder. +func (i *UpdateFriendshipInput) Mutate(m *FriendshipMutation) { + if v := i.CreatedAt; v != nil { + m.SetCreatedAt(*v) + } + if v := i.UserID; v != nil { + m.SetUserID(*v) + } + if v := i.FriendID; v != nil { + m.SetFriendID(*v) + } +} + +// SetInput applies the change-set in the UpdateFriendshipInput on the FriendshipUpdate builder. +func (c *FriendshipUpdate) SetInput(i UpdateFriendshipInput) *FriendshipUpdate { + i.Mutate(c.Mutation()) + return c +} + +// SetInput applies the change-set in the UpdateFriendshipInput on the FriendshipUpdateOne builder. +func (c *FriendshipUpdateOne) SetInput(i UpdateFriendshipInput) *FriendshipUpdateOne { + i.Mutate(c.Mutation()) + return c +} + +// CreateTodoInput represents a mutation input for creating todos. +type CreateTodoInput struct { + Status todo.Status + Priority *int + Text string + Init map[string]interface{} + Value *int + ParentID *int + ChildIDs []int + CategoryID *int + SecretID *int +} + +// Mutate applies the CreateTodoInput on the TodoMutation builder. +func (i *CreateTodoInput) Mutate(m *TodoMutation) { + m.SetStatus(i.Status) + if v := i.Priority; v != nil { + m.SetPriority(*v) + } + m.SetText(i.Text) + if v := i.Init; v != nil { + m.SetInit(v) + } + if v := i.Value; v != nil { + m.SetValue(*v) + } + if v := i.ParentID; v != nil { + m.SetParentID(*v) + } + if v := i.ChildIDs; len(v) > 0 { + m.AddChildIDs(v...) + } + if v := i.CategoryID; v != nil { + m.SetCategoryID(*v) + } + if v := i.SecretID; v != nil { + m.SetSecretID(*v) + } +} + +// SetInput applies the change-set in the CreateTodoInput on the TodoCreate builder. +func (c *TodoCreate) SetInput(i CreateTodoInput) *TodoCreate { + i.Mutate(c.Mutation()) + return c +} + +// UpdateTodoInput represents a mutation input for updating todos. +type UpdateTodoInput struct { + Status *todo.Status + Priority *int + Text *string + ClearInit bool + Init map[string]interface{} + Value *int + ClearParent bool + ParentID *int + ClearChildren bool + AddChildIDs []int + RemoveChildIDs []int + ClearSecret bool + SecretID *int +} + +// Mutate applies the UpdateTodoInput on the TodoMutation builder. +func (i *UpdateTodoInput) Mutate(m *TodoMutation) { + if v := i.Status; v != nil { + m.SetStatus(*v) + } + if v := i.Priority; v != nil { + m.SetPriority(*v) + } + if v := i.Text; v != nil { + m.SetText(*v) + } + if i.ClearInit { + m.ClearInit() + } + if v := i.Init; v != nil { + m.SetInit(v) + } + if v := i.Value; v != nil { + m.SetValue(*v) + } + if i.ClearParent { + m.ClearParent() + } + if v := i.ParentID; v != nil { + m.SetParentID(*v) + } + if i.ClearChildren { + m.ClearChildren() + } + if v := i.AddChildIDs; len(v) > 0 { + m.AddChildIDs(v...) + } + if v := i.RemoveChildIDs; len(v) > 0 { + m.RemoveChildIDs(v...) + } + if i.ClearSecret { + m.ClearSecret() + } + if v := i.SecretID; v != nil { + m.SetSecretID(*v) + } +} + +// SetInput applies the change-set in the UpdateTodoInput on the TodoUpdate builder. +func (c *TodoUpdate) SetInput(i UpdateTodoInput) *TodoUpdate { + i.Mutate(c.Mutation()) + return c +} + +// SetInput applies the change-set in the UpdateTodoInput on the TodoUpdateOne builder. +func (c *TodoUpdateOne) SetInput(i UpdateTodoInput) *TodoUpdateOne { + i.Mutate(c.Mutation()) + return c +} + +// CreateUserInput represents a mutation input for creating users. +type CreateUserInput struct { + Name *string + Username *uuid.UUID + Password *string + RequiredMetadata map[string]interface{} + Metadata map[string]interface{} + GroupIDs []int + FriendIDs []int +} + +// Mutate applies the CreateUserInput on the UserMutation builder. +func (i *CreateUserInput) Mutate(m *UserMutation) { + if v := i.Name; v != nil { + m.SetName(*v) + } + if v := i.Username; v != nil { + m.SetUsername(*v) + } + if v := i.Password; v != nil { + m.SetPassword(*v) + } + if v := i.RequiredMetadata; v != nil { + m.SetRequiredMetadata(v) + } + if v := i.Metadata; v != nil { + m.SetMetadata(v) + } + if v := i.GroupIDs; len(v) > 0 { + m.AddGroupIDs(v...) + } + if v := i.FriendIDs; len(v) > 0 { + m.AddFriendIDs(v...) + } +} + +// SetInput applies the change-set in the CreateUserInput on the UserCreate builder. +func (c *UserCreate) SetInput(i CreateUserInput) *UserCreate { + i.Mutate(c.Mutation()) + return c +} + +// UpdateUserInput represents a mutation input for updating users. +type UpdateUserInput struct { + Name *string + Username *uuid.UUID + ClearPassword bool + Password *string + RequiredMetadata map[string]interface{} + ClearMetadata bool + Metadata map[string]interface{} + ClearGroups bool + AddGroupIDs []int + RemoveGroupIDs []int + ClearFriends bool + AddFriendIDs []int + RemoveFriendIDs []int +} + +// Mutate applies the UpdateUserInput on the UserMutation builder. +func (i *UpdateUserInput) Mutate(m *UserMutation) { + if v := i.Name; v != nil { + m.SetName(*v) + } + if v := i.Username; v != nil { + m.SetUsername(*v) + } + if i.ClearPassword { + m.ClearPassword() + } + if v := i.Password; v != nil { + m.SetPassword(*v) + } + if v := i.RequiredMetadata; v != nil { + m.SetRequiredMetadata(v) + } + if i.ClearMetadata { + m.ClearMetadata() + } + if v := i.Metadata; v != nil { + m.SetMetadata(v) + } + if i.ClearGroups { + m.ClearGroups() + } + if v := i.AddGroupIDs; len(v) > 0 { + m.AddGroupIDs(v...) + } + if v := i.RemoveGroupIDs; len(v) > 0 { + m.RemoveGroupIDs(v...) + } + if i.ClearFriends { + m.ClearFriends() + } + if v := i.AddFriendIDs; len(v) > 0 { + m.AddFriendIDs(v...) + } + if v := i.RemoveFriendIDs; len(v) > 0 { + m.RemoveFriendIDs(v...) + } +} + +// SetInput applies the change-set in the UpdateUserInput on the UserUpdate builder. +func (c *UserUpdate) SetInput(i UpdateUserInput) *UserUpdate { + i.Mutate(c.Mutation()) + return c +} + +// SetInput applies the change-set in the UpdateUserInput on the UserUpdateOne builder. +func (c *UserUpdateOne) SetInput(i UpdateUserInput) *UserUpdateOne { + i.Mutate(c.Mutation()) + return c +} diff --git a/entgql/internal/todoglobalid/ent/gql_node.go b/entgql/internal/todoglobalid/ent/gql_node.go new file mode 100644 index 000000000..961f9ead5 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/gql_node.go @@ -0,0 +1,472 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "encoding/json" + "fmt" + + "entgo.io/contrib/entgql" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/billproduct" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/category" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/friendship" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/group" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/internal" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/onetomany" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/project" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/todo" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/user" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/workspace" + "github.com/99designs/gqlgen/graphql" + "github.com/hashicorp/go-multierror" +) + +// Noder wraps the basic Node method. +type Noder interface { + Node(context.Context) (*Node, error) + IsNode() +} + +var billproductImplementors = []string{"BillProduct", "Node"} + +// IsNode implements the Node interface check for GQLGen. +func (*BillProduct) IsNode() {} + +var categoryImplementors = []string{"Category", "Node"} + +// IsNode implements the Node interface check for GQLGen. +func (*Category) IsNode() {} + +var friendshipImplementors = []string{"Friendship", "Node"} + +// IsNode implements the Node interface check for GQLGen. +func (*Friendship) IsNode() {} + +var groupImplementors = []string{"Group", "Node", "NamedNode"} + +// IsNode implements the Node interface check for GQLGen. +func (*Group) IsNode() {} + +// IsNamedNode implements the NamedNode interface check for GQLGen. +func (*Group) IsNamedNode() {} + +var onetomanyImplementors = []string{"OneToMany", "Node"} + +// IsNode implements the Node interface check for GQLGen. +func (*OneToMany) IsNode() {} + +var projectImplementors = []string{"Project", "Node"} + +// IsNode implements the Node interface check for GQLGen. +func (*Project) IsNode() {} + +var todoImplementors = []string{"Todo", "Node"} + +// IsNode implements the Node interface check for GQLGen. +func (*Todo) IsNode() {} + +var userImplementors = []string{"User", "Node"} + +// IsNode implements the Node interface check for GQLGen. +func (*User) IsNode() {} + +var workspaceImplementors = []string{"Organization", "Node"} + +// IsNode implements the Node interface check for GQLGen. +func (*Workspace) IsNode() {} + +var errNodeInvalidID = &NotFoundError{"node"} + +// NodeOption allows configuring the Noder execution using functional options. +type NodeOption func(*nodeOptions) + +// WithNodeType sets the node Type resolver function (i.e. the table to query). +// If was not provided, the table will be derived from the universal-id +// configuration as described in: https://entgo.io/docs/migrate/#universal-ids. +func WithNodeType(f func(context.Context, int) (string, error)) NodeOption { + return func(o *nodeOptions) { + o.nodeType = f + } +} + +// WithFixedNodeType sets the Type of the node to a fixed value. +func WithFixedNodeType(t string) NodeOption { + return WithNodeType(func(context.Context, int) (string, error) { + return t, nil + }) +} + +type nodeOptions struct { + nodeType func(context.Context, int) (string, error) +} + +// Each node has a range of 1<<32 ids. Pre-computing a map of node starting +// value to node type ensures node type resolution happens in O(1) complexity. +var nodeTypes = func() map[int]string { + var is map[string]int + if err := json.Unmarshal([]byte(internal.IncrementStarts), &is); err != nil { + panic(err) + } + // Get a map of range starting value to node type. + m := make(map[int]string, len(is)) + for k, v := range is { + m[v] = k // ent ensures there are no duplicate starting values + } + return m +}() + +func (c *Client) newNodeOpts(opts []NodeOption) *nodeOptions { + nopts := &nodeOptions{} + for _, opt := range opts { + opt(nopts) + } + if nopts.nodeType == nil { + nopts.nodeType = func(ctx context.Context, id int) (string, error) { + t, ok := nodeTypes[int(id/(1<<32-1))<<32] + if !ok { + return "", fmt.Errorf("cannot resolve table from id %v: %w", id, errNodeInvalidID) + } + return t, nil + } + } + return nopts +} + +// Noder returns a Node by its id. If the NodeType was not provided, it will +// be derived from the id value according to the universal-id configuration. +// +// c.Noder(ctx, id) +// c.Noder(ctx, id, ent.WithNodeType(typeResolver)) +func (c *Client) Noder(ctx context.Context, id int, opts ...NodeOption) (_ Noder, err error) { + defer func() { + if IsNotFound(err) { + err = multierror.Append(err, entgql.ErrNodeNotFound(id)) + } + }() + table, err := c.newNodeOpts(opts).nodeType(ctx, id) + if err != nil { + return nil, err + } + return c.noder(ctx, table, id) +} + +func (c *Client) noder(ctx context.Context, table string, id int) (Noder, error) { + switch table { + case billproduct.Table: + query := c.BillProduct.Query(). + Where(billproduct.ID(id)) + if fc := graphql.GetFieldContext(ctx); fc != nil { + if err := query.collectField(ctx, true, graphql.GetOperationContext(ctx), fc.Field, nil, billproductImplementors...); err != nil { + return nil, err + } + } + return query.Only(ctx) + case category.Table: + query := c.Category.Query(). + Where(category.ID(id)) + if fc := graphql.GetFieldContext(ctx); fc != nil { + if err := query.collectField(ctx, true, graphql.GetOperationContext(ctx), fc.Field, nil, categoryImplementors...); err != nil { + return nil, err + } + } + return query.Only(ctx) + case friendship.Table: + query := c.Friendship.Query(). + Where(friendship.ID(id)) + if fc := graphql.GetFieldContext(ctx); fc != nil { + if err := query.collectField(ctx, true, graphql.GetOperationContext(ctx), fc.Field, nil, friendshipImplementors...); err != nil { + return nil, err + } + } + return query.Only(ctx) + case group.Table: + query := c.Group.Query(). + Where(group.ID(id)) + if fc := graphql.GetFieldContext(ctx); fc != nil { + if err := query.collectField(ctx, true, graphql.GetOperationContext(ctx), fc.Field, nil, groupImplementors...); err != nil { + return nil, err + } + } + return query.Only(ctx) + case onetomany.Table: + query := c.OneToMany.Query(). + Where(onetomany.ID(id)) + if fc := graphql.GetFieldContext(ctx); fc != nil { + if err := query.collectField(ctx, true, graphql.GetOperationContext(ctx), fc.Field, nil, onetomanyImplementors...); err != nil { + return nil, err + } + } + return query.Only(ctx) + case project.Table: + query := c.Project.Query(). + Where(project.ID(id)) + if fc := graphql.GetFieldContext(ctx); fc != nil { + if err := query.collectField(ctx, true, graphql.GetOperationContext(ctx), fc.Field, nil, projectImplementors...); err != nil { + return nil, err + } + } + return query.Only(ctx) + case todo.Table: + query := c.Todo.Query(). + Where(todo.ID(id)) + if fc := graphql.GetFieldContext(ctx); fc != nil { + if err := query.collectField(ctx, true, graphql.GetOperationContext(ctx), fc.Field, nil, todoImplementors...); err != nil { + return nil, err + } + } + return query.Only(ctx) + case user.Table: + query := c.User.Query(). + Where(user.ID(id)) + if fc := graphql.GetFieldContext(ctx); fc != nil { + if err := query.collectField(ctx, true, graphql.GetOperationContext(ctx), fc.Field, nil, userImplementors...); err != nil { + return nil, err + } + } + return query.Only(ctx) + case workspace.Table: + query := c.Workspace.Query(). + Where(workspace.ID(id)) + if fc := graphql.GetFieldContext(ctx); fc != nil { + if err := query.collectField(ctx, true, graphql.GetOperationContext(ctx), fc.Field, nil, workspaceImplementors...); err != nil { + return nil, err + } + } + return query.Only(ctx) + default: + return nil, fmt.Errorf("cannot resolve noder from table %q: %w", table, errNodeInvalidID) + } +} + +func (c *Client) Noders(ctx context.Context, ids []int, opts ...NodeOption) ([]Noder, error) { + switch len(ids) { + case 1: + noder, err := c.Noder(ctx, ids[0], opts...) + if err != nil { + return nil, err + } + return []Noder{noder}, nil + case 0: + return []Noder{}, nil + } + + noders := make([]Noder, len(ids)) + errors := make([]error, len(ids)) + tables := make(map[string][]int) + id2idx := make(map[int][]int, len(ids)) + nopts := c.newNodeOpts(opts) + for i, id := range ids { + table, err := nopts.nodeType(ctx, id) + if err != nil { + errors[i] = err + continue + } + tables[table] = append(tables[table], id) + id2idx[id] = append(id2idx[id], i) + } + + for table, ids := range tables { + nodes, err := c.noders(ctx, table, ids) + if err != nil { + for _, id := range ids { + for _, idx := range id2idx[id] { + errors[idx] = err + } + } + } else { + for i, id := range ids { + for _, idx := range id2idx[id] { + noders[idx] = nodes[i] + } + } + } + } + + for i, id := range ids { + if errors[i] == nil { + if noders[i] != nil { + continue + } + errors[i] = entgql.ErrNodeNotFound(id) + } else if IsNotFound(errors[i]) { + errors[i] = multierror.Append(errors[i], entgql.ErrNodeNotFound(id)) + } + ctx := graphql.WithPathContext(ctx, + graphql.NewPathWithIndex(i), + ) + graphql.AddError(ctx, errors[i]) + } + return noders, nil +} + +func (c *Client) noders(ctx context.Context, table string, ids []int) ([]Noder, error) { + noders := make([]Noder, len(ids)) + idmap := make(map[int][]*Noder, len(ids)) + for i, id := range ids { + idmap[id] = append(idmap[id], &noders[i]) + } + switch table { + case billproduct.Table: + query := c.BillProduct.Query(). + Where(billproduct.IDIn(ids...)) + query, err := query.CollectFields(ctx, billproductImplementors...) + if err != nil { + return nil, err + } + nodes, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, node := range nodes { + for _, noder := range idmap[node.ID] { + *noder = node + } + } + case category.Table: + query := c.Category.Query(). + Where(category.IDIn(ids...)) + query, err := query.CollectFields(ctx, categoryImplementors...) + if err != nil { + return nil, err + } + nodes, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, node := range nodes { + for _, noder := range idmap[node.ID] { + *noder = node + } + } + case friendship.Table: + query := c.Friendship.Query(). + Where(friendship.IDIn(ids...)) + query, err := query.CollectFields(ctx, friendshipImplementors...) + if err != nil { + return nil, err + } + nodes, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, node := range nodes { + for _, noder := range idmap[node.ID] { + *noder = node + } + } + case group.Table: + query := c.Group.Query(). + Where(group.IDIn(ids...)) + query, err := query.CollectFields(ctx, groupImplementors...) + if err != nil { + return nil, err + } + nodes, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, node := range nodes { + for _, noder := range idmap[node.ID] { + *noder = node + } + } + case onetomany.Table: + query := c.OneToMany.Query(). + Where(onetomany.IDIn(ids...)) + query, err := query.CollectFields(ctx, onetomanyImplementors...) + if err != nil { + return nil, err + } + nodes, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, node := range nodes { + for _, noder := range idmap[node.ID] { + *noder = node + } + } + case project.Table: + query := c.Project.Query(). + Where(project.IDIn(ids...)) + query, err := query.CollectFields(ctx, projectImplementors...) + if err != nil { + return nil, err + } + nodes, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, node := range nodes { + for _, noder := range idmap[node.ID] { + *noder = node + } + } + case todo.Table: + query := c.Todo.Query(). + Where(todo.IDIn(ids...)) + query, err := query.CollectFields(ctx, todoImplementors...) + if err != nil { + return nil, err + } + nodes, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, node := range nodes { + for _, noder := range idmap[node.ID] { + *noder = node + } + } + case user.Table: + query := c.User.Query(). + Where(user.IDIn(ids...)) + query, err := query.CollectFields(ctx, userImplementors...) + if err != nil { + return nil, err + } + nodes, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, node := range nodes { + for _, noder := range idmap[node.ID] { + *noder = node + } + } + case workspace.Table: + query := c.Workspace.Query(). + Where(workspace.IDIn(ids...)) + query, err := query.CollectFields(ctx, workspaceImplementors...) + if err != nil { + return nil, err + } + nodes, err := query.All(ctx) + if err != nil { + return nil, err + } + for _, node := range nodes { + for _, noder := range idmap[node.ID] { + *noder = node + } + } + default: + return nil, fmt.Errorf("cannot resolve noders from table %q: %w", table, errNodeInvalidID) + } + return noders, nil +} diff --git a/entgql/internal/todoglobalid/ent/gql_node_descriptor.go b/entgql/internal/todoglobalid/ent/gql_node_descriptor.go new file mode 100644 index 000000000..3b7c85d7b --- /dev/null +++ b/entgql/internal/todoglobalid/ent/gql_node_descriptor.go @@ -0,0 +1,558 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "encoding/json" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/category" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/friendship" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/group" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/onetomany" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/todo" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/user" +) + +// Node in the graph. +type Node struct { + ID int `json:"id,omitempty"` // node id. + Type string `json:"type,omitempty"` // node type. + Fields []*Field `json:"fields,omitempty"` // node fields. + Edges []*Edge `json:"edges,omitempty"` // node edges. +} + +// Field of a node. +type Field struct { + Type string `json:"type,omitempty"` // field type. + Name string `json:"name,omitempty"` // field name (as in struct). + Value string `json:"value,omitempty"` // stringified value. +} + +// Edges between two nodes. +type Edge struct { + Type string `json:"type,omitempty"` // edge type. + Name string `json:"name,omitempty"` // edge name. + IDs []int `json:"ids,omitempty"` // node ids (where this edge point to). +} + +// Node implements Noder interface +func (bp *BillProduct) Node(ctx context.Context) (node *Node, err error) { + node = &Node{ + ID: bp.ID, + Type: "BillProduct", + Fields: make([]*Field, 3), + Edges: make([]*Edge, 0), + } + var buf []byte + if buf, err = json.Marshal(bp.Name); err != nil { + return nil, err + } + node.Fields[0] = &Field{ + Type: "string", + Name: "name", + Value: string(buf), + } + if buf, err = json.Marshal(bp.Sku); err != nil { + return nil, err + } + node.Fields[1] = &Field{ + Type: "string", + Name: "sku", + Value: string(buf), + } + if buf, err = json.Marshal(bp.Quantity); err != nil { + return nil, err + } + node.Fields[2] = &Field{ + Type: "uint64", + Name: "quantity", + Value: string(buf), + } + return node, nil +} + +// Node implements Noder interface +func (c *Category) Node(ctx context.Context) (node *Node, err error) { + node = &Node{ + ID: c.ID, + Type: "Category", + Fields: make([]*Field, 7), + Edges: make([]*Edge, 2), + } + var buf []byte + if buf, err = json.Marshal(c.Text); err != nil { + return nil, err + } + node.Fields[0] = &Field{ + Type: "string", + Name: "text", + Value: string(buf), + } + if buf, err = json.Marshal(c.Status); err != nil { + return nil, err + } + node.Fields[1] = &Field{ + Type: "category.Status", + Name: "status", + Value: string(buf), + } + if buf, err = json.Marshal(c.Config); err != nil { + return nil, err + } + node.Fields[2] = &Field{ + Type: "*schematype.CategoryConfig", + Name: "config", + Value: string(buf), + } + if buf, err = json.Marshal(c.Types); err != nil { + return nil, err + } + node.Fields[3] = &Field{ + Type: "*schematype.CategoryTypes", + Name: "types", + Value: string(buf), + } + if buf, err = json.Marshal(c.Duration); err != nil { + return nil, err + } + node.Fields[4] = &Field{ + Type: "time.Duration", + Name: "duration", + Value: string(buf), + } + if buf, err = json.Marshal(c.Count); err != nil { + return nil, err + } + node.Fields[5] = &Field{ + Type: "uint64", + Name: "count", + Value: string(buf), + } + if buf, err = json.Marshal(c.Strings); err != nil { + return nil, err + } + node.Fields[6] = &Field{ + Type: "[]string", + Name: "strings", + Value: string(buf), + } + node.Edges[0] = &Edge{ + Type: "Todo", + Name: "todos", + } + err = c.QueryTodos(). + Select(todo.FieldID). + Scan(ctx, &node.Edges[0].IDs) + if err != nil { + return nil, err + } + node.Edges[1] = &Edge{ + Type: "Category", + Name: "sub_categories", + } + err = c.QuerySubCategories(). + Select(category.FieldID). + Scan(ctx, &node.Edges[1].IDs) + if err != nil { + return nil, err + } + return node, nil +} + +// Node implements Noder interface +func (f *Friendship) Node(ctx context.Context) (node *Node, err error) { + node = &Node{ + ID: f.ID, + Type: "Friendship", + Fields: make([]*Field, 3), + Edges: make([]*Edge, 2), + } + var buf []byte + if buf, err = json.Marshal(f.CreatedAt); err != nil { + return nil, err + } + node.Fields[0] = &Field{ + Type: "time.Time", + Name: "created_at", + Value: string(buf), + } + if buf, err = json.Marshal(f.UserID); err != nil { + return nil, err + } + node.Fields[1] = &Field{ + Type: "int", + Name: "user_id", + Value: string(buf), + } + if buf, err = json.Marshal(f.FriendID); err != nil { + return nil, err + } + node.Fields[2] = &Field{ + Type: "int", + Name: "friend_id", + Value: string(buf), + } + node.Edges[0] = &Edge{ + Type: "User", + Name: "user", + } + err = f.QueryUser(). + Select(user.FieldID). + Scan(ctx, &node.Edges[0].IDs) + if err != nil { + return nil, err + } + node.Edges[1] = &Edge{ + Type: "User", + Name: "friend", + } + err = f.QueryFriend(). + Select(user.FieldID). + Scan(ctx, &node.Edges[1].IDs) + if err != nil { + return nil, err + } + return node, nil +} + +// Node implements Noder interface +func (gr *Group) Node(ctx context.Context) (node *Node, err error) { + node = &Node{ + ID: gr.ID, + Type: "Group", + Fields: make([]*Field, 1), + Edges: make([]*Edge, 1), + } + var buf []byte + if buf, err = json.Marshal(gr.Name); err != nil { + return nil, err + } + node.Fields[0] = &Field{ + Type: "string", + Name: "name", + Value: string(buf), + } + node.Edges[0] = &Edge{ + Type: "User", + Name: "users", + } + err = gr.QueryUsers(). + Select(user.FieldID). + Scan(ctx, &node.Edges[0].IDs) + if err != nil { + return nil, err + } + return node, nil +} + +// Node implements Noder interface +func (otm *OneToMany) Node(ctx context.Context) (node *Node, err error) { + node = &Node{ + ID: otm.ID, + Type: "OneToMany", + Fields: make([]*Field, 2), + Edges: make([]*Edge, 2), + } + var buf []byte + if buf, err = json.Marshal(otm.Name); err != nil { + return nil, err + } + node.Fields[0] = &Field{ + Type: "string", + Name: "name", + Value: string(buf), + } + if buf, err = json.Marshal(otm.Field2); err != nil { + return nil, err + } + node.Fields[1] = &Field{ + Type: "string", + Name: "field2", + Value: string(buf), + } + node.Edges[0] = &Edge{ + Type: "OneToMany", + Name: "parent", + } + err = otm.QueryParent(). + Select(onetomany.FieldID). + Scan(ctx, &node.Edges[0].IDs) + if err != nil { + return nil, err + } + node.Edges[1] = &Edge{ + Type: "OneToMany", + Name: "children", + } + err = otm.QueryChildren(). + Select(onetomany.FieldID). + Scan(ctx, &node.Edges[1].IDs) + if err != nil { + return nil, err + } + return node, nil +} + +// Node implements Noder interface +func (pr *Project) Node(ctx context.Context) (node *Node, err error) { + node = &Node{ + ID: pr.ID, + Type: "Project", + Fields: make([]*Field, 0), + Edges: make([]*Edge, 1), + } + node.Edges[0] = &Edge{ + Type: "Todo", + Name: "todos", + } + err = pr.QueryTodos(). + Select(todo.FieldID). + Scan(ctx, &node.Edges[0].IDs) + if err != nil { + return nil, err + } + return node, nil +} + +// Node implements Noder interface +func (t *Todo) Node(ctx context.Context) (node *Node, err error) { + node = &Node{ + ID: t.ID, + Type: "Todo", + Fields: make([]*Field, 9), + Edges: make([]*Edge, 3), + } + var buf []byte + if buf, err = json.Marshal(t.CreatedAt); err != nil { + return nil, err + } + node.Fields[0] = &Field{ + Type: "time.Time", + Name: "created_at", + Value: string(buf), + } + if buf, err = json.Marshal(t.Status); err != nil { + return nil, err + } + node.Fields[1] = &Field{ + Type: "todo.Status", + Name: "status", + Value: string(buf), + } + if buf, err = json.Marshal(t.Priority); err != nil { + return nil, err + } + node.Fields[2] = &Field{ + Type: "int", + Name: "priority", + Value: string(buf), + } + if buf, err = json.Marshal(t.Text); err != nil { + return nil, err + } + node.Fields[3] = &Field{ + Type: "string", + Name: "text", + Value: string(buf), + } + if buf, err = json.Marshal(t.CategoryID); err != nil { + return nil, err + } + node.Fields[4] = &Field{ + Type: "int", + Name: "category_id", + Value: string(buf), + } + if buf, err = json.Marshal(t.Init); err != nil { + return nil, err + } + node.Fields[5] = &Field{ + Type: "map[string]interface {}", + Name: "init", + Value: string(buf), + } + if buf, err = json.Marshal(t.Custom); err != nil { + return nil, err + } + node.Fields[6] = &Field{ + Type: "[]customstruct.Custom", + Name: "custom", + Value: string(buf), + } + if buf, err = json.Marshal(t.Customp); err != nil { + return nil, err + } + node.Fields[7] = &Field{ + Type: "[]*customstruct.Custom", + Name: "customp", + Value: string(buf), + } + if buf, err = json.Marshal(t.Value); err != nil { + return nil, err + } + node.Fields[8] = &Field{ + Type: "int", + Name: "value", + Value: string(buf), + } + node.Edges[0] = &Edge{ + Type: "Todo", + Name: "parent", + } + err = t.QueryParent(). + Select(todo.FieldID). + Scan(ctx, &node.Edges[0].IDs) + if err != nil { + return nil, err + } + node.Edges[1] = &Edge{ + Type: "Todo", + Name: "children", + } + err = t.QueryChildren(). + Select(todo.FieldID). + Scan(ctx, &node.Edges[1].IDs) + if err != nil { + return nil, err + } + node.Edges[2] = &Edge{ + Type: "Category", + Name: "category", + } + err = t.QueryCategory(). + Select(category.FieldID). + Scan(ctx, &node.Edges[2].IDs) + if err != nil { + return nil, err + } + return node, nil +} + +// Node implements Noder interface +func (u *User) Node(ctx context.Context) (node *Node, err error) { + node = &Node{ + ID: u.ID, + Type: "User", + Fields: make([]*Field, 5), + Edges: make([]*Edge, 3), + } + var buf []byte + if buf, err = json.Marshal(u.Name); err != nil { + return nil, err + } + node.Fields[0] = &Field{ + Type: "string", + Name: "name", + Value: string(buf), + } + if buf, err = json.Marshal(u.Username); err != nil { + return nil, err + } + node.Fields[1] = &Field{ + Type: "uuid.UUID", + Name: "username", + Value: string(buf), + } + if buf, err = json.Marshal(u.Password); err != nil { + return nil, err + } + node.Fields[2] = &Field{ + Type: "string", + Name: "password", + Value: string(buf), + } + if buf, err = json.Marshal(u.RequiredMetadata); err != nil { + return nil, err + } + node.Fields[3] = &Field{ + Type: "map[string]interface {}", + Name: "required_metadata", + Value: string(buf), + } + if buf, err = json.Marshal(u.Metadata); err != nil { + return nil, err + } + node.Fields[4] = &Field{ + Type: "map[string]interface {}", + Name: "metadata", + Value: string(buf), + } + node.Edges[0] = &Edge{ + Type: "Group", + Name: "groups", + } + err = u.QueryGroups(). + Select(group.FieldID). + Scan(ctx, &node.Edges[0].IDs) + if err != nil { + return nil, err + } + node.Edges[1] = &Edge{ + Type: "User", + Name: "friends", + } + err = u.QueryFriends(). + Select(user.FieldID). + Scan(ctx, &node.Edges[1].IDs) + if err != nil { + return nil, err + } + node.Edges[2] = &Edge{ + Type: "Friendship", + Name: "friendships", + } + err = u.QueryFriendships(). + Select(friendship.FieldID). + Scan(ctx, &node.Edges[2].IDs) + if err != nil { + return nil, err + } + return node, nil +} + +// Node implements Noder interface +func (w *Workspace) Node(ctx context.Context) (node *Node, err error) { + node = &Node{ + ID: w.ID, + Type: "Workspace", + Fields: make([]*Field, 1), + Edges: make([]*Edge, 0), + } + var buf []byte + if buf, err = json.Marshal(w.Name); err != nil { + return nil, err + } + node.Fields[0] = &Field{ + Type: "string", + Name: "name", + Value: string(buf), + } + return node, nil +} + +// Node returns the node with given global ID. +// +// This API helpful in case you want to build +// an administrator tool to browser all types in system. +func (c *Client) Node(ctx context.Context, id int) (*Node, error) { + n, err := c.Noder(ctx, id) + if err != nil { + return nil, err + } + return n.Node(ctx) +} diff --git a/entgql/internal/todoglobalid/ent/gql_pagination.go b/entgql/internal/todoglobalid/ent/gql_pagination.go new file mode 100644 index 000000000..61e9f7ff3 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/gql_pagination.go @@ -0,0 +1,2921 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "io" + "strconv" + + "entgo.io/contrib/entgql" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/billproduct" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/category" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/friendship" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/group" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/onetomany" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/project" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/todo" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/user" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/workspace" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/99designs/gqlgen/graphql" + "github.com/99designs/gqlgen/graphql/errcode" + "github.com/vektah/gqlparser/v2/gqlerror" +) + +// Common entgql types. +type ( + Cursor = entgql.Cursor[int] + PageInfo = entgql.PageInfo[int] + OrderDirection = entgql.OrderDirection +) + +func orderFunc(o OrderDirection, field string) func(*sql.Selector) { + if o == entgql.OrderDirectionDesc { + return Desc(field) + } + return Asc(field) +} + +const errInvalidPagination = "INVALID_PAGINATION" + +func validateFirstLast(first, last *int) (err *gqlerror.Error) { + switch { + case first != nil && last != nil: + err = &gqlerror.Error{ + Message: "Passing both `first` and `last` to paginate a connection is not supported.", + } + case first != nil && *first < 0: + err = &gqlerror.Error{ + Message: "`first` on a connection cannot be less than zero.", + } + errcode.Set(err, errInvalidPagination) + case last != nil && *last < 0: + err = &gqlerror.Error{ + Message: "`last` on a connection cannot be less than zero.", + } + errcode.Set(err, errInvalidPagination) + } + return err +} + +func collectedField(ctx context.Context, path ...string) *graphql.CollectedField { + fc := graphql.GetFieldContext(ctx) + if fc == nil { + return nil + } + field := fc.Field + oc := graphql.GetOperationContext(ctx) +walk: + for _, name := range path { + for _, f := range graphql.CollectFields(oc, field.Selections, nil) { + if f.Alias == name { + field = f + continue walk + } + } + return nil + } + return &field +} + +func hasCollectedField(ctx context.Context, path ...string) bool { + if graphql.GetFieldContext(ctx) == nil { + return true + } + return collectedField(ctx, path...) != nil +} + +const ( + edgesField = "edges" + nodeField = "node" + pageInfoField = "pageInfo" + totalCountField = "totalCount" +) + +func paginateLimit(first, last *int) int { + var limit int + if first != nil { + limit = *first + 1 + } else if last != nil { + limit = *last + 1 + } + return limit +} + +// BillProductEdge is the edge representation of BillProduct. +type BillProductEdge struct { + Node *BillProduct `json:"node"` + Cursor Cursor `json:"cursor"` +} + +// BillProductConnection is the connection containing edges to BillProduct. +type BillProductConnection struct { + Edges []*BillProductEdge `json:"edges"` + PageInfo PageInfo `json:"pageInfo"` + TotalCount int `json:"totalCount"` +} + +func (c *BillProductConnection) build(nodes []*BillProduct, pager *billproductPager, after *Cursor, first *int, before *Cursor, last *int) { + c.PageInfo.HasNextPage = before != nil + c.PageInfo.HasPreviousPage = after != nil + if first != nil && *first+1 == len(nodes) { + c.PageInfo.HasNextPage = true + nodes = nodes[:len(nodes)-1] + } else if last != nil && *last+1 == len(nodes) { + c.PageInfo.HasPreviousPage = true + nodes = nodes[:len(nodes)-1] + } + var nodeAt func(int) *BillProduct + if last != nil { + n := len(nodes) - 1 + nodeAt = func(i int) *BillProduct { + return nodes[n-i] + } + } else { + nodeAt = func(i int) *BillProduct { + return nodes[i] + } + } + c.Edges = make([]*BillProductEdge, len(nodes)) + for i := range nodes { + node := nodeAt(i) + c.Edges[i] = &BillProductEdge{ + Node: node, + Cursor: pager.toCursor(node), + } + } + if l := len(c.Edges); l > 0 { + c.PageInfo.StartCursor = &c.Edges[0].Cursor + c.PageInfo.EndCursor = &c.Edges[l-1].Cursor + } + if c.TotalCount == 0 { + c.TotalCount = len(nodes) + } +} + +// BillProductPaginateOption enables pagination customization. +type BillProductPaginateOption func(*billproductPager) error + +// WithBillProductOrder configures pagination ordering. +func WithBillProductOrder(order *BillProductOrder) BillProductPaginateOption { + if order == nil { + order = DefaultBillProductOrder + } + o := *order + return func(pager *billproductPager) error { + if err := o.Direction.Validate(); err != nil { + return err + } + if o.Field == nil { + o.Field = DefaultBillProductOrder.Field + } + pager.order = &o + return nil + } +} + +// WithBillProductFilter configures pagination filter. +func WithBillProductFilter(filter func(*BillProductQuery) (*BillProductQuery, error)) BillProductPaginateOption { + return func(pager *billproductPager) error { + if filter == nil { + return errors.New("BillProductQuery filter cannot be nil") + } + pager.filter = filter + return nil + } +} + +type billproductPager struct { + reverse bool + order *BillProductOrder + filter func(*BillProductQuery) (*BillProductQuery, error) +} + +func newBillProductPager(opts []BillProductPaginateOption, reverse bool) (*billproductPager, error) { + pager := &billproductPager{reverse: reverse} + for _, opt := range opts { + if err := opt(pager); err != nil { + return nil, err + } + } + if pager.order == nil { + pager.order = DefaultBillProductOrder + } + return pager, nil +} + +func (p *billproductPager) applyFilter(query *BillProductQuery) (*BillProductQuery, error) { + if p.filter != nil { + return p.filter(query) + } + return query, nil +} + +func (p *billproductPager) toCursor(bp *BillProduct) Cursor { + return p.order.Field.toCursor(bp) +} + +func (p *billproductPager) applyCursors(query *BillProductQuery, after, before *Cursor) (*BillProductQuery, error) { + direction := p.order.Direction + if p.reverse { + direction = direction.Reverse() + } + for _, predicate := range entgql.CursorsPredicate(after, before, DefaultBillProductOrder.Field.column, p.order.Field.column, direction) { + query = query.Where(predicate) + } + return query, nil +} + +func (p *billproductPager) applyOrder(query *BillProductQuery) *BillProductQuery { + direction := p.order.Direction + if p.reverse { + direction = direction.Reverse() + } + query = query.Order(p.order.Field.toTerm(direction.OrderTermOption())) + if p.order.Field != DefaultBillProductOrder.Field { + query = query.Order(DefaultBillProductOrder.Field.toTerm(direction.OrderTermOption())) + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(p.order.Field.column) + } + return query +} + +func (p *billproductPager) orderExpr(query *BillProductQuery) sql.Querier { + direction := p.order.Direction + if p.reverse { + direction = direction.Reverse() + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(p.order.Field.column) + } + return sql.ExprFunc(func(b *sql.Builder) { + b.Ident(p.order.Field.column).Pad().WriteString(string(direction)) + if p.order.Field != DefaultBillProductOrder.Field { + b.Comma().Ident(DefaultBillProductOrder.Field.column).Pad().WriteString(string(direction)) + } + }) +} + +// Paginate executes the query and returns a relay based cursor connection to BillProduct. +func (bp *BillProductQuery) Paginate( + ctx context.Context, after *Cursor, first *int, + before *Cursor, last *int, opts ...BillProductPaginateOption, +) (*BillProductConnection, error) { + if err := validateFirstLast(first, last); err != nil { + return nil, err + } + pager, err := newBillProductPager(opts, last != nil) + if err != nil { + return nil, err + } + if bp, err = pager.applyFilter(bp); err != nil { + return nil, err + } + conn := &BillProductConnection{Edges: []*BillProductEdge{}} + ignoredEdges := !hasCollectedField(ctx, edgesField) + if hasCollectedField(ctx, totalCountField) || hasCollectedField(ctx, pageInfoField) { + hasPagination := after != nil || first != nil || before != nil || last != nil + if hasPagination || ignoredEdges { + c := bp.Clone() + c.ctx.Fields = nil + if conn.TotalCount, err = c.Count(ctx); err != nil { + return nil, err + } + conn.PageInfo.HasNextPage = first != nil && conn.TotalCount > 0 + conn.PageInfo.HasPreviousPage = last != nil && conn.TotalCount > 0 + } + } + if ignoredEdges || (first != nil && *first == 0) || (last != nil && *last == 0) { + return conn, nil + } + if bp, err = pager.applyCursors(bp, after, before); err != nil { + return nil, err + } + limit := paginateLimit(first, last) + if limit != 0 { + bp.Limit(limit) + } + if field := collectedField(ctx, edgesField, nodeField); field != nil { + if err := bp.collectField(ctx, limit == 1, graphql.GetOperationContext(ctx), *field, []string{edgesField, nodeField}); err != nil { + return nil, err + } + } + bp = pager.applyOrder(bp) + nodes, err := bp.All(ctx) + if err != nil { + return nil, err + } + conn.build(nodes, pager, after, first, before, last) + return conn, nil +} + +// BillProductOrderField defines the ordering field of BillProduct. +type BillProductOrderField struct { + // Value extracts the ordering value from the given BillProduct. + Value func(*BillProduct) (ent.Value, error) + column string // field or computed. + toTerm func(...sql.OrderTermOption) billproduct.OrderOption + toCursor func(*BillProduct) Cursor +} + +// BillProductOrder defines the ordering of BillProduct. +type BillProductOrder struct { + Direction OrderDirection `json:"direction"` + Field *BillProductOrderField `json:"field"` +} + +// DefaultBillProductOrder is the default ordering of BillProduct. +var DefaultBillProductOrder = &BillProductOrder{ + Direction: entgql.OrderDirectionAsc, + Field: &BillProductOrderField{ + Value: func(bp *BillProduct) (ent.Value, error) { + return bp.ID, nil + }, + column: billproduct.FieldID, + toTerm: billproduct.ByID, + toCursor: func(bp *BillProduct) Cursor { + return Cursor{ID: bp.ID} + }, + }, +} + +// ToEdge converts BillProduct into BillProductEdge. +func (bp *BillProduct) ToEdge(order *BillProductOrder) *BillProductEdge { + if order == nil { + order = DefaultBillProductOrder + } + return &BillProductEdge{ + Node: bp, + Cursor: order.Field.toCursor(bp), + } +} + +// CategoryEdge is the edge representation of Category. +type CategoryEdge struct { + Node *Category `json:"node"` + Cursor Cursor `json:"cursor"` +} + +// CategoryConnection is the connection containing edges to Category. +type CategoryConnection struct { + Edges []*CategoryEdge `json:"edges"` + PageInfo PageInfo `json:"pageInfo"` + TotalCount int `json:"totalCount"` +} + +func (c *CategoryConnection) build(nodes []*Category, pager *categoryPager, after *Cursor, first *int, before *Cursor, last *int) { + c.PageInfo.HasNextPage = before != nil + c.PageInfo.HasPreviousPage = after != nil + if first != nil && *first+1 == len(nodes) { + c.PageInfo.HasNextPage = true + nodes = nodes[:len(nodes)-1] + } else if last != nil && *last+1 == len(nodes) { + c.PageInfo.HasPreviousPage = true + nodes = nodes[:len(nodes)-1] + } + var nodeAt func(int) *Category + if last != nil { + n := len(nodes) - 1 + nodeAt = func(i int) *Category { + return nodes[n-i] + } + } else { + nodeAt = func(i int) *Category { + return nodes[i] + } + } + c.Edges = make([]*CategoryEdge, len(nodes)) + for i := range nodes { + node := nodeAt(i) + c.Edges[i] = &CategoryEdge{ + Node: node, + Cursor: pager.toCursor(node), + } + } + if l := len(c.Edges); l > 0 { + c.PageInfo.StartCursor = &c.Edges[0].Cursor + c.PageInfo.EndCursor = &c.Edges[l-1].Cursor + } + if c.TotalCount == 0 { + c.TotalCount = len(nodes) + } +} + +// CategoryPaginateOption enables pagination customization. +type CategoryPaginateOption func(*categoryPager) error + +// WithCategoryOrder configures pagination ordering. +func WithCategoryOrder(order []*CategoryOrder) CategoryPaginateOption { + return func(pager *categoryPager) error { + for _, o := range order { + if err := o.Direction.Validate(); err != nil { + return err + } + } + pager.order = append(pager.order, order...) + return nil + } +} + +// WithCategoryFilter configures pagination filter. +func WithCategoryFilter(filter func(*CategoryQuery) (*CategoryQuery, error)) CategoryPaginateOption { + return func(pager *categoryPager) error { + if filter == nil { + return errors.New("CategoryQuery filter cannot be nil") + } + pager.filter = filter + return nil + } +} + +type categoryPager struct { + reverse bool + order []*CategoryOrder + filter func(*CategoryQuery) (*CategoryQuery, error) +} + +func newCategoryPager(opts []CategoryPaginateOption, reverse bool) (*categoryPager, error) { + pager := &categoryPager{reverse: reverse} + for _, opt := range opts { + if err := opt(pager); err != nil { + return nil, err + } + } + for i, o := range pager.order { + if i > 0 && o.Field == pager.order[i-1].Field { + return nil, fmt.Errorf("duplicate order direction %q", o.Direction) + } + } + return pager, nil +} + +func (p *categoryPager) applyFilter(query *CategoryQuery) (*CategoryQuery, error) { + if p.filter != nil { + return p.filter(query) + } + return query, nil +} + +func (p *categoryPager) toCursor(c *Category) Cursor { + cs_ := make([]any, 0, len(p.order)) + for _, o_ := range p.order { + cs_ = append(cs_, o_.Field.toCursor(c).Value) + } + return Cursor{ID: c.ID, Value: cs_} +} + +func (p *categoryPager) applyCursors(query *CategoryQuery, after, before *Cursor) (*CategoryQuery, error) { + idDirection := entgql.OrderDirectionAsc + if p.reverse { + idDirection = entgql.OrderDirectionDesc + } + fields, directions := make([]string, 0, len(p.order)), make([]OrderDirection, 0, len(p.order)) + for _, o := range p.order { + fields = append(fields, o.Field.column) + direction := o.Direction + if p.reverse { + direction = direction.Reverse() + } + directions = append(directions, direction) + } + predicates, err := entgql.MultiCursorsPredicate(after, before, &entgql.MultiCursorsOptions{ + FieldID: DefaultCategoryOrder.Field.column, + DirectionID: idDirection, + Fields: fields, + Directions: directions, + }) + if err != nil { + return nil, err + } + for _, predicate := range predicates { + query = query.Where(predicate) + } + return query, nil +} + +func (p *categoryPager) applyOrder(query *CategoryQuery) *CategoryQuery { + var defaultOrdered bool + for _, o := range p.order { + direction := o.Direction + if p.reverse { + direction = direction.Reverse() + } + query = query.Order(o.Field.toTerm(direction.OrderTermOption())) + if o.Field.column == DefaultCategoryOrder.Field.column { + defaultOrdered = true + } + switch o.Field.column { + case CategoryOrderFieldTodosCount.column: + default: + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(o.Field.column) + } + } + } + if !defaultOrdered { + direction := entgql.OrderDirectionAsc + if p.reverse { + direction = direction.Reverse() + } + query = query.Order(DefaultCategoryOrder.Field.toTerm(direction.OrderTermOption())) + } + return query +} + +func (p *categoryPager) orderExpr(query *CategoryQuery) sql.Querier { + for _, o := range p.order { + switch o.Field.column { + case CategoryOrderFieldTodosCount.column: + direction := o.Direction + if p.reverse { + direction = direction.Reverse() + } + query = query.Order(o.Field.toTerm(direction.OrderTermOption())) + default: + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(o.Field.column) + } + } + } + return sql.ExprFunc(func(b *sql.Builder) { + for _, o := range p.order { + direction := o.Direction + if p.reverse { + direction = direction.Reverse() + } + b.Ident(o.Field.column).Pad().WriteString(string(direction)) + b.Comma() + } + direction := entgql.OrderDirectionAsc + if p.reverse { + direction = direction.Reverse() + } + b.Ident(DefaultCategoryOrder.Field.column).Pad().WriteString(string(direction)) + }) +} + +// Paginate executes the query and returns a relay based cursor connection to Category. +func (c *CategoryQuery) Paginate( + ctx context.Context, after *Cursor, first *int, + before *Cursor, last *int, opts ...CategoryPaginateOption, +) (*CategoryConnection, error) { + if err := validateFirstLast(first, last); err != nil { + return nil, err + } + pager, err := newCategoryPager(opts, last != nil) + if err != nil { + return nil, err + } + if c, err = pager.applyFilter(c); err != nil { + return nil, err + } + conn := &CategoryConnection{Edges: []*CategoryEdge{}} + ignoredEdges := !hasCollectedField(ctx, edgesField) + if hasCollectedField(ctx, totalCountField) || hasCollectedField(ctx, pageInfoField) { + hasPagination := after != nil || first != nil || before != nil || last != nil + if hasPagination || ignoredEdges { + c := c.Clone() + c.ctx.Fields = nil + if conn.TotalCount, err = c.Count(ctx); err != nil { + return nil, err + } + conn.PageInfo.HasNextPage = first != nil && conn.TotalCount > 0 + conn.PageInfo.HasPreviousPage = last != nil && conn.TotalCount > 0 + } + } + if ignoredEdges || (first != nil && *first == 0) || (last != nil && *last == 0) { + return conn, nil + } + if c, err = pager.applyCursors(c, after, before); err != nil { + return nil, err + } + limit := paginateLimit(first, last) + if limit != 0 { + c.Limit(limit) + } + if field := collectedField(ctx, edgesField, nodeField); field != nil { + if err := c.collectField(ctx, limit == 1, graphql.GetOperationContext(ctx), *field, []string{edgesField, nodeField}); err != nil { + return nil, err + } + } + c = pager.applyOrder(c) + nodes, err := c.All(ctx) + if err != nil { + return nil, err + } + conn.build(nodes, pager, after, first, before, last) + return conn, nil +} + +var ( + // CategoryOrderFieldID orders Category by id. + CategoryOrderFieldID = &CategoryOrderField{ + Value: func(c *Category) (ent.Value, error) { + return c.ID, nil + }, + column: category.FieldID, + toTerm: category.ByID, + toCursor: func(c *Category) Cursor { + return Cursor{ + ID: c.ID, + Value: c.ID, + } + }, + } + // CategoryOrderFieldText orders Category by text. + CategoryOrderFieldText = &CategoryOrderField{ + Value: func(c *Category) (ent.Value, error) { + return c.Text, nil + }, + column: category.FieldText, + toTerm: category.ByText, + toCursor: func(c *Category) Cursor { + return Cursor{ + ID: c.ID, + Value: c.Text, + } + }, + } + // CategoryOrderFieldStatus orders Category by status. + CategoryOrderFieldStatus = &CategoryOrderField{ + Value: func(c *Category) (ent.Value, error) { + return c.Status, nil + }, + column: category.FieldStatus, + toTerm: category.ByStatus, + toCursor: func(c *Category) Cursor { + return Cursor{ + ID: c.ID, + Value: c.Status, + } + }, + } + // CategoryOrderFieldDuration orders Category by duration. + CategoryOrderFieldDuration = &CategoryOrderField{ + Value: func(c *Category) (ent.Value, error) { + return c.Duration, nil + }, + column: category.FieldDuration, + toTerm: category.ByDuration, + toCursor: func(c *Category) Cursor { + return Cursor{ + ID: c.ID, + Value: c.Duration, + } + }, + } + // CategoryOrderFieldCount orders Category by count. + CategoryOrderFieldCount = &CategoryOrderField{ + Value: func(c *Category) (ent.Value, error) { + return c.Count, nil + }, + column: category.FieldCount, + toTerm: category.ByCount, + toCursor: func(c *Category) Cursor { + return Cursor{ + ID: c.ID, + Value: c.Count, + } + }, + } + // CategoryOrderFieldTodosCount orders by TODOS_COUNT. + CategoryOrderFieldTodosCount = &CategoryOrderField{ + Value: func(c *Category) (ent.Value, error) { + return c.Value("todos_count") + }, + column: "todos_count", + toTerm: func(opts ...sql.OrderTermOption) category.OrderOption { + return category.ByTodosCount( + append(opts, sql.OrderSelectAs("todos_count"))..., + ) + }, + toCursor: func(c *Category) Cursor { + cv, _ := c.Value("todos_count") + return Cursor{ + ID: c.ID, + Value: cv, + } + }, + } +) + +// String implement fmt.Stringer interface. +func (f CategoryOrderField) String() string { + var str string + switch f.column { + case CategoryOrderFieldID.column: + str = "ID" + case CategoryOrderFieldText.column: + str = "TEXT" + case CategoryOrderFieldStatus.column: + str = "STATUS" + case CategoryOrderFieldDuration.column: + str = "DURATION" + case CategoryOrderFieldCount.column: + str = "COUNT" + case CategoryOrderFieldTodosCount.column: + str = "TODOS_COUNT" + } + return str +} + +// MarshalGQL implements graphql.Marshaler interface. +func (f CategoryOrderField) MarshalGQL(w io.Writer) { + io.WriteString(w, strconv.Quote(f.String())) +} + +// UnmarshalGQL implements graphql.Unmarshaler interface. +func (f *CategoryOrderField) UnmarshalGQL(v interface{}) error { + str, ok := v.(string) + if !ok { + return fmt.Errorf("CategoryOrderField %T must be a string", v) + } + switch str { + case "ID": + *f = *CategoryOrderFieldID + case "TEXT": + *f = *CategoryOrderFieldText + case "STATUS": + *f = *CategoryOrderFieldStatus + case "DURATION": + *f = *CategoryOrderFieldDuration + case "COUNT": + *f = *CategoryOrderFieldCount + case "TODOS_COUNT": + *f = *CategoryOrderFieldTodosCount + default: + return fmt.Errorf("%s is not a valid CategoryOrderField", str) + } + return nil +} + +// CategoryOrderField defines the ordering field of Category. +type CategoryOrderField struct { + // Value extracts the ordering value from the given Category. + Value func(*Category) (ent.Value, error) + column string // field or computed. + toTerm func(...sql.OrderTermOption) category.OrderOption + toCursor func(*Category) Cursor +} + +// CategoryOrder defines the ordering of Category. +type CategoryOrder struct { + Direction OrderDirection `json:"direction"` + Field *CategoryOrderField `json:"field"` +} + +// DefaultCategoryOrder is the default ordering of Category. +var DefaultCategoryOrder = &CategoryOrder{ + Direction: entgql.OrderDirectionAsc, + Field: &CategoryOrderField{ + Value: func(c *Category) (ent.Value, error) { + return c.ID, nil + }, + column: category.FieldID, + toTerm: category.ByID, + toCursor: func(c *Category) Cursor { + return Cursor{ID: c.ID} + }, + }, +} + +// ToEdge converts Category into CategoryEdge. +func (c *Category) ToEdge(order *CategoryOrder) *CategoryEdge { + if order == nil { + order = DefaultCategoryOrder + } + return &CategoryEdge{ + Node: c, + Cursor: order.Field.toCursor(c), + } +} + +// FriendshipEdge is the edge representation of Friendship. +type FriendshipEdge struct { + Node *Friendship `json:"node"` + Cursor Cursor `json:"cursor"` +} + +// FriendshipConnection is the connection containing edges to Friendship. +type FriendshipConnection struct { + Edges []*FriendshipEdge `json:"edges"` + PageInfo PageInfo `json:"pageInfo"` + TotalCount int `json:"totalCount"` +} + +func (c *FriendshipConnection) build(nodes []*Friendship, pager *friendshipPager, after *Cursor, first *int, before *Cursor, last *int) { + c.PageInfo.HasNextPage = before != nil + c.PageInfo.HasPreviousPage = after != nil + if first != nil && *first+1 == len(nodes) { + c.PageInfo.HasNextPage = true + nodes = nodes[:len(nodes)-1] + } else if last != nil && *last+1 == len(nodes) { + c.PageInfo.HasPreviousPage = true + nodes = nodes[:len(nodes)-1] + } + var nodeAt func(int) *Friendship + if last != nil { + n := len(nodes) - 1 + nodeAt = func(i int) *Friendship { + return nodes[n-i] + } + } else { + nodeAt = func(i int) *Friendship { + return nodes[i] + } + } + c.Edges = make([]*FriendshipEdge, len(nodes)) + for i := range nodes { + node := nodeAt(i) + c.Edges[i] = &FriendshipEdge{ + Node: node, + Cursor: pager.toCursor(node), + } + } + if l := len(c.Edges); l > 0 { + c.PageInfo.StartCursor = &c.Edges[0].Cursor + c.PageInfo.EndCursor = &c.Edges[l-1].Cursor + } + if c.TotalCount == 0 { + c.TotalCount = len(nodes) + } +} + +// FriendshipPaginateOption enables pagination customization. +type FriendshipPaginateOption func(*friendshipPager) error + +// WithFriendshipOrder configures pagination ordering. +func WithFriendshipOrder(order *FriendshipOrder) FriendshipPaginateOption { + if order == nil { + order = DefaultFriendshipOrder + } + o := *order + return func(pager *friendshipPager) error { + if err := o.Direction.Validate(); err != nil { + return err + } + if o.Field == nil { + o.Field = DefaultFriendshipOrder.Field + } + pager.order = &o + return nil + } +} + +// WithFriendshipFilter configures pagination filter. +func WithFriendshipFilter(filter func(*FriendshipQuery) (*FriendshipQuery, error)) FriendshipPaginateOption { + return func(pager *friendshipPager) error { + if filter == nil { + return errors.New("FriendshipQuery filter cannot be nil") + } + pager.filter = filter + return nil + } +} + +type friendshipPager struct { + reverse bool + order *FriendshipOrder + filter func(*FriendshipQuery) (*FriendshipQuery, error) +} + +func newFriendshipPager(opts []FriendshipPaginateOption, reverse bool) (*friendshipPager, error) { + pager := &friendshipPager{reverse: reverse} + for _, opt := range opts { + if err := opt(pager); err != nil { + return nil, err + } + } + if pager.order == nil { + pager.order = DefaultFriendshipOrder + } + return pager, nil +} + +func (p *friendshipPager) applyFilter(query *FriendshipQuery) (*FriendshipQuery, error) { + if p.filter != nil { + return p.filter(query) + } + return query, nil +} + +func (p *friendshipPager) toCursor(f *Friendship) Cursor { + return p.order.Field.toCursor(f) +} + +func (p *friendshipPager) applyCursors(query *FriendshipQuery, after, before *Cursor) (*FriendshipQuery, error) { + direction := p.order.Direction + if p.reverse { + direction = direction.Reverse() + } + for _, predicate := range entgql.CursorsPredicate(after, before, DefaultFriendshipOrder.Field.column, p.order.Field.column, direction) { + query = query.Where(predicate) + } + return query, nil +} + +func (p *friendshipPager) applyOrder(query *FriendshipQuery) *FriendshipQuery { + direction := p.order.Direction + if p.reverse { + direction = direction.Reverse() + } + query = query.Order(p.order.Field.toTerm(direction.OrderTermOption())) + if p.order.Field != DefaultFriendshipOrder.Field { + query = query.Order(DefaultFriendshipOrder.Field.toTerm(direction.OrderTermOption())) + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(p.order.Field.column) + } + return query +} + +func (p *friendshipPager) orderExpr(query *FriendshipQuery) sql.Querier { + direction := p.order.Direction + if p.reverse { + direction = direction.Reverse() + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(p.order.Field.column) + } + return sql.ExprFunc(func(b *sql.Builder) { + b.Ident(p.order.Field.column).Pad().WriteString(string(direction)) + if p.order.Field != DefaultFriendshipOrder.Field { + b.Comma().Ident(DefaultFriendshipOrder.Field.column).Pad().WriteString(string(direction)) + } + }) +} + +// Paginate executes the query and returns a relay based cursor connection to Friendship. +func (f *FriendshipQuery) Paginate( + ctx context.Context, after *Cursor, first *int, + before *Cursor, last *int, opts ...FriendshipPaginateOption, +) (*FriendshipConnection, error) { + if err := validateFirstLast(first, last); err != nil { + return nil, err + } + pager, err := newFriendshipPager(opts, last != nil) + if err != nil { + return nil, err + } + if f, err = pager.applyFilter(f); err != nil { + return nil, err + } + conn := &FriendshipConnection{Edges: []*FriendshipEdge{}} + ignoredEdges := !hasCollectedField(ctx, edgesField) + if hasCollectedField(ctx, totalCountField) || hasCollectedField(ctx, pageInfoField) { + hasPagination := after != nil || first != nil || before != nil || last != nil + if hasPagination || ignoredEdges { + c := f.Clone() + c.ctx.Fields = nil + if conn.TotalCount, err = c.Count(ctx); err != nil { + return nil, err + } + conn.PageInfo.HasNextPage = first != nil && conn.TotalCount > 0 + conn.PageInfo.HasPreviousPage = last != nil && conn.TotalCount > 0 + } + } + if ignoredEdges || (first != nil && *first == 0) || (last != nil && *last == 0) { + return conn, nil + } + if f, err = pager.applyCursors(f, after, before); err != nil { + return nil, err + } + limit := paginateLimit(first, last) + if limit != 0 { + f.Limit(limit) + } + if field := collectedField(ctx, edgesField, nodeField); field != nil { + if err := f.collectField(ctx, limit == 1, graphql.GetOperationContext(ctx), *field, []string{edgesField, nodeField}); err != nil { + return nil, err + } + } + f = pager.applyOrder(f) + nodes, err := f.All(ctx) + if err != nil { + return nil, err + } + conn.build(nodes, pager, after, first, before, last) + return conn, nil +} + +// FriendshipOrderField defines the ordering field of Friendship. +type FriendshipOrderField struct { + // Value extracts the ordering value from the given Friendship. + Value func(*Friendship) (ent.Value, error) + column string // field or computed. + toTerm func(...sql.OrderTermOption) friendship.OrderOption + toCursor func(*Friendship) Cursor +} + +// FriendshipOrder defines the ordering of Friendship. +type FriendshipOrder struct { + Direction OrderDirection `json:"direction"` + Field *FriendshipOrderField `json:"field"` +} + +// DefaultFriendshipOrder is the default ordering of Friendship. +var DefaultFriendshipOrder = &FriendshipOrder{ + Direction: entgql.OrderDirectionAsc, + Field: &FriendshipOrderField{ + Value: func(f *Friendship) (ent.Value, error) { + return f.ID, nil + }, + column: friendship.FieldID, + toTerm: friendship.ByID, + toCursor: func(f *Friendship) Cursor { + return Cursor{ID: f.ID} + }, + }, +} + +// ToEdge converts Friendship into FriendshipEdge. +func (f *Friendship) ToEdge(order *FriendshipOrder) *FriendshipEdge { + if order == nil { + order = DefaultFriendshipOrder + } + return &FriendshipEdge{ + Node: f, + Cursor: order.Field.toCursor(f), + } +} + +// GroupEdge is the edge representation of Group. +type GroupEdge struct { + Node *Group `json:"node"` + Cursor Cursor `json:"cursor"` +} + +// GroupConnection is the connection containing edges to Group. +type GroupConnection struct { + Edges []*GroupEdge `json:"edges"` + PageInfo PageInfo `json:"pageInfo"` + TotalCount int `json:"totalCount"` +} + +func (c *GroupConnection) build(nodes []*Group, pager *groupPager, after *Cursor, first *int, before *Cursor, last *int) { + c.PageInfo.HasNextPage = before != nil + c.PageInfo.HasPreviousPage = after != nil + if first != nil && *first+1 == len(nodes) { + c.PageInfo.HasNextPage = true + nodes = nodes[:len(nodes)-1] + } else if last != nil && *last+1 == len(nodes) { + c.PageInfo.HasPreviousPage = true + nodes = nodes[:len(nodes)-1] + } + var nodeAt func(int) *Group + if last != nil { + n := len(nodes) - 1 + nodeAt = func(i int) *Group { + return nodes[n-i] + } + } else { + nodeAt = func(i int) *Group { + return nodes[i] + } + } + c.Edges = make([]*GroupEdge, len(nodes)) + for i := range nodes { + node := nodeAt(i) + c.Edges[i] = &GroupEdge{ + Node: node, + Cursor: pager.toCursor(node), + } + } + if l := len(c.Edges); l > 0 { + c.PageInfo.StartCursor = &c.Edges[0].Cursor + c.PageInfo.EndCursor = &c.Edges[l-1].Cursor + } + if c.TotalCount == 0 { + c.TotalCount = len(nodes) + } +} + +// GroupPaginateOption enables pagination customization. +type GroupPaginateOption func(*groupPager) error + +// WithGroupOrder configures pagination ordering. +func WithGroupOrder(order []*GroupOrder) GroupPaginateOption { + return func(pager *groupPager) error { + for _, o := range order { + if err := o.Direction.Validate(); err != nil { + return err + } + } + pager.order = append(pager.order, order...) + return nil + } +} + +// WithGroupFilter configures pagination filter. +func WithGroupFilter(filter func(*GroupQuery) (*GroupQuery, error)) GroupPaginateOption { + return func(pager *groupPager) error { + if filter == nil { + return errors.New("GroupQuery filter cannot be nil") + } + pager.filter = filter + return nil + } +} + +type groupPager struct { + reverse bool + order []*GroupOrder + filter func(*GroupQuery) (*GroupQuery, error) +} + +func newGroupPager(opts []GroupPaginateOption, reverse bool) (*groupPager, error) { + pager := &groupPager{reverse: reverse} + for _, opt := range opts { + if err := opt(pager); err != nil { + return nil, err + } + } + for i, o := range pager.order { + if i > 0 && o.Field == pager.order[i-1].Field { + return nil, fmt.Errorf("duplicate order direction %q", o.Direction) + } + } + return pager, nil +} + +func (p *groupPager) applyFilter(query *GroupQuery) (*GroupQuery, error) { + if p.filter != nil { + return p.filter(query) + } + return query, nil +} + +func (p *groupPager) toCursor(gr *Group) Cursor { + cs_ := make([]any, 0, len(p.order)) + for _, o_ := range p.order { + cs_ = append(cs_, o_.Field.toCursor(gr).Value) + } + return Cursor{ID: gr.ID, Value: cs_} +} + +func (p *groupPager) applyCursors(query *GroupQuery, after, before *Cursor) (*GroupQuery, error) { + idDirection := entgql.OrderDirectionAsc + if p.reverse { + idDirection = entgql.OrderDirectionDesc + } + fields, directions := make([]string, 0, len(p.order)), make([]OrderDirection, 0, len(p.order)) + for _, o := range p.order { + fields = append(fields, o.Field.column) + direction := o.Direction + if p.reverse { + direction = direction.Reverse() + } + directions = append(directions, direction) + } + predicates, err := entgql.MultiCursorsPredicate(after, before, &entgql.MultiCursorsOptions{ + FieldID: DefaultGroupOrder.Field.column, + DirectionID: idDirection, + Fields: fields, + Directions: directions, + }) + if err != nil { + return nil, err + } + for _, predicate := range predicates { + query = query.Where(predicate) + } + return query, nil +} + +func (p *groupPager) applyOrder(query *GroupQuery) *GroupQuery { + var defaultOrdered bool + for _, o := range p.order { + direction := o.Direction + if p.reverse { + direction = direction.Reverse() + } + query = query.Order(o.Field.toTerm(direction.OrderTermOption())) + if o.Field.column == DefaultGroupOrder.Field.column { + defaultOrdered = true + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(o.Field.column) + } + } + if !defaultOrdered { + direction := entgql.OrderDirectionAsc + if p.reverse { + direction = direction.Reverse() + } + query = query.Order(DefaultGroupOrder.Field.toTerm(direction.OrderTermOption())) + } + return query +} + +func (p *groupPager) orderExpr(query *GroupQuery) sql.Querier { + if len(query.ctx.Fields) > 0 { + for _, o := range p.order { + query.ctx.AppendFieldOnce(o.Field.column) + } + } + return sql.ExprFunc(func(b *sql.Builder) { + for _, o := range p.order { + direction := o.Direction + if p.reverse { + direction = direction.Reverse() + } + b.Ident(o.Field.column).Pad().WriteString(string(direction)) + b.Comma() + } + direction := entgql.OrderDirectionAsc + if p.reverse { + direction = direction.Reverse() + } + b.Ident(DefaultGroupOrder.Field.column).Pad().WriteString(string(direction)) + }) +} + +// Paginate executes the query and returns a relay based cursor connection to Group. +func (gr *GroupQuery) Paginate( + ctx context.Context, after *Cursor, first *int, + before *Cursor, last *int, opts ...GroupPaginateOption, +) (*GroupConnection, error) { + if err := validateFirstLast(first, last); err != nil { + return nil, err + } + pager, err := newGroupPager(opts, last != nil) + if err != nil { + return nil, err + } + if gr, err = pager.applyFilter(gr); err != nil { + return nil, err + } + conn := &GroupConnection{Edges: []*GroupEdge{}} + ignoredEdges := !hasCollectedField(ctx, edgesField) + if hasCollectedField(ctx, totalCountField) || hasCollectedField(ctx, pageInfoField) { + hasPagination := after != nil || first != nil || before != nil || last != nil + if hasPagination || ignoredEdges { + c := gr.Clone() + c.ctx.Fields = nil + if conn.TotalCount, err = c.Count(ctx); err != nil { + return nil, err + } + conn.PageInfo.HasNextPage = first != nil && conn.TotalCount > 0 + conn.PageInfo.HasPreviousPage = last != nil && conn.TotalCount > 0 + } + } + if ignoredEdges || (first != nil && *first == 0) || (last != nil && *last == 0) { + return conn, nil + } + if gr, err = pager.applyCursors(gr, after, before); err != nil { + return nil, err + } + limit := paginateLimit(first, last) + if limit != 0 { + gr.Limit(limit) + } + if field := collectedField(ctx, edgesField, nodeField); field != nil { + if err := gr.collectField(ctx, limit == 1, graphql.GetOperationContext(ctx), *field, []string{edgesField, nodeField}); err != nil { + return nil, err + } + } + gr = pager.applyOrder(gr) + nodes, err := gr.All(ctx) + if err != nil { + return nil, err + } + conn.build(nodes, pager, after, first, before, last) + return conn, nil +} + +// GroupOrderField defines the ordering field of Group. +type GroupOrderField struct { + // Value extracts the ordering value from the given Group. + Value func(*Group) (ent.Value, error) + column string // field or computed. + toTerm func(...sql.OrderTermOption) group.OrderOption + toCursor func(*Group) Cursor +} + +// GroupOrder defines the ordering of Group. +type GroupOrder struct { + Direction OrderDirection `json:"direction"` + Field *GroupOrderField `json:"field"` +} + +// DefaultGroupOrder is the default ordering of Group. +var DefaultGroupOrder = &GroupOrder{ + Direction: entgql.OrderDirectionAsc, + Field: &GroupOrderField{ + Value: func(gr *Group) (ent.Value, error) { + return gr.ID, nil + }, + column: group.FieldID, + toTerm: group.ByID, + toCursor: func(gr *Group) Cursor { + return Cursor{ID: gr.ID} + }, + }, +} + +// ToEdge converts Group into GroupEdge. +func (gr *Group) ToEdge(order *GroupOrder) *GroupEdge { + if order == nil { + order = DefaultGroupOrder + } + return &GroupEdge{ + Node: gr, + Cursor: order.Field.toCursor(gr), + } +} + +// OneToManyEdge is the edge representation of OneToMany. +type OneToManyEdge struct { + Node *OneToMany `json:"node"` + Cursor Cursor `json:"cursor"` +} + +// OneToManyConnection is the connection containing edges to OneToMany. +type OneToManyConnection struct { + Edges []*OneToManyEdge `json:"edges"` + PageInfo PageInfo `json:"pageInfo"` + TotalCount int `json:"totalCount"` +} + +func (c *OneToManyConnection) build(nodes []*OneToMany, pager *onetomanyPager, after *Cursor, first *int, before *Cursor, last *int) { + c.PageInfo.HasNextPage = before != nil + c.PageInfo.HasPreviousPage = after != nil + if first != nil && *first+1 == len(nodes) { + c.PageInfo.HasNextPage = true + nodes = nodes[:len(nodes)-1] + } else if last != nil && *last+1 == len(nodes) { + c.PageInfo.HasPreviousPage = true + nodes = nodes[:len(nodes)-1] + } + var nodeAt func(int) *OneToMany + if last != nil { + n := len(nodes) - 1 + nodeAt = func(i int) *OneToMany { + return nodes[n-i] + } + } else { + nodeAt = func(i int) *OneToMany { + return nodes[i] + } + } + c.Edges = make([]*OneToManyEdge, len(nodes)) + for i := range nodes { + node := nodeAt(i) + c.Edges[i] = &OneToManyEdge{ + Node: node, + Cursor: pager.toCursor(node), + } + } + if l := len(c.Edges); l > 0 { + c.PageInfo.StartCursor = &c.Edges[0].Cursor + c.PageInfo.EndCursor = &c.Edges[l-1].Cursor + } + if c.TotalCount == 0 { + c.TotalCount = len(nodes) + } +} + +// OneToManyPaginateOption enables pagination customization. +type OneToManyPaginateOption func(*onetomanyPager) error + +// WithOneToManyOrder configures pagination ordering. +func WithOneToManyOrder(order *OneToManyOrder) OneToManyPaginateOption { + if order == nil { + order = DefaultOneToManyOrder + } + o := *order + return func(pager *onetomanyPager) error { + if err := o.Direction.Validate(); err != nil { + return err + } + if o.Field == nil { + o.Field = DefaultOneToManyOrder.Field + } + pager.order = &o + return nil + } +} + +// WithOneToManyFilter configures pagination filter. +func WithOneToManyFilter(filter func(*OneToManyQuery) (*OneToManyQuery, error)) OneToManyPaginateOption { + return func(pager *onetomanyPager) error { + if filter == nil { + return errors.New("OneToManyQuery filter cannot be nil") + } + pager.filter = filter + return nil + } +} + +type onetomanyPager struct { + reverse bool + order *OneToManyOrder + filter func(*OneToManyQuery) (*OneToManyQuery, error) +} + +func newOneToManyPager(opts []OneToManyPaginateOption, reverse bool) (*onetomanyPager, error) { + pager := &onetomanyPager{reverse: reverse} + for _, opt := range opts { + if err := opt(pager); err != nil { + return nil, err + } + } + if pager.order == nil { + pager.order = DefaultOneToManyOrder + } + return pager, nil +} + +func (p *onetomanyPager) applyFilter(query *OneToManyQuery) (*OneToManyQuery, error) { + if p.filter != nil { + return p.filter(query) + } + return query, nil +} + +func (p *onetomanyPager) toCursor(otm *OneToMany) Cursor { + return p.order.Field.toCursor(otm) +} + +func (p *onetomanyPager) applyCursors(query *OneToManyQuery, after, before *Cursor) (*OneToManyQuery, error) { + direction := p.order.Direction + if p.reverse { + direction = direction.Reverse() + } + for _, predicate := range entgql.CursorsPredicate(after, before, DefaultOneToManyOrder.Field.column, p.order.Field.column, direction) { + query = query.Where(predicate) + } + return query, nil +} + +func (p *onetomanyPager) applyOrder(query *OneToManyQuery) *OneToManyQuery { + direction := p.order.Direction + if p.reverse { + direction = direction.Reverse() + } + query = query.Order(p.order.Field.toTerm(direction.OrderTermOption())) + if p.order.Field != DefaultOneToManyOrder.Field { + query = query.Order(DefaultOneToManyOrder.Field.toTerm(direction.OrderTermOption())) + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(p.order.Field.column) + } + return query +} + +func (p *onetomanyPager) orderExpr(query *OneToManyQuery) sql.Querier { + direction := p.order.Direction + if p.reverse { + direction = direction.Reverse() + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(p.order.Field.column) + } + return sql.ExprFunc(func(b *sql.Builder) { + b.Ident(p.order.Field.column).Pad().WriteString(string(direction)) + if p.order.Field != DefaultOneToManyOrder.Field { + b.Comma().Ident(DefaultOneToManyOrder.Field.column).Pad().WriteString(string(direction)) + } + }) +} + +// Paginate executes the query and returns a relay based cursor connection to OneToMany. +func (otm *OneToManyQuery) Paginate( + ctx context.Context, after *Cursor, first *int, + before *Cursor, last *int, opts ...OneToManyPaginateOption, +) (*OneToManyConnection, error) { + if err := validateFirstLast(first, last); err != nil { + return nil, err + } + pager, err := newOneToManyPager(opts, last != nil) + if err != nil { + return nil, err + } + if otm, err = pager.applyFilter(otm); err != nil { + return nil, err + } + conn := &OneToManyConnection{Edges: []*OneToManyEdge{}} + ignoredEdges := !hasCollectedField(ctx, edgesField) + if hasCollectedField(ctx, totalCountField) || hasCollectedField(ctx, pageInfoField) { + hasPagination := after != nil || first != nil || before != nil || last != nil + if hasPagination || ignoredEdges { + c := otm.Clone() + c.ctx.Fields = nil + if conn.TotalCount, err = c.Count(ctx); err != nil { + return nil, err + } + conn.PageInfo.HasNextPage = first != nil && conn.TotalCount > 0 + conn.PageInfo.HasPreviousPage = last != nil && conn.TotalCount > 0 + } + } + if ignoredEdges || (first != nil && *first == 0) || (last != nil && *last == 0) { + return conn, nil + } + if otm, err = pager.applyCursors(otm, after, before); err != nil { + return nil, err + } + limit := paginateLimit(first, last) + if limit != 0 { + otm.Limit(limit) + } + if field := collectedField(ctx, edgesField, nodeField); field != nil { + if err := otm.collectField(ctx, limit == 1, graphql.GetOperationContext(ctx), *field, []string{edgesField, nodeField}); err != nil { + return nil, err + } + } + otm = pager.applyOrder(otm) + nodes, err := otm.All(ctx) + if err != nil { + return nil, err + } + conn.build(nodes, pager, after, first, before, last) + return conn, nil +} + +var ( + // OneToManyOrderFieldName orders OneToMany by name. + OneToManyOrderFieldName = &OneToManyOrderField{ + Value: func(otm *OneToMany) (ent.Value, error) { + return otm.Name, nil + }, + column: onetomany.FieldName, + toTerm: onetomany.ByName, + toCursor: func(otm *OneToMany) Cursor { + return Cursor{ + ID: otm.ID, + Value: otm.Name, + } + }, + } +) + +// String implement fmt.Stringer interface. +func (f OneToManyOrderField) String() string { + var str string + switch f.column { + case OneToManyOrderFieldName.column: + str = "NAME" + } + return str +} + +// MarshalGQL implements graphql.Marshaler interface. +func (f OneToManyOrderField) MarshalGQL(w io.Writer) { + io.WriteString(w, strconv.Quote(f.String())) +} + +// UnmarshalGQL implements graphql.Unmarshaler interface. +func (f *OneToManyOrderField) UnmarshalGQL(v interface{}) error { + str, ok := v.(string) + if !ok { + return fmt.Errorf("OneToManyOrderField %T must be a string", v) + } + switch str { + case "NAME": + *f = *OneToManyOrderFieldName + default: + return fmt.Errorf("%s is not a valid OneToManyOrderField", str) + } + return nil +} + +// OneToManyOrderField defines the ordering field of OneToMany. +type OneToManyOrderField struct { + // Value extracts the ordering value from the given OneToMany. + Value func(*OneToMany) (ent.Value, error) + column string // field or computed. + toTerm func(...sql.OrderTermOption) onetomany.OrderOption + toCursor func(*OneToMany) Cursor +} + +// OneToManyOrder defines the ordering of OneToMany. +type OneToManyOrder struct { + Direction OrderDirection `json:"direction"` + Field *OneToManyOrderField `json:"field"` +} + +// DefaultOneToManyOrder is the default ordering of OneToMany. +var DefaultOneToManyOrder = &OneToManyOrder{ + Direction: entgql.OrderDirectionAsc, + Field: &OneToManyOrderField{ + Value: func(otm *OneToMany) (ent.Value, error) { + return otm.ID, nil + }, + column: onetomany.FieldID, + toTerm: onetomany.ByID, + toCursor: func(otm *OneToMany) Cursor { + return Cursor{ID: otm.ID} + }, + }, +} + +// ToEdge converts OneToMany into OneToManyEdge. +func (otm *OneToMany) ToEdge(order *OneToManyOrder) *OneToManyEdge { + if order == nil { + order = DefaultOneToManyOrder + } + return &OneToManyEdge{ + Node: otm, + Cursor: order.Field.toCursor(otm), + } +} + +// ProjectEdge is the edge representation of Project. +type ProjectEdge struct { + Node *Project `json:"node"` + Cursor Cursor `json:"cursor"` +} + +// ProjectConnection is the connection containing edges to Project. +type ProjectConnection struct { + Edges []*ProjectEdge `json:"edges"` + PageInfo PageInfo `json:"pageInfo"` + TotalCount int `json:"totalCount"` +} + +func (c *ProjectConnection) build(nodes []*Project, pager *projectPager, after *Cursor, first *int, before *Cursor, last *int) { + c.PageInfo.HasNextPage = before != nil + c.PageInfo.HasPreviousPage = after != nil + if first != nil && *first+1 == len(nodes) { + c.PageInfo.HasNextPage = true + nodes = nodes[:len(nodes)-1] + } else if last != nil && *last+1 == len(nodes) { + c.PageInfo.HasPreviousPage = true + nodes = nodes[:len(nodes)-1] + } + var nodeAt func(int) *Project + if last != nil { + n := len(nodes) - 1 + nodeAt = func(i int) *Project { + return nodes[n-i] + } + } else { + nodeAt = func(i int) *Project { + return nodes[i] + } + } + c.Edges = make([]*ProjectEdge, len(nodes)) + for i := range nodes { + node := nodeAt(i) + c.Edges[i] = &ProjectEdge{ + Node: node, + Cursor: pager.toCursor(node), + } + } + if l := len(c.Edges); l > 0 { + c.PageInfo.StartCursor = &c.Edges[0].Cursor + c.PageInfo.EndCursor = &c.Edges[l-1].Cursor + } + if c.TotalCount == 0 { + c.TotalCount = len(nodes) + } +} + +// ProjectPaginateOption enables pagination customization. +type ProjectPaginateOption func(*projectPager) error + +// WithProjectOrder configures pagination ordering. +func WithProjectOrder(order *ProjectOrder) ProjectPaginateOption { + if order == nil { + order = DefaultProjectOrder + } + o := *order + return func(pager *projectPager) error { + if err := o.Direction.Validate(); err != nil { + return err + } + if o.Field == nil { + o.Field = DefaultProjectOrder.Field + } + pager.order = &o + return nil + } +} + +// WithProjectFilter configures pagination filter. +func WithProjectFilter(filter func(*ProjectQuery) (*ProjectQuery, error)) ProjectPaginateOption { + return func(pager *projectPager) error { + if filter == nil { + return errors.New("ProjectQuery filter cannot be nil") + } + pager.filter = filter + return nil + } +} + +type projectPager struct { + reverse bool + order *ProjectOrder + filter func(*ProjectQuery) (*ProjectQuery, error) +} + +func newProjectPager(opts []ProjectPaginateOption, reverse bool) (*projectPager, error) { + pager := &projectPager{reverse: reverse} + for _, opt := range opts { + if err := opt(pager); err != nil { + return nil, err + } + } + if pager.order == nil { + pager.order = DefaultProjectOrder + } + return pager, nil +} + +func (p *projectPager) applyFilter(query *ProjectQuery) (*ProjectQuery, error) { + if p.filter != nil { + return p.filter(query) + } + return query, nil +} + +func (p *projectPager) toCursor(pr *Project) Cursor { + return p.order.Field.toCursor(pr) +} + +func (p *projectPager) applyCursors(query *ProjectQuery, after, before *Cursor) (*ProjectQuery, error) { + direction := p.order.Direction + if p.reverse { + direction = direction.Reverse() + } + for _, predicate := range entgql.CursorsPredicate(after, before, DefaultProjectOrder.Field.column, p.order.Field.column, direction) { + query = query.Where(predicate) + } + return query, nil +} + +func (p *projectPager) applyOrder(query *ProjectQuery) *ProjectQuery { + direction := p.order.Direction + if p.reverse { + direction = direction.Reverse() + } + query = query.Order(p.order.Field.toTerm(direction.OrderTermOption())) + if p.order.Field != DefaultProjectOrder.Field { + query = query.Order(DefaultProjectOrder.Field.toTerm(direction.OrderTermOption())) + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(p.order.Field.column) + } + return query +} + +func (p *projectPager) orderExpr(query *ProjectQuery) sql.Querier { + direction := p.order.Direction + if p.reverse { + direction = direction.Reverse() + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(p.order.Field.column) + } + return sql.ExprFunc(func(b *sql.Builder) { + b.Ident(p.order.Field.column).Pad().WriteString(string(direction)) + if p.order.Field != DefaultProjectOrder.Field { + b.Comma().Ident(DefaultProjectOrder.Field.column).Pad().WriteString(string(direction)) + } + }) +} + +// Paginate executes the query and returns a relay based cursor connection to Project. +func (pr *ProjectQuery) Paginate( + ctx context.Context, after *Cursor, first *int, + before *Cursor, last *int, opts ...ProjectPaginateOption, +) (*ProjectConnection, error) { + if err := validateFirstLast(first, last); err != nil { + return nil, err + } + pager, err := newProjectPager(opts, last != nil) + if err != nil { + return nil, err + } + if pr, err = pager.applyFilter(pr); err != nil { + return nil, err + } + conn := &ProjectConnection{Edges: []*ProjectEdge{}} + ignoredEdges := !hasCollectedField(ctx, edgesField) + if hasCollectedField(ctx, totalCountField) || hasCollectedField(ctx, pageInfoField) { + hasPagination := after != nil || first != nil || before != nil || last != nil + if hasPagination || ignoredEdges { + c := pr.Clone() + c.ctx.Fields = nil + if conn.TotalCount, err = c.Count(ctx); err != nil { + return nil, err + } + conn.PageInfo.HasNextPage = first != nil && conn.TotalCount > 0 + conn.PageInfo.HasPreviousPage = last != nil && conn.TotalCount > 0 + } + } + if ignoredEdges || (first != nil && *first == 0) || (last != nil && *last == 0) { + return conn, nil + } + if pr, err = pager.applyCursors(pr, after, before); err != nil { + return nil, err + } + limit := paginateLimit(first, last) + if limit != 0 { + pr.Limit(limit) + } + if field := collectedField(ctx, edgesField, nodeField); field != nil { + if err := pr.collectField(ctx, limit == 1, graphql.GetOperationContext(ctx), *field, []string{edgesField, nodeField}); err != nil { + return nil, err + } + } + pr = pager.applyOrder(pr) + nodes, err := pr.All(ctx) + if err != nil { + return nil, err + } + conn.build(nodes, pager, after, first, before, last) + return conn, nil +} + +// ProjectOrderField defines the ordering field of Project. +type ProjectOrderField struct { + // Value extracts the ordering value from the given Project. + Value func(*Project) (ent.Value, error) + column string // field or computed. + toTerm func(...sql.OrderTermOption) project.OrderOption + toCursor func(*Project) Cursor +} + +// ProjectOrder defines the ordering of Project. +type ProjectOrder struct { + Direction OrderDirection `json:"direction"` + Field *ProjectOrderField `json:"field"` +} + +// DefaultProjectOrder is the default ordering of Project. +var DefaultProjectOrder = &ProjectOrder{ + Direction: entgql.OrderDirectionAsc, + Field: &ProjectOrderField{ + Value: func(pr *Project) (ent.Value, error) { + return pr.ID, nil + }, + column: project.FieldID, + toTerm: project.ByID, + toCursor: func(pr *Project) Cursor { + return Cursor{ID: pr.ID} + }, + }, +} + +// ToEdge converts Project into ProjectEdge. +func (pr *Project) ToEdge(order *ProjectOrder) *ProjectEdge { + if order == nil { + order = DefaultProjectOrder + } + return &ProjectEdge{ + Node: pr, + Cursor: order.Field.toCursor(pr), + } +} + +// TodoEdge is the edge representation of Todo. +type TodoEdge struct { + Node *Todo `json:"node"` + Cursor Cursor `json:"cursor"` +} + +// TodoConnection is the connection containing edges to Todo. +type TodoConnection struct { + Edges []*TodoEdge `json:"edges"` + PageInfo PageInfo `json:"pageInfo"` + TotalCount int `json:"totalCount"` +} + +func (c *TodoConnection) build(nodes []*Todo, pager *todoPager, after *Cursor, first *int, before *Cursor, last *int) { + c.PageInfo.HasNextPage = before != nil + c.PageInfo.HasPreviousPage = after != nil + if first != nil && *first+1 == len(nodes) { + c.PageInfo.HasNextPage = true + nodes = nodes[:len(nodes)-1] + } else if last != nil && *last+1 == len(nodes) { + c.PageInfo.HasPreviousPage = true + nodes = nodes[:len(nodes)-1] + } + var nodeAt func(int) *Todo + if last != nil { + n := len(nodes) - 1 + nodeAt = func(i int) *Todo { + return nodes[n-i] + } + } else { + nodeAt = func(i int) *Todo { + return nodes[i] + } + } + c.Edges = make([]*TodoEdge, len(nodes)) + for i := range nodes { + node := nodeAt(i) + c.Edges[i] = &TodoEdge{ + Node: node, + Cursor: pager.toCursor(node), + } + } + if l := len(c.Edges); l > 0 { + c.PageInfo.StartCursor = &c.Edges[0].Cursor + c.PageInfo.EndCursor = &c.Edges[l-1].Cursor + } + if c.TotalCount == 0 { + c.TotalCount = len(nodes) + } +} + +// TodoPaginateOption enables pagination customization. +type TodoPaginateOption func(*todoPager) error + +// WithTodoOrder configures pagination ordering. +func WithTodoOrder(order []*TodoOrder) TodoPaginateOption { + return func(pager *todoPager) error { + for _, o := range order { + if err := o.Direction.Validate(); err != nil { + return err + } + } + pager.order = append(pager.order, order...) + return nil + } +} + +// WithTodoFilter configures pagination filter. +func WithTodoFilter(filter func(*TodoQuery) (*TodoQuery, error)) TodoPaginateOption { + return func(pager *todoPager) error { + if filter == nil { + return errors.New("TodoQuery filter cannot be nil") + } + pager.filter = filter + return nil + } +} + +type todoPager struct { + reverse bool + order []*TodoOrder + filter func(*TodoQuery) (*TodoQuery, error) +} + +func newTodoPager(opts []TodoPaginateOption, reverse bool) (*todoPager, error) { + pager := &todoPager{reverse: reverse} + for _, opt := range opts { + if err := opt(pager); err != nil { + return nil, err + } + } + for i, o := range pager.order { + if i > 0 && o.Field == pager.order[i-1].Field { + return nil, fmt.Errorf("duplicate order direction %q", o.Direction) + } + } + return pager, nil +} + +func (p *todoPager) applyFilter(query *TodoQuery) (*TodoQuery, error) { + if p.filter != nil { + return p.filter(query) + } + return query, nil +} + +func (p *todoPager) toCursor(t *Todo) Cursor { + cs_ := make([]any, 0, len(p.order)) + for _, o_ := range p.order { + cs_ = append(cs_, o_.Field.toCursor(t).Value) + } + return Cursor{ID: t.ID, Value: cs_} +} + +func (p *todoPager) applyCursors(query *TodoQuery, after, before *Cursor) (*TodoQuery, error) { + idDirection := entgql.OrderDirectionAsc + if p.reverse { + idDirection = entgql.OrderDirectionDesc + } + fields, directions := make([]string, 0, len(p.order)), make([]OrderDirection, 0, len(p.order)) + for _, o := range p.order { + fields = append(fields, o.Field.column) + direction := o.Direction + if p.reverse { + direction = direction.Reverse() + } + directions = append(directions, direction) + } + predicates, err := entgql.MultiCursorsPredicate(after, before, &entgql.MultiCursorsOptions{ + FieldID: DefaultTodoOrder.Field.column, + DirectionID: idDirection, + Fields: fields, + Directions: directions, + }) + if err != nil { + return nil, err + } + for _, predicate := range predicates { + query = query.Where(predicate) + } + return query, nil +} + +func (p *todoPager) applyOrder(query *TodoQuery) *TodoQuery { + var defaultOrdered bool + for _, o := range p.order { + direction := o.Direction + if p.reverse { + direction = direction.Reverse() + } + query = query.Order(o.Field.toTerm(direction.OrderTermOption())) + if o.Field.column == DefaultTodoOrder.Field.column { + defaultOrdered = true + } + switch o.Field.column { + case TodoOrderFieldParentStatus.column, TodoOrderFieldChildrenCount.column, TodoOrderFieldCategoryText.column: + default: + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(o.Field.column) + } + } + } + if !defaultOrdered { + direction := entgql.OrderDirectionAsc + if p.reverse { + direction = direction.Reverse() + } + query = query.Order(DefaultTodoOrder.Field.toTerm(direction.OrderTermOption())) + } + return query +} + +func (p *todoPager) orderExpr(query *TodoQuery) sql.Querier { + for _, o := range p.order { + switch o.Field.column { + case TodoOrderFieldParentStatus.column, TodoOrderFieldChildrenCount.column, TodoOrderFieldCategoryText.column: + direction := o.Direction + if p.reverse { + direction = direction.Reverse() + } + query = query.Order(o.Field.toTerm(direction.OrderTermOption())) + default: + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(o.Field.column) + } + } + } + return sql.ExprFunc(func(b *sql.Builder) { + for _, o := range p.order { + direction := o.Direction + if p.reverse { + direction = direction.Reverse() + } + b.Ident(o.Field.column).Pad().WriteString(string(direction)) + b.Comma() + } + direction := entgql.OrderDirectionAsc + if p.reverse { + direction = direction.Reverse() + } + b.Ident(DefaultTodoOrder.Field.column).Pad().WriteString(string(direction)) + }) +} + +// Paginate executes the query and returns a relay based cursor connection to Todo. +func (t *TodoQuery) Paginate( + ctx context.Context, after *Cursor, first *int, + before *Cursor, last *int, opts ...TodoPaginateOption, +) (*TodoConnection, error) { + if err := validateFirstLast(first, last); err != nil { + return nil, err + } + pager, err := newTodoPager(opts, last != nil) + if err != nil { + return nil, err + } + if t, err = pager.applyFilter(t); err != nil { + return nil, err + } + conn := &TodoConnection{Edges: []*TodoEdge{}} + ignoredEdges := !hasCollectedField(ctx, edgesField) + if hasCollectedField(ctx, totalCountField) || hasCollectedField(ctx, pageInfoField) { + hasPagination := after != nil || first != nil || before != nil || last != nil + if hasPagination || ignoredEdges { + c := t.Clone() + c.ctx.Fields = nil + if conn.TotalCount, err = c.Count(ctx); err != nil { + return nil, err + } + conn.PageInfo.HasNextPage = first != nil && conn.TotalCount > 0 + conn.PageInfo.HasPreviousPage = last != nil && conn.TotalCount > 0 + } + } + if ignoredEdges || (first != nil && *first == 0) || (last != nil && *last == 0) { + return conn, nil + } + if t, err = pager.applyCursors(t, after, before); err != nil { + return nil, err + } + limit := paginateLimit(first, last) + if limit != 0 { + t.Limit(limit) + } + if field := collectedField(ctx, edgesField, nodeField); field != nil { + if err := t.collectField(ctx, limit == 1, graphql.GetOperationContext(ctx), *field, []string{edgesField, nodeField}); err != nil { + return nil, err + } + } + t = pager.applyOrder(t) + nodes, err := t.All(ctx) + if err != nil { + return nil, err + } + conn.build(nodes, pager, after, first, before, last) + return conn, nil +} + +var ( + // TodoOrderFieldCreatedAt orders Todo by created_at. + TodoOrderFieldCreatedAt = &TodoOrderField{ + Value: func(t *Todo) (ent.Value, error) { + return t.CreatedAt, nil + }, + column: todo.FieldCreatedAt, + toTerm: todo.ByCreatedAt, + toCursor: func(t *Todo) Cursor { + return Cursor{ + ID: t.ID, + Value: t.CreatedAt, + } + }, + } + // TodoOrderFieldStatus orders Todo by status. + TodoOrderFieldStatus = &TodoOrderField{ + Value: func(t *Todo) (ent.Value, error) { + return t.Status, nil + }, + column: todo.FieldStatus, + toTerm: todo.ByStatus, + toCursor: func(t *Todo) Cursor { + return Cursor{ + ID: t.ID, + Value: t.Status, + } + }, + } + // TodoOrderFieldPriority orders Todo by priority. + TodoOrderFieldPriority = &TodoOrderField{ + Value: func(t *Todo) (ent.Value, error) { + return t.Priority, nil + }, + column: todo.FieldPriority, + toTerm: todo.ByPriority, + toCursor: func(t *Todo) Cursor { + return Cursor{ + ID: t.ID, + Value: t.Priority, + } + }, + } + // TodoOrderFieldText orders Todo by text. + TodoOrderFieldText = &TodoOrderField{ + Value: func(t *Todo) (ent.Value, error) { + return t.Text, nil + }, + column: todo.FieldText, + toTerm: todo.ByText, + toCursor: func(t *Todo) Cursor { + return Cursor{ + ID: t.ID, + Value: t.Text, + } + }, + } + // TodoOrderFieldParentStatus orders by PARENT_STATUS. + TodoOrderFieldParentStatus = &TodoOrderField{ + Value: func(t *Todo) (ent.Value, error) { + return t.GetValue("parent_status") + }, + column: "parent_status", + toTerm: func(opts ...sql.OrderTermOption) todo.OrderOption { + return todo.ByParentField( + todo.FieldStatus, + append(opts, sql.OrderSelectAs("parent_status"))..., + ) + }, + toCursor: func(t *Todo) Cursor { + cv, _ := t.GetValue("parent_status") + return Cursor{ + ID: t.ID, + Value: cv, + } + }, + } + // TodoOrderFieldChildrenCount orders by CHILDREN_COUNT. + TodoOrderFieldChildrenCount = &TodoOrderField{ + Value: func(t *Todo) (ent.Value, error) { + return t.GetValue("children_count") + }, + column: "children_count", + toTerm: func(opts ...sql.OrderTermOption) todo.OrderOption { + return todo.ByChildrenCount( + append(opts, sql.OrderSelectAs("children_count"))..., + ) + }, + toCursor: func(t *Todo) Cursor { + cv, _ := t.GetValue("children_count") + return Cursor{ + ID: t.ID, + Value: cv, + } + }, + } + // TodoOrderFieldCategoryText orders by CATEGORY_TEXT. + TodoOrderFieldCategoryText = &TodoOrderField{ + Value: func(t *Todo) (ent.Value, error) { + return t.GetValue("category_text") + }, + column: "category_text", + toTerm: func(opts ...sql.OrderTermOption) todo.OrderOption { + return todo.ByCategoryField( + category.FieldText, + append(opts, sql.OrderSelectAs("category_text"))..., + ) + }, + toCursor: func(t *Todo) Cursor { + cv, _ := t.GetValue("category_text") + return Cursor{ + ID: t.ID, + Value: cv, + } + }, + } +) + +// String implement fmt.Stringer interface. +func (f TodoOrderField) String() string { + var str string + switch f.column { + case TodoOrderFieldCreatedAt.column: + str = "CREATED_AT" + case TodoOrderFieldStatus.column: + str = "STATUS" + case TodoOrderFieldPriority.column: + str = "PRIORITY_ORDER" + case TodoOrderFieldText.column: + str = "TEXT" + case TodoOrderFieldParentStatus.column: + str = "PARENT_STATUS" + case TodoOrderFieldChildrenCount.column: + str = "CHILDREN_COUNT" + case TodoOrderFieldCategoryText.column: + str = "CATEGORY_TEXT" + } + return str +} + +// MarshalGQL implements graphql.Marshaler interface. +func (f TodoOrderField) MarshalGQL(w io.Writer) { + io.WriteString(w, strconv.Quote(f.String())) +} + +// UnmarshalGQL implements graphql.Unmarshaler interface. +func (f *TodoOrderField) UnmarshalGQL(v interface{}) error { + str, ok := v.(string) + if !ok { + return fmt.Errorf("TodoOrderField %T must be a string", v) + } + switch str { + case "CREATED_AT": + *f = *TodoOrderFieldCreatedAt + case "STATUS": + *f = *TodoOrderFieldStatus + case "PRIORITY_ORDER": + *f = *TodoOrderFieldPriority + case "TEXT": + *f = *TodoOrderFieldText + case "PARENT_STATUS": + *f = *TodoOrderFieldParentStatus + case "CHILDREN_COUNT": + *f = *TodoOrderFieldChildrenCount + case "CATEGORY_TEXT": + *f = *TodoOrderFieldCategoryText + default: + return fmt.Errorf("%s is not a valid TodoOrderField", str) + } + return nil +} + +// TodoOrderField defines the ordering field of Todo. +type TodoOrderField struct { + // Value extracts the ordering value from the given Todo. + Value func(*Todo) (ent.Value, error) + column string // field or computed. + toTerm func(...sql.OrderTermOption) todo.OrderOption + toCursor func(*Todo) Cursor +} + +// TodoOrder defines the ordering of Todo. +type TodoOrder struct { + Direction OrderDirection `json:"direction"` + Field *TodoOrderField `json:"field"` +} + +// DefaultTodoOrder is the default ordering of Todo. +var DefaultTodoOrder = &TodoOrder{ + Direction: entgql.OrderDirectionAsc, + Field: &TodoOrderField{ + Value: func(t *Todo) (ent.Value, error) { + return t.ID, nil + }, + column: todo.FieldID, + toTerm: todo.ByID, + toCursor: func(t *Todo) Cursor { + return Cursor{ID: t.ID} + }, + }, +} + +// ToEdge converts Todo into TodoEdge. +func (t *Todo) ToEdge(order *TodoOrder) *TodoEdge { + if order == nil { + order = DefaultTodoOrder + } + return &TodoEdge{ + Node: t, + Cursor: order.Field.toCursor(t), + } +} + +// UserEdge is the edge representation of User. +type UserEdge struct { + Node *User `json:"node"` + Cursor Cursor `json:"cursor"` +} + +// UserConnection is the connection containing edges to User. +type UserConnection struct { + Edges []*UserEdge `json:"edges"` + PageInfo PageInfo `json:"pageInfo"` + TotalCount int `json:"totalCount"` +} + +func (c *UserConnection) build(nodes []*User, pager *userPager, after *Cursor, first *int, before *Cursor, last *int) { + c.PageInfo.HasNextPage = before != nil + c.PageInfo.HasPreviousPage = after != nil + if first != nil && *first+1 == len(nodes) { + c.PageInfo.HasNextPage = true + nodes = nodes[:len(nodes)-1] + } else if last != nil && *last+1 == len(nodes) { + c.PageInfo.HasPreviousPage = true + nodes = nodes[:len(nodes)-1] + } + var nodeAt func(int) *User + if last != nil { + n := len(nodes) - 1 + nodeAt = func(i int) *User { + return nodes[n-i] + } + } else { + nodeAt = func(i int) *User { + return nodes[i] + } + } + c.Edges = make([]*UserEdge, len(nodes)) + for i := range nodes { + node := nodeAt(i) + c.Edges[i] = &UserEdge{ + Node: node, + Cursor: pager.toCursor(node), + } + } + if l := len(c.Edges); l > 0 { + c.PageInfo.StartCursor = &c.Edges[0].Cursor + c.PageInfo.EndCursor = &c.Edges[l-1].Cursor + } + if c.TotalCount == 0 { + c.TotalCount = len(nodes) + } +} + +// UserPaginateOption enables pagination customization. +type UserPaginateOption func(*userPager) error + +// WithUserOrder configures pagination ordering. +func WithUserOrder(order *UserOrder) UserPaginateOption { + if order == nil { + order = DefaultUserOrder + } + o := *order + return func(pager *userPager) error { + if err := o.Direction.Validate(); err != nil { + return err + } + if o.Field == nil { + o.Field = DefaultUserOrder.Field + } + pager.order = &o + return nil + } +} + +// WithUserFilter configures pagination filter. +func WithUserFilter(filter func(*UserQuery) (*UserQuery, error)) UserPaginateOption { + return func(pager *userPager) error { + if filter == nil { + return errors.New("UserQuery filter cannot be nil") + } + pager.filter = filter + return nil + } +} + +type userPager struct { + reverse bool + order *UserOrder + filter func(*UserQuery) (*UserQuery, error) +} + +func newUserPager(opts []UserPaginateOption, reverse bool) (*userPager, error) { + pager := &userPager{reverse: reverse} + for _, opt := range opts { + if err := opt(pager); err != nil { + return nil, err + } + } + if pager.order == nil { + pager.order = DefaultUserOrder + } + return pager, nil +} + +func (p *userPager) applyFilter(query *UserQuery) (*UserQuery, error) { + if p.filter != nil { + return p.filter(query) + } + return query, nil +} + +func (p *userPager) toCursor(u *User) Cursor { + return p.order.Field.toCursor(u) +} + +func (p *userPager) applyCursors(query *UserQuery, after, before *Cursor) (*UserQuery, error) { + direction := p.order.Direction + if p.reverse { + direction = direction.Reverse() + } + for _, predicate := range entgql.CursorsPredicate(after, before, DefaultUserOrder.Field.column, p.order.Field.column, direction) { + query = query.Where(predicate) + } + return query, nil +} + +func (p *userPager) applyOrder(query *UserQuery) *UserQuery { + direction := p.order.Direction + if p.reverse { + direction = direction.Reverse() + } + query = query.Order(p.order.Field.toTerm(direction.OrderTermOption())) + if p.order.Field != DefaultUserOrder.Field { + query = query.Order(DefaultUserOrder.Field.toTerm(direction.OrderTermOption())) + } + switch p.order.Field.column { + case UserOrderFieldGroupsCount.column: + default: + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(p.order.Field.column) + } + } + return query +} + +func (p *userPager) orderExpr(query *UserQuery) sql.Querier { + direction := p.order.Direction + if p.reverse { + direction = direction.Reverse() + } + switch p.order.Field.column { + case UserOrderFieldGroupsCount.column: + query = query.Order(p.order.Field.toTerm(direction.OrderTermOption())) + default: + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(p.order.Field.column) + } + } + return sql.ExprFunc(func(b *sql.Builder) { + b.Ident(p.order.Field.column).Pad().WriteString(string(direction)) + if p.order.Field != DefaultUserOrder.Field { + b.Comma().Ident(DefaultUserOrder.Field.column).Pad().WriteString(string(direction)) + } + }) +} + +// Paginate executes the query and returns a relay based cursor connection to User. +func (u *UserQuery) Paginate( + ctx context.Context, after *Cursor, first *int, + before *Cursor, last *int, opts ...UserPaginateOption, +) (*UserConnection, error) { + if err := validateFirstLast(first, last); err != nil { + return nil, err + } + pager, err := newUserPager(opts, last != nil) + if err != nil { + return nil, err + } + if u, err = pager.applyFilter(u); err != nil { + return nil, err + } + conn := &UserConnection{Edges: []*UserEdge{}} + ignoredEdges := !hasCollectedField(ctx, edgesField) + if hasCollectedField(ctx, totalCountField) || hasCollectedField(ctx, pageInfoField) { + hasPagination := after != nil || first != nil || before != nil || last != nil + if hasPagination || ignoredEdges { + c := u.Clone() + c.ctx.Fields = nil + if conn.TotalCount, err = c.Count(ctx); err != nil { + return nil, err + } + conn.PageInfo.HasNextPage = first != nil && conn.TotalCount > 0 + conn.PageInfo.HasPreviousPage = last != nil && conn.TotalCount > 0 + } + } + if ignoredEdges || (first != nil && *first == 0) || (last != nil && *last == 0) { + return conn, nil + } + if u, err = pager.applyCursors(u, after, before); err != nil { + return nil, err + } + limit := paginateLimit(first, last) + if limit != 0 { + u.Limit(limit) + } + if field := collectedField(ctx, edgesField, nodeField); field != nil { + if err := u.collectField(ctx, limit == 1, graphql.GetOperationContext(ctx), *field, []string{edgesField, nodeField}); err != nil { + return nil, err + } + } + u = pager.applyOrder(u) + nodes, err := u.All(ctx) + if err != nil { + return nil, err + } + conn.build(nodes, pager, after, first, before, last) + return conn, nil +} + +var ( + // UserOrderFieldGroupsCount orders by GROUPS_COUNT. + UserOrderFieldGroupsCount = &UserOrderField{ + Value: func(u *User) (ent.Value, error) { + return u.Value("groups_count") + }, + column: "groups_count", + toTerm: func(opts ...sql.OrderTermOption) user.OrderOption { + return user.ByGroupsCount( + append(opts, sql.OrderSelectAs("groups_count"))..., + ) + }, + toCursor: func(u *User) Cursor { + cv, _ := u.Value("groups_count") + return Cursor{ + ID: u.ID, + Value: cv, + } + }, + } +) + +// String implement fmt.Stringer interface. +func (f UserOrderField) String() string { + var str string + switch f.column { + case UserOrderFieldGroupsCount.column: + str = "GROUPS_COUNT" + } + return str +} + +// MarshalGQL implements graphql.Marshaler interface. +func (f UserOrderField) MarshalGQL(w io.Writer) { + io.WriteString(w, strconv.Quote(f.String())) +} + +// UnmarshalGQL implements graphql.Unmarshaler interface. +func (f *UserOrderField) UnmarshalGQL(v interface{}) error { + str, ok := v.(string) + if !ok { + return fmt.Errorf("UserOrderField %T must be a string", v) + } + switch str { + case "GROUPS_COUNT": + *f = *UserOrderFieldGroupsCount + default: + return fmt.Errorf("%s is not a valid UserOrderField", str) + } + return nil +} + +// UserOrderField defines the ordering field of User. +type UserOrderField struct { + // Value extracts the ordering value from the given User. + Value func(*User) (ent.Value, error) + column string // field or computed. + toTerm func(...sql.OrderTermOption) user.OrderOption + toCursor func(*User) Cursor +} + +// UserOrder defines the ordering of User. +type UserOrder struct { + Direction OrderDirection `json:"direction"` + Field *UserOrderField `json:"field"` +} + +// DefaultUserOrder is the default ordering of User. +var DefaultUserOrder = &UserOrder{ + Direction: entgql.OrderDirectionAsc, + Field: &UserOrderField{ + Value: func(u *User) (ent.Value, error) { + return u.ID, nil + }, + column: user.FieldID, + toTerm: user.ByID, + toCursor: func(u *User) Cursor { + return Cursor{ID: u.ID} + }, + }, +} + +// ToEdge converts User into UserEdge. +func (u *User) ToEdge(order *UserOrder) *UserEdge { + if order == nil { + order = DefaultUserOrder + } + return &UserEdge{ + Node: u, + Cursor: order.Field.toCursor(u), + } +} + +// Organization is the type alias for Workspace. +type Organization = Workspace + +// OrganizationEdge is the edge representation of Organization. +type OrganizationEdge struct { + Node *Organization `json:"node"` + Cursor Cursor `json:"cursor"` +} + +// OrganizationConnection is the connection containing edges to Organization. +type OrganizationConnection struct { + Edges []*OrganizationEdge `json:"edges"` + PageInfo PageInfo `json:"pageInfo"` + TotalCount int `json:"totalCount"` +} + +func (c *OrganizationConnection) build(nodes []*Organization, pager *organizationPager, after *Cursor, first *int, before *Cursor, last *int) { + c.PageInfo.HasNextPage = before != nil + c.PageInfo.HasPreviousPage = after != nil + if first != nil && *first+1 == len(nodes) { + c.PageInfo.HasNextPage = true + nodes = nodes[:len(nodes)-1] + } else if last != nil && *last+1 == len(nodes) { + c.PageInfo.HasPreviousPage = true + nodes = nodes[:len(nodes)-1] + } + var nodeAt func(int) *Organization + if last != nil { + n := len(nodes) - 1 + nodeAt = func(i int) *Organization { + return nodes[n-i] + } + } else { + nodeAt = func(i int) *Organization { + return nodes[i] + } + } + c.Edges = make([]*OrganizationEdge, len(nodes)) + for i := range nodes { + node := nodeAt(i) + c.Edges[i] = &OrganizationEdge{ + Node: node, + Cursor: pager.toCursor(node), + } + } + if l := len(c.Edges); l > 0 { + c.PageInfo.StartCursor = &c.Edges[0].Cursor + c.PageInfo.EndCursor = &c.Edges[l-1].Cursor + } + if c.TotalCount == 0 { + c.TotalCount = len(nodes) + } +} + +// OrganizationPaginateOption enables pagination customization. +type OrganizationPaginateOption func(*organizationPager) error + +// WithOrganizationOrder configures pagination ordering. +func WithOrganizationOrder(order *OrganizationOrder) OrganizationPaginateOption { + if order == nil { + order = DefaultOrganizationOrder + } + o := *order + return func(pager *organizationPager) error { + if err := o.Direction.Validate(); err != nil { + return err + } + if o.Field == nil { + o.Field = DefaultOrganizationOrder.Field + } + pager.order = &o + return nil + } +} + +// WithOrganizationFilter configures pagination filter. +func WithOrganizationFilter(filter func(*WorkspaceQuery) (*WorkspaceQuery, error)) OrganizationPaginateOption { + return func(pager *organizationPager) error { + if filter == nil { + return errors.New("WorkspaceQuery filter cannot be nil") + } + pager.filter = filter + return nil + } +} + +type organizationPager struct { + reverse bool + order *OrganizationOrder + filter func(*WorkspaceQuery) (*WorkspaceQuery, error) +} + +func newOrganizationPager(opts []OrganizationPaginateOption, reverse bool) (*organizationPager, error) { + pager := &organizationPager{reverse: reverse} + for _, opt := range opts { + if err := opt(pager); err != nil { + return nil, err + } + } + if pager.order == nil { + pager.order = DefaultOrganizationOrder + } + return pager, nil +} + +func (p *organizationPager) applyFilter(query *WorkspaceQuery) (*WorkspaceQuery, error) { + if p.filter != nil { + return p.filter(query) + } + return query, nil +} + +func (p *organizationPager) toCursor(w *Organization) Cursor { + return p.order.Field.toCursor(w) +} + +func (p *organizationPager) applyCursors(query *WorkspaceQuery, after, before *Cursor) (*WorkspaceQuery, error) { + direction := p.order.Direction + if p.reverse { + direction = direction.Reverse() + } + for _, predicate := range entgql.CursorsPredicate(after, before, DefaultOrganizationOrder.Field.column, p.order.Field.column, direction) { + query = query.Where(predicate) + } + return query, nil +} + +func (p *organizationPager) applyOrder(query *WorkspaceQuery) *WorkspaceQuery { + direction := p.order.Direction + if p.reverse { + direction = direction.Reverse() + } + query = query.Order(p.order.Field.toTerm(direction.OrderTermOption())) + if p.order.Field != DefaultOrganizationOrder.Field { + query = query.Order(DefaultOrganizationOrder.Field.toTerm(direction.OrderTermOption())) + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(p.order.Field.column) + } + return query +} + +func (p *organizationPager) orderExpr(query *WorkspaceQuery) sql.Querier { + direction := p.order.Direction + if p.reverse { + direction = direction.Reverse() + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(p.order.Field.column) + } + return sql.ExprFunc(func(b *sql.Builder) { + b.Ident(p.order.Field.column).Pad().WriteString(string(direction)) + if p.order.Field != DefaultOrganizationOrder.Field { + b.Comma().Ident(DefaultOrganizationOrder.Field.column).Pad().WriteString(string(direction)) + } + }) +} + +// Paginate executes the query and returns a relay based cursor connection to Organization. +func (w *WorkspaceQuery) Paginate( + ctx context.Context, after *Cursor, first *int, + before *Cursor, last *int, opts ...OrganizationPaginateOption, +) (*OrganizationConnection, error) { + if err := validateFirstLast(first, last); err != nil { + return nil, err + } + pager, err := newOrganizationPager(opts, last != nil) + if err != nil { + return nil, err + } + if w, err = pager.applyFilter(w); err != nil { + return nil, err + } + conn := &OrganizationConnection{Edges: []*OrganizationEdge{}} + ignoredEdges := !hasCollectedField(ctx, edgesField) + if hasCollectedField(ctx, totalCountField) || hasCollectedField(ctx, pageInfoField) { + hasPagination := after != nil || first != nil || before != nil || last != nil + if hasPagination || ignoredEdges { + c := w.Clone() + c.ctx.Fields = nil + if conn.TotalCount, err = c.Count(ctx); err != nil { + return nil, err + } + conn.PageInfo.HasNextPage = first != nil && conn.TotalCount > 0 + conn.PageInfo.HasPreviousPage = last != nil && conn.TotalCount > 0 + } + } + if ignoredEdges || (first != nil && *first == 0) || (last != nil && *last == 0) { + return conn, nil + } + if w, err = pager.applyCursors(w, after, before); err != nil { + return nil, err + } + limit := paginateLimit(first, last) + if limit != 0 { + w.Limit(limit) + } + if field := collectedField(ctx, edgesField, nodeField); field != nil { + if err := w.collectField(ctx, limit == 1, graphql.GetOperationContext(ctx), *field, []string{edgesField, nodeField}); err != nil { + return nil, err + } + } + w = pager.applyOrder(w) + nodes, err := w.All(ctx) + if err != nil { + return nil, err + } + conn.build(nodes, pager, after, first, before, last) + return conn, nil +} + +// OrganizationOrderField defines the ordering field of Workspace. +type OrganizationOrderField struct { + // Value extracts the ordering value from the given Workspace. + Value func(*Organization) (ent.Value, error) + column string // field or computed. + toTerm func(...sql.OrderTermOption) workspace.OrderOption + toCursor func(*Organization) Cursor +} + +// OrganizationOrder defines the ordering of Workspace. +type OrganizationOrder struct { + Direction OrderDirection `json:"direction"` + Field *OrganizationOrderField `json:"field"` +} + +// DefaultOrganizationOrder is the default ordering of Workspace. +var DefaultOrganizationOrder = &OrganizationOrder{ + Direction: entgql.OrderDirectionAsc, + Field: &OrganizationOrderField{ + Value: func(w *Organization) (ent.Value, error) { + return w.ID, nil + }, + column: workspace.FieldID, + toTerm: workspace.ByID, + toCursor: func(w *Organization) Cursor { + return Cursor{ID: w.ID} + }, + }, +} + +// ToEdge converts Organization into OrganizationEdge. +func (w *Organization) ToEdge(order *OrganizationOrder) *OrganizationEdge { + if order == nil { + order = DefaultOrganizationOrder + } + return &OrganizationEdge{ + Node: w, + Cursor: order.Field.toCursor(w), + } +} diff --git a/entgql/internal/todoglobalid/ent/gql_transaction.go b/entgql/internal/todoglobalid/ent/gql_transaction.go new file mode 100644 index 000000000..36dd5ed38 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/gql_transaction.go @@ -0,0 +1,44 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "database/sql/driver" + "errors" +) + +// OpenTx opens a transaction and returns a transactional +// context along with the created transaction. +func (c *Client) OpenTx(ctx context.Context) (context.Context, driver.Tx, error) { + tx, err := c.Tx(ctx) + if err != nil { + return nil, nil, err + } + ctx = NewTxContext(ctx, tx) + ctx = NewContext(ctx, tx.Client()) + return ctx, tx, nil +} + +// OpenTxFromContext open transactions from client stored in context. +func OpenTxFromContext(ctx context.Context) (context.Context, driver.Tx, error) { + client := FromContext(ctx) + if client == nil { + return nil, nil, errors.New("no client attached to context") + } + return client.OpenTx(ctx) +} diff --git a/entgql/internal/todoglobalid/ent/gql_where_input.go b/entgql/internal/todoglobalid/ent/gql_where_input.go new file mode 100644 index 000000000..7b1d370a7 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/gql_where_input.go @@ -0,0 +1,2444 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "errors" + "fmt" + "time" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/billproduct" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/category" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/friendship" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/group" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/onetomany" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/project" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/schema/schematype" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/todo" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/user" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/workspace" + "github.com/google/uuid" +) + +// BillProductWhereInput represents a where input for filtering BillProduct queries. +type BillProductWhereInput struct { + Predicates []predicate.BillProduct `json:"-"` + Not *BillProductWhereInput `json:"not,omitempty"` + Or []*BillProductWhereInput `json:"or,omitempty"` + And []*BillProductWhereInput `json:"and,omitempty"` + + // "id" field predicates. + ID *int `json:"id,omitempty"` + IDNEQ *int `json:"idNEQ,omitempty"` + IDIn []int `json:"idIn,omitempty"` + IDNotIn []int `json:"idNotIn,omitempty"` + IDGT *int `json:"idGT,omitempty"` + IDGTE *int `json:"idGTE,omitempty"` + IDLT *int `json:"idLT,omitempty"` + IDLTE *int `json:"idLTE,omitempty"` + + // "name" field predicates. + Name *string `json:"name,omitempty"` + NameNEQ *string `json:"nameNEQ,omitempty"` + NameIn []string `json:"nameIn,omitempty"` + NameNotIn []string `json:"nameNotIn,omitempty"` + NameGT *string `json:"nameGT,omitempty"` + NameGTE *string `json:"nameGTE,omitempty"` + NameLT *string `json:"nameLT,omitempty"` + NameLTE *string `json:"nameLTE,omitempty"` + NameContains *string `json:"nameContains,omitempty"` + NameHasPrefix *string `json:"nameHasPrefix,omitempty"` + NameHasSuffix *string `json:"nameHasSuffix,omitempty"` + NameEqualFold *string `json:"nameEqualFold,omitempty"` + NameContainsFold *string `json:"nameContainsFold,omitempty"` + + // "sku" field predicates. + Sku *string `json:"sku,omitempty"` + SkuNEQ *string `json:"skuNEQ,omitempty"` + SkuIn []string `json:"skuIn,omitempty"` + SkuNotIn []string `json:"skuNotIn,omitempty"` + SkuGT *string `json:"skuGT,omitempty"` + SkuGTE *string `json:"skuGTE,omitempty"` + SkuLT *string `json:"skuLT,omitempty"` + SkuLTE *string `json:"skuLTE,omitempty"` + SkuContains *string `json:"skuContains,omitempty"` + SkuHasPrefix *string `json:"skuHasPrefix,omitempty"` + SkuHasSuffix *string `json:"skuHasSuffix,omitempty"` + SkuEqualFold *string `json:"skuEqualFold,omitempty"` + SkuContainsFold *string `json:"skuContainsFold,omitempty"` + + // "quantity" field predicates. + Quantity *uint64 `json:"quantity,omitempty"` + QuantityNEQ *uint64 `json:"quantityNEQ,omitempty"` + QuantityIn []uint64 `json:"quantityIn,omitempty"` + QuantityNotIn []uint64 `json:"quantityNotIn,omitempty"` + QuantityGT *uint64 `json:"quantityGT,omitempty"` + QuantityGTE *uint64 `json:"quantityGTE,omitempty"` + QuantityLT *uint64 `json:"quantityLT,omitempty"` + QuantityLTE *uint64 `json:"quantityLTE,omitempty"` +} + +// AddPredicates adds custom predicates to the where input to be used during the filtering phase. +func (i *BillProductWhereInput) AddPredicates(predicates ...predicate.BillProduct) { + i.Predicates = append(i.Predicates, predicates...) +} + +// Filter applies the BillProductWhereInput filter on the BillProductQuery builder. +func (i *BillProductWhereInput) Filter(q *BillProductQuery) (*BillProductQuery, error) { + if i == nil { + return q, nil + } + p, err := i.P() + if err != nil { + if err == ErrEmptyBillProductWhereInput { + return q, nil + } + return nil, err + } + return q.Where(p), nil +} + +// ErrEmptyBillProductWhereInput is returned in case the BillProductWhereInput is empty. +var ErrEmptyBillProductWhereInput = errors.New("ent: empty predicate BillProductWhereInput") + +// P returns a predicate for filtering billproducts. +// An error is returned if the input is empty or invalid. +func (i *BillProductWhereInput) P() (predicate.BillProduct, error) { + var predicates []predicate.BillProduct + if i.Not != nil { + p, err := i.Not.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'not'", err) + } + predicates = append(predicates, billproduct.Not(p)) + } + switch n := len(i.Or); { + case n == 1: + p, err := i.Or[0].P() + if err != nil { + return nil, fmt.Errorf("%w: field 'or'", err) + } + predicates = append(predicates, p) + case n > 1: + or := make([]predicate.BillProduct, 0, n) + for _, w := range i.Or { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'or'", err) + } + or = append(or, p) + } + predicates = append(predicates, billproduct.Or(or...)) + } + switch n := len(i.And); { + case n == 1: + p, err := i.And[0].P() + if err != nil { + return nil, fmt.Errorf("%w: field 'and'", err) + } + predicates = append(predicates, p) + case n > 1: + and := make([]predicate.BillProduct, 0, n) + for _, w := range i.And { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'and'", err) + } + and = append(and, p) + } + predicates = append(predicates, billproduct.And(and...)) + } + predicates = append(predicates, i.Predicates...) + if i.ID != nil { + predicates = append(predicates, billproduct.IDEQ(*i.ID)) + } + if i.IDNEQ != nil { + predicates = append(predicates, billproduct.IDNEQ(*i.IDNEQ)) + } + if len(i.IDIn) > 0 { + predicates = append(predicates, billproduct.IDIn(i.IDIn...)) + } + if len(i.IDNotIn) > 0 { + predicates = append(predicates, billproduct.IDNotIn(i.IDNotIn...)) + } + if i.IDGT != nil { + predicates = append(predicates, billproduct.IDGT(*i.IDGT)) + } + if i.IDGTE != nil { + predicates = append(predicates, billproduct.IDGTE(*i.IDGTE)) + } + if i.IDLT != nil { + predicates = append(predicates, billproduct.IDLT(*i.IDLT)) + } + if i.IDLTE != nil { + predicates = append(predicates, billproduct.IDLTE(*i.IDLTE)) + } + if i.Name != nil { + predicates = append(predicates, billproduct.NameEQ(*i.Name)) + } + if i.NameNEQ != nil { + predicates = append(predicates, billproduct.NameNEQ(*i.NameNEQ)) + } + if len(i.NameIn) > 0 { + predicates = append(predicates, billproduct.NameIn(i.NameIn...)) + } + if len(i.NameNotIn) > 0 { + predicates = append(predicates, billproduct.NameNotIn(i.NameNotIn...)) + } + if i.NameGT != nil { + predicates = append(predicates, billproduct.NameGT(*i.NameGT)) + } + if i.NameGTE != nil { + predicates = append(predicates, billproduct.NameGTE(*i.NameGTE)) + } + if i.NameLT != nil { + predicates = append(predicates, billproduct.NameLT(*i.NameLT)) + } + if i.NameLTE != nil { + predicates = append(predicates, billproduct.NameLTE(*i.NameLTE)) + } + if i.NameContains != nil { + predicates = append(predicates, billproduct.NameContains(*i.NameContains)) + } + if i.NameHasPrefix != nil { + predicates = append(predicates, billproduct.NameHasPrefix(*i.NameHasPrefix)) + } + if i.NameHasSuffix != nil { + predicates = append(predicates, billproduct.NameHasSuffix(*i.NameHasSuffix)) + } + if i.NameEqualFold != nil { + predicates = append(predicates, billproduct.NameEqualFold(*i.NameEqualFold)) + } + if i.NameContainsFold != nil { + predicates = append(predicates, billproduct.NameContainsFold(*i.NameContainsFold)) + } + if i.Sku != nil { + predicates = append(predicates, billproduct.SkuEQ(*i.Sku)) + } + if i.SkuNEQ != nil { + predicates = append(predicates, billproduct.SkuNEQ(*i.SkuNEQ)) + } + if len(i.SkuIn) > 0 { + predicates = append(predicates, billproduct.SkuIn(i.SkuIn...)) + } + if len(i.SkuNotIn) > 0 { + predicates = append(predicates, billproduct.SkuNotIn(i.SkuNotIn...)) + } + if i.SkuGT != nil { + predicates = append(predicates, billproduct.SkuGT(*i.SkuGT)) + } + if i.SkuGTE != nil { + predicates = append(predicates, billproduct.SkuGTE(*i.SkuGTE)) + } + if i.SkuLT != nil { + predicates = append(predicates, billproduct.SkuLT(*i.SkuLT)) + } + if i.SkuLTE != nil { + predicates = append(predicates, billproduct.SkuLTE(*i.SkuLTE)) + } + if i.SkuContains != nil { + predicates = append(predicates, billproduct.SkuContains(*i.SkuContains)) + } + if i.SkuHasPrefix != nil { + predicates = append(predicates, billproduct.SkuHasPrefix(*i.SkuHasPrefix)) + } + if i.SkuHasSuffix != nil { + predicates = append(predicates, billproduct.SkuHasSuffix(*i.SkuHasSuffix)) + } + if i.SkuEqualFold != nil { + predicates = append(predicates, billproduct.SkuEqualFold(*i.SkuEqualFold)) + } + if i.SkuContainsFold != nil { + predicates = append(predicates, billproduct.SkuContainsFold(*i.SkuContainsFold)) + } + if i.Quantity != nil { + predicates = append(predicates, billproduct.QuantityEQ(*i.Quantity)) + } + if i.QuantityNEQ != nil { + predicates = append(predicates, billproduct.QuantityNEQ(*i.QuantityNEQ)) + } + if len(i.QuantityIn) > 0 { + predicates = append(predicates, billproduct.QuantityIn(i.QuantityIn...)) + } + if len(i.QuantityNotIn) > 0 { + predicates = append(predicates, billproduct.QuantityNotIn(i.QuantityNotIn...)) + } + if i.QuantityGT != nil { + predicates = append(predicates, billproduct.QuantityGT(*i.QuantityGT)) + } + if i.QuantityGTE != nil { + predicates = append(predicates, billproduct.QuantityGTE(*i.QuantityGTE)) + } + if i.QuantityLT != nil { + predicates = append(predicates, billproduct.QuantityLT(*i.QuantityLT)) + } + if i.QuantityLTE != nil { + predicates = append(predicates, billproduct.QuantityLTE(*i.QuantityLTE)) + } + + switch len(predicates) { + case 0: + return nil, ErrEmptyBillProductWhereInput + case 1: + return predicates[0], nil + default: + return billproduct.And(predicates...), nil + } +} + +// CategoryWhereInput represents a where input for filtering Category queries. +type CategoryWhereInput struct { + Predicates []predicate.Category `json:"-"` + Not *CategoryWhereInput `json:"not,omitempty"` + Or []*CategoryWhereInput `json:"or,omitempty"` + And []*CategoryWhereInput `json:"and,omitempty"` + + // "id" field predicates. + ID *int `json:"id,omitempty"` + IDNEQ *int `json:"idNEQ,omitempty"` + IDIn []int `json:"idIn,omitempty"` + IDNotIn []int `json:"idNotIn,omitempty"` + IDGT *int `json:"idGT,omitempty"` + IDGTE *int `json:"idGTE,omitempty"` + IDLT *int `json:"idLT,omitempty"` + IDLTE *int `json:"idLTE,omitempty"` + + // "text" field predicates. + Text *string `json:"text,omitempty"` + TextNEQ *string `json:"textNEQ,omitempty"` + TextIn []string `json:"textIn,omitempty"` + TextNotIn []string `json:"textNotIn,omitempty"` + TextGT *string `json:"textGT,omitempty"` + TextGTE *string `json:"textGTE,omitempty"` + TextLT *string `json:"textLT,omitempty"` + TextLTE *string `json:"textLTE,omitempty"` + TextContains *string `json:"textContains,omitempty"` + TextHasPrefix *string `json:"textHasPrefix,omitempty"` + TextHasSuffix *string `json:"textHasSuffix,omitempty"` + TextEqualFold *string `json:"textEqualFold,omitempty"` + TextContainsFold *string `json:"textContainsFold,omitempty"` + + // "status" field predicates. + Status *category.Status `json:"status,omitempty"` + StatusNEQ *category.Status `json:"statusNEQ,omitempty"` + StatusIn []category.Status `json:"statusIn,omitempty"` + StatusNotIn []category.Status `json:"statusNotIn,omitempty"` + + // "config" field predicates. + Config *schematype.CategoryConfig `json:"config,omitempty"` + ConfigNEQ *schematype.CategoryConfig `json:"configNEQ,omitempty"` + ConfigIn []*schematype.CategoryConfig `json:"configIn,omitempty"` + ConfigNotIn []*schematype.CategoryConfig `json:"configNotIn,omitempty"` + ConfigGT *schematype.CategoryConfig `json:"configGT,omitempty"` + ConfigGTE *schematype.CategoryConfig `json:"configGTE,omitempty"` + ConfigLT *schematype.CategoryConfig `json:"configLT,omitempty"` + ConfigLTE *schematype.CategoryConfig `json:"configLTE,omitempty"` + ConfigIsNil bool `json:"configIsNil,omitempty"` + ConfigNotNil bool `json:"configNotNil,omitempty"` + + // "duration" field predicates. + Duration *time.Duration `json:"duration,omitempty"` + DurationNEQ *time.Duration `json:"durationNEQ,omitempty"` + DurationIn []time.Duration `json:"durationIn,omitempty"` + DurationNotIn []time.Duration `json:"durationNotIn,omitempty"` + DurationGT *time.Duration `json:"durationGT,omitempty"` + DurationGTE *time.Duration `json:"durationGTE,omitempty"` + DurationLT *time.Duration `json:"durationLT,omitempty"` + DurationLTE *time.Duration `json:"durationLTE,omitempty"` + DurationIsNil bool `json:"durationIsNil,omitempty"` + DurationNotNil bool `json:"durationNotNil,omitempty"` + + // "count" field predicates. + Count *uint64 `json:"count,omitempty"` + CountNEQ *uint64 `json:"countNEQ,omitempty"` + CountIn []uint64 `json:"countIn,omitempty"` + CountNotIn []uint64 `json:"countNotIn,omitempty"` + CountGT *uint64 `json:"countGT,omitempty"` + CountGTE *uint64 `json:"countGTE,omitempty"` + CountLT *uint64 `json:"countLT,omitempty"` + CountLTE *uint64 `json:"countLTE,omitempty"` + CountIsNil bool `json:"countIsNil,omitempty"` + CountNotNil bool `json:"countNotNil,omitempty"` + + // "todos" edge predicates. + HasTodos *bool `json:"hasTodos,omitempty"` + HasTodosWith []*TodoWhereInput `json:"hasTodosWith,omitempty"` + + // "sub_categories" edge predicates. + HasSubCategories *bool `json:"hasSubCategories,omitempty"` + HasSubCategoriesWith []*CategoryWhereInput `json:"hasSubCategoriesWith,omitempty"` +} + +// AddPredicates adds custom predicates to the where input to be used during the filtering phase. +func (i *CategoryWhereInput) AddPredicates(predicates ...predicate.Category) { + i.Predicates = append(i.Predicates, predicates...) +} + +// Filter applies the CategoryWhereInput filter on the CategoryQuery builder. +func (i *CategoryWhereInput) Filter(q *CategoryQuery) (*CategoryQuery, error) { + if i == nil { + return q, nil + } + p, err := i.P() + if err != nil { + if err == ErrEmptyCategoryWhereInput { + return q, nil + } + return nil, err + } + return q.Where(p), nil +} + +// ErrEmptyCategoryWhereInput is returned in case the CategoryWhereInput is empty. +var ErrEmptyCategoryWhereInput = errors.New("ent: empty predicate CategoryWhereInput") + +// P returns a predicate for filtering categories. +// An error is returned if the input is empty or invalid. +func (i *CategoryWhereInput) P() (predicate.Category, error) { + var predicates []predicate.Category + if i.Not != nil { + p, err := i.Not.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'not'", err) + } + predicates = append(predicates, category.Not(p)) + } + switch n := len(i.Or); { + case n == 1: + p, err := i.Or[0].P() + if err != nil { + return nil, fmt.Errorf("%w: field 'or'", err) + } + predicates = append(predicates, p) + case n > 1: + or := make([]predicate.Category, 0, n) + for _, w := range i.Or { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'or'", err) + } + or = append(or, p) + } + predicates = append(predicates, category.Or(or...)) + } + switch n := len(i.And); { + case n == 1: + p, err := i.And[0].P() + if err != nil { + return nil, fmt.Errorf("%w: field 'and'", err) + } + predicates = append(predicates, p) + case n > 1: + and := make([]predicate.Category, 0, n) + for _, w := range i.And { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'and'", err) + } + and = append(and, p) + } + predicates = append(predicates, category.And(and...)) + } + predicates = append(predicates, i.Predicates...) + if i.ID != nil { + predicates = append(predicates, category.IDEQ(*i.ID)) + } + if i.IDNEQ != nil { + predicates = append(predicates, category.IDNEQ(*i.IDNEQ)) + } + if len(i.IDIn) > 0 { + predicates = append(predicates, category.IDIn(i.IDIn...)) + } + if len(i.IDNotIn) > 0 { + predicates = append(predicates, category.IDNotIn(i.IDNotIn...)) + } + if i.IDGT != nil { + predicates = append(predicates, category.IDGT(*i.IDGT)) + } + if i.IDGTE != nil { + predicates = append(predicates, category.IDGTE(*i.IDGTE)) + } + if i.IDLT != nil { + predicates = append(predicates, category.IDLT(*i.IDLT)) + } + if i.IDLTE != nil { + predicates = append(predicates, category.IDLTE(*i.IDLTE)) + } + if i.Text != nil { + predicates = append(predicates, category.TextEQ(*i.Text)) + } + if i.TextNEQ != nil { + predicates = append(predicates, category.TextNEQ(*i.TextNEQ)) + } + if len(i.TextIn) > 0 { + predicates = append(predicates, category.TextIn(i.TextIn...)) + } + if len(i.TextNotIn) > 0 { + predicates = append(predicates, category.TextNotIn(i.TextNotIn...)) + } + if i.TextGT != nil { + predicates = append(predicates, category.TextGT(*i.TextGT)) + } + if i.TextGTE != nil { + predicates = append(predicates, category.TextGTE(*i.TextGTE)) + } + if i.TextLT != nil { + predicates = append(predicates, category.TextLT(*i.TextLT)) + } + if i.TextLTE != nil { + predicates = append(predicates, category.TextLTE(*i.TextLTE)) + } + if i.TextContains != nil { + predicates = append(predicates, category.TextContains(*i.TextContains)) + } + if i.TextHasPrefix != nil { + predicates = append(predicates, category.TextHasPrefix(*i.TextHasPrefix)) + } + if i.TextHasSuffix != nil { + predicates = append(predicates, category.TextHasSuffix(*i.TextHasSuffix)) + } + if i.TextEqualFold != nil { + predicates = append(predicates, category.TextEqualFold(*i.TextEqualFold)) + } + if i.TextContainsFold != nil { + predicates = append(predicates, category.TextContainsFold(*i.TextContainsFold)) + } + if i.Status != nil { + predicates = append(predicates, category.StatusEQ(*i.Status)) + } + if i.StatusNEQ != nil { + predicates = append(predicates, category.StatusNEQ(*i.StatusNEQ)) + } + if len(i.StatusIn) > 0 { + predicates = append(predicates, category.StatusIn(i.StatusIn...)) + } + if len(i.StatusNotIn) > 0 { + predicates = append(predicates, category.StatusNotIn(i.StatusNotIn...)) + } + if i.Config != nil { + predicates = append(predicates, category.ConfigEQ(i.Config)) + } + if i.ConfigNEQ != nil { + predicates = append(predicates, category.ConfigNEQ(i.ConfigNEQ)) + } + if len(i.ConfigIn) > 0 { + predicates = append(predicates, category.ConfigIn(i.ConfigIn...)) + } + if len(i.ConfigNotIn) > 0 { + predicates = append(predicates, category.ConfigNotIn(i.ConfigNotIn...)) + } + if i.ConfigGT != nil { + predicates = append(predicates, category.ConfigGT(i.ConfigGT)) + } + if i.ConfigGTE != nil { + predicates = append(predicates, category.ConfigGTE(i.ConfigGTE)) + } + if i.ConfigLT != nil { + predicates = append(predicates, category.ConfigLT(i.ConfigLT)) + } + if i.ConfigLTE != nil { + predicates = append(predicates, category.ConfigLTE(i.ConfigLTE)) + } + if i.ConfigIsNil { + predicates = append(predicates, category.ConfigIsNil()) + } + if i.ConfigNotNil { + predicates = append(predicates, category.ConfigNotNil()) + } + if i.Duration != nil { + predicates = append(predicates, category.DurationEQ(*i.Duration)) + } + if i.DurationNEQ != nil { + predicates = append(predicates, category.DurationNEQ(*i.DurationNEQ)) + } + if len(i.DurationIn) > 0 { + predicates = append(predicates, category.DurationIn(i.DurationIn...)) + } + if len(i.DurationNotIn) > 0 { + predicates = append(predicates, category.DurationNotIn(i.DurationNotIn...)) + } + if i.DurationGT != nil { + predicates = append(predicates, category.DurationGT(*i.DurationGT)) + } + if i.DurationGTE != nil { + predicates = append(predicates, category.DurationGTE(*i.DurationGTE)) + } + if i.DurationLT != nil { + predicates = append(predicates, category.DurationLT(*i.DurationLT)) + } + if i.DurationLTE != nil { + predicates = append(predicates, category.DurationLTE(*i.DurationLTE)) + } + if i.DurationIsNil { + predicates = append(predicates, category.DurationIsNil()) + } + if i.DurationNotNil { + predicates = append(predicates, category.DurationNotNil()) + } + if i.Count != nil { + predicates = append(predicates, category.CountEQ(*i.Count)) + } + if i.CountNEQ != nil { + predicates = append(predicates, category.CountNEQ(*i.CountNEQ)) + } + if len(i.CountIn) > 0 { + predicates = append(predicates, category.CountIn(i.CountIn...)) + } + if len(i.CountNotIn) > 0 { + predicates = append(predicates, category.CountNotIn(i.CountNotIn...)) + } + if i.CountGT != nil { + predicates = append(predicates, category.CountGT(*i.CountGT)) + } + if i.CountGTE != nil { + predicates = append(predicates, category.CountGTE(*i.CountGTE)) + } + if i.CountLT != nil { + predicates = append(predicates, category.CountLT(*i.CountLT)) + } + if i.CountLTE != nil { + predicates = append(predicates, category.CountLTE(*i.CountLTE)) + } + if i.CountIsNil { + predicates = append(predicates, category.CountIsNil()) + } + if i.CountNotNil { + predicates = append(predicates, category.CountNotNil()) + } + + if i.HasTodos != nil { + p := category.HasTodos() + if !*i.HasTodos { + p = category.Not(p) + } + predicates = append(predicates, p) + } + if len(i.HasTodosWith) > 0 { + with := make([]predicate.Todo, 0, len(i.HasTodosWith)) + for _, w := range i.HasTodosWith { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'HasTodosWith'", err) + } + with = append(with, p) + } + predicates = append(predicates, category.HasTodosWith(with...)) + } + if i.HasSubCategories != nil { + p := category.HasSubCategories() + if !*i.HasSubCategories { + p = category.Not(p) + } + predicates = append(predicates, p) + } + if len(i.HasSubCategoriesWith) > 0 { + with := make([]predicate.Category, 0, len(i.HasSubCategoriesWith)) + for _, w := range i.HasSubCategoriesWith { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'HasSubCategoriesWith'", err) + } + with = append(with, p) + } + predicates = append(predicates, category.HasSubCategoriesWith(with...)) + } + switch len(predicates) { + case 0: + return nil, ErrEmptyCategoryWhereInput + case 1: + return predicates[0], nil + default: + return category.And(predicates...), nil + } +} + +// FriendshipWhereInput represents a where input for filtering Friendship queries. +type FriendshipWhereInput struct { + Predicates []predicate.Friendship `json:"-"` + Not *FriendshipWhereInput `json:"not,omitempty"` + Or []*FriendshipWhereInput `json:"or,omitempty"` + And []*FriendshipWhereInput `json:"and,omitempty"` + + // "id" field predicates. + ID *int `json:"id,omitempty"` + IDNEQ *int `json:"idNEQ,omitempty"` + IDIn []int `json:"idIn,omitempty"` + IDNotIn []int `json:"idNotIn,omitempty"` + IDGT *int `json:"idGT,omitempty"` + IDGTE *int `json:"idGTE,omitempty"` + IDLT *int `json:"idLT,omitempty"` + IDLTE *int `json:"idLTE,omitempty"` + + // "created_at" field predicates. + CreatedAt *time.Time `json:"createdAt,omitempty"` + CreatedAtNEQ *time.Time `json:"createdAtNEQ,omitempty"` + CreatedAtIn []time.Time `json:"createdAtIn,omitempty"` + CreatedAtNotIn []time.Time `json:"createdAtNotIn,omitempty"` + CreatedAtGT *time.Time `json:"createdAtGT,omitempty"` + CreatedAtGTE *time.Time `json:"createdAtGTE,omitempty"` + CreatedAtLT *time.Time `json:"createdAtLT,omitempty"` + CreatedAtLTE *time.Time `json:"createdAtLTE,omitempty"` + + // "user_id" field predicates. + UserID *int `json:"userID,omitempty"` + UserIDNEQ *int `json:"userIDNEQ,omitempty"` + UserIDIn []int `json:"userIDIn,omitempty"` + UserIDNotIn []int `json:"userIDNotIn,omitempty"` + + // "friend_id" field predicates. + FriendID *int `json:"friendID,omitempty"` + FriendIDNEQ *int `json:"friendIDNEQ,omitempty"` + FriendIDIn []int `json:"friendIDIn,omitempty"` + FriendIDNotIn []int `json:"friendIDNotIn,omitempty"` + + // "user" edge predicates. + HasUser *bool `json:"hasUser,omitempty"` + HasUserWith []*UserWhereInput `json:"hasUserWith,omitempty"` + + // "friend" edge predicates. + HasFriend *bool `json:"hasFriend,omitempty"` + HasFriendWith []*UserWhereInput `json:"hasFriendWith,omitempty"` +} + +// AddPredicates adds custom predicates to the where input to be used during the filtering phase. +func (i *FriendshipWhereInput) AddPredicates(predicates ...predicate.Friendship) { + i.Predicates = append(i.Predicates, predicates...) +} + +// Filter applies the FriendshipWhereInput filter on the FriendshipQuery builder. +func (i *FriendshipWhereInput) Filter(q *FriendshipQuery) (*FriendshipQuery, error) { + if i == nil { + return q, nil + } + p, err := i.P() + if err != nil { + if err == ErrEmptyFriendshipWhereInput { + return q, nil + } + return nil, err + } + return q.Where(p), nil +} + +// ErrEmptyFriendshipWhereInput is returned in case the FriendshipWhereInput is empty. +var ErrEmptyFriendshipWhereInput = errors.New("ent: empty predicate FriendshipWhereInput") + +// P returns a predicate for filtering friendships. +// An error is returned if the input is empty or invalid. +func (i *FriendshipWhereInput) P() (predicate.Friendship, error) { + var predicates []predicate.Friendship + if i.Not != nil { + p, err := i.Not.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'not'", err) + } + predicates = append(predicates, friendship.Not(p)) + } + switch n := len(i.Or); { + case n == 1: + p, err := i.Or[0].P() + if err != nil { + return nil, fmt.Errorf("%w: field 'or'", err) + } + predicates = append(predicates, p) + case n > 1: + or := make([]predicate.Friendship, 0, n) + for _, w := range i.Or { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'or'", err) + } + or = append(or, p) + } + predicates = append(predicates, friendship.Or(or...)) + } + switch n := len(i.And); { + case n == 1: + p, err := i.And[0].P() + if err != nil { + return nil, fmt.Errorf("%w: field 'and'", err) + } + predicates = append(predicates, p) + case n > 1: + and := make([]predicate.Friendship, 0, n) + for _, w := range i.And { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'and'", err) + } + and = append(and, p) + } + predicates = append(predicates, friendship.And(and...)) + } + predicates = append(predicates, i.Predicates...) + if i.ID != nil { + predicates = append(predicates, friendship.IDEQ(*i.ID)) + } + if i.IDNEQ != nil { + predicates = append(predicates, friendship.IDNEQ(*i.IDNEQ)) + } + if len(i.IDIn) > 0 { + predicates = append(predicates, friendship.IDIn(i.IDIn...)) + } + if len(i.IDNotIn) > 0 { + predicates = append(predicates, friendship.IDNotIn(i.IDNotIn...)) + } + if i.IDGT != nil { + predicates = append(predicates, friendship.IDGT(*i.IDGT)) + } + if i.IDGTE != nil { + predicates = append(predicates, friendship.IDGTE(*i.IDGTE)) + } + if i.IDLT != nil { + predicates = append(predicates, friendship.IDLT(*i.IDLT)) + } + if i.IDLTE != nil { + predicates = append(predicates, friendship.IDLTE(*i.IDLTE)) + } + if i.CreatedAt != nil { + predicates = append(predicates, friendship.CreatedAtEQ(*i.CreatedAt)) + } + if i.CreatedAtNEQ != nil { + predicates = append(predicates, friendship.CreatedAtNEQ(*i.CreatedAtNEQ)) + } + if len(i.CreatedAtIn) > 0 { + predicates = append(predicates, friendship.CreatedAtIn(i.CreatedAtIn...)) + } + if len(i.CreatedAtNotIn) > 0 { + predicates = append(predicates, friendship.CreatedAtNotIn(i.CreatedAtNotIn...)) + } + if i.CreatedAtGT != nil { + predicates = append(predicates, friendship.CreatedAtGT(*i.CreatedAtGT)) + } + if i.CreatedAtGTE != nil { + predicates = append(predicates, friendship.CreatedAtGTE(*i.CreatedAtGTE)) + } + if i.CreatedAtLT != nil { + predicates = append(predicates, friendship.CreatedAtLT(*i.CreatedAtLT)) + } + if i.CreatedAtLTE != nil { + predicates = append(predicates, friendship.CreatedAtLTE(*i.CreatedAtLTE)) + } + if i.UserID != nil { + predicates = append(predicates, friendship.UserIDEQ(*i.UserID)) + } + if i.UserIDNEQ != nil { + predicates = append(predicates, friendship.UserIDNEQ(*i.UserIDNEQ)) + } + if len(i.UserIDIn) > 0 { + predicates = append(predicates, friendship.UserIDIn(i.UserIDIn...)) + } + if len(i.UserIDNotIn) > 0 { + predicates = append(predicates, friendship.UserIDNotIn(i.UserIDNotIn...)) + } + if i.FriendID != nil { + predicates = append(predicates, friendship.FriendIDEQ(*i.FriendID)) + } + if i.FriendIDNEQ != nil { + predicates = append(predicates, friendship.FriendIDNEQ(*i.FriendIDNEQ)) + } + if len(i.FriendIDIn) > 0 { + predicates = append(predicates, friendship.FriendIDIn(i.FriendIDIn...)) + } + if len(i.FriendIDNotIn) > 0 { + predicates = append(predicates, friendship.FriendIDNotIn(i.FriendIDNotIn...)) + } + + if i.HasUser != nil { + p := friendship.HasUser() + if !*i.HasUser { + p = friendship.Not(p) + } + predicates = append(predicates, p) + } + if len(i.HasUserWith) > 0 { + with := make([]predicate.User, 0, len(i.HasUserWith)) + for _, w := range i.HasUserWith { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'HasUserWith'", err) + } + with = append(with, p) + } + predicates = append(predicates, friendship.HasUserWith(with...)) + } + if i.HasFriend != nil { + p := friendship.HasFriend() + if !*i.HasFriend { + p = friendship.Not(p) + } + predicates = append(predicates, p) + } + if len(i.HasFriendWith) > 0 { + with := make([]predicate.User, 0, len(i.HasFriendWith)) + for _, w := range i.HasFriendWith { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'HasFriendWith'", err) + } + with = append(with, p) + } + predicates = append(predicates, friendship.HasFriendWith(with...)) + } + switch len(predicates) { + case 0: + return nil, ErrEmptyFriendshipWhereInput + case 1: + return predicates[0], nil + default: + return friendship.And(predicates...), nil + } +} + +// GroupWhereInput represents a where input for filtering Group queries. +type GroupWhereInput struct { + Predicates []predicate.Group `json:"-"` + Not *GroupWhereInput `json:"not,omitempty"` + Or []*GroupWhereInput `json:"or,omitempty"` + And []*GroupWhereInput `json:"and,omitempty"` + + // "id" field predicates. + ID *int `json:"id,omitempty"` + IDNEQ *int `json:"idNEQ,omitempty"` + IDIn []int `json:"idIn,omitempty"` + IDNotIn []int `json:"idNotIn,omitempty"` + IDGT *int `json:"idGT,omitempty"` + IDGTE *int `json:"idGTE,omitempty"` + IDLT *int `json:"idLT,omitempty"` + IDLTE *int `json:"idLTE,omitempty"` + + // "name" field predicates. + Name *string `json:"name,omitempty"` + NameNEQ *string `json:"nameNEQ,omitempty"` + NameIn []string `json:"nameIn,omitempty"` + NameNotIn []string `json:"nameNotIn,omitempty"` + NameGT *string `json:"nameGT,omitempty"` + NameGTE *string `json:"nameGTE,omitempty"` + NameLT *string `json:"nameLT,omitempty"` + NameLTE *string `json:"nameLTE,omitempty"` + NameContains *string `json:"nameContains,omitempty"` + NameHasPrefix *string `json:"nameHasPrefix,omitempty"` + NameHasSuffix *string `json:"nameHasSuffix,omitempty"` + NameEqualFold *string `json:"nameEqualFold,omitempty"` + NameContainsFold *string `json:"nameContainsFold,omitempty"` + + // "users" edge predicates. + HasUsers *bool `json:"hasUsers,omitempty"` + HasUsersWith []*UserWhereInput `json:"hasUsersWith,omitempty"` +} + +// AddPredicates adds custom predicates to the where input to be used during the filtering phase. +func (i *GroupWhereInput) AddPredicates(predicates ...predicate.Group) { + i.Predicates = append(i.Predicates, predicates...) +} + +// Filter applies the GroupWhereInput filter on the GroupQuery builder. +func (i *GroupWhereInput) Filter(q *GroupQuery) (*GroupQuery, error) { + if i == nil { + return q, nil + } + p, err := i.P() + if err != nil { + if err == ErrEmptyGroupWhereInput { + return q, nil + } + return nil, err + } + return q.Where(p), nil +} + +// ErrEmptyGroupWhereInput is returned in case the GroupWhereInput is empty. +var ErrEmptyGroupWhereInput = errors.New("ent: empty predicate GroupWhereInput") + +// P returns a predicate for filtering groups. +// An error is returned if the input is empty or invalid. +func (i *GroupWhereInput) P() (predicate.Group, error) { + var predicates []predicate.Group + if i.Not != nil { + p, err := i.Not.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'not'", err) + } + predicates = append(predicates, group.Not(p)) + } + switch n := len(i.Or); { + case n == 1: + p, err := i.Or[0].P() + if err != nil { + return nil, fmt.Errorf("%w: field 'or'", err) + } + predicates = append(predicates, p) + case n > 1: + or := make([]predicate.Group, 0, n) + for _, w := range i.Or { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'or'", err) + } + or = append(or, p) + } + predicates = append(predicates, group.Or(or...)) + } + switch n := len(i.And); { + case n == 1: + p, err := i.And[0].P() + if err != nil { + return nil, fmt.Errorf("%w: field 'and'", err) + } + predicates = append(predicates, p) + case n > 1: + and := make([]predicate.Group, 0, n) + for _, w := range i.And { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'and'", err) + } + and = append(and, p) + } + predicates = append(predicates, group.And(and...)) + } + predicates = append(predicates, i.Predicates...) + if i.ID != nil { + predicates = append(predicates, group.IDEQ(*i.ID)) + } + if i.IDNEQ != nil { + predicates = append(predicates, group.IDNEQ(*i.IDNEQ)) + } + if len(i.IDIn) > 0 { + predicates = append(predicates, group.IDIn(i.IDIn...)) + } + if len(i.IDNotIn) > 0 { + predicates = append(predicates, group.IDNotIn(i.IDNotIn...)) + } + if i.IDGT != nil { + predicates = append(predicates, group.IDGT(*i.IDGT)) + } + if i.IDGTE != nil { + predicates = append(predicates, group.IDGTE(*i.IDGTE)) + } + if i.IDLT != nil { + predicates = append(predicates, group.IDLT(*i.IDLT)) + } + if i.IDLTE != nil { + predicates = append(predicates, group.IDLTE(*i.IDLTE)) + } + if i.Name != nil { + predicates = append(predicates, group.NameEQ(*i.Name)) + } + if i.NameNEQ != nil { + predicates = append(predicates, group.NameNEQ(*i.NameNEQ)) + } + if len(i.NameIn) > 0 { + predicates = append(predicates, group.NameIn(i.NameIn...)) + } + if len(i.NameNotIn) > 0 { + predicates = append(predicates, group.NameNotIn(i.NameNotIn...)) + } + if i.NameGT != nil { + predicates = append(predicates, group.NameGT(*i.NameGT)) + } + if i.NameGTE != nil { + predicates = append(predicates, group.NameGTE(*i.NameGTE)) + } + if i.NameLT != nil { + predicates = append(predicates, group.NameLT(*i.NameLT)) + } + if i.NameLTE != nil { + predicates = append(predicates, group.NameLTE(*i.NameLTE)) + } + if i.NameContains != nil { + predicates = append(predicates, group.NameContains(*i.NameContains)) + } + if i.NameHasPrefix != nil { + predicates = append(predicates, group.NameHasPrefix(*i.NameHasPrefix)) + } + if i.NameHasSuffix != nil { + predicates = append(predicates, group.NameHasSuffix(*i.NameHasSuffix)) + } + if i.NameEqualFold != nil { + predicates = append(predicates, group.NameEqualFold(*i.NameEqualFold)) + } + if i.NameContainsFold != nil { + predicates = append(predicates, group.NameContainsFold(*i.NameContainsFold)) + } + + if i.HasUsers != nil { + p := group.HasUsers() + if !*i.HasUsers { + p = group.Not(p) + } + predicates = append(predicates, p) + } + if len(i.HasUsersWith) > 0 { + with := make([]predicate.User, 0, len(i.HasUsersWith)) + for _, w := range i.HasUsersWith { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'HasUsersWith'", err) + } + with = append(with, p) + } + predicates = append(predicates, group.HasUsersWith(with...)) + } + switch len(predicates) { + case 0: + return nil, ErrEmptyGroupWhereInput + case 1: + return predicates[0], nil + default: + return group.And(predicates...), nil + } +} + +// OneToManyWhereInput represents a where input for filtering OneToMany queries. +type OneToManyWhereInput struct { + Predicates []predicate.OneToMany `json:"-"` + Not *OneToManyWhereInput `json:"not,omitempty"` + Or []*OneToManyWhereInput `json:"or,omitempty"` + And []*OneToManyWhereInput `json:"and,omitempty"` + + // "id" field predicates. + ID *int `json:"id,omitempty"` + IDNEQ *int `json:"idNEQ,omitempty"` + IDIn []int `json:"idIn,omitempty"` + IDNotIn []int `json:"idNotIn,omitempty"` + IDGT *int `json:"idGT,omitempty"` + IDGTE *int `json:"idGTE,omitempty"` + IDLT *int `json:"idLT,omitempty"` + IDLTE *int `json:"idLTE,omitempty"` + + // "name" field predicates. + Name *string `json:"name,omitempty"` + NameNEQ *string `json:"nameNEQ,omitempty"` + NameIn []string `json:"nameIn,omitempty"` + NameNotIn []string `json:"nameNotIn,omitempty"` + NameGT *string `json:"nameGT,omitempty"` + NameGTE *string `json:"nameGTE,omitempty"` + NameLT *string `json:"nameLT,omitempty"` + NameLTE *string `json:"nameLTE,omitempty"` + NameContains *string `json:"nameContains,omitempty"` + NameHasPrefix *string `json:"nameHasPrefix,omitempty"` + NameHasSuffix *string `json:"nameHasSuffix,omitempty"` + NameEqualFold *string `json:"nameEqualFold,omitempty"` + NameContainsFold *string `json:"nameContainsFold,omitempty"` + + // "field2" field predicates. + Field2 *string `json:"field2,omitempty"` + Field2NEQ *string `json:"field2NEQ,omitempty"` + Field2In []string `json:"field2In,omitempty"` + Field2NotIn []string `json:"field2NotIn,omitempty"` + Field2GT *string `json:"field2GT,omitempty"` + Field2GTE *string `json:"field2GTE,omitempty"` + Field2LT *string `json:"field2LT,omitempty"` + Field2LTE *string `json:"field2LTE,omitempty"` + Field2Contains *string `json:"field2Contains,omitempty"` + Field2HasPrefix *string `json:"field2HasPrefix,omitempty"` + Field2HasSuffix *string `json:"field2HasSuffix,omitempty"` + Field2IsNil bool `json:"field2IsNil,omitempty"` + Field2NotNil bool `json:"field2NotNil,omitempty"` + Field2EqualFold *string `json:"field2EqualFold,omitempty"` + Field2ContainsFold *string `json:"field2ContainsFold,omitempty"` + + // "parent" edge predicates. + HasParent *bool `json:"hasParent,omitempty"` + HasParentWith []*OneToManyWhereInput `json:"hasParentWith,omitempty"` + + // "children" edge predicates. + HasChildren *bool `json:"hasChildren,omitempty"` + HasChildrenWith []*OneToManyWhereInput `json:"hasChildrenWith,omitempty"` +} + +// AddPredicates adds custom predicates to the where input to be used during the filtering phase. +func (i *OneToManyWhereInput) AddPredicates(predicates ...predicate.OneToMany) { + i.Predicates = append(i.Predicates, predicates...) +} + +// Filter applies the OneToManyWhereInput filter on the OneToManyQuery builder. +func (i *OneToManyWhereInput) Filter(q *OneToManyQuery) (*OneToManyQuery, error) { + if i == nil { + return q, nil + } + p, err := i.P() + if err != nil { + if err == ErrEmptyOneToManyWhereInput { + return q, nil + } + return nil, err + } + return q.Where(p), nil +} + +// ErrEmptyOneToManyWhereInput is returned in case the OneToManyWhereInput is empty. +var ErrEmptyOneToManyWhereInput = errors.New("ent: empty predicate OneToManyWhereInput") + +// P returns a predicate for filtering onetomanies. +// An error is returned if the input is empty or invalid. +func (i *OneToManyWhereInput) P() (predicate.OneToMany, error) { + var predicates []predicate.OneToMany + if i.Not != nil { + p, err := i.Not.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'not'", err) + } + predicates = append(predicates, onetomany.Not(p)) + } + switch n := len(i.Or); { + case n == 1: + p, err := i.Or[0].P() + if err != nil { + return nil, fmt.Errorf("%w: field 'or'", err) + } + predicates = append(predicates, p) + case n > 1: + or := make([]predicate.OneToMany, 0, n) + for _, w := range i.Or { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'or'", err) + } + or = append(or, p) + } + predicates = append(predicates, onetomany.Or(or...)) + } + switch n := len(i.And); { + case n == 1: + p, err := i.And[0].P() + if err != nil { + return nil, fmt.Errorf("%w: field 'and'", err) + } + predicates = append(predicates, p) + case n > 1: + and := make([]predicate.OneToMany, 0, n) + for _, w := range i.And { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'and'", err) + } + and = append(and, p) + } + predicates = append(predicates, onetomany.And(and...)) + } + predicates = append(predicates, i.Predicates...) + if i.ID != nil { + predicates = append(predicates, onetomany.IDEQ(*i.ID)) + } + if i.IDNEQ != nil { + predicates = append(predicates, onetomany.IDNEQ(*i.IDNEQ)) + } + if len(i.IDIn) > 0 { + predicates = append(predicates, onetomany.IDIn(i.IDIn...)) + } + if len(i.IDNotIn) > 0 { + predicates = append(predicates, onetomany.IDNotIn(i.IDNotIn...)) + } + if i.IDGT != nil { + predicates = append(predicates, onetomany.IDGT(*i.IDGT)) + } + if i.IDGTE != nil { + predicates = append(predicates, onetomany.IDGTE(*i.IDGTE)) + } + if i.IDLT != nil { + predicates = append(predicates, onetomany.IDLT(*i.IDLT)) + } + if i.IDLTE != nil { + predicates = append(predicates, onetomany.IDLTE(*i.IDLTE)) + } + if i.Name != nil { + predicates = append(predicates, onetomany.NameEQ(*i.Name)) + } + if i.NameNEQ != nil { + predicates = append(predicates, onetomany.NameNEQ(*i.NameNEQ)) + } + if len(i.NameIn) > 0 { + predicates = append(predicates, onetomany.NameIn(i.NameIn...)) + } + if len(i.NameNotIn) > 0 { + predicates = append(predicates, onetomany.NameNotIn(i.NameNotIn...)) + } + if i.NameGT != nil { + predicates = append(predicates, onetomany.NameGT(*i.NameGT)) + } + if i.NameGTE != nil { + predicates = append(predicates, onetomany.NameGTE(*i.NameGTE)) + } + if i.NameLT != nil { + predicates = append(predicates, onetomany.NameLT(*i.NameLT)) + } + if i.NameLTE != nil { + predicates = append(predicates, onetomany.NameLTE(*i.NameLTE)) + } + if i.NameContains != nil { + predicates = append(predicates, onetomany.NameContains(*i.NameContains)) + } + if i.NameHasPrefix != nil { + predicates = append(predicates, onetomany.NameHasPrefix(*i.NameHasPrefix)) + } + if i.NameHasSuffix != nil { + predicates = append(predicates, onetomany.NameHasSuffix(*i.NameHasSuffix)) + } + if i.NameEqualFold != nil { + predicates = append(predicates, onetomany.NameEqualFold(*i.NameEqualFold)) + } + if i.NameContainsFold != nil { + predicates = append(predicates, onetomany.NameContainsFold(*i.NameContainsFold)) + } + if i.Field2 != nil { + predicates = append(predicates, onetomany.Field2EQ(*i.Field2)) + } + if i.Field2NEQ != nil { + predicates = append(predicates, onetomany.Field2NEQ(*i.Field2NEQ)) + } + if len(i.Field2In) > 0 { + predicates = append(predicates, onetomany.Field2In(i.Field2In...)) + } + if len(i.Field2NotIn) > 0 { + predicates = append(predicates, onetomany.Field2NotIn(i.Field2NotIn...)) + } + if i.Field2GT != nil { + predicates = append(predicates, onetomany.Field2GT(*i.Field2GT)) + } + if i.Field2GTE != nil { + predicates = append(predicates, onetomany.Field2GTE(*i.Field2GTE)) + } + if i.Field2LT != nil { + predicates = append(predicates, onetomany.Field2LT(*i.Field2LT)) + } + if i.Field2LTE != nil { + predicates = append(predicates, onetomany.Field2LTE(*i.Field2LTE)) + } + if i.Field2Contains != nil { + predicates = append(predicates, onetomany.Field2Contains(*i.Field2Contains)) + } + if i.Field2HasPrefix != nil { + predicates = append(predicates, onetomany.Field2HasPrefix(*i.Field2HasPrefix)) + } + if i.Field2HasSuffix != nil { + predicates = append(predicates, onetomany.Field2HasSuffix(*i.Field2HasSuffix)) + } + if i.Field2IsNil { + predicates = append(predicates, onetomany.Field2IsNil()) + } + if i.Field2NotNil { + predicates = append(predicates, onetomany.Field2NotNil()) + } + if i.Field2EqualFold != nil { + predicates = append(predicates, onetomany.Field2EqualFold(*i.Field2EqualFold)) + } + if i.Field2ContainsFold != nil { + predicates = append(predicates, onetomany.Field2ContainsFold(*i.Field2ContainsFold)) + } + + if i.HasParent != nil { + p := onetomany.HasParent() + if !*i.HasParent { + p = onetomany.Not(p) + } + predicates = append(predicates, p) + } + if len(i.HasParentWith) > 0 { + with := make([]predicate.OneToMany, 0, len(i.HasParentWith)) + for _, w := range i.HasParentWith { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'HasParentWith'", err) + } + with = append(with, p) + } + predicates = append(predicates, onetomany.HasParentWith(with...)) + } + if i.HasChildren != nil { + p := onetomany.HasChildren() + if !*i.HasChildren { + p = onetomany.Not(p) + } + predicates = append(predicates, p) + } + if len(i.HasChildrenWith) > 0 { + with := make([]predicate.OneToMany, 0, len(i.HasChildrenWith)) + for _, w := range i.HasChildrenWith { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'HasChildrenWith'", err) + } + with = append(with, p) + } + predicates = append(predicates, onetomany.HasChildrenWith(with...)) + } + switch len(predicates) { + case 0: + return nil, ErrEmptyOneToManyWhereInput + case 1: + return predicates[0], nil + default: + return onetomany.And(predicates...), nil + } +} + +// ProjectWhereInput represents a where input for filtering Project queries. +type ProjectWhereInput struct { + Predicates []predicate.Project `json:"-"` + Not *ProjectWhereInput `json:"not,omitempty"` + Or []*ProjectWhereInput `json:"or,omitempty"` + And []*ProjectWhereInput `json:"and,omitempty"` + + // "id" field predicates. + ID *int `json:"id,omitempty"` + IDNEQ *int `json:"idNEQ,omitempty"` + IDIn []int `json:"idIn,omitempty"` + IDNotIn []int `json:"idNotIn,omitempty"` + IDGT *int `json:"idGT,omitempty"` + IDGTE *int `json:"idGTE,omitempty"` + IDLT *int `json:"idLT,omitempty"` + IDLTE *int `json:"idLTE,omitempty"` + + // "todos" edge predicates. + HasTodos *bool `json:"hasTodos,omitempty"` + HasTodosWith []*TodoWhereInput `json:"hasTodosWith,omitempty"` +} + +// AddPredicates adds custom predicates to the where input to be used during the filtering phase. +func (i *ProjectWhereInput) AddPredicates(predicates ...predicate.Project) { + i.Predicates = append(i.Predicates, predicates...) +} + +// Filter applies the ProjectWhereInput filter on the ProjectQuery builder. +func (i *ProjectWhereInput) Filter(q *ProjectQuery) (*ProjectQuery, error) { + if i == nil { + return q, nil + } + p, err := i.P() + if err != nil { + if err == ErrEmptyProjectWhereInput { + return q, nil + } + return nil, err + } + return q.Where(p), nil +} + +// ErrEmptyProjectWhereInput is returned in case the ProjectWhereInput is empty. +var ErrEmptyProjectWhereInput = errors.New("ent: empty predicate ProjectWhereInput") + +// P returns a predicate for filtering projects. +// An error is returned if the input is empty or invalid. +func (i *ProjectWhereInput) P() (predicate.Project, error) { + var predicates []predicate.Project + if i.Not != nil { + p, err := i.Not.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'not'", err) + } + predicates = append(predicates, project.Not(p)) + } + switch n := len(i.Or); { + case n == 1: + p, err := i.Or[0].P() + if err != nil { + return nil, fmt.Errorf("%w: field 'or'", err) + } + predicates = append(predicates, p) + case n > 1: + or := make([]predicate.Project, 0, n) + for _, w := range i.Or { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'or'", err) + } + or = append(or, p) + } + predicates = append(predicates, project.Or(or...)) + } + switch n := len(i.And); { + case n == 1: + p, err := i.And[0].P() + if err != nil { + return nil, fmt.Errorf("%w: field 'and'", err) + } + predicates = append(predicates, p) + case n > 1: + and := make([]predicate.Project, 0, n) + for _, w := range i.And { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'and'", err) + } + and = append(and, p) + } + predicates = append(predicates, project.And(and...)) + } + predicates = append(predicates, i.Predicates...) + if i.ID != nil { + predicates = append(predicates, project.IDEQ(*i.ID)) + } + if i.IDNEQ != nil { + predicates = append(predicates, project.IDNEQ(*i.IDNEQ)) + } + if len(i.IDIn) > 0 { + predicates = append(predicates, project.IDIn(i.IDIn...)) + } + if len(i.IDNotIn) > 0 { + predicates = append(predicates, project.IDNotIn(i.IDNotIn...)) + } + if i.IDGT != nil { + predicates = append(predicates, project.IDGT(*i.IDGT)) + } + if i.IDGTE != nil { + predicates = append(predicates, project.IDGTE(*i.IDGTE)) + } + if i.IDLT != nil { + predicates = append(predicates, project.IDLT(*i.IDLT)) + } + if i.IDLTE != nil { + predicates = append(predicates, project.IDLTE(*i.IDLTE)) + } + + if i.HasTodos != nil { + p := project.HasTodos() + if !*i.HasTodos { + p = project.Not(p) + } + predicates = append(predicates, p) + } + if len(i.HasTodosWith) > 0 { + with := make([]predicate.Todo, 0, len(i.HasTodosWith)) + for _, w := range i.HasTodosWith { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'HasTodosWith'", err) + } + with = append(with, p) + } + predicates = append(predicates, project.HasTodosWith(with...)) + } + switch len(predicates) { + case 0: + return nil, ErrEmptyProjectWhereInput + case 1: + return predicates[0], nil + default: + return project.And(predicates...), nil + } +} + +// TodoWhereInput represents a where input for filtering Todo queries. +type TodoWhereInput struct { + Predicates []predicate.Todo `json:"-"` + Not *TodoWhereInput `json:"not,omitempty"` + Or []*TodoWhereInput `json:"or,omitempty"` + And []*TodoWhereInput `json:"and,omitempty"` + + // "id" field predicates. + ID *int `json:"id,omitempty"` + IDNEQ *int `json:"idNEQ,omitempty"` + IDIn []int `json:"idIn,omitempty"` + IDNotIn []int `json:"idNotIn,omitempty"` + IDGT *int `json:"idGT,omitempty"` + IDGTE *int `json:"idGTE,omitempty"` + IDLT *int `json:"idLT,omitempty"` + IDLTE *int `json:"idLTE,omitempty"` + + // "created_at" field predicates. + CreatedAt *time.Time `json:"createdAt,omitempty"` + CreatedAtNEQ *time.Time `json:"createdAtNEQ,omitempty"` + CreatedAtIn []time.Time `json:"createdAtIn,omitempty"` + CreatedAtNotIn []time.Time `json:"createdAtNotIn,omitempty"` + CreatedAtGT *time.Time `json:"createdAtGT,omitempty"` + CreatedAtGTE *time.Time `json:"createdAtGTE,omitempty"` + CreatedAtLT *time.Time `json:"createdAtLT,omitempty"` + CreatedAtLTE *time.Time `json:"createdAtLTE,omitempty"` + + // "status" field predicates. + Status *todo.Status `json:"status,omitempty"` + StatusNEQ *todo.Status `json:"statusNEQ,omitempty"` + StatusIn []todo.Status `json:"statusIn,omitempty"` + StatusNotIn []todo.Status `json:"statusNotIn,omitempty"` + + // "priority" field predicates. + Priority *int `json:"priority,omitempty"` + PriorityNEQ *int `json:"priorityNEQ,omitempty"` + PriorityIn []int `json:"priorityIn,omitempty"` + PriorityNotIn []int `json:"priorityNotIn,omitempty"` + PriorityGT *int `json:"priorityGT,omitempty"` + PriorityGTE *int `json:"priorityGTE,omitempty"` + PriorityLT *int `json:"priorityLT,omitempty"` + PriorityLTE *int `json:"priorityLTE,omitempty"` + + // "text" field predicates. + Text *string `json:"text,omitempty"` + TextNEQ *string `json:"textNEQ,omitempty"` + TextIn []string `json:"textIn,omitempty"` + TextNotIn []string `json:"textNotIn,omitempty"` + TextGT *string `json:"textGT,omitempty"` + TextGTE *string `json:"textGTE,omitempty"` + TextLT *string `json:"textLT,omitempty"` + TextLTE *string `json:"textLTE,omitempty"` + TextContains *string `json:"textContains,omitempty"` + TextHasPrefix *string `json:"textHasPrefix,omitempty"` + TextHasSuffix *string `json:"textHasSuffix,omitempty"` + TextEqualFold *string `json:"textEqualFold,omitempty"` + TextContainsFold *string `json:"textContainsFold,omitempty"` + + // "category_id" field predicates. + CategoryID *int `json:"categoryID,omitempty"` + CategoryIDNEQ *int `json:"categoryIDNEQ,omitempty"` + CategoryIDIn []int `json:"categoryIDIn,omitempty"` + CategoryIDNotIn []int `json:"categoryIDNotIn,omitempty"` + CategoryIDIsNil bool `json:"categoryIDIsNil,omitempty"` + CategoryIDNotNil bool `json:"categoryIDNotNil,omitempty"` + + // "value" field predicates. + Value *int `json:"value,omitempty"` + ValueNEQ *int `json:"valueNEQ,omitempty"` + ValueIn []int `json:"valueIn,omitempty"` + ValueNotIn []int `json:"valueNotIn,omitempty"` + ValueGT *int `json:"valueGT,omitempty"` + ValueGTE *int `json:"valueGTE,omitempty"` + ValueLT *int `json:"valueLT,omitempty"` + ValueLTE *int `json:"valueLTE,omitempty"` + + // "parent" edge predicates. + HasParent *bool `json:"hasParent,omitempty"` + HasParentWith []*TodoWhereInput `json:"hasParentWith,omitempty"` + + // "children" edge predicates. + HasChildren *bool `json:"hasChildren,omitempty"` + HasChildrenWith []*TodoWhereInput `json:"hasChildrenWith,omitempty"` + + // "category" edge predicates. + HasCategory *bool `json:"hasCategory,omitempty"` + HasCategoryWith []*CategoryWhereInput `json:"hasCategoryWith,omitempty"` +} + +// AddPredicates adds custom predicates to the where input to be used during the filtering phase. +func (i *TodoWhereInput) AddPredicates(predicates ...predicate.Todo) { + i.Predicates = append(i.Predicates, predicates...) +} + +// Filter applies the TodoWhereInput filter on the TodoQuery builder. +func (i *TodoWhereInput) Filter(q *TodoQuery) (*TodoQuery, error) { + if i == nil { + return q, nil + } + p, err := i.P() + if err != nil { + if err == ErrEmptyTodoWhereInput { + return q, nil + } + return nil, err + } + return q.Where(p), nil +} + +// ErrEmptyTodoWhereInput is returned in case the TodoWhereInput is empty. +var ErrEmptyTodoWhereInput = errors.New("ent: empty predicate TodoWhereInput") + +// P returns a predicate for filtering todos. +// An error is returned if the input is empty or invalid. +func (i *TodoWhereInput) P() (predicate.Todo, error) { + var predicates []predicate.Todo + if i.Not != nil { + p, err := i.Not.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'not'", err) + } + predicates = append(predicates, todo.Not(p)) + } + switch n := len(i.Or); { + case n == 1: + p, err := i.Or[0].P() + if err != nil { + return nil, fmt.Errorf("%w: field 'or'", err) + } + predicates = append(predicates, p) + case n > 1: + or := make([]predicate.Todo, 0, n) + for _, w := range i.Or { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'or'", err) + } + or = append(or, p) + } + predicates = append(predicates, todo.Or(or...)) + } + switch n := len(i.And); { + case n == 1: + p, err := i.And[0].P() + if err != nil { + return nil, fmt.Errorf("%w: field 'and'", err) + } + predicates = append(predicates, p) + case n > 1: + and := make([]predicate.Todo, 0, n) + for _, w := range i.And { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'and'", err) + } + and = append(and, p) + } + predicates = append(predicates, todo.And(and...)) + } + predicates = append(predicates, i.Predicates...) + if i.ID != nil { + predicates = append(predicates, todo.IDEQ(*i.ID)) + } + if i.IDNEQ != nil { + predicates = append(predicates, todo.IDNEQ(*i.IDNEQ)) + } + if len(i.IDIn) > 0 { + predicates = append(predicates, todo.IDIn(i.IDIn...)) + } + if len(i.IDNotIn) > 0 { + predicates = append(predicates, todo.IDNotIn(i.IDNotIn...)) + } + if i.IDGT != nil { + predicates = append(predicates, todo.IDGT(*i.IDGT)) + } + if i.IDGTE != nil { + predicates = append(predicates, todo.IDGTE(*i.IDGTE)) + } + if i.IDLT != nil { + predicates = append(predicates, todo.IDLT(*i.IDLT)) + } + if i.IDLTE != nil { + predicates = append(predicates, todo.IDLTE(*i.IDLTE)) + } + if i.CreatedAt != nil { + predicates = append(predicates, todo.CreatedAtEQ(*i.CreatedAt)) + } + if i.CreatedAtNEQ != nil { + predicates = append(predicates, todo.CreatedAtNEQ(*i.CreatedAtNEQ)) + } + if len(i.CreatedAtIn) > 0 { + predicates = append(predicates, todo.CreatedAtIn(i.CreatedAtIn...)) + } + if len(i.CreatedAtNotIn) > 0 { + predicates = append(predicates, todo.CreatedAtNotIn(i.CreatedAtNotIn...)) + } + if i.CreatedAtGT != nil { + predicates = append(predicates, todo.CreatedAtGT(*i.CreatedAtGT)) + } + if i.CreatedAtGTE != nil { + predicates = append(predicates, todo.CreatedAtGTE(*i.CreatedAtGTE)) + } + if i.CreatedAtLT != nil { + predicates = append(predicates, todo.CreatedAtLT(*i.CreatedAtLT)) + } + if i.CreatedAtLTE != nil { + predicates = append(predicates, todo.CreatedAtLTE(*i.CreatedAtLTE)) + } + if i.Status != nil { + predicates = append(predicates, todo.StatusEQ(*i.Status)) + } + if i.StatusNEQ != nil { + predicates = append(predicates, todo.StatusNEQ(*i.StatusNEQ)) + } + if len(i.StatusIn) > 0 { + predicates = append(predicates, todo.StatusIn(i.StatusIn...)) + } + if len(i.StatusNotIn) > 0 { + predicates = append(predicates, todo.StatusNotIn(i.StatusNotIn...)) + } + if i.Priority != nil { + predicates = append(predicates, todo.PriorityEQ(*i.Priority)) + } + if i.PriorityNEQ != nil { + predicates = append(predicates, todo.PriorityNEQ(*i.PriorityNEQ)) + } + if len(i.PriorityIn) > 0 { + predicates = append(predicates, todo.PriorityIn(i.PriorityIn...)) + } + if len(i.PriorityNotIn) > 0 { + predicates = append(predicates, todo.PriorityNotIn(i.PriorityNotIn...)) + } + if i.PriorityGT != nil { + predicates = append(predicates, todo.PriorityGT(*i.PriorityGT)) + } + if i.PriorityGTE != nil { + predicates = append(predicates, todo.PriorityGTE(*i.PriorityGTE)) + } + if i.PriorityLT != nil { + predicates = append(predicates, todo.PriorityLT(*i.PriorityLT)) + } + if i.PriorityLTE != nil { + predicates = append(predicates, todo.PriorityLTE(*i.PriorityLTE)) + } + if i.Text != nil { + predicates = append(predicates, todo.TextEQ(*i.Text)) + } + if i.TextNEQ != nil { + predicates = append(predicates, todo.TextNEQ(*i.TextNEQ)) + } + if len(i.TextIn) > 0 { + predicates = append(predicates, todo.TextIn(i.TextIn...)) + } + if len(i.TextNotIn) > 0 { + predicates = append(predicates, todo.TextNotIn(i.TextNotIn...)) + } + if i.TextGT != nil { + predicates = append(predicates, todo.TextGT(*i.TextGT)) + } + if i.TextGTE != nil { + predicates = append(predicates, todo.TextGTE(*i.TextGTE)) + } + if i.TextLT != nil { + predicates = append(predicates, todo.TextLT(*i.TextLT)) + } + if i.TextLTE != nil { + predicates = append(predicates, todo.TextLTE(*i.TextLTE)) + } + if i.TextContains != nil { + predicates = append(predicates, todo.TextContains(*i.TextContains)) + } + if i.TextHasPrefix != nil { + predicates = append(predicates, todo.TextHasPrefix(*i.TextHasPrefix)) + } + if i.TextHasSuffix != nil { + predicates = append(predicates, todo.TextHasSuffix(*i.TextHasSuffix)) + } + if i.TextEqualFold != nil { + predicates = append(predicates, todo.TextEqualFold(*i.TextEqualFold)) + } + if i.TextContainsFold != nil { + predicates = append(predicates, todo.TextContainsFold(*i.TextContainsFold)) + } + if i.CategoryID != nil { + predicates = append(predicates, todo.CategoryIDEQ(*i.CategoryID)) + } + if i.CategoryIDNEQ != nil { + predicates = append(predicates, todo.CategoryIDNEQ(*i.CategoryIDNEQ)) + } + if len(i.CategoryIDIn) > 0 { + predicates = append(predicates, todo.CategoryIDIn(i.CategoryIDIn...)) + } + if len(i.CategoryIDNotIn) > 0 { + predicates = append(predicates, todo.CategoryIDNotIn(i.CategoryIDNotIn...)) + } + if i.CategoryIDIsNil { + predicates = append(predicates, todo.CategoryIDIsNil()) + } + if i.CategoryIDNotNil { + predicates = append(predicates, todo.CategoryIDNotNil()) + } + if i.Value != nil { + predicates = append(predicates, todo.ValueEQ(*i.Value)) + } + if i.ValueNEQ != nil { + predicates = append(predicates, todo.ValueNEQ(*i.ValueNEQ)) + } + if len(i.ValueIn) > 0 { + predicates = append(predicates, todo.ValueIn(i.ValueIn...)) + } + if len(i.ValueNotIn) > 0 { + predicates = append(predicates, todo.ValueNotIn(i.ValueNotIn...)) + } + if i.ValueGT != nil { + predicates = append(predicates, todo.ValueGT(*i.ValueGT)) + } + if i.ValueGTE != nil { + predicates = append(predicates, todo.ValueGTE(*i.ValueGTE)) + } + if i.ValueLT != nil { + predicates = append(predicates, todo.ValueLT(*i.ValueLT)) + } + if i.ValueLTE != nil { + predicates = append(predicates, todo.ValueLTE(*i.ValueLTE)) + } + + if i.HasParent != nil { + p := todo.HasParent() + if !*i.HasParent { + p = todo.Not(p) + } + predicates = append(predicates, p) + } + if len(i.HasParentWith) > 0 { + with := make([]predicate.Todo, 0, len(i.HasParentWith)) + for _, w := range i.HasParentWith { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'HasParentWith'", err) + } + with = append(with, p) + } + predicates = append(predicates, todo.HasParentWith(with...)) + } + if i.HasChildren != nil { + p := todo.HasChildren() + if !*i.HasChildren { + p = todo.Not(p) + } + predicates = append(predicates, p) + } + if len(i.HasChildrenWith) > 0 { + with := make([]predicate.Todo, 0, len(i.HasChildrenWith)) + for _, w := range i.HasChildrenWith { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'HasChildrenWith'", err) + } + with = append(with, p) + } + predicates = append(predicates, todo.HasChildrenWith(with...)) + } + if i.HasCategory != nil { + p := todo.HasCategory() + if !*i.HasCategory { + p = todo.Not(p) + } + predicates = append(predicates, p) + } + if len(i.HasCategoryWith) > 0 { + with := make([]predicate.Category, 0, len(i.HasCategoryWith)) + for _, w := range i.HasCategoryWith { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'HasCategoryWith'", err) + } + with = append(with, p) + } + predicates = append(predicates, todo.HasCategoryWith(with...)) + } + switch len(predicates) { + case 0: + return nil, ErrEmptyTodoWhereInput + case 1: + return predicates[0], nil + default: + return todo.And(predicates...), nil + } +} + +// UserWhereInput represents a where input for filtering User queries. +type UserWhereInput struct { + Predicates []predicate.User `json:"-"` + Not *UserWhereInput `json:"not,omitempty"` + Or []*UserWhereInput `json:"or,omitempty"` + And []*UserWhereInput `json:"and,omitempty"` + + // "id" field predicates. + ID *int `json:"id,omitempty"` + IDNEQ *int `json:"idNEQ,omitempty"` + IDIn []int `json:"idIn,omitempty"` + IDNotIn []int `json:"idNotIn,omitempty"` + IDGT *int `json:"idGT,omitempty"` + IDGTE *int `json:"idGTE,omitempty"` + IDLT *int `json:"idLT,omitempty"` + IDLTE *int `json:"idLTE,omitempty"` + + // "name" field predicates. + Name *string `json:"name,omitempty"` + NameNEQ *string `json:"nameNEQ,omitempty"` + NameIn []string `json:"nameIn,omitempty"` + NameNotIn []string `json:"nameNotIn,omitempty"` + NameGT *string `json:"nameGT,omitempty"` + NameGTE *string `json:"nameGTE,omitempty"` + NameLT *string `json:"nameLT,omitempty"` + NameLTE *string `json:"nameLTE,omitempty"` + NameContains *string `json:"nameContains,omitempty"` + NameHasPrefix *string `json:"nameHasPrefix,omitempty"` + NameHasSuffix *string `json:"nameHasSuffix,omitempty"` + NameEqualFold *string `json:"nameEqualFold,omitempty"` + NameContainsFold *string `json:"nameContainsFold,omitempty"` + + // "username" field predicates. + Username *uuid.UUID `json:"username,omitempty"` + UsernameNEQ *uuid.UUID `json:"usernameNEQ,omitempty"` + UsernameIn []uuid.UUID `json:"usernameIn,omitempty"` + UsernameNotIn []uuid.UUID `json:"usernameNotIn,omitempty"` + UsernameGT *uuid.UUID `json:"usernameGT,omitempty"` + UsernameGTE *uuid.UUID `json:"usernameGTE,omitempty"` + UsernameLT *uuid.UUID `json:"usernameLT,omitempty"` + UsernameLTE *uuid.UUID `json:"usernameLTE,omitempty"` + + // "password" field predicates. + Password *string `json:"password,omitempty"` + PasswordNEQ *string `json:"passwordNEQ,omitempty"` + PasswordIn []string `json:"passwordIn,omitempty"` + PasswordNotIn []string `json:"passwordNotIn,omitempty"` + PasswordGT *string `json:"passwordGT,omitempty"` + PasswordGTE *string `json:"passwordGTE,omitempty"` + PasswordLT *string `json:"passwordLT,omitempty"` + PasswordLTE *string `json:"passwordLTE,omitempty"` + PasswordContains *string `json:"passwordContains,omitempty"` + PasswordHasPrefix *string `json:"passwordHasPrefix,omitempty"` + PasswordHasSuffix *string `json:"passwordHasSuffix,omitempty"` + PasswordIsNil bool `json:"passwordIsNil,omitempty"` + PasswordNotNil bool `json:"passwordNotNil,omitempty"` + PasswordEqualFold *string `json:"passwordEqualFold,omitempty"` + PasswordContainsFold *string `json:"passwordContainsFold,omitempty"` + + // "groups" edge predicates. + HasGroups *bool `json:"hasGroups,omitempty"` + HasGroupsWith []*GroupWhereInput `json:"hasGroupsWith,omitempty"` + + // "friends" edge predicates. + HasFriends *bool `json:"hasFriends,omitempty"` + HasFriendsWith []*UserWhereInput `json:"hasFriendsWith,omitempty"` + + // "friendships" edge predicates. + HasFriendships *bool `json:"hasFriendships,omitempty"` + HasFriendshipsWith []*FriendshipWhereInput `json:"hasFriendshipsWith,omitempty"` +} + +// AddPredicates adds custom predicates to the where input to be used during the filtering phase. +func (i *UserWhereInput) AddPredicates(predicates ...predicate.User) { + i.Predicates = append(i.Predicates, predicates...) +} + +// Filter applies the UserWhereInput filter on the UserQuery builder. +func (i *UserWhereInput) Filter(q *UserQuery) (*UserQuery, error) { + if i == nil { + return q, nil + } + p, err := i.P() + if err != nil { + if err == ErrEmptyUserWhereInput { + return q, nil + } + return nil, err + } + return q.Where(p), nil +} + +// ErrEmptyUserWhereInput is returned in case the UserWhereInput is empty. +var ErrEmptyUserWhereInput = errors.New("ent: empty predicate UserWhereInput") + +// P returns a predicate for filtering users. +// An error is returned if the input is empty or invalid. +func (i *UserWhereInput) P() (predicate.User, error) { + var predicates []predicate.User + if i.Not != nil { + p, err := i.Not.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'not'", err) + } + predicates = append(predicates, user.Not(p)) + } + switch n := len(i.Or); { + case n == 1: + p, err := i.Or[0].P() + if err != nil { + return nil, fmt.Errorf("%w: field 'or'", err) + } + predicates = append(predicates, p) + case n > 1: + or := make([]predicate.User, 0, n) + for _, w := range i.Or { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'or'", err) + } + or = append(or, p) + } + predicates = append(predicates, user.Or(or...)) + } + switch n := len(i.And); { + case n == 1: + p, err := i.And[0].P() + if err != nil { + return nil, fmt.Errorf("%w: field 'and'", err) + } + predicates = append(predicates, p) + case n > 1: + and := make([]predicate.User, 0, n) + for _, w := range i.And { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'and'", err) + } + and = append(and, p) + } + predicates = append(predicates, user.And(and...)) + } + predicates = append(predicates, i.Predicates...) + if i.ID != nil { + predicates = append(predicates, user.IDEQ(*i.ID)) + } + if i.IDNEQ != nil { + predicates = append(predicates, user.IDNEQ(*i.IDNEQ)) + } + if len(i.IDIn) > 0 { + predicates = append(predicates, user.IDIn(i.IDIn...)) + } + if len(i.IDNotIn) > 0 { + predicates = append(predicates, user.IDNotIn(i.IDNotIn...)) + } + if i.IDGT != nil { + predicates = append(predicates, user.IDGT(*i.IDGT)) + } + if i.IDGTE != nil { + predicates = append(predicates, user.IDGTE(*i.IDGTE)) + } + if i.IDLT != nil { + predicates = append(predicates, user.IDLT(*i.IDLT)) + } + if i.IDLTE != nil { + predicates = append(predicates, user.IDLTE(*i.IDLTE)) + } + if i.Name != nil { + predicates = append(predicates, user.NameEQ(*i.Name)) + } + if i.NameNEQ != nil { + predicates = append(predicates, user.NameNEQ(*i.NameNEQ)) + } + if len(i.NameIn) > 0 { + predicates = append(predicates, user.NameIn(i.NameIn...)) + } + if len(i.NameNotIn) > 0 { + predicates = append(predicates, user.NameNotIn(i.NameNotIn...)) + } + if i.NameGT != nil { + predicates = append(predicates, user.NameGT(*i.NameGT)) + } + if i.NameGTE != nil { + predicates = append(predicates, user.NameGTE(*i.NameGTE)) + } + if i.NameLT != nil { + predicates = append(predicates, user.NameLT(*i.NameLT)) + } + if i.NameLTE != nil { + predicates = append(predicates, user.NameLTE(*i.NameLTE)) + } + if i.NameContains != nil { + predicates = append(predicates, user.NameContains(*i.NameContains)) + } + if i.NameHasPrefix != nil { + predicates = append(predicates, user.NameHasPrefix(*i.NameHasPrefix)) + } + if i.NameHasSuffix != nil { + predicates = append(predicates, user.NameHasSuffix(*i.NameHasSuffix)) + } + if i.NameEqualFold != nil { + predicates = append(predicates, user.NameEqualFold(*i.NameEqualFold)) + } + if i.NameContainsFold != nil { + predicates = append(predicates, user.NameContainsFold(*i.NameContainsFold)) + } + if i.Username != nil { + predicates = append(predicates, user.UsernameEQ(*i.Username)) + } + if i.UsernameNEQ != nil { + predicates = append(predicates, user.UsernameNEQ(*i.UsernameNEQ)) + } + if len(i.UsernameIn) > 0 { + predicates = append(predicates, user.UsernameIn(i.UsernameIn...)) + } + if len(i.UsernameNotIn) > 0 { + predicates = append(predicates, user.UsernameNotIn(i.UsernameNotIn...)) + } + if i.UsernameGT != nil { + predicates = append(predicates, user.UsernameGT(*i.UsernameGT)) + } + if i.UsernameGTE != nil { + predicates = append(predicates, user.UsernameGTE(*i.UsernameGTE)) + } + if i.UsernameLT != nil { + predicates = append(predicates, user.UsernameLT(*i.UsernameLT)) + } + if i.UsernameLTE != nil { + predicates = append(predicates, user.UsernameLTE(*i.UsernameLTE)) + } + if i.Password != nil { + predicates = append(predicates, user.PasswordEQ(*i.Password)) + } + if i.PasswordNEQ != nil { + predicates = append(predicates, user.PasswordNEQ(*i.PasswordNEQ)) + } + if len(i.PasswordIn) > 0 { + predicates = append(predicates, user.PasswordIn(i.PasswordIn...)) + } + if len(i.PasswordNotIn) > 0 { + predicates = append(predicates, user.PasswordNotIn(i.PasswordNotIn...)) + } + if i.PasswordGT != nil { + predicates = append(predicates, user.PasswordGT(*i.PasswordGT)) + } + if i.PasswordGTE != nil { + predicates = append(predicates, user.PasswordGTE(*i.PasswordGTE)) + } + if i.PasswordLT != nil { + predicates = append(predicates, user.PasswordLT(*i.PasswordLT)) + } + if i.PasswordLTE != nil { + predicates = append(predicates, user.PasswordLTE(*i.PasswordLTE)) + } + if i.PasswordContains != nil { + predicates = append(predicates, user.PasswordContains(*i.PasswordContains)) + } + if i.PasswordHasPrefix != nil { + predicates = append(predicates, user.PasswordHasPrefix(*i.PasswordHasPrefix)) + } + if i.PasswordHasSuffix != nil { + predicates = append(predicates, user.PasswordHasSuffix(*i.PasswordHasSuffix)) + } + if i.PasswordIsNil { + predicates = append(predicates, user.PasswordIsNil()) + } + if i.PasswordNotNil { + predicates = append(predicates, user.PasswordNotNil()) + } + if i.PasswordEqualFold != nil { + predicates = append(predicates, user.PasswordEqualFold(*i.PasswordEqualFold)) + } + if i.PasswordContainsFold != nil { + predicates = append(predicates, user.PasswordContainsFold(*i.PasswordContainsFold)) + } + + if i.HasGroups != nil { + p := user.HasGroups() + if !*i.HasGroups { + p = user.Not(p) + } + predicates = append(predicates, p) + } + if len(i.HasGroupsWith) > 0 { + with := make([]predicate.Group, 0, len(i.HasGroupsWith)) + for _, w := range i.HasGroupsWith { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'HasGroupsWith'", err) + } + with = append(with, p) + } + predicates = append(predicates, user.HasGroupsWith(with...)) + } + if i.HasFriends != nil { + p := user.HasFriends() + if !*i.HasFriends { + p = user.Not(p) + } + predicates = append(predicates, p) + } + if len(i.HasFriendsWith) > 0 { + with := make([]predicate.User, 0, len(i.HasFriendsWith)) + for _, w := range i.HasFriendsWith { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'HasFriendsWith'", err) + } + with = append(with, p) + } + predicates = append(predicates, user.HasFriendsWith(with...)) + } + if i.HasFriendships != nil { + p := user.HasFriendships() + if !*i.HasFriendships { + p = user.Not(p) + } + predicates = append(predicates, p) + } + if len(i.HasFriendshipsWith) > 0 { + with := make([]predicate.Friendship, 0, len(i.HasFriendshipsWith)) + for _, w := range i.HasFriendshipsWith { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'HasFriendshipsWith'", err) + } + with = append(with, p) + } + predicates = append(predicates, user.HasFriendshipsWith(with...)) + } + switch len(predicates) { + case 0: + return nil, ErrEmptyUserWhereInput + case 1: + return predicates[0], nil + default: + return user.And(predicates...), nil + } +} + +// OrganizationWhereInput represents a where input for filtering Workspace queries. +type OrganizationWhereInput struct { + Predicates []predicate.Workspace `json:"-"` + Not *OrganizationWhereInput `json:"not,omitempty"` + Or []*OrganizationWhereInput `json:"or,omitempty"` + And []*OrganizationWhereInput `json:"and,omitempty"` + + // "id" field predicates. + ID *int `json:"id,omitempty"` + IDNEQ *int `json:"idNEQ,omitempty"` + IDIn []int `json:"idIn,omitempty"` + IDNotIn []int `json:"idNotIn,omitempty"` + IDGT *int `json:"idGT,omitempty"` + IDGTE *int `json:"idGTE,omitempty"` + IDLT *int `json:"idLT,omitempty"` + IDLTE *int `json:"idLTE,omitempty"` + + // "name" field predicates. + Name *string `json:"name,omitempty"` + NameNEQ *string `json:"nameNEQ,omitempty"` + NameIn []string `json:"nameIn,omitempty"` + NameNotIn []string `json:"nameNotIn,omitempty"` + NameGT *string `json:"nameGT,omitempty"` + NameGTE *string `json:"nameGTE,omitempty"` + NameLT *string `json:"nameLT,omitempty"` + NameLTE *string `json:"nameLTE,omitempty"` + NameContains *string `json:"nameContains,omitempty"` + NameHasPrefix *string `json:"nameHasPrefix,omitempty"` + NameHasSuffix *string `json:"nameHasSuffix,omitempty"` + NameEqualFold *string `json:"nameEqualFold,omitempty"` + NameContainsFold *string `json:"nameContainsFold,omitempty"` +} + +// AddPredicates adds custom predicates to the where input to be used during the filtering phase. +func (i *OrganizationWhereInput) AddPredicates(predicates ...predicate.Workspace) { + i.Predicates = append(i.Predicates, predicates...) +} + +// Filter applies the OrganizationWhereInput filter on the WorkspaceQuery builder. +func (i *OrganizationWhereInput) Filter(q *WorkspaceQuery) (*WorkspaceQuery, error) { + if i == nil { + return q, nil + } + p, err := i.P() + if err != nil { + if err == ErrEmptyOrganizationWhereInput { + return q, nil + } + return nil, err + } + return q.Where(p), nil +} + +// ErrEmptyOrganizationWhereInput is returned in case the OrganizationWhereInput is empty. +var ErrEmptyOrganizationWhereInput = errors.New("ent: empty predicate OrganizationWhereInput") + +// P returns a predicate for filtering workspaces. +// An error is returned if the input is empty or invalid. +func (i *OrganizationWhereInput) P() (predicate.Workspace, error) { + var predicates []predicate.Workspace + if i.Not != nil { + p, err := i.Not.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'not'", err) + } + predicates = append(predicates, workspace.Not(p)) + } + switch n := len(i.Or); { + case n == 1: + p, err := i.Or[0].P() + if err != nil { + return nil, fmt.Errorf("%w: field 'or'", err) + } + predicates = append(predicates, p) + case n > 1: + or := make([]predicate.Workspace, 0, n) + for _, w := range i.Or { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'or'", err) + } + or = append(or, p) + } + predicates = append(predicates, workspace.Or(or...)) + } + switch n := len(i.And); { + case n == 1: + p, err := i.And[0].P() + if err != nil { + return nil, fmt.Errorf("%w: field 'and'", err) + } + predicates = append(predicates, p) + case n > 1: + and := make([]predicate.Workspace, 0, n) + for _, w := range i.And { + p, err := w.P() + if err != nil { + return nil, fmt.Errorf("%w: field 'and'", err) + } + and = append(and, p) + } + predicates = append(predicates, workspace.And(and...)) + } + predicates = append(predicates, i.Predicates...) + if i.ID != nil { + predicates = append(predicates, workspace.IDEQ(*i.ID)) + } + if i.IDNEQ != nil { + predicates = append(predicates, workspace.IDNEQ(*i.IDNEQ)) + } + if len(i.IDIn) > 0 { + predicates = append(predicates, workspace.IDIn(i.IDIn...)) + } + if len(i.IDNotIn) > 0 { + predicates = append(predicates, workspace.IDNotIn(i.IDNotIn...)) + } + if i.IDGT != nil { + predicates = append(predicates, workspace.IDGT(*i.IDGT)) + } + if i.IDGTE != nil { + predicates = append(predicates, workspace.IDGTE(*i.IDGTE)) + } + if i.IDLT != nil { + predicates = append(predicates, workspace.IDLT(*i.IDLT)) + } + if i.IDLTE != nil { + predicates = append(predicates, workspace.IDLTE(*i.IDLTE)) + } + if i.Name != nil { + predicates = append(predicates, workspace.NameEQ(*i.Name)) + } + if i.NameNEQ != nil { + predicates = append(predicates, workspace.NameNEQ(*i.NameNEQ)) + } + if len(i.NameIn) > 0 { + predicates = append(predicates, workspace.NameIn(i.NameIn...)) + } + if len(i.NameNotIn) > 0 { + predicates = append(predicates, workspace.NameNotIn(i.NameNotIn...)) + } + if i.NameGT != nil { + predicates = append(predicates, workspace.NameGT(*i.NameGT)) + } + if i.NameGTE != nil { + predicates = append(predicates, workspace.NameGTE(*i.NameGTE)) + } + if i.NameLT != nil { + predicates = append(predicates, workspace.NameLT(*i.NameLT)) + } + if i.NameLTE != nil { + predicates = append(predicates, workspace.NameLTE(*i.NameLTE)) + } + if i.NameContains != nil { + predicates = append(predicates, workspace.NameContains(*i.NameContains)) + } + if i.NameHasPrefix != nil { + predicates = append(predicates, workspace.NameHasPrefix(*i.NameHasPrefix)) + } + if i.NameHasSuffix != nil { + predicates = append(predicates, workspace.NameHasSuffix(*i.NameHasSuffix)) + } + if i.NameEqualFold != nil { + predicates = append(predicates, workspace.NameEqualFold(*i.NameEqualFold)) + } + if i.NameContainsFold != nil { + predicates = append(predicates, workspace.NameContainsFold(*i.NameContainsFold)) + } + + switch len(predicates) { + case 0: + return nil, ErrEmptyOrganizationWhereInput + case 1: + return predicates[0], nil + default: + return workspace.And(predicates...), nil + } +} diff --git a/entgql/internal/todoglobalid/ent/group.go b/entgql/internal/todoglobalid/ent/group.go new file mode 100644 index 000000000..0a9adb0ef --- /dev/null +++ b/entgql/internal/todoglobalid/ent/group.go @@ -0,0 +1,171 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/group" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// Group is the model entity for the Group schema. +type Group struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the GroupQuery when eager-loading is set. + Edges GroupEdges `json:"edges"` + selectValues sql.SelectValues +} + +// GroupEdges holds the relations/edges for other nodes in the graph. +type GroupEdges struct { + // Users holds the value of the users edge. + Users []*User `json:"users,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool + // totalCount holds the count of the edges above. + totalCount [1]map[string]int + + namedUsers map[string][]*User +} + +// UsersOrErr returns the Users value or an error if the edge +// was not loaded in eager-loading. +func (e GroupEdges) UsersOrErr() ([]*User, error) { + if e.loadedTypes[0] { + return e.Users, nil + } + return nil, &NotLoadedError{edge: "users"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Group) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case group.FieldID: + values[i] = new(sql.NullInt64) + case group.FieldName: + 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 Group fields. +func (gr *Group) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case group.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + gr.ID = int(value.Int64) + case group.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + gr.Name = value.String + } + default: + gr.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Group. +// This includes values selected through modifiers, order, etc. +func (gr *Group) Value(name string) (ent.Value, error) { + return gr.selectValues.Get(name) +} + +// QueryUsers queries the "users" edge of the Group entity. +func (gr *Group) QueryUsers() *UserQuery { + return NewGroupClient(gr.config).QueryUsers(gr) +} + +// Update returns a builder for updating this Group. +// Note that you need to call Group.Unwrap() before calling this method if this Group +// was returned from a transaction, and the transaction was committed or rolled back. +func (gr *Group) Update() *GroupUpdateOne { + return NewGroupClient(gr.config).UpdateOne(gr) +} + +// Unwrap unwraps the Group entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (gr *Group) Unwrap() *Group { + _tx, ok := gr.config.driver.(*txDriver) + if !ok { + panic("ent: Group is not a transactional entity") + } + gr.config.driver = _tx.drv + return gr +} + +// String implements the fmt.Stringer. +func (gr *Group) String() string { + var builder strings.Builder + builder.WriteString("Group(") + builder.WriteString(fmt.Sprintf("id=%v, ", gr.ID)) + builder.WriteString("name=") + builder.WriteString(gr.Name) + builder.WriteByte(')') + return builder.String() +} + +// NamedUsers returns the Users named value or an error if the edge was not +// loaded in eager-loading with this name. +func (gr *Group) NamedUsers(name string) ([]*User, error) { + if gr.Edges.namedUsers == nil { + return nil, &NotLoadedError{edge: name} + } + nodes, ok := gr.Edges.namedUsers[name] + if !ok { + return nil, &NotLoadedError{edge: name} + } + return nodes, nil +} + +func (gr *Group) appendNamedUsers(name string, edges ...*User) { + if gr.Edges.namedUsers == nil { + gr.Edges.namedUsers = make(map[string][]*User) + } + if len(edges) == 0 { + gr.Edges.namedUsers[name] = []*User{} + } else { + gr.Edges.namedUsers[name] = append(gr.Edges.namedUsers[name], edges...) + } +} + +// Groups is a parsable slice of Group. +type Groups []*Group diff --git a/entgql/internal/todoglobalid/ent/group/group.go b/entgql/internal/todoglobalid/ent/group/group.go new file mode 100644 index 000000000..057110455 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/group/group.go @@ -0,0 +1,101 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package group + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the group type in the database. + Label = "group" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // EdgeUsers holds the string denoting the users edge name in mutations. + EdgeUsers = "users" + // Table holds the table name of the group in the database. + Table = "groups" + // UsersTable is the table that holds the users relation/edge. The primary key declared below. + UsersTable = "user_groups" + // UsersInverseTable is the table name for the User entity. + // It exists in this package in order to avoid circular dependency with the "user" package. + UsersInverseTable = "users" +) + +// Columns holds all SQL columns for group fields. +var Columns = []string{ + FieldID, + FieldName, +} + +var ( + // UsersPrimaryKey and UsersColumn2 are the table columns denoting the + // primary key for the users relation (M2M). + UsersPrimaryKey = []string{"user_id", "group_id"} +) + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultName holds the default value on creation for the "name" field. + DefaultName string +) + +// OrderOption defines the ordering options for the Group 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() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByUsersCount orders the results by users count. +func ByUsersCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newUsersStep(), opts...) + } +} + +// ByUsers orders the results by users terms. +func ByUsers(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newUsersStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newUsersStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(UsersInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, UsersTable, UsersPrimaryKey...), + ) +} diff --git a/entgql/internal/todoglobalid/ent/group/where.go b/entgql/internal/todoglobalid/ent/group/where.go new file mode 100644 index 000000000..b4c613f85 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/group/where.go @@ -0,0 +1,176 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package group + +import ( + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.Group { + return predicate.Group(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.Group { + return predicate.Group(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.Group { + return predicate.Group(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.Group { + return predicate.Group(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.Group { + return predicate.Group(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.Group { + return predicate.Group(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.Group { + return predicate.Group(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.Group { + return predicate.Group(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.Group { + return predicate.Group(sql.FieldLTE(FieldID, id)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.Group { + return predicate.Group(sql.FieldEQ(FieldName, v)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.Group { + return predicate.Group(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.Group { + return predicate.Group(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.Group { + return predicate.Group(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.Group { + return predicate.Group(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.Group { + return predicate.Group(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.Group { + return predicate.Group(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.Group { + return predicate.Group(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.Group { + return predicate.Group(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.Group { + return predicate.Group(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.Group { + return predicate.Group(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.Group { + return predicate.Group(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.Group { + return predicate.Group(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.Group { + return predicate.Group(sql.FieldContainsFold(FieldName, v)) +} + +// HasUsers applies the HasEdge predicate on the "users" edge. +func HasUsers() predicate.Group { + return predicate.Group(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, UsersTable, UsersPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasUsersWith applies the HasEdge predicate on the "users" edge with a given conditions (other predicates). +func HasUsersWith(preds ...predicate.User) predicate.Group { + return predicate.Group(func(s *sql.Selector) { + step := newUsersStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Group) predicate.Group { + return predicate.Group(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Group) predicate.Group { + return predicate.Group(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Group) predicate.Group { + return predicate.Group(sql.NotPredicates(p)) +} diff --git a/entgql/internal/todoglobalid/ent/group_create.go b/entgql/internal/todoglobalid/ent/group_create.go new file mode 100644 index 000000000..9d5ae70fb --- /dev/null +++ b/entgql/internal/todoglobalid/ent/group_create.go @@ -0,0 +1,247 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/group" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/user" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// GroupCreate is the builder for creating a Group entity. +type GroupCreate struct { + config + mutation *GroupMutation + hooks []Hook +} + +// SetName sets the "name" field. +func (gc *GroupCreate) SetName(s string) *GroupCreate { + gc.mutation.SetName(s) + return gc +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (gc *GroupCreate) SetNillableName(s *string) *GroupCreate { + if s != nil { + gc.SetName(*s) + } + return gc +} + +// AddUserIDs adds the "users" edge to the User entity by IDs. +func (gc *GroupCreate) AddUserIDs(ids ...int) *GroupCreate { + gc.mutation.AddUserIDs(ids...) + return gc +} + +// AddUsers adds the "users" edges to the User entity. +func (gc *GroupCreate) AddUsers(u ...*User) *GroupCreate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return gc.AddUserIDs(ids...) +} + +// Mutation returns the GroupMutation object of the builder. +func (gc *GroupCreate) Mutation() *GroupMutation { + return gc.mutation +} + +// Save creates the Group in the database. +func (gc *GroupCreate) Save(ctx context.Context) (*Group, error) { + gc.defaults() + return withHooks(ctx, gc.sqlSave, gc.mutation, gc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (gc *GroupCreate) SaveX(ctx context.Context) *Group { + v, err := gc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (gc *GroupCreate) Exec(ctx context.Context) error { + _, err := gc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (gc *GroupCreate) ExecX(ctx context.Context) { + if err := gc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (gc *GroupCreate) defaults() { + if _, ok := gc.mutation.Name(); !ok { + v := group.DefaultName + gc.mutation.SetName(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (gc *GroupCreate) check() error { + if _, ok := gc.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Group.name"`)} + } + return nil +} + +func (gc *GroupCreate) sqlSave(ctx context.Context) (*Group, error) { + if err := gc.check(); err != nil { + return nil, err + } + _node, _spec := gc.createSpec() + if err := sqlgraph.CreateNode(ctx, gc.driver, _spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + id := _spec.ID.Value.(int64) + _node.ID = int(id) + gc.mutation.id = &_node.ID + gc.mutation.done = true + return _node, nil +} + +func (gc *GroupCreate) createSpec() (*Group, *sqlgraph.CreateSpec) { + var ( + _node = &Group{config: gc.config} + _spec = sqlgraph.NewCreateSpec(group.Table, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt)) + ) + if value, ok := gc.mutation.Name(); ok { + _spec.SetField(group.FieldName, field.TypeString, value) + _node.Name = value + } + if nodes := gc.mutation.UsersIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: group.UsersTable, + Columns: group.UsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// GroupCreateBulk is the builder for creating many Group entities in bulk. +type GroupCreateBulk struct { + config + err error + builders []*GroupCreate +} + +// Save creates the Group entities in the database. +func (gcb *GroupCreateBulk) Save(ctx context.Context) ([]*Group, error) { + if gcb.err != nil { + return nil, gcb.err + } + specs := make([]*sqlgraph.CreateSpec, len(gcb.builders)) + nodes := make([]*Group, len(gcb.builders)) + mutators := make([]Mutator, len(gcb.builders)) + for i := range gcb.builders { + func(i int, root context.Context) { + builder := gcb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*GroupMutation) + if !ok { + return nil, fmt.Errorf("unexpected mutation type %T", m) + } + if err := builder.check(); err != nil { + return nil, err + } + builder.mutation = mutation + var err error + nodes[i], specs[i] = builder.createSpec() + if i < len(mutators)-1 { + _, err = mutators[i+1].Mutate(root, gcb.builders[i+1].mutation) + } else { + spec := &sqlgraph.BatchCreateSpec{Nodes: specs} + // Invoke the actual operation on the latest mutation in the chain. + if err = sqlgraph.BatchCreate(ctx, gcb.driver, spec); err != nil { + if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + } + } + if err != nil { + return nil, err + } + mutation.id = &nodes[i].ID + 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, gcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (gcb *GroupCreateBulk) SaveX(ctx context.Context) []*Group { + v, err := gcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (gcb *GroupCreateBulk) Exec(ctx context.Context) error { + _, err := gcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (gcb *GroupCreateBulk) ExecX(ctx context.Context) { + if err := gcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entgql/internal/todoglobalid/ent/group_delete.go b/entgql/internal/todoglobalid/ent/group_delete.go new file mode 100644 index 000000000..d7370d81f --- /dev/null +++ b/entgql/internal/todoglobalid/ent/group_delete.go @@ -0,0 +1,102 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/group" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// GroupDelete is the builder for deleting a Group entity. +type GroupDelete struct { + config + hooks []Hook + mutation *GroupMutation +} + +// Where appends a list predicates to the GroupDelete builder. +func (gd *GroupDelete) Where(ps ...predicate.Group) *GroupDelete { + gd.mutation.Where(ps...) + return gd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (gd *GroupDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, gd.sqlExec, gd.mutation, gd.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (gd *GroupDelete) ExecX(ctx context.Context) int { + n, err := gd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (gd *GroupDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(group.Table, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt)) + if ps := gd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, gd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + gd.mutation.done = true + return affected, err +} + +// GroupDeleteOne is the builder for deleting a single Group entity. +type GroupDeleteOne struct { + gd *GroupDelete +} + +// Where appends a list predicates to the GroupDelete builder. +func (gdo *GroupDeleteOne) Where(ps ...predicate.Group) *GroupDeleteOne { + gdo.gd.mutation.Where(ps...) + return gdo +} + +// Exec executes the deletion query. +func (gdo *GroupDeleteOne) Exec(ctx context.Context) error { + n, err := gdo.gd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{group.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (gdo *GroupDeleteOne) ExecX(ctx context.Context) { + if err := gdo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entgql/internal/todoglobalid/ent/group_query.go b/entgql/internal/todoglobalid/ent/group_query.go new file mode 100644 index 000000000..37da585b9 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/group_query.go @@ -0,0 +1,702 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "database/sql/driver" + "fmt" + "math" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/group" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/user" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// GroupQuery is the builder for querying Group entities. +type GroupQuery struct { + config + ctx *QueryContext + order []group.OrderOption + inters []Interceptor + predicates []predicate.Group + withUsers *UserQuery + loadTotal []func(context.Context, []*Group) error + modifiers []func(*sql.Selector) + withNamedUsers map[string]*UserQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the GroupQuery builder. +func (gq *GroupQuery) Where(ps ...predicate.Group) *GroupQuery { + gq.predicates = append(gq.predicates, ps...) + return gq +} + +// Limit the number of records to be returned by this query. +func (gq *GroupQuery) Limit(limit int) *GroupQuery { + gq.ctx.Limit = &limit + return gq +} + +// Offset to start from. +func (gq *GroupQuery) Offset(offset int) *GroupQuery { + gq.ctx.Offset = &offset + return gq +} + +// Unique configures the query builder to filter duplicate records on query. +// By default, unique is set to true, and can be disabled using this method. +func (gq *GroupQuery) Unique(unique bool) *GroupQuery { + gq.ctx.Unique = &unique + return gq +} + +// Order specifies how the records should be ordered. +func (gq *GroupQuery) Order(o ...group.OrderOption) *GroupQuery { + gq.order = append(gq.order, o...) + return gq +} + +// QueryUsers chains the current query on the "users" edge. +func (gq *GroupQuery) QueryUsers() *UserQuery { + query := (&UserClient{config: gq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := gq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := gq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(group.Table, group.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2M, true, group.UsersTable, group.UsersPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(gq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Group entity from the query. +// Returns a *NotFoundError when no Group was found. +func (gq *GroupQuery) First(ctx context.Context) (*Group, error) { + nodes, err := gq.Limit(1).All(setContextOp(ctx, gq.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{group.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (gq *GroupQuery) FirstX(ctx context.Context) *Group { + node, err := gq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Group ID from the query. +// Returns a *NotFoundError when no Group ID was found. +func (gq *GroupQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = gq.Limit(1).IDs(setContextOp(ctx, gq.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{group.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (gq *GroupQuery) FirstIDX(ctx context.Context) int { + id, err := gq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Group entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Group entity is found. +// Returns a *NotFoundError when no Group entities are found. +func (gq *GroupQuery) Only(ctx context.Context) (*Group, error) { + nodes, err := gq.Limit(2).All(setContextOp(ctx, gq.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{group.Label} + default: + return nil, &NotSingularError{group.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (gq *GroupQuery) OnlyX(ctx context.Context) *Group { + node, err := gq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Group ID in the query. +// Returns a *NotSingularError when more than one Group ID is found. +// Returns a *NotFoundError when no entities are found. +func (gq *GroupQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = gq.Limit(2).IDs(setContextOp(ctx, gq.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{group.Label} + default: + err = &NotSingularError{group.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (gq *GroupQuery) OnlyIDX(ctx context.Context) int { + id, err := gq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Groups. +func (gq *GroupQuery) All(ctx context.Context) ([]*Group, error) { + ctx = setContextOp(ctx, gq.ctx, ent.OpQueryAll) + if err := gq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Group, *GroupQuery]() + return withInterceptors[[]*Group](ctx, gq, qr, gq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (gq *GroupQuery) AllX(ctx context.Context) []*Group { + nodes, err := gq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Group IDs. +func (gq *GroupQuery) IDs(ctx context.Context) (ids []int, err error) { + if gq.ctx.Unique == nil && gq.path != nil { + gq.Unique(true) + } + ctx = setContextOp(ctx, gq.ctx, ent.OpQueryIDs) + if err = gq.Select(group.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (gq *GroupQuery) IDsX(ctx context.Context) []int { + ids, err := gq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (gq *GroupQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, gq.ctx, ent.OpQueryCount) + if err := gq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, gq, querierCount[*GroupQuery](), gq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (gq *GroupQuery) CountX(ctx context.Context) int { + count, err := gq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (gq *GroupQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, gq.ctx, ent.OpQueryExist) + switch _, err := gq.FirstID(ctx); { + case IsNotFound(err): + return false, nil + case err != nil: + return false, fmt.Errorf("ent: check existence: %w", err) + default: + return true, nil + } +} + +// ExistX is like Exist, but panics if an error occurs. +func (gq *GroupQuery) ExistX(ctx context.Context) bool { + exist, err := gq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the GroupQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (gq *GroupQuery) Clone() *GroupQuery { + if gq == nil { + return nil + } + return &GroupQuery{ + config: gq.config, + ctx: gq.ctx.Clone(), + order: append([]group.OrderOption{}, gq.order...), + inters: append([]Interceptor{}, gq.inters...), + predicates: append([]predicate.Group{}, gq.predicates...), + withUsers: gq.withUsers.Clone(), + // clone intermediate query. + sql: gq.sql.Clone(), + path: gq.path, + modifiers: append([]func(*sql.Selector){}, gq.modifiers...), + } +} + +// WithUsers tells the query-builder to eager-load the nodes that are connected to +// the "users" edge. The optional arguments are used to configure the query builder of the edge. +func (gq *GroupQuery) WithUsers(opts ...func(*UserQuery)) *GroupQuery { + query := (&UserClient{config: gq.config}).Query() + for _, opt := range opts { + opt(query) + } + gq.withUsers = query + return gq +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// Name string `json:"name,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Group.Query(). +// GroupBy(group.FieldName). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (gq *GroupQuery) GroupBy(field string, fields ...string) *GroupGroupBy { + gq.ctx.Fields = append([]string{field}, fields...) + grbuild := &GroupGroupBy{build: gq} + grbuild.flds = &gq.ctx.Fields + grbuild.label = group.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 { +// Name string `json:"name,omitempty"` +// } +// +// client.Group.Query(). +// Select(group.FieldName). +// Scan(ctx, &v) +func (gq *GroupQuery) Select(fields ...string) *GroupSelect { + gq.ctx.Fields = append(gq.ctx.Fields, fields...) + sbuild := &GroupSelect{GroupQuery: gq} + sbuild.label = group.Label + sbuild.flds, sbuild.scan = &gq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a GroupSelect configured with the given aggregations. +func (gq *GroupQuery) Aggregate(fns ...AggregateFunc) *GroupSelect { + return gq.Select().Aggregate(fns...) +} + +func (gq *GroupQuery) prepareQuery(ctx context.Context) error { + for _, inter := range gq.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, gq); err != nil { + return err + } + } + } + for _, f := range gq.ctx.Fields { + if !group.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if gq.path != nil { + prev, err := gq.path(ctx) + if err != nil { + return err + } + gq.sql = prev + } + return nil +} + +func (gq *GroupQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Group, error) { + var ( + nodes = []*Group{} + _spec = gq.querySpec() + loadedTypes = [1]bool{ + gq.withUsers != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Group).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Group{config: gq.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(gq.modifiers) > 0 { + _spec.Modifiers = gq.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, gq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := gq.withUsers; query != nil { + if err := gq.loadUsers(ctx, query, nodes, + func(n *Group) { n.Edges.Users = []*User{} }, + func(n *Group, e *User) { n.Edges.Users = append(n.Edges.Users, e) }); err != nil { + return nil, err + } + } + for name, query := range gq.withNamedUsers { + if err := gq.loadUsers(ctx, query, nodes, + func(n *Group) { n.appendNamedUsers(name) }, + func(n *Group, e *User) { n.appendNamedUsers(name, e) }); err != nil { + return nil, err + } + } + for i := range gq.loadTotal { + if err := gq.loadTotal[i](ctx, nodes); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (gq *GroupQuery) loadUsers(ctx context.Context, query *UserQuery, nodes []*Group, init func(*Group), assign func(*Group, *User)) error { + edgeIDs := make([]driver.Value, len(nodes)) + byID := make(map[int]*Group) + nids := make(map[int]map[*Group]struct{}) + for i, node := range nodes { + edgeIDs[i] = node.ID + byID[node.ID] = node + if init != nil { + init(node) + } + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(group.UsersTable) + s.Join(joinT).On(s.C(user.FieldID), joinT.C(group.UsersPrimaryKey[0])) + s.Where(sql.InValues(joinT.C(group.UsersPrimaryKey[1]), edgeIDs...)) + columns := s.SelectedColumns() + s.Select(joinT.C(group.UsersPrimaryKey[1])) + s.AppendSelect(columns...) + s.SetDistinct(false) + }) + if err := query.prepareQuery(ctx); err != nil { + return err + } + qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) { + assign := spec.Assign + values := spec.ScanValues + spec.ScanValues = func(columns []string) ([]any, error) { + values, err := values(columns[1:]) + if err != nil { + return nil, err + } + return append([]any{new(sql.NullInt64)}, values...), nil + } + spec.Assign = func(columns []string, values []any) error { + outValue := int(values[0].(*sql.NullInt64).Int64) + inValue := int(values[1].(*sql.NullInt64).Int64) + if nids[inValue] == nil { + nids[inValue] = map[*Group]struct{}{byID[outValue]: {}} + return assign(columns[1:], values[1:]) + } + nids[inValue][byID[outValue]] = struct{}{} + return nil + } + }) + }) + neighbors, err := withInterceptors[[]*User](ctx, query, qr, query.inters) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nids[n.ID] + if !ok { + return fmt.Errorf(`unexpected "users" node returned %v`, n.ID) + } + for kn := range nodes { + assign(kn, n) + } + } + return nil +} + +func (gq *GroupQuery) sqlCount(ctx context.Context) (int, error) { + _spec := gq.querySpec() + if len(gq.modifiers) > 0 { + _spec.Modifiers = gq.modifiers + } + _spec.Node.Columns = gq.ctx.Fields + if len(gq.ctx.Fields) > 0 { + _spec.Unique = gq.ctx.Unique != nil && *gq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, gq.driver, _spec) +} + +func (gq *GroupQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(group.Table, group.Columns, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt)) + _spec.From = gq.sql + if unique := gq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if gq.path != nil { + _spec.Unique = true + } + if fields := gq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, group.FieldID) + for i := range fields { + if fields[i] != group.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := gq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := gq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := gq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := gq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (gq *GroupQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(gq.driver.Dialect()) + t1 := builder.Table(group.Table) + columns := gq.ctx.Fields + if len(columns) == 0 { + columns = group.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if gq.sql != nil { + selector = gq.sql + selector.Select(selector.Columns(columns...)...) + } + if gq.ctx.Unique != nil && *gq.ctx.Unique { + selector.Distinct() + } + for _, m := range gq.modifiers { + m(selector) + } + for _, p := range gq.predicates { + p(selector) + } + for _, p := range gq.order { + p(selector) + } + if offset := gq.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 := gq.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (gq *GroupQuery) Modify(modifiers ...func(s *sql.Selector)) *GroupSelect { + gq.modifiers = append(gq.modifiers, modifiers...) + return gq.Select() +} + +// WithNamedUsers tells the query-builder to eager-load the nodes that are connected to the "users" +// edge with the given name. The optional arguments are used to configure the query builder of the edge. +func (gq *GroupQuery) WithNamedUsers(name string, opts ...func(*UserQuery)) *GroupQuery { + query := (&UserClient{config: gq.config}).Query() + for _, opt := range opts { + opt(query) + } + if gq.withNamedUsers == nil { + gq.withNamedUsers = make(map[string]*UserQuery) + } + gq.withNamedUsers[name] = query + return gq +} + +// GroupGroupBy is the group-by builder for Group entities. +type GroupGroupBy struct { + selector + build *GroupQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (ggb *GroupGroupBy) Aggregate(fns ...AggregateFunc) *GroupGroupBy { + ggb.fns = append(ggb.fns, fns...) + return ggb +} + +// Scan applies the selector query and scans the result into the given value. +func (ggb *GroupGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ggb.build.ctx, ent.OpQueryGroupBy) + if err := ggb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*GroupQuery, *GroupGroupBy](ctx, ggb.build, ggb, ggb.build.inters, v) +} + +func (ggb *GroupGroupBy) sqlScan(ctx context.Context, root *GroupQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(ggb.fns)) + for _, fn := range ggb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*ggb.flds)+len(ggb.fns)) + for _, f := range *ggb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*ggb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := ggb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// GroupSelect is the builder for selecting fields of Group entities. +type GroupSelect struct { + *GroupQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (gs *GroupSelect) Aggregate(fns ...AggregateFunc) *GroupSelect { + gs.fns = append(gs.fns, fns...) + return gs +} + +// Scan applies the selector query and scans the result into the given value. +func (gs *GroupSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, gs.ctx, ent.OpQuerySelect) + if err := gs.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*GroupQuery, *GroupSelect](ctx, gs.GroupQuery, gs, gs.inters, v) +} + +func (gs *GroupSelect) sqlScan(ctx context.Context, root *GroupQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(gs.fns)) + for _, fn := range gs.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*gs.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 := gs.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (gs *GroupSelect) Modify(modifiers ...func(s *sql.Selector)) *GroupSelect { + gs.modifiers = append(gs.modifiers, modifiers...) + return gs +} diff --git a/entgql/internal/todoglobalid/ent/group_update.go b/entgql/internal/todoglobalid/ent/group_update.go new file mode 100644 index 000000000..f48ba2332 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/group_update.go @@ -0,0 +1,402 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/group" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/user" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// GroupUpdate is the builder for updating Group entities. +type GroupUpdate struct { + config + hooks []Hook + mutation *GroupMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the GroupUpdate builder. +func (gu *GroupUpdate) Where(ps ...predicate.Group) *GroupUpdate { + gu.mutation.Where(ps...) + return gu +} + +// SetName sets the "name" field. +func (gu *GroupUpdate) SetName(s string) *GroupUpdate { + gu.mutation.SetName(s) + return gu +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (gu *GroupUpdate) SetNillableName(s *string) *GroupUpdate { + if s != nil { + gu.SetName(*s) + } + return gu +} + +// AddUserIDs adds the "users" edge to the User entity by IDs. +func (gu *GroupUpdate) AddUserIDs(ids ...int) *GroupUpdate { + gu.mutation.AddUserIDs(ids...) + return gu +} + +// AddUsers adds the "users" edges to the User entity. +func (gu *GroupUpdate) AddUsers(u ...*User) *GroupUpdate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return gu.AddUserIDs(ids...) +} + +// Mutation returns the GroupMutation object of the builder. +func (gu *GroupUpdate) Mutation() *GroupMutation { + return gu.mutation +} + +// ClearUsers clears all "users" edges to the User entity. +func (gu *GroupUpdate) ClearUsers() *GroupUpdate { + gu.mutation.ClearUsers() + return gu +} + +// RemoveUserIDs removes the "users" edge to User entities by IDs. +func (gu *GroupUpdate) RemoveUserIDs(ids ...int) *GroupUpdate { + gu.mutation.RemoveUserIDs(ids...) + return gu +} + +// RemoveUsers removes "users" edges to User entities. +func (gu *GroupUpdate) RemoveUsers(u ...*User) *GroupUpdate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return gu.RemoveUserIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (gu *GroupUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, gu.sqlSave, gu.mutation, gu.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (gu *GroupUpdate) SaveX(ctx context.Context) int { + affected, err := gu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (gu *GroupUpdate) Exec(ctx context.Context) error { + _, err := gu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (gu *GroupUpdate) ExecX(ctx context.Context) { + if err := gu.Exec(ctx); err != nil { + panic(err) + } +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (gu *GroupUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *GroupUpdate { + gu.modifiers = append(gu.modifiers, modifiers...) + return gu +} + +func (gu *GroupUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := sqlgraph.NewUpdateSpec(group.Table, group.Columns, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt)) + if ps := gu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := gu.mutation.Name(); ok { + _spec.SetField(group.FieldName, field.TypeString, value) + } + if gu.mutation.UsersCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: group.UsersTable, + Columns: group.UsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := gu.mutation.RemovedUsersIDs(); len(nodes) > 0 && !gu.mutation.UsersCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: group.UsersTable, + Columns: group.UsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.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 := gu.mutation.UsersIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: group.UsersTable, + Columns: group.UsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(gu.modifiers...) + if n, err = sqlgraph.UpdateNodes(ctx, gu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{group.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + gu.mutation.done = true + return n, nil +} + +// GroupUpdateOne is the builder for updating a single Group entity. +type GroupUpdateOne struct { + config + fields []string + hooks []Hook + mutation *GroupMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetName sets the "name" field. +func (guo *GroupUpdateOne) SetName(s string) *GroupUpdateOne { + guo.mutation.SetName(s) + return guo +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (guo *GroupUpdateOne) SetNillableName(s *string) *GroupUpdateOne { + if s != nil { + guo.SetName(*s) + } + return guo +} + +// AddUserIDs adds the "users" edge to the User entity by IDs. +func (guo *GroupUpdateOne) AddUserIDs(ids ...int) *GroupUpdateOne { + guo.mutation.AddUserIDs(ids...) + return guo +} + +// AddUsers adds the "users" edges to the User entity. +func (guo *GroupUpdateOne) AddUsers(u ...*User) *GroupUpdateOne { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return guo.AddUserIDs(ids...) +} + +// Mutation returns the GroupMutation object of the builder. +func (guo *GroupUpdateOne) Mutation() *GroupMutation { + return guo.mutation +} + +// ClearUsers clears all "users" edges to the User entity. +func (guo *GroupUpdateOne) ClearUsers() *GroupUpdateOne { + guo.mutation.ClearUsers() + return guo +} + +// RemoveUserIDs removes the "users" edge to User entities by IDs. +func (guo *GroupUpdateOne) RemoveUserIDs(ids ...int) *GroupUpdateOne { + guo.mutation.RemoveUserIDs(ids...) + return guo +} + +// RemoveUsers removes "users" edges to User entities. +func (guo *GroupUpdateOne) RemoveUsers(u ...*User) *GroupUpdateOne { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return guo.RemoveUserIDs(ids...) +} + +// Where appends a list predicates to the GroupUpdate builder. +func (guo *GroupUpdateOne) Where(ps ...predicate.Group) *GroupUpdateOne { + guo.mutation.Where(ps...) + return guo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (guo *GroupUpdateOne) Select(field string, fields ...string) *GroupUpdateOne { + guo.fields = append([]string{field}, fields...) + return guo +} + +// Save executes the query and returns the updated Group entity. +func (guo *GroupUpdateOne) Save(ctx context.Context) (*Group, error) { + return withHooks(ctx, guo.sqlSave, guo.mutation, guo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (guo *GroupUpdateOne) SaveX(ctx context.Context) *Group { + node, err := guo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (guo *GroupUpdateOne) Exec(ctx context.Context) error { + _, err := guo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (guo *GroupUpdateOne) ExecX(ctx context.Context) { + if err := guo.Exec(ctx); err != nil { + panic(err) + } +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (guo *GroupUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *GroupUpdateOne { + guo.modifiers = append(guo.modifiers, modifiers...) + return guo +} + +func (guo *GroupUpdateOne) sqlSave(ctx context.Context) (_node *Group, err error) { + _spec := sqlgraph.NewUpdateSpec(group.Table, group.Columns, sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt)) + id, ok := guo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Group.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := guo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, group.FieldID) + for _, f := range fields { + if !group.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != group.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := guo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := guo.mutation.Name(); ok { + _spec.SetField(group.FieldName, field.TypeString, value) + } + if guo.mutation.UsersCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: group.UsersTable, + Columns: group.UsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := guo.mutation.RemovedUsersIDs(); len(nodes) > 0 && !guo.mutation.UsersCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: group.UsersTable, + Columns: group.UsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.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 := guo.mutation.UsersIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: true, + Table: group.UsersTable, + Columns: group.UsersPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(guo.modifiers...) + _node = &Group{config: guo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, guo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{group.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + guo.mutation.done = true + return _node, nil +} diff --git a/entgql/internal/todoglobalid/ent/hook/hook.go b/entgql/internal/todoglobalid/ent/hook/hook.go new file mode 100644 index 000000000..384c4ea1b --- /dev/null +++ b/entgql/internal/todoglobalid/ent/hook/hook.go @@ -0,0 +1,321 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package hook + +import ( + "context" + "fmt" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent" +) + +// The BillProductFunc type is an adapter to allow the use of ordinary +// function as BillProduct mutator. +type BillProductFunc func(context.Context, *ent.BillProductMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f BillProductFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.BillProductMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.BillProductMutation", m) +} + +// The CategoryFunc type is an adapter to allow the use of ordinary +// function as Category mutator. +type CategoryFunc func(context.Context, *ent.CategoryMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f CategoryFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.CategoryMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.CategoryMutation", m) +} + +// The FriendshipFunc type is an adapter to allow the use of ordinary +// function as Friendship mutator. +type FriendshipFunc func(context.Context, *ent.FriendshipMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f FriendshipFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.FriendshipMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.FriendshipMutation", m) +} + +// The GroupFunc type is an adapter to allow the use of ordinary +// function as Group mutator. +type GroupFunc func(context.Context, *ent.GroupMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f GroupFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.GroupMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.GroupMutation", m) +} + +// The OneToManyFunc type is an adapter to allow the use of ordinary +// function as OneToMany mutator. +type OneToManyFunc func(context.Context, *ent.OneToManyMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f OneToManyFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.OneToManyMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.OneToManyMutation", m) +} + +// The ProjectFunc type is an adapter to allow the use of ordinary +// function as Project mutator. +type ProjectFunc func(context.Context, *ent.ProjectMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f ProjectFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.ProjectMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.ProjectMutation", m) +} + +// The TodoFunc type is an adapter to allow the use of ordinary +// function as Todo mutator. +type TodoFunc func(context.Context, *ent.TodoMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f TodoFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.TodoMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.TodoMutation", m) +} + +// The UserFunc type is an adapter to allow the use of ordinary +// function as User mutator. +type UserFunc func(context.Context, *ent.UserMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f UserFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.UserMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserMutation", m) +} + +// The VerySecretFunc type is an adapter to allow the use of ordinary +// function as VerySecret mutator. +type VerySecretFunc func(context.Context, *ent.VerySecretMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f VerySecretFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.VerySecretMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.VerySecretMutation", m) +} + +// The WorkspaceFunc type is an adapter to allow the use of ordinary +// function as Workspace mutator. +type WorkspaceFunc func(context.Context, *ent.WorkspaceMutation) (ent.Value, error) + +// Mutate calls f(ctx, m). +func (f WorkspaceFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if mv, ok := m.(*ent.WorkspaceMutation); ok { + return f(ctx, mv) + } + return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.WorkspaceMutation", m) +} + +// Condition is a hook condition function. +type Condition func(context.Context, ent.Mutation) bool + +// And groups conditions with the AND operator. +func And(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m ent.Mutation) bool { + if !first(ctx, m) || !second(ctx, m) { + return false + } + for _, cond := range rest { + if !cond(ctx, m) { + return false + } + } + return true + } +} + +// Or groups conditions with the OR operator. +func Or(first, second Condition, rest ...Condition) Condition { + return func(ctx context.Context, m ent.Mutation) bool { + if first(ctx, m) || second(ctx, m) { + return true + } + for _, cond := range rest { + if cond(ctx, m) { + return true + } + } + return false + } +} + +// Not negates a given condition. +func Not(cond Condition) Condition { + return func(ctx context.Context, m ent.Mutation) bool { + return !cond(ctx, m) + } +} + +// HasOp is a condition testing mutation operation. +func HasOp(op ent.Op) Condition { + return func(_ context.Context, m ent.Mutation) bool { + return m.Op().Is(op) + } +} + +// HasAddedFields is a condition validating `.AddedField` on fields. +func HasAddedFields(field string, fields ...string) Condition { + return func(_ context.Context, m ent.Mutation) bool { + if _, exists := m.AddedField(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.AddedField(field); !exists { + return false + } + } + return true + } +} + +// HasClearedFields is a condition validating `.FieldCleared` on fields. +func HasClearedFields(field string, fields ...string) Condition { + return func(_ context.Context, m ent.Mutation) bool { + if exists := m.FieldCleared(field); !exists { + return false + } + for _, field := range fields { + if exists := m.FieldCleared(field); !exists { + return false + } + } + return true + } +} + +// HasFields is a condition validating `.Field` on fields. +func HasFields(field string, fields ...string) Condition { + return func(_ context.Context, m ent.Mutation) bool { + if _, exists := m.Field(field); !exists { + return false + } + for _, field := range fields { + if _, exists := m.Field(field); !exists { + return false + } + } + return true + } +} + +// If executes the given hook under condition. +// +// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...))) +func If(hk ent.Hook, cond Condition) ent.Hook { + return func(next ent.Mutator) ent.Mutator { + return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) { + if cond(ctx, m) { + return hk(next).Mutate(ctx, m) + } + return next.Mutate(ctx, m) + }) + } +} + +// On executes the given hook only for the given operation. +// +// hook.On(Log, ent.Delete|ent.Create) +func On(hk ent.Hook, op ent.Op) ent.Hook { + return If(hk, HasOp(op)) +} + +// Unless skips the given hook only for the given operation. +// +// hook.Unless(Log, ent.Update|ent.UpdateOne) +func Unless(hk ent.Hook, op ent.Op) ent.Hook { + return If(hk, Not(HasOp(op))) +} + +// FixedError is a hook returning a fixed error. +func FixedError(err error) ent.Hook { + return func(ent.Mutator) ent.Mutator { + return ent.MutateFunc(func(context.Context, ent.Mutation) (ent.Value, error) { + return nil, err + }) + } +} + +// Reject returns a hook that rejects all operations that match op. +// +// func (T) Hooks() []ent.Hook { +// return []ent.Hook{ +// Reject(ent.Delete|ent.Update), +// } +// } +func Reject(op ent.Op) ent.Hook { + hk := FixedError(fmt.Errorf("%s operation is not allowed", op)) + return On(hk, op) +} + +// Chain acts as a list of hooks and is effectively immutable. +// Once created, it will always hold the same set of hooks in the same order. +type Chain struct { + hooks []ent.Hook +} + +// NewChain creates a new chain of hooks. +func NewChain(hooks ...ent.Hook) Chain { + return Chain{append([]ent.Hook(nil), hooks...)} +} + +// Hook chains the list of hooks and returns the final hook. +func (c Chain) Hook() ent.Hook { + return func(mutator ent.Mutator) ent.Mutator { + for i := len(c.hooks) - 1; i >= 0; i-- { + mutator = c.hooks[i](mutator) + } + return mutator + } +} + +// Append extends a chain, adding the specified hook +// as the last ones in the mutation flow. +func (c Chain) Append(hooks ...ent.Hook) Chain { + newHooks := make([]ent.Hook, 0, len(c.hooks)+len(hooks)) + newHooks = append(newHooks, c.hooks...) + newHooks = append(newHooks, hooks...) + return Chain{newHooks} +} + +// Extend extends a chain, adding the specified chain +// as the last ones in the mutation flow. +func (c Chain) Extend(chain Chain) Chain { + return c.Append(chain.hooks...) +} diff --git a/entgql/internal/todoglobalid/ent/internal/globalid.go b/entgql/internal/todoglobalid/ent/internal/globalid.go new file mode 100644 index 000000000..7415c93d3 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/internal/globalid.go @@ -0,0 +1,19 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package internal + +const IncrementStarts = "{\"bill_products\":0,\"categories\":4294967296,\"friendships\":8589934592,\"groups\":12884901888,\"one_to_manies\":17179869184,\"projects\":21474836480,\"todos\":25769803776,\"users\":30064771072,\"very_secrets\":34359738368,\"workspaces\":38654705664}" diff --git a/entgql/internal/todoglobalid/ent/migrate/migrate.go b/entgql/internal/todoglobalid/ent/migrate/migrate.go new file mode 100644 index 000000000..6ce1fde33 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/migrate/migrate.go @@ -0,0 +1,78 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package migrate + +import ( + "context" + "fmt" + "io" + + "entgo.io/ent/dialect" + "entgo.io/ent/dialect/sql/schema" +) + +var ( + // WithGlobalUniqueID sets the universal ids options to the migration. + // If this option is enabled, ent migration will allocate a 1<<32 range + // for the ids of each entity (table). + // Note that this option cannot be applied on tables that already exist. + WithGlobalUniqueID = schema.WithGlobalUniqueID + // WithDropColumn sets the drop column option to the migration. + // If this option is enabled, ent migration will drop old columns + // that were used for both fields and edges. This defaults to false. + WithDropColumn = schema.WithDropColumn + // WithDropIndex sets the drop index option to the migration. + // If this option is enabled, ent migration will drop old indexes + // that were defined in the schema. This defaults to false. + // Note that unique constraints are defined using `UNIQUE INDEX`, + // and therefore, it's recommended to enable this option to get more + // flexibility in the schema changes. + WithDropIndex = schema.WithDropIndex + // WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true. + WithForeignKeys = schema.WithForeignKeys +) + +// Schema is the API for creating, migrating and dropping a schema. +type Schema struct { + drv dialect.Driver +} + +// NewSchema creates a new schema client. +func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} } + +// Create creates all schema resources. +func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error { + return Create(ctx, s, Tables, opts...) +} + +// Create creates all table resources using the given schema driver. +func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error { + migrate, err := schema.NewMigrate(s.drv, opts...) + if err != nil { + return fmt.Errorf("ent/migrate: %w", err) + } + return migrate.Create(ctx, tables...) +} + +// WriteTo writes the schema changes to w instead of running them against the database. +// +// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil { +// log.Fatal(err) +// } +func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error { + return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...) +} diff --git a/entgql/internal/todoglobalid/ent/migrate/schema.go b/entgql/internal/todoglobalid/ent/migrate/schema.go new file mode 100644 index 000000000..9caac9e96 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/migrate/schema.go @@ -0,0 +1,327 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package migrate + +import ( + "entgo.io/ent/dialect/entsql" + "entgo.io/ent/dialect/sql/schema" + "entgo.io/ent/schema/field" +) + +var ( + // BillProductsColumns holds the columns for the "bill_products" table. + BillProductsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "name", Type: field.TypeString}, + {Name: "sku", Type: field.TypeString}, + {Name: "quantity", Type: field.TypeUint64}, + } + // BillProductsTable holds the schema information for the "bill_products" table. + BillProductsTable = &schema.Table{ + Name: "bill_products", + Columns: BillProductsColumns, + PrimaryKey: []*schema.Column{BillProductsColumns[0]}, + } + // CategoriesColumns holds the columns for the "categories" table. + CategoriesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "text", Type: field.TypeString, Size: 2147483647}, + {Name: "status", Type: field.TypeEnum, Enums: []string{"ENABLED", "DISABLED"}}, + {Name: "config", Type: field.TypeOther, Nullable: true, SchemaType: map[string]string{"sqlite3": "json"}}, + {Name: "types", Type: field.TypeJSON, Nullable: true}, + {Name: "duration", Type: field.TypeInt64, Nullable: true}, + {Name: "count", Type: field.TypeUint64, Nullable: true}, + {Name: "strings", Type: field.TypeJSON, Nullable: true}, + } + // CategoriesTable holds the schema information for the "categories" table. + CategoriesTable = &schema.Table{ + Name: "categories", + Columns: CategoriesColumns, + PrimaryKey: []*schema.Column{CategoriesColumns[0]}, + } + // FriendshipsColumns holds the columns for the "friendships" table. + FriendshipsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "user_id", Type: field.TypeInt}, + {Name: "friend_id", Type: field.TypeInt}, + } + // FriendshipsTable holds the schema information for the "friendships" table. + FriendshipsTable = &schema.Table{ + Name: "friendships", + Columns: FriendshipsColumns, + PrimaryKey: []*schema.Column{FriendshipsColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "friendships_users_user", + Columns: []*schema.Column{FriendshipsColumns[2]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.NoAction, + }, + { + Symbol: "friendships_users_friend", + Columns: []*schema.Column{FriendshipsColumns[3]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.NoAction, + }, + }, + Indexes: []*schema.Index{ + { + Name: "friendship_user_id_friend_id", + Unique: true, + Columns: []*schema.Column{FriendshipsColumns[2], FriendshipsColumns[3]}, + }, + }, + } + // GroupsColumns holds the columns for the "groups" table. + GroupsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "name", Type: field.TypeString, Default: "Unknown"}, + } + // GroupsTable holds the schema information for the "groups" table. + GroupsTable = &schema.Table{ + Name: "groups", + Columns: GroupsColumns, + PrimaryKey: []*schema.Column{GroupsColumns[0]}, + } + // OneToManiesColumns holds the columns for the "one_to_manies" table. + OneToManiesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "name", Type: field.TypeString}, + {Name: "field2", Type: field.TypeString, Nullable: true}, + {Name: "parent_id", Type: field.TypeInt, Nullable: true}, + } + // OneToManiesTable holds the schema information for the "one_to_manies" table. + OneToManiesTable = &schema.Table{ + Name: "one_to_manies", + Columns: OneToManiesColumns, + PrimaryKey: []*schema.Column{OneToManiesColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "one_to_manies_one_to_manies_children", + Columns: []*schema.Column{OneToManiesColumns[3]}, + RefColumns: []*schema.Column{OneToManiesColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + } + // ProjectsColumns holds the columns for the "projects" table. + ProjectsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + } + // ProjectsTable holds the schema information for the "projects" table. + ProjectsTable = &schema.Table{ + Name: "projects", + Columns: ProjectsColumns, + PrimaryKey: []*schema.Column{ProjectsColumns[0]}, + } + // TodosColumns holds the columns for the "todos" table. + TodosColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "created_at", Type: field.TypeTime}, + {Name: "status", Type: field.TypeEnum, Enums: []string{"IN_PROGRESS", "COMPLETED", "PENDING"}}, + {Name: "priority", Type: field.TypeInt, Default: 0}, + {Name: "text", Type: field.TypeString, Size: 2147483647}, + {Name: "blob", Type: field.TypeBytes, Nullable: true}, + {Name: "init", Type: field.TypeJSON, Nullable: true}, + {Name: "custom", Type: field.TypeJSON, Nullable: true}, + {Name: "customp", Type: field.TypeJSON, Nullable: true}, + {Name: "value", Type: field.TypeInt, Default: 0}, + {Name: "category_id", Type: field.TypeInt, Nullable: true}, + {Name: "project_todos", Type: field.TypeInt, Nullable: true}, + {Name: "todo_children", Type: field.TypeInt, Nullable: true}, + {Name: "todo_secret", Type: field.TypeInt, Nullable: true}, + } + // TodosTable holds the schema information for the "todos" table. + TodosTable = &schema.Table{ + Name: "todos", + Columns: TodosColumns, + PrimaryKey: []*schema.Column{TodosColumns[0]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "todos_categories_todos", + Columns: []*schema.Column{TodosColumns[10]}, + RefColumns: []*schema.Column{CategoriesColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "todos_projects_todos", + Columns: []*schema.Column{TodosColumns[11]}, + RefColumns: []*schema.Column{ProjectsColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "todos_todos_children", + Columns: []*schema.Column{TodosColumns[12]}, + RefColumns: []*schema.Column{TodosColumns[0]}, + OnDelete: schema.SetNull, + }, + { + Symbol: "todos_very_secrets_secret", + Columns: []*schema.Column{TodosColumns[13]}, + RefColumns: []*schema.Column{VerySecretsColumns[0]}, + OnDelete: schema.SetNull, + }, + }, + } + // UsersColumns holds the columns for the "users" table. + UsersColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "name", Type: field.TypeString, Default: "Anonymous"}, + {Name: "username", Type: field.TypeUUID}, + {Name: "password", Type: field.TypeString, Nullable: true}, + {Name: "required_metadata", Type: field.TypeJSON}, + {Name: "metadata", Type: field.TypeJSON, Nullable: true}, + } + // UsersTable holds the schema information for the "users" table. + UsersTable = &schema.Table{ + Name: "users", + Columns: UsersColumns, + PrimaryKey: []*schema.Column{UsersColumns[0]}, + } + // VerySecretsColumns holds the columns for the "very_secrets" table. + VerySecretsColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "password", Type: field.TypeString}, + } + // VerySecretsTable holds the schema information for the "very_secrets" table. + VerySecretsTable = &schema.Table{ + Name: "very_secrets", + Columns: VerySecretsColumns, + PrimaryKey: []*schema.Column{VerySecretsColumns[0]}, + } + // WorkspacesColumns holds the columns for the "workspaces" table. + WorkspacesColumns = []*schema.Column{ + {Name: "id", Type: field.TypeInt, Increment: true}, + {Name: "name", Type: field.TypeString}, + } + // WorkspacesTable holds the schema information for the "workspaces" table. + WorkspacesTable = &schema.Table{ + Name: "workspaces", + Columns: WorkspacesColumns, + PrimaryKey: []*schema.Column{WorkspacesColumns[0]}, + } + // CategorySubCategoriesColumns holds the columns for the "category_sub_categories" table. + CategorySubCategoriesColumns = []*schema.Column{ + {Name: "category_id", Type: field.TypeInt}, + {Name: "sub_category_id", Type: field.TypeInt}, + } + // CategorySubCategoriesTable holds the schema information for the "category_sub_categories" table. + CategorySubCategoriesTable = &schema.Table{ + Name: "category_sub_categories", + Columns: CategorySubCategoriesColumns, + PrimaryKey: []*schema.Column{CategorySubCategoriesColumns[0], CategorySubCategoriesColumns[1]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "category_sub_categories_category_id", + Columns: []*schema.Column{CategorySubCategoriesColumns[0]}, + RefColumns: []*schema.Column{CategoriesColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "category_sub_categories_sub_category_id", + Columns: []*schema.Column{CategorySubCategoriesColumns[1]}, + RefColumns: []*schema.Column{CategoriesColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + } + // UserGroupsColumns holds the columns for the "user_groups" table. + UserGroupsColumns = []*schema.Column{ + {Name: "user_id", Type: field.TypeInt}, + {Name: "group_id", Type: field.TypeInt}, + } + // UserGroupsTable holds the schema information for the "user_groups" table. + UserGroupsTable = &schema.Table{ + Name: "user_groups", + Columns: UserGroupsColumns, + PrimaryKey: []*schema.Column{UserGroupsColumns[0], UserGroupsColumns[1]}, + ForeignKeys: []*schema.ForeignKey{ + { + Symbol: "user_groups_user_id", + Columns: []*schema.Column{UserGroupsColumns[0]}, + RefColumns: []*schema.Column{UsersColumns[0]}, + OnDelete: schema.Cascade, + }, + { + Symbol: "user_groups_group_id", + Columns: []*schema.Column{UserGroupsColumns[1]}, + RefColumns: []*schema.Column{GroupsColumns[0]}, + OnDelete: schema.Cascade, + }, + }, + } + // Tables holds all the tables in the schema. + Tables = []*schema.Table{ + BillProductsTable, + CategoriesTable, + FriendshipsTable, + GroupsTable, + OneToManiesTable, + ProjectsTable, + TodosTable, + UsersTable, + VerySecretsTable, + WorkspacesTable, + CategorySubCategoriesTable, + UserGroupsTable, + } +) + +func init() { + BillProductsTable.Annotation = &entsql.Annotation{ + IncrementStart: func(i int64) *int64 { return &i }(0), + } + CategoriesTable.Annotation = &entsql.Annotation{ + IncrementStart: func(i int64) *int64 { return &i }(4294967296), + } + FriendshipsTable.ForeignKeys[0].RefTable = UsersTable + FriendshipsTable.ForeignKeys[1].RefTable = UsersTable + FriendshipsTable.Annotation = &entsql.Annotation{ + IncrementStart: func(i int64) *int64 { return &i }(8589934592), + } + GroupsTable.Annotation = &entsql.Annotation{ + IncrementStart: func(i int64) *int64 { return &i }(12884901888), + } + OneToManiesTable.ForeignKeys[0].RefTable = OneToManiesTable + OneToManiesTable.Annotation = &entsql.Annotation{ + IncrementStart: func(i int64) *int64 { return &i }(17179869184), + } + ProjectsTable.Annotation = &entsql.Annotation{ + IncrementStart: func(i int64) *int64 { return &i }(21474836480), + } + TodosTable.ForeignKeys[0].RefTable = CategoriesTable + TodosTable.ForeignKeys[1].RefTable = ProjectsTable + TodosTable.ForeignKeys[2].RefTable = TodosTable + TodosTable.ForeignKeys[3].RefTable = VerySecretsTable + TodosTable.Annotation = &entsql.Annotation{ + IncrementStart: func(i int64) *int64 { return &i }(25769803776), + } + UsersTable.Annotation = &entsql.Annotation{ + IncrementStart: func(i int64) *int64 { return &i }(30064771072), + } + VerySecretsTable.Annotation = &entsql.Annotation{ + IncrementStart: func(i int64) *int64 { return &i }(34359738368), + } + WorkspacesTable.Annotation = &entsql.Annotation{ + IncrementStart: func(i int64) *int64 { return &i }(38654705664), + } + CategorySubCategoriesTable.ForeignKeys[0].RefTable = CategoriesTable + CategorySubCategoriesTable.ForeignKeys[1].RefTable = CategoriesTable + UserGroupsTable.ForeignKeys[0].RefTable = UsersTable + UserGroupsTable.ForeignKeys[1].RefTable = GroupsTable +} diff --git a/entgql/internal/todoglobalid/ent/mutation.go b/entgql/internal/todoglobalid/ent/mutation.go new file mode 100644 index 000000000..bb0e2d5ad --- /dev/null +++ b/entgql/internal/todoglobalid/ent/mutation.go @@ -0,0 +1,6245 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "sync" + "time" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/billproduct" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/category" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/friendship" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/group" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/onetomany" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/project" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/schema/customstruct" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/schema/schematype" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/todo" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/user" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/verysecret" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/workspace" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/google/uuid" +) + +const ( + // Operation types. + OpCreate = ent.OpCreate + OpDelete = ent.OpDelete + OpDeleteOne = ent.OpDeleteOne + OpUpdate = ent.OpUpdate + OpUpdateOne = ent.OpUpdateOne + + // Node types. + TypeBillProduct = "BillProduct" + TypeCategory = "Category" + TypeFriendship = "Friendship" + TypeGroup = "Group" + TypeOneToMany = "OneToMany" + TypeProject = "Project" + TypeTodo = "Todo" + TypeUser = "User" + TypeVerySecret = "VerySecret" + TypeWorkspace = "Workspace" +) + +// BillProductMutation represents an operation that mutates the BillProduct nodes in the graph. +type BillProductMutation struct { + config + op Op + typ string + id *int + name *string + sku *string + quantity *uint64 + addquantity *int64 + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*BillProduct, error) + predicates []predicate.BillProduct +} + +var _ ent.Mutation = (*BillProductMutation)(nil) + +// billproductOption allows management of the mutation configuration using functional options. +type billproductOption func(*BillProductMutation) + +// newBillProductMutation creates new mutation for the BillProduct entity. +func newBillProductMutation(c config, op Op, opts ...billproductOption) *BillProductMutation { + m := &BillProductMutation{ + config: c, + op: op, + typ: TypeBillProduct, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withBillProductID sets the ID field of the mutation. +func withBillProductID(id int) billproductOption { + return func(m *BillProductMutation) { + var ( + err error + once sync.Once + value *BillProduct + ) + m.oldValue = func(ctx context.Context) (*BillProduct, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().BillProduct.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withBillProduct sets the old BillProduct of the mutation. +func withBillProduct(node *BillProduct) billproductOption { + return func(m *BillProductMutation) { + m.oldValue = func(context.Context) (*BillProduct, 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 BillProductMutation) 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 BillProductMutation) 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 *BillProductMutation) 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 *BillProductMutation) 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().BillProduct.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetName sets the "name" field. +func (m *BillProductMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *BillProductMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the BillProduct entity. +// If the BillProduct 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 *BillProductMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *BillProductMutation) ResetName() { + m.name = nil +} + +// SetSku sets the "sku" field. +func (m *BillProductMutation) SetSku(s string) { + m.sku = &s +} + +// Sku returns the value of the "sku" field in the mutation. +func (m *BillProductMutation) Sku() (r string, exists bool) { + v := m.sku + if v == nil { + return + } + return *v, true +} + +// OldSku returns the old "sku" field's value of the BillProduct entity. +// If the BillProduct 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 *BillProductMutation) OldSku(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldSku is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldSku requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldSku: %w", err) + } + return oldValue.Sku, nil +} + +// ResetSku resets all changes to the "sku" field. +func (m *BillProductMutation) ResetSku() { + m.sku = nil +} + +// SetQuantity sets the "quantity" field. +func (m *BillProductMutation) SetQuantity(u uint64) { + m.quantity = &u + m.addquantity = nil +} + +// Quantity returns the value of the "quantity" field in the mutation. +func (m *BillProductMutation) Quantity() (r uint64, exists bool) { + v := m.quantity + if v == nil { + return + } + return *v, true +} + +// OldQuantity returns the old "quantity" field's value of the BillProduct entity. +// If the BillProduct 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 *BillProductMutation) OldQuantity(ctx context.Context) (v uint64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldQuantity is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldQuantity requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldQuantity: %w", err) + } + return oldValue.Quantity, nil +} + +// AddQuantity adds u to the "quantity" field. +func (m *BillProductMutation) AddQuantity(u int64) { + if m.addquantity != nil { + *m.addquantity += u + } else { + m.addquantity = &u + } +} + +// AddedQuantity returns the value that was added to the "quantity" field in this mutation. +func (m *BillProductMutation) AddedQuantity() (r int64, exists bool) { + v := m.addquantity + if v == nil { + return + } + return *v, true +} + +// ResetQuantity resets all changes to the "quantity" field. +func (m *BillProductMutation) ResetQuantity() { + m.quantity = nil + m.addquantity = nil +} + +// Where appends a list predicates to the BillProductMutation builder. +func (m *BillProductMutation) Where(ps ...predicate.BillProduct) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the BillProductMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *BillProductMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.BillProduct, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *BillProductMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *BillProductMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (BillProduct). +func (m *BillProductMutation) 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 *BillProductMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.name != nil { + fields = append(fields, billproduct.FieldName) + } + if m.sku != nil { + fields = append(fields, billproduct.FieldSku) + } + if m.quantity != nil { + fields = append(fields, billproduct.FieldQuantity) + } + 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 *BillProductMutation) Field(name string) (ent.Value, bool) { + switch name { + case billproduct.FieldName: + return m.Name() + case billproduct.FieldSku: + return m.Sku() + case billproduct.FieldQuantity: + return m.Quantity() + } + 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 *BillProductMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case billproduct.FieldName: + return m.OldName(ctx) + case billproduct.FieldSku: + return m.OldSku(ctx) + case billproduct.FieldQuantity: + return m.OldQuantity(ctx) + } + return nil, fmt.Errorf("unknown BillProduct 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 *BillProductMutation) SetField(name string, value ent.Value) error { + switch name { + case billproduct.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case billproduct.FieldSku: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetSku(v) + return nil + case billproduct.FieldQuantity: + v, ok := value.(uint64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetQuantity(v) + return nil + } + return fmt.Errorf("unknown BillProduct field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *BillProductMutation) AddedFields() []string { + var fields []string + if m.addquantity != nil { + fields = append(fields, billproduct.FieldQuantity) + } + 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 *BillProductMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case billproduct.FieldQuantity: + return m.AddedQuantity() + } + 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 *BillProductMutation) AddField(name string, value ent.Value) error { + switch name { + case billproduct.FieldQuantity: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddQuantity(v) + return nil + } + return fmt.Errorf("unknown BillProduct numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *BillProductMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *BillProductMutation) 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 *BillProductMutation) ClearField(name string) error { + return fmt.Errorf("unknown BillProduct 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 *BillProductMutation) ResetField(name string) error { + switch name { + case billproduct.FieldName: + m.ResetName() + return nil + case billproduct.FieldSku: + m.ResetSku() + return nil + case billproduct.FieldQuantity: + m.ResetQuantity() + return nil + } + return fmt.Errorf("unknown BillProduct field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *BillProductMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *BillProductMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *BillProductMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *BillProductMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *BillProductMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *BillProductMutation) EdgeCleared(name string) bool { + 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 *BillProductMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown BillProduct 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 *BillProductMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown BillProduct edge %s", name) +} + +// CategoryMutation represents an operation that mutates the Category nodes in the graph. +type CategoryMutation struct { + config + op Op + typ string + id *int + text *string + status *category.Status + _config **schematype.CategoryConfig + types **schematype.CategoryTypes + duration *time.Duration + addduration *time.Duration + count *uint64 + addcount *int64 + strings *[]string + appendstrings []string + clearedFields map[string]struct{} + todos map[int]struct{} + removedtodos map[int]struct{} + clearedtodos bool + sub_categories map[int]struct{} + removedsub_categories map[int]struct{} + clearedsub_categories bool + done bool + oldValue func(context.Context) (*Category, error) + predicates []predicate.Category +} + +var _ ent.Mutation = (*CategoryMutation)(nil) + +// categoryOption allows management of the mutation configuration using functional options. +type categoryOption func(*CategoryMutation) + +// newCategoryMutation creates new mutation for the Category entity. +func newCategoryMutation(c config, op Op, opts ...categoryOption) *CategoryMutation { + m := &CategoryMutation{ + config: c, + op: op, + typ: TypeCategory, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withCategoryID sets the ID field of the mutation. +func withCategoryID(id int) categoryOption { + return func(m *CategoryMutation) { + var ( + err error + once sync.Once + value *Category + ) + m.oldValue = func(ctx context.Context) (*Category, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Category.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withCategory sets the old Category of the mutation. +func withCategory(node *Category) categoryOption { + return func(m *CategoryMutation) { + m.oldValue = func(context.Context) (*Category, 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 CategoryMutation) 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 CategoryMutation) 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 Category entities. +func (m *CategoryMutation) SetID(id int) { + 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 *CategoryMutation) 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 *CategoryMutation) 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().Category.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetText sets the "text" field. +func (m *CategoryMutation) SetText(s string) { + m.text = &s +} + +// Text returns the value of the "text" field in the mutation. +func (m *CategoryMutation) Text() (r string, exists bool) { + v := m.text + if v == nil { + return + } + return *v, true +} + +// OldText returns the old "text" field's value of the Category entity. +// If the Category 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 *CategoryMutation) OldText(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldText is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldText requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldText: %w", err) + } + return oldValue.Text, nil +} + +// ResetText resets all changes to the "text" field. +func (m *CategoryMutation) ResetText() { + m.text = nil +} + +// SetStatus sets the "status" field. +func (m *CategoryMutation) SetStatus(c category.Status) { + m.status = &c +} + +// Status returns the value of the "status" field in the mutation. +func (m *CategoryMutation) Status() (r category.Status, exists bool) { + v := m.status + if v == nil { + return + } + return *v, true +} + +// OldStatus returns the old "status" field's value of the Category entity. +// If the Category 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 *CategoryMutation) OldStatus(ctx context.Context) (v category.Status, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStatus is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStatus requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStatus: %w", err) + } + return oldValue.Status, nil +} + +// ResetStatus resets all changes to the "status" field. +func (m *CategoryMutation) ResetStatus() { + m.status = nil +} + +// SetConfig sets the "config" field. +func (m *CategoryMutation) SetConfig(sc *schematype.CategoryConfig) { + m._config = &sc +} + +// Config returns the value of the "config" field in the mutation. +func (m *CategoryMutation) Config() (r *schematype.CategoryConfig, exists bool) { + v := m._config + if v == nil { + return + } + return *v, true +} + +// OldConfig returns the old "config" field's value of the Category entity. +// If the Category 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 *CategoryMutation) OldConfig(ctx context.Context) (v *schematype.CategoryConfig, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldConfig is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldConfig requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldConfig: %w", err) + } + return oldValue.Config, nil +} + +// ClearConfig clears the value of the "config" field. +func (m *CategoryMutation) ClearConfig() { + m._config = nil + m.clearedFields[category.FieldConfig] = struct{}{} +} + +// ConfigCleared returns if the "config" field was cleared in this mutation. +func (m *CategoryMutation) ConfigCleared() bool { + _, ok := m.clearedFields[category.FieldConfig] + return ok +} + +// ResetConfig resets all changes to the "config" field. +func (m *CategoryMutation) ResetConfig() { + m._config = nil + delete(m.clearedFields, category.FieldConfig) +} + +// SetTypes sets the "types" field. +func (m *CategoryMutation) SetTypes(st *schematype.CategoryTypes) { + m.types = &st +} + +// Types returns the value of the "types" field in the mutation. +func (m *CategoryMutation) Types() (r *schematype.CategoryTypes, exists bool) { + v := m.types + if v == nil { + return + } + return *v, true +} + +// OldTypes returns the old "types" field's value of the Category entity. +// If the Category 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 *CategoryMutation) OldTypes(ctx context.Context) (v *schematype.CategoryTypes, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldTypes is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldTypes requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldTypes: %w", err) + } + return oldValue.Types, nil +} + +// ClearTypes clears the value of the "types" field. +func (m *CategoryMutation) ClearTypes() { + m.types = nil + m.clearedFields[category.FieldTypes] = struct{}{} +} + +// TypesCleared returns if the "types" field was cleared in this mutation. +func (m *CategoryMutation) TypesCleared() bool { + _, ok := m.clearedFields[category.FieldTypes] + return ok +} + +// ResetTypes resets all changes to the "types" field. +func (m *CategoryMutation) ResetTypes() { + m.types = nil + delete(m.clearedFields, category.FieldTypes) +} + +// SetDuration sets the "duration" field. +func (m *CategoryMutation) SetDuration(t time.Duration) { + m.duration = &t + m.addduration = nil +} + +// Duration returns the value of the "duration" field in the mutation. +func (m *CategoryMutation) Duration() (r time.Duration, exists bool) { + v := m.duration + if v == nil { + return + } + return *v, true +} + +// OldDuration returns the old "duration" field's value of the Category entity. +// If the Category 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 *CategoryMutation) OldDuration(ctx context.Context) (v time.Duration, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldDuration is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldDuration requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldDuration: %w", err) + } + return oldValue.Duration, nil +} + +// AddDuration adds t to the "duration" field. +func (m *CategoryMutation) AddDuration(t time.Duration) { + if m.addduration != nil { + *m.addduration += t + } else { + m.addduration = &t + } +} + +// AddedDuration returns the value that was added to the "duration" field in this mutation. +func (m *CategoryMutation) AddedDuration() (r time.Duration, exists bool) { + v := m.addduration + if v == nil { + return + } + return *v, true +} + +// ClearDuration clears the value of the "duration" field. +func (m *CategoryMutation) ClearDuration() { + m.duration = nil + m.addduration = nil + m.clearedFields[category.FieldDuration] = struct{}{} +} + +// DurationCleared returns if the "duration" field was cleared in this mutation. +func (m *CategoryMutation) DurationCleared() bool { + _, ok := m.clearedFields[category.FieldDuration] + return ok +} + +// ResetDuration resets all changes to the "duration" field. +func (m *CategoryMutation) ResetDuration() { + m.duration = nil + m.addduration = nil + delete(m.clearedFields, category.FieldDuration) +} + +// SetCount sets the "count" field. +func (m *CategoryMutation) SetCount(u uint64) { + m.count = &u + m.addcount = nil +} + +// Count returns the value of the "count" field in the mutation. +func (m *CategoryMutation) Count() (r uint64, exists bool) { + v := m.count + if v == nil { + return + } + return *v, true +} + +// OldCount returns the old "count" field's value of the Category entity. +// If the Category 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 *CategoryMutation) OldCount(ctx context.Context) (v uint64, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCount is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCount requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCount: %w", err) + } + return oldValue.Count, nil +} + +// AddCount adds u to the "count" field. +func (m *CategoryMutation) AddCount(u int64) { + if m.addcount != nil { + *m.addcount += u + } else { + m.addcount = &u + } +} + +// AddedCount returns the value that was added to the "count" field in this mutation. +func (m *CategoryMutation) AddedCount() (r int64, exists bool) { + v := m.addcount + if v == nil { + return + } + return *v, true +} + +// ClearCount clears the value of the "count" field. +func (m *CategoryMutation) ClearCount() { + m.count = nil + m.addcount = nil + m.clearedFields[category.FieldCount] = struct{}{} +} + +// CountCleared returns if the "count" field was cleared in this mutation. +func (m *CategoryMutation) CountCleared() bool { + _, ok := m.clearedFields[category.FieldCount] + return ok +} + +// ResetCount resets all changes to the "count" field. +func (m *CategoryMutation) ResetCount() { + m.count = nil + m.addcount = nil + delete(m.clearedFields, category.FieldCount) +} + +// SetStrings sets the "strings" field. +func (m *CategoryMutation) SetStrings(s []string) { + m.strings = &s + m.appendstrings = nil +} + +// Strings returns the value of the "strings" field in the mutation. +func (m *CategoryMutation) Strings() (r []string, exists bool) { + v := m.strings + if v == nil { + return + } + return *v, true +} + +// OldStrings returns the old "strings" field's value of the Category entity. +// If the Category 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 *CategoryMutation) OldStrings(ctx context.Context) (v []string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStrings is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStrings requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStrings: %w", err) + } + return oldValue.Strings, nil +} + +// AppendStrings adds s to the "strings" field. +func (m *CategoryMutation) AppendStrings(s []string) { + m.appendstrings = append(m.appendstrings, s...) +} + +// AppendedStrings returns the list of values that were appended to the "strings" field in this mutation. +func (m *CategoryMutation) AppendedStrings() ([]string, bool) { + if len(m.appendstrings) == 0 { + return nil, false + } + return m.appendstrings, true +} + +// ClearStrings clears the value of the "strings" field. +func (m *CategoryMutation) ClearStrings() { + m.strings = nil + m.appendstrings = nil + m.clearedFields[category.FieldStrings] = struct{}{} +} + +// StringsCleared returns if the "strings" field was cleared in this mutation. +func (m *CategoryMutation) StringsCleared() bool { + _, ok := m.clearedFields[category.FieldStrings] + return ok +} + +// ResetStrings resets all changes to the "strings" field. +func (m *CategoryMutation) ResetStrings() { + m.strings = nil + m.appendstrings = nil + delete(m.clearedFields, category.FieldStrings) +} + +// AddTodoIDs adds the "todos" edge to the Todo entity by ids. +func (m *CategoryMutation) AddTodoIDs(ids ...int) { + if m.todos == nil { + m.todos = make(map[int]struct{}) + } + for i := range ids { + m.todos[ids[i]] = struct{}{} + } +} + +// ClearTodos clears the "todos" edge to the Todo entity. +func (m *CategoryMutation) ClearTodos() { + m.clearedtodos = true +} + +// TodosCleared reports if the "todos" edge to the Todo entity was cleared. +func (m *CategoryMutation) TodosCleared() bool { + return m.clearedtodos +} + +// RemoveTodoIDs removes the "todos" edge to the Todo entity by IDs. +func (m *CategoryMutation) RemoveTodoIDs(ids ...int) { + if m.removedtodos == nil { + m.removedtodos = make(map[int]struct{}) + } + for i := range ids { + delete(m.todos, ids[i]) + m.removedtodos[ids[i]] = struct{}{} + } +} + +// RemovedTodos returns the removed IDs of the "todos" edge to the Todo entity. +func (m *CategoryMutation) RemovedTodosIDs() (ids []int) { + for id := range m.removedtodos { + ids = append(ids, id) + } + return +} + +// TodosIDs returns the "todos" edge IDs in the mutation. +func (m *CategoryMutation) TodosIDs() (ids []int) { + for id := range m.todos { + ids = append(ids, id) + } + return +} + +// ResetTodos resets all changes to the "todos" edge. +func (m *CategoryMutation) ResetTodos() { + m.todos = nil + m.clearedtodos = false + m.removedtodos = nil +} + +// AddSubCategoryIDs adds the "sub_categories" edge to the Category entity by ids. +func (m *CategoryMutation) AddSubCategoryIDs(ids ...int) { + if m.sub_categories == nil { + m.sub_categories = make(map[int]struct{}) + } + for i := range ids { + m.sub_categories[ids[i]] = struct{}{} + } +} + +// ClearSubCategories clears the "sub_categories" edge to the Category entity. +func (m *CategoryMutation) ClearSubCategories() { + m.clearedsub_categories = true +} + +// SubCategoriesCleared reports if the "sub_categories" edge to the Category entity was cleared. +func (m *CategoryMutation) SubCategoriesCleared() bool { + return m.clearedsub_categories +} + +// RemoveSubCategoryIDs removes the "sub_categories" edge to the Category entity by IDs. +func (m *CategoryMutation) RemoveSubCategoryIDs(ids ...int) { + if m.removedsub_categories == nil { + m.removedsub_categories = make(map[int]struct{}) + } + for i := range ids { + delete(m.sub_categories, ids[i]) + m.removedsub_categories[ids[i]] = struct{}{} + } +} + +// RemovedSubCategories returns the removed IDs of the "sub_categories" edge to the Category entity. +func (m *CategoryMutation) RemovedSubCategoriesIDs() (ids []int) { + for id := range m.removedsub_categories { + ids = append(ids, id) + } + return +} + +// SubCategoriesIDs returns the "sub_categories" edge IDs in the mutation. +func (m *CategoryMutation) SubCategoriesIDs() (ids []int) { + for id := range m.sub_categories { + ids = append(ids, id) + } + return +} + +// ResetSubCategories resets all changes to the "sub_categories" edge. +func (m *CategoryMutation) ResetSubCategories() { + m.sub_categories = nil + m.clearedsub_categories = false + m.removedsub_categories = nil +} + +// Where appends a list predicates to the CategoryMutation builder. +func (m *CategoryMutation) Where(ps ...predicate.Category) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the CategoryMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *CategoryMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Category, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *CategoryMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *CategoryMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Category). +func (m *CategoryMutation) 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 *CategoryMutation) Fields() []string { + fields := make([]string, 0, 7) + if m.text != nil { + fields = append(fields, category.FieldText) + } + if m.status != nil { + fields = append(fields, category.FieldStatus) + } + if m._config != nil { + fields = append(fields, category.FieldConfig) + } + if m.types != nil { + fields = append(fields, category.FieldTypes) + } + if m.duration != nil { + fields = append(fields, category.FieldDuration) + } + if m.count != nil { + fields = append(fields, category.FieldCount) + } + if m.strings != nil { + fields = append(fields, category.FieldStrings) + } + 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 *CategoryMutation) Field(name string) (ent.Value, bool) { + switch name { + case category.FieldText: + return m.Text() + case category.FieldStatus: + return m.Status() + case category.FieldConfig: + return m.Config() + case category.FieldTypes: + return m.Types() + case category.FieldDuration: + return m.Duration() + case category.FieldCount: + return m.Count() + case category.FieldStrings: + return m.Strings() + } + 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 *CategoryMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case category.FieldText: + return m.OldText(ctx) + case category.FieldStatus: + return m.OldStatus(ctx) + case category.FieldConfig: + return m.OldConfig(ctx) + case category.FieldTypes: + return m.OldTypes(ctx) + case category.FieldDuration: + return m.OldDuration(ctx) + case category.FieldCount: + return m.OldCount(ctx) + case category.FieldStrings: + return m.OldStrings(ctx) + } + return nil, fmt.Errorf("unknown Category 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 *CategoryMutation) SetField(name string, value ent.Value) error { + switch name { + case category.FieldText: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetText(v) + return nil + case category.FieldStatus: + v, ok := value.(category.Status) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatus(v) + return nil + case category.FieldConfig: + v, ok := value.(*schematype.CategoryConfig) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetConfig(v) + return nil + case category.FieldTypes: + v, ok := value.(*schematype.CategoryTypes) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetTypes(v) + return nil + case category.FieldDuration: + v, ok := value.(time.Duration) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetDuration(v) + return nil + case category.FieldCount: + v, ok := value.(uint64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCount(v) + return nil + case category.FieldStrings: + v, ok := value.([]string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStrings(v) + return nil + } + return fmt.Errorf("unknown Category field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *CategoryMutation) AddedFields() []string { + var fields []string + if m.addduration != nil { + fields = append(fields, category.FieldDuration) + } + if m.addcount != nil { + fields = append(fields, category.FieldCount) + } + 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 *CategoryMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case category.FieldDuration: + return m.AddedDuration() + case category.FieldCount: + return m.AddedCount() + } + 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 *CategoryMutation) AddField(name string, value ent.Value) error { + switch name { + case category.FieldDuration: + v, ok := value.(time.Duration) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddDuration(v) + return nil + case category.FieldCount: + v, ok := value.(int64) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddCount(v) + return nil + } + return fmt.Errorf("unknown Category numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *CategoryMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(category.FieldConfig) { + fields = append(fields, category.FieldConfig) + } + if m.FieldCleared(category.FieldTypes) { + fields = append(fields, category.FieldTypes) + } + if m.FieldCleared(category.FieldDuration) { + fields = append(fields, category.FieldDuration) + } + if m.FieldCleared(category.FieldCount) { + fields = append(fields, category.FieldCount) + } + if m.FieldCleared(category.FieldStrings) { + fields = append(fields, category.FieldStrings) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *CategoryMutation) 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 *CategoryMutation) ClearField(name string) error { + switch name { + case category.FieldConfig: + m.ClearConfig() + return nil + case category.FieldTypes: + m.ClearTypes() + return nil + case category.FieldDuration: + m.ClearDuration() + return nil + case category.FieldCount: + m.ClearCount() + return nil + case category.FieldStrings: + m.ClearStrings() + return nil + } + return fmt.Errorf("unknown Category 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 *CategoryMutation) ResetField(name string) error { + switch name { + case category.FieldText: + m.ResetText() + return nil + case category.FieldStatus: + m.ResetStatus() + return nil + case category.FieldConfig: + m.ResetConfig() + return nil + case category.FieldTypes: + m.ResetTypes() + return nil + case category.FieldDuration: + m.ResetDuration() + return nil + case category.FieldCount: + m.ResetCount() + return nil + case category.FieldStrings: + m.ResetStrings() + return nil + } + return fmt.Errorf("unknown Category field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *CategoryMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.todos != nil { + edges = append(edges, category.EdgeTodos) + } + if m.sub_categories != nil { + edges = append(edges, category.EdgeSubCategories) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *CategoryMutation) AddedIDs(name string) []ent.Value { + switch name { + case category.EdgeTodos: + ids := make([]ent.Value, 0, len(m.todos)) + for id := range m.todos { + ids = append(ids, id) + } + return ids + case category.EdgeSubCategories: + ids := make([]ent.Value, 0, len(m.sub_categories)) + for id := range m.sub_categories { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *CategoryMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + if m.removedtodos != nil { + edges = append(edges, category.EdgeTodos) + } + if m.removedsub_categories != nil { + edges = append(edges, category.EdgeSubCategories) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *CategoryMutation) RemovedIDs(name string) []ent.Value { + switch name { + case category.EdgeTodos: + ids := make([]ent.Value, 0, len(m.removedtodos)) + for id := range m.removedtodos { + ids = append(ids, id) + } + return ids + case category.EdgeSubCategories: + ids := make([]ent.Value, 0, len(m.removedsub_categories)) + for id := range m.removedsub_categories { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *CategoryMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedtodos { + edges = append(edges, category.EdgeTodos) + } + if m.clearedsub_categories { + edges = append(edges, category.EdgeSubCategories) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *CategoryMutation) EdgeCleared(name string) bool { + switch name { + case category.EdgeTodos: + return m.clearedtodos + case category.EdgeSubCategories: + return m.clearedsub_categories + } + 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 *CategoryMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown Category 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 *CategoryMutation) ResetEdge(name string) error { + switch name { + case category.EdgeTodos: + m.ResetTodos() + return nil + case category.EdgeSubCategories: + m.ResetSubCategories() + return nil + } + return fmt.Errorf("unknown Category edge %s", name) +} + +// FriendshipMutation represents an operation that mutates the Friendship nodes in the graph. +type FriendshipMutation struct { + config + op Op + typ string + id *int + created_at *time.Time + clearedFields map[string]struct{} + user *int + cleareduser bool + friend *int + clearedfriend bool + done bool + oldValue func(context.Context) (*Friendship, error) + predicates []predicate.Friendship +} + +var _ ent.Mutation = (*FriendshipMutation)(nil) + +// friendshipOption allows management of the mutation configuration using functional options. +type friendshipOption func(*FriendshipMutation) + +// newFriendshipMutation creates new mutation for the Friendship entity. +func newFriendshipMutation(c config, op Op, opts ...friendshipOption) *FriendshipMutation { + m := &FriendshipMutation{ + config: c, + op: op, + typ: TypeFriendship, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withFriendshipID sets the ID field of the mutation. +func withFriendshipID(id int) friendshipOption { + return func(m *FriendshipMutation) { + var ( + err error + once sync.Once + value *Friendship + ) + m.oldValue = func(ctx context.Context) (*Friendship, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Friendship.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withFriendship sets the old Friendship of the mutation. +func withFriendship(node *Friendship) friendshipOption { + return func(m *FriendshipMutation) { + m.oldValue = func(context.Context) (*Friendship, 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 FriendshipMutation) 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 FriendshipMutation) 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 *FriendshipMutation) 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 *FriendshipMutation) 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().Friendship.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetCreatedAt sets the "created_at" field. +func (m *FriendshipMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *FriendshipMutation) 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 Friendship entity. +// If the Friendship 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 *FriendshipMutation) 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 *FriendshipMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetUserID sets the "user_id" field. +func (m *FriendshipMutation) SetUserID(i int) { + m.user = &i +} + +// UserID returns the value of the "user_id" field in the mutation. +func (m *FriendshipMutation) UserID() (r int, exists bool) { + v := m.user + if v == nil { + return + } + return *v, true +} + +// OldUserID returns the old "user_id" field's value of the Friendship entity. +// If the Friendship 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 *FriendshipMutation) OldUserID(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUserID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUserID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUserID: %w", err) + } + return oldValue.UserID, nil +} + +// ResetUserID resets all changes to the "user_id" field. +func (m *FriendshipMutation) ResetUserID() { + m.user = nil +} + +// SetFriendID sets the "friend_id" field. +func (m *FriendshipMutation) SetFriendID(i int) { + m.friend = &i +} + +// FriendID returns the value of the "friend_id" field in the mutation. +func (m *FriendshipMutation) FriendID() (r int, exists bool) { + v := m.friend + if v == nil { + return + } + return *v, true +} + +// OldFriendID returns the old "friend_id" field's value of the Friendship entity. +// If the Friendship 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 *FriendshipMutation) OldFriendID(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldFriendID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldFriendID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldFriendID: %w", err) + } + return oldValue.FriendID, nil +} + +// ResetFriendID resets all changes to the "friend_id" field. +func (m *FriendshipMutation) ResetFriendID() { + m.friend = nil +} + +// ClearUser clears the "user" edge to the User entity. +func (m *FriendshipMutation) ClearUser() { + m.cleareduser = true + m.clearedFields[friendship.FieldUserID] = struct{}{} +} + +// UserCleared reports if the "user" edge to the User entity was cleared. +func (m *FriendshipMutation) UserCleared() bool { + return m.cleareduser +} + +// UserIDs returns the "user" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// UserID instead. It exists only for internal usage by the builders. +func (m *FriendshipMutation) UserIDs() (ids []int) { + if id := m.user; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetUser resets all changes to the "user" edge. +func (m *FriendshipMutation) ResetUser() { + m.user = nil + m.cleareduser = false +} + +// ClearFriend clears the "friend" edge to the User entity. +func (m *FriendshipMutation) ClearFriend() { + m.clearedfriend = true + m.clearedFields[friendship.FieldFriendID] = struct{}{} +} + +// FriendCleared reports if the "friend" edge to the User entity was cleared. +func (m *FriendshipMutation) FriendCleared() bool { + return m.clearedfriend +} + +// FriendIDs returns the "friend" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// FriendID instead. It exists only for internal usage by the builders. +func (m *FriendshipMutation) FriendIDs() (ids []int) { + if id := m.friend; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetFriend resets all changes to the "friend" edge. +func (m *FriendshipMutation) ResetFriend() { + m.friend = nil + m.clearedfriend = false +} + +// Where appends a list predicates to the FriendshipMutation builder. +func (m *FriendshipMutation) Where(ps ...predicate.Friendship) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the FriendshipMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *FriendshipMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Friendship, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *FriendshipMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *FriendshipMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Friendship). +func (m *FriendshipMutation) 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 *FriendshipMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.created_at != nil { + fields = append(fields, friendship.FieldCreatedAt) + } + if m.user != nil { + fields = append(fields, friendship.FieldUserID) + } + if m.friend != nil { + fields = append(fields, friendship.FieldFriendID) + } + 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 *FriendshipMutation) Field(name string) (ent.Value, bool) { + switch name { + case friendship.FieldCreatedAt: + return m.CreatedAt() + case friendship.FieldUserID: + return m.UserID() + case friendship.FieldFriendID: + return m.FriendID() + } + 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 *FriendshipMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case friendship.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case friendship.FieldUserID: + return m.OldUserID(ctx) + case friendship.FieldFriendID: + return m.OldFriendID(ctx) + } + return nil, fmt.Errorf("unknown Friendship 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 *FriendshipMutation) SetField(name string, value ent.Value) error { + switch name { + case friendship.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case friendship.FieldUserID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUserID(v) + return nil + case friendship.FieldFriendID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetFriendID(v) + return nil + } + return fmt.Errorf("unknown Friendship field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *FriendshipMutation) AddedFields() []string { + var fields []string + 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 *FriendshipMutation) AddedField(name string) (ent.Value, bool) { + switch name { + } + 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 *FriendshipMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Friendship numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *FriendshipMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *FriendshipMutation) 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 *FriendshipMutation) ClearField(name string) error { + return fmt.Errorf("unknown Friendship 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 *FriendshipMutation) ResetField(name string) error { + switch name { + case friendship.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case friendship.FieldUserID: + m.ResetUserID() + return nil + case friendship.FieldFriendID: + m.ResetFriendID() + return nil + } + return fmt.Errorf("unknown Friendship field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *FriendshipMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.user != nil { + edges = append(edges, friendship.EdgeUser) + } + if m.friend != nil { + edges = append(edges, friendship.EdgeFriend) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *FriendshipMutation) AddedIDs(name string) []ent.Value { + switch name { + case friendship.EdgeUser: + if id := m.user; id != nil { + return []ent.Value{*id} + } + case friendship.EdgeFriend: + if id := m.friend; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *FriendshipMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *FriendshipMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *FriendshipMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.cleareduser { + edges = append(edges, friendship.EdgeUser) + } + if m.clearedfriend { + edges = append(edges, friendship.EdgeFriend) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *FriendshipMutation) EdgeCleared(name string) bool { + switch name { + case friendship.EdgeUser: + return m.cleareduser + case friendship.EdgeFriend: + return m.clearedfriend + } + 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 *FriendshipMutation) ClearEdge(name string) error { + switch name { + case friendship.EdgeUser: + m.ClearUser() + return nil + case friendship.EdgeFriend: + m.ClearFriend() + return nil + } + return fmt.Errorf("unknown Friendship 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 *FriendshipMutation) ResetEdge(name string) error { + switch name { + case friendship.EdgeUser: + m.ResetUser() + return nil + case friendship.EdgeFriend: + m.ResetFriend() + return nil + } + return fmt.Errorf("unknown Friendship edge %s", name) +} + +// GroupMutation represents an operation that mutates the Group nodes in the graph. +type GroupMutation struct { + config + op Op + typ string + id *int + name *string + clearedFields map[string]struct{} + users map[int]struct{} + removedusers map[int]struct{} + clearedusers bool + done bool + oldValue func(context.Context) (*Group, error) + predicates []predicate.Group +} + +var _ ent.Mutation = (*GroupMutation)(nil) + +// groupOption allows management of the mutation configuration using functional options. +type groupOption func(*GroupMutation) + +// newGroupMutation creates new mutation for the Group entity. +func newGroupMutation(c config, op Op, opts ...groupOption) *GroupMutation { + m := &GroupMutation{ + config: c, + op: op, + typ: TypeGroup, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withGroupID sets the ID field of the mutation. +func withGroupID(id int) groupOption { + return func(m *GroupMutation) { + var ( + err error + once sync.Once + value *Group + ) + m.oldValue = func(ctx context.Context) (*Group, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Group.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withGroup sets the old Group of the mutation. +func withGroup(node *Group) groupOption { + return func(m *GroupMutation) { + m.oldValue = func(context.Context) (*Group, 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 GroupMutation) 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 GroupMutation) 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 *GroupMutation) 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 *GroupMutation) 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().Group.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetName sets the "name" field. +func (m *GroupMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *GroupMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the Group entity. +// If the Group 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 *GroupMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *GroupMutation) ResetName() { + m.name = nil +} + +// AddUserIDs adds the "users" edge to the User entity by ids. +func (m *GroupMutation) AddUserIDs(ids ...int) { + if m.users == nil { + m.users = make(map[int]struct{}) + } + for i := range ids { + m.users[ids[i]] = struct{}{} + } +} + +// ClearUsers clears the "users" edge to the User entity. +func (m *GroupMutation) ClearUsers() { + m.clearedusers = true +} + +// UsersCleared reports if the "users" edge to the User entity was cleared. +func (m *GroupMutation) UsersCleared() bool { + return m.clearedusers +} + +// RemoveUserIDs removes the "users" edge to the User entity by IDs. +func (m *GroupMutation) RemoveUserIDs(ids ...int) { + if m.removedusers == nil { + m.removedusers = make(map[int]struct{}) + } + for i := range ids { + delete(m.users, ids[i]) + m.removedusers[ids[i]] = struct{}{} + } +} + +// RemovedUsers returns the removed IDs of the "users" edge to the User entity. +func (m *GroupMutation) RemovedUsersIDs() (ids []int) { + for id := range m.removedusers { + ids = append(ids, id) + } + return +} + +// UsersIDs returns the "users" edge IDs in the mutation. +func (m *GroupMutation) UsersIDs() (ids []int) { + for id := range m.users { + ids = append(ids, id) + } + return +} + +// ResetUsers resets all changes to the "users" edge. +func (m *GroupMutation) ResetUsers() { + m.users = nil + m.clearedusers = false + m.removedusers = nil +} + +// Where appends a list predicates to the GroupMutation builder. +func (m *GroupMutation) Where(ps ...predicate.Group) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the GroupMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *GroupMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Group, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *GroupMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *GroupMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Group). +func (m *GroupMutation) 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 *GroupMutation) Fields() []string { + fields := make([]string, 0, 1) + if m.name != nil { + fields = append(fields, group.FieldName) + } + 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 *GroupMutation) Field(name string) (ent.Value, bool) { + switch name { + case group.FieldName: + return m.Name() + } + 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 *GroupMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case group.FieldName: + return m.OldName(ctx) + } + return nil, fmt.Errorf("unknown Group 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 *GroupMutation) SetField(name string, value ent.Value) error { + switch name { + case group.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + } + return fmt.Errorf("unknown Group field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *GroupMutation) 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 *GroupMutation) 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 *GroupMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Group numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *GroupMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *GroupMutation) 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 *GroupMutation) ClearField(name string) error { + return fmt.Errorf("unknown Group 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 *GroupMutation) ResetField(name string) error { + switch name { + case group.FieldName: + m.ResetName() + return nil + } + return fmt.Errorf("unknown Group field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *GroupMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.users != nil { + edges = append(edges, group.EdgeUsers) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *GroupMutation) AddedIDs(name string) []ent.Value { + switch name { + case group.EdgeUsers: + ids := make([]ent.Value, 0, len(m.users)) + for id := range m.users { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *GroupMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + if m.removedusers != nil { + edges = append(edges, group.EdgeUsers) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *GroupMutation) RemovedIDs(name string) []ent.Value { + switch name { + case group.EdgeUsers: + ids := make([]ent.Value, 0, len(m.removedusers)) + for id := range m.removedusers { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *GroupMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedusers { + edges = append(edges, group.EdgeUsers) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *GroupMutation) EdgeCleared(name string) bool { + switch name { + case group.EdgeUsers: + return m.clearedusers + } + 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 *GroupMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown Group 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 *GroupMutation) ResetEdge(name string) error { + switch name { + case group.EdgeUsers: + m.ResetUsers() + return nil + } + return fmt.Errorf("unknown Group edge %s", name) +} + +// OneToManyMutation represents an operation that mutates the OneToMany nodes in the graph. +type OneToManyMutation struct { + config + op Op + typ string + id *int + name *string + field2 *string + clearedFields map[string]struct{} + parent *int + clearedparent bool + children map[int]struct{} + removedchildren map[int]struct{} + clearedchildren bool + done bool + oldValue func(context.Context) (*OneToMany, error) + predicates []predicate.OneToMany +} + +var _ ent.Mutation = (*OneToManyMutation)(nil) + +// onetomanyOption allows management of the mutation configuration using functional options. +type onetomanyOption func(*OneToManyMutation) + +// newOneToManyMutation creates new mutation for the OneToMany entity. +func newOneToManyMutation(c config, op Op, opts ...onetomanyOption) *OneToManyMutation { + m := &OneToManyMutation{ + config: c, + op: op, + typ: TypeOneToMany, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withOneToManyID sets the ID field of the mutation. +func withOneToManyID(id int) onetomanyOption { + return func(m *OneToManyMutation) { + var ( + err error + once sync.Once + value *OneToMany + ) + m.oldValue = func(ctx context.Context) (*OneToMany, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().OneToMany.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withOneToMany sets the old OneToMany of the mutation. +func withOneToMany(node *OneToMany) onetomanyOption { + return func(m *OneToManyMutation) { + m.oldValue = func(context.Context) (*OneToMany, 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 OneToManyMutation) 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 OneToManyMutation) 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 *OneToManyMutation) 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 *OneToManyMutation) 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().OneToMany.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetName sets the "name" field. +func (m *OneToManyMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *OneToManyMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the OneToMany entity. +// If the OneToMany 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 *OneToManyMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *OneToManyMutation) ResetName() { + m.name = nil +} + +// SetField2 sets the "field2" field. +func (m *OneToManyMutation) SetField2(s string) { + m.field2 = &s +} + +// Field2 returns the value of the "field2" field in the mutation. +func (m *OneToManyMutation) Field2() (r string, exists bool) { + v := m.field2 + if v == nil { + return + } + return *v, true +} + +// OldField2 returns the old "field2" field's value of the OneToMany entity. +// If the OneToMany 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 *OneToManyMutation) OldField2(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldField2 is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldField2 requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldField2: %w", err) + } + return oldValue.Field2, nil +} + +// ClearField2 clears the value of the "field2" field. +func (m *OneToManyMutation) ClearField2() { + m.field2 = nil + m.clearedFields[onetomany.FieldField2] = struct{}{} +} + +// Field2Cleared returns if the "field2" field was cleared in this mutation. +func (m *OneToManyMutation) Field2Cleared() bool { + _, ok := m.clearedFields[onetomany.FieldField2] + return ok +} + +// ResetField2 resets all changes to the "field2" field. +func (m *OneToManyMutation) ResetField2() { + m.field2 = nil + delete(m.clearedFields, onetomany.FieldField2) +} + +// SetParentID sets the "parent_id" field. +func (m *OneToManyMutation) SetParentID(i int) { + m.parent = &i +} + +// ParentID returns the value of the "parent_id" field in the mutation. +func (m *OneToManyMutation) ParentID() (r int, exists bool) { + v := m.parent + if v == nil { + return + } + return *v, true +} + +// OldParentID returns the old "parent_id" field's value of the OneToMany entity. +// If the OneToMany 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 *OneToManyMutation) OldParentID(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldParentID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldParentID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldParentID: %w", err) + } + return oldValue.ParentID, nil +} + +// ClearParentID clears the value of the "parent_id" field. +func (m *OneToManyMutation) ClearParentID() { + m.parent = nil + m.clearedFields[onetomany.FieldParentID] = struct{}{} +} + +// ParentIDCleared returns if the "parent_id" field was cleared in this mutation. +func (m *OneToManyMutation) ParentIDCleared() bool { + _, ok := m.clearedFields[onetomany.FieldParentID] + return ok +} + +// ResetParentID resets all changes to the "parent_id" field. +func (m *OneToManyMutation) ResetParentID() { + m.parent = nil + delete(m.clearedFields, onetomany.FieldParentID) +} + +// ClearParent clears the "parent" edge to the OneToMany entity. +func (m *OneToManyMutation) ClearParent() { + m.clearedparent = true + m.clearedFields[onetomany.FieldParentID] = struct{}{} +} + +// ParentCleared reports if the "parent" edge to the OneToMany entity was cleared. +func (m *OneToManyMutation) ParentCleared() bool { + return m.ParentIDCleared() || m.clearedparent +} + +// ParentIDs returns the "parent" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// ParentID instead. It exists only for internal usage by the builders. +func (m *OneToManyMutation) ParentIDs() (ids []int) { + if id := m.parent; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetParent resets all changes to the "parent" edge. +func (m *OneToManyMutation) ResetParent() { + m.parent = nil + m.clearedparent = false +} + +// AddChildIDs adds the "children" edge to the OneToMany entity by ids. +func (m *OneToManyMutation) AddChildIDs(ids ...int) { + if m.children == nil { + m.children = make(map[int]struct{}) + } + for i := range ids { + m.children[ids[i]] = struct{}{} + } +} + +// ClearChildren clears the "children" edge to the OneToMany entity. +func (m *OneToManyMutation) ClearChildren() { + m.clearedchildren = true +} + +// ChildrenCleared reports if the "children" edge to the OneToMany entity was cleared. +func (m *OneToManyMutation) ChildrenCleared() bool { + return m.clearedchildren +} + +// RemoveChildIDs removes the "children" edge to the OneToMany entity by IDs. +func (m *OneToManyMutation) RemoveChildIDs(ids ...int) { + if m.removedchildren == nil { + m.removedchildren = make(map[int]struct{}) + } + for i := range ids { + delete(m.children, ids[i]) + m.removedchildren[ids[i]] = struct{}{} + } +} + +// RemovedChildren returns the removed IDs of the "children" edge to the OneToMany entity. +func (m *OneToManyMutation) RemovedChildrenIDs() (ids []int) { + for id := range m.removedchildren { + ids = append(ids, id) + } + return +} + +// ChildrenIDs returns the "children" edge IDs in the mutation. +func (m *OneToManyMutation) ChildrenIDs() (ids []int) { + for id := range m.children { + ids = append(ids, id) + } + return +} + +// ResetChildren resets all changes to the "children" edge. +func (m *OneToManyMutation) ResetChildren() { + m.children = nil + m.clearedchildren = false + m.removedchildren = nil +} + +// Where appends a list predicates to the OneToManyMutation builder. +func (m *OneToManyMutation) Where(ps ...predicate.OneToMany) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the OneToManyMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *OneToManyMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.OneToMany, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *OneToManyMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *OneToManyMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (OneToMany). +func (m *OneToManyMutation) 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 *OneToManyMutation) Fields() []string { + fields := make([]string, 0, 3) + if m.name != nil { + fields = append(fields, onetomany.FieldName) + } + if m.field2 != nil { + fields = append(fields, onetomany.FieldField2) + } + if m.parent != nil { + fields = append(fields, onetomany.FieldParentID) + } + 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 *OneToManyMutation) Field(name string) (ent.Value, bool) { + switch name { + case onetomany.FieldName: + return m.Name() + case onetomany.FieldField2: + return m.Field2() + case onetomany.FieldParentID: + return m.ParentID() + } + 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 *OneToManyMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case onetomany.FieldName: + return m.OldName(ctx) + case onetomany.FieldField2: + return m.OldField2(ctx) + case onetomany.FieldParentID: + return m.OldParentID(ctx) + } + return nil, fmt.Errorf("unknown OneToMany 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 *OneToManyMutation) SetField(name string, value ent.Value) error { + switch name { + case onetomany.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case onetomany.FieldField2: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetField2(v) + return nil + case onetomany.FieldParentID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetParentID(v) + return nil + } + return fmt.Errorf("unknown OneToMany field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *OneToManyMutation) AddedFields() []string { + var fields []string + 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 *OneToManyMutation) AddedField(name string) (ent.Value, bool) { + switch name { + } + 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 *OneToManyMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown OneToMany numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *OneToManyMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(onetomany.FieldField2) { + fields = append(fields, onetomany.FieldField2) + } + if m.FieldCleared(onetomany.FieldParentID) { + fields = append(fields, onetomany.FieldParentID) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *OneToManyMutation) 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 *OneToManyMutation) ClearField(name string) error { + switch name { + case onetomany.FieldField2: + m.ClearField2() + return nil + case onetomany.FieldParentID: + m.ClearParentID() + return nil + } + return fmt.Errorf("unknown OneToMany 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 *OneToManyMutation) ResetField(name string) error { + switch name { + case onetomany.FieldName: + m.ResetName() + return nil + case onetomany.FieldField2: + m.ResetField2() + return nil + case onetomany.FieldParentID: + m.ResetParentID() + return nil + } + return fmt.Errorf("unknown OneToMany field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *OneToManyMutation) AddedEdges() []string { + edges := make([]string, 0, 2) + if m.parent != nil { + edges = append(edges, onetomany.EdgeParent) + } + if m.children != nil { + edges = append(edges, onetomany.EdgeChildren) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *OneToManyMutation) AddedIDs(name string) []ent.Value { + switch name { + case onetomany.EdgeParent: + if id := m.parent; id != nil { + return []ent.Value{*id} + } + case onetomany.EdgeChildren: + ids := make([]ent.Value, 0, len(m.children)) + for id := range m.children { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *OneToManyMutation) RemovedEdges() []string { + edges := make([]string, 0, 2) + if m.removedchildren != nil { + edges = append(edges, onetomany.EdgeChildren) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *OneToManyMutation) RemovedIDs(name string) []ent.Value { + switch name { + case onetomany.EdgeChildren: + ids := make([]ent.Value, 0, len(m.removedchildren)) + for id := range m.removedchildren { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *OneToManyMutation) ClearedEdges() []string { + edges := make([]string, 0, 2) + if m.clearedparent { + edges = append(edges, onetomany.EdgeParent) + } + if m.clearedchildren { + edges = append(edges, onetomany.EdgeChildren) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *OneToManyMutation) EdgeCleared(name string) bool { + switch name { + case onetomany.EdgeParent: + return m.clearedparent + case onetomany.EdgeChildren: + return m.clearedchildren + } + 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 *OneToManyMutation) ClearEdge(name string) error { + switch name { + case onetomany.EdgeParent: + m.ClearParent() + return nil + } + return fmt.Errorf("unknown OneToMany 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 *OneToManyMutation) ResetEdge(name string) error { + switch name { + case onetomany.EdgeParent: + m.ResetParent() + return nil + case onetomany.EdgeChildren: + m.ResetChildren() + return nil + } + return fmt.Errorf("unknown OneToMany edge %s", name) +} + +// ProjectMutation represents an operation that mutates the Project nodes in the graph. +type ProjectMutation struct { + config + op Op + typ string + id *int + clearedFields map[string]struct{} + todos map[int]struct{} + removedtodos map[int]struct{} + clearedtodos bool + done bool + oldValue func(context.Context) (*Project, error) + predicates []predicate.Project +} + +var _ ent.Mutation = (*ProjectMutation)(nil) + +// projectOption allows management of the mutation configuration using functional options. +type projectOption func(*ProjectMutation) + +// newProjectMutation creates new mutation for the Project entity. +func newProjectMutation(c config, op Op, opts ...projectOption) *ProjectMutation { + m := &ProjectMutation{ + config: c, + op: op, + typ: TypeProject, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withProjectID sets the ID field of the mutation. +func withProjectID(id int) projectOption { + return func(m *ProjectMutation) { + var ( + err error + once sync.Once + value *Project + ) + m.oldValue = func(ctx context.Context) (*Project, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Project.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withProject sets the old Project of the mutation. +func withProject(node *Project) projectOption { + return func(m *ProjectMutation) { + m.oldValue = func(context.Context) (*Project, 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 ProjectMutation) 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 ProjectMutation) 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 *ProjectMutation) 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 *ProjectMutation) 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().Project.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// AddTodoIDs adds the "todos" edge to the Todo entity by ids. +func (m *ProjectMutation) AddTodoIDs(ids ...int) { + if m.todos == nil { + m.todos = make(map[int]struct{}) + } + for i := range ids { + m.todos[ids[i]] = struct{}{} + } +} + +// ClearTodos clears the "todos" edge to the Todo entity. +func (m *ProjectMutation) ClearTodos() { + m.clearedtodos = true +} + +// TodosCleared reports if the "todos" edge to the Todo entity was cleared. +func (m *ProjectMutation) TodosCleared() bool { + return m.clearedtodos +} + +// RemoveTodoIDs removes the "todos" edge to the Todo entity by IDs. +func (m *ProjectMutation) RemoveTodoIDs(ids ...int) { + if m.removedtodos == nil { + m.removedtodos = make(map[int]struct{}) + } + for i := range ids { + delete(m.todos, ids[i]) + m.removedtodos[ids[i]] = struct{}{} + } +} + +// RemovedTodos returns the removed IDs of the "todos" edge to the Todo entity. +func (m *ProjectMutation) RemovedTodosIDs() (ids []int) { + for id := range m.removedtodos { + ids = append(ids, id) + } + return +} + +// TodosIDs returns the "todos" edge IDs in the mutation. +func (m *ProjectMutation) TodosIDs() (ids []int) { + for id := range m.todos { + ids = append(ids, id) + } + return +} + +// ResetTodos resets all changes to the "todos" edge. +func (m *ProjectMutation) ResetTodos() { + m.todos = nil + m.clearedtodos = false + m.removedtodos = nil +} + +// Where appends a list predicates to the ProjectMutation builder. +func (m *ProjectMutation) Where(ps ...predicate.Project) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the ProjectMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *ProjectMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Project, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *ProjectMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *ProjectMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Project). +func (m *ProjectMutation) 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 *ProjectMutation) Fields() []string { + fields := make([]string, 0, 0) + 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 *ProjectMutation) Field(name string) (ent.Value, bool) { + 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 *ProjectMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + return nil, fmt.Errorf("unknown Project 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 *ProjectMutation) SetField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Project field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *ProjectMutation) 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 *ProjectMutation) 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 *ProjectMutation) AddField(name string, value ent.Value) error { + return fmt.Errorf("unknown Project numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *ProjectMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *ProjectMutation) 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 *ProjectMutation) ClearField(name string) error { + return fmt.Errorf("unknown Project 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 *ProjectMutation) ResetField(name string) error { + return fmt.Errorf("unknown Project field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *ProjectMutation) AddedEdges() []string { + edges := make([]string, 0, 1) + if m.todos != nil { + edges = append(edges, project.EdgeTodos) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *ProjectMutation) AddedIDs(name string) []ent.Value { + switch name { + case project.EdgeTodos: + ids := make([]ent.Value, 0, len(m.todos)) + for id := range m.todos { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *ProjectMutation) RemovedEdges() []string { + edges := make([]string, 0, 1) + if m.removedtodos != nil { + edges = append(edges, project.EdgeTodos) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *ProjectMutation) RemovedIDs(name string) []ent.Value { + switch name { + case project.EdgeTodos: + ids := make([]ent.Value, 0, len(m.removedtodos)) + for id := range m.removedtodos { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *ProjectMutation) ClearedEdges() []string { + edges := make([]string, 0, 1) + if m.clearedtodos { + edges = append(edges, project.EdgeTodos) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *ProjectMutation) EdgeCleared(name string) bool { + switch name { + case project.EdgeTodos: + return m.clearedtodos + } + 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 *ProjectMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown Project 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 *ProjectMutation) ResetEdge(name string) error { + switch name { + case project.EdgeTodos: + m.ResetTodos() + return nil + } + return fmt.Errorf("unknown Project edge %s", name) +} + +// TodoMutation represents an operation that mutates the Todo nodes in the graph. +type TodoMutation struct { + config + op Op + typ string + id *int + created_at *time.Time + status *todo.Status + priority *int + addpriority *int + text *string + blob *[]byte + init *map[string]interface{} + custom *[]customstruct.Custom + appendcustom []customstruct.Custom + customp *[]*customstruct.Custom + appendcustomp []*customstruct.Custom + value *int + addvalue *int + clearedFields map[string]struct{} + parent *int + clearedparent bool + children map[int]struct{} + removedchildren map[int]struct{} + clearedchildren bool + category *int + clearedcategory bool + secret *int + clearedsecret bool + done bool + oldValue func(context.Context) (*Todo, error) + predicates []predicate.Todo +} + +var _ ent.Mutation = (*TodoMutation)(nil) + +// todoOption allows management of the mutation configuration using functional options. +type todoOption func(*TodoMutation) + +// newTodoMutation creates new mutation for the Todo entity. +func newTodoMutation(c config, op Op, opts ...todoOption) *TodoMutation { + m := &TodoMutation{ + config: c, + op: op, + typ: TypeTodo, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withTodoID sets the ID field of the mutation. +func withTodoID(id int) todoOption { + return func(m *TodoMutation) { + var ( + err error + once sync.Once + value *Todo + ) + m.oldValue = func(ctx context.Context) (*Todo, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Todo.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withTodo sets the old Todo of the mutation. +func withTodo(node *Todo) todoOption { + return func(m *TodoMutation) { + m.oldValue = func(context.Context) (*Todo, 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 TodoMutation) 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 TodoMutation) 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 *TodoMutation) 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 *TodoMutation) 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().Todo.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetCreatedAt sets the "created_at" field. +func (m *TodoMutation) SetCreatedAt(t time.Time) { + m.created_at = &t +} + +// CreatedAt returns the value of the "created_at" field in the mutation. +func (m *TodoMutation) 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 Todo entity. +// If the Todo 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 *TodoMutation) 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 *TodoMutation) ResetCreatedAt() { + m.created_at = nil +} + +// SetStatus sets the "status" field. +func (m *TodoMutation) SetStatus(t todo.Status) { + m.status = &t +} + +// Status returns the value of the "status" field in the mutation. +func (m *TodoMutation) Status() (r todo.Status, exists bool) { + v := m.status + if v == nil { + return + } + return *v, true +} + +// OldStatus returns the old "status" field's value of the Todo entity. +// If the Todo 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 *TodoMutation) OldStatus(ctx context.Context) (v todo.Status, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldStatus is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldStatus requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldStatus: %w", err) + } + return oldValue.Status, nil +} + +// ResetStatus resets all changes to the "status" field. +func (m *TodoMutation) ResetStatus() { + m.status = nil +} + +// SetPriority sets the "priority" field. +func (m *TodoMutation) SetPriority(i int) { + m.priority = &i + m.addpriority = nil +} + +// Priority returns the value of the "priority" field in the mutation. +func (m *TodoMutation) Priority() (r int, exists bool) { + v := m.priority + if v == nil { + return + } + return *v, true +} + +// OldPriority returns the old "priority" field's value of the Todo entity. +// If the Todo 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 *TodoMutation) OldPriority(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPriority is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPriority requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPriority: %w", err) + } + return oldValue.Priority, nil +} + +// AddPriority adds i to the "priority" field. +func (m *TodoMutation) AddPriority(i int) { + if m.addpriority != nil { + *m.addpriority += i + } else { + m.addpriority = &i + } +} + +// AddedPriority returns the value that was added to the "priority" field in this mutation. +func (m *TodoMutation) AddedPriority() (r int, exists bool) { + v := m.addpriority + if v == nil { + return + } + return *v, true +} + +// ResetPriority resets all changes to the "priority" field. +func (m *TodoMutation) ResetPriority() { + m.priority = nil + m.addpriority = nil +} + +// SetText sets the "text" field. +func (m *TodoMutation) SetText(s string) { + m.text = &s +} + +// Text returns the value of the "text" field in the mutation. +func (m *TodoMutation) Text() (r string, exists bool) { + v := m.text + if v == nil { + return + } + return *v, true +} + +// OldText returns the old "text" field's value of the Todo entity. +// If the Todo 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 *TodoMutation) OldText(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldText is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldText requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldText: %w", err) + } + return oldValue.Text, nil +} + +// ResetText resets all changes to the "text" field. +func (m *TodoMutation) ResetText() { + m.text = nil +} + +// SetBlob sets the "blob" field. +func (m *TodoMutation) SetBlob(b []byte) { + m.blob = &b +} + +// Blob returns the value of the "blob" field in the mutation. +func (m *TodoMutation) Blob() (r []byte, exists bool) { + v := m.blob + if v == nil { + return + } + return *v, true +} + +// OldBlob returns the old "blob" field's value of the Todo entity. +// If the Todo 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 *TodoMutation) OldBlob(ctx context.Context) (v []byte, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldBlob is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldBlob requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldBlob: %w", err) + } + return oldValue.Blob, nil +} + +// ClearBlob clears the value of the "blob" field. +func (m *TodoMutation) ClearBlob() { + m.blob = nil + m.clearedFields[todo.FieldBlob] = struct{}{} +} + +// BlobCleared returns if the "blob" field was cleared in this mutation. +func (m *TodoMutation) BlobCleared() bool { + _, ok := m.clearedFields[todo.FieldBlob] + return ok +} + +// ResetBlob resets all changes to the "blob" field. +func (m *TodoMutation) ResetBlob() { + m.blob = nil + delete(m.clearedFields, todo.FieldBlob) +} + +// SetCategoryID sets the "category_id" field. +func (m *TodoMutation) SetCategoryID(i int) { + m.category = &i +} + +// CategoryID returns the value of the "category_id" field in the mutation. +func (m *TodoMutation) CategoryID() (r int, exists bool) { + v := m.category + if v == nil { + return + } + return *v, true +} + +// OldCategoryID returns the old "category_id" field's value of the Todo entity. +// If the Todo 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 *TodoMutation) OldCategoryID(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCategoryID is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCategoryID requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCategoryID: %w", err) + } + return oldValue.CategoryID, nil +} + +// ClearCategoryID clears the value of the "category_id" field. +func (m *TodoMutation) ClearCategoryID() { + m.category = nil + m.clearedFields[todo.FieldCategoryID] = struct{}{} +} + +// CategoryIDCleared returns if the "category_id" field was cleared in this mutation. +func (m *TodoMutation) CategoryIDCleared() bool { + _, ok := m.clearedFields[todo.FieldCategoryID] + return ok +} + +// ResetCategoryID resets all changes to the "category_id" field. +func (m *TodoMutation) ResetCategoryID() { + m.category = nil + delete(m.clearedFields, todo.FieldCategoryID) +} + +// SetInit sets the "init" field. +func (m *TodoMutation) SetInit(value map[string]interface{}) { + m.init = &value +} + +// Init returns the value of the "init" field in the mutation. +func (m *TodoMutation) Init() (r map[string]interface{}, exists bool) { + v := m.init + if v == nil { + return + } + return *v, true +} + +// OldInit returns the old "init" field's value of the Todo entity. +// If the Todo 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 *TodoMutation) OldInit(ctx context.Context) (v map[string]interface{}, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldInit is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldInit requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldInit: %w", err) + } + return oldValue.Init, nil +} + +// ClearInit clears the value of the "init" field. +func (m *TodoMutation) ClearInit() { + m.init = nil + m.clearedFields[todo.FieldInit] = struct{}{} +} + +// InitCleared returns if the "init" field was cleared in this mutation. +func (m *TodoMutation) InitCleared() bool { + _, ok := m.clearedFields[todo.FieldInit] + return ok +} + +// ResetInit resets all changes to the "init" field. +func (m *TodoMutation) ResetInit() { + m.init = nil + delete(m.clearedFields, todo.FieldInit) +} + +// SetCustom sets the "custom" field. +func (m *TodoMutation) SetCustom(c []customstruct.Custom) { + m.custom = &c + m.appendcustom = nil +} + +// Custom returns the value of the "custom" field in the mutation. +func (m *TodoMutation) Custom() (r []customstruct.Custom, exists bool) { + v := m.custom + if v == nil { + return + } + return *v, true +} + +// OldCustom returns the old "custom" field's value of the Todo entity. +// If the Todo 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 *TodoMutation) OldCustom(ctx context.Context) (v []customstruct.Custom, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustom is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustom requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustom: %w", err) + } + return oldValue.Custom, nil +} + +// AppendCustom adds c to the "custom" field. +func (m *TodoMutation) AppendCustom(c []customstruct.Custom) { + m.appendcustom = append(m.appendcustom, c...) +} + +// AppendedCustom returns the list of values that were appended to the "custom" field in this mutation. +func (m *TodoMutation) AppendedCustom() ([]customstruct.Custom, bool) { + if len(m.appendcustom) == 0 { + return nil, false + } + return m.appendcustom, true +} + +// ClearCustom clears the value of the "custom" field. +func (m *TodoMutation) ClearCustom() { + m.custom = nil + m.appendcustom = nil + m.clearedFields[todo.FieldCustom] = struct{}{} +} + +// CustomCleared returns if the "custom" field was cleared in this mutation. +func (m *TodoMutation) CustomCleared() bool { + _, ok := m.clearedFields[todo.FieldCustom] + return ok +} + +// ResetCustom resets all changes to the "custom" field. +func (m *TodoMutation) ResetCustom() { + m.custom = nil + m.appendcustom = nil + delete(m.clearedFields, todo.FieldCustom) +} + +// SetCustomp sets the "customp" field. +func (m *TodoMutation) SetCustomp(c []*customstruct.Custom) { + m.customp = &c + m.appendcustomp = nil +} + +// Customp returns the value of the "customp" field in the mutation. +func (m *TodoMutation) Customp() (r []*customstruct.Custom, exists bool) { + v := m.customp + if v == nil { + return + } + return *v, true +} + +// OldCustomp returns the old "customp" field's value of the Todo entity. +// If the Todo 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 *TodoMutation) OldCustomp(ctx context.Context) (v []*customstruct.Custom, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldCustomp is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldCustomp requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldCustomp: %w", err) + } + return oldValue.Customp, nil +} + +// AppendCustomp adds c to the "customp" field. +func (m *TodoMutation) AppendCustomp(c []*customstruct.Custom) { + m.appendcustomp = append(m.appendcustomp, c...) +} + +// AppendedCustomp returns the list of values that were appended to the "customp" field in this mutation. +func (m *TodoMutation) AppendedCustomp() ([]*customstruct.Custom, bool) { + if len(m.appendcustomp) == 0 { + return nil, false + } + return m.appendcustomp, true +} + +// ClearCustomp clears the value of the "customp" field. +func (m *TodoMutation) ClearCustomp() { + m.customp = nil + m.appendcustomp = nil + m.clearedFields[todo.FieldCustomp] = struct{}{} +} + +// CustompCleared returns if the "customp" field was cleared in this mutation. +func (m *TodoMutation) CustompCleared() bool { + _, ok := m.clearedFields[todo.FieldCustomp] + return ok +} + +// ResetCustomp resets all changes to the "customp" field. +func (m *TodoMutation) ResetCustomp() { + m.customp = nil + m.appendcustomp = nil + delete(m.clearedFields, todo.FieldCustomp) +} + +// SetValue sets the "value" field. +func (m *TodoMutation) SetValue(i int) { + m.value = &i + m.addvalue = nil +} + +// Value returns the value of the "value" field in the mutation. +func (m *TodoMutation) Value() (r int, exists bool) { + v := m.value + if v == nil { + return + } + return *v, true +} + +// OldValue returns the old "value" field's value of the Todo entity. +// If the Todo 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 *TodoMutation) OldValue(ctx context.Context) (v int, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldValue is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldValue requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldValue: %w", err) + } + return oldValue.Value, nil +} + +// AddValue adds i to the "value" field. +func (m *TodoMutation) AddValue(i int) { + if m.addvalue != nil { + *m.addvalue += i + } else { + m.addvalue = &i + } +} + +// AddedValue returns the value that was added to the "value" field in this mutation. +func (m *TodoMutation) AddedValue() (r int, exists bool) { + v := m.addvalue + if v == nil { + return + } + return *v, true +} + +// ResetValue resets all changes to the "value" field. +func (m *TodoMutation) ResetValue() { + m.value = nil + m.addvalue = nil +} + +// SetParentID sets the "parent" edge to the Todo entity by id. +func (m *TodoMutation) SetParentID(id int) { + m.parent = &id +} + +// ClearParent clears the "parent" edge to the Todo entity. +func (m *TodoMutation) ClearParent() { + m.clearedparent = true +} + +// ParentCleared reports if the "parent" edge to the Todo entity was cleared. +func (m *TodoMutation) ParentCleared() bool { + return m.clearedparent +} + +// ParentID returns the "parent" edge ID in the mutation. +func (m *TodoMutation) ParentID() (id int, exists bool) { + if m.parent != nil { + return *m.parent, true + } + return +} + +// ParentIDs returns the "parent" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// ParentID instead. It exists only for internal usage by the builders. +func (m *TodoMutation) ParentIDs() (ids []int) { + if id := m.parent; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetParent resets all changes to the "parent" edge. +func (m *TodoMutation) ResetParent() { + m.parent = nil + m.clearedparent = false +} + +// AddChildIDs adds the "children" edge to the Todo entity by ids. +func (m *TodoMutation) AddChildIDs(ids ...int) { + if m.children == nil { + m.children = make(map[int]struct{}) + } + for i := range ids { + m.children[ids[i]] = struct{}{} + } +} + +// ClearChildren clears the "children" edge to the Todo entity. +func (m *TodoMutation) ClearChildren() { + m.clearedchildren = true +} + +// ChildrenCleared reports if the "children" edge to the Todo entity was cleared. +func (m *TodoMutation) ChildrenCleared() bool { + return m.clearedchildren +} + +// RemoveChildIDs removes the "children" edge to the Todo entity by IDs. +func (m *TodoMutation) RemoveChildIDs(ids ...int) { + if m.removedchildren == nil { + m.removedchildren = make(map[int]struct{}) + } + for i := range ids { + delete(m.children, ids[i]) + m.removedchildren[ids[i]] = struct{}{} + } +} + +// RemovedChildren returns the removed IDs of the "children" edge to the Todo entity. +func (m *TodoMutation) RemovedChildrenIDs() (ids []int) { + for id := range m.removedchildren { + ids = append(ids, id) + } + return +} + +// ChildrenIDs returns the "children" edge IDs in the mutation. +func (m *TodoMutation) ChildrenIDs() (ids []int) { + for id := range m.children { + ids = append(ids, id) + } + return +} + +// ResetChildren resets all changes to the "children" edge. +func (m *TodoMutation) ResetChildren() { + m.children = nil + m.clearedchildren = false + m.removedchildren = nil +} + +// ClearCategory clears the "category" edge to the Category entity. +func (m *TodoMutation) ClearCategory() { + m.clearedcategory = true + m.clearedFields[todo.FieldCategoryID] = struct{}{} +} + +// CategoryCleared reports if the "category" edge to the Category entity was cleared. +func (m *TodoMutation) CategoryCleared() bool { + return m.CategoryIDCleared() || m.clearedcategory +} + +// CategoryIDs returns the "category" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// CategoryID instead. It exists only for internal usage by the builders. +func (m *TodoMutation) CategoryIDs() (ids []int) { + if id := m.category; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetCategory resets all changes to the "category" edge. +func (m *TodoMutation) ResetCategory() { + m.category = nil + m.clearedcategory = false +} + +// SetSecretID sets the "secret" edge to the VerySecret entity by id. +func (m *TodoMutation) SetSecretID(id int) { + m.secret = &id +} + +// ClearSecret clears the "secret" edge to the VerySecret entity. +func (m *TodoMutation) ClearSecret() { + m.clearedsecret = true +} + +// SecretCleared reports if the "secret" edge to the VerySecret entity was cleared. +func (m *TodoMutation) SecretCleared() bool { + return m.clearedsecret +} + +// SecretID returns the "secret" edge ID in the mutation. +func (m *TodoMutation) SecretID() (id int, exists bool) { + if m.secret != nil { + return *m.secret, true + } + return +} + +// SecretIDs returns the "secret" edge IDs in the mutation. +// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use +// SecretID instead. It exists only for internal usage by the builders. +func (m *TodoMutation) SecretIDs() (ids []int) { + if id := m.secret; id != nil { + ids = append(ids, *id) + } + return +} + +// ResetSecret resets all changes to the "secret" edge. +func (m *TodoMutation) ResetSecret() { + m.secret = nil + m.clearedsecret = false +} + +// Where appends a list predicates to the TodoMutation builder. +func (m *TodoMutation) Where(ps ...predicate.Todo) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the TodoMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *TodoMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Todo, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *TodoMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *TodoMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Todo). +func (m *TodoMutation) 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 *TodoMutation) Fields() []string { + fields := make([]string, 0, 10) + if m.created_at != nil { + fields = append(fields, todo.FieldCreatedAt) + } + if m.status != nil { + fields = append(fields, todo.FieldStatus) + } + if m.priority != nil { + fields = append(fields, todo.FieldPriority) + } + if m.text != nil { + fields = append(fields, todo.FieldText) + } + if m.blob != nil { + fields = append(fields, todo.FieldBlob) + } + if m.category != nil { + fields = append(fields, todo.FieldCategoryID) + } + if m.init != nil { + fields = append(fields, todo.FieldInit) + } + if m.custom != nil { + fields = append(fields, todo.FieldCustom) + } + if m.customp != nil { + fields = append(fields, todo.FieldCustomp) + } + if m.value != nil { + fields = append(fields, todo.FieldValue) + } + 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 *TodoMutation) Field(name string) (ent.Value, bool) { + switch name { + case todo.FieldCreatedAt: + return m.CreatedAt() + case todo.FieldStatus: + return m.Status() + case todo.FieldPriority: + return m.Priority() + case todo.FieldText: + return m.Text() + case todo.FieldBlob: + return m.Blob() + case todo.FieldCategoryID: + return m.CategoryID() + case todo.FieldInit: + return m.Init() + case todo.FieldCustom: + return m.Custom() + case todo.FieldCustomp: + return m.Customp() + case todo.FieldValue: + return m.Value() + } + 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 *TodoMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case todo.FieldCreatedAt: + return m.OldCreatedAt(ctx) + case todo.FieldStatus: + return m.OldStatus(ctx) + case todo.FieldPriority: + return m.OldPriority(ctx) + case todo.FieldText: + return m.OldText(ctx) + case todo.FieldBlob: + return m.OldBlob(ctx) + case todo.FieldCategoryID: + return m.OldCategoryID(ctx) + case todo.FieldInit: + return m.OldInit(ctx) + case todo.FieldCustom: + return m.OldCustom(ctx) + case todo.FieldCustomp: + return m.OldCustomp(ctx) + case todo.FieldValue: + return m.OldValue(ctx) + } + return nil, fmt.Errorf("unknown Todo 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 *TodoMutation) SetField(name string, value ent.Value) error { + switch name { + case todo.FieldCreatedAt: + v, ok := value.(time.Time) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCreatedAt(v) + return nil + case todo.FieldStatus: + v, ok := value.(todo.Status) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetStatus(v) + return nil + case todo.FieldPriority: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPriority(v) + return nil + case todo.FieldText: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetText(v) + return nil + case todo.FieldBlob: + v, ok := value.([]byte) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetBlob(v) + return nil + case todo.FieldCategoryID: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCategoryID(v) + return nil + case todo.FieldInit: + v, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetInit(v) + return nil + case todo.FieldCustom: + v, ok := value.([]customstruct.Custom) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustom(v) + return nil + case todo.FieldCustomp: + v, ok := value.([]*customstruct.Custom) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetCustomp(v) + return nil + case todo.FieldValue: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetValue(v) + return nil + } + return fmt.Errorf("unknown Todo field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *TodoMutation) AddedFields() []string { + var fields []string + if m.addpriority != nil { + fields = append(fields, todo.FieldPriority) + } + if m.addvalue != nil { + fields = append(fields, todo.FieldValue) + } + 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 *TodoMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case todo.FieldPriority: + return m.AddedPriority() + case todo.FieldValue: + return m.AddedValue() + } + 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 *TodoMutation) AddField(name string, value ent.Value) error { + switch name { + case todo.FieldPriority: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddPriority(v) + return nil + case todo.FieldValue: + v, ok := value.(int) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.AddValue(v) + return nil + } + return fmt.Errorf("unknown Todo numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *TodoMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(todo.FieldBlob) { + fields = append(fields, todo.FieldBlob) + } + if m.FieldCleared(todo.FieldCategoryID) { + fields = append(fields, todo.FieldCategoryID) + } + if m.FieldCleared(todo.FieldInit) { + fields = append(fields, todo.FieldInit) + } + if m.FieldCleared(todo.FieldCustom) { + fields = append(fields, todo.FieldCustom) + } + if m.FieldCleared(todo.FieldCustomp) { + fields = append(fields, todo.FieldCustomp) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *TodoMutation) 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 *TodoMutation) ClearField(name string) error { + switch name { + case todo.FieldBlob: + m.ClearBlob() + return nil + case todo.FieldCategoryID: + m.ClearCategoryID() + return nil + case todo.FieldInit: + m.ClearInit() + return nil + case todo.FieldCustom: + m.ClearCustom() + return nil + case todo.FieldCustomp: + m.ClearCustomp() + return nil + } + return fmt.Errorf("unknown Todo 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 *TodoMutation) ResetField(name string) error { + switch name { + case todo.FieldCreatedAt: + m.ResetCreatedAt() + return nil + case todo.FieldStatus: + m.ResetStatus() + return nil + case todo.FieldPriority: + m.ResetPriority() + return nil + case todo.FieldText: + m.ResetText() + return nil + case todo.FieldBlob: + m.ResetBlob() + return nil + case todo.FieldCategoryID: + m.ResetCategoryID() + return nil + case todo.FieldInit: + m.ResetInit() + return nil + case todo.FieldCustom: + m.ResetCustom() + return nil + case todo.FieldCustomp: + m.ResetCustomp() + return nil + case todo.FieldValue: + m.ResetValue() + return nil + } + return fmt.Errorf("unknown Todo field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *TodoMutation) AddedEdges() []string { + edges := make([]string, 0, 4) + if m.parent != nil { + edges = append(edges, todo.EdgeParent) + } + if m.children != nil { + edges = append(edges, todo.EdgeChildren) + } + if m.category != nil { + edges = append(edges, todo.EdgeCategory) + } + if m.secret != nil { + edges = append(edges, todo.EdgeSecret) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *TodoMutation) AddedIDs(name string) []ent.Value { + switch name { + case todo.EdgeParent: + if id := m.parent; id != nil { + return []ent.Value{*id} + } + case todo.EdgeChildren: + ids := make([]ent.Value, 0, len(m.children)) + for id := range m.children { + ids = append(ids, id) + } + return ids + case todo.EdgeCategory: + if id := m.category; id != nil { + return []ent.Value{*id} + } + case todo.EdgeSecret: + if id := m.secret; id != nil { + return []ent.Value{*id} + } + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *TodoMutation) RemovedEdges() []string { + edges := make([]string, 0, 4) + if m.removedchildren != nil { + edges = append(edges, todo.EdgeChildren) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *TodoMutation) RemovedIDs(name string) []ent.Value { + switch name { + case todo.EdgeChildren: + ids := make([]ent.Value, 0, len(m.removedchildren)) + for id := range m.removedchildren { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *TodoMutation) ClearedEdges() []string { + edges := make([]string, 0, 4) + if m.clearedparent { + edges = append(edges, todo.EdgeParent) + } + if m.clearedchildren { + edges = append(edges, todo.EdgeChildren) + } + if m.clearedcategory { + edges = append(edges, todo.EdgeCategory) + } + if m.clearedsecret { + edges = append(edges, todo.EdgeSecret) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *TodoMutation) EdgeCleared(name string) bool { + switch name { + case todo.EdgeParent: + return m.clearedparent + case todo.EdgeChildren: + return m.clearedchildren + case todo.EdgeCategory: + return m.clearedcategory + case todo.EdgeSecret: + return m.clearedsecret + } + 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 *TodoMutation) ClearEdge(name string) error { + switch name { + case todo.EdgeParent: + m.ClearParent() + return nil + case todo.EdgeCategory: + m.ClearCategory() + return nil + case todo.EdgeSecret: + m.ClearSecret() + return nil + } + return fmt.Errorf("unknown Todo 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 *TodoMutation) ResetEdge(name string) error { + switch name { + case todo.EdgeParent: + m.ResetParent() + return nil + case todo.EdgeChildren: + m.ResetChildren() + return nil + case todo.EdgeCategory: + m.ResetCategory() + return nil + case todo.EdgeSecret: + m.ResetSecret() + return nil + } + return fmt.Errorf("unknown Todo edge %s", name) +} + +// UserMutation represents an operation that mutates the User nodes in the graph. +type UserMutation struct { + config + op Op + typ string + id *int + name *string + username *uuid.UUID + password *string + required_metadata *map[string]interface{} + metadata *map[string]interface{} + clearedFields map[string]struct{} + groups map[int]struct{} + removedgroups map[int]struct{} + clearedgroups bool + friends map[int]struct{} + removedfriends map[int]struct{} + clearedfriends bool + friendships map[int]struct{} + removedfriendships map[int]struct{} + clearedfriendships bool + done bool + oldValue func(context.Context) (*User, error) + predicates []predicate.User +} + +var _ ent.Mutation = (*UserMutation)(nil) + +// userOption allows management of the mutation configuration using functional options. +type userOption func(*UserMutation) + +// newUserMutation creates new mutation for the User entity. +func newUserMutation(c config, op Op, opts ...userOption) *UserMutation { + m := &UserMutation{ + config: c, + op: op, + typ: TypeUser, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withUserID sets the ID field of the mutation. +func withUserID(id int) userOption { + return func(m *UserMutation) { + var ( + err error + once sync.Once + value *User + ) + m.oldValue = func(ctx context.Context) (*User, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().User.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withUser sets the old User of the mutation. +func withUser(node *User) userOption { + return func(m *UserMutation) { + m.oldValue = func(context.Context) (*User, error) { + return node, nil + } + m.id = &node.ID + } +} + +// Client returns a new `ent.Client` from the mutation. If the mutation was +// executed in a transaction (ent.Tx), a transactional client is returned. +func (m UserMutation) Client() *Client { + client := &Client{config: m.config} + client.init() + return client +} + +// Tx returns an `ent.Tx` for mutations that were executed in transactions; +// it returns an error otherwise. +func (m UserMutation) Tx() (*Tx, error) { + if _, ok := m.driver.(*txDriver); !ok { + return nil, errors.New("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 *UserMutation) 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 *UserMutation) 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().User.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetName sets the "name" field. +func (m *UserMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *UserMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *UserMutation) ResetName() { + m.name = nil +} + +// SetUsername sets the "username" field. +func (m *UserMutation) SetUsername(u uuid.UUID) { + m.username = &u +} + +// Username returns the value of the "username" field in the mutation. +func (m *UserMutation) Username() (r uuid.UUID, exists bool) { + v := m.username + if v == nil { + return + } + return *v, true +} + +// OldUsername returns the old "username" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldUsername(ctx context.Context) (v uuid.UUID, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldUsername is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldUsername requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldUsername: %w", err) + } + return oldValue.Username, nil +} + +// ResetUsername resets all changes to the "username" field. +func (m *UserMutation) ResetUsername() { + m.username = nil +} + +// SetPassword sets the "password" field. +func (m *UserMutation) SetPassword(s string) { + m.password = &s +} + +// Password returns the value of the "password" field in the mutation. +func (m *UserMutation) Password() (r string, exists bool) { + v := m.password + if v == nil { + return + } + return *v, true +} + +// OldPassword returns the old "password" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldPassword(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPassword is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPassword requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPassword: %w", err) + } + return oldValue.Password, nil +} + +// ClearPassword clears the value of the "password" field. +func (m *UserMutation) ClearPassword() { + m.password = nil + m.clearedFields[user.FieldPassword] = struct{}{} +} + +// PasswordCleared returns if the "password" field was cleared in this mutation. +func (m *UserMutation) PasswordCleared() bool { + _, ok := m.clearedFields[user.FieldPassword] + return ok +} + +// ResetPassword resets all changes to the "password" field. +func (m *UserMutation) ResetPassword() { + m.password = nil + delete(m.clearedFields, user.FieldPassword) +} + +// SetRequiredMetadata sets the "required_metadata" field. +func (m *UserMutation) SetRequiredMetadata(value map[string]interface{}) { + m.required_metadata = &value +} + +// RequiredMetadata returns the value of the "required_metadata" field in the mutation. +func (m *UserMutation) RequiredMetadata() (r map[string]interface{}, exists bool) { + v := m.required_metadata + if v == nil { + return + } + return *v, true +} + +// OldRequiredMetadata returns the old "required_metadata" field's value of the User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) OldRequiredMetadata(ctx context.Context) (v map[string]interface{}, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldRequiredMetadata is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldRequiredMetadata requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldRequiredMetadata: %w", err) + } + return oldValue.RequiredMetadata, nil +} + +// ResetRequiredMetadata resets all changes to the "required_metadata" field. +func (m *UserMutation) ResetRequiredMetadata() { + m.required_metadata = nil +} + +// SetMetadata sets the "metadata" field. +func (m *UserMutation) SetMetadata(value map[string]interface{}) { + m.metadata = &value +} + +// Metadata returns the value of the "metadata" field in the mutation. +func (m *UserMutation) 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 User entity. +// If the User object wasn't provided to the builder, the object is fetched from the database. +// An error is returned if the mutation operation is not UpdateOne, or the database query fails. +func (m *UserMutation) 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 *UserMutation) ClearMetadata() { + m.metadata = nil + m.clearedFields[user.FieldMetadata] = struct{}{} +} + +// MetadataCleared returns if the "metadata" field was cleared in this mutation. +func (m *UserMutation) MetadataCleared() bool { + _, ok := m.clearedFields[user.FieldMetadata] + return ok +} + +// ResetMetadata resets all changes to the "metadata" field. +func (m *UserMutation) ResetMetadata() { + m.metadata = nil + delete(m.clearedFields, user.FieldMetadata) +} + +// AddGroupIDs adds the "groups" edge to the Group entity by ids. +func (m *UserMutation) AddGroupIDs(ids ...int) { + if m.groups == nil { + m.groups = make(map[int]struct{}) + } + for i := range ids { + m.groups[ids[i]] = struct{}{} + } +} + +// ClearGroups clears the "groups" edge to the Group entity. +func (m *UserMutation) ClearGroups() { + m.clearedgroups = true +} + +// GroupsCleared reports if the "groups" edge to the Group entity was cleared. +func (m *UserMutation) GroupsCleared() bool { + return m.clearedgroups +} + +// RemoveGroupIDs removes the "groups" edge to the Group entity by IDs. +func (m *UserMutation) RemoveGroupIDs(ids ...int) { + if m.removedgroups == nil { + m.removedgroups = make(map[int]struct{}) + } + for i := range ids { + delete(m.groups, ids[i]) + m.removedgroups[ids[i]] = struct{}{} + } +} + +// RemovedGroups returns the removed IDs of the "groups" edge to the Group entity. +func (m *UserMutation) RemovedGroupsIDs() (ids []int) { + for id := range m.removedgroups { + ids = append(ids, id) + } + return +} + +// GroupsIDs returns the "groups" edge IDs in the mutation. +func (m *UserMutation) GroupsIDs() (ids []int) { + for id := range m.groups { + ids = append(ids, id) + } + return +} + +// ResetGroups resets all changes to the "groups" edge. +func (m *UserMutation) ResetGroups() { + m.groups = nil + m.clearedgroups = false + m.removedgroups = nil +} + +// AddFriendIDs adds the "friends" edge to the User entity by ids. +func (m *UserMutation) AddFriendIDs(ids ...int) { + if m.friends == nil { + m.friends = make(map[int]struct{}) + } + for i := range ids { + m.friends[ids[i]] = struct{}{} + } +} + +// ClearFriends clears the "friends" edge to the User entity. +func (m *UserMutation) ClearFriends() { + m.clearedfriends = true +} + +// FriendsCleared reports if the "friends" edge to the User entity was cleared. +func (m *UserMutation) FriendsCleared() bool { + return m.clearedfriends +} + +// RemoveFriendIDs removes the "friends" edge to the User entity by IDs. +func (m *UserMutation) RemoveFriendIDs(ids ...int) { + if m.removedfriends == nil { + m.removedfriends = make(map[int]struct{}) + } + for i := range ids { + delete(m.friends, ids[i]) + m.removedfriends[ids[i]] = struct{}{} + } +} + +// RemovedFriends returns the removed IDs of the "friends" edge to the User entity. +func (m *UserMutation) RemovedFriendsIDs() (ids []int) { + for id := range m.removedfriends { + ids = append(ids, id) + } + return +} + +// FriendsIDs returns the "friends" edge IDs in the mutation. +func (m *UserMutation) FriendsIDs() (ids []int) { + for id := range m.friends { + ids = append(ids, id) + } + return +} + +// ResetFriends resets all changes to the "friends" edge. +func (m *UserMutation) ResetFriends() { + m.friends = nil + m.clearedfriends = false + m.removedfriends = nil +} + +// AddFriendshipIDs adds the "friendships" edge to the Friendship entity by ids. +func (m *UserMutation) AddFriendshipIDs(ids ...int) { + if m.friendships == nil { + m.friendships = make(map[int]struct{}) + } + for i := range ids { + m.friendships[ids[i]] = struct{}{} + } +} + +// ClearFriendships clears the "friendships" edge to the Friendship entity. +func (m *UserMutation) ClearFriendships() { + m.clearedfriendships = true +} + +// FriendshipsCleared reports if the "friendships" edge to the Friendship entity was cleared. +func (m *UserMutation) FriendshipsCleared() bool { + return m.clearedfriendships +} + +// RemoveFriendshipIDs removes the "friendships" edge to the Friendship entity by IDs. +func (m *UserMutation) RemoveFriendshipIDs(ids ...int) { + if m.removedfriendships == nil { + m.removedfriendships = make(map[int]struct{}) + } + for i := range ids { + delete(m.friendships, ids[i]) + m.removedfriendships[ids[i]] = struct{}{} + } +} + +// RemovedFriendships returns the removed IDs of the "friendships" edge to the Friendship entity. +func (m *UserMutation) RemovedFriendshipsIDs() (ids []int) { + for id := range m.removedfriendships { + ids = append(ids, id) + } + return +} + +// FriendshipsIDs returns the "friendships" edge IDs in the mutation. +func (m *UserMutation) FriendshipsIDs() (ids []int) { + for id := range m.friendships { + ids = append(ids, id) + } + return +} + +// ResetFriendships resets all changes to the "friendships" edge. +func (m *UserMutation) ResetFriendships() { + m.friendships = nil + m.clearedfriendships = false + m.removedfriendships = nil +} + +// Where appends a list predicates to the UserMutation builder. +func (m *UserMutation) Where(ps ...predicate.User) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the UserMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *UserMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.User, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *UserMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *UserMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (User). +func (m *UserMutation) Type() string { + return m.typ +} + +// Fields returns all fields that were changed during this mutation. Note that in +// order to get all numeric fields that were incremented/decremented, call +// AddedFields(). +func (m *UserMutation) Fields() []string { + fields := make([]string, 0, 5) + if m.name != nil { + fields = append(fields, user.FieldName) + } + if m.username != nil { + fields = append(fields, user.FieldUsername) + } + if m.password != nil { + fields = append(fields, user.FieldPassword) + } + if m.required_metadata != nil { + fields = append(fields, user.FieldRequiredMetadata) + } + if m.metadata != nil { + fields = append(fields, user.FieldMetadata) + } + 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 *UserMutation) Field(name string) (ent.Value, bool) { + switch name { + case user.FieldName: + return m.Name() + case user.FieldUsername: + return m.Username() + case user.FieldPassword: + return m.Password() + case user.FieldRequiredMetadata: + return m.RequiredMetadata() + case user.FieldMetadata: + return m.Metadata() + } + 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 *UserMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case user.FieldName: + return m.OldName(ctx) + case user.FieldUsername: + return m.OldUsername(ctx) + case user.FieldPassword: + return m.OldPassword(ctx) + case user.FieldRequiredMetadata: + return m.OldRequiredMetadata(ctx) + case user.FieldMetadata: + return m.OldMetadata(ctx) + } + return nil, fmt.Errorf("unknown User field %s", name) +} + +// SetField sets the value of a field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *UserMutation) SetField(name string, value ent.Value) error { + switch name { + case user.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + case user.FieldUsername: + v, ok := value.(uuid.UUID) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetUsername(v) + return nil + case user.FieldPassword: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPassword(v) + return nil + case user.FieldRequiredMetadata: + v, ok := value.(map[string]interface{}) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetRequiredMetadata(v) + return nil + case user.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 + } + return fmt.Errorf("unknown User field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *UserMutation) AddedFields() []string { + return nil +} + +// AddedField returns the numeric value that was incremented/decremented on a field +// with the given name. The second boolean return value indicates that this field +// was not set, or was not defined in the schema. +func (m *UserMutation) AddedField(name string) (ent.Value, bool) { + return nil, false +} + +// AddField adds the value to the field with the given name. It returns an error if +// the field is not defined in the schema, or if the type mismatched the field +// type. +func (m *UserMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown User numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *UserMutation) ClearedFields() []string { + var fields []string + if m.FieldCleared(user.FieldPassword) { + fields = append(fields, user.FieldPassword) + } + if m.FieldCleared(user.FieldMetadata) { + fields = append(fields, user.FieldMetadata) + } + return fields +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *UserMutation) FieldCleared(name string) bool { + _, ok := m.clearedFields[name] + return ok +} + +// ClearField clears the value of the field with the given name. It returns an +// error if the field is not defined in the schema. +func (m *UserMutation) ClearField(name string) error { + switch name { + case user.FieldPassword: + m.ClearPassword() + return nil + case user.FieldMetadata: + m.ClearMetadata() + return nil + } + return fmt.Errorf("unknown User nullable field %s", name) +} + +// ResetField resets all changes in the mutation for the field with the given name. +// It returns an error if the field is not defined in the schema. +func (m *UserMutation) ResetField(name string) error { + switch name { + case user.FieldName: + m.ResetName() + return nil + case user.FieldUsername: + m.ResetUsername() + return nil + case user.FieldPassword: + m.ResetPassword() + return nil + case user.FieldRequiredMetadata: + m.ResetRequiredMetadata() + return nil + case user.FieldMetadata: + m.ResetMetadata() + return nil + } + return fmt.Errorf("unknown User field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *UserMutation) AddedEdges() []string { + edges := make([]string, 0, 3) + if m.groups != nil { + edges = append(edges, user.EdgeGroups) + } + if m.friends != nil { + edges = append(edges, user.EdgeFriends) + } + if m.friendships != nil { + edges = append(edges, user.EdgeFriendships) + } + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *UserMutation) AddedIDs(name string) []ent.Value { + switch name { + case user.EdgeGroups: + ids := make([]ent.Value, 0, len(m.groups)) + for id := range m.groups { + ids = append(ids, id) + } + return ids + case user.EdgeFriends: + ids := make([]ent.Value, 0, len(m.friends)) + for id := range m.friends { + ids = append(ids, id) + } + return ids + case user.EdgeFriendships: + ids := make([]ent.Value, 0, len(m.friendships)) + for id := range m.friendships { + ids = append(ids, id) + } + return ids + } + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *UserMutation) RemovedEdges() []string { + edges := make([]string, 0, 3) + if m.removedgroups != nil { + edges = append(edges, user.EdgeGroups) + } + if m.removedfriends != nil { + edges = append(edges, user.EdgeFriends) + } + if m.removedfriendships != nil { + edges = append(edges, user.EdgeFriendships) + } + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *UserMutation) RemovedIDs(name string) []ent.Value { + switch name { + case user.EdgeGroups: + ids := make([]ent.Value, 0, len(m.removedgroups)) + for id := range m.removedgroups { + ids = append(ids, id) + } + return ids + case user.EdgeFriends: + ids := make([]ent.Value, 0, len(m.removedfriends)) + for id := range m.removedfriends { + ids = append(ids, id) + } + return ids + case user.EdgeFriendships: + ids := make([]ent.Value, 0, len(m.removedfriendships)) + for id := range m.removedfriendships { + ids = append(ids, id) + } + return ids + } + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *UserMutation) ClearedEdges() []string { + edges := make([]string, 0, 3) + if m.clearedgroups { + edges = append(edges, user.EdgeGroups) + } + if m.clearedfriends { + edges = append(edges, user.EdgeFriends) + } + if m.clearedfriendships { + edges = append(edges, user.EdgeFriendships) + } + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *UserMutation) EdgeCleared(name string) bool { + switch name { + case user.EdgeGroups: + return m.clearedgroups + case user.EdgeFriends: + return m.clearedfriends + case user.EdgeFriendships: + return m.clearedfriendships + } + 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 *UserMutation) ClearEdge(name string) error { + switch name { + } + return fmt.Errorf("unknown User unique edge %s", name) +} + +// ResetEdge resets all changes to the edge with the given name in this mutation. +// It returns an error if the edge is not defined in the schema. +func (m *UserMutation) ResetEdge(name string) error { + switch name { + case user.EdgeGroups: + m.ResetGroups() + return nil + case user.EdgeFriends: + m.ResetFriends() + return nil + case user.EdgeFriendships: + m.ResetFriendships() + return nil + } + return fmt.Errorf("unknown User edge %s", name) +} + +// VerySecretMutation represents an operation that mutates the VerySecret nodes in the graph. +type VerySecretMutation struct { + config + op Op + typ string + id *int + password *string + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*VerySecret, error) + predicates []predicate.VerySecret +} + +var _ ent.Mutation = (*VerySecretMutation)(nil) + +// verysecretOption allows management of the mutation configuration using functional options. +type verysecretOption func(*VerySecretMutation) + +// newVerySecretMutation creates new mutation for the VerySecret entity. +func newVerySecretMutation(c config, op Op, opts ...verysecretOption) *VerySecretMutation { + m := &VerySecretMutation{ + config: c, + op: op, + typ: TypeVerySecret, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withVerySecretID sets the ID field of the mutation. +func withVerySecretID(id int) verysecretOption { + return func(m *VerySecretMutation) { + var ( + err error + once sync.Once + value *VerySecret + ) + m.oldValue = func(ctx context.Context) (*VerySecret, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().VerySecret.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withVerySecret sets the old VerySecret of the mutation. +func withVerySecret(node *VerySecret) verysecretOption { + return func(m *VerySecretMutation) { + m.oldValue = func(context.Context) (*VerySecret, 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 VerySecretMutation) 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 VerySecretMutation) 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 *VerySecretMutation) 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 *VerySecretMutation) 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().VerySecret.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetPassword sets the "password" field. +func (m *VerySecretMutation) SetPassword(s string) { + m.password = &s +} + +// Password returns the value of the "password" field in the mutation. +func (m *VerySecretMutation) Password() (r string, exists bool) { + v := m.password + if v == nil { + return + } + return *v, true +} + +// OldPassword returns the old "password" field's value of the VerySecret entity. +// If the VerySecret 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 *VerySecretMutation) OldPassword(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldPassword is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldPassword requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldPassword: %w", err) + } + return oldValue.Password, nil +} + +// ResetPassword resets all changes to the "password" field. +func (m *VerySecretMutation) ResetPassword() { + m.password = nil +} + +// Where appends a list predicates to the VerySecretMutation builder. +func (m *VerySecretMutation) Where(ps ...predicate.VerySecret) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the VerySecretMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *VerySecretMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.VerySecret, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *VerySecretMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *VerySecretMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (VerySecret). +func (m *VerySecretMutation) 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 *VerySecretMutation) Fields() []string { + fields := make([]string, 0, 1) + if m.password != nil { + fields = append(fields, verysecret.FieldPassword) + } + 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 *VerySecretMutation) Field(name string) (ent.Value, bool) { + switch name { + case verysecret.FieldPassword: + return m.Password() + } + 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 *VerySecretMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case verysecret.FieldPassword: + return m.OldPassword(ctx) + } + return nil, fmt.Errorf("unknown VerySecret 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 *VerySecretMutation) SetField(name string, value ent.Value) error { + switch name { + case verysecret.FieldPassword: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetPassword(v) + return nil + } + return fmt.Errorf("unknown VerySecret field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *VerySecretMutation) 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 *VerySecretMutation) 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 *VerySecretMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown VerySecret numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *VerySecretMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *VerySecretMutation) 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 *VerySecretMutation) ClearField(name string) error { + return fmt.Errorf("unknown VerySecret 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 *VerySecretMutation) ResetField(name string) error { + switch name { + case verysecret.FieldPassword: + m.ResetPassword() + return nil + } + return fmt.Errorf("unknown VerySecret field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *VerySecretMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *VerySecretMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *VerySecretMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *VerySecretMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *VerySecretMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *VerySecretMutation) EdgeCleared(name string) bool { + 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 *VerySecretMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown VerySecret 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 *VerySecretMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown VerySecret edge %s", name) +} + +// WorkspaceMutation represents an operation that mutates the Workspace nodes in the graph. +type WorkspaceMutation struct { + config + op Op + typ string + id *int + name *string + clearedFields map[string]struct{} + done bool + oldValue func(context.Context) (*Workspace, error) + predicates []predicate.Workspace +} + +var _ ent.Mutation = (*WorkspaceMutation)(nil) + +// workspaceOption allows management of the mutation configuration using functional options. +type workspaceOption func(*WorkspaceMutation) + +// newWorkspaceMutation creates new mutation for the Workspace entity. +func newWorkspaceMutation(c config, op Op, opts ...workspaceOption) *WorkspaceMutation { + m := &WorkspaceMutation{ + config: c, + op: op, + typ: TypeWorkspace, + clearedFields: make(map[string]struct{}), + } + for _, opt := range opts { + opt(m) + } + return m +} + +// withWorkspaceID sets the ID field of the mutation. +func withWorkspaceID(id int) workspaceOption { + return func(m *WorkspaceMutation) { + var ( + err error + once sync.Once + value *Workspace + ) + m.oldValue = func(ctx context.Context) (*Workspace, error) { + once.Do(func() { + if m.done { + err = errors.New("querying old values post mutation is not allowed") + } else { + value, err = m.Client().Workspace.Get(ctx, id) + } + }) + return value, err + } + m.id = &id + } +} + +// withWorkspace sets the old Workspace of the mutation. +func withWorkspace(node *Workspace) workspaceOption { + return func(m *WorkspaceMutation) { + m.oldValue = func(context.Context) (*Workspace, 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 WorkspaceMutation) 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 WorkspaceMutation) 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 *WorkspaceMutation) 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 *WorkspaceMutation) 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().Workspace.Query().Where(m.predicates...).IDs(ctx) + default: + return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) + } +} + +// SetName sets the "name" field. +func (m *WorkspaceMutation) SetName(s string) { + m.name = &s +} + +// Name returns the value of the "name" field in the mutation. +func (m *WorkspaceMutation) Name() (r string, exists bool) { + v := m.name + if v == nil { + return + } + return *v, true +} + +// OldName returns the old "name" field's value of the Workspace entity. +// If the Workspace 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 *WorkspaceMutation) OldName(ctx context.Context) (v string, err error) { + if !m.op.Is(OpUpdateOne) { + return v, errors.New("OldName is only allowed on UpdateOne operations") + } + if m.id == nil || m.oldValue == nil { + return v, errors.New("OldName requires an ID field in the mutation") + } + oldValue, err := m.oldValue(ctx) + if err != nil { + return v, fmt.Errorf("querying old value for OldName: %w", err) + } + return oldValue.Name, nil +} + +// ResetName resets all changes to the "name" field. +func (m *WorkspaceMutation) ResetName() { + m.name = nil +} + +// Where appends a list predicates to the WorkspaceMutation builder. +func (m *WorkspaceMutation) Where(ps ...predicate.Workspace) { + m.predicates = append(m.predicates, ps...) +} + +// WhereP appends storage-level predicates to the WorkspaceMutation builder. Using this method, +// users can use type-assertion to append predicates that do not depend on any generated package. +func (m *WorkspaceMutation) WhereP(ps ...func(*sql.Selector)) { + p := make([]predicate.Workspace, len(ps)) + for i := range ps { + p[i] = ps[i] + } + m.Where(p...) +} + +// Op returns the operation name. +func (m *WorkspaceMutation) Op() Op { + return m.op +} + +// SetOp allows setting the mutation operation. +func (m *WorkspaceMutation) SetOp(op Op) { + m.op = op +} + +// Type returns the node type of this mutation (Workspace). +func (m *WorkspaceMutation) 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 *WorkspaceMutation) Fields() []string { + fields := make([]string, 0, 1) + if m.name != nil { + fields = append(fields, workspace.FieldName) + } + 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 *WorkspaceMutation) Field(name string) (ent.Value, bool) { + switch name { + case workspace.FieldName: + return m.Name() + } + 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 *WorkspaceMutation) OldField(ctx context.Context, name string) (ent.Value, error) { + switch name { + case workspace.FieldName: + return m.OldName(ctx) + } + return nil, fmt.Errorf("unknown Workspace 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 *WorkspaceMutation) SetField(name string, value ent.Value) error { + switch name { + case workspace.FieldName: + v, ok := value.(string) + if !ok { + return fmt.Errorf("unexpected type %T for field %s", value, name) + } + m.SetName(v) + return nil + } + return fmt.Errorf("unknown Workspace field %s", name) +} + +// AddedFields returns all numeric fields that were incremented/decremented during +// this mutation. +func (m *WorkspaceMutation) 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 *WorkspaceMutation) 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 *WorkspaceMutation) AddField(name string, value ent.Value) error { + switch name { + } + return fmt.Errorf("unknown Workspace numeric field %s", name) +} + +// ClearedFields returns all nullable fields that were cleared during this +// mutation. +func (m *WorkspaceMutation) ClearedFields() []string { + return nil +} + +// FieldCleared returns a boolean indicating if a field with the given name was +// cleared in this mutation. +func (m *WorkspaceMutation) 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 *WorkspaceMutation) ClearField(name string) error { + return fmt.Errorf("unknown Workspace 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 *WorkspaceMutation) ResetField(name string) error { + switch name { + case workspace.FieldName: + m.ResetName() + return nil + } + return fmt.Errorf("unknown Workspace field %s", name) +} + +// AddedEdges returns all edge names that were set/added in this mutation. +func (m *WorkspaceMutation) AddedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// AddedIDs returns all IDs (to other nodes) that were added for the given edge +// name in this mutation. +func (m *WorkspaceMutation) AddedIDs(name string) []ent.Value { + return nil +} + +// RemovedEdges returns all edge names that were removed in this mutation. +func (m *WorkspaceMutation) RemovedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with +// the given name in this mutation. +func (m *WorkspaceMutation) RemovedIDs(name string) []ent.Value { + return nil +} + +// ClearedEdges returns all edge names that were cleared in this mutation. +func (m *WorkspaceMutation) ClearedEdges() []string { + edges := make([]string, 0, 0) + return edges +} + +// EdgeCleared returns a boolean which indicates if the edge with the given name +// was cleared in this mutation. +func (m *WorkspaceMutation) EdgeCleared(name string) bool { + 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 *WorkspaceMutation) ClearEdge(name string) error { + return fmt.Errorf("unknown Workspace 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 *WorkspaceMutation) ResetEdge(name string) error { + return fmt.Errorf("unknown Workspace edge %s", name) +} diff --git a/entgql/internal/todoglobalid/ent/onetomany.go b/entgql/internal/todoglobalid/ent/onetomany.go new file mode 100644 index 000000000..37e85f2e0 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/onetomany.go @@ -0,0 +1,211 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/onetomany" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// OneToMany is the model entity for the OneToMany schema. +type OneToMany struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Field2 holds the value of the "field2" field. + Field2 string `json:"field2,omitempty"` + // ParentID holds the value of the "parent_id" field. + ParentID int `json:"parent_id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the OneToManyQuery when eager-loading is set. + Edges OneToManyEdges `json:"edges"` + selectValues sql.SelectValues +} + +// OneToManyEdges holds the relations/edges for other nodes in the graph. +type OneToManyEdges struct { + // Parent holds the value of the parent edge. + Parent *OneToMany `json:"parent,omitempty"` + // Children holds the value of the children edge. + Children []*OneToMany `json:"children,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [2]bool + // totalCount holds the count of the edges above. + totalCount [2]map[string]int + + namedChildren map[string][]*OneToMany +} + +// ParentOrErr returns the Parent value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e OneToManyEdges) ParentOrErr() (*OneToMany, error) { + if e.Parent != nil { + return e.Parent, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: onetomany.Label} + } + return nil, &NotLoadedError{edge: "parent"} +} + +// ChildrenOrErr returns the Children value or an error if the edge +// was not loaded in eager-loading. +func (e OneToManyEdges) ChildrenOrErr() ([]*OneToMany, error) { + if e.loadedTypes[1] { + return e.Children, nil + } + return nil, &NotLoadedError{edge: "children"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*OneToMany) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case onetomany.FieldID, onetomany.FieldParentID: + values[i] = new(sql.NullInt64) + case onetomany.FieldName, onetomany.FieldField2: + 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 OneToMany fields. +func (otm *OneToMany) 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 onetomany.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + otm.ID = int(value.Int64) + case onetomany.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + otm.Name = value.String + } + case onetomany.FieldField2: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field field2", values[i]) + } else if value.Valid { + otm.Field2 = value.String + } + case onetomany.FieldParentID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field parent_id", values[i]) + } else if value.Valid { + otm.ParentID = int(value.Int64) + } + default: + otm.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the OneToMany. +// This includes values selected through modifiers, order, etc. +func (otm *OneToMany) Value(name string) (ent.Value, error) { + return otm.selectValues.Get(name) +} + +// QueryParent queries the "parent" edge of the OneToMany entity. +func (otm *OneToMany) QueryParent() *OneToManyQuery { + return NewOneToManyClient(otm.config).QueryParent(otm) +} + +// QueryChildren queries the "children" edge of the OneToMany entity. +func (otm *OneToMany) QueryChildren() *OneToManyQuery { + return NewOneToManyClient(otm.config).QueryChildren(otm) +} + +// Update returns a builder for updating this OneToMany. +// Note that you need to call OneToMany.Unwrap() before calling this method if this OneToMany +// was returned from a transaction, and the transaction was committed or rolled back. +func (otm *OneToMany) Update() *OneToManyUpdateOne { + return NewOneToManyClient(otm.config).UpdateOne(otm) +} + +// Unwrap unwraps the OneToMany 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 (otm *OneToMany) Unwrap() *OneToMany { + _tx, ok := otm.config.driver.(*txDriver) + if !ok { + panic("ent: OneToMany is not a transactional entity") + } + otm.config.driver = _tx.drv + return otm +} + +// String implements the fmt.Stringer. +func (otm *OneToMany) String() string { + var builder strings.Builder + builder.WriteString("OneToMany(") + builder.WriteString(fmt.Sprintf("id=%v, ", otm.ID)) + builder.WriteString("name=") + builder.WriteString(otm.Name) + builder.WriteString(", ") + builder.WriteString("field2=") + builder.WriteString(otm.Field2) + builder.WriteString(", ") + builder.WriteString("parent_id=") + builder.WriteString(fmt.Sprintf("%v", otm.ParentID)) + builder.WriteByte(')') + return builder.String() +} + +// NamedChildren returns the Children named value or an error if the edge was not +// loaded in eager-loading with this name. +func (otm *OneToMany) NamedChildren(name string) ([]*OneToMany, error) { + if otm.Edges.namedChildren == nil { + return nil, &NotLoadedError{edge: name} + } + nodes, ok := otm.Edges.namedChildren[name] + if !ok { + return nil, &NotLoadedError{edge: name} + } + return nodes, nil +} + +func (otm *OneToMany) appendNamedChildren(name string, edges ...*OneToMany) { + if otm.Edges.namedChildren == nil { + otm.Edges.namedChildren = make(map[string][]*OneToMany) + } + if len(edges) == 0 { + otm.Edges.namedChildren[name] = []*OneToMany{} + } else { + otm.Edges.namedChildren[name] = append(otm.Edges.namedChildren[name], edges...) + } +} + +// OneToManies is a parsable slice of OneToMany. +type OneToManies []*OneToMany diff --git a/entgql/internal/todoglobalid/ent/onetomany/onetomany.go b/entgql/internal/todoglobalid/ent/onetomany/onetomany.go new file mode 100644 index 000000000..7d74bf430 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/onetomany/onetomany.go @@ -0,0 +1,130 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package onetomany + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the onetomany type in the database. + Label = "one_to_many" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldField2 holds the string denoting the field2 field in the database. + FieldField2 = "field2" + // FieldParentID holds the string denoting the parent_id field in the database. + FieldParentID = "parent_id" + // EdgeParent holds the string denoting the parent edge name in mutations. + EdgeParent = "parent" + // EdgeChildren holds the string denoting the children edge name in mutations. + EdgeChildren = "children" + // Table holds the table name of the onetomany in the database. + Table = "one_to_manies" + // ParentTable is the table that holds the parent relation/edge. + ParentTable = "one_to_manies" + // ParentColumn is the table column denoting the parent relation/edge. + ParentColumn = "parent_id" + // ChildrenTable is the table that holds the children relation/edge. + ChildrenTable = "one_to_manies" + // ChildrenColumn is the table column denoting the children relation/edge. + ChildrenColumn = "parent_id" +) + +// Columns holds all SQL columns for onetomany fields. +var Columns = []string{ + FieldID, + FieldName, + FieldField2, + FieldParentID, +} + +// 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 ( + // NameValidator is a validator for the "name" field. It is called by the builders before save. + NameValidator func(string) error +) + +// OrderOption defines the ordering options for the OneToMany 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() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByField2 orders the results by the field2 field. +func ByField2(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldField2, opts...).ToFunc() +} + +// ByParentID orders the results by the parent_id field. +func ByParentID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldParentID, opts...).ToFunc() +} + +// ByParentField orders the results by parent field. +func ByParentField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newParentStep(), sql.OrderByField(field, opts...)) + } +} + +// ByChildrenCount orders the results by children count. +func ByChildrenCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newChildrenStep(), opts...) + } +} + +// ByChildren orders the results by children terms. +func ByChildren(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newChildrenStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newParentStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ParentTable, ParentColumn), + ) +} +func newChildrenStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ChildrenTable, ChildrenColumn), + ) +} diff --git a/entgql/internal/todoglobalid/ent/onetomany/where.go b/entgql/internal/todoglobalid/ent/onetomany/where.go new file mode 100644 index 000000000..262616d80 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/onetomany/where.go @@ -0,0 +1,314 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package onetomany + +import ( + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.OneToMany { + return predicate.OneToMany(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.OneToMany { + return predicate.OneToMany(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.OneToMany { + return predicate.OneToMany(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.OneToMany { + return predicate.OneToMany(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.OneToMany { + return predicate.OneToMany(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.OneToMany { + return predicate.OneToMany(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.OneToMany { + return predicate.OneToMany(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.OneToMany { + return predicate.OneToMany(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.OneToMany { + return predicate.OneToMany(sql.FieldLTE(FieldID, id)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.OneToMany { + return predicate.OneToMany(sql.FieldEQ(FieldName, v)) +} + +// Field2 applies equality check predicate on the "field2" field. It's identical to Field2EQ. +func Field2(v string) predicate.OneToMany { + return predicate.OneToMany(sql.FieldEQ(FieldField2, v)) +} + +// ParentID applies equality check predicate on the "parent_id" field. It's identical to ParentIDEQ. +func ParentID(v int) predicate.OneToMany { + return predicate.OneToMany(sql.FieldEQ(FieldParentID, v)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.OneToMany { + return predicate.OneToMany(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.OneToMany { + return predicate.OneToMany(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.OneToMany { + return predicate.OneToMany(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.OneToMany { + return predicate.OneToMany(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.OneToMany { + return predicate.OneToMany(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.OneToMany { + return predicate.OneToMany(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.OneToMany { + return predicate.OneToMany(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.OneToMany { + return predicate.OneToMany(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.OneToMany { + return predicate.OneToMany(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.OneToMany { + return predicate.OneToMany(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.OneToMany { + return predicate.OneToMany(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.OneToMany { + return predicate.OneToMany(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.OneToMany { + return predicate.OneToMany(sql.FieldContainsFold(FieldName, v)) +} + +// Field2EQ applies the EQ predicate on the "field2" field. +func Field2EQ(v string) predicate.OneToMany { + return predicate.OneToMany(sql.FieldEQ(FieldField2, v)) +} + +// Field2NEQ applies the NEQ predicate on the "field2" field. +func Field2NEQ(v string) predicate.OneToMany { + return predicate.OneToMany(sql.FieldNEQ(FieldField2, v)) +} + +// Field2In applies the In predicate on the "field2" field. +func Field2In(vs ...string) predicate.OneToMany { + return predicate.OneToMany(sql.FieldIn(FieldField2, vs...)) +} + +// Field2NotIn applies the NotIn predicate on the "field2" field. +func Field2NotIn(vs ...string) predicate.OneToMany { + return predicate.OneToMany(sql.FieldNotIn(FieldField2, vs...)) +} + +// Field2GT applies the GT predicate on the "field2" field. +func Field2GT(v string) predicate.OneToMany { + return predicate.OneToMany(sql.FieldGT(FieldField2, v)) +} + +// Field2GTE applies the GTE predicate on the "field2" field. +func Field2GTE(v string) predicate.OneToMany { + return predicate.OneToMany(sql.FieldGTE(FieldField2, v)) +} + +// Field2LT applies the LT predicate on the "field2" field. +func Field2LT(v string) predicate.OneToMany { + return predicate.OneToMany(sql.FieldLT(FieldField2, v)) +} + +// Field2LTE applies the LTE predicate on the "field2" field. +func Field2LTE(v string) predicate.OneToMany { + return predicate.OneToMany(sql.FieldLTE(FieldField2, v)) +} + +// Field2Contains applies the Contains predicate on the "field2" field. +func Field2Contains(v string) predicate.OneToMany { + return predicate.OneToMany(sql.FieldContains(FieldField2, v)) +} + +// Field2HasPrefix applies the HasPrefix predicate on the "field2" field. +func Field2HasPrefix(v string) predicate.OneToMany { + return predicate.OneToMany(sql.FieldHasPrefix(FieldField2, v)) +} + +// Field2HasSuffix applies the HasSuffix predicate on the "field2" field. +func Field2HasSuffix(v string) predicate.OneToMany { + return predicate.OneToMany(sql.FieldHasSuffix(FieldField2, v)) +} + +// Field2IsNil applies the IsNil predicate on the "field2" field. +func Field2IsNil() predicate.OneToMany { + return predicate.OneToMany(sql.FieldIsNull(FieldField2)) +} + +// Field2NotNil applies the NotNil predicate on the "field2" field. +func Field2NotNil() predicate.OneToMany { + return predicate.OneToMany(sql.FieldNotNull(FieldField2)) +} + +// Field2EqualFold applies the EqualFold predicate on the "field2" field. +func Field2EqualFold(v string) predicate.OneToMany { + return predicate.OneToMany(sql.FieldEqualFold(FieldField2, v)) +} + +// Field2ContainsFold applies the ContainsFold predicate on the "field2" field. +func Field2ContainsFold(v string) predicate.OneToMany { + return predicate.OneToMany(sql.FieldContainsFold(FieldField2, v)) +} + +// ParentIDEQ applies the EQ predicate on the "parent_id" field. +func ParentIDEQ(v int) predicate.OneToMany { + return predicate.OneToMany(sql.FieldEQ(FieldParentID, v)) +} + +// ParentIDNEQ applies the NEQ predicate on the "parent_id" field. +func ParentIDNEQ(v int) predicate.OneToMany { + return predicate.OneToMany(sql.FieldNEQ(FieldParentID, v)) +} + +// ParentIDIn applies the In predicate on the "parent_id" field. +func ParentIDIn(vs ...int) predicate.OneToMany { + return predicate.OneToMany(sql.FieldIn(FieldParentID, vs...)) +} + +// ParentIDNotIn applies the NotIn predicate on the "parent_id" field. +func ParentIDNotIn(vs ...int) predicate.OneToMany { + return predicate.OneToMany(sql.FieldNotIn(FieldParentID, vs...)) +} + +// ParentIDIsNil applies the IsNil predicate on the "parent_id" field. +func ParentIDIsNil() predicate.OneToMany { + return predicate.OneToMany(sql.FieldIsNull(FieldParentID)) +} + +// ParentIDNotNil applies the NotNil predicate on the "parent_id" field. +func ParentIDNotNil() predicate.OneToMany { + return predicate.OneToMany(sql.FieldNotNull(FieldParentID)) +} + +// HasParent applies the HasEdge predicate on the "parent" edge. +func HasParent() predicate.OneToMany { + return predicate.OneToMany(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ParentTable, ParentColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasParentWith applies the HasEdge predicate on the "parent" edge with a given conditions (other predicates). +func HasParentWith(preds ...predicate.OneToMany) predicate.OneToMany { + return predicate.OneToMany(func(s *sql.Selector) { + step := newParentStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasChildren applies the HasEdge predicate on the "children" edge. +func HasChildren() predicate.OneToMany { + return predicate.OneToMany(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ChildrenTable, ChildrenColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasChildrenWith applies the HasEdge predicate on the "children" edge with a given conditions (other predicates). +func HasChildrenWith(preds ...predicate.OneToMany) predicate.OneToMany { + return predicate.OneToMany(func(s *sql.Selector) { + step := newChildrenStep() + 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.OneToMany) predicate.OneToMany { + return predicate.OneToMany(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.OneToMany) predicate.OneToMany { + return predicate.OneToMany(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.OneToMany) predicate.OneToMany { + return predicate.OneToMany(sql.NotPredicates(p)) +} diff --git a/entgql/internal/todoglobalid/ent/onetomany_create.go b/entgql/internal/todoglobalid/ent/onetomany_create.go new file mode 100644 index 000000000..6dc632923 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/onetomany_create.go @@ -0,0 +1,287 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/onetomany" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// OneToManyCreate is the builder for creating a OneToMany entity. +type OneToManyCreate struct { + config + mutation *OneToManyMutation + hooks []Hook +} + +// SetName sets the "name" field. +func (otmc *OneToManyCreate) SetName(s string) *OneToManyCreate { + otmc.mutation.SetName(s) + return otmc +} + +// SetField2 sets the "field2" field. +func (otmc *OneToManyCreate) SetField2(s string) *OneToManyCreate { + otmc.mutation.SetField2(s) + return otmc +} + +// SetNillableField2 sets the "field2" field if the given value is not nil. +func (otmc *OneToManyCreate) SetNillableField2(s *string) *OneToManyCreate { + if s != nil { + otmc.SetField2(*s) + } + return otmc +} + +// SetParentID sets the "parent_id" field. +func (otmc *OneToManyCreate) SetParentID(i int) *OneToManyCreate { + otmc.mutation.SetParentID(i) + return otmc +} + +// SetNillableParentID sets the "parent_id" field if the given value is not nil. +func (otmc *OneToManyCreate) SetNillableParentID(i *int) *OneToManyCreate { + if i != nil { + otmc.SetParentID(*i) + } + return otmc +} + +// SetParent sets the "parent" edge to the OneToMany entity. +func (otmc *OneToManyCreate) SetParent(o *OneToMany) *OneToManyCreate { + return otmc.SetParentID(o.ID) +} + +// AddChildIDs adds the "children" edge to the OneToMany entity by IDs. +func (otmc *OneToManyCreate) AddChildIDs(ids ...int) *OneToManyCreate { + otmc.mutation.AddChildIDs(ids...) + return otmc +} + +// AddChildren adds the "children" edges to the OneToMany entity. +func (otmc *OneToManyCreate) AddChildren(o ...*OneToMany) *OneToManyCreate { + ids := make([]int, len(o)) + for i := range o { + ids[i] = o[i].ID + } + return otmc.AddChildIDs(ids...) +} + +// Mutation returns the OneToManyMutation object of the builder. +func (otmc *OneToManyCreate) Mutation() *OneToManyMutation { + return otmc.mutation +} + +// Save creates the OneToMany in the database. +func (otmc *OneToManyCreate) Save(ctx context.Context) (*OneToMany, error) { + return withHooks(ctx, otmc.sqlSave, otmc.mutation, otmc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (otmc *OneToManyCreate) SaveX(ctx context.Context) *OneToMany { + v, err := otmc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (otmc *OneToManyCreate) Exec(ctx context.Context) error { + _, err := otmc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (otmc *OneToManyCreate) ExecX(ctx context.Context) { + if err := otmc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (otmc *OneToManyCreate) check() error { + if _, ok := otmc.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "OneToMany.name"`)} + } + if v, ok := otmc.mutation.Name(); ok { + if err := onetomany.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "OneToMany.name": %w`, err)} + } + } + return nil +} + +func (otmc *OneToManyCreate) sqlSave(ctx context.Context) (*OneToMany, error) { + if err := otmc.check(); err != nil { + return nil, err + } + _node, _spec := otmc.createSpec() + if err := sqlgraph.CreateNode(ctx, otmc.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) + otmc.mutation.id = &_node.ID + otmc.mutation.done = true + return _node, nil +} + +func (otmc *OneToManyCreate) createSpec() (*OneToMany, *sqlgraph.CreateSpec) { + var ( + _node = &OneToMany{config: otmc.config} + _spec = sqlgraph.NewCreateSpec(onetomany.Table, sqlgraph.NewFieldSpec(onetomany.FieldID, field.TypeInt)) + ) + if value, ok := otmc.mutation.Name(); ok { + _spec.SetField(onetomany.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := otmc.mutation.Field2(); ok { + _spec.SetField(onetomany.FieldField2, field.TypeString, value) + _node.Field2 = value + } + if nodes := otmc.mutation.ParentIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: onetomany.ParentTable, + Columns: []string{onetomany.ParentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(onetomany.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.ParentID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := otmc.mutation.ChildrenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: onetomany.ChildrenTable, + Columns: []string{onetomany.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(onetomany.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// OneToManyCreateBulk is the builder for creating many OneToMany entities in bulk. +type OneToManyCreateBulk struct { + config + err error + builders []*OneToManyCreate +} + +// Save creates the OneToMany entities in the database. +func (otmcb *OneToManyCreateBulk) Save(ctx context.Context) ([]*OneToMany, error) { + if otmcb.err != nil { + return nil, otmcb.err + } + specs := make([]*sqlgraph.CreateSpec, len(otmcb.builders)) + nodes := make([]*OneToMany, len(otmcb.builders)) + mutators := make([]Mutator, len(otmcb.builders)) + for i := range otmcb.builders { + func(i int, root context.Context) { + builder := otmcb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*OneToManyMutation) + 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, otmcb.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, otmcb.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, otmcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (otmcb *OneToManyCreateBulk) SaveX(ctx context.Context) []*OneToMany { + v, err := otmcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (otmcb *OneToManyCreateBulk) Exec(ctx context.Context) error { + _, err := otmcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (otmcb *OneToManyCreateBulk) ExecX(ctx context.Context) { + if err := otmcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entgql/internal/todoglobalid/ent/onetomany_delete.go b/entgql/internal/todoglobalid/ent/onetomany_delete.go new file mode 100644 index 000000000..987d882e4 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/onetomany_delete.go @@ -0,0 +1,102 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/onetomany" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// OneToManyDelete is the builder for deleting a OneToMany entity. +type OneToManyDelete struct { + config + hooks []Hook + mutation *OneToManyMutation +} + +// Where appends a list predicates to the OneToManyDelete builder. +func (otmd *OneToManyDelete) Where(ps ...predicate.OneToMany) *OneToManyDelete { + otmd.mutation.Where(ps...) + return otmd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (otmd *OneToManyDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, otmd.sqlExec, otmd.mutation, otmd.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (otmd *OneToManyDelete) ExecX(ctx context.Context) int { + n, err := otmd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (otmd *OneToManyDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(onetomany.Table, sqlgraph.NewFieldSpec(onetomany.FieldID, field.TypeInt)) + if ps := otmd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, otmd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + otmd.mutation.done = true + return affected, err +} + +// OneToManyDeleteOne is the builder for deleting a single OneToMany entity. +type OneToManyDeleteOne struct { + otmd *OneToManyDelete +} + +// Where appends a list predicates to the OneToManyDelete builder. +func (otmdo *OneToManyDeleteOne) Where(ps ...predicate.OneToMany) *OneToManyDeleteOne { + otmdo.otmd.mutation.Where(ps...) + return otmdo +} + +// Exec executes the deletion query. +func (otmdo *OneToManyDeleteOne) Exec(ctx context.Context) error { + n, err := otmdo.otmd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{onetomany.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (otmdo *OneToManyDeleteOne) ExecX(ctx context.Context) { + if err := otmdo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entgql/internal/todoglobalid/ent/onetomany_query.go b/entgql/internal/todoglobalid/ent/onetomany_query.go new file mode 100644 index 000000000..fb17ca61c --- /dev/null +++ b/entgql/internal/todoglobalid/ent/onetomany_query.go @@ -0,0 +1,744 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "database/sql/driver" + "fmt" + "math" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/onetomany" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// OneToManyQuery is the builder for querying OneToMany entities. +type OneToManyQuery struct { + config + ctx *QueryContext + order []onetomany.OrderOption + inters []Interceptor + predicates []predicate.OneToMany + withParent *OneToManyQuery + withChildren *OneToManyQuery + loadTotal []func(context.Context, []*OneToMany) error + modifiers []func(*sql.Selector) + withNamedChildren map[string]*OneToManyQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the OneToManyQuery builder. +func (otmq *OneToManyQuery) Where(ps ...predicate.OneToMany) *OneToManyQuery { + otmq.predicates = append(otmq.predicates, ps...) + return otmq +} + +// Limit the number of records to be returned by this query. +func (otmq *OneToManyQuery) Limit(limit int) *OneToManyQuery { + otmq.ctx.Limit = &limit + return otmq +} + +// Offset to start from. +func (otmq *OneToManyQuery) Offset(offset int) *OneToManyQuery { + otmq.ctx.Offset = &offset + return otmq +} + +// 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 (otmq *OneToManyQuery) Unique(unique bool) *OneToManyQuery { + otmq.ctx.Unique = &unique + return otmq +} + +// Order specifies how the records should be ordered. +func (otmq *OneToManyQuery) Order(o ...onetomany.OrderOption) *OneToManyQuery { + otmq.order = append(otmq.order, o...) + return otmq +} + +// QueryParent chains the current query on the "parent" edge. +func (otmq *OneToManyQuery) QueryParent() *OneToManyQuery { + query := (&OneToManyClient{config: otmq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := otmq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := otmq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(onetomany.Table, onetomany.FieldID, selector), + sqlgraph.To(onetomany.Table, onetomany.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, onetomany.ParentTable, onetomany.ParentColumn), + ) + fromU = sqlgraph.SetNeighbors(otmq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryChildren chains the current query on the "children" edge. +func (otmq *OneToManyQuery) QueryChildren() *OneToManyQuery { + query := (&OneToManyClient{config: otmq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := otmq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := otmq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(onetomany.Table, onetomany.FieldID, selector), + sqlgraph.To(onetomany.Table, onetomany.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, onetomany.ChildrenTable, onetomany.ChildrenColumn), + ) + fromU = sqlgraph.SetNeighbors(otmq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first OneToMany entity from the query. +// Returns a *NotFoundError when no OneToMany was found. +func (otmq *OneToManyQuery) First(ctx context.Context) (*OneToMany, error) { + nodes, err := otmq.Limit(1).All(setContextOp(ctx, otmq.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{onetomany.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (otmq *OneToManyQuery) FirstX(ctx context.Context) *OneToMany { + node, err := otmq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first OneToMany ID from the query. +// Returns a *NotFoundError when no OneToMany ID was found. +func (otmq *OneToManyQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = otmq.Limit(1).IDs(setContextOp(ctx, otmq.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{onetomany.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (otmq *OneToManyQuery) FirstIDX(ctx context.Context) int { + id, err := otmq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single OneToMany entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one OneToMany entity is found. +// Returns a *NotFoundError when no OneToMany entities are found. +func (otmq *OneToManyQuery) Only(ctx context.Context) (*OneToMany, error) { + nodes, err := otmq.Limit(2).All(setContextOp(ctx, otmq.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{onetomany.Label} + default: + return nil, &NotSingularError{onetomany.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (otmq *OneToManyQuery) OnlyX(ctx context.Context) *OneToMany { + node, err := otmq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only OneToMany ID in the query. +// Returns a *NotSingularError when more than one OneToMany ID is found. +// Returns a *NotFoundError when no entities are found. +func (otmq *OneToManyQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = otmq.Limit(2).IDs(setContextOp(ctx, otmq.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{onetomany.Label} + default: + err = &NotSingularError{onetomany.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (otmq *OneToManyQuery) OnlyIDX(ctx context.Context) int { + id, err := otmq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of OneToManies. +func (otmq *OneToManyQuery) All(ctx context.Context) ([]*OneToMany, error) { + ctx = setContextOp(ctx, otmq.ctx, ent.OpQueryAll) + if err := otmq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*OneToMany, *OneToManyQuery]() + return withInterceptors[[]*OneToMany](ctx, otmq, qr, otmq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (otmq *OneToManyQuery) AllX(ctx context.Context) []*OneToMany { + nodes, err := otmq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of OneToMany IDs. +func (otmq *OneToManyQuery) IDs(ctx context.Context) (ids []int, err error) { + if otmq.ctx.Unique == nil && otmq.path != nil { + otmq.Unique(true) + } + ctx = setContextOp(ctx, otmq.ctx, ent.OpQueryIDs) + if err = otmq.Select(onetomany.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (otmq *OneToManyQuery) IDsX(ctx context.Context) []int { + ids, err := otmq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (otmq *OneToManyQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, otmq.ctx, ent.OpQueryCount) + if err := otmq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, otmq, querierCount[*OneToManyQuery](), otmq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (otmq *OneToManyQuery) CountX(ctx context.Context) int { + count, err := otmq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (otmq *OneToManyQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, otmq.ctx, ent.OpQueryExist) + switch _, err := otmq.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 (otmq *OneToManyQuery) ExistX(ctx context.Context) bool { + exist, err := otmq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the OneToManyQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (otmq *OneToManyQuery) Clone() *OneToManyQuery { + if otmq == nil { + return nil + } + return &OneToManyQuery{ + config: otmq.config, + ctx: otmq.ctx.Clone(), + order: append([]onetomany.OrderOption{}, otmq.order...), + inters: append([]Interceptor{}, otmq.inters...), + predicates: append([]predicate.OneToMany{}, otmq.predicates...), + withParent: otmq.withParent.Clone(), + withChildren: otmq.withChildren.Clone(), + // clone intermediate query. + sql: otmq.sql.Clone(), + path: otmq.path, + modifiers: append([]func(*sql.Selector){}, otmq.modifiers...), + } +} + +// WithParent tells the query-builder to eager-load the nodes that are connected to +// the "parent" edge. The optional arguments are used to configure the query builder of the edge. +func (otmq *OneToManyQuery) WithParent(opts ...func(*OneToManyQuery)) *OneToManyQuery { + query := (&OneToManyClient{config: otmq.config}).Query() + for _, opt := range opts { + opt(query) + } + otmq.withParent = query + return otmq +} + +// WithChildren tells the query-builder to eager-load the nodes that are connected to +// the "children" edge. The optional arguments are used to configure the query builder of the edge. +func (otmq *OneToManyQuery) WithChildren(opts ...func(*OneToManyQuery)) *OneToManyQuery { + query := (&OneToManyClient{config: otmq.config}).Query() + for _, opt := range opts { + opt(query) + } + otmq.withChildren = query + return otmq +} + +// 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 { +// Name string `json:"name,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.OneToMany.Query(). +// GroupBy(onetomany.FieldName). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (otmq *OneToManyQuery) GroupBy(field string, fields ...string) *OneToManyGroupBy { + otmq.ctx.Fields = append([]string{field}, fields...) + grbuild := &OneToManyGroupBy{build: otmq} + grbuild.flds = &otmq.ctx.Fields + grbuild.label = onetomany.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 { +// Name string `json:"name,omitempty"` +// } +// +// client.OneToMany.Query(). +// Select(onetomany.FieldName). +// Scan(ctx, &v) +func (otmq *OneToManyQuery) Select(fields ...string) *OneToManySelect { + otmq.ctx.Fields = append(otmq.ctx.Fields, fields...) + sbuild := &OneToManySelect{OneToManyQuery: otmq} + sbuild.label = onetomany.Label + sbuild.flds, sbuild.scan = &otmq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a OneToManySelect configured with the given aggregations. +func (otmq *OneToManyQuery) Aggregate(fns ...AggregateFunc) *OneToManySelect { + return otmq.Select().Aggregate(fns...) +} + +func (otmq *OneToManyQuery) prepareQuery(ctx context.Context) error { + for _, inter := range otmq.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, otmq); err != nil { + return err + } + } + } + for _, f := range otmq.ctx.Fields { + if !onetomany.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if otmq.path != nil { + prev, err := otmq.path(ctx) + if err != nil { + return err + } + otmq.sql = prev + } + return nil +} + +func (otmq *OneToManyQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*OneToMany, error) { + var ( + nodes = []*OneToMany{} + _spec = otmq.querySpec() + loadedTypes = [2]bool{ + otmq.withParent != nil, + otmq.withChildren != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*OneToMany).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &OneToMany{config: otmq.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(otmq.modifiers) > 0 { + _spec.Modifiers = otmq.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, otmq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := otmq.withParent; query != nil { + if err := otmq.loadParent(ctx, query, nodes, nil, + func(n *OneToMany, e *OneToMany) { n.Edges.Parent = e }); err != nil { + return nil, err + } + } + if query := otmq.withChildren; query != nil { + if err := otmq.loadChildren(ctx, query, nodes, + func(n *OneToMany) { n.Edges.Children = []*OneToMany{} }, + func(n *OneToMany, e *OneToMany) { n.Edges.Children = append(n.Edges.Children, e) }); err != nil { + return nil, err + } + } + for name, query := range otmq.withNamedChildren { + if err := otmq.loadChildren(ctx, query, nodes, + func(n *OneToMany) { n.appendNamedChildren(name) }, + func(n *OneToMany, e *OneToMany) { n.appendNamedChildren(name, e) }); err != nil { + return nil, err + } + } + for i := range otmq.loadTotal { + if err := otmq.loadTotal[i](ctx, nodes); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (otmq *OneToManyQuery) loadParent(ctx context.Context, query *OneToManyQuery, nodes []*OneToMany, init func(*OneToMany), assign func(*OneToMany, *OneToMany)) error { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*OneToMany) + for i := range nodes { + fk := nodes[i].ParentID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(onetomany.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 "parent_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (otmq *OneToManyQuery) loadChildren(ctx context.Context, query *OneToManyQuery, nodes []*OneToMany, init func(*OneToMany), assign func(*OneToMany, *OneToMany)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*OneToMany) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(onetomany.FieldParentID) + } + query.Where(predicate.OneToMany(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(onetomany.ChildrenColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.ParentID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "parent_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (otmq *OneToManyQuery) sqlCount(ctx context.Context) (int, error) { + _spec := otmq.querySpec() + if len(otmq.modifiers) > 0 { + _spec.Modifiers = otmq.modifiers + } + _spec.Node.Columns = otmq.ctx.Fields + if len(otmq.ctx.Fields) > 0 { + _spec.Unique = otmq.ctx.Unique != nil && *otmq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, otmq.driver, _spec) +} + +func (otmq *OneToManyQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(onetomany.Table, onetomany.Columns, sqlgraph.NewFieldSpec(onetomany.FieldID, field.TypeInt)) + _spec.From = otmq.sql + if unique := otmq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if otmq.path != nil { + _spec.Unique = true + } + if fields := otmq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, onetomany.FieldID) + for i := range fields { + if fields[i] != onetomany.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if otmq.withParent != nil { + _spec.Node.AddColumnOnce(onetomany.FieldParentID) + } + } + if ps := otmq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := otmq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := otmq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := otmq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (otmq *OneToManyQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(otmq.driver.Dialect()) + t1 := builder.Table(onetomany.Table) + columns := otmq.ctx.Fields + if len(columns) == 0 { + columns = onetomany.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if otmq.sql != nil { + selector = otmq.sql + selector.Select(selector.Columns(columns...)...) + } + if otmq.ctx.Unique != nil && *otmq.ctx.Unique { + selector.Distinct() + } + for _, m := range otmq.modifiers { + m(selector) + } + for _, p := range otmq.predicates { + p(selector) + } + for _, p := range otmq.order { + p(selector) + } + if offset := otmq.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 := otmq.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (otmq *OneToManyQuery) Modify(modifiers ...func(s *sql.Selector)) *OneToManySelect { + otmq.modifiers = append(otmq.modifiers, modifiers...) + return otmq.Select() +} + +// WithNamedChildren tells the query-builder to eager-load the nodes that are connected to the "children" +// edge with the given name. The optional arguments are used to configure the query builder of the edge. +func (otmq *OneToManyQuery) WithNamedChildren(name string, opts ...func(*OneToManyQuery)) *OneToManyQuery { + query := (&OneToManyClient{config: otmq.config}).Query() + for _, opt := range opts { + opt(query) + } + if otmq.withNamedChildren == nil { + otmq.withNamedChildren = make(map[string]*OneToManyQuery) + } + otmq.withNamedChildren[name] = query + return otmq +} + +// OneToManyGroupBy is the group-by builder for OneToMany entities. +type OneToManyGroupBy struct { + selector + build *OneToManyQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (otmgb *OneToManyGroupBy) Aggregate(fns ...AggregateFunc) *OneToManyGroupBy { + otmgb.fns = append(otmgb.fns, fns...) + return otmgb +} + +// Scan applies the selector query and scans the result into the given value. +func (otmgb *OneToManyGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, otmgb.build.ctx, ent.OpQueryGroupBy) + if err := otmgb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*OneToManyQuery, *OneToManyGroupBy](ctx, otmgb.build, otmgb, otmgb.build.inters, v) +} + +func (otmgb *OneToManyGroupBy) sqlScan(ctx context.Context, root *OneToManyQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(otmgb.fns)) + for _, fn := range otmgb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*otmgb.flds)+len(otmgb.fns)) + for _, f := range *otmgb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*otmgb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := otmgb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// OneToManySelect is the builder for selecting fields of OneToMany entities. +type OneToManySelect struct { + *OneToManyQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (otms *OneToManySelect) Aggregate(fns ...AggregateFunc) *OneToManySelect { + otms.fns = append(otms.fns, fns...) + return otms +} + +// Scan applies the selector query and scans the result into the given value. +func (otms *OneToManySelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, otms.ctx, ent.OpQuerySelect) + if err := otms.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*OneToManyQuery, *OneToManySelect](ctx, otms.OneToManyQuery, otms, otms.inters, v) +} + +func (otms *OneToManySelect) sqlScan(ctx context.Context, root *OneToManyQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(otms.fns)) + for _, fn := range otms.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*otms.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 := otms.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (otms *OneToManySelect) Modify(modifiers ...func(s *sql.Selector)) *OneToManySelect { + otms.modifiers = append(otms.modifiers, modifiers...) + return otms +} diff --git a/entgql/internal/todoglobalid/ent/onetomany_update.go b/entgql/internal/todoglobalid/ent/onetomany_update.go new file mode 100644 index 000000000..ec6e1f581 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/onetomany_update.go @@ -0,0 +1,599 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/onetomany" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// OneToManyUpdate is the builder for updating OneToMany entities. +type OneToManyUpdate struct { + config + hooks []Hook + mutation *OneToManyMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the OneToManyUpdate builder. +func (otmu *OneToManyUpdate) Where(ps ...predicate.OneToMany) *OneToManyUpdate { + otmu.mutation.Where(ps...) + return otmu +} + +// SetName sets the "name" field. +func (otmu *OneToManyUpdate) SetName(s string) *OneToManyUpdate { + otmu.mutation.SetName(s) + return otmu +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (otmu *OneToManyUpdate) SetNillableName(s *string) *OneToManyUpdate { + if s != nil { + otmu.SetName(*s) + } + return otmu +} + +// SetField2 sets the "field2" field. +func (otmu *OneToManyUpdate) SetField2(s string) *OneToManyUpdate { + otmu.mutation.SetField2(s) + return otmu +} + +// SetNillableField2 sets the "field2" field if the given value is not nil. +func (otmu *OneToManyUpdate) SetNillableField2(s *string) *OneToManyUpdate { + if s != nil { + otmu.SetField2(*s) + } + return otmu +} + +// ClearField2 clears the value of the "field2" field. +func (otmu *OneToManyUpdate) ClearField2() *OneToManyUpdate { + otmu.mutation.ClearField2() + return otmu +} + +// SetParentID sets the "parent_id" field. +func (otmu *OneToManyUpdate) SetParentID(i int) *OneToManyUpdate { + otmu.mutation.SetParentID(i) + return otmu +} + +// SetNillableParentID sets the "parent_id" field if the given value is not nil. +func (otmu *OneToManyUpdate) SetNillableParentID(i *int) *OneToManyUpdate { + if i != nil { + otmu.SetParentID(*i) + } + return otmu +} + +// ClearParentID clears the value of the "parent_id" field. +func (otmu *OneToManyUpdate) ClearParentID() *OneToManyUpdate { + otmu.mutation.ClearParentID() + return otmu +} + +// SetParent sets the "parent" edge to the OneToMany entity. +func (otmu *OneToManyUpdate) SetParent(o *OneToMany) *OneToManyUpdate { + return otmu.SetParentID(o.ID) +} + +// AddChildIDs adds the "children" edge to the OneToMany entity by IDs. +func (otmu *OneToManyUpdate) AddChildIDs(ids ...int) *OneToManyUpdate { + otmu.mutation.AddChildIDs(ids...) + return otmu +} + +// AddChildren adds the "children" edges to the OneToMany entity. +func (otmu *OneToManyUpdate) AddChildren(o ...*OneToMany) *OneToManyUpdate { + ids := make([]int, len(o)) + for i := range o { + ids[i] = o[i].ID + } + return otmu.AddChildIDs(ids...) +} + +// Mutation returns the OneToManyMutation object of the builder. +func (otmu *OneToManyUpdate) Mutation() *OneToManyMutation { + return otmu.mutation +} + +// ClearParent clears the "parent" edge to the OneToMany entity. +func (otmu *OneToManyUpdate) ClearParent() *OneToManyUpdate { + otmu.mutation.ClearParent() + return otmu +} + +// ClearChildren clears all "children" edges to the OneToMany entity. +func (otmu *OneToManyUpdate) ClearChildren() *OneToManyUpdate { + otmu.mutation.ClearChildren() + return otmu +} + +// RemoveChildIDs removes the "children" edge to OneToMany entities by IDs. +func (otmu *OneToManyUpdate) RemoveChildIDs(ids ...int) *OneToManyUpdate { + otmu.mutation.RemoveChildIDs(ids...) + return otmu +} + +// RemoveChildren removes "children" edges to OneToMany entities. +func (otmu *OneToManyUpdate) RemoveChildren(o ...*OneToMany) *OneToManyUpdate { + ids := make([]int, len(o)) + for i := range o { + ids[i] = o[i].ID + } + return otmu.RemoveChildIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (otmu *OneToManyUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, otmu.sqlSave, otmu.mutation, otmu.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (otmu *OneToManyUpdate) SaveX(ctx context.Context) int { + affected, err := otmu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (otmu *OneToManyUpdate) Exec(ctx context.Context) error { + _, err := otmu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (otmu *OneToManyUpdate) ExecX(ctx context.Context) { + if err := otmu.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (otmu *OneToManyUpdate) check() error { + if v, ok := otmu.mutation.Name(); ok { + if err := onetomany.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "OneToMany.name": %w`, err)} + } + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (otmu *OneToManyUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *OneToManyUpdate { + otmu.modifiers = append(otmu.modifiers, modifiers...) + return otmu +} + +func (otmu *OneToManyUpdate) sqlSave(ctx context.Context) (n int, err error) { + if err := otmu.check(); err != nil { + return n, err + } + _spec := sqlgraph.NewUpdateSpec(onetomany.Table, onetomany.Columns, sqlgraph.NewFieldSpec(onetomany.FieldID, field.TypeInt)) + if ps := otmu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := otmu.mutation.Name(); ok { + _spec.SetField(onetomany.FieldName, field.TypeString, value) + } + if value, ok := otmu.mutation.Field2(); ok { + _spec.SetField(onetomany.FieldField2, field.TypeString, value) + } + if otmu.mutation.Field2Cleared() { + _spec.ClearField(onetomany.FieldField2, field.TypeString) + } + if otmu.mutation.ParentCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: onetomany.ParentTable, + Columns: []string{onetomany.ParentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(onetomany.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := otmu.mutation.ParentIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: onetomany.ParentTable, + Columns: []string{onetomany.ParentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(onetomany.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if otmu.mutation.ChildrenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: onetomany.ChildrenTable, + Columns: []string{onetomany.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(onetomany.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := otmu.mutation.RemovedChildrenIDs(); len(nodes) > 0 && !otmu.mutation.ChildrenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: onetomany.ChildrenTable, + Columns: []string{onetomany.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(onetomany.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 := otmu.mutation.ChildrenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: onetomany.ChildrenTable, + Columns: []string{onetomany.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(onetomany.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(otmu.modifiers...) + if n, err = sqlgraph.UpdateNodes(ctx, otmu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{onetomany.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + otmu.mutation.done = true + return n, nil +} + +// OneToManyUpdateOne is the builder for updating a single OneToMany entity. +type OneToManyUpdateOne struct { + config + fields []string + hooks []Hook + mutation *OneToManyMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetName sets the "name" field. +func (otmuo *OneToManyUpdateOne) SetName(s string) *OneToManyUpdateOne { + otmuo.mutation.SetName(s) + return otmuo +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (otmuo *OneToManyUpdateOne) SetNillableName(s *string) *OneToManyUpdateOne { + if s != nil { + otmuo.SetName(*s) + } + return otmuo +} + +// SetField2 sets the "field2" field. +func (otmuo *OneToManyUpdateOne) SetField2(s string) *OneToManyUpdateOne { + otmuo.mutation.SetField2(s) + return otmuo +} + +// SetNillableField2 sets the "field2" field if the given value is not nil. +func (otmuo *OneToManyUpdateOne) SetNillableField2(s *string) *OneToManyUpdateOne { + if s != nil { + otmuo.SetField2(*s) + } + return otmuo +} + +// ClearField2 clears the value of the "field2" field. +func (otmuo *OneToManyUpdateOne) ClearField2() *OneToManyUpdateOne { + otmuo.mutation.ClearField2() + return otmuo +} + +// SetParentID sets the "parent_id" field. +func (otmuo *OneToManyUpdateOne) SetParentID(i int) *OneToManyUpdateOne { + otmuo.mutation.SetParentID(i) + return otmuo +} + +// SetNillableParentID sets the "parent_id" field if the given value is not nil. +func (otmuo *OneToManyUpdateOne) SetNillableParentID(i *int) *OneToManyUpdateOne { + if i != nil { + otmuo.SetParentID(*i) + } + return otmuo +} + +// ClearParentID clears the value of the "parent_id" field. +func (otmuo *OneToManyUpdateOne) ClearParentID() *OneToManyUpdateOne { + otmuo.mutation.ClearParentID() + return otmuo +} + +// SetParent sets the "parent" edge to the OneToMany entity. +func (otmuo *OneToManyUpdateOne) SetParent(o *OneToMany) *OneToManyUpdateOne { + return otmuo.SetParentID(o.ID) +} + +// AddChildIDs adds the "children" edge to the OneToMany entity by IDs. +func (otmuo *OneToManyUpdateOne) AddChildIDs(ids ...int) *OneToManyUpdateOne { + otmuo.mutation.AddChildIDs(ids...) + return otmuo +} + +// AddChildren adds the "children" edges to the OneToMany entity. +func (otmuo *OneToManyUpdateOne) AddChildren(o ...*OneToMany) *OneToManyUpdateOne { + ids := make([]int, len(o)) + for i := range o { + ids[i] = o[i].ID + } + return otmuo.AddChildIDs(ids...) +} + +// Mutation returns the OneToManyMutation object of the builder. +func (otmuo *OneToManyUpdateOne) Mutation() *OneToManyMutation { + return otmuo.mutation +} + +// ClearParent clears the "parent" edge to the OneToMany entity. +func (otmuo *OneToManyUpdateOne) ClearParent() *OneToManyUpdateOne { + otmuo.mutation.ClearParent() + return otmuo +} + +// ClearChildren clears all "children" edges to the OneToMany entity. +func (otmuo *OneToManyUpdateOne) ClearChildren() *OneToManyUpdateOne { + otmuo.mutation.ClearChildren() + return otmuo +} + +// RemoveChildIDs removes the "children" edge to OneToMany entities by IDs. +func (otmuo *OneToManyUpdateOne) RemoveChildIDs(ids ...int) *OneToManyUpdateOne { + otmuo.mutation.RemoveChildIDs(ids...) + return otmuo +} + +// RemoveChildren removes "children" edges to OneToMany entities. +func (otmuo *OneToManyUpdateOne) RemoveChildren(o ...*OneToMany) *OneToManyUpdateOne { + ids := make([]int, len(o)) + for i := range o { + ids[i] = o[i].ID + } + return otmuo.RemoveChildIDs(ids...) +} + +// Where appends a list predicates to the OneToManyUpdate builder. +func (otmuo *OneToManyUpdateOne) Where(ps ...predicate.OneToMany) *OneToManyUpdateOne { + otmuo.mutation.Where(ps...) + return otmuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (otmuo *OneToManyUpdateOne) Select(field string, fields ...string) *OneToManyUpdateOne { + otmuo.fields = append([]string{field}, fields...) + return otmuo +} + +// Save executes the query and returns the updated OneToMany entity. +func (otmuo *OneToManyUpdateOne) Save(ctx context.Context) (*OneToMany, error) { + return withHooks(ctx, otmuo.sqlSave, otmuo.mutation, otmuo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (otmuo *OneToManyUpdateOne) SaveX(ctx context.Context) *OneToMany { + node, err := otmuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (otmuo *OneToManyUpdateOne) Exec(ctx context.Context) error { + _, err := otmuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (otmuo *OneToManyUpdateOne) ExecX(ctx context.Context) { + if err := otmuo.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (otmuo *OneToManyUpdateOne) check() error { + if v, ok := otmuo.mutation.Name(); ok { + if err := onetomany.NameValidator(v); err != nil { + return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "OneToMany.name": %w`, err)} + } + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (otmuo *OneToManyUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *OneToManyUpdateOne { + otmuo.modifiers = append(otmuo.modifiers, modifiers...) + return otmuo +} + +func (otmuo *OneToManyUpdateOne) sqlSave(ctx context.Context) (_node *OneToMany, err error) { + if err := otmuo.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(onetomany.Table, onetomany.Columns, sqlgraph.NewFieldSpec(onetomany.FieldID, field.TypeInt)) + id, ok := otmuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "OneToMany.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := otmuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, onetomany.FieldID) + for _, f := range fields { + if !onetomany.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != onetomany.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := otmuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := otmuo.mutation.Name(); ok { + _spec.SetField(onetomany.FieldName, field.TypeString, value) + } + if value, ok := otmuo.mutation.Field2(); ok { + _spec.SetField(onetomany.FieldField2, field.TypeString, value) + } + if otmuo.mutation.Field2Cleared() { + _spec.ClearField(onetomany.FieldField2, field.TypeString) + } + if otmuo.mutation.ParentCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: onetomany.ParentTable, + Columns: []string{onetomany.ParentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(onetomany.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := otmuo.mutation.ParentIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: onetomany.ParentTable, + Columns: []string{onetomany.ParentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(onetomany.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if otmuo.mutation.ChildrenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: onetomany.ChildrenTable, + Columns: []string{onetomany.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(onetomany.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := otmuo.mutation.RemovedChildrenIDs(); len(nodes) > 0 && !otmuo.mutation.ChildrenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: onetomany.ChildrenTable, + Columns: []string{onetomany.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(onetomany.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 := otmuo.mutation.ChildrenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: onetomany.ChildrenTable, + Columns: []string{onetomany.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(onetomany.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(otmuo.modifiers...) + _node = &OneToMany{config: otmuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, otmuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{onetomany.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + otmuo.mutation.done = true + return _node, nil +} diff --git a/entgql/internal/todoglobalid/ent/predicate/predicate.go b/entgql/internal/todoglobalid/ent/predicate/predicate.go new file mode 100644 index 000000000..c845c1038 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/predicate/predicate.go @@ -0,0 +1,51 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package predicate + +import ( + "entgo.io/ent/dialect/sql" +) + +// BillProduct is the predicate function for billproduct builders. +type BillProduct func(*sql.Selector) + +// Category is the predicate function for category builders. +type Category func(*sql.Selector) + +// Friendship is the predicate function for friendship builders. +type Friendship func(*sql.Selector) + +// Group is the predicate function for group builders. +type Group func(*sql.Selector) + +// OneToMany is the predicate function for onetomany builders. +type OneToMany func(*sql.Selector) + +// Project is the predicate function for project builders. +type Project func(*sql.Selector) + +// Todo is the predicate function for todo builders. +type Todo func(*sql.Selector) + +// User is the predicate function for user builders. +type User func(*sql.Selector) + +// VerySecret is the predicate function for verysecret builders. +type VerySecret func(*sql.Selector) + +// Workspace is the predicate function for workspace builders. +type Workspace func(*sql.Selector) diff --git a/entgql/internal/todoglobalid/ent/project.go b/entgql/internal/todoglobalid/ent/project.go new file mode 100644 index 000000000..2d67a9031 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/project.go @@ -0,0 +1,159 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/project" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// Project is the model entity for the Project schema. +type Project struct { + config + // ID of the ent. + ID int `json:"id,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the ProjectQuery when eager-loading is set. + Edges ProjectEdges `json:"edges"` + selectValues sql.SelectValues +} + +// ProjectEdges holds the relations/edges for other nodes in the graph. +type ProjectEdges struct { + // Todos holds the value of the todos edge. + Todos []*Todo `json:"todos,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [1]bool + // totalCount holds the count of the edges above. + totalCount [1]map[string]int + + namedTodos map[string][]*Todo +} + +// TodosOrErr returns the Todos value or an error if the edge +// was not loaded in eager-loading. +func (e ProjectEdges) TodosOrErr() ([]*Todo, error) { + if e.loadedTypes[0] { + return e.Todos, nil + } + return nil, &NotLoadedError{edge: "todos"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Project) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case project.FieldID: + 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 Project fields. +func (pr *Project) 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 project.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + pr.ID = int(value.Int64) + default: + pr.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Project. +// This includes values selected through modifiers, order, etc. +func (pr *Project) Value(name string) (ent.Value, error) { + return pr.selectValues.Get(name) +} + +// QueryTodos queries the "todos" edge of the Project entity. +func (pr *Project) QueryTodos() *TodoQuery { + return NewProjectClient(pr.config).QueryTodos(pr) +} + +// Update returns a builder for updating this Project. +// Note that you need to call Project.Unwrap() before calling this method if this Project +// was returned from a transaction, and the transaction was committed or rolled back. +func (pr *Project) Update() *ProjectUpdateOne { + return NewProjectClient(pr.config).UpdateOne(pr) +} + +// Unwrap unwraps the Project 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 (pr *Project) Unwrap() *Project { + _tx, ok := pr.config.driver.(*txDriver) + if !ok { + panic("ent: Project is not a transactional entity") + } + pr.config.driver = _tx.drv + return pr +} + +// String implements the fmt.Stringer. +func (pr *Project) String() string { + var builder strings.Builder + builder.WriteString("Project(") + builder.WriteString(fmt.Sprintf("id=%v", pr.ID)) + builder.WriteByte(')') + return builder.String() +} + +// NamedTodos returns the Todos named value or an error if the edge was not +// loaded in eager-loading with this name. +func (pr *Project) NamedTodos(name string) ([]*Todo, error) { + if pr.Edges.namedTodos == nil { + return nil, &NotLoadedError{edge: name} + } + nodes, ok := pr.Edges.namedTodos[name] + if !ok { + return nil, &NotLoadedError{edge: name} + } + return nodes, nil +} + +func (pr *Project) appendNamedTodos(name string, edges ...*Todo) { + if pr.Edges.namedTodos == nil { + pr.Edges.namedTodos = make(map[string][]*Todo) + } + if len(edges) == 0 { + pr.Edges.namedTodos[name] = []*Todo{} + } else { + pr.Edges.namedTodos[name] = append(pr.Edges.namedTodos[name], edges...) + } +} + +// Projects is a parsable slice of Project. +type Projects []*Project diff --git a/entgql/internal/todoglobalid/ent/project/project.go b/entgql/internal/todoglobalid/ent/project/project.go new file mode 100644 index 000000000..c603889a6 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/project/project.go @@ -0,0 +1,84 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package project + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the project type in the database. + Label = "project" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // EdgeTodos holds the string denoting the todos edge name in mutations. + EdgeTodos = "todos" + // Table holds the table name of the project in the database. + Table = "projects" + // TodosTable is the table that holds the todos relation/edge. + TodosTable = "todos" + // TodosInverseTable is the table name for the Todo entity. + // It exists in this package in order to avoid circular dependency with the "todo" package. + TodosInverseTable = "todos" + // TodosColumn is the table column denoting the todos relation/edge. + TodosColumn = "project_todos" +) + +// Columns holds all SQL columns for project fields. +var Columns = []string{ + FieldID, +} + +// 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 +} + +// OrderOption defines the ordering options for the Project 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() +} + +// ByTodosCount orders the results by todos count. +func ByTodosCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newTodosStep(), opts...) + } +} + +// ByTodos orders the results by todos terms. +func ByTodos(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newTodosStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newTodosStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(TodosInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, TodosTable, TodosColumn), + ) +} diff --git a/entgql/internal/todoglobalid/ent/project/where.go b/entgql/internal/todoglobalid/ent/project/where.go new file mode 100644 index 000000000..bb44af4f1 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/project/where.go @@ -0,0 +1,106 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package project + +import ( + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.Project { + return predicate.Project(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.Project { + return predicate.Project(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.Project { + return predicate.Project(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.Project { + return predicate.Project(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.Project { + return predicate.Project(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.Project { + return predicate.Project(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.Project { + return predicate.Project(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.Project { + return predicate.Project(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.Project { + return predicate.Project(sql.FieldLTE(FieldID, id)) +} + +// HasTodos applies the HasEdge predicate on the "todos" edge. +func HasTodos() predicate.Project { + return predicate.Project(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, TodosTable, TodosColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasTodosWith applies the HasEdge predicate on the "todos" edge with a given conditions (other predicates). +func HasTodosWith(preds ...predicate.Todo) predicate.Project { + return predicate.Project(func(s *sql.Selector) { + step := newTodosStep() + 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.Project) predicate.Project { + return predicate.Project(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Project) predicate.Project { + return predicate.Project(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Project) predicate.Project { + return predicate.Project(sql.NotPredicates(p)) +} diff --git a/entgql/internal/todoglobalid/ent/project_create.go b/entgql/internal/todoglobalid/ent/project_create.go new file mode 100644 index 000000000..4c07f3454 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/project_create.go @@ -0,0 +1,215 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/project" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/todo" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// ProjectCreate is the builder for creating a Project entity. +type ProjectCreate struct { + config + mutation *ProjectMutation + hooks []Hook +} + +// AddTodoIDs adds the "todos" edge to the Todo entity by IDs. +func (pc *ProjectCreate) AddTodoIDs(ids ...int) *ProjectCreate { + pc.mutation.AddTodoIDs(ids...) + return pc +} + +// AddTodos adds the "todos" edges to the Todo entity. +func (pc *ProjectCreate) AddTodos(t ...*Todo) *ProjectCreate { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return pc.AddTodoIDs(ids...) +} + +// Mutation returns the ProjectMutation object of the builder. +func (pc *ProjectCreate) Mutation() *ProjectMutation { + return pc.mutation +} + +// Save creates the Project in the database. +func (pc *ProjectCreate) Save(ctx context.Context) (*Project, error) { + return withHooks(ctx, pc.sqlSave, pc.mutation, pc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (pc *ProjectCreate) SaveX(ctx context.Context) *Project { + v, err := pc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (pc *ProjectCreate) Exec(ctx context.Context) error { + _, err := pc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (pc *ProjectCreate) ExecX(ctx context.Context) { + if err := pc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (pc *ProjectCreate) check() error { + return nil +} + +func (pc *ProjectCreate) sqlSave(ctx context.Context) (*Project, error) { + if err := pc.check(); err != nil { + return nil, err + } + _node, _spec := pc.createSpec() + if err := sqlgraph.CreateNode(ctx, pc.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) + pc.mutation.id = &_node.ID + pc.mutation.done = true + return _node, nil +} + +func (pc *ProjectCreate) createSpec() (*Project, *sqlgraph.CreateSpec) { + var ( + _node = &Project{config: pc.config} + _spec = sqlgraph.NewCreateSpec(project.Table, sqlgraph.NewFieldSpec(project.FieldID, field.TypeInt)) + ) + if nodes := pc.mutation.TodosIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: project.TodosTable, + Columns: []string{project.TodosColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// ProjectCreateBulk is the builder for creating many Project entities in bulk. +type ProjectCreateBulk struct { + config + err error + builders []*ProjectCreate +} + +// Save creates the Project entities in the database. +func (pcb *ProjectCreateBulk) Save(ctx context.Context) ([]*Project, error) { + if pcb.err != nil { + return nil, pcb.err + } + specs := make([]*sqlgraph.CreateSpec, len(pcb.builders)) + nodes := make([]*Project, len(pcb.builders)) + mutators := make([]Mutator, len(pcb.builders)) + for i := range pcb.builders { + func(i int, root context.Context) { + builder := pcb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*ProjectMutation) + 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, pcb.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, pcb.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, pcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (pcb *ProjectCreateBulk) SaveX(ctx context.Context) []*Project { + v, err := pcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (pcb *ProjectCreateBulk) Exec(ctx context.Context) error { + _, err := pcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (pcb *ProjectCreateBulk) ExecX(ctx context.Context) { + if err := pcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entgql/internal/todoglobalid/ent/project_delete.go b/entgql/internal/todoglobalid/ent/project_delete.go new file mode 100644 index 000000000..c3f565161 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/project_delete.go @@ -0,0 +1,102 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/project" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// ProjectDelete is the builder for deleting a Project entity. +type ProjectDelete struct { + config + hooks []Hook + mutation *ProjectMutation +} + +// Where appends a list predicates to the ProjectDelete builder. +func (pd *ProjectDelete) Where(ps ...predicate.Project) *ProjectDelete { + pd.mutation.Where(ps...) + return pd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (pd *ProjectDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, pd.sqlExec, pd.mutation, pd.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (pd *ProjectDelete) ExecX(ctx context.Context) int { + n, err := pd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (pd *ProjectDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(project.Table, sqlgraph.NewFieldSpec(project.FieldID, field.TypeInt)) + if ps := pd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, pd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + pd.mutation.done = true + return affected, err +} + +// ProjectDeleteOne is the builder for deleting a single Project entity. +type ProjectDeleteOne struct { + pd *ProjectDelete +} + +// Where appends a list predicates to the ProjectDelete builder. +func (pdo *ProjectDeleteOne) Where(ps ...predicate.Project) *ProjectDeleteOne { + pdo.pd.mutation.Where(ps...) + return pdo +} + +// Exec executes the deletion query. +func (pdo *ProjectDeleteOne) Exec(ctx context.Context) error { + n, err := pdo.pd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{project.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (pdo *ProjectDeleteOne) ExecX(ctx context.Context) { + if err := pdo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entgql/internal/todoglobalid/ent/project_query.go b/entgql/internal/todoglobalid/ent/project_query.go new file mode 100644 index 000000000..e84751b63 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/project_query.go @@ -0,0 +1,650 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "database/sql/driver" + "fmt" + "math" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/project" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/todo" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// ProjectQuery is the builder for querying Project entities. +type ProjectQuery struct { + config + ctx *QueryContext + order []project.OrderOption + inters []Interceptor + predicates []predicate.Project + withTodos *TodoQuery + loadTotal []func(context.Context, []*Project) error + modifiers []func(*sql.Selector) + withNamedTodos map[string]*TodoQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the ProjectQuery builder. +func (pq *ProjectQuery) Where(ps ...predicate.Project) *ProjectQuery { + pq.predicates = append(pq.predicates, ps...) + return pq +} + +// Limit the number of records to be returned by this query. +func (pq *ProjectQuery) Limit(limit int) *ProjectQuery { + pq.ctx.Limit = &limit + return pq +} + +// Offset to start from. +func (pq *ProjectQuery) Offset(offset int) *ProjectQuery { + pq.ctx.Offset = &offset + return pq +} + +// 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 (pq *ProjectQuery) Unique(unique bool) *ProjectQuery { + pq.ctx.Unique = &unique + return pq +} + +// Order specifies how the records should be ordered. +func (pq *ProjectQuery) Order(o ...project.OrderOption) *ProjectQuery { + pq.order = append(pq.order, o...) + return pq +} + +// QueryTodos chains the current query on the "todos" edge. +func (pq *ProjectQuery) QueryTodos() *TodoQuery { + query := (&TodoClient{config: pq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := pq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := pq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(project.Table, project.FieldID, selector), + sqlgraph.To(todo.Table, todo.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, project.TodosTable, project.TodosColumn), + ) + fromU = sqlgraph.SetNeighbors(pq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Project entity from the query. +// Returns a *NotFoundError when no Project was found. +func (pq *ProjectQuery) First(ctx context.Context) (*Project, error) { + nodes, err := pq.Limit(1).All(setContextOp(ctx, pq.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{project.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (pq *ProjectQuery) FirstX(ctx context.Context) *Project { + node, err := pq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Project ID from the query. +// Returns a *NotFoundError when no Project ID was found. +func (pq *ProjectQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = pq.Limit(1).IDs(setContextOp(ctx, pq.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{project.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (pq *ProjectQuery) FirstIDX(ctx context.Context) int { + id, err := pq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Project entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Project entity is found. +// Returns a *NotFoundError when no Project entities are found. +func (pq *ProjectQuery) Only(ctx context.Context) (*Project, error) { + nodes, err := pq.Limit(2).All(setContextOp(ctx, pq.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{project.Label} + default: + return nil, &NotSingularError{project.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (pq *ProjectQuery) OnlyX(ctx context.Context) *Project { + node, err := pq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Project ID in the query. +// Returns a *NotSingularError when more than one Project ID is found. +// Returns a *NotFoundError when no entities are found. +func (pq *ProjectQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = pq.Limit(2).IDs(setContextOp(ctx, pq.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{project.Label} + default: + err = &NotSingularError{project.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (pq *ProjectQuery) OnlyIDX(ctx context.Context) int { + id, err := pq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Projects. +func (pq *ProjectQuery) All(ctx context.Context) ([]*Project, error) { + ctx = setContextOp(ctx, pq.ctx, ent.OpQueryAll) + if err := pq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Project, *ProjectQuery]() + return withInterceptors[[]*Project](ctx, pq, qr, pq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (pq *ProjectQuery) AllX(ctx context.Context) []*Project { + nodes, err := pq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Project IDs. +func (pq *ProjectQuery) IDs(ctx context.Context) (ids []int, err error) { + if pq.ctx.Unique == nil && pq.path != nil { + pq.Unique(true) + } + ctx = setContextOp(ctx, pq.ctx, ent.OpQueryIDs) + if err = pq.Select(project.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (pq *ProjectQuery) IDsX(ctx context.Context) []int { + ids, err := pq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (pq *ProjectQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, pq.ctx, ent.OpQueryCount) + if err := pq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, pq, querierCount[*ProjectQuery](), pq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (pq *ProjectQuery) CountX(ctx context.Context) int { + count, err := pq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (pq *ProjectQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, pq.ctx, ent.OpQueryExist) + switch _, err := pq.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 (pq *ProjectQuery) ExistX(ctx context.Context) bool { + exist, err := pq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the ProjectQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (pq *ProjectQuery) Clone() *ProjectQuery { + if pq == nil { + return nil + } + return &ProjectQuery{ + config: pq.config, + ctx: pq.ctx.Clone(), + order: append([]project.OrderOption{}, pq.order...), + inters: append([]Interceptor{}, pq.inters...), + predicates: append([]predicate.Project{}, pq.predicates...), + withTodos: pq.withTodos.Clone(), + // clone intermediate query. + sql: pq.sql.Clone(), + path: pq.path, + modifiers: append([]func(*sql.Selector){}, pq.modifiers...), + } +} + +// WithTodos tells the query-builder to eager-load the nodes that are connected to +// the "todos" edge. The optional arguments are used to configure the query builder of the edge. +func (pq *ProjectQuery) WithTodos(opts ...func(*TodoQuery)) *ProjectQuery { + query := (&TodoClient{config: pq.config}).Query() + for _, opt := range opts { + opt(query) + } + pq.withTodos = query + return pq +} + +// 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. +func (pq *ProjectQuery) GroupBy(field string, fields ...string) *ProjectGroupBy { + pq.ctx.Fields = append([]string{field}, fields...) + grbuild := &ProjectGroupBy{build: pq} + grbuild.flds = &pq.ctx.Fields + grbuild.label = project.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. +func (pq *ProjectQuery) Select(fields ...string) *ProjectSelect { + pq.ctx.Fields = append(pq.ctx.Fields, fields...) + sbuild := &ProjectSelect{ProjectQuery: pq} + sbuild.label = project.Label + sbuild.flds, sbuild.scan = &pq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a ProjectSelect configured with the given aggregations. +func (pq *ProjectQuery) Aggregate(fns ...AggregateFunc) *ProjectSelect { + return pq.Select().Aggregate(fns...) +} + +func (pq *ProjectQuery) prepareQuery(ctx context.Context) error { + for _, inter := range pq.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, pq); err != nil { + return err + } + } + } + for _, f := range pq.ctx.Fields { + if !project.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if pq.path != nil { + prev, err := pq.path(ctx) + if err != nil { + return err + } + pq.sql = prev + } + return nil +} + +func (pq *ProjectQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Project, error) { + var ( + nodes = []*Project{} + _spec = pq.querySpec() + loadedTypes = [1]bool{ + pq.withTodos != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Project).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Project{config: pq.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(pq.modifiers) > 0 { + _spec.Modifiers = pq.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, pq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := pq.withTodos; query != nil { + if err := pq.loadTodos(ctx, query, nodes, + func(n *Project) { n.Edges.Todos = []*Todo{} }, + func(n *Project, e *Todo) { n.Edges.Todos = append(n.Edges.Todos, e) }); err != nil { + return nil, err + } + } + for name, query := range pq.withNamedTodos { + if err := pq.loadTodos(ctx, query, nodes, + func(n *Project) { n.appendNamedTodos(name) }, + func(n *Project, e *Todo) { n.appendNamedTodos(name, e) }); err != nil { + return nil, err + } + } + for i := range pq.loadTotal { + if err := pq.loadTotal[i](ctx, nodes); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (pq *ProjectQuery) loadTodos(ctx context.Context, query *TodoQuery, nodes []*Project, init func(*Project), assign func(*Project, *Todo)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*Project) + 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.Todo(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(project.TodosColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.project_todos + if fk == nil { + return fmt.Errorf(`foreign-key "project_todos" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "project_todos" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (pq *ProjectQuery) sqlCount(ctx context.Context) (int, error) { + _spec := pq.querySpec() + if len(pq.modifiers) > 0 { + _spec.Modifiers = pq.modifiers + } + _spec.Node.Columns = pq.ctx.Fields + if len(pq.ctx.Fields) > 0 { + _spec.Unique = pq.ctx.Unique != nil && *pq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, pq.driver, _spec) +} + +func (pq *ProjectQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(project.Table, project.Columns, sqlgraph.NewFieldSpec(project.FieldID, field.TypeInt)) + _spec.From = pq.sql + if unique := pq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if pq.path != nil { + _spec.Unique = true + } + if fields := pq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, project.FieldID) + for i := range fields { + if fields[i] != project.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := pq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := pq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := pq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := pq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (pq *ProjectQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(pq.driver.Dialect()) + t1 := builder.Table(project.Table) + columns := pq.ctx.Fields + if len(columns) == 0 { + columns = project.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if pq.sql != nil { + selector = pq.sql + selector.Select(selector.Columns(columns...)...) + } + if pq.ctx.Unique != nil && *pq.ctx.Unique { + selector.Distinct() + } + for _, m := range pq.modifiers { + m(selector) + } + for _, p := range pq.predicates { + p(selector) + } + for _, p := range pq.order { + p(selector) + } + if offset := pq.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 := pq.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (pq *ProjectQuery) Modify(modifiers ...func(s *sql.Selector)) *ProjectSelect { + pq.modifiers = append(pq.modifiers, modifiers...) + return pq.Select() +} + +// WithNamedTodos tells the query-builder to eager-load the nodes that are connected to the "todos" +// edge with the given name. The optional arguments are used to configure the query builder of the edge. +func (pq *ProjectQuery) WithNamedTodos(name string, opts ...func(*TodoQuery)) *ProjectQuery { + query := (&TodoClient{config: pq.config}).Query() + for _, opt := range opts { + opt(query) + } + if pq.withNamedTodos == nil { + pq.withNamedTodos = make(map[string]*TodoQuery) + } + pq.withNamedTodos[name] = query + return pq +} + +// ProjectGroupBy is the group-by builder for Project entities. +type ProjectGroupBy struct { + selector + build *ProjectQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (pgb *ProjectGroupBy) Aggregate(fns ...AggregateFunc) *ProjectGroupBy { + pgb.fns = append(pgb.fns, fns...) + return pgb +} + +// Scan applies the selector query and scans the result into the given value. +func (pgb *ProjectGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, pgb.build.ctx, ent.OpQueryGroupBy) + if err := pgb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ProjectQuery, *ProjectGroupBy](ctx, pgb.build, pgb, pgb.build.inters, v) +} + +func (pgb *ProjectGroupBy) sqlScan(ctx context.Context, root *ProjectQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(pgb.fns)) + for _, fn := range pgb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*pgb.flds)+len(pgb.fns)) + for _, f := range *pgb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*pgb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := pgb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// ProjectSelect is the builder for selecting fields of Project entities. +type ProjectSelect struct { + *ProjectQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (ps *ProjectSelect) Aggregate(fns ...AggregateFunc) *ProjectSelect { + ps.fns = append(ps.fns, fns...) + return ps +} + +// Scan applies the selector query and scans the result into the given value. +func (ps *ProjectSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ps.ctx, ent.OpQuerySelect) + if err := ps.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*ProjectQuery, *ProjectSelect](ctx, ps.ProjectQuery, ps, ps.inters, v) +} + +func (ps *ProjectSelect) sqlScan(ctx context.Context, root *ProjectQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(ps.fns)) + for _, fn := range ps.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*ps.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 := ps.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (ps *ProjectSelect) Modify(modifiers ...func(s *sql.Selector)) *ProjectSelect { + ps.modifiers = append(ps.modifiers, modifiers...) + return ps +} diff --git a/entgql/internal/todoglobalid/ent/project_update.go b/entgql/internal/todoglobalid/ent/project_update.go new file mode 100644 index 000000000..301924ad6 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/project_update.go @@ -0,0 +1,368 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/project" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/todo" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// ProjectUpdate is the builder for updating Project entities. +type ProjectUpdate struct { + config + hooks []Hook + mutation *ProjectMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the ProjectUpdate builder. +func (pu *ProjectUpdate) Where(ps ...predicate.Project) *ProjectUpdate { + pu.mutation.Where(ps...) + return pu +} + +// AddTodoIDs adds the "todos" edge to the Todo entity by IDs. +func (pu *ProjectUpdate) AddTodoIDs(ids ...int) *ProjectUpdate { + pu.mutation.AddTodoIDs(ids...) + return pu +} + +// AddTodos adds the "todos" edges to the Todo entity. +func (pu *ProjectUpdate) AddTodos(t ...*Todo) *ProjectUpdate { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return pu.AddTodoIDs(ids...) +} + +// Mutation returns the ProjectMutation object of the builder. +func (pu *ProjectUpdate) Mutation() *ProjectMutation { + return pu.mutation +} + +// ClearTodos clears all "todos" edges to the Todo entity. +func (pu *ProjectUpdate) ClearTodos() *ProjectUpdate { + pu.mutation.ClearTodos() + return pu +} + +// RemoveTodoIDs removes the "todos" edge to Todo entities by IDs. +func (pu *ProjectUpdate) RemoveTodoIDs(ids ...int) *ProjectUpdate { + pu.mutation.RemoveTodoIDs(ids...) + return pu +} + +// RemoveTodos removes "todos" edges to Todo entities. +func (pu *ProjectUpdate) RemoveTodos(t ...*Todo) *ProjectUpdate { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return pu.RemoveTodoIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (pu *ProjectUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, pu.sqlSave, pu.mutation, pu.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (pu *ProjectUpdate) SaveX(ctx context.Context) int { + affected, err := pu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (pu *ProjectUpdate) Exec(ctx context.Context) error { + _, err := pu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (pu *ProjectUpdate) ExecX(ctx context.Context) { + if err := pu.Exec(ctx); err != nil { + panic(err) + } +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (pu *ProjectUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *ProjectUpdate { + pu.modifiers = append(pu.modifiers, modifiers...) + return pu +} + +func (pu *ProjectUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := sqlgraph.NewUpdateSpec(project.Table, project.Columns, sqlgraph.NewFieldSpec(project.FieldID, field.TypeInt)) + if ps := pu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if pu.mutation.TodosCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: project.TodosTable, + Columns: []string{project.TodosColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := pu.mutation.RemovedTodosIDs(); len(nodes) > 0 && !pu.mutation.TodosCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: project.TodosTable, + Columns: []string{project.TodosColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(todo.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 := pu.mutation.TodosIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: project.TodosTable, + Columns: []string{project.TodosColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(pu.modifiers...) + if n, err = sqlgraph.UpdateNodes(ctx, pu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{project.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + pu.mutation.done = true + return n, nil +} + +// ProjectUpdateOne is the builder for updating a single Project entity. +type ProjectUpdateOne struct { + config + fields []string + hooks []Hook + mutation *ProjectMutation + modifiers []func(*sql.UpdateBuilder) +} + +// AddTodoIDs adds the "todos" edge to the Todo entity by IDs. +func (puo *ProjectUpdateOne) AddTodoIDs(ids ...int) *ProjectUpdateOne { + puo.mutation.AddTodoIDs(ids...) + return puo +} + +// AddTodos adds the "todos" edges to the Todo entity. +func (puo *ProjectUpdateOne) AddTodos(t ...*Todo) *ProjectUpdateOne { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return puo.AddTodoIDs(ids...) +} + +// Mutation returns the ProjectMutation object of the builder. +func (puo *ProjectUpdateOne) Mutation() *ProjectMutation { + return puo.mutation +} + +// ClearTodos clears all "todos" edges to the Todo entity. +func (puo *ProjectUpdateOne) ClearTodos() *ProjectUpdateOne { + puo.mutation.ClearTodos() + return puo +} + +// RemoveTodoIDs removes the "todos" edge to Todo entities by IDs. +func (puo *ProjectUpdateOne) RemoveTodoIDs(ids ...int) *ProjectUpdateOne { + puo.mutation.RemoveTodoIDs(ids...) + return puo +} + +// RemoveTodos removes "todos" edges to Todo entities. +func (puo *ProjectUpdateOne) RemoveTodos(t ...*Todo) *ProjectUpdateOne { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return puo.RemoveTodoIDs(ids...) +} + +// Where appends a list predicates to the ProjectUpdate builder. +func (puo *ProjectUpdateOne) Where(ps ...predicate.Project) *ProjectUpdateOne { + puo.mutation.Where(ps...) + return puo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (puo *ProjectUpdateOne) Select(field string, fields ...string) *ProjectUpdateOne { + puo.fields = append([]string{field}, fields...) + return puo +} + +// Save executes the query and returns the updated Project entity. +func (puo *ProjectUpdateOne) Save(ctx context.Context) (*Project, error) { + return withHooks(ctx, puo.sqlSave, puo.mutation, puo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (puo *ProjectUpdateOne) SaveX(ctx context.Context) *Project { + node, err := puo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (puo *ProjectUpdateOne) Exec(ctx context.Context) error { + _, err := puo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (puo *ProjectUpdateOne) ExecX(ctx context.Context) { + if err := puo.Exec(ctx); err != nil { + panic(err) + } +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (puo *ProjectUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *ProjectUpdateOne { + puo.modifiers = append(puo.modifiers, modifiers...) + return puo +} + +func (puo *ProjectUpdateOne) sqlSave(ctx context.Context) (_node *Project, err error) { + _spec := sqlgraph.NewUpdateSpec(project.Table, project.Columns, sqlgraph.NewFieldSpec(project.FieldID, field.TypeInt)) + id, ok := puo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Project.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := puo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, project.FieldID) + for _, f := range fields { + if !project.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != project.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := puo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if puo.mutation.TodosCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: project.TodosTable, + Columns: []string{project.TodosColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := puo.mutation.RemovedTodosIDs(); len(nodes) > 0 && !puo.mutation.TodosCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: project.TodosTable, + Columns: []string{project.TodosColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(todo.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 := puo.mutation.TodosIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: project.TodosTable, + Columns: []string{project.TodosColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(puo.modifiers...) + _node = &Project{config: puo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, puo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{project.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + puo.mutation.done = true + return _node, nil +} diff --git a/entgql/internal/todoglobalid/ent/runtime.go b/entgql/internal/todoglobalid/ent/runtime.go new file mode 100644 index 000000000..0cab45bc1 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/runtime.go @@ -0,0 +1,88 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "time" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/category" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/friendship" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/group" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/onetomany" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/schema" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/todo" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/user" + "github.com/google/uuid" +) + +// The init function reads all schema descriptors with runtime code +// (default values, validators, hooks and policies) and stitches it +// to their package variables. +func init() { + categoryFields := schema.Category{}.Fields() + _ = categoryFields + // categoryDescText is the schema descriptor for text field. + categoryDescText := categoryFields[1].Descriptor() + // category.TextValidator is a validator for the "text" field. It is called by the builders before save. + category.TextValidator = categoryDescText.Validators[0].(func(string) error) + friendshipFields := schema.Friendship{}.Fields() + _ = friendshipFields + // friendshipDescCreatedAt is the schema descriptor for created_at field. + friendshipDescCreatedAt := friendshipFields[0].Descriptor() + // friendship.DefaultCreatedAt holds the default value on creation for the created_at field. + friendship.DefaultCreatedAt = friendshipDescCreatedAt.Default.(func() time.Time) + groupFields := schema.Group{}.Fields() + _ = groupFields + // groupDescName is the schema descriptor for name field. + groupDescName := groupFields[0].Descriptor() + // group.DefaultName holds the default value on creation for the name field. + group.DefaultName = groupDescName.Default.(string) + onetomanyFields := schema.OneToMany{}.Fields() + _ = onetomanyFields + // onetomanyDescName is the schema descriptor for name field. + onetomanyDescName := onetomanyFields[0].Descriptor() + // onetomany.NameValidator is a validator for the "name" field. It is called by the builders before save. + onetomany.NameValidator = onetomanyDescName.Validators[0].(func(string) error) + todoFields := schema.Todo{}.Fields() + _ = todoFields + // todoDescCreatedAt is the schema descriptor for created_at field. + todoDescCreatedAt := todoFields[0].Descriptor() + // todo.DefaultCreatedAt holds the default value on creation for the created_at field. + todo.DefaultCreatedAt = todoDescCreatedAt.Default.(func() time.Time) + // todoDescPriority is the schema descriptor for priority field. + todoDescPriority := todoFields[2].Descriptor() + // todo.DefaultPriority holds the default value on creation for the priority field. + todo.DefaultPriority = todoDescPriority.Default.(int) + // todoDescText is the schema descriptor for text field. + todoDescText := todoFields[3].Descriptor() + // todo.TextValidator is a validator for the "text" field. It is called by the builders before save. + todo.TextValidator = todoDescText.Validators[0].(func(string) error) + // todoDescValue is the schema descriptor for value field. + todoDescValue := todoFields[9].Descriptor() + // todo.DefaultValue holds the default value on creation for the value field. + todo.DefaultValue = todoDescValue.Default.(int) + userFields := schema.User{}.Fields() + _ = userFields + // userDescName is the schema descriptor for name field. + userDescName := userFields[0].Descriptor() + // user.DefaultName holds the default value on creation for the name field. + user.DefaultName = userDescName.Default.(string) + // userDescUsername is the schema descriptor for username field. + userDescUsername := userFields[1].Descriptor() + // user.DefaultUsername holds the default value on creation for the username field. + user.DefaultUsername = userDescUsername.Default.(func() uuid.UUID) +} diff --git a/entgql/internal/todoglobalid/ent/runtime/runtime.go b/entgql/internal/todoglobalid/ent/runtime/runtime.go new file mode 100644 index 000000000..3f014ef2b --- /dev/null +++ b/entgql/internal/todoglobalid/ent/runtime/runtime.go @@ -0,0 +1,24 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package runtime + +// The schema-stitching logic is generated in entgo.io/contrib/entgql/internal/todoglobalid/ent/runtime.go + +const ( + Version = "v0.14.2-0.20250116103911-b91f8daf0e32" // Version of ent codegen. + Sum = "h1:caGPxY54QfxAj6W9Msw3vgOPDved92NoZjHXYiTRFHI=" // Sum of ent codegen. +) diff --git a/entgql/internal/todoglobalid/ent/schema/annotation/has_permissions.go b/entgql/internal/todoglobalid/ent/schema/annotation/has_permissions.go new file mode 100644 index 000000000..e2f380fa3 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/schema/annotation/has_permissions.go @@ -0,0 +1,42 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package annotation + +import ( + "entgo.io/contrib/entgql" + "github.com/vektah/gqlparser/v2/ast" +) + +func HasPermissions(permissions []string) entgql.Directive { + children := make(ast.ChildValueList, 0, len(permissions)) + for _, p := range permissions { + children = append(children, &ast.ChildValue{ + Value: &ast.Value{ + Raw: p, + Kind: ast.StringValue, + }, + }) + } + return entgql.NewDirective( + "hasPermissions", + &ast.Argument{ + Name: "permissions", + Value: &ast.Value{ + Children: children, + Kind: ast.ListValue, + }, + }, + ) +} diff --git a/entgql/internal/todoglobalid/ent/schema/billproduct.go b/entgql/internal/todoglobalid/ent/schema/billproduct.go new file mode 100644 index 000000000..372c21f9e --- /dev/null +++ b/entgql/internal/todoglobalid/ent/schema/billproduct.go @@ -0,0 +1,43 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package schema + +import ( + "entgo.io/contrib/entgql" + "entgo.io/ent" + "entgo.io/ent/schema" + "entgo.io/ent/schema/field" +) + +// BillProduct holds the schema definition for the BillProduct entity. +type BillProduct struct { + ent.Schema +} + +// Fields of the BillProduct. +func (BillProduct) Fields() []ent.Field { + return []ent.Field{ + field.String("name"), + field.String("sku"), + field.Uint64("quantity").Annotations(entgql.Type("Uint64")), + } +} + +// Annotations returns BillProduct annotations. +func (BillProduct) Annotations() []schema.Annotation { + return []schema.Annotation{ + entgql.QueryField(), + } +} diff --git a/entgql/internal/todoglobalid/ent/schema/category.go b/entgql/internal/todoglobalid/ent/schema/category.go new file mode 100644 index 000000000..9e667219e --- /dev/null +++ b/entgql/internal/todoglobalid/ent/schema/category.go @@ -0,0 +1,105 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package schema + +import ( + "time" + + "entgo.io/contrib/entgql" + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/schema/schematype" +) + +// Category holds the schema definition for the Category entity. +type Category struct { + ent.Schema +} + +// Fields of the Category. +func (Category) Fields() []ent.Field { + return []ent.Field{ + field.Int("id"). + Annotations( + // Setting the OrderField explicitly on the "ID" + // field, adds it to the generated GraphQL schema. + entgql.OrderField("ID"), + ), + field.Text("text"). + NotEmpty(). + Annotations( + entgql.OrderField("TEXT"), + ), + field.Enum("status"). + NamedValues( + "Enabled", "ENABLED", + "Disabled", "DISABLED", + ). + Annotations( + entgql.Type("CategoryStatus"), + entgql.OrderField("STATUS"), + ), + field.Other("config", &schematype.CategoryConfig{}). + SchemaType(map[string]string{ + dialect.SQLite: "json", + }). + Optional(), + field.JSON("types", &schematype.CategoryTypes{}). + Optional(), + field.Int64("duration"). + GoType(time.Duration(0)). + Optional(). + Annotations( + entgql.OrderField("DURATION"), + entgql.Type("Duration"), + ), + field.Uint64("count"). + Optional(). + Annotations( + entgql.OrderField("COUNT"), + entgql.Type("Uint64"), + ), + field.Strings("strings"). + Optional(). + Deprecated("use `string` instead"), + } +} + +// Edges of the Category. +func (Category) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("todos", Todo.Type). + Annotations( + entgql.RelayConnection(), + entgql.OrderField("TODOS_COUNT"), + ), + edge.To("sub_categories", Category.Type). + Annotations(entgql.RelayConnection()), + } +} + +// Annotations returns Todo annotations. +func (Category) Annotations() []schema.Annotation { + return []schema.Annotation{ + entgql.QueryField(), + entgql.RelayConnection(), + entgql.Mutations(entgql.MutationCreate(), entgql.MutationUpdate()), + entgql.MultiOrder(), + } +} diff --git a/entgql/internal/todoglobalid/ent/schema/customstruct/custom.go b/entgql/internal/todoglobalid/ent/schema/customstruct/custom.go new file mode 100644 index 000000000..fa525613c --- /dev/null +++ b/entgql/internal/todoglobalid/ent/schema/customstruct/custom.go @@ -0,0 +1,19 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package customstruct + +type Custom struct { + Info string +} diff --git a/entgql/internal/todoglobalid/ent/schema/durationgql/durationgql.go b/entgql/internal/todoglobalid/ent/schema/durationgql/durationgql.go new file mode 100644 index 000000000..04574034c --- /dev/null +++ b/entgql/internal/todoglobalid/ent/schema/durationgql/durationgql.go @@ -0,0 +1,48 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package durationgql + +import ( + "encoding/json" + "fmt" + "io" + "strconv" + "time" + + "github.com/99designs/gqlgen/graphql" +) + +func MarshalDuration(t time.Duration) graphql.Marshaler { + return graphql.WriterFunc(func(w io.Writer) { + _, _ = io.WriteString(w, strconv.FormatInt(int64(t), 10)) + }) +} + +func UnmarshalDuration(v interface{}) (time.Duration, error) { + switch v := v.(type) { + case int64: + return time.Duration(v), nil + case string: + return time.ParseDuration(v) + case json.Number: + i, err := v.Int64() + if err != nil { + return 0, err + } + return time.Duration(i), nil + default: + return 0, fmt.Errorf("invalid type %T, expect string", v) + } +} diff --git a/entgql/internal/todoglobalid/ent/schema/friendship.go b/entgql/internal/todoglobalid/ent/schema/friendship.go new file mode 100644 index 000000000..c41664c15 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/schema/friendship.go @@ -0,0 +1,64 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package schema + +import ( + "time" + + "entgo.io/contrib/entgql" + "entgo.io/ent" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" +) + +// Friendship holds the edge schema definition of the Friendship relationship. +type Friendship struct { + ent.Schema +} + +// Fields of the Friendship. +func (Friendship) Fields() []ent.Field { + return []ent.Field{ + field.Time("created_at"). + Default(time.Now), + field.Int("user_id"), + field.Int("friend_id"), + } +} + +// Edges of the Friendship. +func (Friendship) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("user", User.Type). + Required(). + Unique(). + Field("user_id"), + edge.To("friend", User.Type). + Required(). + Unique(). + Field("friend_id"), + } +} + +// Annotations of the Friendship. +func (Friendship) Annotations() []schema.Annotation { + return []schema.Annotation{ + entgql.RelayConnection(), + entgql.Mutations( + entgql.MutationUpdate(), + ), + } +} diff --git a/entgql/internal/todoglobalid/ent/schema/group.go b/entgql/internal/todoglobalid/ent/schema/group.go new file mode 100644 index 000000000..87ba62935 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/schema/group.go @@ -0,0 +1,59 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package schema + +import ( + "entgo.io/contrib/entgql" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/schema/annotation" + "entgo.io/ent" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" +) + +// Group holds the schema definition for the Group entity. +type Group struct { + ent.Schema +} + +// Fields of the Group. +func (Group) Fields() []ent.Field { + return []ent.Field{ + field.String("name"). + Default("Unknown"), + } +} + +// Edges of the Group. +func (Group) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("users", User.Type). + Ref("groups"). + Annotations(entgql.RelayConnection()), + } +} + +// Annotations returns Group annotations. +func (Group) Annotations() []schema.Annotation { + return []schema.Annotation{ + entgql.RelayConnection(), + entgql.QueryField(), + entgql.Directives( + annotation.HasPermissions([]string{"ADMIN", "MODERATOR"}), + ), + entgql.MultiOrder(), + entgql.Implements("NamedNode"), + } +} diff --git a/entgql/internal/todoglobalid/ent/schema/mixin.go b/entgql/internal/todoglobalid/ent/schema/mixin.go new file mode 100644 index 000000000..8cc04f4f1 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/schema/mixin.go @@ -0,0 +1,69 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package schema + +import "entgo.io/ent" + +type filterFields struct { + ent.Interface + fields map[string]struct{} +} + +func (f *filterFields) Fields() []ent.Field { + fields := f.Interface.Fields() + result := make([]ent.Field, 0, len(fields)) + for _, field := range fields { + if _, ok := f.fields[field.Descriptor().Name]; !ok { + result = append(result, field) + } + } + + return result +} + +func FilterFields(s ent.Interface, filters ...string) ent.Interface { + fields := make(map[string]struct{}) + for _, filter := range filters { + fields[filter] = struct{}{} + } + + return &filterFields{Interface: s, fields: fields} +} + +type filterEdges struct { + ent.Interface + edges map[string]struct{} +} + +func (f *filterEdges) Edges() []ent.Edge { + edges := f.Interface.Edges() + result := make([]ent.Edge, 0, len(edges)) + for _, field := range edges { + if _, ok := f.edges[field.Descriptor().Name]; !ok { + result = append(result, field) + } + } + + return result +} + +func FilterEdges(s ent.Interface, filters ...string) ent.Interface { + edges := make(map[string]struct{}) + for _, filter := range filters { + edges[filter] = struct{}{} + } + + return &filterEdges{Interface: s, edges: edges} +} diff --git a/entgql/internal/todoglobalid/ent/schema/onetomany.go b/entgql/internal/todoglobalid/ent/schema/onetomany.go new file mode 100644 index 000000000..16eeb1004 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/schema/onetomany.go @@ -0,0 +1,63 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package schema + +import ( + "entgo.io/contrib/entgql" + "entgo.io/ent" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" +) + +// OneToMany holds the schema definition for the OneToMany entity. +type OneToMany struct { + ent.Schema +} + +// Fields of the OneToMany. +func (OneToMany) Fields() []ent.Field { + return []ent.Field{ + field.String("name"). + NotEmpty(). + Annotations( + entgql.OrderField("NAME"), + ), + field.String("field2"). + Optional(), + field.Int("parent_id"). + Optional(). + Annotations( + entgql.Skip(entgql.SkipAll), + ), + } +} + +// Edges of the OneToMany. +func (OneToMany) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("children", OneToMany.Type). + From("parent"). + Field("parent_id"). + Unique(), + } +} + +func (OneToMany) Annotations() []schema.Annotation { + return []schema.Annotation{ + entgql.QueryField("oneToMany"), + entgql.RelayConnection(), + } +} diff --git a/entgql/internal/todoglobalid/ent/schema/project.go b/entgql/internal/todoglobalid/ent/schema/project.go new file mode 100644 index 000000000..9fe1a9cf5 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/schema/project.go @@ -0,0 +1,36 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package schema + +import ( + "entgo.io/contrib/entgql" + "entgo.io/ent" + "entgo.io/ent/schema/edge" +) + +// Project holds the schema definition for the GroupTodo entity. +type Project struct { + ent.Schema +} + +// Note, this schema intentionally does not have any fields. + +// Edges of the Project. +func (Project) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("todos", Todo.Type). + Annotations(entgql.RelayConnection()), + } +} diff --git a/entgql/internal/todoglobalid/ent/schema/schematype/schematype.go b/entgql/internal/todoglobalid/ent/schema/schematype/schematype.go new file mode 100644 index 000000000..000782edc --- /dev/null +++ b/entgql/internal/todoglobalid/ent/schema/schematype/schematype.go @@ -0,0 +1,45 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package schematype provides custom types for ent/schema. +package schematype + +import ( + "database/sql/driver" + "encoding/json" +) + +// CategoryConfig implements the field.ValueScanner interface. +type CategoryConfig struct { + MaxMembers int `json:"maxMembers,omitempty"` +} + +func (t *CategoryConfig) Scan(v interface{}) (err error) { + switch v := v.(type) { + case string: + err = json.Unmarshal([]byte(v), t) + case []byte: + err = json.Unmarshal(v, t) + } + return +} + +func (t *CategoryConfig) Value() (driver.Value, error) { + return json.Marshal(t) +} + +// CategoryTypes is a simple JSON type. +type CategoryTypes struct { + Public bool `json:"public,omitempty"` +} diff --git a/entgql/internal/todoglobalid/ent/schema/todo.go b/entgql/internal/todoglobalid/ent/schema/todo.go new file mode 100644 index 000000000..89f85f44d --- /dev/null +++ b/entgql/internal/todoglobalid/ent/schema/todo.go @@ -0,0 +1,132 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package schema + +import ( + "time" + + "entgo.io/contrib/entgql" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/schema/customstruct" + "entgo.io/ent" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" +) + +// Todo defines the todo type schema. +type Todo struct { + ent.Schema +} + +// Fields returns todo fields. +func (Todo) Fields() []ent.Field { + return []ent.Field{ + field.Time("created_at"). + Default(time.Now). + Immutable(). + Annotations( + entgql.OrderField("CREATED_AT"), + entgql.Skip(entgql.SkipMutationCreateInput), + ), + field.Enum("status"). + NamedValues( + "InProgress", "IN_PROGRESS", + "Completed", "COMPLETED", + "Pending", "PENDING", + ). + Annotations( + entgql.OrderField("STATUS"), + ), + field.Int("priority"). + Default(0). + Annotations( + entgql.OrderField("PRIORITY_ORDER"), + entgql.MapsTo("priorityOrder"), + ), + field.Text("text"). + NotEmpty(). + Annotations( + entgql.OrderField("TEXT"), + ), + field.Bytes("blob"). + Annotations( + entgql.Skip(), + ). + Optional(), + field.Int("category_id"). + Optional(). + Immutable(). + Annotations( + entgql.MapsTo("categoryID", "category_id", "categoryX"), + ), + field.JSON("init", map[string]any{}). + Optional(). + Annotations(entgql.Type("Map")), + field.JSON("custom", []customstruct.Custom{}). + Annotations( + entgql.Skip(entgql.SkipMutationCreateInput), + entgql.Skip(entgql.SkipMutationUpdateInput), + ). + Optional(), + field.JSON("customp", []*customstruct.Custom{}). + Annotations( + entgql.Skip(entgql.SkipMutationCreateInput), + entgql.Skip(entgql.SkipMutationUpdateInput), + ). + Optional(), + field.Int("value"). + Default(0), + } +} + +// Edges returns todo edges. +func (Todo) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("children", Todo.Type). + Annotations( + entgql.RelayConnection(), + // For non-unique edges, the order field can be only on edge count. + // The convention is "UPPER()_COUNT". + entgql.OrderField("CHILDREN_COUNT"), + ). + From("parent"). + Annotations( + // For unique edges, the order field can be on the edge field that is defined + // as entgql.OrderField. The convention is "UPPER()_". + entgql.OrderField("PARENT_STATUS"), + ). + Unique(), + edge.From("category", Category.Type). + Ref("todos"). + Field("category_id"). + Unique(). + Immutable(). + Annotations( + entgql.OrderField("CATEGORY_TEXT"), + ), + edge.To("secret", VerySecret.Type). + Unique(), + } +} + +// Annotations returns Todo annotations. +func (Todo) Annotations() []schema.Annotation { + return []schema.Annotation{ + entgql.RelayConnection(), + entgql.QueryField().Description("This is the todo item"), + entgql.Mutations(entgql.MutationCreate(), entgql.MutationUpdate()), + entgql.MultiOrder(), + } +} diff --git a/entgql/internal/todoglobalid/ent/schema/user.go b/entgql/internal/todoglobalid/ent/schema/user.go new file mode 100644 index 000000000..c37be6637 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/schema/user.go @@ -0,0 +1,72 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package schema + +import ( + "entgo.io/contrib/entgql" + "entgo.io/ent" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "github.com/google/uuid" +) + +// User holds the schema definition for the User entity. +type User struct { + ent.Schema +} + +// Fields of the User. +func (User) Fields() []ent.Field { + return []ent.Field{ + field.String("name"). + Default("Anonymous"), + field.UUID("username", uuid.UUID{}). + Default(uuid.New), + field.String("password"). + Sensitive(). + Optional(), + field.JSON("required_metadata", map[string]any{}), + field.JSON("metadata", map[string]any{}). + Optional(), + } +} + +// Edges of the User. +func (User) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("groups", Group.Type). + Comment("The groups of the user"). + Annotations( + entgql.RelayConnection(), + entgql.OrderField("GROUPS_COUNT"), + ), + edge.To("friends", User.Type). + Through("friendships", Friendship.Type). + Annotations(entgql.RelayConnection()), + } +} + +// Annotations returns User annotations. +func (User) Annotations() []schema.Annotation { + return []schema.Annotation{ + entgql.RelayConnection(), + entgql.QueryField(), + entgql.Mutations( + entgql.MutationCreate(), + entgql.MutationUpdate(), + ), + } +} diff --git a/entgql/internal/todoglobalid/ent/schema/verysecret.go b/entgql/internal/todoglobalid/ent/schema/verysecret.go new file mode 100644 index 000000000..9081e6a79 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/schema/verysecret.go @@ -0,0 +1,40 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package schema + +import ( + "entgo.io/contrib/entgql" + "entgo.io/ent" + "entgo.io/ent/schema" + "entgo.io/ent/schema/field" +) + +// VerySecret defines the very secret type schema. +type VerySecret struct { + ent.Schema +} + +// Fields returns private fields. +func (VerySecret) Fields() []ent.Field { + return []ent.Field{ + field.String("password"), + } +} + +func (VerySecret) Annotations() []schema.Annotation { + return []schema.Annotation{ + entgql.Skip(), + } +} diff --git a/entgql/internal/todoglobalid/ent/schema/workspace.go b/entgql/internal/todoglobalid/ent/schema/workspace.go new file mode 100644 index 000000000..eacbe9801 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/schema/workspace.go @@ -0,0 +1,42 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package schema + +import ( + "entgo.io/contrib/entgql" + "entgo.io/ent" + "entgo.io/ent/schema" + "entgo.io/ent/schema/field" +) + +// Workspace defines the workspace type schema. +type Workspace struct { + ent.Schema +} + +// Fields returns workspace fields. +func (Workspace) Fields() []ent.Field { + return []ent.Field{ + field.String("name"), + } +} + +func (Workspace) Annotations() []schema.Annotation { + return []schema.Annotation{ + // Intentionally change the type + // name to test fields collection. + entgql.Type("Organization"), + } +} diff --git a/entgql/internal/todoglobalid/ent/todo.go b/entgql/internal/todoglobalid/ent/todo.go new file mode 100644 index 000000000..a289cd365 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/todo.go @@ -0,0 +1,369 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "encoding/json" + "fmt" + "strings" + "time" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/category" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/schema/customstruct" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/todo" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/verysecret" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// Todo is the model entity for the Todo schema. +type Todo struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // CreatedAt holds the value of the "created_at" field. + CreatedAt time.Time `json:"created_at,omitempty"` + // Status holds the value of the "status" field. + Status todo.Status `json:"status,omitempty"` + // Priority holds the value of the "priority" field. + Priority int `json:"priority,omitempty"` + // Text holds the value of the "text" field. + Text string `json:"text,omitempty"` + // Blob holds the value of the "blob" field. + Blob []byte `json:"blob,omitempty"` + // CategoryID holds the value of the "category_id" field. + CategoryID int `json:"category_id,omitempty"` + // Init holds the value of the "init" field. + Init map[string]interface{} `json:"init,omitempty"` + // Custom holds the value of the "custom" field. + Custom []customstruct.Custom `json:"custom,omitempty"` + // Customp holds the value of the "customp" field. + Customp []*customstruct.Custom `json:"customp,omitempty"` + // Value holds the value of the "value" field. + Value int `json:"value,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the TodoQuery when eager-loading is set. + Edges TodoEdges `json:"edges"` + project_todos *int + todo_children *int + todo_secret *int + selectValues sql.SelectValues +} + +// TodoEdges holds the relations/edges for other nodes in the graph. +type TodoEdges struct { + // Parent holds the value of the parent edge. + Parent *Todo `json:"parent,omitempty"` + // Children holds the value of the children edge. + Children []*Todo `json:"children,omitempty"` + // Category holds the value of the category edge. + Category *Category `json:"category,omitempty"` + // Secret holds the value of the secret edge. + Secret *VerySecret `json:"secret,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [4]bool + // totalCount holds the count of the edges above. + totalCount [3]map[string]int + + namedChildren map[string][]*Todo +} + +// ParentOrErr returns the Parent value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e TodoEdges) ParentOrErr() (*Todo, error) { + if e.Parent != nil { + return e.Parent, nil + } else if e.loadedTypes[0] { + return nil, &NotFoundError{label: todo.Label} + } + return nil, &NotLoadedError{edge: "parent"} +} + +// ChildrenOrErr returns the Children value or an error if the edge +// was not loaded in eager-loading. +func (e TodoEdges) ChildrenOrErr() ([]*Todo, error) { + if e.loadedTypes[1] { + return e.Children, nil + } + return nil, &NotLoadedError{edge: "children"} +} + +// CategoryOrErr returns the Category value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e TodoEdges) CategoryOrErr() (*Category, error) { + if e.Category != nil { + return e.Category, nil + } else if e.loadedTypes[2] { + return nil, &NotFoundError{label: category.Label} + } + return nil, &NotLoadedError{edge: "category"} +} + +// SecretOrErr returns the Secret value or an error if the edge +// was not loaded in eager-loading, or loaded but was not found. +func (e TodoEdges) SecretOrErr() (*VerySecret, error) { + if e.Secret != nil { + return e.Secret, nil + } else if e.loadedTypes[3] { + return nil, &NotFoundError{label: verysecret.Label} + } + return nil, &NotLoadedError{edge: "secret"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Todo) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case todo.FieldBlob, todo.FieldInit, todo.FieldCustom, todo.FieldCustomp: + values[i] = new([]byte) + case todo.FieldID, todo.FieldPriority, todo.FieldCategoryID, todo.FieldValue: + values[i] = new(sql.NullInt64) + case todo.FieldStatus, todo.FieldText: + values[i] = new(sql.NullString) + case todo.FieldCreatedAt: + values[i] = new(sql.NullTime) + case todo.ForeignKeys[0]: // project_todos + values[i] = new(sql.NullInt64) + case todo.ForeignKeys[1]: // todo_children + values[i] = new(sql.NullInt64) + case todo.ForeignKeys[2]: // todo_secret + 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 Todo fields. +func (t *Todo) 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 todo.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + t.ID = int(value.Int64) + case todo.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 { + t.CreatedAt = value.Time + } + case todo.FieldStatus: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field status", values[i]) + } else if value.Valid { + t.Status = todo.Status(value.String) + } + case todo.FieldPriority: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field priority", values[i]) + } else if value.Valid { + t.Priority = int(value.Int64) + } + case todo.FieldText: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field text", values[i]) + } else if value.Valid { + t.Text = value.String + } + case todo.FieldBlob: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field blob", values[i]) + } else if value != nil { + t.Blob = *value + } + case todo.FieldCategoryID: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field category_id", values[i]) + } else if value.Valid { + t.CategoryID = int(value.Int64) + } + case todo.FieldInit: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field init", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &t.Init); err != nil { + return fmt.Errorf("unmarshal field init: %w", err) + } + } + case todo.FieldCustom: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field custom", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &t.Custom); err != nil { + return fmt.Errorf("unmarshal field custom: %w", err) + } + } + case todo.FieldCustomp: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field customp", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &t.Customp); err != nil { + return fmt.Errorf("unmarshal field customp: %w", err) + } + } + case todo.FieldValue: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for field value", values[i]) + } else if value.Valid { + t.Value = int(value.Int64) + } + case todo.ForeignKeys[0]: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for edge-field project_todos", value) + } else if value.Valid { + t.project_todos = new(int) + *t.project_todos = int(value.Int64) + } + case todo.ForeignKeys[1]: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for edge-field todo_children", value) + } else if value.Valid { + t.todo_children = new(int) + *t.todo_children = int(value.Int64) + } + case todo.ForeignKeys[2]: + if value, ok := values[i].(*sql.NullInt64); !ok { + return fmt.Errorf("unexpected type %T for edge-field todo_secret", value) + } else if value.Valid { + t.todo_secret = new(int) + *t.todo_secret = int(value.Int64) + } + default: + t.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// GetValue returns the ent.Value that was dynamically selected and assigned to the Todo. +// This includes values selected through modifiers, order, etc. +func (t *Todo) GetValue(name string) (ent.Value, error) { + return t.selectValues.Get(name) +} + +// QueryParent queries the "parent" edge of the Todo entity. +func (t *Todo) QueryParent() *TodoQuery { + return NewTodoClient(t.config).QueryParent(t) +} + +// QueryChildren queries the "children" edge of the Todo entity. +func (t *Todo) QueryChildren() *TodoQuery { + return NewTodoClient(t.config).QueryChildren(t) +} + +// QueryCategory queries the "category" edge of the Todo entity. +func (t *Todo) QueryCategory() *CategoryQuery { + return NewTodoClient(t.config).QueryCategory(t) +} + +// QuerySecret queries the "secret" edge of the Todo entity. +func (t *Todo) QuerySecret() *VerySecretQuery { + return NewTodoClient(t.config).QuerySecret(t) +} + +// Update returns a builder for updating this Todo. +// Note that you need to call Todo.Unwrap() before calling this method if this Todo +// was returned from a transaction, and the transaction was committed or rolled back. +func (t *Todo) Update() *TodoUpdateOne { + return NewTodoClient(t.config).UpdateOne(t) +} + +// Unwrap unwraps the Todo 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 (t *Todo) Unwrap() *Todo { + _tx, ok := t.config.driver.(*txDriver) + if !ok { + panic("ent: Todo is not a transactional entity") + } + t.config.driver = _tx.drv + return t +} + +// String implements the fmt.Stringer. +func (t *Todo) String() string { + var builder strings.Builder + builder.WriteString("Todo(") + builder.WriteString(fmt.Sprintf("id=%v, ", t.ID)) + builder.WriteString("created_at=") + builder.WriteString(t.CreatedAt.Format(time.ANSIC)) + builder.WriteString(", ") + builder.WriteString("status=") + builder.WriteString(fmt.Sprintf("%v", t.Status)) + builder.WriteString(", ") + builder.WriteString("priority=") + builder.WriteString(fmt.Sprintf("%v", t.Priority)) + builder.WriteString(", ") + builder.WriteString("text=") + builder.WriteString(t.Text) + builder.WriteString(", ") + builder.WriteString("blob=") + builder.WriteString(fmt.Sprintf("%v", t.Blob)) + builder.WriteString(", ") + builder.WriteString("category_id=") + builder.WriteString(fmt.Sprintf("%v", t.CategoryID)) + builder.WriteString(", ") + builder.WriteString("init=") + builder.WriteString(fmt.Sprintf("%v", t.Init)) + builder.WriteString(", ") + builder.WriteString("custom=") + builder.WriteString(fmt.Sprintf("%v", t.Custom)) + builder.WriteString(", ") + builder.WriteString("customp=") + builder.WriteString(fmt.Sprintf("%v", t.Customp)) + builder.WriteString(", ") + builder.WriteString("value=") + builder.WriteString(fmt.Sprintf("%v", t.Value)) + builder.WriteByte(')') + return builder.String() +} + +// NamedChildren returns the Children named value or an error if the edge was not +// loaded in eager-loading with this name. +func (t *Todo) NamedChildren(name string) ([]*Todo, error) { + if t.Edges.namedChildren == nil { + return nil, &NotLoadedError{edge: name} + } + nodes, ok := t.Edges.namedChildren[name] + if !ok { + return nil, &NotLoadedError{edge: name} + } + return nodes, nil +} + +func (t *Todo) appendNamedChildren(name string, edges ...*Todo) { + if t.Edges.namedChildren == nil { + t.Edges.namedChildren = make(map[string][]*Todo) + } + if len(edges) == 0 { + t.Edges.namedChildren[name] = []*Todo{} + } else { + t.Edges.namedChildren[name] = append(t.Edges.namedChildren[name], edges...) + } +} + +// Todos is a parsable slice of Todo. +type Todos []*Todo diff --git a/entgql/internal/todoglobalid/ent/todo/todo.go b/entgql/internal/todoglobalid/ent/todo/todo.go new file mode 100644 index 000000000..e386089d8 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/todo/todo.go @@ -0,0 +1,278 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package todo + +import ( + "fmt" + "io" + "strconv" + "time" + + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +const ( + // Label holds the string label denoting the todo type in the database. + Label = "todo" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldCreatedAt holds the string denoting the created_at field in the database. + FieldCreatedAt = "created_at" + // FieldStatus holds the string denoting the status field in the database. + FieldStatus = "status" + // FieldPriority holds the string denoting the priority field in the database. + FieldPriority = "priority" + // FieldText holds the string denoting the text field in the database. + FieldText = "text" + // FieldBlob holds the string denoting the blob field in the database. + FieldBlob = "blob" + // FieldCategoryID holds the string denoting the category_id field in the database. + FieldCategoryID = "category_id" + // FieldInit holds the string denoting the init field in the database. + FieldInit = "init" + // FieldCustom holds the string denoting the custom field in the database. + FieldCustom = "custom" + // FieldCustomp holds the string denoting the customp field in the database. + FieldCustomp = "customp" + // FieldValue holds the string denoting the value field in the database. + FieldValue = "value" + // EdgeParent holds the string denoting the parent edge name in mutations. + EdgeParent = "parent" + // EdgeChildren holds the string denoting the children edge name in mutations. + EdgeChildren = "children" + // EdgeCategory holds the string denoting the category edge name in mutations. + EdgeCategory = "category" + // EdgeSecret holds the string denoting the secret edge name in mutations. + EdgeSecret = "secret" + // Table holds the table name of the todo in the database. + Table = "todos" + // ParentTable is the table that holds the parent relation/edge. + ParentTable = "todos" + // ParentColumn is the table column denoting the parent relation/edge. + ParentColumn = "todo_children" + // ChildrenTable is the table that holds the children relation/edge. + ChildrenTable = "todos" + // ChildrenColumn is the table column denoting the children relation/edge. + ChildrenColumn = "todo_children" + // CategoryTable is the table that holds the category relation/edge. + CategoryTable = "todos" + // CategoryInverseTable is the table name for the Category entity. + // It exists in this package in order to avoid circular dependency with the "category" package. + CategoryInverseTable = "categories" + // CategoryColumn is the table column denoting the category relation/edge. + CategoryColumn = "category_id" + // SecretTable is the table that holds the secret relation/edge. + SecretTable = "todos" + // SecretInverseTable is the table name for the VerySecret entity. + // It exists in this package in order to avoid circular dependency with the "verysecret" package. + SecretInverseTable = "very_secrets" + // SecretColumn is the table column denoting the secret relation/edge. + SecretColumn = "todo_secret" +) + +// Columns holds all SQL columns for todo fields. +var Columns = []string{ + FieldID, + FieldCreatedAt, + FieldStatus, + FieldPriority, + FieldText, + FieldBlob, + FieldCategoryID, + FieldInit, + FieldCustom, + FieldCustomp, + FieldValue, +} + +// ForeignKeys holds the SQL foreign-keys that are owned by the "todos" +// table and are not defined as standalone fields in the schema. +var ForeignKeys = []string{ + "project_todos", + "todo_children", + "todo_secret", +} + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + for i := range ForeignKeys { + if column == ForeignKeys[i] { + return true + } + } + return false +} + +var ( + // DefaultCreatedAt holds the default value on creation for the "created_at" field. + DefaultCreatedAt func() time.Time + // DefaultPriority holds the default value on creation for the "priority" field. + DefaultPriority int + // TextValidator is a validator for the "text" field. It is called by the builders before save. + TextValidator func(string) error + // DefaultValue holds the default value on creation for the "value" field. + DefaultValue int +) + +// Status defines the type for the "status" enum field. +type Status string + +// Status values. +const ( + StatusInProgress Status = "IN_PROGRESS" + StatusCompleted Status = "COMPLETED" + StatusPending Status = "PENDING" +) + +func (s Status) String() string { + return string(s) +} + +// StatusValidator is a validator for the "status" field enum values. It is called by the builders before save. +func StatusValidator(s Status) error { + switch s { + case StatusInProgress, StatusCompleted, StatusPending: + return nil + default: + return fmt.Errorf("todo: invalid enum value for status field: %q", s) + } +} + +// OrderOption defines the ordering options for the Todo 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() +} + +// ByCreatedAt orders the results by the created_at field. +func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() +} + +// ByStatus orders the results by the status field. +func ByStatus(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldStatus, opts...).ToFunc() +} + +// ByPriority orders the results by the priority field. +func ByPriority(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPriority, opts...).ToFunc() +} + +// ByText orders the results by the text field. +func ByText(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldText, opts...).ToFunc() +} + +// ByCategoryID orders the results by the category_id field. +func ByCategoryID(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldCategoryID, opts...).ToFunc() +} + +// ByValue orders the results by the value field. +func ByValue(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldValue, opts...).ToFunc() +} + +// ByParentField orders the results by parent field. +func ByParentField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newParentStep(), sql.OrderByField(field, opts...)) + } +} + +// ByChildrenCount orders the results by children count. +func ByChildrenCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newChildrenStep(), opts...) + } +} + +// ByChildren orders the results by children terms. +func ByChildren(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newChildrenStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByCategoryField orders the results by category field. +func ByCategoryField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newCategoryStep(), sql.OrderByField(field, opts...)) + } +} + +// BySecretField orders the results by secret field. +func BySecretField(field string, opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newSecretStep(), sql.OrderByField(field, opts...)) + } +} +func newParentStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ParentTable, ParentColumn), + ) +} +func newChildrenStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ChildrenTable, ChildrenColumn), + ) +} +func newCategoryStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(CategoryInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, CategoryTable, CategoryColumn), + ) +} +func newSecretStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(SecretInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, SecretTable, SecretColumn), + ) +} + +// MarshalGQL implements graphql.Marshaler interface. +func (e Status) MarshalGQL(w io.Writer) { + io.WriteString(w, strconv.Quote(e.String())) +} + +// UnmarshalGQL implements graphql.Unmarshaler interface. +func (e *Status) UnmarshalGQL(val interface{}) error { + str, ok := val.(string) + if !ok { + return fmt.Errorf("enum %T must be a string", val) + } + *e = Status(str) + if err := StatusValidator(*e); err != nil { + return fmt.Errorf("%s is not a valid Status", str) + } + return nil +} diff --git a/entgql/internal/todoglobalid/ent/todo/where.go b/entgql/internal/todoglobalid/ent/todo/where.go new file mode 100644 index 000000000..689e6c4f6 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/todo/where.go @@ -0,0 +1,522 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package todo + +import ( + "time" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.Todo { + return predicate.Todo(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.Todo { + return predicate.Todo(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.Todo { + return predicate.Todo(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.Todo { + return predicate.Todo(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.Todo { + return predicate.Todo(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.Todo { + return predicate.Todo(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.Todo { + return predicate.Todo(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.Todo { + return predicate.Todo(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.Todo { + return predicate.Todo(sql.FieldLTE(FieldID, id)) +} + +// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. +func CreatedAt(v time.Time) predicate.Todo { + return predicate.Todo(sql.FieldEQ(FieldCreatedAt, v)) +} + +// Priority applies equality check predicate on the "priority" field. It's identical to PriorityEQ. +func Priority(v int) predicate.Todo { + return predicate.Todo(sql.FieldEQ(FieldPriority, v)) +} + +// Text applies equality check predicate on the "text" field. It's identical to TextEQ. +func Text(v string) predicate.Todo { + return predicate.Todo(sql.FieldEQ(FieldText, v)) +} + +// Blob applies equality check predicate on the "blob" field. It's identical to BlobEQ. +func Blob(v []byte) predicate.Todo { + return predicate.Todo(sql.FieldEQ(FieldBlob, v)) +} + +// CategoryID applies equality check predicate on the "category_id" field. It's identical to CategoryIDEQ. +func CategoryID(v int) predicate.Todo { + return predicate.Todo(sql.FieldEQ(FieldCategoryID, v)) +} + +// Value applies equality check predicate on the "value" field. It's identical to ValueEQ. +func Value(v int) predicate.Todo { + return predicate.Todo(sql.FieldEQ(FieldValue, v)) +} + +// CreatedAtEQ applies the EQ predicate on the "created_at" field. +func CreatedAtEQ(v time.Time) predicate.Todo { + return predicate.Todo(sql.FieldEQ(FieldCreatedAt, v)) +} + +// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. +func CreatedAtNEQ(v time.Time) predicate.Todo { + return predicate.Todo(sql.FieldNEQ(FieldCreatedAt, v)) +} + +// CreatedAtIn applies the In predicate on the "created_at" field. +func CreatedAtIn(vs ...time.Time) predicate.Todo { + return predicate.Todo(sql.FieldIn(FieldCreatedAt, vs...)) +} + +// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. +func CreatedAtNotIn(vs ...time.Time) predicate.Todo { + return predicate.Todo(sql.FieldNotIn(FieldCreatedAt, vs...)) +} + +// CreatedAtGT applies the GT predicate on the "created_at" field. +func CreatedAtGT(v time.Time) predicate.Todo { + return predicate.Todo(sql.FieldGT(FieldCreatedAt, v)) +} + +// CreatedAtGTE applies the GTE predicate on the "created_at" field. +func CreatedAtGTE(v time.Time) predicate.Todo { + return predicate.Todo(sql.FieldGTE(FieldCreatedAt, v)) +} + +// CreatedAtLT applies the LT predicate on the "created_at" field. +func CreatedAtLT(v time.Time) predicate.Todo { + return predicate.Todo(sql.FieldLT(FieldCreatedAt, v)) +} + +// CreatedAtLTE applies the LTE predicate on the "created_at" field. +func CreatedAtLTE(v time.Time) predicate.Todo { + return predicate.Todo(sql.FieldLTE(FieldCreatedAt, v)) +} + +// StatusEQ applies the EQ predicate on the "status" field. +func StatusEQ(v Status) predicate.Todo { + return predicate.Todo(sql.FieldEQ(FieldStatus, v)) +} + +// StatusNEQ applies the NEQ predicate on the "status" field. +func StatusNEQ(v Status) predicate.Todo { + return predicate.Todo(sql.FieldNEQ(FieldStatus, v)) +} + +// StatusIn applies the In predicate on the "status" field. +func StatusIn(vs ...Status) predicate.Todo { + return predicate.Todo(sql.FieldIn(FieldStatus, vs...)) +} + +// StatusNotIn applies the NotIn predicate on the "status" field. +func StatusNotIn(vs ...Status) predicate.Todo { + return predicate.Todo(sql.FieldNotIn(FieldStatus, vs...)) +} + +// PriorityEQ applies the EQ predicate on the "priority" field. +func PriorityEQ(v int) predicate.Todo { + return predicate.Todo(sql.FieldEQ(FieldPriority, v)) +} + +// PriorityNEQ applies the NEQ predicate on the "priority" field. +func PriorityNEQ(v int) predicate.Todo { + return predicate.Todo(sql.FieldNEQ(FieldPriority, v)) +} + +// PriorityIn applies the In predicate on the "priority" field. +func PriorityIn(vs ...int) predicate.Todo { + return predicate.Todo(sql.FieldIn(FieldPriority, vs...)) +} + +// PriorityNotIn applies the NotIn predicate on the "priority" field. +func PriorityNotIn(vs ...int) predicate.Todo { + return predicate.Todo(sql.FieldNotIn(FieldPriority, vs...)) +} + +// PriorityGT applies the GT predicate on the "priority" field. +func PriorityGT(v int) predicate.Todo { + return predicate.Todo(sql.FieldGT(FieldPriority, v)) +} + +// PriorityGTE applies the GTE predicate on the "priority" field. +func PriorityGTE(v int) predicate.Todo { + return predicate.Todo(sql.FieldGTE(FieldPriority, v)) +} + +// PriorityLT applies the LT predicate on the "priority" field. +func PriorityLT(v int) predicate.Todo { + return predicate.Todo(sql.FieldLT(FieldPriority, v)) +} + +// PriorityLTE applies the LTE predicate on the "priority" field. +func PriorityLTE(v int) predicate.Todo { + return predicate.Todo(sql.FieldLTE(FieldPriority, v)) +} + +// TextEQ applies the EQ predicate on the "text" field. +func TextEQ(v string) predicate.Todo { + return predicate.Todo(sql.FieldEQ(FieldText, v)) +} + +// TextNEQ applies the NEQ predicate on the "text" field. +func TextNEQ(v string) predicate.Todo { + return predicate.Todo(sql.FieldNEQ(FieldText, v)) +} + +// TextIn applies the In predicate on the "text" field. +func TextIn(vs ...string) predicate.Todo { + return predicate.Todo(sql.FieldIn(FieldText, vs...)) +} + +// TextNotIn applies the NotIn predicate on the "text" field. +func TextNotIn(vs ...string) predicate.Todo { + return predicate.Todo(sql.FieldNotIn(FieldText, vs...)) +} + +// TextGT applies the GT predicate on the "text" field. +func TextGT(v string) predicate.Todo { + return predicate.Todo(sql.FieldGT(FieldText, v)) +} + +// TextGTE applies the GTE predicate on the "text" field. +func TextGTE(v string) predicate.Todo { + return predicate.Todo(sql.FieldGTE(FieldText, v)) +} + +// TextLT applies the LT predicate on the "text" field. +func TextLT(v string) predicate.Todo { + return predicate.Todo(sql.FieldLT(FieldText, v)) +} + +// TextLTE applies the LTE predicate on the "text" field. +func TextLTE(v string) predicate.Todo { + return predicate.Todo(sql.FieldLTE(FieldText, v)) +} + +// TextContains applies the Contains predicate on the "text" field. +func TextContains(v string) predicate.Todo { + return predicate.Todo(sql.FieldContains(FieldText, v)) +} + +// TextHasPrefix applies the HasPrefix predicate on the "text" field. +func TextHasPrefix(v string) predicate.Todo { + return predicate.Todo(sql.FieldHasPrefix(FieldText, v)) +} + +// TextHasSuffix applies the HasSuffix predicate on the "text" field. +func TextHasSuffix(v string) predicate.Todo { + return predicate.Todo(sql.FieldHasSuffix(FieldText, v)) +} + +// TextEqualFold applies the EqualFold predicate on the "text" field. +func TextEqualFold(v string) predicate.Todo { + return predicate.Todo(sql.FieldEqualFold(FieldText, v)) +} + +// TextContainsFold applies the ContainsFold predicate on the "text" field. +func TextContainsFold(v string) predicate.Todo { + return predicate.Todo(sql.FieldContainsFold(FieldText, v)) +} + +// BlobEQ applies the EQ predicate on the "blob" field. +func BlobEQ(v []byte) predicate.Todo { + return predicate.Todo(sql.FieldEQ(FieldBlob, v)) +} + +// BlobNEQ applies the NEQ predicate on the "blob" field. +func BlobNEQ(v []byte) predicate.Todo { + return predicate.Todo(sql.FieldNEQ(FieldBlob, v)) +} + +// BlobIn applies the In predicate on the "blob" field. +func BlobIn(vs ...[]byte) predicate.Todo { + return predicate.Todo(sql.FieldIn(FieldBlob, vs...)) +} + +// BlobNotIn applies the NotIn predicate on the "blob" field. +func BlobNotIn(vs ...[]byte) predicate.Todo { + return predicate.Todo(sql.FieldNotIn(FieldBlob, vs...)) +} + +// BlobGT applies the GT predicate on the "blob" field. +func BlobGT(v []byte) predicate.Todo { + return predicate.Todo(sql.FieldGT(FieldBlob, v)) +} + +// BlobGTE applies the GTE predicate on the "blob" field. +func BlobGTE(v []byte) predicate.Todo { + return predicate.Todo(sql.FieldGTE(FieldBlob, v)) +} + +// BlobLT applies the LT predicate on the "blob" field. +func BlobLT(v []byte) predicate.Todo { + return predicate.Todo(sql.FieldLT(FieldBlob, v)) +} + +// BlobLTE applies the LTE predicate on the "blob" field. +func BlobLTE(v []byte) predicate.Todo { + return predicate.Todo(sql.FieldLTE(FieldBlob, v)) +} + +// BlobIsNil applies the IsNil predicate on the "blob" field. +func BlobIsNil() predicate.Todo { + return predicate.Todo(sql.FieldIsNull(FieldBlob)) +} + +// BlobNotNil applies the NotNil predicate on the "blob" field. +func BlobNotNil() predicate.Todo { + return predicate.Todo(sql.FieldNotNull(FieldBlob)) +} + +// CategoryIDEQ applies the EQ predicate on the "category_id" field. +func CategoryIDEQ(v int) predicate.Todo { + return predicate.Todo(sql.FieldEQ(FieldCategoryID, v)) +} + +// CategoryIDNEQ applies the NEQ predicate on the "category_id" field. +func CategoryIDNEQ(v int) predicate.Todo { + return predicate.Todo(sql.FieldNEQ(FieldCategoryID, v)) +} + +// CategoryIDIn applies the In predicate on the "category_id" field. +func CategoryIDIn(vs ...int) predicate.Todo { + return predicate.Todo(sql.FieldIn(FieldCategoryID, vs...)) +} + +// CategoryIDNotIn applies the NotIn predicate on the "category_id" field. +func CategoryIDNotIn(vs ...int) predicate.Todo { + return predicate.Todo(sql.FieldNotIn(FieldCategoryID, vs...)) +} + +// CategoryIDIsNil applies the IsNil predicate on the "category_id" field. +func CategoryIDIsNil() predicate.Todo { + return predicate.Todo(sql.FieldIsNull(FieldCategoryID)) +} + +// CategoryIDNotNil applies the NotNil predicate on the "category_id" field. +func CategoryIDNotNil() predicate.Todo { + return predicate.Todo(sql.FieldNotNull(FieldCategoryID)) +} + +// InitIsNil applies the IsNil predicate on the "init" field. +func InitIsNil() predicate.Todo { + return predicate.Todo(sql.FieldIsNull(FieldInit)) +} + +// InitNotNil applies the NotNil predicate on the "init" field. +func InitNotNil() predicate.Todo { + return predicate.Todo(sql.FieldNotNull(FieldInit)) +} + +// CustomIsNil applies the IsNil predicate on the "custom" field. +func CustomIsNil() predicate.Todo { + return predicate.Todo(sql.FieldIsNull(FieldCustom)) +} + +// CustomNotNil applies the NotNil predicate on the "custom" field. +func CustomNotNil() predicate.Todo { + return predicate.Todo(sql.FieldNotNull(FieldCustom)) +} + +// CustompIsNil applies the IsNil predicate on the "customp" field. +func CustompIsNil() predicate.Todo { + return predicate.Todo(sql.FieldIsNull(FieldCustomp)) +} + +// CustompNotNil applies the NotNil predicate on the "customp" field. +func CustompNotNil() predicate.Todo { + return predicate.Todo(sql.FieldNotNull(FieldCustomp)) +} + +// ValueEQ applies the EQ predicate on the "value" field. +func ValueEQ(v int) predicate.Todo { + return predicate.Todo(sql.FieldEQ(FieldValue, v)) +} + +// ValueNEQ applies the NEQ predicate on the "value" field. +func ValueNEQ(v int) predicate.Todo { + return predicate.Todo(sql.FieldNEQ(FieldValue, v)) +} + +// ValueIn applies the In predicate on the "value" field. +func ValueIn(vs ...int) predicate.Todo { + return predicate.Todo(sql.FieldIn(FieldValue, vs...)) +} + +// ValueNotIn applies the NotIn predicate on the "value" field. +func ValueNotIn(vs ...int) predicate.Todo { + return predicate.Todo(sql.FieldNotIn(FieldValue, vs...)) +} + +// ValueGT applies the GT predicate on the "value" field. +func ValueGT(v int) predicate.Todo { + return predicate.Todo(sql.FieldGT(FieldValue, v)) +} + +// ValueGTE applies the GTE predicate on the "value" field. +func ValueGTE(v int) predicate.Todo { + return predicate.Todo(sql.FieldGTE(FieldValue, v)) +} + +// ValueLT applies the LT predicate on the "value" field. +func ValueLT(v int) predicate.Todo { + return predicate.Todo(sql.FieldLT(FieldValue, v)) +} + +// ValueLTE applies the LTE predicate on the "value" field. +func ValueLTE(v int) predicate.Todo { + return predicate.Todo(sql.FieldLTE(FieldValue, v)) +} + +// HasParent applies the HasEdge predicate on the "parent" edge. +func HasParent() predicate.Todo { + return predicate.Todo(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, ParentTable, ParentColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasParentWith applies the HasEdge predicate on the "parent" edge with a given conditions (other predicates). +func HasParentWith(preds ...predicate.Todo) predicate.Todo { + return predicate.Todo(func(s *sql.Selector) { + step := newParentStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasChildren applies the HasEdge predicate on the "children" edge. +func HasChildren() predicate.Todo { + return predicate.Todo(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, ChildrenTable, ChildrenColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasChildrenWith applies the HasEdge predicate on the "children" edge with a given conditions (other predicates). +func HasChildrenWith(preds ...predicate.Todo) predicate.Todo { + return predicate.Todo(func(s *sql.Selector) { + step := newChildrenStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasCategory applies the HasEdge predicate on the "category" edge. +func HasCategory() predicate.Todo { + return predicate.Todo(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, CategoryTable, CategoryColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasCategoryWith applies the HasEdge predicate on the "category" edge with a given conditions (other predicates). +func HasCategoryWith(preds ...predicate.Category) predicate.Todo { + return predicate.Todo(func(s *sql.Selector) { + step := newCategoryStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasSecret applies the HasEdge predicate on the "secret" edge. +func HasSecret() predicate.Todo { + return predicate.Todo(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, SecretTable, SecretColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasSecretWith applies the HasEdge predicate on the "secret" edge with a given conditions (other predicates). +func HasSecretWith(preds ...predicate.VerySecret) predicate.Todo { + return predicate.Todo(func(s *sql.Selector) { + step := newSecretStep() + 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.Todo) predicate.Todo { + return predicate.Todo(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Todo) predicate.Todo { + return predicate.Todo(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Todo) predicate.Todo { + return predicate.Todo(sql.NotPredicates(p)) +} diff --git a/entgql/internal/todoglobalid/ent/todo_create.go b/entgql/internal/todoglobalid/ent/todo_create.go new file mode 100644 index 000000000..ed9581707 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/todo_create.go @@ -0,0 +1,484 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + "time" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/category" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/schema/customstruct" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/todo" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/verysecret" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// TodoCreate is the builder for creating a Todo entity. +type TodoCreate struct { + config + mutation *TodoMutation + hooks []Hook +} + +// SetCreatedAt sets the "created_at" field. +func (tc *TodoCreate) SetCreatedAt(t time.Time) *TodoCreate { + tc.mutation.SetCreatedAt(t) + return tc +} + +// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. +func (tc *TodoCreate) SetNillableCreatedAt(t *time.Time) *TodoCreate { + if t != nil { + tc.SetCreatedAt(*t) + } + return tc +} + +// SetStatus sets the "status" field. +func (tc *TodoCreate) SetStatus(t todo.Status) *TodoCreate { + tc.mutation.SetStatus(t) + return tc +} + +// SetPriority sets the "priority" field. +func (tc *TodoCreate) SetPriority(i int) *TodoCreate { + tc.mutation.SetPriority(i) + return tc +} + +// SetNillablePriority sets the "priority" field if the given value is not nil. +func (tc *TodoCreate) SetNillablePriority(i *int) *TodoCreate { + if i != nil { + tc.SetPriority(*i) + } + return tc +} + +// SetText sets the "text" field. +func (tc *TodoCreate) SetText(s string) *TodoCreate { + tc.mutation.SetText(s) + return tc +} + +// SetBlob sets the "blob" field. +func (tc *TodoCreate) SetBlob(b []byte) *TodoCreate { + tc.mutation.SetBlob(b) + return tc +} + +// SetCategoryID sets the "category_id" field. +func (tc *TodoCreate) SetCategoryID(i int) *TodoCreate { + tc.mutation.SetCategoryID(i) + return tc +} + +// SetNillableCategoryID sets the "category_id" field if the given value is not nil. +func (tc *TodoCreate) SetNillableCategoryID(i *int) *TodoCreate { + if i != nil { + tc.SetCategoryID(*i) + } + return tc +} + +// SetInit sets the "init" field. +func (tc *TodoCreate) SetInit(m map[string]interface{}) *TodoCreate { + tc.mutation.SetInit(m) + return tc +} + +// SetCustom sets the "custom" field. +func (tc *TodoCreate) SetCustom(c []customstruct.Custom) *TodoCreate { + tc.mutation.SetCustom(c) + return tc +} + +// SetCustomp sets the "customp" field. +func (tc *TodoCreate) SetCustomp(c []*customstruct.Custom) *TodoCreate { + tc.mutation.SetCustomp(c) + return tc +} + +// SetValue sets the "value" field. +func (tc *TodoCreate) SetValue(i int) *TodoCreate { + tc.mutation.SetValue(i) + return tc +} + +// SetNillableValue sets the "value" field if the given value is not nil. +func (tc *TodoCreate) SetNillableValue(i *int) *TodoCreate { + if i != nil { + tc.SetValue(*i) + } + return tc +} + +// SetParentID sets the "parent" edge to the Todo entity by ID. +func (tc *TodoCreate) SetParentID(id int) *TodoCreate { + tc.mutation.SetParentID(id) + return tc +} + +// SetNillableParentID sets the "parent" edge to the Todo entity by ID if the given value is not nil. +func (tc *TodoCreate) SetNillableParentID(id *int) *TodoCreate { + if id != nil { + tc = tc.SetParentID(*id) + } + return tc +} + +// SetParent sets the "parent" edge to the Todo entity. +func (tc *TodoCreate) SetParent(t *Todo) *TodoCreate { + return tc.SetParentID(t.ID) +} + +// AddChildIDs adds the "children" edge to the Todo entity by IDs. +func (tc *TodoCreate) AddChildIDs(ids ...int) *TodoCreate { + tc.mutation.AddChildIDs(ids...) + return tc +} + +// AddChildren adds the "children" edges to the Todo entity. +func (tc *TodoCreate) AddChildren(t ...*Todo) *TodoCreate { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tc.AddChildIDs(ids...) +} + +// SetCategory sets the "category" edge to the Category entity. +func (tc *TodoCreate) SetCategory(c *Category) *TodoCreate { + return tc.SetCategoryID(c.ID) +} + +// SetSecretID sets the "secret" edge to the VerySecret entity by ID. +func (tc *TodoCreate) SetSecretID(id int) *TodoCreate { + tc.mutation.SetSecretID(id) + return tc +} + +// SetNillableSecretID sets the "secret" edge to the VerySecret entity by ID if the given value is not nil. +func (tc *TodoCreate) SetNillableSecretID(id *int) *TodoCreate { + if id != nil { + tc = tc.SetSecretID(*id) + } + return tc +} + +// SetSecret sets the "secret" edge to the VerySecret entity. +func (tc *TodoCreate) SetSecret(v *VerySecret) *TodoCreate { + return tc.SetSecretID(v.ID) +} + +// Mutation returns the TodoMutation object of the builder. +func (tc *TodoCreate) Mutation() *TodoMutation { + return tc.mutation +} + +// Save creates the Todo in the database. +func (tc *TodoCreate) Save(ctx context.Context) (*Todo, error) { + tc.defaults() + return withHooks(ctx, tc.sqlSave, tc.mutation, tc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (tc *TodoCreate) SaveX(ctx context.Context) *Todo { + v, err := tc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (tc *TodoCreate) Exec(ctx context.Context) error { + _, err := tc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tc *TodoCreate) ExecX(ctx context.Context) { + if err := tc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (tc *TodoCreate) defaults() { + if _, ok := tc.mutation.CreatedAt(); !ok { + v := todo.DefaultCreatedAt() + tc.mutation.SetCreatedAt(v) + } + if _, ok := tc.mutation.Priority(); !ok { + v := todo.DefaultPriority + tc.mutation.SetPriority(v) + } + if _, ok := tc.mutation.Value(); !ok { + v := todo.DefaultValue + tc.mutation.SetValue(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (tc *TodoCreate) check() error { + if _, ok := tc.mutation.CreatedAt(); !ok { + return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Todo.created_at"`)} + } + if _, ok := tc.mutation.Status(); !ok { + return &ValidationError{Name: "status", err: errors.New(`ent: missing required field "Todo.status"`)} + } + if v, ok := tc.mutation.Status(); ok { + if err := todo.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "Todo.status": %w`, err)} + } + } + if _, ok := tc.mutation.Priority(); !ok { + return &ValidationError{Name: "priority", err: errors.New(`ent: missing required field "Todo.priority"`)} + } + if _, ok := tc.mutation.Text(); !ok { + return &ValidationError{Name: "text", err: errors.New(`ent: missing required field "Todo.text"`)} + } + if v, ok := tc.mutation.Text(); ok { + if err := todo.TextValidator(v); err != nil { + return &ValidationError{Name: "text", err: fmt.Errorf(`ent: validator failed for field "Todo.text": %w`, err)} + } + } + if _, ok := tc.mutation.Value(); !ok { + return &ValidationError{Name: "value", err: errors.New(`ent: missing required field "Todo.value"`)} + } + return nil +} + +func (tc *TodoCreate) sqlSave(ctx context.Context) (*Todo, error) { + if err := tc.check(); err != nil { + return nil, err + } + _node, _spec := tc.createSpec() + if err := sqlgraph.CreateNode(ctx, tc.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) + tc.mutation.id = &_node.ID + tc.mutation.done = true + return _node, nil +} + +func (tc *TodoCreate) createSpec() (*Todo, *sqlgraph.CreateSpec) { + var ( + _node = &Todo{config: tc.config} + _spec = sqlgraph.NewCreateSpec(todo.Table, sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt)) + ) + if value, ok := tc.mutation.CreatedAt(); ok { + _spec.SetField(todo.FieldCreatedAt, field.TypeTime, value) + _node.CreatedAt = value + } + if value, ok := tc.mutation.Status(); ok { + _spec.SetField(todo.FieldStatus, field.TypeEnum, value) + _node.Status = value + } + if value, ok := tc.mutation.Priority(); ok { + _spec.SetField(todo.FieldPriority, field.TypeInt, value) + _node.Priority = value + } + if value, ok := tc.mutation.Text(); ok { + _spec.SetField(todo.FieldText, field.TypeString, value) + _node.Text = value + } + if value, ok := tc.mutation.Blob(); ok { + _spec.SetField(todo.FieldBlob, field.TypeBytes, value) + _node.Blob = value + } + if value, ok := tc.mutation.Init(); ok { + _spec.SetField(todo.FieldInit, field.TypeJSON, value) + _node.Init = value + } + if value, ok := tc.mutation.Custom(); ok { + _spec.SetField(todo.FieldCustom, field.TypeJSON, value) + _node.Custom = value + } + if value, ok := tc.mutation.Customp(); ok { + _spec.SetField(todo.FieldCustomp, field.TypeJSON, value) + _node.Customp = value + } + if value, ok := tc.mutation.Value(); ok { + _spec.SetField(todo.FieldValue, field.TypeInt, value) + _node.Value = value + } + if nodes := tc.mutation.ParentIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: todo.ParentTable, + Columns: []string{todo.ParentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.todo_children = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := tc.mutation.ChildrenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: todo.ChildrenTable, + Columns: []string{todo.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := tc.mutation.CategoryIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: todo.CategoryTable, + Columns: []string{todo.CategoryColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(category.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.CategoryID = nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := tc.mutation.SecretIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: todo.SecretTable, + Columns: []string{todo.SecretColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(verysecret.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _node.todo_secret = &nodes[0] + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// TodoCreateBulk is the builder for creating many Todo entities in bulk. +type TodoCreateBulk struct { + config + err error + builders []*TodoCreate +} + +// Save creates the Todo entities in the database. +func (tcb *TodoCreateBulk) Save(ctx context.Context) ([]*Todo, error) { + if tcb.err != nil { + return nil, tcb.err + } + specs := make([]*sqlgraph.CreateSpec, len(tcb.builders)) + nodes := make([]*Todo, len(tcb.builders)) + mutators := make([]Mutator, len(tcb.builders)) + for i := range tcb.builders { + func(i int, root context.Context) { + builder := tcb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*TodoMutation) + 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, tcb.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, tcb.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, tcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (tcb *TodoCreateBulk) SaveX(ctx context.Context) []*Todo { + v, err := tcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (tcb *TodoCreateBulk) Exec(ctx context.Context) error { + _, err := tcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tcb *TodoCreateBulk) ExecX(ctx context.Context) { + if err := tcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entgql/internal/todoglobalid/ent/todo_delete.go b/entgql/internal/todoglobalid/ent/todo_delete.go new file mode 100644 index 000000000..6effb0bb2 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/todo_delete.go @@ -0,0 +1,102 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/todo" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// TodoDelete is the builder for deleting a Todo entity. +type TodoDelete struct { + config + hooks []Hook + mutation *TodoMutation +} + +// Where appends a list predicates to the TodoDelete builder. +func (td *TodoDelete) Where(ps ...predicate.Todo) *TodoDelete { + td.mutation.Where(ps...) + return td +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (td *TodoDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, td.sqlExec, td.mutation, td.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (td *TodoDelete) ExecX(ctx context.Context) int { + n, err := td.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (td *TodoDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(todo.Table, sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt)) + if ps := td.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, td.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + td.mutation.done = true + return affected, err +} + +// TodoDeleteOne is the builder for deleting a single Todo entity. +type TodoDeleteOne struct { + td *TodoDelete +} + +// Where appends a list predicates to the TodoDelete builder. +func (tdo *TodoDeleteOne) Where(ps ...predicate.Todo) *TodoDeleteOne { + tdo.td.mutation.Where(ps...) + return tdo +} + +// Exec executes the deletion query. +func (tdo *TodoDeleteOne) Exec(ctx context.Context) error { + n, err := tdo.td.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{todo.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (tdo *TodoDeleteOne) ExecX(ctx context.Context) { + if err := tdo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entgql/internal/todoglobalid/ent/todo_query.go b/entgql/internal/todoglobalid/ent/todo_query.go new file mode 100644 index 000000000..31529d23a --- /dev/null +++ b/entgql/internal/todoglobalid/ent/todo_query.go @@ -0,0 +1,903 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "database/sql/driver" + "fmt" + "math" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/category" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/todo" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/verysecret" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// TodoQuery is the builder for querying Todo entities. +type TodoQuery struct { + config + ctx *QueryContext + order []todo.OrderOption + inters []Interceptor + predicates []predicate.Todo + withParent *TodoQuery + withChildren *TodoQuery + withCategory *CategoryQuery + withSecret *VerySecretQuery + withFKs bool + loadTotal []func(context.Context, []*Todo) error + modifiers []func(*sql.Selector) + withNamedChildren map[string]*TodoQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the TodoQuery builder. +func (tq *TodoQuery) Where(ps ...predicate.Todo) *TodoQuery { + tq.predicates = append(tq.predicates, ps...) + return tq +} + +// Limit the number of records to be returned by this query. +func (tq *TodoQuery) Limit(limit int) *TodoQuery { + tq.ctx.Limit = &limit + return tq +} + +// Offset to start from. +func (tq *TodoQuery) Offset(offset int) *TodoQuery { + tq.ctx.Offset = &offset + return tq +} + +// 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 (tq *TodoQuery) Unique(unique bool) *TodoQuery { + tq.ctx.Unique = &unique + return tq +} + +// Order specifies how the records should be ordered. +func (tq *TodoQuery) Order(o ...todo.OrderOption) *TodoQuery { + tq.order = append(tq.order, o...) + return tq +} + +// QueryParent chains the current query on the "parent" edge. +func (tq *TodoQuery) QueryParent() *TodoQuery { + query := (&TodoClient{config: tq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := tq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := tq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(todo.Table, todo.FieldID, selector), + sqlgraph.To(todo.Table, todo.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, todo.ParentTable, todo.ParentColumn), + ) + fromU = sqlgraph.SetNeighbors(tq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryChildren chains the current query on the "children" edge. +func (tq *TodoQuery) QueryChildren() *TodoQuery { + query := (&TodoClient{config: tq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := tq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := tq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(todo.Table, todo.FieldID, selector), + sqlgraph.To(todo.Table, todo.FieldID), + sqlgraph.Edge(sqlgraph.O2M, false, todo.ChildrenTable, todo.ChildrenColumn), + ) + fromU = sqlgraph.SetNeighbors(tq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryCategory chains the current query on the "category" edge. +func (tq *TodoQuery) QueryCategory() *CategoryQuery { + query := (&CategoryClient{config: tq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := tq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := tq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(todo.Table, todo.FieldID, selector), + sqlgraph.To(category.Table, category.FieldID), + sqlgraph.Edge(sqlgraph.M2O, true, todo.CategoryTable, todo.CategoryColumn), + ) + fromU = sqlgraph.SetNeighbors(tq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QuerySecret chains the current query on the "secret" edge. +func (tq *TodoQuery) QuerySecret() *VerySecretQuery { + query := (&VerySecretClient{config: tq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := tq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := tq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(todo.Table, todo.FieldID, selector), + sqlgraph.To(verysecret.Table, verysecret.FieldID), + sqlgraph.Edge(sqlgraph.M2O, false, todo.SecretTable, todo.SecretColumn), + ) + fromU = sqlgraph.SetNeighbors(tq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first Todo entity from the query. +// Returns a *NotFoundError when no Todo was found. +func (tq *TodoQuery) First(ctx context.Context) (*Todo, error) { + nodes, err := tq.Limit(1).All(setContextOp(ctx, tq.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{todo.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (tq *TodoQuery) FirstX(ctx context.Context) *Todo { + node, err := tq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Todo ID from the query. +// Returns a *NotFoundError when no Todo ID was found. +func (tq *TodoQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = tq.Limit(1).IDs(setContextOp(ctx, tq.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{todo.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (tq *TodoQuery) FirstIDX(ctx context.Context) int { + id, err := tq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Todo entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Todo entity is found. +// Returns a *NotFoundError when no Todo entities are found. +func (tq *TodoQuery) Only(ctx context.Context) (*Todo, error) { + nodes, err := tq.Limit(2).All(setContextOp(ctx, tq.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{todo.Label} + default: + return nil, &NotSingularError{todo.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (tq *TodoQuery) OnlyX(ctx context.Context) *Todo { + node, err := tq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Todo ID in the query. +// Returns a *NotSingularError when more than one Todo ID is found. +// Returns a *NotFoundError when no entities are found. +func (tq *TodoQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = tq.Limit(2).IDs(setContextOp(ctx, tq.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{todo.Label} + default: + err = &NotSingularError{todo.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (tq *TodoQuery) OnlyIDX(ctx context.Context) int { + id, err := tq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Todos. +func (tq *TodoQuery) All(ctx context.Context) ([]*Todo, error) { + ctx = setContextOp(ctx, tq.ctx, ent.OpQueryAll) + if err := tq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Todo, *TodoQuery]() + return withInterceptors[[]*Todo](ctx, tq, qr, tq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (tq *TodoQuery) AllX(ctx context.Context) []*Todo { + nodes, err := tq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Todo IDs. +func (tq *TodoQuery) IDs(ctx context.Context) (ids []int, err error) { + if tq.ctx.Unique == nil && tq.path != nil { + tq.Unique(true) + } + ctx = setContextOp(ctx, tq.ctx, ent.OpQueryIDs) + if err = tq.Select(todo.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (tq *TodoQuery) IDsX(ctx context.Context) []int { + ids, err := tq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (tq *TodoQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, tq.ctx, ent.OpQueryCount) + if err := tq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, tq, querierCount[*TodoQuery](), tq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (tq *TodoQuery) CountX(ctx context.Context) int { + count, err := tq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (tq *TodoQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, tq.ctx, ent.OpQueryExist) + switch _, err := tq.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 (tq *TodoQuery) ExistX(ctx context.Context) bool { + exist, err := tq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the TodoQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (tq *TodoQuery) Clone() *TodoQuery { + if tq == nil { + return nil + } + return &TodoQuery{ + config: tq.config, + ctx: tq.ctx.Clone(), + order: append([]todo.OrderOption{}, tq.order...), + inters: append([]Interceptor{}, tq.inters...), + predicates: append([]predicate.Todo{}, tq.predicates...), + withParent: tq.withParent.Clone(), + withChildren: tq.withChildren.Clone(), + withCategory: tq.withCategory.Clone(), + withSecret: tq.withSecret.Clone(), + // clone intermediate query. + sql: tq.sql.Clone(), + path: tq.path, + modifiers: append([]func(*sql.Selector){}, tq.modifiers...), + } +} + +// WithParent tells the query-builder to eager-load the nodes that are connected to +// the "parent" edge. The optional arguments are used to configure the query builder of the edge. +func (tq *TodoQuery) WithParent(opts ...func(*TodoQuery)) *TodoQuery { + query := (&TodoClient{config: tq.config}).Query() + for _, opt := range opts { + opt(query) + } + tq.withParent = query + return tq +} + +// WithChildren tells the query-builder to eager-load the nodes that are connected to +// the "children" edge. The optional arguments are used to configure the query builder of the edge. +func (tq *TodoQuery) WithChildren(opts ...func(*TodoQuery)) *TodoQuery { + query := (&TodoClient{config: tq.config}).Query() + for _, opt := range opts { + opt(query) + } + tq.withChildren = query + return tq +} + +// WithCategory tells the query-builder to eager-load the nodes that are connected to +// the "category" edge. The optional arguments are used to configure the query builder of the edge. +func (tq *TodoQuery) WithCategory(opts ...func(*CategoryQuery)) *TodoQuery { + query := (&CategoryClient{config: tq.config}).Query() + for _, opt := range opts { + opt(query) + } + tq.withCategory = query + return tq +} + +// WithSecret tells the query-builder to eager-load the nodes that are connected to +// the "secret" edge. The optional arguments are used to configure the query builder of the edge. +func (tq *TodoQuery) WithSecret(opts ...func(*VerySecretQuery)) *TodoQuery { + query := (&VerySecretClient{config: tq.config}).Query() + for _, opt := range opts { + opt(query) + } + tq.withSecret = query + return tq +} + +// GroupBy is used to group vertices by one or more fields/columns. +// It is often used with aggregate functions, like: count, max, mean, min, sum. +// +// Example: +// +// var v []struct { +// CreatedAt time.Time `json:"created_at,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Todo.Query(). +// GroupBy(todo.FieldCreatedAt). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (tq *TodoQuery) GroupBy(field string, fields ...string) *TodoGroupBy { + tq.ctx.Fields = append([]string{field}, fields...) + grbuild := &TodoGroupBy{build: tq} + grbuild.flds = &tq.ctx.Fields + grbuild.label = todo.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 { +// CreatedAt time.Time `json:"created_at,omitempty"` +// } +// +// client.Todo.Query(). +// Select(todo.FieldCreatedAt). +// Scan(ctx, &v) +func (tq *TodoQuery) Select(fields ...string) *TodoSelect { + tq.ctx.Fields = append(tq.ctx.Fields, fields...) + sbuild := &TodoSelect{TodoQuery: tq} + sbuild.label = todo.Label + sbuild.flds, sbuild.scan = &tq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a TodoSelect configured with the given aggregations. +func (tq *TodoQuery) Aggregate(fns ...AggregateFunc) *TodoSelect { + return tq.Select().Aggregate(fns...) +} + +func (tq *TodoQuery) prepareQuery(ctx context.Context) error { + for _, inter := range tq.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, tq); err != nil { + return err + } + } + } + for _, f := range tq.ctx.Fields { + if !todo.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if tq.path != nil { + prev, err := tq.path(ctx) + if err != nil { + return err + } + tq.sql = prev + } + return nil +} + +func (tq *TodoQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Todo, error) { + var ( + nodes = []*Todo{} + withFKs = tq.withFKs + _spec = tq.querySpec() + loadedTypes = [4]bool{ + tq.withParent != nil, + tq.withChildren != nil, + tq.withCategory != nil, + tq.withSecret != nil, + } + ) + if tq.withParent != nil || tq.withSecret != nil { + withFKs = true + } + if withFKs { + _spec.Node.Columns = append(_spec.Node.Columns, todo.ForeignKeys...) + } + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Todo).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Todo{config: tq.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(tq.modifiers) > 0 { + _spec.Modifiers = tq.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, tq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := tq.withParent; query != nil { + if err := tq.loadParent(ctx, query, nodes, nil, + func(n *Todo, e *Todo) { n.Edges.Parent = e }); err != nil { + return nil, err + } + } + if query := tq.withChildren; query != nil { + if err := tq.loadChildren(ctx, query, nodes, + func(n *Todo) { n.Edges.Children = []*Todo{} }, + func(n *Todo, e *Todo) { n.Edges.Children = append(n.Edges.Children, e) }); err != nil { + return nil, err + } + } + if query := tq.withCategory; query != nil { + if err := tq.loadCategory(ctx, query, nodes, nil, + func(n *Todo, e *Category) { n.Edges.Category = e }); err != nil { + return nil, err + } + } + if query := tq.withSecret; query != nil { + if err := tq.loadSecret(ctx, query, nodes, nil, + func(n *Todo, e *VerySecret) { n.Edges.Secret = e }); err != nil { + return nil, err + } + } + for name, query := range tq.withNamedChildren { + if err := tq.loadChildren(ctx, query, nodes, + func(n *Todo) { n.appendNamedChildren(name) }, + func(n *Todo, e *Todo) { n.appendNamedChildren(name, e) }); err != nil { + return nil, err + } + } + for i := range tq.loadTotal { + if err := tq.loadTotal[i](ctx, nodes); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (tq *TodoQuery) loadParent(ctx context.Context, query *TodoQuery, nodes []*Todo, init func(*Todo), assign func(*Todo, *Todo)) error { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*Todo) + for i := range nodes { + if nodes[i].todo_children == nil { + continue + } + fk := *nodes[i].todo_children + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(todo.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 "todo_children" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (tq *TodoQuery) loadChildren(ctx context.Context, query *TodoQuery, nodes []*Todo, init func(*Todo), assign func(*Todo, *Todo)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*Todo) + 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.Todo(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(todo.ChildrenColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.todo_children + if fk == nil { + return fmt.Errorf(`foreign-key "todo_children" is nil for node %v`, n.ID) + } + node, ok := nodeids[*fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "todo_children" returned %v for node %v`, *fk, n.ID) + } + assign(node, n) + } + return nil +} +func (tq *TodoQuery) loadCategory(ctx context.Context, query *CategoryQuery, nodes []*Todo, init func(*Todo), assign func(*Todo, *Category)) error { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*Todo) + for i := range nodes { + fk := nodes[i].CategoryID + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(category.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 "category_id" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} +func (tq *TodoQuery) loadSecret(ctx context.Context, query *VerySecretQuery, nodes []*Todo, init func(*Todo), assign func(*Todo, *VerySecret)) error { + ids := make([]int, 0, len(nodes)) + nodeids := make(map[int][]*Todo) + for i := range nodes { + if nodes[i].todo_secret == nil { + continue + } + fk := *nodes[i].todo_secret + if _, ok := nodeids[fk]; !ok { + ids = append(ids, fk) + } + nodeids[fk] = append(nodeids[fk], nodes[i]) + } + if len(ids) == 0 { + return nil + } + query.Where(verysecret.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 "todo_secret" returned %v`, n.ID) + } + for i := range nodes { + assign(nodes[i], n) + } + } + return nil +} + +func (tq *TodoQuery) sqlCount(ctx context.Context) (int, error) { + _spec := tq.querySpec() + if len(tq.modifiers) > 0 { + _spec.Modifiers = tq.modifiers + } + _spec.Node.Columns = tq.ctx.Fields + if len(tq.ctx.Fields) > 0 { + _spec.Unique = tq.ctx.Unique != nil && *tq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, tq.driver, _spec) +} + +func (tq *TodoQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(todo.Table, todo.Columns, sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt)) + _spec.From = tq.sql + if unique := tq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if tq.path != nil { + _spec.Unique = true + } + if fields := tq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, todo.FieldID) + for i := range fields { + if fields[i] != todo.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + if tq.withCategory != nil { + _spec.Node.AddColumnOnce(todo.FieldCategoryID) + } + } + if ps := tq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := tq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := tq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := tq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (tq *TodoQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(tq.driver.Dialect()) + t1 := builder.Table(todo.Table) + columns := tq.ctx.Fields + if len(columns) == 0 { + columns = todo.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if tq.sql != nil { + selector = tq.sql + selector.Select(selector.Columns(columns...)...) + } + if tq.ctx.Unique != nil && *tq.ctx.Unique { + selector.Distinct() + } + for _, m := range tq.modifiers { + m(selector) + } + for _, p := range tq.predicates { + p(selector) + } + for _, p := range tq.order { + p(selector) + } + if offset := tq.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 := tq.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (tq *TodoQuery) Modify(modifiers ...func(s *sql.Selector)) *TodoSelect { + tq.modifiers = append(tq.modifiers, modifiers...) + return tq.Select() +} + +// WithNamedChildren tells the query-builder to eager-load the nodes that are connected to the "children" +// edge with the given name. The optional arguments are used to configure the query builder of the edge. +func (tq *TodoQuery) WithNamedChildren(name string, opts ...func(*TodoQuery)) *TodoQuery { + query := (&TodoClient{config: tq.config}).Query() + for _, opt := range opts { + opt(query) + } + if tq.withNamedChildren == nil { + tq.withNamedChildren = make(map[string]*TodoQuery) + } + tq.withNamedChildren[name] = query + return tq +} + +// TodoGroupBy is the group-by builder for Todo entities. +type TodoGroupBy struct { + selector + build *TodoQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (tgb *TodoGroupBy) Aggregate(fns ...AggregateFunc) *TodoGroupBy { + tgb.fns = append(tgb.fns, fns...) + return tgb +} + +// Scan applies the selector query and scans the result into the given value. +func (tgb *TodoGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, tgb.build.ctx, ent.OpQueryGroupBy) + if err := tgb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*TodoQuery, *TodoGroupBy](ctx, tgb.build, tgb, tgb.build.inters, v) +} + +func (tgb *TodoGroupBy) sqlScan(ctx context.Context, root *TodoQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(tgb.fns)) + for _, fn := range tgb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*tgb.flds)+len(tgb.fns)) + for _, f := range *tgb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*tgb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := tgb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// TodoSelect is the builder for selecting fields of Todo entities. +type TodoSelect struct { + *TodoQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (ts *TodoSelect) Aggregate(fns ...AggregateFunc) *TodoSelect { + ts.fns = append(ts.fns, fns...) + return ts +} + +// Scan applies the selector query and scans the result into the given value. +func (ts *TodoSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ts.ctx, ent.OpQuerySelect) + if err := ts.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*TodoQuery, *TodoSelect](ctx, ts.TodoQuery, ts, ts.inters, v) +} + +func (ts *TodoSelect) sqlScan(ctx context.Context, root *TodoQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(ts.fns)) + for _, fn := range ts.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*ts.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 := ts.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (ts *TodoSelect) Modify(modifiers ...func(s *sql.Selector)) *TodoSelect { + ts.modifiers = append(ts.modifiers, modifiers...) + return ts +} diff --git a/entgql/internal/todoglobalid/ent/todo_update.go b/entgql/internal/todoglobalid/ent/todo_update.go new file mode 100644 index 000000000..92353858a --- /dev/null +++ b/entgql/internal/todoglobalid/ent/todo_update.go @@ -0,0 +1,986 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/schema/customstruct" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/todo" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/verysecret" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/dialect/sql/sqljson" + "entgo.io/ent/schema/field" +) + +// TodoUpdate is the builder for updating Todo entities. +type TodoUpdate struct { + config + hooks []Hook + mutation *TodoMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the TodoUpdate builder. +func (tu *TodoUpdate) Where(ps ...predicate.Todo) *TodoUpdate { + tu.mutation.Where(ps...) + return tu +} + +// SetStatus sets the "status" field. +func (tu *TodoUpdate) SetStatus(t todo.Status) *TodoUpdate { + tu.mutation.SetStatus(t) + return tu +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (tu *TodoUpdate) SetNillableStatus(t *todo.Status) *TodoUpdate { + if t != nil { + tu.SetStatus(*t) + } + return tu +} + +// SetPriority sets the "priority" field. +func (tu *TodoUpdate) SetPriority(i int) *TodoUpdate { + tu.mutation.ResetPriority() + tu.mutation.SetPriority(i) + return tu +} + +// SetNillablePriority sets the "priority" field if the given value is not nil. +func (tu *TodoUpdate) SetNillablePriority(i *int) *TodoUpdate { + if i != nil { + tu.SetPriority(*i) + } + return tu +} + +// AddPriority adds i to the "priority" field. +func (tu *TodoUpdate) AddPriority(i int) *TodoUpdate { + tu.mutation.AddPriority(i) + return tu +} + +// SetText sets the "text" field. +func (tu *TodoUpdate) SetText(s string) *TodoUpdate { + tu.mutation.SetText(s) + return tu +} + +// SetNillableText sets the "text" field if the given value is not nil. +func (tu *TodoUpdate) SetNillableText(s *string) *TodoUpdate { + if s != nil { + tu.SetText(*s) + } + return tu +} + +// SetBlob sets the "blob" field. +func (tu *TodoUpdate) SetBlob(b []byte) *TodoUpdate { + tu.mutation.SetBlob(b) + return tu +} + +// ClearBlob clears the value of the "blob" field. +func (tu *TodoUpdate) ClearBlob() *TodoUpdate { + tu.mutation.ClearBlob() + return tu +} + +// SetInit sets the "init" field. +func (tu *TodoUpdate) SetInit(m map[string]interface{}) *TodoUpdate { + tu.mutation.SetInit(m) + return tu +} + +// ClearInit clears the value of the "init" field. +func (tu *TodoUpdate) ClearInit() *TodoUpdate { + tu.mutation.ClearInit() + return tu +} + +// SetCustom sets the "custom" field. +func (tu *TodoUpdate) SetCustom(c []customstruct.Custom) *TodoUpdate { + tu.mutation.SetCustom(c) + return tu +} + +// AppendCustom appends c to the "custom" field. +func (tu *TodoUpdate) AppendCustom(c []customstruct.Custom) *TodoUpdate { + tu.mutation.AppendCustom(c) + return tu +} + +// ClearCustom clears the value of the "custom" field. +func (tu *TodoUpdate) ClearCustom() *TodoUpdate { + tu.mutation.ClearCustom() + return tu +} + +// SetCustomp sets the "customp" field. +func (tu *TodoUpdate) SetCustomp(c []*customstruct.Custom) *TodoUpdate { + tu.mutation.SetCustomp(c) + return tu +} + +// AppendCustomp appends c to the "customp" field. +func (tu *TodoUpdate) AppendCustomp(c []*customstruct.Custom) *TodoUpdate { + tu.mutation.AppendCustomp(c) + return tu +} + +// ClearCustomp clears the value of the "customp" field. +func (tu *TodoUpdate) ClearCustomp() *TodoUpdate { + tu.mutation.ClearCustomp() + return tu +} + +// SetValue sets the "value" field. +func (tu *TodoUpdate) SetValue(i int) *TodoUpdate { + tu.mutation.ResetValue() + tu.mutation.SetValue(i) + return tu +} + +// SetNillableValue sets the "value" field if the given value is not nil. +func (tu *TodoUpdate) SetNillableValue(i *int) *TodoUpdate { + if i != nil { + tu.SetValue(*i) + } + return tu +} + +// AddValue adds i to the "value" field. +func (tu *TodoUpdate) AddValue(i int) *TodoUpdate { + tu.mutation.AddValue(i) + return tu +} + +// SetParentID sets the "parent" edge to the Todo entity by ID. +func (tu *TodoUpdate) SetParentID(id int) *TodoUpdate { + tu.mutation.SetParentID(id) + return tu +} + +// SetNillableParentID sets the "parent" edge to the Todo entity by ID if the given value is not nil. +func (tu *TodoUpdate) SetNillableParentID(id *int) *TodoUpdate { + if id != nil { + tu = tu.SetParentID(*id) + } + return tu +} + +// SetParent sets the "parent" edge to the Todo entity. +func (tu *TodoUpdate) SetParent(t *Todo) *TodoUpdate { + return tu.SetParentID(t.ID) +} + +// AddChildIDs adds the "children" edge to the Todo entity by IDs. +func (tu *TodoUpdate) AddChildIDs(ids ...int) *TodoUpdate { + tu.mutation.AddChildIDs(ids...) + return tu +} + +// AddChildren adds the "children" edges to the Todo entity. +func (tu *TodoUpdate) AddChildren(t ...*Todo) *TodoUpdate { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tu.AddChildIDs(ids...) +} + +// SetSecretID sets the "secret" edge to the VerySecret entity by ID. +func (tu *TodoUpdate) SetSecretID(id int) *TodoUpdate { + tu.mutation.SetSecretID(id) + return tu +} + +// SetNillableSecretID sets the "secret" edge to the VerySecret entity by ID if the given value is not nil. +func (tu *TodoUpdate) SetNillableSecretID(id *int) *TodoUpdate { + if id != nil { + tu = tu.SetSecretID(*id) + } + return tu +} + +// SetSecret sets the "secret" edge to the VerySecret entity. +func (tu *TodoUpdate) SetSecret(v *VerySecret) *TodoUpdate { + return tu.SetSecretID(v.ID) +} + +// Mutation returns the TodoMutation object of the builder. +func (tu *TodoUpdate) Mutation() *TodoMutation { + return tu.mutation +} + +// ClearParent clears the "parent" edge to the Todo entity. +func (tu *TodoUpdate) ClearParent() *TodoUpdate { + tu.mutation.ClearParent() + return tu +} + +// ClearChildren clears all "children" edges to the Todo entity. +func (tu *TodoUpdate) ClearChildren() *TodoUpdate { + tu.mutation.ClearChildren() + return tu +} + +// RemoveChildIDs removes the "children" edge to Todo entities by IDs. +func (tu *TodoUpdate) RemoveChildIDs(ids ...int) *TodoUpdate { + tu.mutation.RemoveChildIDs(ids...) + return tu +} + +// RemoveChildren removes "children" edges to Todo entities. +func (tu *TodoUpdate) RemoveChildren(t ...*Todo) *TodoUpdate { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tu.RemoveChildIDs(ids...) +} + +// ClearSecret clears the "secret" edge to the VerySecret entity. +func (tu *TodoUpdate) ClearSecret() *TodoUpdate { + tu.mutation.ClearSecret() + return tu +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (tu *TodoUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, tu.sqlSave, tu.mutation, tu.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (tu *TodoUpdate) SaveX(ctx context.Context) int { + affected, err := tu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (tu *TodoUpdate) Exec(ctx context.Context) error { + _, err := tu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tu *TodoUpdate) ExecX(ctx context.Context) { + if err := tu.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (tu *TodoUpdate) check() error { + if v, ok := tu.mutation.Status(); ok { + if err := todo.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "Todo.status": %w`, err)} + } + } + if v, ok := tu.mutation.Text(); ok { + if err := todo.TextValidator(v); err != nil { + return &ValidationError{Name: "text", err: fmt.Errorf(`ent: validator failed for field "Todo.text": %w`, err)} + } + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (tu *TodoUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *TodoUpdate { + tu.modifiers = append(tu.modifiers, modifiers...) + return tu +} + +func (tu *TodoUpdate) sqlSave(ctx context.Context) (n int, err error) { + if err := tu.check(); err != nil { + return n, err + } + _spec := sqlgraph.NewUpdateSpec(todo.Table, todo.Columns, sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt)) + if ps := tu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := tu.mutation.Status(); ok { + _spec.SetField(todo.FieldStatus, field.TypeEnum, value) + } + if value, ok := tu.mutation.Priority(); ok { + _spec.SetField(todo.FieldPriority, field.TypeInt, value) + } + if value, ok := tu.mutation.AddedPriority(); ok { + _spec.AddField(todo.FieldPriority, field.TypeInt, value) + } + if value, ok := tu.mutation.Text(); ok { + _spec.SetField(todo.FieldText, field.TypeString, value) + } + if value, ok := tu.mutation.Blob(); ok { + _spec.SetField(todo.FieldBlob, field.TypeBytes, value) + } + if tu.mutation.BlobCleared() { + _spec.ClearField(todo.FieldBlob, field.TypeBytes) + } + if value, ok := tu.mutation.Init(); ok { + _spec.SetField(todo.FieldInit, field.TypeJSON, value) + } + if tu.mutation.InitCleared() { + _spec.ClearField(todo.FieldInit, field.TypeJSON) + } + if value, ok := tu.mutation.Custom(); ok { + _spec.SetField(todo.FieldCustom, field.TypeJSON, value) + } + if value, ok := tu.mutation.AppendedCustom(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, todo.FieldCustom, value) + }) + } + if tu.mutation.CustomCleared() { + _spec.ClearField(todo.FieldCustom, field.TypeJSON) + } + if value, ok := tu.mutation.Customp(); ok { + _spec.SetField(todo.FieldCustomp, field.TypeJSON, value) + } + if value, ok := tu.mutation.AppendedCustomp(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, todo.FieldCustomp, value) + }) + } + if tu.mutation.CustompCleared() { + _spec.ClearField(todo.FieldCustomp, field.TypeJSON) + } + if value, ok := tu.mutation.Value(); ok { + _spec.SetField(todo.FieldValue, field.TypeInt, value) + } + if value, ok := tu.mutation.AddedValue(); ok { + _spec.AddField(todo.FieldValue, field.TypeInt, value) + } + if tu.mutation.ParentCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: todo.ParentTable, + Columns: []string{todo.ParentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tu.mutation.ParentIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: todo.ParentTable, + Columns: []string{todo.ParentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if tu.mutation.ChildrenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: todo.ChildrenTable, + Columns: []string{todo.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tu.mutation.RemovedChildrenIDs(); len(nodes) > 0 && !tu.mutation.ChildrenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: todo.ChildrenTable, + Columns: []string{todo.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(todo.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 := tu.mutation.ChildrenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: todo.ChildrenTable, + Columns: []string{todo.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if tu.mutation.SecretCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: todo.SecretTable, + Columns: []string{todo.SecretColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(verysecret.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tu.mutation.SecretIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: todo.SecretTable, + Columns: []string{todo.SecretColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(verysecret.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(tu.modifiers...) + if n, err = sqlgraph.UpdateNodes(ctx, tu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{todo.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + tu.mutation.done = true + return n, nil +} + +// TodoUpdateOne is the builder for updating a single Todo entity. +type TodoUpdateOne struct { + config + fields []string + hooks []Hook + mutation *TodoMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetStatus sets the "status" field. +func (tuo *TodoUpdateOne) SetStatus(t todo.Status) *TodoUpdateOne { + tuo.mutation.SetStatus(t) + return tuo +} + +// SetNillableStatus sets the "status" field if the given value is not nil. +func (tuo *TodoUpdateOne) SetNillableStatus(t *todo.Status) *TodoUpdateOne { + if t != nil { + tuo.SetStatus(*t) + } + return tuo +} + +// SetPriority sets the "priority" field. +func (tuo *TodoUpdateOne) SetPriority(i int) *TodoUpdateOne { + tuo.mutation.ResetPriority() + tuo.mutation.SetPriority(i) + return tuo +} + +// SetNillablePriority sets the "priority" field if the given value is not nil. +func (tuo *TodoUpdateOne) SetNillablePriority(i *int) *TodoUpdateOne { + if i != nil { + tuo.SetPriority(*i) + } + return tuo +} + +// AddPriority adds i to the "priority" field. +func (tuo *TodoUpdateOne) AddPriority(i int) *TodoUpdateOne { + tuo.mutation.AddPriority(i) + return tuo +} + +// SetText sets the "text" field. +func (tuo *TodoUpdateOne) SetText(s string) *TodoUpdateOne { + tuo.mutation.SetText(s) + return tuo +} + +// SetNillableText sets the "text" field if the given value is not nil. +func (tuo *TodoUpdateOne) SetNillableText(s *string) *TodoUpdateOne { + if s != nil { + tuo.SetText(*s) + } + return tuo +} + +// SetBlob sets the "blob" field. +func (tuo *TodoUpdateOne) SetBlob(b []byte) *TodoUpdateOne { + tuo.mutation.SetBlob(b) + return tuo +} + +// ClearBlob clears the value of the "blob" field. +func (tuo *TodoUpdateOne) ClearBlob() *TodoUpdateOne { + tuo.mutation.ClearBlob() + return tuo +} + +// SetInit sets the "init" field. +func (tuo *TodoUpdateOne) SetInit(m map[string]interface{}) *TodoUpdateOne { + tuo.mutation.SetInit(m) + return tuo +} + +// ClearInit clears the value of the "init" field. +func (tuo *TodoUpdateOne) ClearInit() *TodoUpdateOne { + tuo.mutation.ClearInit() + return tuo +} + +// SetCustom sets the "custom" field. +func (tuo *TodoUpdateOne) SetCustom(c []customstruct.Custom) *TodoUpdateOne { + tuo.mutation.SetCustom(c) + return tuo +} + +// AppendCustom appends c to the "custom" field. +func (tuo *TodoUpdateOne) AppendCustom(c []customstruct.Custom) *TodoUpdateOne { + tuo.mutation.AppendCustom(c) + return tuo +} + +// ClearCustom clears the value of the "custom" field. +func (tuo *TodoUpdateOne) ClearCustom() *TodoUpdateOne { + tuo.mutation.ClearCustom() + return tuo +} + +// SetCustomp sets the "customp" field. +func (tuo *TodoUpdateOne) SetCustomp(c []*customstruct.Custom) *TodoUpdateOne { + tuo.mutation.SetCustomp(c) + return tuo +} + +// AppendCustomp appends c to the "customp" field. +func (tuo *TodoUpdateOne) AppendCustomp(c []*customstruct.Custom) *TodoUpdateOne { + tuo.mutation.AppendCustomp(c) + return tuo +} + +// ClearCustomp clears the value of the "customp" field. +func (tuo *TodoUpdateOne) ClearCustomp() *TodoUpdateOne { + tuo.mutation.ClearCustomp() + return tuo +} + +// SetValue sets the "value" field. +func (tuo *TodoUpdateOne) SetValue(i int) *TodoUpdateOne { + tuo.mutation.ResetValue() + tuo.mutation.SetValue(i) + return tuo +} + +// SetNillableValue sets the "value" field if the given value is not nil. +func (tuo *TodoUpdateOne) SetNillableValue(i *int) *TodoUpdateOne { + if i != nil { + tuo.SetValue(*i) + } + return tuo +} + +// AddValue adds i to the "value" field. +func (tuo *TodoUpdateOne) AddValue(i int) *TodoUpdateOne { + tuo.mutation.AddValue(i) + return tuo +} + +// SetParentID sets the "parent" edge to the Todo entity by ID. +func (tuo *TodoUpdateOne) SetParentID(id int) *TodoUpdateOne { + tuo.mutation.SetParentID(id) + return tuo +} + +// SetNillableParentID sets the "parent" edge to the Todo entity by ID if the given value is not nil. +func (tuo *TodoUpdateOne) SetNillableParentID(id *int) *TodoUpdateOne { + if id != nil { + tuo = tuo.SetParentID(*id) + } + return tuo +} + +// SetParent sets the "parent" edge to the Todo entity. +func (tuo *TodoUpdateOne) SetParent(t *Todo) *TodoUpdateOne { + return tuo.SetParentID(t.ID) +} + +// AddChildIDs adds the "children" edge to the Todo entity by IDs. +func (tuo *TodoUpdateOne) AddChildIDs(ids ...int) *TodoUpdateOne { + tuo.mutation.AddChildIDs(ids...) + return tuo +} + +// AddChildren adds the "children" edges to the Todo entity. +func (tuo *TodoUpdateOne) AddChildren(t ...*Todo) *TodoUpdateOne { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tuo.AddChildIDs(ids...) +} + +// SetSecretID sets the "secret" edge to the VerySecret entity by ID. +func (tuo *TodoUpdateOne) SetSecretID(id int) *TodoUpdateOne { + tuo.mutation.SetSecretID(id) + return tuo +} + +// SetNillableSecretID sets the "secret" edge to the VerySecret entity by ID if the given value is not nil. +func (tuo *TodoUpdateOne) SetNillableSecretID(id *int) *TodoUpdateOne { + if id != nil { + tuo = tuo.SetSecretID(*id) + } + return tuo +} + +// SetSecret sets the "secret" edge to the VerySecret entity. +func (tuo *TodoUpdateOne) SetSecret(v *VerySecret) *TodoUpdateOne { + return tuo.SetSecretID(v.ID) +} + +// Mutation returns the TodoMutation object of the builder. +func (tuo *TodoUpdateOne) Mutation() *TodoMutation { + return tuo.mutation +} + +// ClearParent clears the "parent" edge to the Todo entity. +func (tuo *TodoUpdateOne) ClearParent() *TodoUpdateOne { + tuo.mutation.ClearParent() + return tuo +} + +// ClearChildren clears all "children" edges to the Todo entity. +func (tuo *TodoUpdateOne) ClearChildren() *TodoUpdateOne { + tuo.mutation.ClearChildren() + return tuo +} + +// RemoveChildIDs removes the "children" edge to Todo entities by IDs. +func (tuo *TodoUpdateOne) RemoveChildIDs(ids ...int) *TodoUpdateOne { + tuo.mutation.RemoveChildIDs(ids...) + return tuo +} + +// RemoveChildren removes "children" edges to Todo entities. +func (tuo *TodoUpdateOne) RemoveChildren(t ...*Todo) *TodoUpdateOne { + ids := make([]int, len(t)) + for i := range t { + ids[i] = t[i].ID + } + return tuo.RemoveChildIDs(ids...) +} + +// ClearSecret clears the "secret" edge to the VerySecret entity. +func (tuo *TodoUpdateOne) ClearSecret() *TodoUpdateOne { + tuo.mutation.ClearSecret() + return tuo +} + +// Where appends a list predicates to the TodoUpdate builder. +func (tuo *TodoUpdateOne) Where(ps ...predicate.Todo) *TodoUpdateOne { + tuo.mutation.Where(ps...) + return tuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (tuo *TodoUpdateOne) Select(field string, fields ...string) *TodoUpdateOne { + tuo.fields = append([]string{field}, fields...) + return tuo +} + +// Save executes the query and returns the updated Todo entity. +func (tuo *TodoUpdateOne) Save(ctx context.Context) (*Todo, error) { + return withHooks(ctx, tuo.sqlSave, tuo.mutation, tuo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (tuo *TodoUpdateOne) SaveX(ctx context.Context) *Todo { + node, err := tuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (tuo *TodoUpdateOne) Exec(ctx context.Context) error { + _, err := tuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (tuo *TodoUpdateOne) ExecX(ctx context.Context) { + if err := tuo.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (tuo *TodoUpdateOne) check() error { + if v, ok := tuo.mutation.Status(); ok { + if err := todo.StatusValidator(v); err != nil { + return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "Todo.status": %w`, err)} + } + } + if v, ok := tuo.mutation.Text(); ok { + if err := todo.TextValidator(v); err != nil { + return &ValidationError{Name: "text", err: fmt.Errorf(`ent: validator failed for field "Todo.text": %w`, err)} + } + } + return nil +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (tuo *TodoUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *TodoUpdateOne { + tuo.modifiers = append(tuo.modifiers, modifiers...) + return tuo +} + +func (tuo *TodoUpdateOne) sqlSave(ctx context.Context) (_node *Todo, err error) { + if err := tuo.check(); err != nil { + return _node, err + } + _spec := sqlgraph.NewUpdateSpec(todo.Table, todo.Columns, sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt)) + id, ok := tuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Todo.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := tuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, todo.FieldID) + for _, f := range fields { + if !todo.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != todo.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := tuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := tuo.mutation.Status(); ok { + _spec.SetField(todo.FieldStatus, field.TypeEnum, value) + } + if value, ok := tuo.mutation.Priority(); ok { + _spec.SetField(todo.FieldPriority, field.TypeInt, value) + } + if value, ok := tuo.mutation.AddedPriority(); ok { + _spec.AddField(todo.FieldPriority, field.TypeInt, value) + } + if value, ok := tuo.mutation.Text(); ok { + _spec.SetField(todo.FieldText, field.TypeString, value) + } + if value, ok := tuo.mutation.Blob(); ok { + _spec.SetField(todo.FieldBlob, field.TypeBytes, value) + } + if tuo.mutation.BlobCleared() { + _spec.ClearField(todo.FieldBlob, field.TypeBytes) + } + if value, ok := tuo.mutation.Init(); ok { + _spec.SetField(todo.FieldInit, field.TypeJSON, value) + } + if tuo.mutation.InitCleared() { + _spec.ClearField(todo.FieldInit, field.TypeJSON) + } + if value, ok := tuo.mutation.Custom(); ok { + _spec.SetField(todo.FieldCustom, field.TypeJSON, value) + } + if value, ok := tuo.mutation.AppendedCustom(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, todo.FieldCustom, value) + }) + } + if tuo.mutation.CustomCleared() { + _spec.ClearField(todo.FieldCustom, field.TypeJSON) + } + if value, ok := tuo.mutation.Customp(); ok { + _spec.SetField(todo.FieldCustomp, field.TypeJSON, value) + } + if value, ok := tuo.mutation.AppendedCustomp(); ok { + _spec.AddModifier(func(u *sql.UpdateBuilder) { + sqljson.Append(u, todo.FieldCustomp, value) + }) + } + if tuo.mutation.CustompCleared() { + _spec.ClearField(todo.FieldCustomp, field.TypeJSON) + } + if value, ok := tuo.mutation.Value(); ok { + _spec.SetField(todo.FieldValue, field.TypeInt, value) + } + if value, ok := tuo.mutation.AddedValue(); ok { + _spec.AddField(todo.FieldValue, field.TypeInt, value) + } + if tuo.mutation.ParentCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: todo.ParentTable, + Columns: []string{todo.ParentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tuo.mutation.ParentIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: true, + Table: todo.ParentTable, + Columns: []string{todo.ParentColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if tuo.mutation.ChildrenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: todo.ChildrenTable, + Columns: []string{todo.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tuo.mutation.RemovedChildrenIDs(); len(nodes) > 0 && !tuo.mutation.ChildrenCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: todo.ChildrenTable, + Columns: []string{todo.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(todo.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 := tuo.mutation.ChildrenIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: false, + Table: todo.ChildrenTable, + Columns: []string{todo.ChildrenColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(todo.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if tuo.mutation.SecretCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: todo.SecretTable, + Columns: []string{todo.SecretColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(verysecret.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := tuo.mutation.SecretIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2O, + Inverse: false, + Table: todo.SecretTable, + Columns: []string{todo.SecretColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(verysecret.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(tuo.modifiers...) + _node = &Todo{config: tuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, tuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{todo.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + tuo.mutation.done = true + return _node, nil +} diff --git a/entgql/internal/todoglobalid/ent/tx.go b/entgql/internal/todoglobalid/ent/tx.go new file mode 100644 index 000000000..b047282f7 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/tx.go @@ -0,0 +1,251 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "sync" + + "entgo.io/ent/dialect" +) + +// Tx is a transactional client that is created by calling Client.Tx(). +type Tx struct { + config + // BillProduct is the client for interacting with the BillProduct builders. + BillProduct *BillProductClient + // Category is the client for interacting with the Category builders. + Category *CategoryClient + // Friendship is the client for interacting with the Friendship builders. + Friendship *FriendshipClient + // Group is the client for interacting with the Group builders. + Group *GroupClient + // OneToMany is the client for interacting with the OneToMany builders. + OneToMany *OneToManyClient + // Project is the client for interacting with the Project builders. + Project *ProjectClient + // Todo is the client for interacting with the Todo builders. + Todo *TodoClient + // User is the client for interacting with the User builders. + User *UserClient + // VerySecret is the client for interacting with the VerySecret builders. + VerySecret *VerySecretClient + // Workspace is the client for interacting with the Workspace builders. + Workspace *WorkspaceClient + + // lazily loaded. + client *Client + clientOnce sync.Once + // ctx lives for the life of the transaction. It is + // the same context used by the underlying connection. + ctx context.Context +} + +type ( + // Committer is the interface that wraps the Commit method. + Committer interface { + Commit(context.Context, *Tx) error + } + + // The CommitFunc type is an adapter to allow the use of ordinary + // function as a Committer. If f is a function with the appropriate + // signature, CommitFunc(f) is a Committer that calls f. + CommitFunc func(context.Context, *Tx) error + + // CommitHook defines the "commit middleware". A function that gets a Committer + // and returns a Committer. For example: + // + // hook := func(next ent.Committer) ent.Committer { + // return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error { + // // Do some stuff before. + // if err := next.Commit(ctx, tx); err != nil { + // return err + // } + // // Do some stuff after. + // return nil + // }) + // } + // + CommitHook func(Committer) Committer +) + +// Commit calls f(ctx, m). +func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error { + return f(ctx, tx) +} + +// Commit commits the transaction. +func (tx *Tx) Commit() error { + txDriver := tx.config.driver.(*txDriver) + var fn Committer = CommitFunc(func(context.Context, *Tx) error { + return txDriver.tx.Commit() + }) + txDriver.mu.Lock() + hooks := append([]CommitHook(nil), txDriver.onCommit...) + txDriver.mu.Unlock() + for i := len(hooks) - 1; i >= 0; i-- { + fn = hooks[i](fn) + } + return fn.Commit(tx.ctx, tx) +} + +// OnCommit adds a hook to call on commit. +func (tx *Tx) OnCommit(f CommitHook) { + txDriver := tx.config.driver.(*txDriver) + txDriver.mu.Lock() + txDriver.onCommit = append(txDriver.onCommit, f) + txDriver.mu.Unlock() +} + +type ( + // Rollbacker is the interface that wraps the Rollback method. + Rollbacker interface { + Rollback(context.Context, *Tx) error + } + + // The RollbackFunc type is an adapter to allow the use of ordinary + // function as a Rollbacker. If f is a function with the appropriate + // signature, RollbackFunc(f) is a Rollbacker that calls f. + RollbackFunc func(context.Context, *Tx) error + + // RollbackHook defines the "rollback middleware". A function that gets a Rollbacker + // and returns a Rollbacker. For example: + // + // hook := func(next ent.Rollbacker) ent.Rollbacker { + // return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error { + // // Do some stuff before. + // if err := next.Rollback(ctx, tx); err != nil { + // return err + // } + // // Do some stuff after. + // return nil + // }) + // } + // + RollbackHook func(Rollbacker) Rollbacker +) + +// Rollback calls f(ctx, m). +func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error { + return f(ctx, tx) +} + +// Rollback rollbacks the transaction. +func (tx *Tx) Rollback() error { + txDriver := tx.config.driver.(*txDriver) + var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error { + return txDriver.tx.Rollback() + }) + txDriver.mu.Lock() + hooks := append([]RollbackHook(nil), txDriver.onRollback...) + txDriver.mu.Unlock() + for i := len(hooks) - 1; i >= 0; i-- { + fn = hooks[i](fn) + } + return fn.Rollback(tx.ctx, tx) +} + +// OnRollback adds a hook to call on rollback. +func (tx *Tx) OnRollback(f RollbackHook) { + txDriver := tx.config.driver.(*txDriver) + txDriver.mu.Lock() + txDriver.onRollback = append(txDriver.onRollback, f) + txDriver.mu.Unlock() +} + +// Client returns a Client that binds to current transaction. +func (tx *Tx) Client() *Client { + tx.clientOnce.Do(func() { + tx.client = &Client{config: tx.config} + tx.client.init() + }) + return tx.client +} + +func (tx *Tx) init() { + tx.BillProduct = NewBillProductClient(tx.config) + tx.Category = NewCategoryClient(tx.config) + tx.Friendship = NewFriendshipClient(tx.config) + tx.Group = NewGroupClient(tx.config) + tx.OneToMany = NewOneToManyClient(tx.config) + tx.Project = NewProjectClient(tx.config) + tx.Todo = NewTodoClient(tx.config) + tx.User = NewUserClient(tx.config) + tx.VerySecret = NewVerySecretClient(tx.config) + tx.Workspace = NewWorkspaceClient(tx.config) +} + +// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation. +// The idea is to support transactions without adding any extra code to the builders. +// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance. +// Commit and Rollback are nop for the internal builders and the user must call one +// of them in order to commit or rollback the transaction. +// +// If a closed transaction is embedded in one of the generated entities, and the entity +// applies a query, for example: BillProduct.QueryXXX(), the query will be executed +// through the driver which created this transaction. +// +// Note that txDriver is not goroutine safe. +type txDriver struct { + // the driver we started the transaction from. + drv dialect.Driver + // tx is the underlying transaction. + tx dialect.Tx + // completion hooks. + mu sync.Mutex + onCommit []CommitHook + onRollback []RollbackHook +} + +// newTx creates a new transactional driver. +func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) { + tx, err := drv.Tx(ctx) + if err != nil { + return nil, err + } + return &txDriver{tx: tx, drv: drv}, nil +} + +// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls +// from the internal builders. Should be called only by the internal builders. +func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil } + +// Dialect returns the dialect of the driver we started the transaction from. +func (tx *txDriver) Dialect() string { return tx.drv.Dialect() } + +// Close is a nop close. +func (*txDriver) Close() error { return nil } + +// Commit is a nop commit for the internal builders. +// User must call `Tx.Commit` in order to commit the transaction. +func (*txDriver) Commit() error { return nil } + +// Rollback is a nop rollback for the internal builders. +// User must call `Tx.Rollback` in order to rollback the transaction. +func (*txDriver) Rollback() error { return nil } + +// Exec calls tx.Exec. +func (tx *txDriver) Exec(ctx context.Context, query string, args, v any) error { + return tx.tx.Exec(ctx, query, args, v) +} + +// Query calls tx.Query. +func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error { + return tx.tx.Query(ctx, query, args, v) +} + +var _ dialect.Driver = (*txDriver)(nil) diff --git a/entgql/internal/todoglobalid/ent/user.go b/entgql/internal/todoglobalid/ent/user.go new file mode 100644 index 000000000..564b1e8c7 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/user.go @@ -0,0 +1,306 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "encoding/json" + "fmt" + "strings" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/user" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "github.com/google/uuid" +) + +// User is the model entity for the User schema. +type User struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + // Username holds the value of the "username" field. + Username uuid.UUID `json:"username,omitempty"` + // Password holds the value of the "password" field. + Password string `json:"-"` + // RequiredMetadata holds the value of the "required_metadata" field. + RequiredMetadata map[string]interface{} `json:"required_metadata,omitempty"` + // Metadata holds the value of the "metadata" field. + Metadata map[string]interface{} `json:"metadata,omitempty"` + // Edges holds the relations/edges for other nodes in the graph. + // The values are being populated by the UserQuery when eager-loading is set. + Edges UserEdges `json:"edges"` + selectValues sql.SelectValues +} + +// UserEdges holds the relations/edges for other nodes in the graph. +type UserEdges struct { + // The groups of the user + Groups []*Group `json:"groups,omitempty"` + // Friends holds the value of the friends edge. + Friends []*User `json:"friends,omitempty"` + // Friendships holds the value of the friendships edge. + Friendships []*Friendship `json:"friendships,omitempty"` + // loadedTypes holds the information for reporting if a + // type was loaded (or requested) in eager-loading or not. + loadedTypes [3]bool + // totalCount holds the count of the edges above. + totalCount [3]map[string]int + + namedGroups map[string][]*Group + namedFriends map[string][]*User + namedFriendships map[string][]*Friendship +} + +// GroupsOrErr returns the Groups value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) GroupsOrErr() ([]*Group, error) { + if e.loadedTypes[0] { + return e.Groups, nil + } + return nil, &NotLoadedError{edge: "groups"} +} + +// FriendsOrErr returns the Friends value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) FriendsOrErr() ([]*User, error) { + if e.loadedTypes[1] { + return e.Friends, nil + } + return nil, &NotLoadedError{edge: "friends"} +} + +// FriendshipsOrErr returns the Friendships value or an error if the edge +// was not loaded in eager-loading. +func (e UserEdges) FriendshipsOrErr() ([]*Friendship, error) { + if e.loadedTypes[2] { + return e.Friendships, nil + } + return nil, &NotLoadedError{edge: "friendships"} +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*User) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case user.FieldRequiredMetadata, user.FieldMetadata: + values[i] = new([]byte) + case user.FieldID: + values[i] = new(sql.NullInt64) + case user.FieldName, user.FieldPassword: + values[i] = new(sql.NullString) + case user.FieldUsername: + values[i] = new(uuid.UUID) + default: + values[i] = new(sql.UnknownType) + } + } + return values, nil +} + +// assignValues assigns the values that were returned from sql.Rows (after scanning) +// to the User fields. +func (u *User) assignValues(columns []string, values []any) error { + if m, n := len(values), len(columns); m < n { + return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) + } + for i := range columns { + switch columns[i] { + case user.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + u.ID = int(value.Int64) + case user.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + u.Name = value.String + } + case user.FieldUsername: + if value, ok := values[i].(*uuid.UUID); !ok { + return fmt.Errorf("unexpected type %T for field username", values[i]) + } else if value != nil { + u.Username = *value + } + case user.FieldPassword: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field password", values[i]) + } else if value.Valid { + u.Password = value.String + } + case user.FieldRequiredMetadata: + if value, ok := values[i].(*[]byte); !ok { + return fmt.Errorf("unexpected type %T for field required_metadata", values[i]) + } else if value != nil && len(*value) > 0 { + if err := json.Unmarshal(*value, &u.RequiredMetadata); err != nil { + return fmt.Errorf("unmarshal field required_metadata: %w", err) + } + } + case user.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, &u.Metadata); err != nil { + return fmt.Errorf("unmarshal field metadata: %w", err) + } + } + default: + u.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the User. +// This includes values selected through modifiers, order, etc. +func (u *User) Value(name string) (ent.Value, error) { + return u.selectValues.Get(name) +} + +// QueryGroups queries the "groups" edge of the User entity. +func (u *User) QueryGroups() *GroupQuery { + return NewUserClient(u.config).QueryGroups(u) +} + +// QueryFriends queries the "friends" edge of the User entity. +func (u *User) QueryFriends() *UserQuery { + return NewUserClient(u.config).QueryFriends(u) +} + +// QueryFriendships queries the "friendships" edge of the User entity. +func (u *User) QueryFriendships() *FriendshipQuery { + return NewUserClient(u.config).QueryFriendships(u) +} + +// Update returns a builder for updating this User. +// Note that you need to call User.Unwrap() before calling this method if this User +// was returned from a transaction, and the transaction was committed or rolled back. +func (u *User) Update() *UserUpdateOne { + return NewUserClient(u.config).UpdateOne(u) +} + +// Unwrap unwraps the User entity that was returned from a transaction after it was closed, +// so that all future queries will be executed through the driver which created the transaction. +func (u *User) Unwrap() *User { + _tx, ok := u.config.driver.(*txDriver) + if !ok { + panic("ent: User is not a transactional entity") + } + u.config.driver = _tx.drv + return u +} + +// String implements the fmt.Stringer. +func (u *User) String() string { + var builder strings.Builder + builder.WriteString("User(") + builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) + builder.WriteString("name=") + builder.WriteString(u.Name) + builder.WriteString(", ") + builder.WriteString("username=") + builder.WriteString(fmt.Sprintf("%v", u.Username)) + builder.WriteString(", ") + builder.WriteString("password=") + builder.WriteString(", ") + builder.WriteString("required_metadata=") + builder.WriteString(fmt.Sprintf("%v", u.RequiredMetadata)) + builder.WriteString(", ") + builder.WriteString("metadata=") + builder.WriteString(fmt.Sprintf("%v", u.Metadata)) + builder.WriteByte(')') + return builder.String() +} + +// NamedGroups returns the Groups named value or an error if the edge was not +// loaded in eager-loading with this name. +func (u *User) NamedGroups(name string) ([]*Group, error) { + if u.Edges.namedGroups == nil { + return nil, &NotLoadedError{edge: name} + } + nodes, ok := u.Edges.namedGroups[name] + if !ok { + return nil, &NotLoadedError{edge: name} + } + return nodes, nil +} + +func (u *User) appendNamedGroups(name string, edges ...*Group) { + if u.Edges.namedGroups == nil { + u.Edges.namedGroups = make(map[string][]*Group) + } + if len(edges) == 0 { + u.Edges.namedGroups[name] = []*Group{} + } else { + u.Edges.namedGroups[name] = append(u.Edges.namedGroups[name], edges...) + } +} + +// NamedFriends returns the Friends named value or an error if the edge was not +// loaded in eager-loading with this name. +func (u *User) NamedFriends(name string) ([]*User, error) { + if u.Edges.namedFriends == nil { + return nil, &NotLoadedError{edge: name} + } + nodes, ok := u.Edges.namedFriends[name] + if !ok { + return nil, &NotLoadedError{edge: name} + } + return nodes, nil +} + +func (u *User) appendNamedFriends(name string, edges ...*User) { + if u.Edges.namedFriends == nil { + u.Edges.namedFriends = make(map[string][]*User) + } + if len(edges) == 0 { + u.Edges.namedFriends[name] = []*User{} + } else { + u.Edges.namedFriends[name] = append(u.Edges.namedFriends[name], edges...) + } +} + +// NamedFriendships returns the Friendships named value or an error if the edge was not +// loaded in eager-loading with this name. +func (u *User) NamedFriendships(name string) ([]*Friendship, error) { + if u.Edges.namedFriendships == nil { + return nil, &NotLoadedError{edge: name} + } + nodes, ok := u.Edges.namedFriendships[name] + if !ok { + return nil, &NotLoadedError{edge: name} + } + return nodes, nil +} + +func (u *User) appendNamedFriendships(name string, edges ...*Friendship) { + if u.Edges.namedFriendships == nil { + u.Edges.namedFriendships = make(map[string][]*Friendship) + } + if len(edges) == 0 { + u.Edges.namedFriendships[name] = []*Friendship{} + } else { + u.Edges.namedFriendships[name] = append(u.Edges.namedFriendships[name], edges...) + } +} + +// Users is a parsable slice of User. +type Users []*User diff --git a/entgql/internal/todoglobalid/ent/user/user.go b/entgql/internal/todoglobalid/ent/user/user.go new file mode 100644 index 000000000..55beb1349 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/user/user.go @@ -0,0 +1,184 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package user + +import ( + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/google/uuid" +) + +const ( + // Label holds the string label denoting the user type in the database. + Label = "user" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // FieldUsername holds the string denoting the username field in the database. + FieldUsername = "username" + // FieldPassword holds the string denoting the password field in the database. + FieldPassword = "password" + // FieldRequiredMetadata holds the string denoting the required_metadata field in the database. + FieldRequiredMetadata = "required_metadata" + // FieldMetadata holds the string denoting the metadata field in the database. + FieldMetadata = "metadata" + // EdgeGroups holds the string denoting the groups edge name in mutations. + EdgeGroups = "groups" + // EdgeFriends holds the string denoting the friends edge name in mutations. + EdgeFriends = "friends" + // EdgeFriendships holds the string denoting the friendships edge name in mutations. + EdgeFriendships = "friendships" + // Table holds the table name of the user in the database. + Table = "users" + // GroupsTable is the table that holds the groups relation/edge. The primary key declared below. + GroupsTable = "user_groups" + // GroupsInverseTable is the table name for the Group entity. + // It exists in this package in order to avoid circular dependency with the "group" package. + GroupsInverseTable = "groups" + // FriendsTable is the table that holds the friends relation/edge. The primary key declared below. + FriendsTable = "friendships" + // FriendshipsTable is the table that holds the friendships relation/edge. + FriendshipsTable = "friendships" + // FriendshipsInverseTable is the table name for the Friendship entity. + // It exists in this package in order to avoid circular dependency with the "friendship" package. + FriendshipsInverseTable = "friendships" + // FriendshipsColumn is the table column denoting the friendships relation/edge. + FriendshipsColumn = "user_id" +) + +// Columns holds all SQL columns for user fields. +var Columns = []string{ + FieldID, + FieldName, + FieldUsername, + FieldPassword, + FieldRequiredMetadata, + FieldMetadata, +} + +var ( + // GroupsPrimaryKey and GroupsColumn2 are the table columns denoting the + // primary key for the groups relation (M2M). + GroupsPrimaryKey = []string{"user_id", "group_id"} + // FriendsPrimaryKey and FriendsColumn2 are the table columns denoting the + // primary key for the friends relation (M2M). + FriendsPrimaryKey = []string{"user_id", "friend_id"} +) + +// ValidColumn reports if the column name is valid (part of the table columns). +func ValidColumn(column string) bool { + for i := range Columns { + if column == Columns[i] { + return true + } + } + return false +} + +var ( + // DefaultName holds the default value on creation for the "name" field. + DefaultName string + // DefaultUsername holds the default value on creation for the "username" field. + DefaultUsername func() uuid.UUID +) + +// OrderOption defines the ordering options for the User 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() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} + +// ByUsername orders the results by the username field. +func ByUsername(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldUsername, opts...).ToFunc() +} + +// ByPassword orders the results by the password field. +func ByPassword(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPassword, opts...).ToFunc() +} + +// ByGroupsCount orders the results by groups count. +func ByGroupsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newGroupsStep(), opts...) + } +} + +// ByGroups orders the results by groups terms. +func ByGroups(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newGroupsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByFriendsCount orders the results by friends count. +func ByFriendsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newFriendsStep(), opts...) + } +} + +// ByFriends orders the results by friends terms. +func ByFriends(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newFriendsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} + +// ByFriendshipsCount orders the results by friendships count. +func ByFriendshipsCount(opts ...sql.OrderTermOption) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborsCount(s, newFriendshipsStep(), opts...) + } +} + +// ByFriendships orders the results by friendships terms. +func ByFriendships(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { + return func(s *sql.Selector) { + sqlgraph.OrderByNeighborTerms(s, newFriendshipsStep(), append([]sql.OrderTerm{term}, terms...)...) + } +} +func newGroupsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(GroupsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, GroupsTable, GroupsPrimaryKey...), + ) +} +func newFriendsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, FriendsTable, FriendsPrimaryKey...), + ) +} +func newFriendshipsStep() *sqlgraph.Step { + return sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.To(FriendshipsInverseTable, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, FriendshipsTable, FriendshipsColumn), + ) +} diff --git a/entgql/internal/todoglobalid/ent/user/where.go b/entgql/internal/todoglobalid/ent/user/where.go new file mode 100644 index 000000000..4372d4f65 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/user/where.go @@ -0,0 +1,358 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package user + +import ( + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "github.com/google/uuid" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.User { + return predicate.User(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.User { + return predicate.User(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.User { + return predicate.User(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.User { + return predicate.User(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.User { + return predicate.User(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.User { + return predicate.User(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.User { + return predicate.User(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.User { + return predicate.User(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.User { + return predicate.User(sql.FieldLTE(FieldID, id)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.User { + return predicate.User(sql.FieldEQ(FieldName, v)) +} + +// Username applies equality check predicate on the "username" field. It's identical to UsernameEQ. +func Username(v uuid.UUID) predicate.User { + return predicate.User(sql.FieldEQ(FieldUsername, v)) +} + +// Password applies equality check predicate on the "password" field. It's identical to PasswordEQ. +func Password(v string) predicate.User { + return predicate.User(sql.FieldEQ(FieldPassword, v)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.User { + return predicate.User(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.User { + return predicate.User(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.User { + return predicate.User(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.User { + return predicate.User(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.User { + return predicate.User(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.User { + return predicate.User(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.User { + return predicate.User(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.User { + return predicate.User(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.User { + return predicate.User(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.User { + return predicate.User(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.User { + return predicate.User(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.User { + return predicate.User(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.User { + return predicate.User(sql.FieldContainsFold(FieldName, v)) +} + +// UsernameEQ applies the EQ predicate on the "username" field. +func UsernameEQ(v uuid.UUID) predicate.User { + return predicate.User(sql.FieldEQ(FieldUsername, v)) +} + +// UsernameNEQ applies the NEQ predicate on the "username" field. +func UsernameNEQ(v uuid.UUID) predicate.User { + return predicate.User(sql.FieldNEQ(FieldUsername, v)) +} + +// UsernameIn applies the In predicate on the "username" field. +func UsernameIn(vs ...uuid.UUID) predicate.User { + return predicate.User(sql.FieldIn(FieldUsername, vs...)) +} + +// UsernameNotIn applies the NotIn predicate on the "username" field. +func UsernameNotIn(vs ...uuid.UUID) predicate.User { + return predicate.User(sql.FieldNotIn(FieldUsername, vs...)) +} + +// UsernameGT applies the GT predicate on the "username" field. +func UsernameGT(v uuid.UUID) predicate.User { + return predicate.User(sql.FieldGT(FieldUsername, v)) +} + +// UsernameGTE applies the GTE predicate on the "username" field. +func UsernameGTE(v uuid.UUID) predicate.User { + return predicate.User(sql.FieldGTE(FieldUsername, v)) +} + +// UsernameLT applies the LT predicate on the "username" field. +func UsernameLT(v uuid.UUID) predicate.User { + return predicate.User(sql.FieldLT(FieldUsername, v)) +} + +// UsernameLTE applies the LTE predicate on the "username" field. +func UsernameLTE(v uuid.UUID) predicate.User { + return predicate.User(sql.FieldLTE(FieldUsername, v)) +} + +// PasswordEQ applies the EQ predicate on the "password" field. +func PasswordEQ(v string) predicate.User { + return predicate.User(sql.FieldEQ(FieldPassword, v)) +} + +// PasswordNEQ applies the NEQ predicate on the "password" field. +func PasswordNEQ(v string) predicate.User { + return predicate.User(sql.FieldNEQ(FieldPassword, v)) +} + +// PasswordIn applies the In predicate on the "password" field. +func PasswordIn(vs ...string) predicate.User { + return predicate.User(sql.FieldIn(FieldPassword, vs...)) +} + +// PasswordNotIn applies the NotIn predicate on the "password" field. +func PasswordNotIn(vs ...string) predicate.User { + return predicate.User(sql.FieldNotIn(FieldPassword, vs...)) +} + +// PasswordGT applies the GT predicate on the "password" field. +func PasswordGT(v string) predicate.User { + return predicate.User(sql.FieldGT(FieldPassword, v)) +} + +// PasswordGTE applies the GTE predicate on the "password" field. +func PasswordGTE(v string) predicate.User { + return predicate.User(sql.FieldGTE(FieldPassword, v)) +} + +// PasswordLT applies the LT predicate on the "password" field. +func PasswordLT(v string) predicate.User { + return predicate.User(sql.FieldLT(FieldPassword, v)) +} + +// PasswordLTE applies the LTE predicate on the "password" field. +func PasswordLTE(v string) predicate.User { + return predicate.User(sql.FieldLTE(FieldPassword, v)) +} + +// PasswordContains applies the Contains predicate on the "password" field. +func PasswordContains(v string) predicate.User { + return predicate.User(sql.FieldContains(FieldPassword, v)) +} + +// PasswordHasPrefix applies the HasPrefix predicate on the "password" field. +func PasswordHasPrefix(v string) predicate.User { + return predicate.User(sql.FieldHasPrefix(FieldPassword, v)) +} + +// PasswordHasSuffix applies the HasSuffix predicate on the "password" field. +func PasswordHasSuffix(v string) predicate.User { + return predicate.User(sql.FieldHasSuffix(FieldPassword, v)) +} + +// PasswordIsNil applies the IsNil predicate on the "password" field. +func PasswordIsNil() predicate.User { + return predicate.User(sql.FieldIsNull(FieldPassword)) +} + +// PasswordNotNil applies the NotNil predicate on the "password" field. +func PasswordNotNil() predicate.User { + return predicate.User(sql.FieldNotNull(FieldPassword)) +} + +// PasswordEqualFold applies the EqualFold predicate on the "password" field. +func PasswordEqualFold(v string) predicate.User { + return predicate.User(sql.FieldEqualFold(FieldPassword, v)) +} + +// PasswordContainsFold applies the ContainsFold predicate on the "password" field. +func PasswordContainsFold(v string) predicate.User { + return predicate.User(sql.FieldContainsFold(FieldPassword, v)) +} + +// MetadataIsNil applies the IsNil predicate on the "metadata" field. +func MetadataIsNil() predicate.User { + return predicate.User(sql.FieldIsNull(FieldMetadata)) +} + +// MetadataNotNil applies the NotNil predicate on the "metadata" field. +func MetadataNotNil() predicate.User { + return predicate.User(sql.FieldNotNull(FieldMetadata)) +} + +// HasGroups applies the HasEdge predicate on the "groups" edge. +func HasGroups() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, GroupsTable, GroupsPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasGroupsWith applies the HasEdge predicate on the "groups" edge with a given conditions (other predicates). +func HasGroupsWith(preds ...predicate.Group) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := newGroupsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasFriends applies the HasEdge predicate on the "friends" edge. +func HasFriends() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, FriendsTable, FriendsPrimaryKey...), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasFriendsWith applies the HasEdge predicate on the "friends" edge with a given conditions (other predicates). +func HasFriendsWith(preds ...predicate.User) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := newFriendsStep() + sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { + for _, p := range preds { + p(s) + } + }) + }) +} + +// HasFriendships applies the HasEdge predicate on the "friendships" edge. +func HasFriendships() predicate.User { + return predicate.User(func(s *sql.Selector) { + step := sqlgraph.NewStep( + sqlgraph.From(Table, FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, FriendshipsTable, FriendshipsColumn), + ) + sqlgraph.HasNeighbors(s, step) + }) +} + +// HasFriendshipsWith applies the HasEdge predicate on the "friendships" edge with a given conditions (other predicates). +func HasFriendshipsWith(preds ...predicate.Friendship) predicate.User { + return predicate.User(func(s *sql.Selector) { + step := newFriendshipsStep() + 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.User) predicate.User { + return predicate.User(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.User) predicate.User { + return predicate.User(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.User) predicate.User { + return predicate.User(sql.NotPredicates(p)) +} diff --git a/entgql/internal/todoglobalid/ent/user_create.go b/entgql/internal/todoglobalid/ent/user_create.go new file mode 100644 index 000000000..d2a00c088 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/user_create.go @@ -0,0 +1,381 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/friendship" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/group" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/user" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/google/uuid" +) + +// UserCreate is the builder for creating a User entity. +type UserCreate struct { + config + mutation *UserMutation + hooks []Hook +} + +// SetName sets the "name" field. +func (uc *UserCreate) SetName(s string) *UserCreate { + uc.mutation.SetName(s) + return uc +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (uc *UserCreate) SetNillableName(s *string) *UserCreate { + if s != nil { + uc.SetName(*s) + } + return uc +} + +// SetUsername sets the "username" field. +func (uc *UserCreate) SetUsername(u uuid.UUID) *UserCreate { + uc.mutation.SetUsername(u) + return uc +} + +// SetNillableUsername sets the "username" field if the given value is not nil. +func (uc *UserCreate) SetNillableUsername(u *uuid.UUID) *UserCreate { + if u != nil { + uc.SetUsername(*u) + } + return uc +} + +// SetPassword sets the "password" field. +func (uc *UserCreate) SetPassword(s string) *UserCreate { + uc.mutation.SetPassword(s) + return uc +} + +// SetNillablePassword sets the "password" field if the given value is not nil. +func (uc *UserCreate) SetNillablePassword(s *string) *UserCreate { + if s != nil { + uc.SetPassword(*s) + } + return uc +} + +// SetRequiredMetadata sets the "required_metadata" field. +func (uc *UserCreate) SetRequiredMetadata(m map[string]interface{}) *UserCreate { + uc.mutation.SetRequiredMetadata(m) + return uc +} + +// SetMetadata sets the "metadata" field. +func (uc *UserCreate) SetMetadata(m map[string]interface{}) *UserCreate { + uc.mutation.SetMetadata(m) + return uc +} + +// AddGroupIDs adds the "groups" edge to the Group entity by IDs. +func (uc *UserCreate) AddGroupIDs(ids ...int) *UserCreate { + uc.mutation.AddGroupIDs(ids...) + return uc +} + +// AddGroups adds the "groups" edges to the Group entity. +func (uc *UserCreate) AddGroups(g ...*Group) *UserCreate { + ids := make([]int, len(g)) + for i := range g { + ids[i] = g[i].ID + } + return uc.AddGroupIDs(ids...) +} + +// AddFriendIDs adds the "friends" edge to the User entity by IDs. +func (uc *UserCreate) AddFriendIDs(ids ...int) *UserCreate { + uc.mutation.AddFriendIDs(ids...) + return uc +} + +// AddFriends adds the "friends" edges to the User entity. +func (uc *UserCreate) AddFriends(u ...*User) *UserCreate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uc.AddFriendIDs(ids...) +} + +// AddFriendshipIDs adds the "friendships" edge to the Friendship entity by IDs. +func (uc *UserCreate) AddFriendshipIDs(ids ...int) *UserCreate { + uc.mutation.AddFriendshipIDs(ids...) + return uc +} + +// AddFriendships adds the "friendships" edges to the Friendship entity. +func (uc *UserCreate) AddFriendships(f ...*Friendship) *UserCreate { + ids := make([]int, len(f)) + for i := range f { + ids[i] = f[i].ID + } + return uc.AddFriendshipIDs(ids...) +} + +// Mutation returns the UserMutation object of the builder. +func (uc *UserCreate) Mutation() *UserMutation { + return uc.mutation +} + +// Save creates the User in the database. +func (uc *UserCreate) Save(ctx context.Context) (*User, error) { + uc.defaults() + return withHooks(ctx, uc.sqlSave, uc.mutation, uc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (uc *UserCreate) SaveX(ctx context.Context) *User { + v, err := uc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (uc *UserCreate) Exec(ctx context.Context) error { + _, err := uc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (uc *UserCreate) ExecX(ctx context.Context) { + if err := uc.Exec(ctx); err != nil { + panic(err) + } +} + +// defaults sets the default values of the builder before save. +func (uc *UserCreate) defaults() { + if _, ok := uc.mutation.Name(); !ok { + v := user.DefaultName + uc.mutation.SetName(v) + } + if _, ok := uc.mutation.Username(); !ok { + v := user.DefaultUsername() + uc.mutation.SetUsername(v) + } +} + +// check runs all checks and user-defined validators on the builder. +func (uc *UserCreate) check() error { + if _, ok := uc.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "User.name"`)} + } + if _, ok := uc.mutation.Username(); !ok { + return &ValidationError{Name: "username", err: errors.New(`ent: missing required field "User.username"`)} + } + if _, ok := uc.mutation.RequiredMetadata(); !ok { + return &ValidationError{Name: "required_metadata", err: errors.New(`ent: missing required field "User.required_metadata"`)} + } + return nil +} + +func (uc *UserCreate) sqlSave(ctx context.Context) (*User, error) { + if err := uc.check(); err != nil { + return nil, err + } + _node, _spec := uc.createSpec() + if err := sqlgraph.CreateNode(ctx, uc.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) + uc.mutation.id = &_node.ID + uc.mutation.done = true + return _node, nil +} + +func (uc *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) { + var ( + _node = &User{config: uc.config} + _spec = sqlgraph.NewCreateSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt)) + ) + if value, ok := uc.mutation.Name(); ok { + _spec.SetField(user.FieldName, field.TypeString, value) + _node.Name = value + } + if value, ok := uc.mutation.Username(); ok { + _spec.SetField(user.FieldUsername, field.TypeUUID, value) + _node.Username = value + } + if value, ok := uc.mutation.Password(); ok { + _spec.SetField(user.FieldPassword, field.TypeString, value) + _node.Password = value + } + if value, ok := uc.mutation.RequiredMetadata(); ok { + _spec.SetField(user.FieldRequiredMetadata, field.TypeJSON, value) + _node.RequiredMetadata = value + } + if value, ok := uc.mutation.Metadata(); ok { + _spec.SetField(user.FieldMetadata, field.TypeJSON, value) + _node.Metadata = value + } + if nodes := uc.mutation.GroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.GroupsTable, + Columns: user.GroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := uc.mutation.FriendsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.FriendsTable, + Columns: user.FriendsPrimaryKey, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &FriendshipCreate{config: uc.config, mutation: newFriendshipMutation(uc.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges = append(_spec.Edges, edge) + } + if nodes := uc.mutation.FriendshipsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.FriendshipsTable, + Columns: []string{user.FriendshipsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(friendship.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges = append(_spec.Edges, edge) + } + return _node, _spec +} + +// UserCreateBulk is the builder for creating many User entities in bulk. +type UserCreateBulk struct { + config + err error + builders []*UserCreate +} + +// Save creates the User entities in the database. +func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { + if ucb.err != nil { + return nil, ucb.err + } + specs := make([]*sqlgraph.CreateSpec, len(ucb.builders)) + nodes := make([]*User, len(ucb.builders)) + mutators := make([]Mutator, len(ucb.builders)) + for i := range ucb.builders { + func(i int, root context.Context) { + builder := ucb.builders[i] + builder.defaults() + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*UserMutation) + 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, ucb.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, ucb.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, ucb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (ucb *UserCreateBulk) SaveX(ctx context.Context) []*User { + v, err := ucb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (ucb *UserCreateBulk) Exec(ctx context.Context) error { + _, err := ucb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (ucb *UserCreateBulk) ExecX(ctx context.Context) { + if err := ucb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entgql/internal/todoglobalid/ent/user_delete.go b/entgql/internal/todoglobalid/ent/user_delete.go new file mode 100644 index 000000000..598dc9c0c --- /dev/null +++ b/entgql/internal/todoglobalid/ent/user_delete.go @@ -0,0 +1,102 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/user" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// UserDelete is the builder for deleting a User entity. +type UserDelete struct { + config + hooks []Hook + mutation *UserMutation +} + +// Where appends a list predicates to the UserDelete builder. +func (ud *UserDelete) Where(ps ...predicate.User) *UserDelete { + ud.mutation.Where(ps...) + return ud +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (ud *UserDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, ud.sqlExec, ud.mutation, ud.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (ud *UserDelete) ExecX(ctx context.Context) int { + n, err := ud.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (ud *UserDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt)) + if ps := ud.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, ud.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + ud.mutation.done = true + return affected, err +} + +// UserDeleteOne is the builder for deleting a single User entity. +type UserDeleteOne struct { + ud *UserDelete +} + +// Where appends a list predicates to the UserDelete builder. +func (udo *UserDeleteOne) Where(ps ...predicate.User) *UserDeleteOne { + udo.ud.mutation.Where(ps...) + return udo +} + +// Exec executes the deletion query. +func (udo *UserDeleteOne) Exec(ctx context.Context) error { + n, err := udo.ud.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{user.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (udo *UserDeleteOne) ExecX(ctx context.Context) { + if err := udo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entgql/internal/todoglobalid/ent/user_query.go b/entgql/internal/todoglobalid/ent/user_query.go new file mode 100644 index 000000000..a32d2935e --- /dev/null +++ b/entgql/internal/todoglobalid/ent/user_query.go @@ -0,0 +1,924 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "database/sql/driver" + "fmt" + "math" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/friendship" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/group" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/user" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// UserQuery is the builder for querying User entities. +type UserQuery struct { + config + ctx *QueryContext + order []user.OrderOption + inters []Interceptor + predicates []predicate.User + withGroups *GroupQuery + withFriends *UserQuery + withFriendships *FriendshipQuery + loadTotal []func(context.Context, []*User) error + modifiers []func(*sql.Selector) + withNamedGroups map[string]*GroupQuery + withNamedFriends map[string]*UserQuery + withNamedFriendships map[string]*FriendshipQuery + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the UserQuery builder. +func (uq *UserQuery) Where(ps ...predicate.User) *UserQuery { + uq.predicates = append(uq.predicates, ps...) + return uq +} + +// Limit the number of records to be returned by this query. +func (uq *UserQuery) Limit(limit int) *UserQuery { + uq.ctx.Limit = &limit + return uq +} + +// Offset to start from. +func (uq *UserQuery) Offset(offset int) *UserQuery { + uq.ctx.Offset = &offset + return uq +} + +// 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 (uq *UserQuery) Unique(unique bool) *UserQuery { + uq.ctx.Unique = &unique + return uq +} + +// Order specifies how the records should be ordered. +func (uq *UserQuery) Order(o ...user.OrderOption) *UserQuery { + uq.order = append(uq.order, o...) + return uq +} + +// QueryGroups chains the current query on the "groups" edge. +func (uq *UserQuery) QueryGroups() *GroupQuery { + query := (&GroupClient{config: uq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := uq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := uq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, selector), + sqlgraph.To(group.Table, group.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, user.GroupsTable, user.GroupsPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryFriends chains the current query on the "friends" edge. +func (uq *UserQuery) QueryFriends() *UserQuery { + query := (&UserClient{config: uq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := uq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := uq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, selector), + sqlgraph.To(user.Table, user.FieldID), + sqlgraph.Edge(sqlgraph.M2M, false, user.FriendsTable, user.FriendsPrimaryKey...), + ) + fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// QueryFriendships chains the current query on the "friendships" edge. +func (uq *UserQuery) QueryFriendships() *FriendshipQuery { + query := (&FriendshipClient{config: uq.config}).Query() + query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { + if err := uq.prepareQuery(ctx); err != nil { + return nil, err + } + selector := uq.sqlQuery(ctx) + if err := selector.Err(); err != nil { + return nil, err + } + step := sqlgraph.NewStep( + sqlgraph.From(user.Table, user.FieldID, selector), + sqlgraph.To(friendship.Table, friendship.FieldID), + sqlgraph.Edge(sqlgraph.O2M, true, user.FriendshipsTable, user.FriendshipsColumn), + ) + fromU = sqlgraph.SetNeighbors(uq.driver.Dialect(), step) + return fromU, nil + } + return query +} + +// First returns the first User entity from the query. +// Returns a *NotFoundError when no User was found. +func (uq *UserQuery) First(ctx context.Context) (*User, error) { + nodes, err := uq.Limit(1).All(setContextOp(ctx, uq.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{user.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (uq *UserQuery) FirstX(ctx context.Context) *User { + node, err := uq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first User ID from the query. +// Returns a *NotFoundError when no User ID was found. +func (uq *UserQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = uq.Limit(1).IDs(setContextOp(ctx, uq.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{user.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (uq *UserQuery) FirstIDX(ctx context.Context) int { + id, err := uq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single User entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one User entity is found. +// Returns a *NotFoundError when no User entities are found. +func (uq *UserQuery) Only(ctx context.Context) (*User, error) { + nodes, err := uq.Limit(2).All(setContextOp(ctx, uq.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{user.Label} + default: + return nil, &NotSingularError{user.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (uq *UserQuery) OnlyX(ctx context.Context) *User { + node, err := uq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only User ID in the query. +// Returns a *NotSingularError when more than one User ID is found. +// Returns a *NotFoundError when no entities are found. +func (uq *UserQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = uq.Limit(2).IDs(setContextOp(ctx, uq.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{user.Label} + default: + err = &NotSingularError{user.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (uq *UserQuery) OnlyIDX(ctx context.Context) int { + id, err := uq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Users. +func (uq *UserQuery) All(ctx context.Context) ([]*User, error) { + ctx = setContextOp(ctx, uq.ctx, ent.OpQueryAll) + if err := uq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*User, *UserQuery]() + return withInterceptors[[]*User](ctx, uq, qr, uq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (uq *UserQuery) AllX(ctx context.Context) []*User { + nodes, err := uq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of User IDs. +func (uq *UserQuery) IDs(ctx context.Context) (ids []int, err error) { + if uq.ctx.Unique == nil && uq.path != nil { + uq.Unique(true) + } + ctx = setContextOp(ctx, uq.ctx, ent.OpQueryIDs) + if err = uq.Select(user.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (uq *UserQuery) IDsX(ctx context.Context) []int { + ids, err := uq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (uq *UserQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, uq.ctx, ent.OpQueryCount) + if err := uq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, uq, querierCount[*UserQuery](), uq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (uq *UserQuery) CountX(ctx context.Context) int { + count, err := uq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (uq *UserQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, uq.ctx, ent.OpQueryExist) + switch _, err := uq.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 (uq *UserQuery) ExistX(ctx context.Context) bool { + exist, err := uq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the UserQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (uq *UserQuery) Clone() *UserQuery { + if uq == nil { + return nil + } + return &UserQuery{ + config: uq.config, + ctx: uq.ctx.Clone(), + order: append([]user.OrderOption{}, uq.order...), + inters: append([]Interceptor{}, uq.inters...), + predicates: append([]predicate.User{}, uq.predicates...), + withGroups: uq.withGroups.Clone(), + withFriends: uq.withFriends.Clone(), + withFriendships: uq.withFriendships.Clone(), + // clone intermediate query. + sql: uq.sql.Clone(), + path: uq.path, + modifiers: append([]func(*sql.Selector){}, uq.modifiers...), + } +} + +// WithGroups tells the query-builder to eager-load the nodes that are connected to +// the "groups" edge. The optional arguments are used to configure the query builder of the edge. +func (uq *UserQuery) WithGroups(opts ...func(*GroupQuery)) *UserQuery { + query := (&GroupClient{config: uq.config}).Query() + for _, opt := range opts { + opt(query) + } + uq.withGroups = query + return uq +} + +// WithFriends tells the query-builder to eager-load the nodes that are connected to +// the "friends" edge. The optional arguments are used to configure the query builder of the edge. +func (uq *UserQuery) WithFriends(opts ...func(*UserQuery)) *UserQuery { + query := (&UserClient{config: uq.config}).Query() + for _, opt := range opts { + opt(query) + } + uq.withFriends = query + return uq +} + +// WithFriendships tells the query-builder to eager-load the nodes that are connected to +// the "friendships" edge. The optional arguments are used to configure the query builder of the edge. +func (uq *UserQuery) WithFriendships(opts ...func(*FriendshipQuery)) *UserQuery { + query := (&FriendshipClient{config: uq.config}).Query() + for _, opt := range opts { + opt(query) + } + uq.withFriendships = query + return uq +} + +// 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 { +// Name string `json:"name,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.User.Query(). +// GroupBy(user.FieldName). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (uq *UserQuery) GroupBy(field string, fields ...string) *UserGroupBy { + uq.ctx.Fields = append([]string{field}, fields...) + grbuild := &UserGroupBy{build: uq} + grbuild.flds = &uq.ctx.Fields + grbuild.label = user.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 { +// Name string `json:"name,omitempty"` +// } +// +// client.User.Query(). +// Select(user.FieldName). +// Scan(ctx, &v) +func (uq *UserQuery) Select(fields ...string) *UserSelect { + uq.ctx.Fields = append(uq.ctx.Fields, fields...) + sbuild := &UserSelect{UserQuery: uq} + sbuild.label = user.Label + sbuild.flds, sbuild.scan = &uq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a UserSelect configured with the given aggregations. +func (uq *UserQuery) Aggregate(fns ...AggregateFunc) *UserSelect { + return uq.Select().Aggregate(fns...) +} + +func (uq *UserQuery) prepareQuery(ctx context.Context) error { + for _, inter := range uq.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, uq); err != nil { + return err + } + } + } + for _, f := range uq.ctx.Fields { + if !user.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if uq.path != nil { + prev, err := uq.path(ctx) + if err != nil { + return err + } + uq.sql = prev + } + return nil +} + +func (uq *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, error) { + var ( + nodes = []*User{} + _spec = uq.querySpec() + loadedTypes = [3]bool{ + uq.withGroups != nil, + uq.withFriends != nil, + uq.withFriendships != nil, + } + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*User).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &User{config: uq.config} + nodes = append(nodes, node) + node.Edges.loadedTypes = loadedTypes + return node.assignValues(columns, values) + } + if len(uq.modifiers) > 0 { + _spec.Modifiers = uq.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, uq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + if query := uq.withGroups; query != nil { + if err := uq.loadGroups(ctx, query, nodes, + func(n *User) { n.Edges.Groups = []*Group{} }, + func(n *User, e *Group) { n.Edges.Groups = append(n.Edges.Groups, e) }); err != nil { + return nil, err + } + } + if query := uq.withFriends; query != nil { + if err := uq.loadFriends(ctx, query, nodes, + func(n *User) { n.Edges.Friends = []*User{} }, + func(n *User, e *User) { n.Edges.Friends = append(n.Edges.Friends, e) }); err != nil { + return nil, err + } + } + if query := uq.withFriendships; query != nil { + if err := uq.loadFriendships(ctx, query, nodes, + func(n *User) { n.Edges.Friendships = []*Friendship{} }, + func(n *User, e *Friendship) { n.Edges.Friendships = append(n.Edges.Friendships, e) }); err != nil { + return nil, err + } + } + for name, query := range uq.withNamedGroups { + if err := uq.loadGroups(ctx, query, nodes, + func(n *User) { n.appendNamedGroups(name) }, + func(n *User, e *Group) { n.appendNamedGroups(name, e) }); err != nil { + return nil, err + } + } + for name, query := range uq.withNamedFriends { + if err := uq.loadFriends(ctx, query, nodes, + func(n *User) { n.appendNamedFriends(name) }, + func(n *User, e *User) { n.appendNamedFriends(name, e) }); err != nil { + return nil, err + } + } + for name, query := range uq.withNamedFriendships { + if err := uq.loadFriendships(ctx, query, nodes, + func(n *User) { n.appendNamedFriendships(name) }, + func(n *User, e *Friendship) { n.appendNamedFriendships(name, e) }); err != nil { + return nil, err + } + } + for i := range uq.loadTotal { + if err := uq.loadTotal[i](ctx, nodes); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (uq *UserQuery) loadGroups(ctx context.Context, query *GroupQuery, nodes []*User, init func(*User), assign func(*User, *Group)) error { + edgeIDs := make([]driver.Value, len(nodes)) + byID := make(map[int]*User) + nids := make(map[int]map[*User]struct{}) + for i, node := range nodes { + edgeIDs[i] = node.ID + byID[node.ID] = node + if init != nil { + init(node) + } + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(user.GroupsTable) + s.Join(joinT).On(s.C(group.FieldID), joinT.C(user.GroupsPrimaryKey[1])) + s.Where(sql.InValues(joinT.C(user.GroupsPrimaryKey[0]), edgeIDs...)) + columns := s.SelectedColumns() + s.Select(joinT.C(user.GroupsPrimaryKey[0])) + s.AppendSelect(columns...) + s.SetDistinct(false) + }) + if err := query.prepareQuery(ctx); err != nil { + return err + } + qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) { + assign := spec.Assign + values := spec.ScanValues + spec.ScanValues = func(columns []string) ([]any, error) { + values, err := values(columns[1:]) + if err != nil { + return nil, err + } + return append([]any{new(sql.NullInt64)}, values...), nil + } + spec.Assign = func(columns []string, values []any) error { + outValue := int(values[0].(*sql.NullInt64).Int64) + inValue := int(values[1].(*sql.NullInt64).Int64) + if nids[inValue] == nil { + nids[inValue] = map[*User]struct{}{byID[outValue]: {}} + return assign(columns[1:], values[1:]) + } + nids[inValue][byID[outValue]] = struct{}{} + return nil + } + }) + }) + neighbors, err := withInterceptors[[]*Group](ctx, query, qr, query.inters) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nids[n.ID] + if !ok { + return fmt.Errorf(`unexpected "groups" node returned %v`, n.ID) + } + for kn := range nodes { + assign(kn, n) + } + } + return nil +} +func (uq *UserQuery) loadFriends(ctx context.Context, query *UserQuery, nodes []*User, init func(*User), assign func(*User, *User)) error { + edgeIDs := make([]driver.Value, len(nodes)) + byID := make(map[int]*User) + nids := make(map[int]map[*User]struct{}) + for i, node := range nodes { + edgeIDs[i] = node.ID + byID[node.ID] = node + if init != nil { + init(node) + } + } + query.Where(func(s *sql.Selector) { + joinT := sql.Table(user.FriendsTable) + s.Join(joinT).On(s.C(user.FieldID), joinT.C(user.FriendsPrimaryKey[1])) + s.Where(sql.InValues(joinT.C(user.FriendsPrimaryKey[0]), edgeIDs...)) + columns := s.SelectedColumns() + s.Select(joinT.C(user.FriendsPrimaryKey[0])) + s.AppendSelect(columns...) + s.SetDistinct(false) + }) + if err := query.prepareQuery(ctx); err != nil { + return err + } + qr := QuerierFunc(func(ctx context.Context, q Query) (Value, error) { + return query.sqlAll(ctx, func(_ context.Context, spec *sqlgraph.QuerySpec) { + assign := spec.Assign + values := spec.ScanValues + spec.ScanValues = func(columns []string) ([]any, error) { + values, err := values(columns[1:]) + if err != nil { + return nil, err + } + return append([]any{new(sql.NullInt64)}, values...), nil + } + spec.Assign = func(columns []string, values []any) error { + outValue := int(values[0].(*sql.NullInt64).Int64) + inValue := int(values[1].(*sql.NullInt64).Int64) + if nids[inValue] == nil { + nids[inValue] = map[*User]struct{}{byID[outValue]: {}} + return assign(columns[1:], values[1:]) + } + nids[inValue][byID[outValue]] = struct{}{} + return nil + } + }) + }) + neighbors, err := withInterceptors[[]*User](ctx, query, qr, query.inters) + if err != nil { + return err + } + for _, n := range neighbors { + nodes, ok := nids[n.ID] + if !ok { + return fmt.Errorf(`unexpected "friends" node returned %v`, n.ID) + } + for kn := range nodes { + assign(kn, n) + } + } + return nil +} +func (uq *UserQuery) loadFriendships(ctx context.Context, query *FriendshipQuery, nodes []*User, init func(*User), assign func(*User, *Friendship)) error { + fks := make([]driver.Value, 0, len(nodes)) + nodeids := make(map[int]*User) + for i := range nodes { + fks = append(fks, nodes[i].ID) + nodeids[nodes[i].ID] = nodes[i] + if init != nil { + init(nodes[i]) + } + } + if len(query.ctx.Fields) > 0 { + query.ctx.AppendFieldOnce(friendship.FieldUserID) + } + query.Where(predicate.Friendship(func(s *sql.Selector) { + s.Where(sql.InValues(s.C(user.FriendshipsColumn), fks...)) + })) + neighbors, err := query.All(ctx) + if err != nil { + return err + } + for _, n := range neighbors { + fk := n.UserID + node, ok := nodeids[fk] + if !ok { + return fmt.Errorf(`unexpected referenced foreign-key "user_id" returned %v for node %v`, fk, n.ID) + } + assign(node, n) + } + return nil +} + +func (uq *UserQuery) sqlCount(ctx context.Context) (int, error) { + _spec := uq.querySpec() + if len(uq.modifiers) > 0 { + _spec.Modifiers = uq.modifiers + } + _spec.Node.Columns = uq.ctx.Fields + if len(uq.ctx.Fields) > 0 { + _spec.Unique = uq.ctx.Unique != nil && *uq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, uq.driver, _spec) +} + +func (uq *UserQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt)) + _spec.From = uq.sql + if unique := uq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if uq.path != nil { + _spec.Unique = true + } + if fields := uq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, user.FieldID) + for i := range fields { + if fields[i] != user.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := uq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := uq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := uq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := uq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (uq *UserQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(uq.driver.Dialect()) + t1 := builder.Table(user.Table) + columns := uq.ctx.Fields + if len(columns) == 0 { + columns = user.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if uq.sql != nil { + selector = uq.sql + selector.Select(selector.Columns(columns...)...) + } + if uq.ctx.Unique != nil && *uq.ctx.Unique { + selector.Distinct() + } + for _, m := range uq.modifiers { + m(selector) + } + for _, p := range uq.predicates { + p(selector) + } + for _, p := range uq.order { + p(selector) + } + if offset := uq.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 := uq.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (uq *UserQuery) Modify(modifiers ...func(s *sql.Selector)) *UserSelect { + uq.modifiers = append(uq.modifiers, modifiers...) + return uq.Select() +} + +// WithNamedGroups tells the query-builder to eager-load the nodes that are connected to the "groups" +// edge with the given name. The optional arguments are used to configure the query builder of the edge. +func (uq *UserQuery) WithNamedGroups(name string, opts ...func(*GroupQuery)) *UserQuery { + query := (&GroupClient{config: uq.config}).Query() + for _, opt := range opts { + opt(query) + } + if uq.withNamedGroups == nil { + uq.withNamedGroups = make(map[string]*GroupQuery) + } + uq.withNamedGroups[name] = query + return uq +} + +// WithNamedFriends tells the query-builder to eager-load the nodes that are connected to the "friends" +// edge with the given name. The optional arguments are used to configure the query builder of the edge. +func (uq *UserQuery) WithNamedFriends(name string, opts ...func(*UserQuery)) *UserQuery { + query := (&UserClient{config: uq.config}).Query() + for _, opt := range opts { + opt(query) + } + if uq.withNamedFriends == nil { + uq.withNamedFriends = make(map[string]*UserQuery) + } + uq.withNamedFriends[name] = query + return uq +} + +// WithNamedFriendships tells the query-builder to eager-load the nodes that are connected to the "friendships" +// edge with the given name. The optional arguments are used to configure the query builder of the edge. +func (uq *UserQuery) WithNamedFriendships(name string, opts ...func(*FriendshipQuery)) *UserQuery { + query := (&FriendshipClient{config: uq.config}).Query() + for _, opt := range opts { + opt(query) + } + if uq.withNamedFriendships == nil { + uq.withNamedFriendships = make(map[string]*FriendshipQuery) + } + uq.withNamedFriendships[name] = query + return uq +} + +// UserGroupBy is the group-by builder for User entities. +type UserGroupBy struct { + selector + build *UserQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (ugb *UserGroupBy) Aggregate(fns ...AggregateFunc) *UserGroupBy { + ugb.fns = append(ugb.fns, fns...) + return ugb +} + +// Scan applies the selector query and scans the result into the given value. +func (ugb *UserGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ugb.build.ctx, ent.OpQueryGroupBy) + if err := ugb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*UserQuery, *UserGroupBy](ctx, ugb.build, ugb, ugb.build.inters, v) +} + +func (ugb *UserGroupBy) sqlScan(ctx context.Context, root *UserQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(ugb.fns)) + for _, fn := range ugb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*ugb.flds)+len(ugb.fns)) + for _, f := range *ugb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*ugb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := ugb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// UserSelect is the builder for selecting fields of User entities. +type UserSelect struct { + *UserQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (us *UserSelect) Aggregate(fns ...AggregateFunc) *UserSelect { + us.fns = append(us.fns, fns...) + return us +} + +// Scan applies the selector query and scans the result into the given value. +func (us *UserSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, us.ctx, ent.OpQuerySelect) + if err := us.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*UserQuery, *UserSelect](ctx, us.UserQuery, us, us.inters, v) +} + +func (us *UserSelect) sqlScan(ctx context.Context, root *UserQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(us.fns)) + for _, fn := range us.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*us.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 := us.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (us *UserSelect) Modify(modifiers ...func(s *sql.Selector)) *UserSelect { + us.modifiers = append(us.modifiers, modifiers...) + return us +} diff --git a/entgql/internal/todoglobalid/ent/user_update.go b/entgql/internal/todoglobalid/ent/user_update.go new file mode 100644 index 000000000..539887422 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/user_update.go @@ -0,0 +1,892 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/friendship" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/group" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/user" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" + "github.com/google/uuid" +) + +// UserUpdate is the builder for updating User entities. +type UserUpdate struct { + config + hooks []Hook + mutation *UserMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the UserUpdate builder. +func (uu *UserUpdate) Where(ps ...predicate.User) *UserUpdate { + uu.mutation.Where(ps...) + return uu +} + +// SetName sets the "name" field. +func (uu *UserUpdate) SetName(s string) *UserUpdate { + uu.mutation.SetName(s) + return uu +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (uu *UserUpdate) SetNillableName(s *string) *UserUpdate { + if s != nil { + uu.SetName(*s) + } + return uu +} + +// SetUsername sets the "username" field. +func (uu *UserUpdate) SetUsername(u uuid.UUID) *UserUpdate { + uu.mutation.SetUsername(u) + return uu +} + +// SetNillableUsername sets the "username" field if the given value is not nil. +func (uu *UserUpdate) SetNillableUsername(u *uuid.UUID) *UserUpdate { + if u != nil { + uu.SetUsername(*u) + } + return uu +} + +// SetPassword sets the "password" field. +func (uu *UserUpdate) SetPassword(s string) *UserUpdate { + uu.mutation.SetPassword(s) + return uu +} + +// SetNillablePassword sets the "password" field if the given value is not nil. +func (uu *UserUpdate) SetNillablePassword(s *string) *UserUpdate { + if s != nil { + uu.SetPassword(*s) + } + return uu +} + +// ClearPassword clears the value of the "password" field. +func (uu *UserUpdate) ClearPassword() *UserUpdate { + uu.mutation.ClearPassword() + return uu +} + +// SetRequiredMetadata sets the "required_metadata" field. +func (uu *UserUpdate) SetRequiredMetadata(m map[string]interface{}) *UserUpdate { + uu.mutation.SetRequiredMetadata(m) + return uu +} + +// SetMetadata sets the "metadata" field. +func (uu *UserUpdate) SetMetadata(m map[string]interface{}) *UserUpdate { + uu.mutation.SetMetadata(m) + return uu +} + +// ClearMetadata clears the value of the "metadata" field. +func (uu *UserUpdate) ClearMetadata() *UserUpdate { + uu.mutation.ClearMetadata() + return uu +} + +// AddGroupIDs adds the "groups" edge to the Group entity by IDs. +func (uu *UserUpdate) AddGroupIDs(ids ...int) *UserUpdate { + uu.mutation.AddGroupIDs(ids...) + return uu +} + +// AddGroups adds the "groups" edges to the Group entity. +func (uu *UserUpdate) AddGroups(g ...*Group) *UserUpdate { + ids := make([]int, len(g)) + for i := range g { + ids[i] = g[i].ID + } + return uu.AddGroupIDs(ids...) +} + +// AddFriendIDs adds the "friends" edge to the User entity by IDs. +func (uu *UserUpdate) AddFriendIDs(ids ...int) *UserUpdate { + uu.mutation.AddFriendIDs(ids...) + return uu +} + +// AddFriends adds the "friends" edges to the User entity. +func (uu *UserUpdate) AddFriends(u ...*User) *UserUpdate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uu.AddFriendIDs(ids...) +} + +// AddFriendshipIDs adds the "friendships" edge to the Friendship entity by IDs. +func (uu *UserUpdate) AddFriendshipIDs(ids ...int) *UserUpdate { + uu.mutation.AddFriendshipIDs(ids...) + return uu +} + +// AddFriendships adds the "friendships" edges to the Friendship entity. +func (uu *UserUpdate) AddFriendships(f ...*Friendship) *UserUpdate { + ids := make([]int, len(f)) + for i := range f { + ids[i] = f[i].ID + } + return uu.AddFriendshipIDs(ids...) +} + +// Mutation returns the UserMutation object of the builder. +func (uu *UserUpdate) Mutation() *UserMutation { + return uu.mutation +} + +// ClearGroups clears all "groups" edges to the Group entity. +func (uu *UserUpdate) ClearGroups() *UserUpdate { + uu.mutation.ClearGroups() + return uu +} + +// RemoveGroupIDs removes the "groups" edge to Group entities by IDs. +func (uu *UserUpdate) RemoveGroupIDs(ids ...int) *UserUpdate { + uu.mutation.RemoveGroupIDs(ids...) + return uu +} + +// RemoveGroups removes "groups" edges to Group entities. +func (uu *UserUpdate) RemoveGroups(g ...*Group) *UserUpdate { + ids := make([]int, len(g)) + for i := range g { + ids[i] = g[i].ID + } + return uu.RemoveGroupIDs(ids...) +} + +// ClearFriends clears all "friends" edges to the User entity. +func (uu *UserUpdate) ClearFriends() *UserUpdate { + uu.mutation.ClearFriends() + return uu +} + +// RemoveFriendIDs removes the "friends" edge to User entities by IDs. +func (uu *UserUpdate) RemoveFriendIDs(ids ...int) *UserUpdate { + uu.mutation.RemoveFriendIDs(ids...) + return uu +} + +// RemoveFriends removes "friends" edges to User entities. +func (uu *UserUpdate) RemoveFriends(u ...*User) *UserUpdate { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uu.RemoveFriendIDs(ids...) +} + +// ClearFriendships clears all "friendships" edges to the Friendship entity. +func (uu *UserUpdate) ClearFriendships() *UserUpdate { + uu.mutation.ClearFriendships() + return uu +} + +// RemoveFriendshipIDs removes the "friendships" edge to Friendship entities by IDs. +func (uu *UserUpdate) RemoveFriendshipIDs(ids ...int) *UserUpdate { + uu.mutation.RemoveFriendshipIDs(ids...) + return uu +} + +// RemoveFriendships removes "friendships" edges to Friendship entities. +func (uu *UserUpdate) RemoveFriendships(f ...*Friendship) *UserUpdate { + ids := make([]int, len(f)) + for i := range f { + ids[i] = f[i].ID + } + return uu.RemoveFriendshipIDs(ids...) +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (uu *UserUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, uu.sqlSave, uu.mutation, uu.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (uu *UserUpdate) SaveX(ctx context.Context) int { + affected, err := uu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (uu *UserUpdate) Exec(ctx context.Context) error { + _, err := uu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (uu *UserUpdate) ExecX(ctx context.Context) { + if err := uu.Exec(ctx); err != nil { + panic(err) + } +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (uu *UserUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *UserUpdate { + uu.modifiers = append(uu.modifiers, modifiers...) + return uu +} + +func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt)) + if ps := uu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := uu.mutation.Name(); ok { + _spec.SetField(user.FieldName, field.TypeString, value) + } + if value, ok := uu.mutation.Username(); ok { + _spec.SetField(user.FieldUsername, field.TypeUUID, value) + } + if value, ok := uu.mutation.Password(); ok { + _spec.SetField(user.FieldPassword, field.TypeString, value) + } + if uu.mutation.PasswordCleared() { + _spec.ClearField(user.FieldPassword, field.TypeString) + } + if value, ok := uu.mutation.RequiredMetadata(); ok { + _spec.SetField(user.FieldRequiredMetadata, field.TypeJSON, value) + } + if value, ok := uu.mutation.Metadata(); ok { + _spec.SetField(user.FieldMetadata, field.TypeJSON, value) + } + if uu.mutation.MetadataCleared() { + _spec.ClearField(user.FieldMetadata, field.TypeJSON) + } + if uu.mutation.GroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.GroupsTable, + Columns: user.GroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.RemovedGroupsIDs(); len(nodes) > 0 && !uu.mutation.GroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.GroupsTable, + Columns: user.GroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(group.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 := uu.mutation.GroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.GroupsTable, + Columns: user.GroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if uu.mutation.FriendsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.FriendsTable, + Columns: user.FriendsPrimaryKey, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + createE := &FriendshipCreate{config: uu.config, mutation: newFriendshipMutation(uu.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.RemovedFriendsIDs(); len(nodes) > 0 && !uu.mutation.FriendsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.FriendsTable, + Columns: user.FriendsPrimaryKey, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &FriendshipCreate{config: uu.config, mutation: newFriendshipMutation(uu.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.FriendsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.FriendsTable, + Columns: user.FriendsPrimaryKey, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &FriendshipCreate{config: uu.config, mutation: newFriendshipMutation(uu.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if uu.mutation.FriendshipsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.FriendshipsTable, + Columns: []string{user.FriendshipsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(friendship.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uu.mutation.RemovedFriendshipsIDs(); len(nodes) > 0 && !uu.mutation.FriendshipsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.FriendshipsTable, + Columns: []string{user.FriendshipsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(friendship.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 := uu.mutation.FriendshipsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.FriendshipsTable, + Columns: []string{user.FriendshipsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(friendship.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(uu.modifiers...) + if n, err = sqlgraph.UpdateNodes(ctx, uu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{user.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + uu.mutation.done = true + return n, nil +} + +// UserUpdateOne is the builder for updating a single User entity. +type UserUpdateOne struct { + config + fields []string + hooks []Hook + mutation *UserMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetName sets the "name" field. +func (uuo *UserUpdateOne) SetName(s string) *UserUpdateOne { + uuo.mutation.SetName(s) + return uuo +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (uuo *UserUpdateOne) SetNillableName(s *string) *UserUpdateOne { + if s != nil { + uuo.SetName(*s) + } + return uuo +} + +// SetUsername sets the "username" field. +func (uuo *UserUpdateOne) SetUsername(u uuid.UUID) *UserUpdateOne { + uuo.mutation.SetUsername(u) + return uuo +} + +// SetNillableUsername sets the "username" field if the given value is not nil. +func (uuo *UserUpdateOne) SetNillableUsername(u *uuid.UUID) *UserUpdateOne { + if u != nil { + uuo.SetUsername(*u) + } + return uuo +} + +// SetPassword sets the "password" field. +func (uuo *UserUpdateOne) SetPassword(s string) *UserUpdateOne { + uuo.mutation.SetPassword(s) + return uuo +} + +// SetNillablePassword sets the "password" field if the given value is not nil. +func (uuo *UserUpdateOne) SetNillablePassword(s *string) *UserUpdateOne { + if s != nil { + uuo.SetPassword(*s) + } + return uuo +} + +// ClearPassword clears the value of the "password" field. +func (uuo *UserUpdateOne) ClearPassword() *UserUpdateOne { + uuo.mutation.ClearPassword() + return uuo +} + +// SetRequiredMetadata sets the "required_metadata" field. +func (uuo *UserUpdateOne) SetRequiredMetadata(m map[string]interface{}) *UserUpdateOne { + uuo.mutation.SetRequiredMetadata(m) + return uuo +} + +// SetMetadata sets the "metadata" field. +func (uuo *UserUpdateOne) SetMetadata(m map[string]interface{}) *UserUpdateOne { + uuo.mutation.SetMetadata(m) + return uuo +} + +// ClearMetadata clears the value of the "metadata" field. +func (uuo *UserUpdateOne) ClearMetadata() *UserUpdateOne { + uuo.mutation.ClearMetadata() + return uuo +} + +// AddGroupIDs adds the "groups" edge to the Group entity by IDs. +func (uuo *UserUpdateOne) AddGroupIDs(ids ...int) *UserUpdateOne { + uuo.mutation.AddGroupIDs(ids...) + return uuo +} + +// AddGroups adds the "groups" edges to the Group entity. +func (uuo *UserUpdateOne) AddGroups(g ...*Group) *UserUpdateOne { + ids := make([]int, len(g)) + for i := range g { + ids[i] = g[i].ID + } + return uuo.AddGroupIDs(ids...) +} + +// AddFriendIDs adds the "friends" edge to the User entity by IDs. +func (uuo *UserUpdateOne) AddFriendIDs(ids ...int) *UserUpdateOne { + uuo.mutation.AddFriendIDs(ids...) + return uuo +} + +// AddFriends adds the "friends" edges to the User entity. +func (uuo *UserUpdateOne) AddFriends(u ...*User) *UserUpdateOne { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uuo.AddFriendIDs(ids...) +} + +// AddFriendshipIDs adds the "friendships" edge to the Friendship entity by IDs. +func (uuo *UserUpdateOne) AddFriendshipIDs(ids ...int) *UserUpdateOne { + uuo.mutation.AddFriendshipIDs(ids...) + return uuo +} + +// AddFriendships adds the "friendships" edges to the Friendship entity. +func (uuo *UserUpdateOne) AddFriendships(f ...*Friendship) *UserUpdateOne { + ids := make([]int, len(f)) + for i := range f { + ids[i] = f[i].ID + } + return uuo.AddFriendshipIDs(ids...) +} + +// Mutation returns the UserMutation object of the builder. +func (uuo *UserUpdateOne) Mutation() *UserMutation { + return uuo.mutation +} + +// ClearGroups clears all "groups" edges to the Group entity. +func (uuo *UserUpdateOne) ClearGroups() *UserUpdateOne { + uuo.mutation.ClearGroups() + return uuo +} + +// RemoveGroupIDs removes the "groups" edge to Group entities by IDs. +func (uuo *UserUpdateOne) RemoveGroupIDs(ids ...int) *UserUpdateOne { + uuo.mutation.RemoveGroupIDs(ids...) + return uuo +} + +// RemoveGroups removes "groups" edges to Group entities. +func (uuo *UserUpdateOne) RemoveGroups(g ...*Group) *UserUpdateOne { + ids := make([]int, len(g)) + for i := range g { + ids[i] = g[i].ID + } + return uuo.RemoveGroupIDs(ids...) +} + +// ClearFriends clears all "friends" edges to the User entity. +func (uuo *UserUpdateOne) ClearFriends() *UserUpdateOne { + uuo.mutation.ClearFriends() + return uuo +} + +// RemoveFriendIDs removes the "friends" edge to User entities by IDs. +func (uuo *UserUpdateOne) RemoveFriendIDs(ids ...int) *UserUpdateOne { + uuo.mutation.RemoveFriendIDs(ids...) + return uuo +} + +// RemoveFriends removes "friends" edges to User entities. +func (uuo *UserUpdateOne) RemoveFriends(u ...*User) *UserUpdateOne { + ids := make([]int, len(u)) + for i := range u { + ids[i] = u[i].ID + } + return uuo.RemoveFriendIDs(ids...) +} + +// ClearFriendships clears all "friendships" edges to the Friendship entity. +func (uuo *UserUpdateOne) ClearFriendships() *UserUpdateOne { + uuo.mutation.ClearFriendships() + return uuo +} + +// RemoveFriendshipIDs removes the "friendships" edge to Friendship entities by IDs. +func (uuo *UserUpdateOne) RemoveFriendshipIDs(ids ...int) *UserUpdateOne { + uuo.mutation.RemoveFriendshipIDs(ids...) + return uuo +} + +// RemoveFriendships removes "friendships" edges to Friendship entities. +func (uuo *UserUpdateOne) RemoveFriendships(f ...*Friendship) *UserUpdateOne { + ids := make([]int, len(f)) + for i := range f { + ids[i] = f[i].ID + } + return uuo.RemoveFriendshipIDs(ids...) +} + +// Where appends a list predicates to the UserUpdate builder. +func (uuo *UserUpdateOne) Where(ps ...predicate.User) *UserUpdateOne { + uuo.mutation.Where(ps...) + return uuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (uuo *UserUpdateOne) Select(field string, fields ...string) *UserUpdateOne { + uuo.fields = append([]string{field}, fields...) + return uuo +} + +// Save executes the query and returns the updated User entity. +func (uuo *UserUpdateOne) Save(ctx context.Context) (*User, error) { + return withHooks(ctx, uuo.sqlSave, uuo.mutation, uuo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (uuo *UserUpdateOne) SaveX(ctx context.Context) *User { + node, err := uuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (uuo *UserUpdateOne) Exec(ctx context.Context) error { + _, err := uuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (uuo *UserUpdateOne) ExecX(ctx context.Context) { + if err := uuo.Exec(ctx); err != nil { + panic(err) + } +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (uuo *UserUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *UserUpdateOne { + uuo.modifiers = append(uuo.modifiers, modifiers...) + return uuo +} + +func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) { + _spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt)) + id, ok := uuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "User.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := uuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, user.FieldID) + for _, f := range fields { + if !user.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != user.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := uuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := uuo.mutation.Name(); ok { + _spec.SetField(user.FieldName, field.TypeString, value) + } + if value, ok := uuo.mutation.Username(); ok { + _spec.SetField(user.FieldUsername, field.TypeUUID, value) + } + if value, ok := uuo.mutation.Password(); ok { + _spec.SetField(user.FieldPassword, field.TypeString, value) + } + if uuo.mutation.PasswordCleared() { + _spec.ClearField(user.FieldPassword, field.TypeString) + } + if value, ok := uuo.mutation.RequiredMetadata(); ok { + _spec.SetField(user.FieldRequiredMetadata, field.TypeJSON, value) + } + if value, ok := uuo.mutation.Metadata(); ok { + _spec.SetField(user.FieldMetadata, field.TypeJSON, value) + } + if uuo.mutation.MetadataCleared() { + _spec.ClearField(user.FieldMetadata, field.TypeJSON) + } + if uuo.mutation.GroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.GroupsTable, + Columns: user.GroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.RemovedGroupsIDs(); len(nodes) > 0 && !uuo.mutation.GroupsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.GroupsTable, + Columns: user.GroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(group.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 := uuo.mutation.GroupsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.GroupsTable, + Columns: user.GroupsPrimaryKey, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(group.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if uuo.mutation.FriendsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.FriendsTable, + Columns: user.FriendsPrimaryKey, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + createE := &FriendshipCreate{config: uuo.config, mutation: newFriendshipMutation(uuo.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.RemovedFriendsIDs(); len(nodes) > 0 && !uuo.mutation.FriendsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.FriendsTable, + Columns: user.FriendsPrimaryKey, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &FriendshipCreate{config: uuo.config, mutation: newFriendshipMutation(uuo.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.FriendsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.M2M, + Inverse: false, + Table: user.FriendsTable, + Columns: user.FriendsPrimaryKey, + Bidi: true, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + createE := &FriendshipCreate{config: uuo.config, mutation: newFriendshipMutation(uuo.config, OpCreate)} + createE.defaults() + _, specE := createE.createSpec() + edge.Target.Fields = specE.Fields + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + if uuo.mutation.FriendshipsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.FriendshipsTable, + Columns: []string{user.FriendshipsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(friendship.FieldID, field.TypeInt), + }, + } + _spec.Edges.Clear = append(_spec.Edges.Clear, edge) + } + if nodes := uuo.mutation.RemovedFriendshipsIDs(); len(nodes) > 0 && !uuo.mutation.FriendshipsCleared() { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.FriendshipsTable, + Columns: []string{user.FriendshipsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(friendship.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 := uuo.mutation.FriendshipsIDs(); len(nodes) > 0 { + edge := &sqlgraph.EdgeSpec{ + Rel: sqlgraph.O2M, + Inverse: true, + Table: user.FriendshipsTable, + Columns: []string{user.FriendshipsColumn}, + Bidi: false, + Target: &sqlgraph.EdgeTarget{ + IDSpec: sqlgraph.NewFieldSpec(friendship.FieldID, field.TypeInt), + }, + } + for _, k := range nodes { + edge.Target.Nodes = append(edge.Target.Nodes, k) + } + _spec.Edges.Add = append(_spec.Edges.Add, edge) + } + _spec.AddModifiers(uuo.modifiers...) + _node = &User{config: uuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, uuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{user.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + uuo.mutation.done = true + return _node, nil +} diff --git a/entgql/internal/todoglobalid/ent/verysecret.go b/entgql/internal/todoglobalid/ent/verysecret.go new file mode 100644 index 000000000..0550b1024 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/verysecret.go @@ -0,0 +1,117 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/verysecret" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// VerySecret is the model entity for the VerySecret schema. +type VerySecret struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Password holds the value of the "password" field. + Password string `json:"password,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*VerySecret) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case verysecret.FieldID: + values[i] = new(sql.NullInt64) + case verysecret.FieldPassword: + 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 VerySecret fields. +func (vs *VerySecret) 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 verysecret.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + vs.ID = int(value.Int64) + case verysecret.FieldPassword: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field password", values[i]) + } else if value.Valid { + vs.Password = value.String + } + default: + vs.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the VerySecret. +// This includes values selected through modifiers, order, etc. +func (vs *VerySecret) Value(name string) (ent.Value, error) { + return vs.selectValues.Get(name) +} + +// Update returns a builder for updating this VerySecret. +// Note that you need to call VerySecret.Unwrap() before calling this method if this VerySecret +// was returned from a transaction, and the transaction was committed or rolled back. +func (vs *VerySecret) Update() *VerySecretUpdateOne { + return NewVerySecretClient(vs.config).UpdateOne(vs) +} + +// Unwrap unwraps the VerySecret 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 (vs *VerySecret) Unwrap() *VerySecret { + _tx, ok := vs.config.driver.(*txDriver) + if !ok { + panic("ent: VerySecret is not a transactional entity") + } + vs.config.driver = _tx.drv + return vs +} + +// String implements the fmt.Stringer. +func (vs *VerySecret) String() string { + var builder strings.Builder + builder.WriteString("VerySecret(") + builder.WriteString(fmt.Sprintf("id=%v, ", vs.ID)) + builder.WriteString("password=") + builder.WriteString(vs.Password) + builder.WriteByte(')') + return builder.String() +} + +// VerySecrets is a parsable slice of VerySecret. +type VerySecrets []*VerySecret diff --git a/entgql/internal/todoglobalid/ent/verysecret/verysecret.go b/entgql/internal/todoglobalid/ent/verysecret/verysecret.go new file mode 100644 index 000000000..fa7c88de7 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/verysecret/verysecret.go @@ -0,0 +1,61 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package verysecret + +import ( + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the verysecret type in the database. + Label = "very_secret" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldPassword holds the string denoting the password field in the database. + FieldPassword = "password" + // Table holds the table name of the verysecret in the database. + Table = "very_secrets" +) + +// Columns holds all SQL columns for verysecret fields. +var Columns = []string{ + FieldID, + FieldPassword, +} + +// 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 +} + +// OrderOption defines the ordering options for the VerySecret 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() +} + +// ByPassword orders the results by the password field. +func ByPassword(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldPassword, opts...).ToFunc() +} diff --git a/entgql/internal/todoglobalid/ent/verysecret/where.go b/entgql/internal/todoglobalid/ent/verysecret/where.go new file mode 100644 index 000000000..b5e8a954e --- /dev/null +++ b/entgql/internal/todoglobalid/ent/verysecret/where.go @@ -0,0 +1,152 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package verysecret + +import ( + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.VerySecret { + return predicate.VerySecret(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.VerySecret { + return predicate.VerySecret(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.VerySecret { + return predicate.VerySecret(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.VerySecret { + return predicate.VerySecret(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.VerySecret { + return predicate.VerySecret(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.VerySecret { + return predicate.VerySecret(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.VerySecret { + return predicate.VerySecret(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.VerySecret { + return predicate.VerySecret(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.VerySecret { + return predicate.VerySecret(sql.FieldLTE(FieldID, id)) +} + +// Password applies equality check predicate on the "password" field. It's identical to PasswordEQ. +func Password(v string) predicate.VerySecret { + return predicate.VerySecret(sql.FieldEQ(FieldPassword, v)) +} + +// PasswordEQ applies the EQ predicate on the "password" field. +func PasswordEQ(v string) predicate.VerySecret { + return predicate.VerySecret(sql.FieldEQ(FieldPassword, v)) +} + +// PasswordNEQ applies the NEQ predicate on the "password" field. +func PasswordNEQ(v string) predicate.VerySecret { + return predicate.VerySecret(sql.FieldNEQ(FieldPassword, v)) +} + +// PasswordIn applies the In predicate on the "password" field. +func PasswordIn(vs ...string) predicate.VerySecret { + return predicate.VerySecret(sql.FieldIn(FieldPassword, vs...)) +} + +// PasswordNotIn applies the NotIn predicate on the "password" field. +func PasswordNotIn(vs ...string) predicate.VerySecret { + return predicate.VerySecret(sql.FieldNotIn(FieldPassword, vs...)) +} + +// PasswordGT applies the GT predicate on the "password" field. +func PasswordGT(v string) predicate.VerySecret { + return predicate.VerySecret(sql.FieldGT(FieldPassword, v)) +} + +// PasswordGTE applies the GTE predicate on the "password" field. +func PasswordGTE(v string) predicate.VerySecret { + return predicate.VerySecret(sql.FieldGTE(FieldPassword, v)) +} + +// PasswordLT applies the LT predicate on the "password" field. +func PasswordLT(v string) predicate.VerySecret { + return predicate.VerySecret(sql.FieldLT(FieldPassword, v)) +} + +// PasswordLTE applies the LTE predicate on the "password" field. +func PasswordLTE(v string) predicate.VerySecret { + return predicate.VerySecret(sql.FieldLTE(FieldPassword, v)) +} + +// PasswordContains applies the Contains predicate on the "password" field. +func PasswordContains(v string) predicate.VerySecret { + return predicate.VerySecret(sql.FieldContains(FieldPassword, v)) +} + +// PasswordHasPrefix applies the HasPrefix predicate on the "password" field. +func PasswordHasPrefix(v string) predicate.VerySecret { + return predicate.VerySecret(sql.FieldHasPrefix(FieldPassword, v)) +} + +// PasswordHasSuffix applies the HasSuffix predicate on the "password" field. +func PasswordHasSuffix(v string) predicate.VerySecret { + return predicate.VerySecret(sql.FieldHasSuffix(FieldPassword, v)) +} + +// PasswordEqualFold applies the EqualFold predicate on the "password" field. +func PasswordEqualFold(v string) predicate.VerySecret { + return predicate.VerySecret(sql.FieldEqualFold(FieldPassword, v)) +} + +// PasswordContainsFold applies the ContainsFold predicate on the "password" field. +func PasswordContainsFold(v string) predicate.VerySecret { + return predicate.VerySecret(sql.FieldContainsFold(FieldPassword, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.VerySecret) predicate.VerySecret { + return predicate.VerySecret(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.VerySecret) predicate.VerySecret { + return predicate.VerySecret(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.VerySecret) predicate.VerySecret { + return predicate.VerySecret(sql.NotPredicates(p)) +} diff --git a/entgql/internal/todoglobalid/ent/verysecret_create.go b/entgql/internal/todoglobalid/ent/verysecret_create.go new file mode 100644 index 000000000..2bf644db8 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/verysecret_create.go @@ -0,0 +1,197 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/verysecret" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// VerySecretCreate is the builder for creating a VerySecret entity. +type VerySecretCreate struct { + config + mutation *VerySecretMutation + hooks []Hook +} + +// SetPassword sets the "password" field. +func (vsc *VerySecretCreate) SetPassword(s string) *VerySecretCreate { + vsc.mutation.SetPassword(s) + return vsc +} + +// Mutation returns the VerySecretMutation object of the builder. +func (vsc *VerySecretCreate) Mutation() *VerySecretMutation { + return vsc.mutation +} + +// Save creates the VerySecret in the database. +func (vsc *VerySecretCreate) Save(ctx context.Context) (*VerySecret, error) { + return withHooks(ctx, vsc.sqlSave, vsc.mutation, vsc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (vsc *VerySecretCreate) SaveX(ctx context.Context) *VerySecret { + v, err := vsc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (vsc *VerySecretCreate) Exec(ctx context.Context) error { + _, err := vsc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (vsc *VerySecretCreate) ExecX(ctx context.Context) { + if err := vsc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (vsc *VerySecretCreate) check() error { + if _, ok := vsc.mutation.Password(); !ok { + return &ValidationError{Name: "password", err: errors.New(`ent: missing required field "VerySecret.password"`)} + } + return nil +} + +func (vsc *VerySecretCreate) sqlSave(ctx context.Context) (*VerySecret, error) { + if err := vsc.check(); err != nil { + return nil, err + } + _node, _spec := vsc.createSpec() + if err := sqlgraph.CreateNode(ctx, vsc.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) + vsc.mutation.id = &_node.ID + vsc.mutation.done = true + return _node, nil +} + +func (vsc *VerySecretCreate) createSpec() (*VerySecret, *sqlgraph.CreateSpec) { + var ( + _node = &VerySecret{config: vsc.config} + _spec = sqlgraph.NewCreateSpec(verysecret.Table, sqlgraph.NewFieldSpec(verysecret.FieldID, field.TypeInt)) + ) + if value, ok := vsc.mutation.Password(); ok { + _spec.SetField(verysecret.FieldPassword, field.TypeString, value) + _node.Password = value + } + return _node, _spec +} + +// VerySecretCreateBulk is the builder for creating many VerySecret entities in bulk. +type VerySecretCreateBulk struct { + config + err error + builders []*VerySecretCreate +} + +// Save creates the VerySecret entities in the database. +func (vscb *VerySecretCreateBulk) Save(ctx context.Context) ([]*VerySecret, error) { + if vscb.err != nil { + return nil, vscb.err + } + specs := make([]*sqlgraph.CreateSpec, len(vscb.builders)) + nodes := make([]*VerySecret, len(vscb.builders)) + mutators := make([]Mutator, len(vscb.builders)) + for i := range vscb.builders { + func(i int, root context.Context) { + builder := vscb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*VerySecretMutation) + 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, vscb.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, vscb.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, vscb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (vscb *VerySecretCreateBulk) SaveX(ctx context.Context) []*VerySecret { + v, err := vscb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (vscb *VerySecretCreateBulk) Exec(ctx context.Context) error { + _, err := vscb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (vscb *VerySecretCreateBulk) ExecX(ctx context.Context) { + if err := vscb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entgql/internal/todoglobalid/ent/verysecret_delete.go b/entgql/internal/todoglobalid/ent/verysecret_delete.go new file mode 100644 index 000000000..9a3ff6f7b --- /dev/null +++ b/entgql/internal/todoglobalid/ent/verysecret_delete.go @@ -0,0 +1,102 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/verysecret" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// VerySecretDelete is the builder for deleting a VerySecret entity. +type VerySecretDelete struct { + config + hooks []Hook + mutation *VerySecretMutation +} + +// Where appends a list predicates to the VerySecretDelete builder. +func (vsd *VerySecretDelete) Where(ps ...predicate.VerySecret) *VerySecretDelete { + vsd.mutation.Where(ps...) + return vsd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (vsd *VerySecretDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, vsd.sqlExec, vsd.mutation, vsd.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (vsd *VerySecretDelete) ExecX(ctx context.Context) int { + n, err := vsd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (vsd *VerySecretDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(verysecret.Table, sqlgraph.NewFieldSpec(verysecret.FieldID, field.TypeInt)) + if ps := vsd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, vsd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + vsd.mutation.done = true + return affected, err +} + +// VerySecretDeleteOne is the builder for deleting a single VerySecret entity. +type VerySecretDeleteOne struct { + vsd *VerySecretDelete +} + +// Where appends a list predicates to the VerySecretDelete builder. +func (vsdo *VerySecretDeleteOne) Where(ps ...predicate.VerySecret) *VerySecretDeleteOne { + vsdo.vsd.mutation.Where(ps...) + return vsdo +} + +// Exec executes the deletion query. +func (vsdo *VerySecretDeleteOne) Exec(ctx context.Context) error { + n, err := vsdo.vsd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{verysecret.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (vsdo *VerySecretDeleteOne) ExecX(ctx context.Context) { + if err := vsdo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entgql/internal/todoglobalid/ent/verysecret_query.go b/entgql/internal/todoglobalid/ent/verysecret_query.go new file mode 100644 index 000000000..b17124c76 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/verysecret_query.go @@ -0,0 +1,570 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/verysecret" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// VerySecretQuery is the builder for querying VerySecret entities. +type VerySecretQuery struct { + config + ctx *QueryContext + order []verysecret.OrderOption + inters []Interceptor + predicates []predicate.VerySecret + loadTotal []func(context.Context, []*VerySecret) error + modifiers []func(*sql.Selector) + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the VerySecretQuery builder. +func (vsq *VerySecretQuery) Where(ps ...predicate.VerySecret) *VerySecretQuery { + vsq.predicates = append(vsq.predicates, ps...) + return vsq +} + +// Limit the number of records to be returned by this query. +func (vsq *VerySecretQuery) Limit(limit int) *VerySecretQuery { + vsq.ctx.Limit = &limit + return vsq +} + +// Offset to start from. +func (vsq *VerySecretQuery) Offset(offset int) *VerySecretQuery { + vsq.ctx.Offset = &offset + return vsq +} + +// 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 (vsq *VerySecretQuery) Unique(unique bool) *VerySecretQuery { + vsq.ctx.Unique = &unique + return vsq +} + +// Order specifies how the records should be ordered. +func (vsq *VerySecretQuery) Order(o ...verysecret.OrderOption) *VerySecretQuery { + vsq.order = append(vsq.order, o...) + return vsq +} + +// First returns the first VerySecret entity from the query. +// Returns a *NotFoundError when no VerySecret was found. +func (vsq *VerySecretQuery) First(ctx context.Context) (*VerySecret, error) { + nodes, err := vsq.Limit(1).All(setContextOp(ctx, vsq.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{verysecret.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (vsq *VerySecretQuery) FirstX(ctx context.Context) *VerySecret { + node, err := vsq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first VerySecret ID from the query. +// Returns a *NotFoundError when no VerySecret ID was found. +func (vsq *VerySecretQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = vsq.Limit(1).IDs(setContextOp(ctx, vsq.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{verysecret.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (vsq *VerySecretQuery) FirstIDX(ctx context.Context) int { + id, err := vsq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single VerySecret entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one VerySecret entity is found. +// Returns a *NotFoundError when no VerySecret entities are found. +func (vsq *VerySecretQuery) Only(ctx context.Context) (*VerySecret, error) { + nodes, err := vsq.Limit(2).All(setContextOp(ctx, vsq.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{verysecret.Label} + default: + return nil, &NotSingularError{verysecret.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (vsq *VerySecretQuery) OnlyX(ctx context.Context) *VerySecret { + node, err := vsq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only VerySecret ID in the query. +// Returns a *NotSingularError when more than one VerySecret ID is found. +// Returns a *NotFoundError when no entities are found. +func (vsq *VerySecretQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = vsq.Limit(2).IDs(setContextOp(ctx, vsq.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{verysecret.Label} + default: + err = &NotSingularError{verysecret.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (vsq *VerySecretQuery) OnlyIDX(ctx context.Context) int { + id, err := vsq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of VerySecrets. +func (vsq *VerySecretQuery) All(ctx context.Context) ([]*VerySecret, error) { + ctx = setContextOp(ctx, vsq.ctx, ent.OpQueryAll) + if err := vsq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*VerySecret, *VerySecretQuery]() + return withInterceptors[[]*VerySecret](ctx, vsq, qr, vsq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (vsq *VerySecretQuery) AllX(ctx context.Context) []*VerySecret { + nodes, err := vsq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of VerySecret IDs. +func (vsq *VerySecretQuery) IDs(ctx context.Context) (ids []int, err error) { + if vsq.ctx.Unique == nil && vsq.path != nil { + vsq.Unique(true) + } + ctx = setContextOp(ctx, vsq.ctx, ent.OpQueryIDs) + if err = vsq.Select(verysecret.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (vsq *VerySecretQuery) IDsX(ctx context.Context) []int { + ids, err := vsq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (vsq *VerySecretQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, vsq.ctx, ent.OpQueryCount) + if err := vsq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, vsq, querierCount[*VerySecretQuery](), vsq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (vsq *VerySecretQuery) CountX(ctx context.Context) int { + count, err := vsq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (vsq *VerySecretQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, vsq.ctx, ent.OpQueryExist) + switch _, err := vsq.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 (vsq *VerySecretQuery) ExistX(ctx context.Context) bool { + exist, err := vsq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the VerySecretQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (vsq *VerySecretQuery) Clone() *VerySecretQuery { + if vsq == nil { + return nil + } + return &VerySecretQuery{ + config: vsq.config, + ctx: vsq.ctx.Clone(), + order: append([]verysecret.OrderOption{}, vsq.order...), + inters: append([]Interceptor{}, vsq.inters...), + predicates: append([]predicate.VerySecret{}, vsq.predicates...), + // clone intermediate query. + sql: vsq.sql.Clone(), + path: vsq.path, + modifiers: append([]func(*sql.Selector){}, vsq.modifiers...), + } +} + +// 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 { +// Password string `json:"password,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.VerySecret.Query(). +// GroupBy(verysecret.FieldPassword). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (vsq *VerySecretQuery) GroupBy(field string, fields ...string) *VerySecretGroupBy { + vsq.ctx.Fields = append([]string{field}, fields...) + grbuild := &VerySecretGroupBy{build: vsq} + grbuild.flds = &vsq.ctx.Fields + grbuild.label = verysecret.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 { +// Password string `json:"password,omitempty"` +// } +// +// client.VerySecret.Query(). +// Select(verysecret.FieldPassword). +// Scan(ctx, &v) +func (vsq *VerySecretQuery) Select(fields ...string) *VerySecretSelect { + vsq.ctx.Fields = append(vsq.ctx.Fields, fields...) + sbuild := &VerySecretSelect{VerySecretQuery: vsq} + sbuild.label = verysecret.Label + sbuild.flds, sbuild.scan = &vsq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a VerySecretSelect configured with the given aggregations. +func (vsq *VerySecretQuery) Aggregate(fns ...AggregateFunc) *VerySecretSelect { + return vsq.Select().Aggregate(fns...) +} + +func (vsq *VerySecretQuery) prepareQuery(ctx context.Context) error { + for _, inter := range vsq.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, vsq); err != nil { + return err + } + } + } + for _, f := range vsq.ctx.Fields { + if !verysecret.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if vsq.path != nil { + prev, err := vsq.path(ctx) + if err != nil { + return err + } + vsq.sql = prev + } + return nil +} + +func (vsq *VerySecretQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*VerySecret, error) { + var ( + nodes = []*VerySecret{} + _spec = vsq.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*VerySecret).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &VerySecret{config: vsq.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + if len(vsq.modifiers) > 0 { + _spec.Modifiers = vsq.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, vsq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + for i := range vsq.loadTotal { + if err := vsq.loadTotal[i](ctx, nodes); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (vsq *VerySecretQuery) sqlCount(ctx context.Context) (int, error) { + _spec := vsq.querySpec() + if len(vsq.modifiers) > 0 { + _spec.Modifiers = vsq.modifiers + } + _spec.Node.Columns = vsq.ctx.Fields + if len(vsq.ctx.Fields) > 0 { + _spec.Unique = vsq.ctx.Unique != nil && *vsq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, vsq.driver, _spec) +} + +func (vsq *VerySecretQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(verysecret.Table, verysecret.Columns, sqlgraph.NewFieldSpec(verysecret.FieldID, field.TypeInt)) + _spec.From = vsq.sql + if unique := vsq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if vsq.path != nil { + _spec.Unique = true + } + if fields := vsq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, verysecret.FieldID) + for i := range fields { + if fields[i] != verysecret.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := vsq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := vsq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := vsq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := vsq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (vsq *VerySecretQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(vsq.driver.Dialect()) + t1 := builder.Table(verysecret.Table) + columns := vsq.ctx.Fields + if len(columns) == 0 { + columns = verysecret.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if vsq.sql != nil { + selector = vsq.sql + selector.Select(selector.Columns(columns...)...) + } + if vsq.ctx.Unique != nil && *vsq.ctx.Unique { + selector.Distinct() + } + for _, m := range vsq.modifiers { + m(selector) + } + for _, p := range vsq.predicates { + p(selector) + } + for _, p := range vsq.order { + p(selector) + } + if offset := vsq.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 := vsq.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (vsq *VerySecretQuery) Modify(modifiers ...func(s *sql.Selector)) *VerySecretSelect { + vsq.modifiers = append(vsq.modifiers, modifiers...) + return vsq.Select() +} + +// VerySecretGroupBy is the group-by builder for VerySecret entities. +type VerySecretGroupBy struct { + selector + build *VerySecretQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (vsgb *VerySecretGroupBy) Aggregate(fns ...AggregateFunc) *VerySecretGroupBy { + vsgb.fns = append(vsgb.fns, fns...) + return vsgb +} + +// Scan applies the selector query and scans the result into the given value. +func (vsgb *VerySecretGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, vsgb.build.ctx, ent.OpQueryGroupBy) + if err := vsgb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*VerySecretQuery, *VerySecretGroupBy](ctx, vsgb.build, vsgb, vsgb.build.inters, v) +} + +func (vsgb *VerySecretGroupBy) sqlScan(ctx context.Context, root *VerySecretQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(vsgb.fns)) + for _, fn := range vsgb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*vsgb.flds)+len(vsgb.fns)) + for _, f := range *vsgb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*vsgb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := vsgb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// VerySecretSelect is the builder for selecting fields of VerySecret entities. +type VerySecretSelect struct { + *VerySecretQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (vss *VerySecretSelect) Aggregate(fns ...AggregateFunc) *VerySecretSelect { + vss.fns = append(vss.fns, fns...) + return vss +} + +// Scan applies the selector query and scans the result into the given value. +func (vss *VerySecretSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, vss.ctx, ent.OpQuerySelect) + if err := vss.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*VerySecretQuery, *VerySecretSelect](ctx, vss.VerySecretQuery, vss, vss.inters, v) +} + +func (vss *VerySecretSelect) sqlScan(ctx context.Context, root *VerySecretQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(vss.fns)) + for _, fn := range vss.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*vss.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 := vss.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (vss *VerySecretSelect) Modify(modifiers ...func(s *sql.Selector)) *VerySecretSelect { + vss.modifiers = append(vss.modifiers, modifiers...) + return vss +} diff --git a/entgql/internal/todoglobalid/ent/verysecret_update.go b/entgql/internal/todoglobalid/ent/verysecret_update.go new file mode 100644 index 000000000..5a32318c7 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/verysecret_update.go @@ -0,0 +1,239 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/verysecret" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// VerySecretUpdate is the builder for updating VerySecret entities. +type VerySecretUpdate struct { + config + hooks []Hook + mutation *VerySecretMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the VerySecretUpdate builder. +func (vsu *VerySecretUpdate) Where(ps ...predicate.VerySecret) *VerySecretUpdate { + vsu.mutation.Where(ps...) + return vsu +} + +// SetPassword sets the "password" field. +func (vsu *VerySecretUpdate) SetPassword(s string) *VerySecretUpdate { + vsu.mutation.SetPassword(s) + return vsu +} + +// SetNillablePassword sets the "password" field if the given value is not nil. +func (vsu *VerySecretUpdate) SetNillablePassword(s *string) *VerySecretUpdate { + if s != nil { + vsu.SetPassword(*s) + } + return vsu +} + +// Mutation returns the VerySecretMutation object of the builder. +func (vsu *VerySecretUpdate) Mutation() *VerySecretMutation { + return vsu.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (vsu *VerySecretUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, vsu.sqlSave, vsu.mutation, vsu.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (vsu *VerySecretUpdate) SaveX(ctx context.Context) int { + affected, err := vsu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (vsu *VerySecretUpdate) Exec(ctx context.Context) error { + _, err := vsu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (vsu *VerySecretUpdate) ExecX(ctx context.Context) { + if err := vsu.Exec(ctx); err != nil { + panic(err) + } +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (vsu *VerySecretUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *VerySecretUpdate { + vsu.modifiers = append(vsu.modifiers, modifiers...) + return vsu +} + +func (vsu *VerySecretUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := sqlgraph.NewUpdateSpec(verysecret.Table, verysecret.Columns, sqlgraph.NewFieldSpec(verysecret.FieldID, field.TypeInt)) + if ps := vsu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := vsu.mutation.Password(); ok { + _spec.SetField(verysecret.FieldPassword, field.TypeString, value) + } + _spec.AddModifiers(vsu.modifiers...) + if n, err = sqlgraph.UpdateNodes(ctx, vsu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{verysecret.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + vsu.mutation.done = true + return n, nil +} + +// VerySecretUpdateOne is the builder for updating a single VerySecret entity. +type VerySecretUpdateOne struct { + config + fields []string + hooks []Hook + mutation *VerySecretMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetPassword sets the "password" field. +func (vsuo *VerySecretUpdateOne) SetPassword(s string) *VerySecretUpdateOne { + vsuo.mutation.SetPassword(s) + return vsuo +} + +// SetNillablePassword sets the "password" field if the given value is not nil. +func (vsuo *VerySecretUpdateOne) SetNillablePassword(s *string) *VerySecretUpdateOne { + if s != nil { + vsuo.SetPassword(*s) + } + return vsuo +} + +// Mutation returns the VerySecretMutation object of the builder. +func (vsuo *VerySecretUpdateOne) Mutation() *VerySecretMutation { + return vsuo.mutation +} + +// Where appends a list predicates to the VerySecretUpdate builder. +func (vsuo *VerySecretUpdateOne) Where(ps ...predicate.VerySecret) *VerySecretUpdateOne { + vsuo.mutation.Where(ps...) + return vsuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (vsuo *VerySecretUpdateOne) Select(field string, fields ...string) *VerySecretUpdateOne { + vsuo.fields = append([]string{field}, fields...) + return vsuo +} + +// Save executes the query and returns the updated VerySecret entity. +func (vsuo *VerySecretUpdateOne) Save(ctx context.Context) (*VerySecret, error) { + return withHooks(ctx, vsuo.sqlSave, vsuo.mutation, vsuo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (vsuo *VerySecretUpdateOne) SaveX(ctx context.Context) *VerySecret { + node, err := vsuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (vsuo *VerySecretUpdateOne) Exec(ctx context.Context) error { + _, err := vsuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (vsuo *VerySecretUpdateOne) ExecX(ctx context.Context) { + if err := vsuo.Exec(ctx); err != nil { + panic(err) + } +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (vsuo *VerySecretUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *VerySecretUpdateOne { + vsuo.modifiers = append(vsuo.modifiers, modifiers...) + return vsuo +} + +func (vsuo *VerySecretUpdateOne) sqlSave(ctx context.Context) (_node *VerySecret, err error) { + _spec := sqlgraph.NewUpdateSpec(verysecret.Table, verysecret.Columns, sqlgraph.NewFieldSpec(verysecret.FieldID, field.TypeInt)) + id, ok := vsuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "VerySecret.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := vsuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, verysecret.FieldID) + for _, f := range fields { + if !verysecret.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != verysecret.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := vsuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := vsuo.mutation.Password(); ok { + _spec.SetField(verysecret.FieldPassword, field.TypeString, value) + } + _spec.AddModifiers(vsuo.modifiers...) + _node = &VerySecret{config: vsuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, vsuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{verysecret.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + vsuo.mutation.done = true + return _node, nil +} diff --git a/entgql/internal/todoglobalid/ent/workspace.go b/entgql/internal/todoglobalid/ent/workspace.go new file mode 100644 index 000000000..5f532df70 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/workspace.go @@ -0,0 +1,117 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "fmt" + "strings" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/workspace" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" +) + +// Workspace is the model entity for the Workspace schema. +type Workspace struct { + config `json:"-"` + // ID of the ent. + ID int `json:"id,omitempty"` + // Name holds the value of the "name" field. + Name string `json:"name,omitempty"` + selectValues sql.SelectValues +} + +// scanValues returns the types for scanning values from sql.Rows. +func (*Workspace) scanValues(columns []string) ([]any, error) { + values := make([]any, len(columns)) + for i := range columns { + switch columns[i] { + case workspace.FieldID: + values[i] = new(sql.NullInt64) + case workspace.FieldName: + 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 Workspace fields. +func (w *Workspace) 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 workspace.FieldID: + value, ok := values[i].(*sql.NullInt64) + if !ok { + return fmt.Errorf("unexpected type %T for field id", value) + } + w.ID = int(value.Int64) + case workspace.FieldName: + if value, ok := values[i].(*sql.NullString); !ok { + return fmt.Errorf("unexpected type %T for field name", values[i]) + } else if value.Valid { + w.Name = value.String + } + default: + w.selectValues.Set(columns[i], values[i]) + } + } + return nil +} + +// Value returns the ent.Value that was dynamically selected and assigned to the Workspace. +// This includes values selected through modifiers, order, etc. +func (w *Workspace) Value(name string) (ent.Value, error) { + return w.selectValues.Get(name) +} + +// Update returns a builder for updating this Workspace. +// Note that you need to call Workspace.Unwrap() before calling this method if this Workspace +// was returned from a transaction, and the transaction was committed or rolled back. +func (w *Workspace) Update() *WorkspaceUpdateOne { + return NewWorkspaceClient(w.config).UpdateOne(w) +} + +// Unwrap unwraps the Workspace 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 (w *Workspace) Unwrap() *Workspace { + _tx, ok := w.config.driver.(*txDriver) + if !ok { + panic("ent: Workspace is not a transactional entity") + } + w.config.driver = _tx.drv + return w +} + +// String implements the fmt.Stringer. +func (w *Workspace) String() string { + var builder strings.Builder + builder.WriteString("Workspace(") + builder.WriteString(fmt.Sprintf("id=%v, ", w.ID)) + builder.WriteString("name=") + builder.WriteString(w.Name) + builder.WriteByte(')') + return builder.String() +} + +// Workspaces is a parsable slice of Workspace. +type Workspaces []*Workspace diff --git a/entgql/internal/todoglobalid/ent/workspace/where.go b/entgql/internal/todoglobalid/ent/workspace/where.go new file mode 100644 index 000000000..1ec473725 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/workspace/where.go @@ -0,0 +1,152 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package workspace + +import ( + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/ent/dialect/sql" +) + +// ID filters vertices based on their ID field. +func ID(id int) predicate.Workspace { + return predicate.Workspace(sql.FieldEQ(FieldID, id)) +} + +// IDEQ applies the EQ predicate on the ID field. +func IDEQ(id int) predicate.Workspace { + return predicate.Workspace(sql.FieldEQ(FieldID, id)) +} + +// IDNEQ applies the NEQ predicate on the ID field. +func IDNEQ(id int) predicate.Workspace { + return predicate.Workspace(sql.FieldNEQ(FieldID, id)) +} + +// IDIn applies the In predicate on the ID field. +func IDIn(ids ...int) predicate.Workspace { + return predicate.Workspace(sql.FieldIn(FieldID, ids...)) +} + +// IDNotIn applies the NotIn predicate on the ID field. +func IDNotIn(ids ...int) predicate.Workspace { + return predicate.Workspace(sql.FieldNotIn(FieldID, ids...)) +} + +// IDGT applies the GT predicate on the ID field. +func IDGT(id int) predicate.Workspace { + return predicate.Workspace(sql.FieldGT(FieldID, id)) +} + +// IDGTE applies the GTE predicate on the ID field. +func IDGTE(id int) predicate.Workspace { + return predicate.Workspace(sql.FieldGTE(FieldID, id)) +} + +// IDLT applies the LT predicate on the ID field. +func IDLT(id int) predicate.Workspace { + return predicate.Workspace(sql.FieldLT(FieldID, id)) +} + +// IDLTE applies the LTE predicate on the ID field. +func IDLTE(id int) predicate.Workspace { + return predicate.Workspace(sql.FieldLTE(FieldID, id)) +} + +// Name applies equality check predicate on the "name" field. It's identical to NameEQ. +func Name(v string) predicate.Workspace { + return predicate.Workspace(sql.FieldEQ(FieldName, v)) +} + +// NameEQ applies the EQ predicate on the "name" field. +func NameEQ(v string) predicate.Workspace { + return predicate.Workspace(sql.FieldEQ(FieldName, v)) +} + +// NameNEQ applies the NEQ predicate on the "name" field. +func NameNEQ(v string) predicate.Workspace { + return predicate.Workspace(sql.FieldNEQ(FieldName, v)) +} + +// NameIn applies the In predicate on the "name" field. +func NameIn(vs ...string) predicate.Workspace { + return predicate.Workspace(sql.FieldIn(FieldName, vs...)) +} + +// NameNotIn applies the NotIn predicate on the "name" field. +func NameNotIn(vs ...string) predicate.Workspace { + return predicate.Workspace(sql.FieldNotIn(FieldName, vs...)) +} + +// NameGT applies the GT predicate on the "name" field. +func NameGT(v string) predicate.Workspace { + return predicate.Workspace(sql.FieldGT(FieldName, v)) +} + +// NameGTE applies the GTE predicate on the "name" field. +func NameGTE(v string) predicate.Workspace { + return predicate.Workspace(sql.FieldGTE(FieldName, v)) +} + +// NameLT applies the LT predicate on the "name" field. +func NameLT(v string) predicate.Workspace { + return predicate.Workspace(sql.FieldLT(FieldName, v)) +} + +// NameLTE applies the LTE predicate on the "name" field. +func NameLTE(v string) predicate.Workspace { + return predicate.Workspace(sql.FieldLTE(FieldName, v)) +} + +// NameContains applies the Contains predicate on the "name" field. +func NameContains(v string) predicate.Workspace { + return predicate.Workspace(sql.FieldContains(FieldName, v)) +} + +// NameHasPrefix applies the HasPrefix predicate on the "name" field. +func NameHasPrefix(v string) predicate.Workspace { + return predicate.Workspace(sql.FieldHasPrefix(FieldName, v)) +} + +// NameHasSuffix applies the HasSuffix predicate on the "name" field. +func NameHasSuffix(v string) predicate.Workspace { + return predicate.Workspace(sql.FieldHasSuffix(FieldName, v)) +} + +// NameEqualFold applies the EqualFold predicate on the "name" field. +func NameEqualFold(v string) predicate.Workspace { + return predicate.Workspace(sql.FieldEqualFold(FieldName, v)) +} + +// NameContainsFold applies the ContainsFold predicate on the "name" field. +func NameContainsFold(v string) predicate.Workspace { + return predicate.Workspace(sql.FieldContainsFold(FieldName, v)) +} + +// And groups predicates with the AND operator between them. +func And(predicates ...predicate.Workspace) predicate.Workspace { + return predicate.Workspace(sql.AndPredicates(predicates...)) +} + +// Or groups predicates with the OR operator between them. +func Or(predicates ...predicate.Workspace) predicate.Workspace { + return predicate.Workspace(sql.OrPredicates(predicates...)) +} + +// Not applies the not operator on the given predicate. +func Not(p predicate.Workspace) predicate.Workspace { + return predicate.Workspace(sql.NotPredicates(p)) +} diff --git a/entgql/internal/todoglobalid/ent/workspace/workspace.go b/entgql/internal/todoglobalid/ent/workspace/workspace.go new file mode 100644 index 000000000..6ff1632c3 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/workspace/workspace.go @@ -0,0 +1,61 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package workspace + +import ( + "entgo.io/ent/dialect/sql" +) + +const ( + // Label holds the string label denoting the workspace type in the database. + Label = "workspace" + // FieldID holds the string denoting the id field in the database. + FieldID = "id" + // FieldName holds the string denoting the name field in the database. + FieldName = "name" + // Table holds the table name of the workspace in the database. + Table = "workspaces" +) + +// Columns holds all SQL columns for workspace fields. +var Columns = []string{ + FieldID, + FieldName, +} + +// 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 +} + +// OrderOption defines the ordering options for the Workspace 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() +} + +// ByName orders the results by the name field. +func ByName(opts ...sql.OrderTermOption) OrderOption { + return sql.OrderByField(FieldName, opts...).ToFunc() +} diff --git a/entgql/internal/todoglobalid/ent/workspace_create.go b/entgql/internal/todoglobalid/ent/workspace_create.go new file mode 100644 index 000000000..2e2329035 --- /dev/null +++ b/entgql/internal/todoglobalid/ent/workspace_create.go @@ -0,0 +1,197 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/workspace" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// WorkspaceCreate is the builder for creating a Workspace entity. +type WorkspaceCreate struct { + config + mutation *WorkspaceMutation + hooks []Hook +} + +// SetName sets the "name" field. +func (wc *WorkspaceCreate) SetName(s string) *WorkspaceCreate { + wc.mutation.SetName(s) + return wc +} + +// Mutation returns the WorkspaceMutation object of the builder. +func (wc *WorkspaceCreate) Mutation() *WorkspaceMutation { + return wc.mutation +} + +// Save creates the Workspace in the database. +func (wc *WorkspaceCreate) Save(ctx context.Context) (*Workspace, error) { + return withHooks(ctx, wc.sqlSave, wc.mutation, wc.hooks) +} + +// SaveX calls Save and panics if Save returns an error. +func (wc *WorkspaceCreate) SaveX(ctx context.Context) *Workspace { + v, err := wc.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (wc *WorkspaceCreate) Exec(ctx context.Context) error { + _, err := wc.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (wc *WorkspaceCreate) ExecX(ctx context.Context) { + if err := wc.Exec(ctx); err != nil { + panic(err) + } +} + +// check runs all checks and user-defined validators on the builder. +func (wc *WorkspaceCreate) check() error { + if _, ok := wc.mutation.Name(); !ok { + return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Workspace.name"`)} + } + return nil +} + +func (wc *WorkspaceCreate) sqlSave(ctx context.Context) (*Workspace, error) { + if err := wc.check(); err != nil { + return nil, err + } + _node, _spec := wc.createSpec() + if err := sqlgraph.CreateNode(ctx, wc.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) + wc.mutation.id = &_node.ID + wc.mutation.done = true + return _node, nil +} + +func (wc *WorkspaceCreate) createSpec() (*Workspace, *sqlgraph.CreateSpec) { + var ( + _node = &Workspace{config: wc.config} + _spec = sqlgraph.NewCreateSpec(workspace.Table, sqlgraph.NewFieldSpec(workspace.FieldID, field.TypeInt)) + ) + if value, ok := wc.mutation.Name(); ok { + _spec.SetField(workspace.FieldName, field.TypeString, value) + _node.Name = value + } + return _node, _spec +} + +// WorkspaceCreateBulk is the builder for creating many Workspace entities in bulk. +type WorkspaceCreateBulk struct { + config + err error + builders []*WorkspaceCreate +} + +// Save creates the Workspace entities in the database. +func (wcb *WorkspaceCreateBulk) Save(ctx context.Context) ([]*Workspace, error) { + if wcb.err != nil { + return nil, wcb.err + } + specs := make([]*sqlgraph.CreateSpec, len(wcb.builders)) + nodes := make([]*Workspace, len(wcb.builders)) + mutators := make([]Mutator, len(wcb.builders)) + for i := range wcb.builders { + func(i int, root context.Context) { + builder := wcb.builders[i] + var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { + mutation, ok := m.(*WorkspaceMutation) + 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, wcb.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, wcb.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, wcb.builders[0].mutation); err != nil { + return nil, err + } + } + return nodes, nil +} + +// SaveX is like Save, but panics if an error occurs. +func (wcb *WorkspaceCreateBulk) SaveX(ctx context.Context) []*Workspace { + v, err := wcb.Save(ctx) + if err != nil { + panic(err) + } + return v +} + +// Exec executes the query. +func (wcb *WorkspaceCreateBulk) Exec(ctx context.Context) error { + _, err := wcb.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (wcb *WorkspaceCreateBulk) ExecX(ctx context.Context) { + if err := wcb.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entgql/internal/todoglobalid/ent/workspace_delete.go b/entgql/internal/todoglobalid/ent/workspace_delete.go new file mode 100644 index 000000000..3d1c7bd6b --- /dev/null +++ b/entgql/internal/todoglobalid/ent/workspace_delete.go @@ -0,0 +1,102 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/workspace" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// WorkspaceDelete is the builder for deleting a Workspace entity. +type WorkspaceDelete struct { + config + hooks []Hook + mutation *WorkspaceMutation +} + +// Where appends a list predicates to the WorkspaceDelete builder. +func (wd *WorkspaceDelete) Where(ps ...predicate.Workspace) *WorkspaceDelete { + wd.mutation.Where(ps...) + return wd +} + +// Exec executes the deletion query and returns how many vertices were deleted. +func (wd *WorkspaceDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, wd.sqlExec, wd.mutation, wd.hooks) +} + +// ExecX is like Exec, but panics if an error occurs. +func (wd *WorkspaceDelete) ExecX(ctx context.Context) int { + n, err := wd.Exec(ctx) + if err != nil { + panic(err) + } + return n +} + +func (wd *WorkspaceDelete) sqlExec(ctx context.Context) (int, error) { + _spec := sqlgraph.NewDeleteSpec(workspace.Table, sqlgraph.NewFieldSpec(workspace.FieldID, field.TypeInt)) + if ps := wd.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + affected, err := sqlgraph.DeleteNodes(ctx, wd.driver, _spec) + if err != nil && sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + wd.mutation.done = true + return affected, err +} + +// WorkspaceDeleteOne is the builder for deleting a single Workspace entity. +type WorkspaceDeleteOne struct { + wd *WorkspaceDelete +} + +// Where appends a list predicates to the WorkspaceDelete builder. +func (wdo *WorkspaceDeleteOne) Where(ps ...predicate.Workspace) *WorkspaceDeleteOne { + wdo.wd.mutation.Where(ps...) + return wdo +} + +// Exec executes the deletion query. +func (wdo *WorkspaceDeleteOne) Exec(ctx context.Context) error { + n, err := wdo.wd.Exec(ctx) + switch { + case err != nil: + return err + case n == 0: + return &NotFoundError{workspace.Label} + default: + return nil + } +} + +// ExecX is like Exec, but panics if an error occurs. +func (wdo *WorkspaceDeleteOne) ExecX(ctx context.Context) { + if err := wdo.Exec(ctx); err != nil { + panic(err) + } +} diff --git a/entgql/internal/todoglobalid/ent/workspace_query.go b/entgql/internal/todoglobalid/ent/workspace_query.go new file mode 100644 index 000000000..fcdee9c2d --- /dev/null +++ b/entgql/internal/todoglobalid/ent/workspace_query.go @@ -0,0 +1,570 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "fmt" + "math" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/workspace" + "entgo.io/ent" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// WorkspaceQuery is the builder for querying Workspace entities. +type WorkspaceQuery struct { + config + ctx *QueryContext + order []workspace.OrderOption + inters []Interceptor + predicates []predicate.Workspace + loadTotal []func(context.Context, []*Workspace) error + modifiers []func(*sql.Selector) + // intermediate query (i.e. traversal path). + sql *sql.Selector + path func(context.Context) (*sql.Selector, error) +} + +// Where adds a new predicate for the WorkspaceQuery builder. +func (wq *WorkspaceQuery) Where(ps ...predicate.Workspace) *WorkspaceQuery { + wq.predicates = append(wq.predicates, ps...) + return wq +} + +// Limit the number of records to be returned by this query. +func (wq *WorkspaceQuery) Limit(limit int) *WorkspaceQuery { + wq.ctx.Limit = &limit + return wq +} + +// Offset to start from. +func (wq *WorkspaceQuery) Offset(offset int) *WorkspaceQuery { + wq.ctx.Offset = &offset + return wq +} + +// 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 (wq *WorkspaceQuery) Unique(unique bool) *WorkspaceQuery { + wq.ctx.Unique = &unique + return wq +} + +// Order specifies how the records should be ordered. +func (wq *WorkspaceQuery) Order(o ...workspace.OrderOption) *WorkspaceQuery { + wq.order = append(wq.order, o...) + return wq +} + +// First returns the first Workspace entity from the query. +// Returns a *NotFoundError when no Workspace was found. +func (wq *WorkspaceQuery) First(ctx context.Context) (*Workspace, error) { + nodes, err := wq.Limit(1).All(setContextOp(ctx, wq.ctx, ent.OpQueryFirst)) + if err != nil { + return nil, err + } + if len(nodes) == 0 { + return nil, &NotFoundError{workspace.Label} + } + return nodes[0], nil +} + +// FirstX is like First, but panics if an error occurs. +func (wq *WorkspaceQuery) FirstX(ctx context.Context) *Workspace { + node, err := wq.First(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return node +} + +// FirstID returns the first Workspace ID from the query. +// Returns a *NotFoundError when no Workspace ID was found. +func (wq *WorkspaceQuery) FirstID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = wq.Limit(1).IDs(setContextOp(ctx, wq.ctx, ent.OpQueryFirstID)); err != nil { + return + } + if len(ids) == 0 { + err = &NotFoundError{workspace.Label} + return + } + return ids[0], nil +} + +// FirstIDX is like FirstID, but panics if an error occurs. +func (wq *WorkspaceQuery) FirstIDX(ctx context.Context) int { + id, err := wq.FirstID(ctx) + if err != nil && !IsNotFound(err) { + panic(err) + } + return id +} + +// Only returns a single Workspace entity found by the query, ensuring it only returns one. +// Returns a *NotSingularError when more than one Workspace entity is found. +// Returns a *NotFoundError when no Workspace entities are found. +func (wq *WorkspaceQuery) Only(ctx context.Context) (*Workspace, error) { + nodes, err := wq.Limit(2).All(setContextOp(ctx, wq.ctx, ent.OpQueryOnly)) + if err != nil { + return nil, err + } + switch len(nodes) { + case 1: + return nodes[0], nil + case 0: + return nil, &NotFoundError{workspace.Label} + default: + return nil, &NotSingularError{workspace.Label} + } +} + +// OnlyX is like Only, but panics if an error occurs. +func (wq *WorkspaceQuery) OnlyX(ctx context.Context) *Workspace { + node, err := wq.Only(ctx) + if err != nil { + panic(err) + } + return node +} + +// OnlyID is like Only, but returns the only Workspace ID in the query. +// Returns a *NotSingularError when more than one Workspace ID is found. +// Returns a *NotFoundError when no entities are found. +func (wq *WorkspaceQuery) OnlyID(ctx context.Context) (id int, err error) { + var ids []int + if ids, err = wq.Limit(2).IDs(setContextOp(ctx, wq.ctx, ent.OpQueryOnlyID)); err != nil { + return + } + switch len(ids) { + case 1: + id = ids[0] + case 0: + err = &NotFoundError{workspace.Label} + default: + err = &NotSingularError{workspace.Label} + } + return +} + +// OnlyIDX is like OnlyID, but panics if an error occurs. +func (wq *WorkspaceQuery) OnlyIDX(ctx context.Context) int { + id, err := wq.OnlyID(ctx) + if err != nil { + panic(err) + } + return id +} + +// All executes the query and returns a list of Workspaces. +func (wq *WorkspaceQuery) All(ctx context.Context) ([]*Workspace, error) { + ctx = setContextOp(ctx, wq.ctx, ent.OpQueryAll) + if err := wq.prepareQuery(ctx); err != nil { + return nil, err + } + qr := querierAll[[]*Workspace, *WorkspaceQuery]() + return withInterceptors[[]*Workspace](ctx, wq, qr, wq.inters) +} + +// AllX is like All, but panics if an error occurs. +func (wq *WorkspaceQuery) AllX(ctx context.Context) []*Workspace { + nodes, err := wq.All(ctx) + if err != nil { + panic(err) + } + return nodes +} + +// IDs executes the query and returns a list of Workspace IDs. +func (wq *WorkspaceQuery) IDs(ctx context.Context) (ids []int, err error) { + if wq.ctx.Unique == nil && wq.path != nil { + wq.Unique(true) + } + ctx = setContextOp(ctx, wq.ctx, ent.OpQueryIDs) + if err = wq.Select(workspace.FieldID).Scan(ctx, &ids); err != nil { + return nil, err + } + return ids, nil +} + +// IDsX is like IDs, but panics if an error occurs. +func (wq *WorkspaceQuery) IDsX(ctx context.Context) []int { + ids, err := wq.IDs(ctx) + if err != nil { + panic(err) + } + return ids +} + +// Count returns the count of the given query. +func (wq *WorkspaceQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, wq.ctx, ent.OpQueryCount) + if err := wq.prepareQuery(ctx); err != nil { + return 0, err + } + return withInterceptors[int](ctx, wq, querierCount[*WorkspaceQuery](), wq.inters) +} + +// CountX is like Count, but panics if an error occurs. +func (wq *WorkspaceQuery) CountX(ctx context.Context) int { + count, err := wq.Count(ctx) + if err != nil { + panic(err) + } + return count +} + +// Exist returns true if the query has elements in the graph. +func (wq *WorkspaceQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, wq.ctx, ent.OpQueryExist) + switch _, err := wq.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 (wq *WorkspaceQuery) ExistX(ctx context.Context) bool { + exist, err := wq.Exist(ctx) + if err != nil { + panic(err) + } + return exist +} + +// Clone returns a duplicate of the WorkspaceQuery builder, including all associated steps. It can be +// used to prepare common query builders and use them differently after the clone is made. +func (wq *WorkspaceQuery) Clone() *WorkspaceQuery { + if wq == nil { + return nil + } + return &WorkspaceQuery{ + config: wq.config, + ctx: wq.ctx.Clone(), + order: append([]workspace.OrderOption{}, wq.order...), + inters: append([]Interceptor{}, wq.inters...), + predicates: append([]predicate.Workspace{}, wq.predicates...), + // clone intermediate query. + sql: wq.sql.Clone(), + path: wq.path, + modifiers: append([]func(*sql.Selector){}, wq.modifiers...), + } +} + +// 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 { +// Name string `json:"name,omitempty"` +// Count int `json:"count,omitempty"` +// } +// +// client.Workspace.Query(). +// GroupBy(workspace.FieldName). +// Aggregate(ent.Count()). +// Scan(ctx, &v) +func (wq *WorkspaceQuery) GroupBy(field string, fields ...string) *WorkspaceGroupBy { + wq.ctx.Fields = append([]string{field}, fields...) + grbuild := &WorkspaceGroupBy{build: wq} + grbuild.flds = &wq.ctx.Fields + grbuild.label = workspace.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 { +// Name string `json:"name,omitempty"` +// } +// +// client.Workspace.Query(). +// Select(workspace.FieldName). +// Scan(ctx, &v) +func (wq *WorkspaceQuery) Select(fields ...string) *WorkspaceSelect { + wq.ctx.Fields = append(wq.ctx.Fields, fields...) + sbuild := &WorkspaceSelect{WorkspaceQuery: wq} + sbuild.label = workspace.Label + sbuild.flds, sbuild.scan = &wq.ctx.Fields, sbuild.Scan + return sbuild +} + +// Aggregate returns a WorkspaceSelect configured with the given aggregations. +func (wq *WorkspaceQuery) Aggregate(fns ...AggregateFunc) *WorkspaceSelect { + return wq.Select().Aggregate(fns...) +} + +func (wq *WorkspaceQuery) prepareQuery(ctx context.Context) error { + for _, inter := range wq.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, wq); err != nil { + return err + } + } + } + for _, f := range wq.ctx.Fields { + if !workspace.ValidColumn(f) { + return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + } + if wq.path != nil { + prev, err := wq.path(ctx) + if err != nil { + return err + } + wq.sql = prev + } + return nil +} + +func (wq *WorkspaceQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Workspace, error) { + var ( + nodes = []*Workspace{} + _spec = wq.querySpec() + ) + _spec.ScanValues = func(columns []string) ([]any, error) { + return (*Workspace).scanValues(nil, columns) + } + _spec.Assign = func(columns []string, values []any) error { + node := &Workspace{config: wq.config} + nodes = append(nodes, node) + return node.assignValues(columns, values) + } + if len(wq.modifiers) > 0 { + _spec.Modifiers = wq.modifiers + } + for i := range hooks { + hooks[i](ctx, _spec) + } + if err := sqlgraph.QueryNodes(ctx, wq.driver, _spec); err != nil { + return nil, err + } + if len(nodes) == 0 { + return nodes, nil + } + for i := range wq.loadTotal { + if err := wq.loadTotal[i](ctx, nodes); err != nil { + return nil, err + } + } + return nodes, nil +} + +func (wq *WorkspaceQuery) sqlCount(ctx context.Context) (int, error) { + _spec := wq.querySpec() + if len(wq.modifiers) > 0 { + _spec.Modifiers = wq.modifiers + } + _spec.Node.Columns = wq.ctx.Fields + if len(wq.ctx.Fields) > 0 { + _spec.Unique = wq.ctx.Unique != nil && *wq.ctx.Unique + } + return sqlgraph.CountNodes(ctx, wq.driver, _spec) +} + +func (wq *WorkspaceQuery) querySpec() *sqlgraph.QuerySpec { + _spec := sqlgraph.NewQuerySpec(workspace.Table, workspace.Columns, sqlgraph.NewFieldSpec(workspace.FieldID, field.TypeInt)) + _spec.From = wq.sql + if unique := wq.ctx.Unique; unique != nil { + _spec.Unique = *unique + } else if wq.path != nil { + _spec.Unique = true + } + if fields := wq.ctx.Fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, workspace.FieldID) + for i := range fields { + if fields[i] != workspace.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) + } + } + } + if ps := wq.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if limit := wq.ctx.Limit; limit != nil { + _spec.Limit = *limit + } + if offset := wq.ctx.Offset; offset != nil { + _spec.Offset = *offset + } + if ps := wq.order; len(ps) > 0 { + _spec.Order = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + return _spec +} + +func (wq *WorkspaceQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(wq.driver.Dialect()) + t1 := builder.Table(workspace.Table) + columns := wq.ctx.Fields + if len(columns) == 0 { + columns = workspace.Columns + } + selector := builder.Select(t1.Columns(columns...)...).From(t1) + if wq.sql != nil { + selector = wq.sql + selector.Select(selector.Columns(columns...)...) + } + if wq.ctx.Unique != nil && *wq.ctx.Unique { + selector.Distinct() + } + for _, m := range wq.modifiers { + m(selector) + } + for _, p := range wq.predicates { + p(selector) + } + for _, p := range wq.order { + p(selector) + } + if offset := wq.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 := wq.ctx.Limit; limit != nil { + selector.Limit(*limit) + } + return selector +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (wq *WorkspaceQuery) Modify(modifiers ...func(s *sql.Selector)) *WorkspaceSelect { + wq.modifiers = append(wq.modifiers, modifiers...) + return wq.Select() +} + +// WorkspaceGroupBy is the group-by builder for Workspace entities. +type WorkspaceGroupBy struct { + selector + build *WorkspaceQuery +} + +// Aggregate adds the given aggregation functions to the group-by query. +func (wgb *WorkspaceGroupBy) Aggregate(fns ...AggregateFunc) *WorkspaceGroupBy { + wgb.fns = append(wgb.fns, fns...) + return wgb +} + +// Scan applies the selector query and scans the result into the given value. +func (wgb *WorkspaceGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, wgb.build.ctx, ent.OpQueryGroupBy) + if err := wgb.build.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*WorkspaceQuery, *WorkspaceGroupBy](ctx, wgb.build, wgb, wgb.build.inters, v) +} + +func (wgb *WorkspaceGroupBy) sqlScan(ctx context.Context, root *WorkspaceQuery, v any) error { + selector := root.sqlQuery(ctx).Select() + aggregation := make([]string, 0, len(wgb.fns)) + for _, fn := range wgb.fns { + aggregation = append(aggregation, fn(selector)) + } + if len(selector.SelectedColumns()) == 0 { + columns := make([]string, 0, len(*wgb.flds)+len(wgb.fns)) + for _, f := range *wgb.flds { + columns = append(columns, selector.C(f)) + } + columns = append(columns, aggregation...) + selector.Select(columns...) + } + selector.GroupBy(selector.Columns(*wgb.flds...)...) + if err := selector.Err(); err != nil { + return err + } + rows := &sql.Rows{} + query, args := selector.Query() + if err := wgb.build.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// WorkspaceSelect is the builder for selecting fields of Workspace entities. +type WorkspaceSelect struct { + *WorkspaceQuery + selector +} + +// Aggregate adds the given aggregation functions to the selector query. +func (ws *WorkspaceSelect) Aggregate(fns ...AggregateFunc) *WorkspaceSelect { + ws.fns = append(ws.fns, fns...) + return ws +} + +// Scan applies the selector query and scans the result into the given value. +func (ws *WorkspaceSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, ws.ctx, ent.OpQuerySelect) + if err := ws.prepareQuery(ctx); err != nil { + return err + } + return scanWithInterceptors[*WorkspaceQuery, *WorkspaceSelect](ctx, ws.WorkspaceQuery, ws, ws.inters, v) +} + +func (ws *WorkspaceSelect) sqlScan(ctx context.Context, root *WorkspaceQuery, v any) error { + selector := root.sqlQuery(ctx) + aggregation := make([]string, 0, len(ws.fns)) + for _, fn := range ws.fns { + aggregation = append(aggregation, fn(selector)) + } + switch n := len(*ws.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 := ws.driver.Query(ctx, query, args, rows); err != nil { + return err + } + defer rows.Close() + return sql.ScanSlice(rows, v) +} + +// Modify adds a query modifier for attaching custom logic to queries. +func (ws *WorkspaceSelect) Modify(modifiers ...func(s *sql.Selector)) *WorkspaceSelect { + ws.modifiers = append(ws.modifiers, modifiers...) + return ws +} diff --git a/entgql/internal/todoglobalid/ent/workspace_update.go b/entgql/internal/todoglobalid/ent/workspace_update.go new file mode 100644 index 000000000..009202fdd --- /dev/null +++ b/entgql/internal/todoglobalid/ent/workspace_update.go @@ -0,0 +1,239 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Code generated by entc, DO NOT EDIT. + +package ent + +import ( + "context" + "errors" + "fmt" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/predicate" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/workspace" + "entgo.io/ent/dialect/sql" + "entgo.io/ent/dialect/sql/sqlgraph" + "entgo.io/ent/schema/field" +) + +// WorkspaceUpdate is the builder for updating Workspace entities. +type WorkspaceUpdate struct { + config + hooks []Hook + mutation *WorkspaceMutation + modifiers []func(*sql.UpdateBuilder) +} + +// Where appends a list predicates to the WorkspaceUpdate builder. +func (wu *WorkspaceUpdate) Where(ps ...predicate.Workspace) *WorkspaceUpdate { + wu.mutation.Where(ps...) + return wu +} + +// SetName sets the "name" field. +func (wu *WorkspaceUpdate) SetName(s string) *WorkspaceUpdate { + wu.mutation.SetName(s) + return wu +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (wu *WorkspaceUpdate) SetNillableName(s *string) *WorkspaceUpdate { + if s != nil { + wu.SetName(*s) + } + return wu +} + +// Mutation returns the WorkspaceMutation object of the builder. +func (wu *WorkspaceUpdate) Mutation() *WorkspaceMutation { + return wu.mutation +} + +// Save executes the query and returns the number of nodes affected by the update operation. +func (wu *WorkspaceUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, wu.sqlSave, wu.mutation, wu.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (wu *WorkspaceUpdate) SaveX(ctx context.Context) int { + affected, err := wu.Save(ctx) + if err != nil { + panic(err) + } + return affected +} + +// Exec executes the query. +func (wu *WorkspaceUpdate) Exec(ctx context.Context) error { + _, err := wu.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (wu *WorkspaceUpdate) ExecX(ctx context.Context) { + if err := wu.Exec(ctx); err != nil { + panic(err) + } +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (wu *WorkspaceUpdate) Modify(modifiers ...func(u *sql.UpdateBuilder)) *WorkspaceUpdate { + wu.modifiers = append(wu.modifiers, modifiers...) + return wu +} + +func (wu *WorkspaceUpdate) sqlSave(ctx context.Context) (n int, err error) { + _spec := sqlgraph.NewUpdateSpec(workspace.Table, workspace.Columns, sqlgraph.NewFieldSpec(workspace.FieldID, field.TypeInt)) + if ps := wu.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := wu.mutation.Name(); ok { + _spec.SetField(workspace.FieldName, field.TypeString, value) + } + _spec.AddModifiers(wu.modifiers...) + if n, err = sqlgraph.UpdateNodes(ctx, wu.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{workspace.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return 0, err + } + wu.mutation.done = true + return n, nil +} + +// WorkspaceUpdateOne is the builder for updating a single Workspace entity. +type WorkspaceUpdateOne struct { + config + fields []string + hooks []Hook + mutation *WorkspaceMutation + modifiers []func(*sql.UpdateBuilder) +} + +// SetName sets the "name" field. +func (wuo *WorkspaceUpdateOne) SetName(s string) *WorkspaceUpdateOne { + wuo.mutation.SetName(s) + return wuo +} + +// SetNillableName sets the "name" field if the given value is not nil. +func (wuo *WorkspaceUpdateOne) SetNillableName(s *string) *WorkspaceUpdateOne { + if s != nil { + wuo.SetName(*s) + } + return wuo +} + +// Mutation returns the WorkspaceMutation object of the builder. +func (wuo *WorkspaceUpdateOne) Mutation() *WorkspaceMutation { + return wuo.mutation +} + +// Where appends a list predicates to the WorkspaceUpdate builder. +func (wuo *WorkspaceUpdateOne) Where(ps ...predicate.Workspace) *WorkspaceUpdateOne { + wuo.mutation.Where(ps...) + return wuo +} + +// Select allows selecting one or more fields (columns) of the returned entity. +// The default is selecting all fields defined in the entity schema. +func (wuo *WorkspaceUpdateOne) Select(field string, fields ...string) *WorkspaceUpdateOne { + wuo.fields = append([]string{field}, fields...) + return wuo +} + +// Save executes the query and returns the updated Workspace entity. +func (wuo *WorkspaceUpdateOne) Save(ctx context.Context) (*Workspace, error) { + return withHooks(ctx, wuo.sqlSave, wuo.mutation, wuo.hooks) +} + +// SaveX is like Save, but panics if an error occurs. +func (wuo *WorkspaceUpdateOne) SaveX(ctx context.Context) *Workspace { + node, err := wuo.Save(ctx) + if err != nil { + panic(err) + } + return node +} + +// Exec executes the query on the entity. +func (wuo *WorkspaceUpdateOne) Exec(ctx context.Context) error { + _, err := wuo.Save(ctx) + return err +} + +// ExecX is like Exec, but panics if an error occurs. +func (wuo *WorkspaceUpdateOne) ExecX(ctx context.Context) { + if err := wuo.Exec(ctx); err != nil { + panic(err) + } +} + +// Modify adds a statement modifier for attaching custom logic to the UPDATE statement. +func (wuo *WorkspaceUpdateOne) Modify(modifiers ...func(u *sql.UpdateBuilder)) *WorkspaceUpdateOne { + wuo.modifiers = append(wuo.modifiers, modifiers...) + return wuo +} + +func (wuo *WorkspaceUpdateOne) sqlSave(ctx context.Context) (_node *Workspace, err error) { + _spec := sqlgraph.NewUpdateSpec(workspace.Table, workspace.Columns, sqlgraph.NewFieldSpec(workspace.FieldID, field.TypeInt)) + id, ok := wuo.mutation.ID() + if !ok { + return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Workspace.id" for update`)} + } + _spec.Node.ID.Value = id + if fields := wuo.fields; len(fields) > 0 { + _spec.Node.Columns = make([]string, 0, len(fields)) + _spec.Node.Columns = append(_spec.Node.Columns, workspace.FieldID) + for _, f := range fields { + if !workspace.ValidColumn(f) { + return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} + } + if f != workspace.FieldID { + _spec.Node.Columns = append(_spec.Node.Columns, f) + } + } + } + if ps := wuo.mutation.predicates; len(ps) > 0 { + _spec.Predicate = func(selector *sql.Selector) { + for i := range ps { + ps[i](selector) + } + } + } + if value, ok := wuo.mutation.Name(); ok { + _spec.SetField(workspace.FieldName, field.TypeString, value) + } + _spec.AddModifiers(wuo.modifiers...) + _node = &Workspace{config: wuo.config} + _spec.Assign = _node.assignValues + _spec.ScanValues = _node.scanValues + if err = sqlgraph.UpdateNode(ctx, wuo.driver, _spec); err != nil { + if _, ok := err.(*sqlgraph.NotFoundError); ok { + err = &NotFoundError{workspace.Label} + } else if sqlgraph.IsConstraintError(err) { + err = &ConstraintError{msg: err.Error(), wrap: err} + } + return nil, err + } + wuo.mutation.done = true + return _node, nil +} diff --git a/entgql/internal/todoglobalid/gen.go b/entgql/internal/todoglobalid/gen.go new file mode 100644 index 000000000..29c344bfc --- /dev/null +++ b/entgql/internal/todoglobalid/gen.go @@ -0,0 +1,19 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package todo + +//go:generate go run -mod=mod ./ent/entc.go +//go:generate go run -mod=mod github.com/99designs/gqlgen +//go:generate go run -mod=mod github.com/google/addlicense -c Facebook -y 2019-present ./ diff --git a/entgql/internal/todoglobalid/gen_test.go b/entgql/internal/todoglobalid/gen_test.go new file mode 100644 index 000000000..d447c25b4 --- /dev/null +++ b/entgql/internal/todoglobalid/gen_test.go @@ -0,0 +1,54 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package todo_test + +import ( + "os" + "path/filepath" + "testing" + + "entgo.io/contrib/entgql" + "entgo.io/ent/entc" + "entgo.io/ent/entc/gen" + "github.com/stretchr/testify/require" +) + +func TestGeneratedSchema(t *testing.T) { + tempDir := t.TempDir() + gqlcfg, err := os.ReadFile("./gqlgen.yml") + require.NoError(t, err) + err = os.WriteFile(filepath.Join(tempDir, "gqlgen.yml"), gqlcfg, 0644) + require.NoError(t, err) + ex, err := entgql.NewExtension( + entgql.WithConfigPath(filepath.Join(tempDir, "gqlgen.yml")), + entgql.WithSchemaGenerator(), + entgql.WithSchemaPath(filepath.Join(tempDir, "ent.graphql")), + entgql.WithWhereInputs(true), + entgql.WithNodeDescriptor(true), + ) + require.NoError(t, err) + err = entc.Generate("./ent/schema", &gen.Config{ + Target: tempDir, + Features: []gen.Feature{ + gen.FeatureModifier, + }, + }, entc.Extensions(ex)) + require.NoError(t, err) + expected, err := os.ReadFile("./ent.graphql") + require.NoError(t, err) + actual, err := os.ReadFile(filepath.Join(tempDir, "ent.graphql")) + require.NoError(t, err) + require.Equal(t, string(expected), string(actual)) +} diff --git a/entgql/internal/todoglobalid/generated.go b/entgql/internal/todoglobalid/generated.go new file mode 100644 index 000000000..3865ed174 --- /dev/null +++ b/entgql/internal/todoglobalid/generated.go @@ -0,0 +1,19423 @@ +// Code generated by github.com/99designs/gqlgen, DO NOT EDIT. + +package todo + +import ( + "bytes" + "context" + "embed" + "errors" + "fmt" + "strconv" + "sync" + "sync/atomic" + "time" + + "entgo.io/contrib/entgql" + "entgo.io/contrib/entgql/internal/todoglobalid/ent" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/category" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/schema/customstruct" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/schema/durationgql" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/schema/schematype" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/todo" + "entgo.io/contrib/entgql/internal/todouuid/ent/schema/uuidgql" + "github.com/99designs/gqlgen/graphql" + "github.com/99designs/gqlgen/graphql/introspection" + "github.com/google/uuid" + gqlparser "github.com/vektah/gqlparser/v2" + "github.com/vektah/gqlparser/v2/ast" +) + +// region ************************** generated!.gotpl ************************** + +// NewExecutableSchema creates an ExecutableSchema from the ResolverRoot interface. +func NewExecutableSchema(cfg Config) graphql.ExecutableSchema { + return &executableSchema{ + schema: cfg.Schema, + resolvers: cfg.Resolvers, + directives: cfg.Directives, + complexity: cfg.Complexity, + } +} + +type Config struct { + Schema *ast.Schema + Resolvers ResolverRoot + Directives DirectiveRoot + Complexity ComplexityRoot +} + +type ResolverRoot interface { + Category() CategoryResolver + Mutation() MutationResolver + Query() QueryResolver + Todo() TodoResolver + CreateCategoryInput() CreateCategoryInputResolver + TodoWhereInput() TodoWhereInputResolver +} + +type DirectiveRoot struct { + HasPermissions func(ctx context.Context, obj any, next graphql.Resolver, permissions []string) (res any, err error) +} + +type ComplexityRoot struct { + BillProduct struct { + ID func(childComplexity int) int + Name func(childComplexity int) int + Quantity func(childComplexity int) int + Sku func(childComplexity int) int + } + + Category struct { + Config func(childComplexity int) int + Count func(childComplexity int) int + Duration func(childComplexity int) int + ID func(childComplexity int) int + Status func(childComplexity int) int + Strings func(childComplexity int) int + SubCategories func(childComplexity int, after *entgql.Cursor[int], first *int, before *entgql.Cursor[int], last *int, orderBy []*ent.CategoryOrder, where *ent.CategoryWhereInput) int + Text func(childComplexity int) int + Todos func(childComplexity int, after *entgql.Cursor[int], first *int, before *entgql.Cursor[int], last *int, orderBy []*ent.TodoOrder, where *ent.TodoWhereInput) int + TodosCount func(childComplexity int) int + Types func(childComplexity int) int + } + + CategoryConfig struct { + MaxMembers func(childComplexity int) int + } + + CategoryConnection struct { + Edges func(childComplexity int) int + PageInfo func(childComplexity int) int + TotalCount func(childComplexity int) int + } + + CategoryEdge struct { + Cursor func(childComplexity int) int + Node func(childComplexity int) int + } + + CategoryTypes struct { + Public func(childComplexity int) int + } + + Custom struct { + Info func(childComplexity int) int + } + + Friendship struct { + CreatedAt func(childComplexity int) int + Friend func(childComplexity int) int + FriendID func(childComplexity int) int + ID func(childComplexity int) int + User func(childComplexity int) int + UserID func(childComplexity int) int + } + + FriendshipConnection struct { + Edges func(childComplexity int) int + PageInfo func(childComplexity int) int + TotalCount func(childComplexity int) int + } + + FriendshipEdge struct { + Cursor func(childComplexity int) int + Node func(childComplexity int) int + } + + Group struct { + ID func(childComplexity int) int + Name func(childComplexity int) int + Users func(childComplexity int, after *entgql.Cursor[int], first *int, before *entgql.Cursor[int], last *int, orderBy *ent.UserOrder, where *ent.UserWhereInput) int + } + + GroupConnection struct { + Edges func(childComplexity int) int + PageInfo func(childComplexity int) int + TotalCount func(childComplexity int) int + } + + GroupEdge struct { + Cursor func(childComplexity int) int + Node func(childComplexity int) int + } + + Mutation struct { + ClearTodos func(childComplexity int) int + CreateCategory func(childComplexity int, input ent.CreateCategoryInput) int + CreateTodo func(childComplexity int, input ent.CreateTodoInput) int + UpdateFriendship func(childComplexity int, id int, input ent.UpdateFriendshipInput) int + UpdateTodo func(childComplexity int, id int, input ent.UpdateTodoInput) int + } + + OneToMany struct { + Children func(childComplexity int) int + Field2 func(childComplexity int) int + ID func(childComplexity int) int + Name func(childComplexity int) int + Parent func(childComplexity int) int + } + + OneToManyConnection struct { + Edges func(childComplexity int) int + PageInfo func(childComplexity int) int + TotalCount func(childComplexity int) int + } + + OneToManyEdge struct { + Cursor func(childComplexity int) int + Node func(childComplexity int) int + } + + Organization struct { + ID func(childComplexity int) int + Name func(childComplexity int) int + } + + PageInfo struct { + EndCursor func(childComplexity int) int + HasNextPage func(childComplexity int) int + HasPreviousPage func(childComplexity int) int + StartCursor func(childComplexity int) int + } + + Project struct { + ID func(childComplexity int) int + Todos func(childComplexity int, after *entgql.Cursor[int], first *int, before *entgql.Cursor[int], last *int, orderBy []*ent.TodoOrder, where *ent.TodoWhereInput) int + } + + Query struct { + BillProducts func(childComplexity int) int + Categories func(childComplexity int, after *entgql.Cursor[int], first *int, before *entgql.Cursor[int], last *int, orderBy []*ent.CategoryOrder, where *ent.CategoryWhereInput) int + Groups func(childComplexity int, after *entgql.Cursor[int], first *int, before *entgql.Cursor[int], last *int, where *ent.GroupWhereInput) int + Node func(childComplexity int, id int) int + Nodes func(childComplexity int, ids []int) int + OneToMany func(childComplexity int, after *entgql.Cursor[int], first *int, before *entgql.Cursor[int], last *int, orderBy *ent.OneToManyOrder, where *ent.OneToManyWhereInput) int + Ping func(childComplexity int) int + Todos func(childComplexity int, after *entgql.Cursor[int], first *int, before *entgql.Cursor[int], last *int, orderBy []*ent.TodoOrder, where *ent.TodoWhereInput) int + TodosWithJoins func(childComplexity int, after *entgql.Cursor[int], first *int, before *entgql.Cursor[int], last *int, orderBy []*ent.TodoOrder, where *ent.TodoWhereInput) int + Users func(childComplexity int, after *entgql.Cursor[int], first *int, before *entgql.Cursor[int], last *int, orderBy *ent.UserOrder, where *ent.UserWhereInput) int + } + + Todo struct { + Category func(childComplexity int) int + CategoryID func(childComplexity int) int + Children func(childComplexity int, after *entgql.Cursor[int], first *int, before *entgql.Cursor[int], last *int, orderBy []*ent.TodoOrder, where *ent.TodoWhereInput) int + CreatedAt func(childComplexity int) int + Custom func(childComplexity int) int + Customp func(childComplexity int) int + ExtendedField func(childComplexity int) int + ID func(childComplexity int) int + Init func(childComplexity int) int + Parent func(childComplexity int) int + Priority func(childComplexity int) int + Status func(childComplexity int) int + Text func(childComplexity int) int + Value func(childComplexity int) int + } + + TodoConnection struct { + Edges func(childComplexity int) int + PageInfo func(childComplexity int) int + TotalCount func(childComplexity int) int + } + + TodoEdge struct { + Cursor func(childComplexity int) int + Node func(childComplexity int) int + } + + User struct { + Friends func(childComplexity int, after *entgql.Cursor[int], first *int, before *entgql.Cursor[int], last *int, orderBy *ent.UserOrder, where *ent.UserWhereInput) int + Friendships func(childComplexity int, after *entgql.Cursor[int], first *int, before *entgql.Cursor[int], last *int, where *ent.FriendshipWhereInput) int + Groups func(childComplexity int, after *entgql.Cursor[int], first *int, before *entgql.Cursor[int], last *int, where *ent.GroupWhereInput) int + ID func(childComplexity int) int + Metadata func(childComplexity int) int + Name func(childComplexity int) int + RequiredMetadata func(childComplexity int) int + Username func(childComplexity int) int + } + + UserConnection struct { + Edges func(childComplexity int) int + PageInfo func(childComplexity int) int + TotalCount func(childComplexity int) int + } + + UserEdge struct { + Cursor func(childComplexity int) int + Node func(childComplexity int) int + } +} + +type CategoryResolver interface { + TodosCount(ctx context.Context, obj *ent.Category) (*int, error) +} +type MutationResolver interface { + CreateCategory(ctx context.Context, input ent.CreateCategoryInput) (*ent.Category, error) + CreateTodo(ctx context.Context, input ent.CreateTodoInput) (*ent.Todo, error) + UpdateTodo(ctx context.Context, id int, input ent.UpdateTodoInput) (*ent.Todo, error) + ClearTodos(ctx context.Context) (int, error) + UpdateFriendship(ctx context.Context, id int, input ent.UpdateFriendshipInput) (*ent.Friendship, error) +} +type QueryResolver interface { + Node(ctx context.Context, id int) (ent.Noder, error) + Nodes(ctx context.Context, ids []int) ([]ent.Noder, error) + BillProducts(ctx context.Context) ([]*ent.BillProduct, error) + Categories(ctx context.Context, after *entgql.Cursor[int], first *int, before *entgql.Cursor[int], last *int, orderBy []*ent.CategoryOrder, where *ent.CategoryWhereInput) (*ent.CategoryConnection, error) + Groups(ctx context.Context, after *entgql.Cursor[int], first *int, before *entgql.Cursor[int], last *int, where *ent.GroupWhereInput) (*ent.GroupConnection, error) + OneToMany(ctx context.Context, after *entgql.Cursor[int], first *int, before *entgql.Cursor[int], last *int, orderBy *ent.OneToManyOrder, where *ent.OneToManyWhereInput) (*ent.OneToManyConnection, error) + Todos(ctx context.Context, after *entgql.Cursor[int], first *int, before *entgql.Cursor[int], last *int, orderBy []*ent.TodoOrder, where *ent.TodoWhereInput) (*ent.TodoConnection, error) + Users(ctx context.Context, after *entgql.Cursor[int], first *int, before *entgql.Cursor[int], last *int, orderBy *ent.UserOrder, where *ent.UserWhereInput) (*ent.UserConnection, error) + Ping(ctx context.Context) (string, error) + TodosWithJoins(ctx context.Context, after *entgql.Cursor[int], first *int, before *entgql.Cursor[int], last *int, orderBy []*ent.TodoOrder, where *ent.TodoWhereInput) (*ent.TodoConnection, error) +} +type TodoResolver interface { + ExtendedField(ctx context.Context, obj *ent.Todo) (*string, error) +} + +type CreateCategoryInputResolver interface { + CreateTodos(ctx context.Context, obj *ent.CreateCategoryInput, data []*ent.CreateTodoInput) error +} +type TodoWhereInputResolver interface { + CreatedToday(ctx context.Context, obj *ent.TodoWhereInput, data *bool) error +} + +type executableSchema struct { + schema *ast.Schema + resolvers ResolverRoot + directives DirectiveRoot + complexity ComplexityRoot +} + +func (e *executableSchema) Schema() *ast.Schema { + if e.schema != nil { + return e.schema + } + return parsedSchema +} + +func (e *executableSchema) Complexity(typeName, field string, childComplexity int, rawArgs map[string]any) (int, bool) { + ec := executionContext{nil, e, 0, 0, nil} + _ = ec + switch typeName + "." + field { + + case "BillProduct.id": + if e.complexity.BillProduct.ID == nil { + break + } + + return e.complexity.BillProduct.ID(childComplexity), true + + case "BillProduct.name": + if e.complexity.BillProduct.Name == nil { + break + } + + return e.complexity.BillProduct.Name(childComplexity), true + + case "BillProduct.quantity": + if e.complexity.BillProduct.Quantity == nil { + break + } + + return e.complexity.BillProduct.Quantity(childComplexity), true + + case "BillProduct.sku": + if e.complexity.BillProduct.Sku == nil { + break + } + + return e.complexity.BillProduct.Sku(childComplexity), true + + case "Category.config": + if e.complexity.Category.Config == nil { + break + } + + return e.complexity.Category.Config(childComplexity), true + + case "Category.count": + if e.complexity.Category.Count == nil { + break + } + + return e.complexity.Category.Count(childComplexity), true + + case "Category.duration": + if e.complexity.Category.Duration == nil { + break + } + + return e.complexity.Category.Duration(childComplexity), true + + case "Category.id": + if e.complexity.Category.ID == nil { + break + } + + return e.complexity.Category.ID(childComplexity), true + + case "Category.status": + if e.complexity.Category.Status == nil { + break + } + + return e.complexity.Category.Status(childComplexity), true + + case "Category.strings": + if e.complexity.Category.Strings == nil { + break + } + + return e.complexity.Category.Strings(childComplexity), true + + case "Category.subCategories": + if e.complexity.Category.SubCategories == nil { + break + } + + args, err := ec.field_Category_subCategories_args(context.TODO(), rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Category.SubCategories(childComplexity, args["after"].(*entgql.Cursor[int]), args["first"].(*int), args["before"].(*entgql.Cursor[int]), args["last"].(*int), args["orderBy"].([]*ent.CategoryOrder), args["where"].(*ent.CategoryWhereInput)), true + + case "Category.text": + if e.complexity.Category.Text == nil { + break + } + + return e.complexity.Category.Text(childComplexity), true + + case "Category.todos": + if e.complexity.Category.Todos == nil { + break + } + + args, err := ec.field_Category_todos_args(context.TODO(), rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Category.Todos(childComplexity, args["after"].(*entgql.Cursor[int]), args["first"].(*int), args["before"].(*entgql.Cursor[int]), args["last"].(*int), args["orderBy"].([]*ent.TodoOrder), args["where"].(*ent.TodoWhereInput)), true + + case "Category.todosCount": + if e.complexity.Category.TodosCount == nil { + break + } + + return e.complexity.Category.TodosCount(childComplexity), true + + case "Category.types": + if e.complexity.Category.Types == nil { + break + } + + return e.complexity.Category.Types(childComplexity), true + + case "CategoryConfig.maxMembers": + if e.complexity.CategoryConfig.MaxMembers == nil { + break + } + + return e.complexity.CategoryConfig.MaxMembers(childComplexity), true + + case "CategoryConnection.edges": + if e.complexity.CategoryConnection.Edges == nil { + break + } + + return e.complexity.CategoryConnection.Edges(childComplexity), true + + case "CategoryConnection.pageInfo": + if e.complexity.CategoryConnection.PageInfo == nil { + break + } + + return e.complexity.CategoryConnection.PageInfo(childComplexity), true + + case "CategoryConnection.totalCount": + if e.complexity.CategoryConnection.TotalCount == nil { + break + } + + return e.complexity.CategoryConnection.TotalCount(childComplexity), true + + case "CategoryEdge.cursor": + if e.complexity.CategoryEdge.Cursor == nil { + break + } + + return e.complexity.CategoryEdge.Cursor(childComplexity), true + + case "CategoryEdge.node": + if e.complexity.CategoryEdge.Node == nil { + break + } + + return e.complexity.CategoryEdge.Node(childComplexity), true + + case "CategoryTypes.public": + if e.complexity.CategoryTypes.Public == nil { + break + } + + return e.complexity.CategoryTypes.Public(childComplexity), true + + case "Custom.info": + if e.complexity.Custom.Info == nil { + break + } + + return e.complexity.Custom.Info(childComplexity), true + + case "Friendship.createdAt": + if e.complexity.Friendship.CreatedAt == nil { + break + } + + return e.complexity.Friendship.CreatedAt(childComplexity), true + + case "Friendship.friend": + if e.complexity.Friendship.Friend == nil { + break + } + + return e.complexity.Friendship.Friend(childComplexity), true + + case "Friendship.friendID": + if e.complexity.Friendship.FriendID == nil { + break + } + + return e.complexity.Friendship.FriendID(childComplexity), true + + case "Friendship.id": + if e.complexity.Friendship.ID == nil { + break + } + + return e.complexity.Friendship.ID(childComplexity), true + + case "Friendship.user": + if e.complexity.Friendship.User == nil { + break + } + + return e.complexity.Friendship.User(childComplexity), true + + case "Friendship.userID": + if e.complexity.Friendship.UserID == nil { + break + } + + return e.complexity.Friendship.UserID(childComplexity), true + + case "FriendshipConnection.edges": + if e.complexity.FriendshipConnection.Edges == nil { + break + } + + return e.complexity.FriendshipConnection.Edges(childComplexity), true + + case "FriendshipConnection.pageInfo": + if e.complexity.FriendshipConnection.PageInfo == nil { + break + } + + return e.complexity.FriendshipConnection.PageInfo(childComplexity), true + + case "FriendshipConnection.totalCount": + if e.complexity.FriendshipConnection.TotalCount == nil { + break + } + + return e.complexity.FriendshipConnection.TotalCount(childComplexity), true + + case "FriendshipEdge.cursor": + if e.complexity.FriendshipEdge.Cursor == nil { + break + } + + return e.complexity.FriendshipEdge.Cursor(childComplexity), true + + case "FriendshipEdge.node": + if e.complexity.FriendshipEdge.Node == nil { + break + } + + return e.complexity.FriendshipEdge.Node(childComplexity), true + + case "Group.id": + if e.complexity.Group.ID == nil { + break + } + + return e.complexity.Group.ID(childComplexity), true + + case "Group.name": + if e.complexity.Group.Name == nil { + break + } + + return e.complexity.Group.Name(childComplexity), true + + case "Group.users": + if e.complexity.Group.Users == nil { + break + } + + args, err := ec.field_Group_users_args(context.TODO(), rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Group.Users(childComplexity, args["after"].(*entgql.Cursor[int]), args["first"].(*int), args["before"].(*entgql.Cursor[int]), args["last"].(*int), args["orderBy"].(*ent.UserOrder), args["where"].(*ent.UserWhereInput)), true + + case "GroupConnection.edges": + if e.complexity.GroupConnection.Edges == nil { + break + } + + return e.complexity.GroupConnection.Edges(childComplexity), true + + case "GroupConnection.pageInfo": + if e.complexity.GroupConnection.PageInfo == nil { + break + } + + return e.complexity.GroupConnection.PageInfo(childComplexity), true + + case "GroupConnection.totalCount": + if e.complexity.GroupConnection.TotalCount == nil { + break + } + + return e.complexity.GroupConnection.TotalCount(childComplexity), true + + case "GroupEdge.cursor": + if e.complexity.GroupEdge.Cursor == nil { + break + } + + return e.complexity.GroupEdge.Cursor(childComplexity), true + + case "GroupEdge.node": + if e.complexity.GroupEdge.Node == nil { + break + } + + return e.complexity.GroupEdge.Node(childComplexity), true + + case "Mutation.clearTodos": + if e.complexity.Mutation.ClearTodos == nil { + break + } + + return e.complexity.Mutation.ClearTodos(childComplexity), true + + case "Mutation.createCategory": + if e.complexity.Mutation.CreateCategory == nil { + break + } + + args, err := ec.field_Mutation_createCategory_args(context.TODO(), rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Mutation.CreateCategory(childComplexity, args["input"].(ent.CreateCategoryInput)), true + + case "Mutation.createTodo": + if e.complexity.Mutation.CreateTodo == nil { + break + } + + args, err := ec.field_Mutation_createTodo_args(context.TODO(), rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Mutation.CreateTodo(childComplexity, args["input"].(ent.CreateTodoInput)), true + + case "Mutation.updateFriendship": + if e.complexity.Mutation.UpdateFriendship == nil { + break + } + + args, err := ec.field_Mutation_updateFriendship_args(context.TODO(), rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Mutation.UpdateFriendship(childComplexity, args["id"].(int), args["input"].(ent.UpdateFriendshipInput)), true + + case "Mutation.updateTodo": + if e.complexity.Mutation.UpdateTodo == nil { + break + } + + args, err := ec.field_Mutation_updateTodo_args(context.TODO(), rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Mutation.UpdateTodo(childComplexity, args["id"].(int), args["input"].(ent.UpdateTodoInput)), true + + case "OneToMany.children": + if e.complexity.OneToMany.Children == nil { + break + } + + return e.complexity.OneToMany.Children(childComplexity), true + + case "OneToMany.field2": + if e.complexity.OneToMany.Field2 == nil { + break + } + + return e.complexity.OneToMany.Field2(childComplexity), true + + case "OneToMany.id": + if e.complexity.OneToMany.ID == nil { + break + } + + return e.complexity.OneToMany.ID(childComplexity), true + + case "OneToMany.name": + if e.complexity.OneToMany.Name == nil { + break + } + + return e.complexity.OneToMany.Name(childComplexity), true + + case "OneToMany.parent": + if e.complexity.OneToMany.Parent == nil { + break + } + + return e.complexity.OneToMany.Parent(childComplexity), true + + case "OneToManyConnection.edges": + if e.complexity.OneToManyConnection.Edges == nil { + break + } + + return e.complexity.OneToManyConnection.Edges(childComplexity), true + + case "OneToManyConnection.pageInfo": + if e.complexity.OneToManyConnection.PageInfo == nil { + break + } + + return e.complexity.OneToManyConnection.PageInfo(childComplexity), true + + case "OneToManyConnection.totalCount": + if e.complexity.OneToManyConnection.TotalCount == nil { + break + } + + return e.complexity.OneToManyConnection.TotalCount(childComplexity), true + + case "OneToManyEdge.cursor": + if e.complexity.OneToManyEdge.Cursor == nil { + break + } + + return e.complexity.OneToManyEdge.Cursor(childComplexity), true + + case "OneToManyEdge.node": + if e.complexity.OneToManyEdge.Node == nil { + break + } + + return e.complexity.OneToManyEdge.Node(childComplexity), true + + case "Organization.id": + if e.complexity.Organization.ID == nil { + break + } + + return e.complexity.Organization.ID(childComplexity), true + + case "Organization.name": + if e.complexity.Organization.Name == nil { + break + } + + return e.complexity.Organization.Name(childComplexity), true + + case "PageInfo.endCursor": + if e.complexity.PageInfo.EndCursor == nil { + break + } + + return e.complexity.PageInfo.EndCursor(childComplexity), true + + case "PageInfo.hasNextPage": + if e.complexity.PageInfo.HasNextPage == nil { + break + } + + return e.complexity.PageInfo.HasNextPage(childComplexity), true + + case "PageInfo.hasPreviousPage": + if e.complexity.PageInfo.HasPreviousPage == nil { + break + } + + return e.complexity.PageInfo.HasPreviousPage(childComplexity), true + + case "PageInfo.startCursor": + if e.complexity.PageInfo.StartCursor == nil { + break + } + + return e.complexity.PageInfo.StartCursor(childComplexity), true + + case "Project.id": + if e.complexity.Project.ID == nil { + break + } + + return e.complexity.Project.ID(childComplexity), true + + case "Project.todos": + if e.complexity.Project.Todos == nil { + break + } + + args, err := ec.field_Project_todos_args(context.TODO(), rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Project.Todos(childComplexity, args["after"].(*entgql.Cursor[int]), args["first"].(*int), args["before"].(*entgql.Cursor[int]), args["last"].(*int), args["orderBy"].([]*ent.TodoOrder), args["where"].(*ent.TodoWhereInput)), true + + case "Query.billProducts": + if e.complexity.Query.BillProducts == nil { + break + } + + return e.complexity.Query.BillProducts(childComplexity), true + + case "Query.categories": + if e.complexity.Query.Categories == nil { + break + } + + args, err := ec.field_Query_categories_args(context.TODO(), rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Query.Categories(childComplexity, args["after"].(*entgql.Cursor[int]), args["first"].(*int), args["before"].(*entgql.Cursor[int]), args["last"].(*int), args["orderBy"].([]*ent.CategoryOrder), args["where"].(*ent.CategoryWhereInput)), true + + case "Query.groups": + if e.complexity.Query.Groups == nil { + break + } + + args, err := ec.field_Query_groups_args(context.TODO(), rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Query.Groups(childComplexity, args["after"].(*entgql.Cursor[int]), args["first"].(*int), args["before"].(*entgql.Cursor[int]), args["last"].(*int), args["where"].(*ent.GroupWhereInput)), true + + case "Query.node": + if e.complexity.Query.Node == nil { + break + } + + args, err := ec.field_Query_node_args(context.TODO(), rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Query.Node(childComplexity, args["id"].(int)), true + + case "Query.nodes": + if e.complexity.Query.Nodes == nil { + break + } + + args, err := ec.field_Query_nodes_args(context.TODO(), rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Query.Nodes(childComplexity, args["ids"].([]int)), true + + case "Query.oneToMany": + if e.complexity.Query.OneToMany == nil { + break + } + + args, err := ec.field_Query_oneToMany_args(context.TODO(), rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Query.OneToMany(childComplexity, args["after"].(*entgql.Cursor[int]), args["first"].(*int), args["before"].(*entgql.Cursor[int]), args["last"].(*int), args["orderBy"].(*ent.OneToManyOrder), args["where"].(*ent.OneToManyWhereInput)), true + + case "Query.ping": + if e.complexity.Query.Ping == nil { + break + } + + return e.complexity.Query.Ping(childComplexity), true + + case "Query.todos": + if e.complexity.Query.Todos == nil { + break + } + + args, err := ec.field_Query_todos_args(context.TODO(), rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Query.Todos(childComplexity, args["after"].(*entgql.Cursor[int]), args["first"].(*int), args["before"].(*entgql.Cursor[int]), args["last"].(*int), args["orderBy"].([]*ent.TodoOrder), args["where"].(*ent.TodoWhereInput)), true + + case "Query.todosWithJoins": + if e.complexity.Query.TodosWithJoins == nil { + break + } + + args, err := ec.field_Query_todosWithJoins_args(context.TODO(), rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Query.TodosWithJoins(childComplexity, args["after"].(*entgql.Cursor[int]), args["first"].(*int), args["before"].(*entgql.Cursor[int]), args["last"].(*int), args["orderBy"].([]*ent.TodoOrder), args["where"].(*ent.TodoWhereInput)), true + + case "Query.users": + if e.complexity.Query.Users == nil { + break + } + + args, err := ec.field_Query_users_args(context.TODO(), rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Query.Users(childComplexity, args["after"].(*entgql.Cursor[int]), args["first"].(*int), args["before"].(*entgql.Cursor[int]), args["last"].(*int), args["orderBy"].(*ent.UserOrder), args["where"].(*ent.UserWhereInput)), true + + case "Todo.category": + if e.complexity.Todo.Category == nil { + break + } + + return e.complexity.Todo.Category(childComplexity), true + + case "Todo.categoryID", "Todo.category_id", "Todo.categoryX": + if e.complexity.Todo.CategoryID == nil { + break + } + + return e.complexity.Todo.CategoryID(childComplexity), true + + case "Todo.children": + if e.complexity.Todo.Children == nil { + break + } + + args, err := ec.field_Todo_children_args(context.TODO(), rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.Todo.Children(childComplexity, args["after"].(*entgql.Cursor[int]), args["first"].(*int), args["before"].(*entgql.Cursor[int]), args["last"].(*int), args["orderBy"].([]*ent.TodoOrder), args["where"].(*ent.TodoWhereInput)), true + + case "Todo.createdAt": + if e.complexity.Todo.CreatedAt == nil { + break + } + + return e.complexity.Todo.CreatedAt(childComplexity), true + + case "Todo.custom": + if e.complexity.Todo.Custom == nil { + break + } + + return e.complexity.Todo.Custom(childComplexity), true + + case "Todo.customp": + if e.complexity.Todo.Customp == nil { + break + } + + return e.complexity.Todo.Customp(childComplexity), true + + case "Todo.extendedField": + if e.complexity.Todo.ExtendedField == nil { + break + } + + return e.complexity.Todo.ExtendedField(childComplexity), true + + case "Todo.id": + if e.complexity.Todo.ID == nil { + break + } + + return e.complexity.Todo.ID(childComplexity), true + + case "Todo.init": + if e.complexity.Todo.Init == nil { + break + } + + return e.complexity.Todo.Init(childComplexity), true + + case "Todo.parent": + if e.complexity.Todo.Parent == nil { + break + } + + return e.complexity.Todo.Parent(childComplexity), true + + case "Todo.priorityOrder": + if e.complexity.Todo.Priority == nil { + break + } + + return e.complexity.Todo.Priority(childComplexity), true + + case "Todo.status": + if e.complexity.Todo.Status == nil { + break + } + + return e.complexity.Todo.Status(childComplexity), true + + case "Todo.text": + if e.complexity.Todo.Text == nil { + break + } + + return e.complexity.Todo.Text(childComplexity), true + + case "Todo.value": + if e.complexity.Todo.Value == nil { + break + } + + return e.complexity.Todo.Value(childComplexity), true + + case "TodoConnection.edges": + if e.complexity.TodoConnection.Edges == nil { + break + } + + return e.complexity.TodoConnection.Edges(childComplexity), true + + case "TodoConnection.pageInfo": + if e.complexity.TodoConnection.PageInfo == nil { + break + } + + return e.complexity.TodoConnection.PageInfo(childComplexity), true + + case "TodoConnection.totalCount": + if e.complexity.TodoConnection.TotalCount == nil { + break + } + + return e.complexity.TodoConnection.TotalCount(childComplexity), true + + case "TodoEdge.cursor": + if e.complexity.TodoEdge.Cursor == nil { + break + } + + return e.complexity.TodoEdge.Cursor(childComplexity), true + + case "TodoEdge.node": + if e.complexity.TodoEdge.Node == nil { + break + } + + return e.complexity.TodoEdge.Node(childComplexity), true + + case "User.friends": + if e.complexity.User.Friends == nil { + break + } + + args, err := ec.field_User_friends_args(context.TODO(), rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.User.Friends(childComplexity, args["after"].(*entgql.Cursor[int]), args["first"].(*int), args["before"].(*entgql.Cursor[int]), args["last"].(*int), args["orderBy"].(*ent.UserOrder), args["where"].(*ent.UserWhereInput)), true + + case "User.friendships": + if e.complexity.User.Friendships == nil { + break + } + + args, err := ec.field_User_friendships_args(context.TODO(), rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.User.Friendships(childComplexity, args["after"].(*entgql.Cursor[int]), args["first"].(*int), args["before"].(*entgql.Cursor[int]), args["last"].(*int), args["where"].(*ent.FriendshipWhereInput)), true + + case "User.groups": + if e.complexity.User.Groups == nil { + break + } + + args, err := ec.field_User_groups_args(context.TODO(), rawArgs) + if err != nil { + return 0, false + } + + return e.complexity.User.Groups(childComplexity, args["after"].(*entgql.Cursor[int]), args["first"].(*int), args["before"].(*entgql.Cursor[int]), args["last"].(*int), args["where"].(*ent.GroupWhereInput)), true + + case "User.id": + if e.complexity.User.ID == nil { + break + } + + return e.complexity.User.ID(childComplexity), true + + case "User.metadata": + if e.complexity.User.Metadata == nil { + break + } + + return e.complexity.User.Metadata(childComplexity), true + + case "User.name": + if e.complexity.User.Name == nil { + break + } + + return e.complexity.User.Name(childComplexity), true + + case "User.requiredMetadata": + if e.complexity.User.RequiredMetadata == nil { + break + } + + return e.complexity.User.RequiredMetadata(childComplexity), true + + case "User.username": + if e.complexity.User.Username == nil { + break + } + + return e.complexity.User.Username(childComplexity), true + + case "UserConnection.edges": + if e.complexity.UserConnection.Edges == nil { + break + } + + return e.complexity.UserConnection.Edges(childComplexity), true + + case "UserConnection.pageInfo": + if e.complexity.UserConnection.PageInfo == nil { + break + } + + return e.complexity.UserConnection.PageInfo(childComplexity), true + + case "UserConnection.totalCount": + if e.complexity.UserConnection.TotalCount == nil { + break + } + + return e.complexity.UserConnection.TotalCount(childComplexity), true + + case "UserEdge.cursor": + if e.complexity.UserEdge.Cursor == nil { + break + } + + return e.complexity.UserEdge.Cursor(childComplexity), true + + case "UserEdge.node": + if e.complexity.UserEdge.Node == nil { + break + } + + return e.complexity.UserEdge.Node(childComplexity), true + + } + return 0, false +} + +func (e *executableSchema) Exec(ctx context.Context) graphql.ResponseHandler { + opCtx := graphql.GetOperationContext(ctx) + ec := executionContext{opCtx, e, 0, 0, make(chan graphql.DeferredResult)} + inputUnmarshalMap := graphql.BuildUnmarshalerMap( + ec.unmarshalInputBillProductWhereInput, + ec.unmarshalInputCategoryConfigInput, + ec.unmarshalInputCategoryOrder, + ec.unmarshalInputCategoryTypesInput, + ec.unmarshalInputCategoryWhereInput, + ec.unmarshalInputCreateCategoryInput, + ec.unmarshalInputCreateTodoInput, + ec.unmarshalInputCreateUserInput, + ec.unmarshalInputFriendshipWhereInput, + ec.unmarshalInputGroupWhereInput, + ec.unmarshalInputOneToManyOrder, + ec.unmarshalInputOneToManyWhereInput, + ec.unmarshalInputOrganizationWhereInput, + ec.unmarshalInputProjectWhereInput, + ec.unmarshalInputTodoOrder, + ec.unmarshalInputTodoWhereInput, + ec.unmarshalInputUpdateCategoryInput, + ec.unmarshalInputUpdateFriendshipInput, + ec.unmarshalInputUpdateTodoInput, + ec.unmarshalInputUpdateUserInput, + ec.unmarshalInputUserOrder, + ec.unmarshalInputUserWhereInput, + ) + first := true + + switch opCtx.Operation.Operation { + case ast.Query: + return func(ctx context.Context) *graphql.Response { + var response graphql.Response + var data graphql.Marshaler + if first { + first = false + ctx = graphql.WithUnmarshalerMap(ctx, inputUnmarshalMap) + data = ec._Query(ctx, opCtx.Operation.SelectionSet) + } else { + if atomic.LoadInt32(&ec.pendingDeferred) > 0 { + result := <-ec.deferredResults + atomic.AddInt32(&ec.pendingDeferred, -1) + data = result.Result + response.Path = result.Path + response.Label = result.Label + response.Errors = result.Errors + } else { + return nil + } + } + var buf bytes.Buffer + data.MarshalGQL(&buf) + response.Data = buf.Bytes() + if atomic.LoadInt32(&ec.deferred) > 0 { + hasNext := atomic.LoadInt32(&ec.pendingDeferred) > 0 + response.HasNext = &hasNext + } + + return &response + } + case ast.Mutation: + return func(ctx context.Context) *graphql.Response { + if !first { + return nil + } + first = false + ctx = graphql.WithUnmarshalerMap(ctx, inputUnmarshalMap) + data := ec._Mutation(ctx, opCtx.Operation.SelectionSet) + var buf bytes.Buffer + data.MarshalGQL(&buf) + + return &graphql.Response{ + Data: buf.Bytes(), + } + } + + default: + return graphql.OneShot(graphql.ErrorResponse(ctx, "unsupported GraphQL operation")) + } +} + +type executionContext struct { + *graphql.OperationContext + *executableSchema + deferred int32 + pendingDeferred int32 + deferredResults chan graphql.DeferredResult +} + +func (ec *executionContext) processDeferredGroup(dg graphql.DeferredGroup) { + atomic.AddInt32(&ec.pendingDeferred, 1) + go func() { + ctx := graphql.WithFreshResponseContext(dg.Context) + dg.FieldSet.Dispatch(ctx) + ds := graphql.DeferredResult{ + Path: dg.Path, + Label: dg.Label, + Result: dg.FieldSet, + Errors: graphql.GetErrors(ctx), + } + // null fields should bubble up + if dg.FieldSet.Invalids > 0 { + ds.Result = graphql.Null + } + ec.deferredResults <- ds + }() +} + +func (ec *executionContext) introspectSchema() (*introspection.Schema, error) { + if ec.DisableIntrospection { + return nil, errors.New("introspection disabled") + } + return introspection.WrapSchema(ec.Schema()), nil +} + +func (ec *executionContext) introspectType(name string) (*introspection.Type, error) { + if ec.DisableIntrospection { + return nil, errors.New("introspection disabled") + } + return introspection.WrapTypeFromDef(ec.Schema(), ec.Schema().Types[name]), nil +} + +//go:embed "todo.graphql" "ent.graphql" +var sourcesFS embed.FS + +func sourceData(filename string) string { + data, err := sourcesFS.ReadFile(filename) + if err != nil { + panic(fmt.Sprintf("codegen problem: %s not available", filename)) + } + return string(data) +} + +var sources = []*ast.Source{ + {Name: "todo.graphql", Input: sourceData("todo.graphql"), BuiltIn: false}, + {Name: "ent.graphql", Input: sourceData("ent.graphql"), BuiltIn: false}, +} +var parsedSchema = gqlparser.MustLoadSchema(sources...) + +// endregion ************************** generated!.gotpl ************************** + +// region ***************************** args.gotpl ***************************** + +func (ec *executionContext) dir_hasPermissions_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := ec.dir_hasPermissions_argsPermissions(ctx, rawArgs) + if err != nil { + return nil, err + } + args["permissions"] = arg0 + return args, nil +} +func (ec *executionContext) dir_hasPermissions_argsPermissions( + ctx context.Context, + rawArgs map[string]any, +) ([]string, error) { + if _, ok := rawArgs["permissions"]; !ok { + var zeroVal []string + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("permissions")) + if tmp, ok := rawArgs["permissions"]; ok { + return ec.unmarshalNString2ᚕstringᚄ(ctx, tmp) + } + + var zeroVal []string + return zeroVal, nil +} + +func (ec *executionContext) field_Category_subCategories_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := ec.field_Category_subCategories_argsAfter(ctx, rawArgs) + if err != nil { + return nil, err + } + args["after"] = arg0 + arg1, err := ec.field_Category_subCategories_argsFirst(ctx, rawArgs) + if err != nil { + return nil, err + } + args["first"] = arg1 + arg2, err := ec.field_Category_subCategories_argsBefore(ctx, rawArgs) + if err != nil { + return nil, err + } + args["before"] = arg2 + arg3, err := ec.field_Category_subCategories_argsLast(ctx, rawArgs) + if err != nil { + return nil, err + } + args["last"] = arg3 + arg4, err := ec.field_Category_subCategories_argsOrderBy(ctx, rawArgs) + if err != nil { + return nil, err + } + args["orderBy"] = arg4 + arg5, err := ec.field_Category_subCategories_argsWhere(ctx, rawArgs) + if err != nil { + return nil, err + } + args["where"] = arg5 + return args, nil +} +func (ec *executionContext) field_Category_subCategories_argsAfter( + ctx context.Context, + rawArgs map[string]any, +) (*entgql.Cursor[int], error) { + if _, ok := rawArgs["after"]; !ok { + var zeroVal *entgql.Cursor[int] + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("after")) + if tmp, ok := rawArgs["after"]; ok { + return ec.unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, tmp) + } + + var zeroVal *entgql.Cursor[int] + return zeroVal, nil +} + +func (ec *executionContext) field_Category_subCategories_argsFirst( + ctx context.Context, + rawArgs map[string]any, +) (*int, error) { + if _, ok := rawArgs["first"]; !ok { + var zeroVal *int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("first")) + if tmp, ok := rawArgs["first"]; ok { + return ec.unmarshalOInt2ᚖint(ctx, tmp) + } + + var zeroVal *int + return zeroVal, nil +} + +func (ec *executionContext) field_Category_subCategories_argsBefore( + ctx context.Context, + rawArgs map[string]any, +) (*entgql.Cursor[int], error) { + if _, ok := rawArgs["before"]; !ok { + var zeroVal *entgql.Cursor[int] + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("before")) + if tmp, ok := rawArgs["before"]; ok { + return ec.unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, tmp) + } + + var zeroVal *entgql.Cursor[int] + return zeroVal, nil +} + +func (ec *executionContext) field_Category_subCategories_argsLast( + ctx context.Context, + rawArgs map[string]any, +) (*int, error) { + if _, ok := rawArgs["last"]; !ok { + var zeroVal *int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("last")) + if tmp, ok := rawArgs["last"]; ok { + return ec.unmarshalOInt2ᚖint(ctx, tmp) + } + + var zeroVal *int + return zeroVal, nil +} + +func (ec *executionContext) field_Category_subCategories_argsOrderBy( + ctx context.Context, + rawArgs map[string]any, +) ([]*ent.CategoryOrder, error) { + if _, ok := rawArgs["orderBy"]; !ok { + var zeroVal []*ent.CategoryOrder + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("orderBy")) + if tmp, ok := rawArgs["orderBy"]; ok { + return ec.unmarshalOCategoryOrder2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategoryOrderᚄ(ctx, tmp) + } + + var zeroVal []*ent.CategoryOrder + return zeroVal, nil +} + +func (ec *executionContext) field_Category_subCategories_argsWhere( + ctx context.Context, + rawArgs map[string]any, +) (*ent.CategoryWhereInput, error) { + if _, ok := rawArgs["where"]; !ok { + var zeroVal *ent.CategoryWhereInput + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("where")) + if tmp, ok := rawArgs["where"]; ok { + return ec.unmarshalOCategoryWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategoryWhereInput(ctx, tmp) + } + + var zeroVal *ent.CategoryWhereInput + return zeroVal, nil +} + +func (ec *executionContext) field_Category_todos_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := ec.field_Category_todos_argsAfter(ctx, rawArgs) + if err != nil { + return nil, err + } + args["after"] = arg0 + arg1, err := ec.field_Category_todos_argsFirst(ctx, rawArgs) + if err != nil { + return nil, err + } + args["first"] = arg1 + arg2, err := ec.field_Category_todos_argsBefore(ctx, rawArgs) + if err != nil { + return nil, err + } + args["before"] = arg2 + arg3, err := ec.field_Category_todos_argsLast(ctx, rawArgs) + if err != nil { + return nil, err + } + args["last"] = arg3 + arg4, err := ec.field_Category_todos_argsOrderBy(ctx, rawArgs) + if err != nil { + return nil, err + } + args["orderBy"] = arg4 + arg5, err := ec.field_Category_todos_argsWhere(ctx, rawArgs) + if err != nil { + return nil, err + } + args["where"] = arg5 + return args, nil +} +func (ec *executionContext) field_Category_todos_argsAfter( + ctx context.Context, + rawArgs map[string]any, +) (*entgql.Cursor[int], error) { + if _, ok := rawArgs["after"]; !ok { + var zeroVal *entgql.Cursor[int] + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("after")) + if tmp, ok := rawArgs["after"]; ok { + return ec.unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, tmp) + } + + var zeroVal *entgql.Cursor[int] + return zeroVal, nil +} + +func (ec *executionContext) field_Category_todos_argsFirst( + ctx context.Context, + rawArgs map[string]any, +) (*int, error) { + if _, ok := rawArgs["first"]; !ok { + var zeroVal *int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("first")) + if tmp, ok := rawArgs["first"]; ok { + return ec.unmarshalOInt2ᚖint(ctx, tmp) + } + + var zeroVal *int + return zeroVal, nil +} + +func (ec *executionContext) field_Category_todos_argsBefore( + ctx context.Context, + rawArgs map[string]any, +) (*entgql.Cursor[int], error) { + if _, ok := rawArgs["before"]; !ok { + var zeroVal *entgql.Cursor[int] + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("before")) + if tmp, ok := rawArgs["before"]; ok { + return ec.unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, tmp) + } + + var zeroVal *entgql.Cursor[int] + return zeroVal, nil +} + +func (ec *executionContext) field_Category_todos_argsLast( + ctx context.Context, + rawArgs map[string]any, +) (*int, error) { + if _, ok := rawArgs["last"]; !ok { + var zeroVal *int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("last")) + if tmp, ok := rawArgs["last"]; ok { + return ec.unmarshalOInt2ᚖint(ctx, tmp) + } + + var zeroVal *int + return zeroVal, nil +} + +func (ec *executionContext) field_Category_todos_argsOrderBy( + ctx context.Context, + rawArgs map[string]any, +) ([]*ent.TodoOrder, error) { + if _, ok := rawArgs["orderBy"]; !ok { + var zeroVal []*ent.TodoOrder + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("orderBy")) + if tmp, ok := rawArgs["orderBy"]; ok { + return ec.unmarshalOTodoOrder2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoOrderᚄ(ctx, tmp) + } + + var zeroVal []*ent.TodoOrder + return zeroVal, nil +} + +func (ec *executionContext) field_Category_todos_argsWhere( + ctx context.Context, + rawArgs map[string]any, +) (*ent.TodoWhereInput, error) { + if _, ok := rawArgs["where"]; !ok { + var zeroVal *ent.TodoWhereInput + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("where")) + if tmp, ok := rawArgs["where"]; ok { + return ec.unmarshalOTodoWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoWhereInput(ctx, tmp) + } + + var zeroVal *ent.TodoWhereInput + return zeroVal, nil +} + +func (ec *executionContext) field_Group_users_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := ec.field_Group_users_argsAfter(ctx, rawArgs) + if err != nil { + return nil, err + } + args["after"] = arg0 + arg1, err := ec.field_Group_users_argsFirst(ctx, rawArgs) + if err != nil { + return nil, err + } + args["first"] = arg1 + arg2, err := ec.field_Group_users_argsBefore(ctx, rawArgs) + if err != nil { + return nil, err + } + args["before"] = arg2 + arg3, err := ec.field_Group_users_argsLast(ctx, rawArgs) + if err != nil { + return nil, err + } + args["last"] = arg3 + arg4, err := ec.field_Group_users_argsOrderBy(ctx, rawArgs) + if err != nil { + return nil, err + } + args["orderBy"] = arg4 + arg5, err := ec.field_Group_users_argsWhere(ctx, rawArgs) + if err != nil { + return nil, err + } + args["where"] = arg5 + return args, nil +} +func (ec *executionContext) field_Group_users_argsAfter( + ctx context.Context, + rawArgs map[string]any, +) (*entgql.Cursor[int], error) { + if _, ok := rawArgs["after"]; !ok { + var zeroVal *entgql.Cursor[int] + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("after")) + if tmp, ok := rawArgs["after"]; ok { + return ec.unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, tmp) + } + + var zeroVal *entgql.Cursor[int] + return zeroVal, nil +} + +func (ec *executionContext) field_Group_users_argsFirst( + ctx context.Context, + rawArgs map[string]any, +) (*int, error) { + if _, ok := rawArgs["first"]; !ok { + var zeroVal *int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("first")) + if tmp, ok := rawArgs["first"]; ok { + return ec.unmarshalOInt2ᚖint(ctx, tmp) + } + + var zeroVal *int + return zeroVal, nil +} + +func (ec *executionContext) field_Group_users_argsBefore( + ctx context.Context, + rawArgs map[string]any, +) (*entgql.Cursor[int], error) { + if _, ok := rawArgs["before"]; !ok { + var zeroVal *entgql.Cursor[int] + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("before")) + if tmp, ok := rawArgs["before"]; ok { + return ec.unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, tmp) + } + + var zeroVal *entgql.Cursor[int] + return zeroVal, nil +} + +func (ec *executionContext) field_Group_users_argsLast( + ctx context.Context, + rawArgs map[string]any, +) (*int, error) { + if _, ok := rawArgs["last"]; !ok { + var zeroVal *int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("last")) + if tmp, ok := rawArgs["last"]; ok { + return ec.unmarshalOInt2ᚖint(ctx, tmp) + } + + var zeroVal *int + return zeroVal, nil +} + +func (ec *executionContext) field_Group_users_argsOrderBy( + ctx context.Context, + rawArgs map[string]any, +) (*ent.UserOrder, error) { + if _, ok := rawArgs["orderBy"]; !ok { + var zeroVal *ent.UserOrder + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("orderBy")) + if tmp, ok := rawArgs["orderBy"]; ok { + return ec.unmarshalOUserOrder2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUserOrder(ctx, tmp) + } + + var zeroVal *ent.UserOrder + return zeroVal, nil +} + +func (ec *executionContext) field_Group_users_argsWhere( + ctx context.Context, + rawArgs map[string]any, +) (*ent.UserWhereInput, error) { + if _, ok := rawArgs["where"]; !ok { + var zeroVal *ent.UserWhereInput + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("where")) + if tmp, ok := rawArgs["where"]; ok { + return ec.unmarshalOUserWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUserWhereInput(ctx, tmp) + } + + var zeroVal *ent.UserWhereInput + return zeroVal, nil +} + +func (ec *executionContext) field_Mutation_createCategory_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := ec.field_Mutation_createCategory_argsInput(ctx, rawArgs) + if err != nil { + return nil, err + } + args["input"] = arg0 + return args, nil +} +func (ec *executionContext) field_Mutation_createCategory_argsInput( + ctx context.Context, + rawArgs map[string]any, +) (ent.CreateCategoryInput, error) { + if _, ok := rawArgs["input"]; !ok { + var zeroVal ent.CreateCategoryInput + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("input")) + if tmp, ok := rawArgs["input"]; ok { + return ec.unmarshalNCreateCategoryInput2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCreateCategoryInput(ctx, tmp) + } + + var zeroVal ent.CreateCategoryInput + return zeroVal, nil +} + +func (ec *executionContext) field_Mutation_createTodo_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := ec.field_Mutation_createTodo_argsInput(ctx, rawArgs) + if err != nil { + return nil, err + } + args["input"] = arg0 + return args, nil +} +func (ec *executionContext) field_Mutation_createTodo_argsInput( + ctx context.Context, + rawArgs map[string]any, +) (ent.CreateTodoInput, error) { + if _, ok := rawArgs["input"]; !ok { + var zeroVal ent.CreateTodoInput + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("input")) + if tmp, ok := rawArgs["input"]; ok { + return ec.unmarshalNCreateTodoInput2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCreateTodoInput(ctx, tmp) + } + + var zeroVal ent.CreateTodoInput + return zeroVal, nil +} + +func (ec *executionContext) field_Mutation_updateFriendship_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := ec.field_Mutation_updateFriendship_argsID(ctx, rawArgs) + if err != nil { + return nil, err + } + args["id"] = arg0 + arg1, err := ec.field_Mutation_updateFriendship_argsInput(ctx, rawArgs) + if err != nil { + return nil, err + } + args["input"] = arg1 + return args, nil +} +func (ec *executionContext) field_Mutation_updateFriendship_argsID( + ctx context.Context, + rawArgs map[string]any, +) (int, error) { + if _, ok := rawArgs["id"]; !ok { + var zeroVal int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) + if tmp, ok := rawArgs["id"]; ok { + return ec.unmarshalNID2int(ctx, tmp) + } + + var zeroVal int + return zeroVal, nil +} + +func (ec *executionContext) field_Mutation_updateFriendship_argsInput( + ctx context.Context, + rawArgs map[string]any, +) (ent.UpdateFriendshipInput, error) { + if _, ok := rawArgs["input"]; !ok { + var zeroVal ent.UpdateFriendshipInput + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("input")) + if tmp, ok := rawArgs["input"]; ok { + return ec.unmarshalNUpdateFriendshipInput2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUpdateFriendshipInput(ctx, tmp) + } + + var zeroVal ent.UpdateFriendshipInput + return zeroVal, nil +} + +func (ec *executionContext) field_Mutation_updateTodo_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := ec.field_Mutation_updateTodo_argsID(ctx, rawArgs) + if err != nil { + return nil, err + } + args["id"] = arg0 + arg1, err := ec.field_Mutation_updateTodo_argsInput(ctx, rawArgs) + if err != nil { + return nil, err + } + args["input"] = arg1 + return args, nil +} +func (ec *executionContext) field_Mutation_updateTodo_argsID( + ctx context.Context, + rawArgs map[string]any, +) (int, error) { + if _, ok := rawArgs["id"]; !ok { + var zeroVal int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) + if tmp, ok := rawArgs["id"]; ok { + return ec.unmarshalNID2int(ctx, tmp) + } + + var zeroVal int + return zeroVal, nil +} + +func (ec *executionContext) field_Mutation_updateTodo_argsInput( + ctx context.Context, + rawArgs map[string]any, +) (ent.UpdateTodoInput, error) { + if _, ok := rawArgs["input"]; !ok { + var zeroVal ent.UpdateTodoInput + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("input")) + if tmp, ok := rawArgs["input"]; ok { + return ec.unmarshalNUpdateTodoInput2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUpdateTodoInput(ctx, tmp) + } + + var zeroVal ent.UpdateTodoInput + return zeroVal, nil +} + +func (ec *executionContext) field_Project_todos_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := ec.field_Project_todos_argsAfter(ctx, rawArgs) + if err != nil { + return nil, err + } + args["after"] = arg0 + arg1, err := ec.field_Project_todos_argsFirst(ctx, rawArgs) + if err != nil { + return nil, err + } + args["first"] = arg1 + arg2, err := ec.field_Project_todos_argsBefore(ctx, rawArgs) + if err != nil { + return nil, err + } + args["before"] = arg2 + arg3, err := ec.field_Project_todos_argsLast(ctx, rawArgs) + if err != nil { + return nil, err + } + args["last"] = arg3 + arg4, err := ec.field_Project_todos_argsOrderBy(ctx, rawArgs) + if err != nil { + return nil, err + } + args["orderBy"] = arg4 + arg5, err := ec.field_Project_todos_argsWhere(ctx, rawArgs) + if err != nil { + return nil, err + } + args["where"] = arg5 + return args, nil +} +func (ec *executionContext) field_Project_todos_argsAfter( + ctx context.Context, + rawArgs map[string]any, +) (*entgql.Cursor[int], error) { + if _, ok := rawArgs["after"]; !ok { + var zeroVal *entgql.Cursor[int] + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("after")) + if tmp, ok := rawArgs["after"]; ok { + return ec.unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, tmp) + } + + var zeroVal *entgql.Cursor[int] + return zeroVal, nil +} + +func (ec *executionContext) field_Project_todos_argsFirst( + ctx context.Context, + rawArgs map[string]any, +) (*int, error) { + if _, ok := rawArgs["first"]; !ok { + var zeroVal *int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("first")) + if tmp, ok := rawArgs["first"]; ok { + return ec.unmarshalOInt2ᚖint(ctx, tmp) + } + + var zeroVal *int + return zeroVal, nil +} + +func (ec *executionContext) field_Project_todos_argsBefore( + ctx context.Context, + rawArgs map[string]any, +) (*entgql.Cursor[int], error) { + if _, ok := rawArgs["before"]; !ok { + var zeroVal *entgql.Cursor[int] + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("before")) + if tmp, ok := rawArgs["before"]; ok { + return ec.unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, tmp) + } + + var zeroVal *entgql.Cursor[int] + return zeroVal, nil +} + +func (ec *executionContext) field_Project_todos_argsLast( + ctx context.Context, + rawArgs map[string]any, +) (*int, error) { + if _, ok := rawArgs["last"]; !ok { + var zeroVal *int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("last")) + if tmp, ok := rawArgs["last"]; ok { + return ec.unmarshalOInt2ᚖint(ctx, tmp) + } + + var zeroVal *int + return zeroVal, nil +} + +func (ec *executionContext) field_Project_todos_argsOrderBy( + ctx context.Context, + rawArgs map[string]any, +) ([]*ent.TodoOrder, error) { + if _, ok := rawArgs["orderBy"]; !ok { + var zeroVal []*ent.TodoOrder + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("orderBy")) + if tmp, ok := rawArgs["orderBy"]; ok { + return ec.unmarshalOTodoOrder2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoOrderᚄ(ctx, tmp) + } + + var zeroVal []*ent.TodoOrder + return zeroVal, nil +} + +func (ec *executionContext) field_Project_todos_argsWhere( + ctx context.Context, + rawArgs map[string]any, +) (*ent.TodoWhereInput, error) { + if _, ok := rawArgs["where"]; !ok { + var zeroVal *ent.TodoWhereInput + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("where")) + if tmp, ok := rawArgs["where"]; ok { + return ec.unmarshalOTodoWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoWhereInput(ctx, tmp) + } + + var zeroVal *ent.TodoWhereInput + return zeroVal, nil +} + +func (ec *executionContext) field_Query___type_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := ec.field_Query___type_argsName(ctx, rawArgs) + if err != nil { + return nil, err + } + args["name"] = arg0 + return args, nil +} +func (ec *executionContext) field_Query___type_argsName( + ctx context.Context, + rawArgs map[string]any, +) (string, error) { + if _, ok := rawArgs["name"]; !ok { + var zeroVal string + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("name")) + if tmp, ok := rawArgs["name"]; ok { + return ec.unmarshalNString2string(ctx, tmp) + } + + var zeroVal string + return zeroVal, nil +} + +func (ec *executionContext) field_Query_categories_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := ec.field_Query_categories_argsAfter(ctx, rawArgs) + if err != nil { + return nil, err + } + args["after"] = arg0 + arg1, err := ec.field_Query_categories_argsFirst(ctx, rawArgs) + if err != nil { + return nil, err + } + args["first"] = arg1 + arg2, err := ec.field_Query_categories_argsBefore(ctx, rawArgs) + if err != nil { + return nil, err + } + args["before"] = arg2 + arg3, err := ec.field_Query_categories_argsLast(ctx, rawArgs) + if err != nil { + return nil, err + } + args["last"] = arg3 + arg4, err := ec.field_Query_categories_argsOrderBy(ctx, rawArgs) + if err != nil { + return nil, err + } + args["orderBy"] = arg4 + arg5, err := ec.field_Query_categories_argsWhere(ctx, rawArgs) + if err != nil { + return nil, err + } + args["where"] = arg5 + return args, nil +} +func (ec *executionContext) field_Query_categories_argsAfter( + ctx context.Context, + rawArgs map[string]any, +) (*entgql.Cursor[int], error) { + if _, ok := rawArgs["after"]; !ok { + var zeroVal *entgql.Cursor[int] + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("after")) + if tmp, ok := rawArgs["after"]; ok { + return ec.unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, tmp) + } + + var zeroVal *entgql.Cursor[int] + return zeroVal, nil +} + +func (ec *executionContext) field_Query_categories_argsFirst( + ctx context.Context, + rawArgs map[string]any, +) (*int, error) { + if _, ok := rawArgs["first"]; !ok { + var zeroVal *int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("first")) + if tmp, ok := rawArgs["first"]; ok { + return ec.unmarshalOInt2ᚖint(ctx, tmp) + } + + var zeroVal *int + return zeroVal, nil +} + +func (ec *executionContext) field_Query_categories_argsBefore( + ctx context.Context, + rawArgs map[string]any, +) (*entgql.Cursor[int], error) { + if _, ok := rawArgs["before"]; !ok { + var zeroVal *entgql.Cursor[int] + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("before")) + if tmp, ok := rawArgs["before"]; ok { + return ec.unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, tmp) + } + + var zeroVal *entgql.Cursor[int] + return zeroVal, nil +} + +func (ec *executionContext) field_Query_categories_argsLast( + ctx context.Context, + rawArgs map[string]any, +) (*int, error) { + if _, ok := rawArgs["last"]; !ok { + var zeroVal *int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("last")) + if tmp, ok := rawArgs["last"]; ok { + return ec.unmarshalOInt2ᚖint(ctx, tmp) + } + + var zeroVal *int + return zeroVal, nil +} + +func (ec *executionContext) field_Query_categories_argsOrderBy( + ctx context.Context, + rawArgs map[string]any, +) ([]*ent.CategoryOrder, error) { + if _, ok := rawArgs["orderBy"]; !ok { + var zeroVal []*ent.CategoryOrder + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("orderBy")) + if tmp, ok := rawArgs["orderBy"]; ok { + return ec.unmarshalOCategoryOrder2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategoryOrderᚄ(ctx, tmp) + } + + var zeroVal []*ent.CategoryOrder + return zeroVal, nil +} + +func (ec *executionContext) field_Query_categories_argsWhere( + ctx context.Context, + rawArgs map[string]any, +) (*ent.CategoryWhereInput, error) { + if _, ok := rawArgs["where"]; !ok { + var zeroVal *ent.CategoryWhereInput + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("where")) + if tmp, ok := rawArgs["where"]; ok { + return ec.unmarshalOCategoryWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategoryWhereInput(ctx, tmp) + } + + var zeroVal *ent.CategoryWhereInput + return zeroVal, nil +} + +func (ec *executionContext) field_Query_groups_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := ec.field_Query_groups_argsAfter(ctx, rawArgs) + if err != nil { + return nil, err + } + args["after"] = arg0 + arg1, err := ec.field_Query_groups_argsFirst(ctx, rawArgs) + if err != nil { + return nil, err + } + args["first"] = arg1 + arg2, err := ec.field_Query_groups_argsBefore(ctx, rawArgs) + if err != nil { + return nil, err + } + args["before"] = arg2 + arg3, err := ec.field_Query_groups_argsLast(ctx, rawArgs) + if err != nil { + return nil, err + } + args["last"] = arg3 + arg4, err := ec.field_Query_groups_argsWhere(ctx, rawArgs) + if err != nil { + return nil, err + } + args["where"] = arg4 + return args, nil +} +func (ec *executionContext) field_Query_groups_argsAfter( + ctx context.Context, + rawArgs map[string]any, +) (*entgql.Cursor[int], error) { + if _, ok := rawArgs["after"]; !ok { + var zeroVal *entgql.Cursor[int] + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("after")) + if tmp, ok := rawArgs["after"]; ok { + return ec.unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, tmp) + } + + var zeroVal *entgql.Cursor[int] + return zeroVal, nil +} + +func (ec *executionContext) field_Query_groups_argsFirst( + ctx context.Context, + rawArgs map[string]any, +) (*int, error) { + if _, ok := rawArgs["first"]; !ok { + var zeroVal *int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("first")) + if tmp, ok := rawArgs["first"]; ok { + return ec.unmarshalOInt2ᚖint(ctx, tmp) + } + + var zeroVal *int + return zeroVal, nil +} + +func (ec *executionContext) field_Query_groups_argsBefore( + ctx context.Context, + rawArgs map[string]any, +) (*entgql.Cursor[int], error) { + if _, ok := rawArgs["before"]; !ok { + var zeroVal *entgql.Cursor[int] + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("before")) + if tmp, ok := rawArgs["before"]; ok { + return ec.unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, tmp) + } + + var zeroVal *entgql.Cursor[int] + return zeroVal, nil +} + +func (ec *executionContext) field_Query_groups_argsLast( + ctx context.Context, + rawArgs map[string]any, +) (*int, error) { + if _, ok := rawArgs["last"]; !ok { + var zeroVal *int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("last")) + if tmp, ok := rawArgs["last"]; ok { + return ec.unmarshalOInt2ᚖint(ctx, tmp) + } + + var zeroVal *int + return zeroVal, nil +} + +func (ec *executionContext) field_Query_groups_argsWhere( + ctx context.Context, + rawArgs map[string]any, +) (*ent.GroupWhereInput, error) { + if _, ok := rawArgs["where"]; !ok { + var zeroVal *ent.GroupWhereInput + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("where")) + if tmp, ok := rawArgs["where"]; ok { + return ec.unmarshalOGroupWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐGroupWhereInput(ctx, tmp) + } + + var zeroVal *ent.GroupWhereInput + return zeroVal, nil +} + +func (ec *executionContext) field_Query_node_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := ec.field_Query_node_argsID(ctx, rawArgs) + if err != nil { + return nil, err + } + args["id"] = arg0 + return args, nil +} +func (ec *executionContext) field_Query_node_argsID( + ctx context.Context, + rawArgs map[string]any, +) (int, error) { + if _, ok := rawArgs["id"]; !ok { + var zeroVal int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) + if tmp, ok := rawArgs["id"]; ok { + return ec.unmarshalNID2int(ctx, tmp) + } + + var zeroVal int + return zeroVal, nil +} + +func (ec *executionContext) field_Query_nodes_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := ec.field_Query_nodes_argsIds(ctx, rawArgs) + if err != nil { + return nil, err + } + args["ids"] = arg0 + return args, nil +} +func (ec *executionContext) field_Query_nodes_argsIds( + ctx context.Context, + rawArgs map[string]any, +) ([]int, error) { + if _, ok := rawArgs["ids"]; !ok { + var zeroVal []int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("ids")) + if tmp, ok := rawArgs["ids"]; ok { + return ec.unmarshalNID2ᚕintᚄ(ctx, tmp) + } + + var zeroVal []int + return zeroVal, nil +} + +func (ec *executionContext) field_Query_oneToMany_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := ec.field_Query_oneToMany_argsAfter(ctx, rawArgs) + if err != nil { + return nil, err + } + args["after"] = arg0 + arg1, err := ec.field_Query_oneToMany_argsFirst(ctx, rawArgs) + if err != nil { + return nil, err + } + args["first"] = arg1 + arg2, err := ec.field_Query_oneToMany_argsBefore(ctx, rawArgs) + if err != nil { + return nil, err + } + args["before"] = arg2 + arg3, err := ec.field_Query_oneToMany_argsLast(ctx, rawArgs) + if err != nil { + return nil, err + } + args["last"] = arg3 + arg4, err := ec.field_Query_oneToMany_argsOrderBy(ctx, rawArgs) + if err != nil { + return nil, err + } + args["orderBy"] = arg4 + arg5, err := ec.field_Query_oneToMany_argsWhere(ctx, rawArgs) + if err != nil { + return nil, err + } + args["where"] = arg5 + return args, nil +} +func (ec *executionContext) field_Query_oneToMany_argsAfter( + ctx context.Context, + rawArgs map[string]any, +) (*entgql.Cursor[int], error) { + if _, ok := rawArgs["after"]; !ok { + var zeroVal *entgql.Cursor[int] + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("after")) + if tmp, ok := rawArgs["after"]; ok { + return ec.unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, tmp) + } + + var zeroVal *entgql.Cursor[int] + return zeroVal, nil +} + +func (ec *executionContext) field_Query_oneToMany_argsFirst( + ctx context.Context, + rawArgs map[string]any, +) (*int, error) { + if _, ok := rawArgs["first"]; !ok { + var zeroVal *int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("first")) + if tmp, ok := rawArgs["first"]; ok { + return ec.unmarshalOInt2ᚖint(ctx, tmp) + } + + var zeroVal *int + return zeroVal, nil +} + +func (ec *executionContext) field_Query_oneToMany_argsBefore( + ctx context.Context, + rawArgs map[string]any, +) (*entgql.Cursor[int], error) { + if _, ok := rawArgs["before"]; !ok { + var zeroVal *entgql.Cursor[int] + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("before")) + if tmp, ok := rawArgs["before"]; ok { + return ec.unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, tmp) + } + + var zeroVal *entgql.Cursor[int] + return zeroVal, nil +} + +func (ec *executionContext) field_Query_oneToMany_argsLast( + ctx context.Context, + rawArgs map[string]any, +) (*int, error) { + if _, ok := rawArgs["last"]; !ok { + var zeroVal *int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("last")) + if tmp, ok := rawArgs["last"]; ok { + return ec.unmarshalOInt2ᚖint(ctx, tmp) + } + + var zeroVal *int + return zeroVal, nil +} + +func (ec *executionContext) field_Query_oneToMany_argsOrderBy( + ctx context.Context, + rawArgs map[string]any, +) (*ent.OneToManyOrder, error) { + if _, ok := rawArgs["orderBy"]; !ok { + var zeroVal *ent.OneToManyOrder + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("orderBy")) + if tmp, ok := rawArgs["orderBy"]; ok { + return ec.unmarshalOOneToManyOrder2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToManyOrder(ctx, tmp) + } + + var zeroVal *ent.OneToManyOrder + return zeroVal, nil +} + +func (ec *executionContext) field_Query_oneToMany_argsWhere( + ctx context.Context, + rawArgs map[string]any, +) (*ent.OneToManyWhereInput, error) { + if _, ok := rawArgs["where"]; !ok { + var zeroVal *ent.OneToManyWhereInput + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("where")) + if tmp, ok := rawArgs["where"]; ok { + return ec.unmarshalOOneToManyWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToManyWhereInput(ctx, tmp) + } + + var zeroVal *ent.OneToManyWhereInput + return zeroVal, nil +} + +func (ec *executionContext) field_Query_todosWithJoins_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := ec.field_Query_todosWithJoins_argsAfter(ctx, rawArgs) + if err != nil { + return nil, err + } + args["after"] = arg0 + arg1, err := ec.field_Query_todosWithJoins_argsFirst(ctx, rawArgs) + if err != nil { + return nil, err + } + args["first"] = arg1 + arg2, err := ec.field_Query_todosWithJoins_argsBefore(ctx, rawArgs) + if err != nil { + return nil, err + } + args["before"] = arg2 + arg3, err := ec.field_Query_todosWithJoins_argsLast(ctx, rawArgs) + if err != nil { + return nil, err + } + args["last"] = arg3 + arg4, err := ec.field_Query_todosWithJoins_argsOrderBy(ctx, rawArgs) + if err != nil { + return nil, err + } + args["orderBy"] = arg4 + arg5, err := ec.field_Query_todosWithJoins_argsWhere(ctx, rawArgs) + if err != nil { + return nil, err + } + args["where"] = arg5 + return args, nil +} +func (ec *executionContext) field_Query_todosWithJoins_argsAfter( + ctx context.Context, + rawArgs map[string]any, +) (*entgql.Cursor[int], error) { + if _, ok := rawArgs["after"]; !ok { + var zeroVal *entgql.Cursor[int] + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("after")) + if tmp, ok := rawArgs["after"]; ok { + return ec.unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, tmp) + } + + var zeroVal *entgql.Cursor[int] + return zeroVal, nil +} + +func (ec *executionContext) field_Query_todosWithJoins_argsFirst( + ctx context.Context, + rawArgs map[string]any, +) (*int, error) { + if _, ok := rawArgs["first"]; !ok { + var zeroVal *int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("first")) + if tmp, ok := rawArgs["first"]; ok { + return ec.unmarshalOInt2ᚖint(ctx, tmp) + } + + var zeroVal *int + return zeroVal, nil +} + +func (ec *executionContext) field_Query_todosWithJoins_argsBefore( + ctx context.Context, + rawArgs map[string]any, +) (*entgql.Cursor[int], error) { + if _, ok := rawArgs["before"]; !ok { + var zeroVal *entgql.Cursor[int] + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("before")) + if tmp, ok := rawArgs["before"]; ok { + return ec.unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, tmp) + } + + var zeroVal *entgql.Cursor[int] + return zeroVal, nil +} + +func (ec *executionContext) field_Query_todosWithJoins_argsLast( + ctx context.Context, + rawArgs map[string]any, +) (*int, error) { + if _, ok := rawArgs["last"]; !ok { + var zeroVal *int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("last")) + if tmp, ok := rawArgs["last"]; ok { + return ec.unmarshalOInt2ᚖint(ctx, tmp) + } + + var zeroVal *int + return zeroVal, nil +} + +func (ec *executionContext) field_Query_todosWithJoins_argsOrderBy( + ctx context.Context, + rawArgs map[string]any, +) ([]*ent.TodoOrder, error) { + if _, ok := rawArgs["orderBy"]; !ok { + var zeroVal []*ent.TodoOrder + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("orderBy")) + if tmp, ok := rawArgs["orderBy"]; ok { + return ec.unmarshalOTodoOrder2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoOrderᚄ(ctx, tmp) + } + + var zeroVal []*ent.TodoOrder + return zeroVal, nil +} + +func (ec *executionContext) field_Query_todosWithJoins_argsWhere( + ctx context.Context, + rawArgs map[string]any, +) (*ent.TodoWhereInput, error) { + if _, ok := rawArgs["where"]; !ok { + var zeroVal *ent.TodoWhereInput + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("where")) + if tmp, ok := rawArgs["where"]; ok { + return ec.unmarshalOTodoWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoWhereInput(ctx, tmp) + } + + var zeroVal *ent.TodoWhereInput + return zeroVal, nil +} + +func (ec *executionContext) field_Query_todos_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := ec.field_Query_todos_argsAfter(ctx, rawArgs) + if err != nil { + return nil, err + } + args["after"] = arg0 + arg1, err := ec.field_Query_todos_argsFirst(ctx, rawArgs) + if err != nil { + return nil, err + } + args["first"] = arg1 + arg2, err := ec.field_Query_todos_argsBefore(ctx, rawArgs) + if err != nil { + return nil, err + } + args["before"] = arg2 + arg3, err := ec.field_Query_todos_argsLast(ctx, rawArgs) + if err != nil { + return nil, err + } + args["last"] = arg3 + arg4, err := ec.field_Query_todos_argsOrderBy(ctx, rawArgs) + if err != nil { + return nil, err + } + args["orderBy"] = arg4 + arg5, err := ec.field_Query_todos_argsWhere(ctx, rawArgs) + if err != nil { + return nil, err + } + args["where"] = arg5 + return args, nil +} +func (ec *executionContext) field_Query_todos_argsAfter( + ctx context.Context, + rawArgs map[string]any, +) (*entgql.Cursor[int], error) { + if _, ok := rawArgs["after"]; !ok { + var zeroVal *entgql.Cursor[int] + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("after")) + if tmp, ok := rawArgs["after"]; ok { + return ec.unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, tmp) + } + + var zeroVal *entgql.Cursor[int] + return zeroVal, nil +} + +func (ec *executionContext) field_Query_todos_argsFirst( + ctx context.Context, + rawArgs map[string]any, +) (*int, error) { + if _, ok := rawArgs["first"]; !ok { + var zeroVal *int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("first")) + if tmp, ok := rawArgs["first"]; ok { + return ec.unmarshalOInt2ᚖint(ctx, tmp) + } + + var zeroVal *int + return zeroVal, nil +} + +func (ec *executionContext) field_Query_todos_argsBefore( + ctx context.Context, + rawArgs map[string]any, +) (*entgql.Cursor[int], error) { + if _, ok := rawArgs["before"]; !ok { + var zeroVal *entgql.Cursor[int] + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("before")) + if tmp, ok := rawArgs["before"]; ok { + return ec.unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, tmp) + } + + var zeroVal *entgql.Cursor[int] + return zeroVal, nil +} + +func (ec *executionContext) field_Query_todos_argsLast( + ctx context.Context, + rawArgs map[string]any, +) (*int, error) { + if _, ok := rawArgs["last"]; !ok { + var zeroVal *int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("last")) + if tmp, ok := rawArgs["last"]; ok { + return ec.unmarshalOInt2ᚖint(ctx, tmp) + } + + var zeroVal *int + return zeroVal, nil +} + +func (ec *executionContext) field_Query_todos_argsOrderBy( + ctx context.Context, + rawArgs map[string]any, +) ([]*ent.TodoOrder, error) { + if _, ok := rawArgs["orderBy"]; !ok { + var zeroVal []*ent.TodoOrder + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("orderBy")) + if tmp, ok := rawArgs["orderBy"]; ok { + return ec.unmarshalOTodoOrder2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoOrderᚄ(ctx, tmp) + } + + var zeroVal []*ent.TodoOrder + return zeroVal, nil +} + +func (ec *executionContext) field_Query_todos_argsWhere( + ctx context.Context, + rawArgs map[string]any, +) (*ent.TodoWhereInput, error) { + if _, ok := rawArgs["where"]; !ok { + var zeroVal *ent.TodoWhereInput + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("where")) + if tmp, ok := rawArgs["where"]; ok { + return ec.unmarshalOTodoWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoWhereInput(ctx, tmp) + } + + var zeroVal *ent.TodoWhereInput + return zeroVal, nil +} + +func (ec *executionContext) field_Query_users_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := ec.field_Query_users_argsAfter(ctx, rawArgs) + if err != nil { + return nil, err + } + args["after"] = arg0 + arg1, err := ec.field_Query_users_argsFirst(ctx, rawArgs) + if err != nil { + return nil, err + } + args["first"] = arg1 + arg2, err := ec.field_Query_users_argsBefore(ctx, rawArgs) + if err != nil { + return nil, err + } + args["before"] = arg2 + arg3, err := ec.field_Query_users_argsLast(ctx, rawArgs) + if err != nil { + return nil, err + } + args["last"] = arg3 + arg4, err := ec.field_Query_users_argsOrderBy(ctx, rawArgs) + if err != nil { + return nil, err + } + args["orderBy"] = arg4 + arg5, err := ec.field_Query_users_argsWhere(ctx, rawArgs) + if err != nil { + return nil, err + } + args["where"] = arg5 + return args, nil +} +func (ec *executionContext) field_Query_users_argsAfter( + ctx context.Context, + rawArgs map[string]any, +) (*entgql.Cursor[int], error) { + if _, ok := rawArgs["after"]; !ok { + var zeroVal *entgql.Cursor[int] + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("after")) + if tmp, ok := rawArgs["after"]; ok { + return ec.unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, tmp) + } + + var zeroVal *entgql.Cursor[int] + return zeroVal, nil +} + +func (ec *executionContext) field_Query_users_argsFirst( + ctx context.Context, + rawArgs map[string]any, +) (*int, error) { + if _, ok := rawArgs["first"]; !ok { + var zeroVal *int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("first")) + if tmp, ok := rawArgs["first"]; ok { + return ec.unmarshalOInt2ᚖint(ctx, tmp) + } + + var zeroVal *int + return zeroVal, nil +} + +func (ec *executionContext) field_Query_users_argsBefore( + ctx context.Context, + rawArgs map[string]any, +) (*entgql.Cursor[int], error) { + if _, ok := rawArgs["before"]; !ok { + var zeroVal *entgql.Cursor[int] + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("before")) + if tmp, ok := rawArgs["before"]; ok { + return ec.unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, tmp) + } + + var zeroVal *entgql.Cursor[int] + return zeroVal, nil +} + +func (ec *executionContext) field_Query_users_argsLast( + ctx context.Context, + rawArgs map[string]any, +) (*int, error) { + if _, ok := rawArgs["last"]; !ok { + var zeroVal *int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("last")) + if tmp, ok := rawArgs["last"]; ok { + return ec.unmarshalOInt2ᚖint(ctx, tmp) + } + + var zeroVal *int + return zeroVal, nil +} + +func (ec *executionContext) field_Query_users_argsOrderBy( + ctx context.Context, + rawArgs map[string]any, +) (*ent.UserOrder, error) { + if _, ok := rawArgs["orderBy"]; !ok { + var zeroVal *ent.UserOrder + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("orderBy")) + if tmp, ok := rawArgs["orderBy"]; ok { + return ec.unmarshalOUserOrder2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUserOrder(ctx, tmp) + } + + var zeroVal *ent.UserOrder + return zeroVal, nil +} + +func (ec *executionContext) field_Query_users_argsWhere( + ctx context.Context, + rawArgs map[string]any, +) (*ent.UserWhereInput, error) { + if _, ok := rawArgs["where"]; !ok { + var zeroVal *ent.UserWhereInput + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("where")) + if tmp, ok := rawArgs["where"]; ok { + return ec.unmarshalOUserWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUserWhereInput(ctx, tmp) + } + + var zeroVal *ent.UserWhereInput + return zeroVal, nil +} + +func (ec *executionContext) field_Todo_children_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := ec.field_Todo_children_argsAfter(ctx, rawArgs) + if err != nil { + return nil, err + } + args["after"] = arg0 + arg1, err := ec.field_Todo_children_argsFirst(ctx, rawArgs) + if err != nil { + return nil, err + } + args["first"] = arg1 + arg2, err := ec.field_Todo_children_argsBefore(ctx, rawArgs) + if err != nil { + return nil, err + } + args["before"] = arg2 + arg3, err := ec.field_Todo_children_argsLast(ctx, rawArgs) + if err != nil { + return nil, err + } + args["last"] = arg3 + arg4, err := ec.field_Todo_children_argsOrderBy(ctx, rawArgs) + if err != nil { + return nil, err + } + args["orderBy"] = arg4 + arg5, err := ec.field_Todo_children_argsWhere(ctx, rawArgs) + if err != nil { + return nil, err + } + args["where"] = arg5 + return args, nil +} +func (ec *executionContext) field_Todo_children_argsAfter( + ctx context.Context, + rawArgs map[string]any, +) (*entgql.Cursor[int], error) { + if _, ok := rawArgs["after"]; !ok { + var zeroVal *entgql.Cursor[int] + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("after")) + if tmp, ok := rawArgs["after"]; ok { + return ec.unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, tmp) + } + + var zeroVal *entgql.Cursor[int] + return zeroVal, nil +} + +func (ec *executionContext) field_Todo_children_argsFirst( + ctx context.Context, + rawArgs map[string]any, +) (*int, error) { + if _, ok := rawArgs["first"]; !ok { + var zeroVal *int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("first")) + if tmp, ok := rawArgs["first"]; ok { + return ec.unmarshalOInt2ᚖint(ctx, tmp) + } + + var zeroVal *int + return zeroVal, nil +} + +func (ec *executionContext) field_Todo_children_argsBefore( + ctx context.Context, + rawArgs map[string]any, +) (*entgql.Cursor[int], error) { + if _, ok := rawArgs["before"]; !ok { + var zeroVal *entgql.Cursor[int] + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("before")) + if tmp, ok := rawArgs["before"]; ok { + return ec.unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, tmp) + } + + var zeroVal *entgql.Cursor[int] + return zeroVal, nil +} + +func (ec *executionContext) field_Todo_children_argsLast( + ctx context.Context, + rawArgs map[string]any, +) (*int, error) { + if _, ok := rawArgs["last"]; !ok { + var zeroVal *int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("last")) + if tmp, ok := rawArgs["last"]; ok { + return ec.unmarshalOInt2ᚖint(ctx, tmp) + } + + var zeroVal *int + return zeroVal, nil +} + +func (ec *executionContext) field_Todo_children_argsOrderBy( + ctx context.Context, + rawArgs map[string]any, +) ([]*ent.TodoOrder, error) { + if _, ok := rawArgs["orderBy"]; !ok { + var zeroVal []*ent.TodoOrder + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("orderBy")) + if tmp, ok := rawArgs["orderBy"]; ok { + return ec.unmarshalOTodoOrder2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoOrderᚄ(ctx, tmp) + } + + var zeroVal []*ent.TodoOrder + return zeroVal, nil +} + +func (ec *executionContext) field_Todo_children_argsWhere( + ctx context.Context, + rawArgs map[string]any, +) (*ent.TodoWhereInput, error) { + if _, ok := rawArgs["where"]; !ok { + var zeroVal *ent.TodoWhereInput + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("where")) + if tmp, ok := rawArgs["where"]; ok { + return ec.unmarshalOTodoWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoWhereInput(ctx, tmp) + } + + var zeroVal *ent.TodoWhereInput + return zeroVal, nil +} + +func (ec *executionContext) field_User_friends_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := ec.field_User_friends_argsAfter(ctx, rawArgs) + if err != nil { + return nil, err + } + args["after"] = arg0 + arg1, err := ec.field_User_friends_argsFirst(ctx, rawArgs) + if err != nil { + return nil, err + } + args["first"] = arg1 + arg2, err := ec.field_User_friends_argsBefore(ctx, rawArgs) + if err != nil { + return nil, err + } + args["before"] = arg2 + arg3, err := ec.field_User_friends_argsLast(ctx, rawArgs) + if err != nil { + return nil, err + } + args["last"] = arg3 + arg4, err := ec.field_User_friends_argsOrderBy(ctx, rawArgs) + if err != nil { + return nil, err + } + args["orderBy"] = arg4 + arg5, err := ec.field_User_friends_argsWhere(ctx, rawArgs) + if err != nil { + return nil, err + } + args["where"] = arg5 + return args, nil +} +func (ec *executionContext) field_User_friends_argsAfter( + ctx context.Context, + rawArgs map[string]any, +) (*entgql.Cursor[int], error) { + if _, ok := rawArgs["after"]; !ok { + var zeroVal *entgql.Cursor[int] + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("after")) + if tmp, ok := rawArgs["after"]; ok { + return ec.unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, tmp) + } + + var zeroVal *entgql.Cursor[int] + return zeroVal, nil +} + +func (ec *executionContext) field_User_friends_argsFirst( + ctx context.Context, + rawArgs map[string]any, +) (*int, error) { + if _, ok := rawArgs["first"]; !ok { + var zeroVal *int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("first")) + if tmp, ok := rawArgs["first"]; ok { + return ec.unmarshalOInt2ᚖint(ctx, tmp) + } + + var zeroVal *int + return zeroVal, nil +} + +func (ec *executionContext) field_User_friends_argsBefore( + ctx context.Context, + rawArgs map[string]any, +) (*entgql.Cursor[int], error) { + if _, ok := rawArgs["before"]; !ok { + var zeroVal *entgql.Cursor[int] + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("before")) + if tmp, ok := rawArgs["before"]; ok { + return ec.unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, tmp) + } + + var zeroVal *entgql.Cursor[int] + return zeroVal, nil +} + +func (ec *executionContext) field_User_friends_argsLast( + ctx context.Context, + rawArgs map[string]any, +) (*int, error) { + if _, ok := rawArgs["last"]; !ok { + var zeroVal *int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("last")) + if tmp, ok := rawArgs["last"]; ok { + return ec.unmarshalOInt2ᚖint(ctx, tmp) + } + + var zeroVal *int + return zeroVal, nil +} + +func (ec *executionContext) field_User_friends_argsOrderBy( + ctx context.Context, + rawArgs map[string]any, +) (*ent.UserOrder, error) { + if _, ok := rawArgs["orderBy"]; !ok { + var zeroVal *ent.UserOrder + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("orderBy")) + if tmp, ok := rawArgs["orderBy"]; ok { + return ec.unmarshalOUserOrder2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUserOrder(ctx, tmp) + } + + var zeroVal *ent.UserOrder + return zeroVal, nil +} + +func (ec *executionContext) field_User_friends_argsWhere( + ctx context.Context, + rawArgs map[string]any, +) (*ent.UserWhereInput, error) { + if _, ok := rawArgs["where"]; !ok { + var zeroVal *ent.UserWhereInput + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("where")) + if tmp, ok := rawArgs["where"]; ok { + return ec.unmarshalOUserWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUserWhereInput(ctx, tmp) + } + + var zeroVal *ent.UserWhereInput + return zeroVal, nil +} + +func (ec *executionContext) field_User_friendships_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := ec.field_User_friendships_argsAfter(ctx, rawArgs) + if err != nil { + return nil, err + } + args["after"] = arg0 + arg1, err := ec.field_User_friendships_argsFirst(ctx, rawArgs) + if err != nil { + return nil, err + } + args["first"] = arg1 + arg2, err := ec.field_User_friendships_argsBefore(ctx, rawArgs) + if err != nil { + return nil, err + } + args["before"] = arg2 + arg3, err := ec.field_User_friendships_argsLast(ctx, rawArgs) + if err != nil { + return nil, err + } + args["last"] = arg3 + arg4, err := ec.field_User_friendships_argsWhere(ctx, rawArgs) + if err != nil { + return nil, err + } + args["where"] = arg4 + return args, nil +} +func (ec *executionContext) field_User_friendships_argsAfter( + ctx context.Context, + rawArgs map[string]any, +) (*entgql.Cursor[int], error) { + if _, ok := rawArgs["after"]; !ok { + var zeroVal *entgql.Cursor[int] + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("after")) + if tmp, ok := rawArgs["after"]; ok { + return ec.unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, tmp) + } + + var zeroVal *entgql.Cursor[int] + return zeroVal, nil +} + +func (ec *executionContext) field_User_friendships_argsFirst( + ctx context.Context, + rawArgs map[string]any, +) (*int, error) { + if _, ok := rawArgs["first"]; !ok { + var zeroVal *int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("first")) + if tmp, ok := rawArgs["first"]; ok { + return ec.unmarshalOInt2ᚖint(ctx, tmp) + } + + var zeroVal *int + return zeroVal, nil +} + +func (ec *executionContext) field_User_friendships_argsBefore( + ctx context.Context, + rawArgs map[string]any, +) (*entgql.Cursor[int], error) { + if _, ok := rawArgs["before"]; !ok { + var zeroVal *entgql.Cursor[int] + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("before")) + if tmp, ok := rawArgs["before"]; ok { + return ec.unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, tmp) + } + + var zeroVal *entgql.Cursor[int] + return zeroVal, nil +} + +func (ec *executionContext) field_User_friendships_argsLast( + ctx context.Context, + rawArgs map[string]any, +) (*int, error) { + if _, ok := rawArgs["last"]; !ok { + var zeroVal *int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("last")) + if tmp, ok := rawArgs["last"]; ok { + return ec.unmarshalOInt2ᚖint(ctx, tmp) + } + + var zeroVal *int + return zeroVal, nil +} + +func (ec *executionContext) field_User_friendships_argsWhere( + ctx context.Context, + rawArgs map[string]any, +) (*ent.FriendshipWhereInput, error) { + if _, ok := rawArgs["where"]; !ok { + var zeroVal *ent.FriendshipWhereInput + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("where")) + if tmp, ok := rawArgs["where"]; ok { + return ec.unmarshalOFriendshipWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐFriendshipWhereInput(ctx, tmp) + } + + var zeroVal *ent.FriendshipWhereInput + return zeroVal, nil +} + +func (ec *executionContext) field_User_groups_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := ec.field_User_groups_argsAfter(ctx, rawArgs) + if err != nil { + return nil, err + } + args["after"] = arg0 + arg1, err := ec.field_User_groups_argsFirst(ctx, rawArgs) + if err != nil { + return nil, err + } + args["first"] = arg1 + arg2, err := ec.field_User_groups_argsBefore(ctx, rawArgs) + if err != nil { + return nil, err + } + args["before"] = arg2 + arg3, err := ec.field_User_groups_argsLast(ctx, rawArgs) + if err != nil { + return nil, err + } + args["last"] = arg3 + arg4, err := ec.field_User_groups_argsWhere(ctx, rawArgs) + if err != nil { + return nil, err + } + args["where"] = arg4 + return args, nil +} +func (ec *executionContext) field_User_groups_argsAfter( + ctx context.Context, + rawArgs map[string]any, +) (*entgql.Cursor[int], error) { + if _, ok := rawArgs["after"]; !ok { + var zeroVal *entgql.Cursor[int] + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("after")) + if tmp, ok := rawArgs["after"]; ok { + return ec.unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, tmp) + } + + var zeroVal *entgql.Cursor[int] + return zeroVal, nil +} + +func (ec *executionContext) field_User_groups_argsFirst( + ctx context.Context, + rawArgs map[string]any, +) (*int, error) { + if _, ok := rawArgs["first"]; !ok { + var zeroVal *int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("first")) + if tmp, ok := rawArgs["first"]; ok { + return ec.unmarshalOInt2ᚖint(ctx, tmp) + } + + var zeroVal *int + return zeroVal, nil +} + +func (ec *executionContext) field_User_groups_argsBefore( + ctx context.Context, + rawArgs map[string]any, +) (*entgql.Cursor[int], error) { + if _, ok := rawArgs["before"]; !ok { + var zeroVal *entgql.Cursor[int] + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("before")) + if tmp, ok := rawArgs["before"]; ok { + return ec.unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, tmp) + } + + var zeroVal *entgql.Cursor[int] + return zeroVal, nil +} + +func (ec *executionContext) field_User_groups_argsLast( + ctx context.Context, + rawArgs map[string]any, +) (*int, error) { + if _, ok := rawArgs["last"]; !ok { + var zeroVal *int + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("last")) + if tmp, ok := rawArgs["last"]; ok { + return ec.unmarshalOInt2ᚖint(ctx, tmp) + } + + var zeroVal *int + return zeroVal, nil +} + +func (ec *executionContext) field_User_groups_argsWhere( + ctx context.Context, + rawArgs map[string]any, +) (*ent.GroupWhereInput, error) { + if _, ok := rawArgs["where"]; !ok { + var zeroVal *ent.GroupWhereInput + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("where")) + if tmp, ok := rawArgs["where"]; ok { + return ec.unmarshalOGroupWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐGroupWhereInput(ctx, tmp) + } + + var zeroVal *ent.GroupWhereInput + return zeroVal, nil +} + +func (ec *executionContext) field___Type_enumValues_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := ec.field___Type_enumValues_argsIncludeDeprecated(ctx, rawArgs) + if err != nil { + return nil, err + } + args["includeDeprecated"] = arg0 + return args, nil +} +func (ec *executionContext) field___Type_enumValues_argsIncludeDeprecated( + ctx context.Context, + rawArgs map[string]any, +) (bool, error) { + if _, ok := rawArgs["includeDeprecated"]; !ok { + var zeroVal bool + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("includeDeprecated")) + if tmp, ok := rawArgs["includeDeprecated"]; ok { + return ec.unmarshalOBoolean2bool(ctx, tmp) + } + + var zeroVal bool + return zeroVal, nil +} + +func (ec *executionContext) field___Type_fields_args(ctx context.Context, rawArgs map[string]any) (map[string]any, error) { + var err error + args := map[string]any{} + arg0, err := ec.field___Type_fields_argsIncludeDeprecated(ctx, rawArgs) + if err != nil { + return nil, err + } + args["includeDeprecated"] = arg0 + return args, nil +} +func (ec *executionContext) field___Type_fields_argsIncludeDeprecated( + ctx context.Context, + rawArgs map[string]any, +) (bool, error) { + if _, ok := rawArgs["includeDeprecated"]; !ok { + var zeroVal bool + return zeroVal, nil + } + + ctx = graphql.WithPathContext(ctx, graphql.NewPathWithField("includeDeprecated")) + if tmp, ok := rawArgs["includeDeprecated"]; ok { + return ec.unmarshalOBoolean2bool(ctx, tmp) + } + + var zeroVal bool + return zeroVal, nil +} + +// endregion ***************************** args.gotpl ***************************** + +// region ************************** directives.gotpl ************************** + +// endregion ************************** directives.gotpl ************************** + +// region **************************** field.gotpl ***************************** + +func (ec *executionContext) _BillProduct_id(ctx context.Context, field graphql.CollectedField, obj *ent.BillProduct) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_BillProduct_id(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.ID, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(int) + fc.Result = res + return ec.marshalNID2int(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_BillProduct_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "BillProduct", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _BillProduct_name(ctx context.Context, field graphql.CollectedField, obj *ent.BillProduct) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_BillProduct_name(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Name, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalNString2string(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_BillProduct_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "BillProduct", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _BillProduct_sku(ctx context.Context, field graphql.CollectedField, obj *ent.BillProduct) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_BillProduct_sku(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Sku, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalNString2string(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_BillProduct_sku(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "BillProduct", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _BillProduct_quantity(ctx context.Context, field graphql.CollectedField, obj *ent.BillProduct) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_BillProduct_quantity(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Quantity, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(uint64) + fc.Result = res + return ec.marshalNUint642uint64(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_BillProduct_quantity(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "BillProduct", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Uint64 does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Category_id(ctx context.Context, field graphql.CollectedField, obj *ent.Category) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Category_id(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.ID, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(int) + fc.Result = res + return ec.marshalNID2int(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Category_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Category", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Category_text(ctx context.Context, field graphql.CollectedField, obj *ent.Category) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Category_text(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Text, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalNString2string(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Category_text(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Category", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Category_status(ctx context.Context, field graphql.CollectedField, obj *ent.Category) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Category_status(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Status, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(category.Status) + fc.Result = res + return ec.marshalNCategoryStatus2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋcategoryᚐStatus(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Category_status(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Category", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type CategoryStatus does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Category_config(ctx context.Context, field graphql.CollectedField, obj *ent.Category) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Category_config(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Config, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*schematype.CategoryConfig) + fc.Result = res + return ec.marshalOCategoryConfig2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋschematypeᚐCategoryConfig(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Category_config(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Category", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "maxMembers": + return ec.fieldContext_CategoryConfig_maxMembers(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type CategoryConfig", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _Category_types(ctx context.Context, field graphql.CollectedField, obj *ent.Category) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Category_types(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Types, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*schematype.CategoryTypes) + fc.Result = res + return ec.marshalOCategoryTypes2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋschematypeᚐCategoryTypes(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Category_types(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Category", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "public": + return ec.fieldContext_CategoryTypes_public(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type CategoryTypes", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _Category_duration(ctx context.Context, field graphql.CollectedField, obj *ent.Category) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Category_duration(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Duration, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(time.Duration) + fc.Result = res + return ec.marshalODuration2timeᚐDuration(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Category_duration(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Category", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Duration does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Category_count(ctx context.Context, field graphql.CollectedField, obj *ent.Category) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Category_count(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Count, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(uint64) + fc.Result = res + return ec.marshalOUint642uint64(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Category_count(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Category", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Uint64 does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Category_strings(ctx context.Context, field graphql.CollectedField, obj *ent.Category) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Category_strings(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Strings, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.([]string) + fc.Result = res + return ec.marshalOString2ᚕstringᚄ(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Category_strings(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Category", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Category_todos(ctx context.Context, field graphql.CollectedField, obj *ent.Category) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Category_todos(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Todos(ctx, fc.Args["after"].(*entgql.Cursor[int]), fc.Args["first"].(*int), fc.Args["before"].(*entgql.Cursor[int]), fc.Args["last"].(*int), fc.Args["orderBy"].([]*ent.TodoOrder), fc.Args["where"].(*ent.TodoWhereInput)) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*ent.TodoConnection) + fc.Result = res + return ec.marshalNTodoConnection2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoConnection(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Category_todos(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Category", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "edges": + return ec.fieldContext_TodoConnection_edges(ctx, field) + case "pageInfo": + return ec.fieldContext_TodoConnection_pageInfo(ctx, field) + case "totalCount": + return ec.fieldContext_TodoConnection_totalCount(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type TodoConnection", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Category_todos_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Category_subCategories(ctx context.Context, field graphql.CollectedField, obj *ent.Category) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Category_subCategories(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.SubCategories(ctx, fc.Args["after"].(*entgql.Cursor[int]), fc.Args["first"].(*int), fc.Args["before"].(*entgql.Cursor[int]), fc.Args["last"].(*int), fc.Args["orderBy"].([]*ent.CategoryOrder), fc.Args["where"].(*ent.CategoryWhereInput)) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*ent.CategoryConnection) + fc.Result = res + return ec.marshalNCategoryConnection2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategoryConnection(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Category_subCategories(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Category", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "edges": + return ec.fieldContext_CategoryConnection_edges(ctx, field) + case "pageInfo": + return ec.fieldContext_CategoryConnection_pageInfo(ctx, field) + case "totalCount": + return ec.fieldContext_CategoryConnection_totalCount(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type CategoryConnection", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Category_subCategories_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Category_todosCount(ctx context.Context, field graphql.CollectedField, obj *ent.Category) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Category_todosCount(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return ec.resolvers.Category().TodosCount(rctx, obj) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*int) + fc.Result = res + return ec.marshalOInt2ᚖint(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Category_todosCount(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Category", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Int does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _CategoryConfig_maxMembers(ctx context.Context, field graphql.CollectedField, obj *schematype.CategoryConfig) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_CategoryConfig_maxMembers(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.MaxMembers, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(int) + fc.Result = res + return ec.marshalOInt2int(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_CategoryConfig_maxMembers(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "CategoryConfig", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Int does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _CategoryConnection_edges(ctx context.Context, field graphql.CollectedField, obj *ent.CategoryConnection) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_CategoryConnection_edges(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Edges, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.([]*ent.CategoryEdge) + fc.Result = res + return ec.marshalOCategoryEdge2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategoryEdge(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_CategoryConnection_edges(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "CategoryConnection", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "node": + return ec.fieldContext_CategoryEdge_node(ctx, field) + case "cursor": + return ec.fieldContext_CategoryEdge_cursor(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type CategoryEdge", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _CategoryConnection_pageInfo(ctx context.Context, field graphql.CollectedField, obj *ent.CategoryConnection) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_CategoryConnection_pageInfo(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.PageInfo, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(entgql.PageInfo[int]) + fc.Result = res + return ec.marshalNPageInfo2entgoᚗioᚋcontribᚋentgqlᚐPageInfo(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_CategoryConnection_pageInfo(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "CategoryConnection", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "hasNextPage": + return ec.fieldContext_PageInfo_hasNextPage(ctx, field) + case "hasPreviousPage": + return ec.fieldContext_PageInfo_hasPreviousPage(ctx, field) + case "startCursor": + return ec.fieldContext_PageInfo_startCursor(ctx, field) + case "endCursor": + return ec.fieldContext_PageInfo_endCursor(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type PageInfo", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _CategoryConnection_totalCount(ctx context.Context, field graphql.CollectedField, obj *ent.CategoryConnection) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_CategoryConnection_totalCount(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.TotalCount, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(int) + fc.Result = res + return ec.marshalNInt2int(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_CategoryConnection_totalCount(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "CategoryConnection", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Int does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _CategoryEdge_node(ctx context.Context, field graphql.CollectedField, obj *ent.CategoryEdge) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_CategoryEdge_node(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Node, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*ent.Category) + fc.Result = res + return ec.marshalOCategory2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategory(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_CategoryEdge_node(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "CategoryEdge", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_Category_id(ctx, field) + case "text": + return ec.fieldContext_Category_text(ctx, field) + case "status": + return ec.fieldContext_Category_status(ctx, field) + case "config": + return ec.fieldContext_Category_config(ctx, field) + case "types": + return ec.fieldContext_Category_types(ctx, field) + case "duration": + return ec.fieldContext_Category_duration(ctx, field) + case "count": + return ec.fieldContext_Category_count(ctx, field) + case "strings": + return ec.fieldContext_Category_strings(ctx, field) + case "todos": + return ec.fieldContext_Category_todos(ctx, field) + case "subCategories": + return ec.fieldContext_Category_subCategories(ctx, field) + case "todosCount": + return ec.fieldContext_Category_todosCount(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type Category", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _CategoryEdge_cursor(ctx context.Context, field graphql.CollectedField, obj *ent.CategoryEdge) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_CategoryEdge_cursor(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Cursor, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(entgql.Cursor[int]) + fc.Result = res + return ec.marshalNCursor2entgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_CategoryEdge_cursor(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "CategoryEdge", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Cursor does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _CategoryTypes_public(ctx context.Context, field graphql.CollectedField, obj *schematype.CategoryTypes) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_CategoryTypes_public(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Public, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(bool) + fc.Result = res + return ec.marshalOBoolean2bool(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_CategoryTypes_public(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "CategoryTypes", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Custom_info(ctx context.Context, field graphql.CollectedField, obj *customstruct.Custom) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Custom_info(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Info, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalNString2string(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Custom_info(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Custom", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Friendship_id(ctx context.Context, field graphql.CollectedField, obj *ent.Friendship) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Friendship_id(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.ID, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(int) + fc.Result = res + return ec.marshalNID2int(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Friendship_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Friendship", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Friendship_createdAt(ctx context.Context, field graphql.CollectedField, obj *ent.Friendship) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Friendship_createdAt(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.CreatedAt, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(time.Time) + fc.Result = res + return ec.marshalNTime2timeᚐTime(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Friendship_createdAt(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Friendship", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Time does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Friendship_userID(ctx context.Context, field graphql.CollectedField, obj *ent.Friendship) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Friendship_userID(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.UserID, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(int) + fc.Result = res + return ec.marshalNID2int(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Friendship_userID(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Friendship", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Friendship_friendID(ctx context.Context, field graphql.CollectedField, obj *ent.Friendship) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Friendship_friendID(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.FriendID, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(int) + fc.Result = res + return ec.marshalNID2int(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Friendship_friendID(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Friendship", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Friendship_user(ctx context.Context, field graphql.CollectedField, obj *ent.Friendship) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Friendship_user(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.User(ctx) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*ent.User) + fc.Result = res + return ec.marshalNUser2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUser(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Friendship_user(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Friendship", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_User_id(ctx, field) + case "name": + return ec.fieldContext_User_name(ctx, field) + case "username": + return ec.fieldContext_User_username(ctx, field) + case "requiredMetadata": + return ec.fieldContext_User_requiredMetadata(ctx, field) + case "metadata": + return ec.fieldContext_User_metadata(ctx, field) + case "groups": + return ec.fieldContext_User_groups(ctx, field) + case "friends": + return ec.fieldContext_User_friends(ctx, field) + case "friendships": + return ec.fieldContext_User_friendships(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type User", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _Friendship_friend(ctx context.Context, field graphql.CollectedField, obj *ent.Friendship) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Friendship_friend(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Friend(ctx) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*ent.User) + fc.Result = res + return ec.marshalNUser2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUser(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Friendship_friend(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Friendship", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_User_id(ctx, field) + case "name": + return ec.fieldContext_User_name(ctx, field) + case "username": + return ec.fieldContext_User_username(ctx, field) + case "requiredMetadata": + return ec.fieldContext_User_requiredMetadata(ctx, field) + case "metadata": + return ec.fieldContext_User_metadata(ctx, field) + case "groups": + return ec.fieldContext_User_groups(ctx, field) + case "friends": + return ec.fieldContext_User_friends(ctx, field) + case "friendships": + return ec.fieldContext_User_friendships(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type User", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _FriendshipConnection_edges(ctx context.Context, field graphql.CollectedField, obj *ent.FriendshipConnection) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_FriendshipConnection_edges(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Edges, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.([]*ent.FriendshipEdge) + fc.Result = res + return ec.marshalOFriendshipEdge2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐFriendshipEdge(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_FriendshipConnection_edges(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "FriendshipConnection", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "node": + return ec.fieldContext_FriendshipEdge_node(ctx, field) + case "cursor": + return ec.fieldContext_FriendshipEdge_cursor(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type FriendshipEdge", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _FriendshipConnection_pageInfo(ctx context.Context, field graphql.CollectedField, obj *ent.FriendshipConnection) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_FriendshipConnection_pageInfo(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.PageInfo, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(entgql.PageInfo[int]) + fc.Result = res + return ec.marshalNPageInfo2entgoᚗioᚋcontribᚋentgqlᚐPageInfo(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_FriendshipConnection_pageInfo(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "FriendshipConnection", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "hasNextPage": + return ec.fieldContext_PageInfo_hasNextPage(ctx, field) + case "hasPreviousPage": + return ec.fieldContext_PageInfo_hasPreviousPage(ctx, field) + case "startCursor": + return ec.fieldContext_PageInfo_startCursor(ctx, field) + case "endCursor": + return ec.fieldContext_PageInfo_endCursor(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type PageInfo", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _FriendshipConnection_totalCount(ctx context.Context, field graphql.CollectedField, obj *ent.FriendshipConnection) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_FriendshipConnection_totalCount(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.TotalCount, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(int) + fc.Result = res + return ec.marshalNInt2int(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_FriendshipConnection_totalCount(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "FriendshipConnection", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Int does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _FriendshipEdge_node(ctx context.Context, field graphql.CollectedField, obj *ent.FriendshipEdge) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_FriendshipEdge_node(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Node, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*ent.Friendship) + fc.Result = res + return ec.marshalOFriendship2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐFriendship(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_FriendshipEdge_node(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "FriendshipEdge", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_Friendship_id(ctx, field) + case "createdAt": + return ec.fieldContext_Friendship_createdAt(ctx, field) + case "userID": + return ec.fieldContext_Friendship_userID(ctx, field) + case "friendID": + return ec.fieldContext_Friendship_friendID(ctx, field) + case "user": + return ec.fieldContext_Friendship_user(ctx, field) + case "friend": + return ec.fieldContext_Friendship_friend(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type Friendship", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _FriendshipEdge_cursor(ctx context.Context, field graphql.CollectedField, obj *ent.FriendshipEdge) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_FriendshipEdge_cursor(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Cursor, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(entgql.Cursor[int]) + fc.Result = res + return ec.marshalNCursor2entgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_FriendshipEdge_cursor(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "FriendshipEdge", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Cursor does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Group_id(ctx context.Context, field graphql.CollectedField, obj *ent.Group) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Group_id(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.ID, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(int) + fc.Result = res + return ec.marshalNID2int(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Group_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Group", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Group_name(ctx context.Context, field graphql.CollectedField, obj *ent.Group) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Group_name(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Name, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalNString2string(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Group_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Group", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Group_users(ctx context.Context, field graphql.CollectedField, obj *ent.Group) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Group_users(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Users(ctx, fc.Args["after"].(*entgql.Cursor[int]), fc.Args["first"].(*int), fc.Args["before"].(*entgql.Cursor[int]), fc.Args["last"].(*int), fc.Args["orderBy"].(*ent.UserOrder), fc.Args["where"].(*ent.UserWhereInput)) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*ent.UserConnection) + fc.Result = res + return ec.marshalNUserConnection2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUserConnection(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Group_users(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Group", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "edges": + return ec.fieldContext_UserConnection_edges(ctx, field) + case "pageInfo": + return ec.fieldContext_UserConnection_pageInfo(ctx, field) + case "totalCount": + return ec.fieldContext_UserConnection_totalCount(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type UserConnection", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Group_users_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _GroupConnection_edges(ctx context.Context, field graphql.CollectedField, obj *ent.GroupConnection) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_GroupConnection_edges(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Edges, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.([]*ent.GroupEdge) + fc.Result = res + return ec.marshalOGroupEdge2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐGroupEdge(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_GroupConnection_edges(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "GroupConnection", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "node": + return ec.fieldContext_GroupEdge_node(ctx, field) + case "cursor": + return ec.fieldContext_GroupEdge_cursor(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type GroupEdge", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _GroupConnection_pageInfo(ctx context.Context, field graphql.CollectedField, obj *ent.GroupConnection) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_GroupConnection_pageInfo(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.PageInfo, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(entgql.PageInfo[int]) + fc.Result = res + return ec.marshalNPageInfo2entgoᚗioᚋcontribᚋentgqlᚐPageInfo(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_GroupConnection_pageInfo(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "GroupConnection", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "hasNextPage": + return ec.fieldContext_PageInfo_hasNextPage(ctx, field) + case "hasPreviousPage": + return ec.fieldContext_PageInfo_hasPreviousPage(ctx, field) + case "startCursor": + return ec.fieldContext_PageInfo_startCursor(ctx, field) + case "endCursor": + return ec.fieldContext_PageInfo_endCursor(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type PageInfo", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _GroupConnection_totalCount(ctx context.Context, field graphql.CollectedField, obj *ent.GroupConnection) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_GroupConnection_totalCount(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.TotalCount, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(int) + fc.Result = res + return ec.marshalNInt2int(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_GroupConnection_totalCount(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "GroupConnection", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Int does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _GroupEdge_node(ctx context.Context, field graphql.CollectedField, obj *ent.GroupEdge) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_GroupEdge_node(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + directive0 := func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Node, nil + } + + directive1 := func(ctx context.Context) (any, error) { + permissions, err := ec.unmarshalNString2ᚕstringᚄ(ctx, []any{"ADMIN", "MODERATOR"}) + if err != nil { + var zeroVal *ent.Group + return zeroVal, err + } + if ec.directives.HasPermissions == nil { + var zeroVal *ent.Group + return zeroVal, errors.New("directive hasPermissions is not implemented") + } + return ec.directives.HasPermissions(ctx, obj, directive0, permissions) + } + + tmp, err := directive1(rctx) + if err != nil { + return nil, graphql.ErrorOnPath(ctx, err) + } + if tmp == nil { + return nil, nil + } + if data, ok := tmp.(*ent.Group); ok { + return data, nil + } + return nil, fmt.Errorf(`unexpected type %T from directive, should be *entgo.io/contrib/entgql/internal/todoglobalid/ent.Group`, tmp) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*ent.Group) + fc.Result = res + return ec.marshalOGroup2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐGroup(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_GroupEdge_node(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "GroupEdge", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_Group_id(ctx, field) + case "name": + return ec.fieldContext_Group_name(ctx, field) + case "users": + return ec.fieldContext_Group_users(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type Group", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _GroupEdge_cursor(ctx context.Context, field graphql.CollectedField, obj *ent.GroupEdge) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_GroupEdge_cursor(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Cursor, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(entgql.Cursor[int]) + fc.Result = res + return ec.marshalNCursor2entgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_GroupEdge_cursor(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "GroupEdge", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Cursor does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Mutation_createCategory(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Mutation_createCategory(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return ec.resolvers.Mutation().CreateCategory(rctx, fc.Args["input"].(ent.CreateCategoryInput)) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*ent.Category) + fc.Result = res + return ec.marshalNCategory2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategory(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Mutation_createCategory(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Mutation", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_Category_id(ctx, field) + case "text": + return ec.fieldContext_Category_text(ctx, field) + case "status": + return ec.fieldContext_Category_status(ctx, field) + case "config": + return ec.fieldContext_Category_config(ctx, field) + case "types": + return ec.fieldContext_Category_types(ctx, field) + case "duration": + return ec.fieldContext_Category_duration(ctx, field) + case "count": + return ec.fieldContext_Category_count(ctx, field) + case "strings": + return ec.fieldContext_Category_strings(ctx, field) + case "todos": + return ec.fieldContext_Category_todos(ctx, field) + case "subCategories": + return ec.fieldContext_Category_subCategories(ctx, field) + case "todosCount": + return ec.fieldContext_Category_todosCount(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type Category", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Mutation_createCategory_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Mutation_createTodo(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Mutation_createTodo(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return ec.resolvers.Mutation().CreateTodo(rctx, fc.Args["input"].(ent.CreateTodoInput)) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*ent.Todo) + fc.Result = res + return ec.marshalNTodo2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodo(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Mutation_createTodo(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Mutation", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_Todo_id(ctx, field) + case "createdAt": + return ec.fieldContext_Todo_createdAt(ctx, field) + case "status": + return ec.fieldContext_Todo_status(ctx, field) + case "priorityOrder": + return ec.fieldContext_Todo_priorityOrder(ctx, field) + case "text": + return ec.fieldContext_Todo_text(ctx, field) + case "categoryID": + return ec.fieldContext_Todo_categoryID(ctx, field) + case "category_id": + return ec.fieldContext_Todo_category_id(ctx, field) + case "categoryX": + return ec.fieldContext_Todo_categoryX(ctx, field) + case "init": + return ec.fieldContext_Todo_init(ctx, field) + case "custom": + return ec.fieldContext_Todo_custom(ctx, field) + case "customp": + return ec.fieldContext_Todo_customp(ctx, field) + case "value": + return ec.fieldContext_Todo_value(ctx, field) + case "parent": + return ec.fieldContext_Todo_parent(ctx, field) + case "children": + return ec.fieldContext_Todo_children(ctx, field) + case "category": + return ec.fieldContext_Todo_category(ctx, field) + case "extendedField": + return ec.fieldContext_Todo_extendedField(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type Todo", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Mutation_createTodo_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Mutation_updateTodo(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Mutation_updateTodo(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return ec.resolvers.Mutation().UpdateTodo(rctx, fc.Args["id"].(int), fc.Args["input"].(ent.UpdateTodoInput)) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*ent.Todo) + fc.Result = res + return ec.marshalNTodo2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodo(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Mutation_updateTodo(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Mutation", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_Todo_id(ctx, field) + case "createdAt": + return ec.fieldContext_Todo_createdAt(ctx, field) + case "status": + return ec.fieldContext_Todo_status(ctx, field) + case "priorityOrder": + return ec.fieldContext_Todo_priorityOrder(ctx, field) + case "text": + return ec.fieldContext_Todo_text(ctx, field) + case "categoryID": + return ec.fieldContext_Todo_categoryID(ctx, field) + case "category_id": + return ec.fieldContext_Todo_category_id(ctx, field) + case "categoryX": + return ec.fieldContext_Todo_categoryX(ctx, field) + case "init": + return ec.fieldContext_Todo_init(ctx, field) + case "custom": + return ec.fieldContext_Todo_custom(ctx, field) + case "customp": + return ec.fieldContext_Todo_customp(ctx, field) + case "value": + return ec.fieldContext_Todo_value(ctx, field) + case "parent": + return ec.fieldContext_Todo_parent(ctx, field) + case "children": + return ec.fieldContext_Todo_children(ctx, field) + case "category": + return ec.fieldContext_Todo_category(ctx, field) + case "extendedField": + return ec.fieldContext_Todo_extendedField(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type Todo", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Mutation_updateTodo_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Mutation_clearTodos(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Mutation_clearTodos(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return ec.resolvers.Mutation().ClearTodos(rctx) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(int) + fc.Result = res + return ec.marshalNInt2int(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Mutation_clearTodos(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Mutation", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Int does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Mutation_updateFriendship(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Mutation_updateFriendship(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return ec.resolvers.Mutation().UpdateFriendship(rctx, fc.Args["id"].(int), fc.Args["input"].(ent.UpdateFriendshipInput)) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*ent.Friendship) + fc.Result = res + return ec.marshalNFriendship2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐFriendship(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Mutation_updateFriendship(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Mutation", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_Friendship_id(ctx, field) + case "createdAt": + return ec.fieldContext_Friendship_createdAt(ctx, field) + case "userID": + return ec.fieldContext_Friendship_userID(ctx, field) + case "friendID": + return ec.fieldContext_Friendship_friendID(ctx, field) + case "user": + return ec.fieldContext_Friendship_user(ctx, field) + case "friend": + return ec.fieldContext_Friendship_friend(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type Friendship", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Mutation_updateFriendship_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _OneToMany_id(ctx context.Context, field graphql.CollectedField, obj *ent.OneToMany) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_OneToMany_id(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.ID, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(int) + fc.Result = res + return ec.marshalNID2int(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_OneToMany_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "OneToMany", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _OneToMany_name(ctx context.Context, field graphql.CollectedField, obj *ent.OneToMany) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_OneToMany_name(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Name, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalNString2string(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_OneToMany_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "OneToMany", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _OneToMany_field2(ctx context.Context, field graphql.CollectedField, obj *ent.OneToMany) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_OneToMany_field2(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Field2, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalOString2string(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_OneToMany_field2(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "OneToMany", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _OneToMany_parent(ctx context.Context, field graphql.CollectedField, obj *ent.OneToMany) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_OneToMany_parent(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Parent(ctx) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*ent.OneToMany) + fc.Result = res + return ec.marshalOOneToMany2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToMany(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_OneToMany_parent(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "OneToMany", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_OneToMany_id(ctx, field) + case "name": + return ec.fieldContext_OneToMany_name(ctx, field) + case "field2": + return ec.fieldContext_OneToMany_field2(ctx, field) + case "parent": + return ec.fieldContext_OneToMany_parent(ctx, field) + case "children": + return ec.fieldContext_OneToMany_children(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type OneToMany", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _OneToMany_children(ctx context.Context, field graphql.CollectedField, obj *ent.OneToMany) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_OneToMany_children(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Children(ctx) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.([]*ent.OneToMany) + fc.Result = res + return ec.marshalOOneToMany2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToManyᚄ(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_OneToMany_children(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "OneToMany", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_OneToMany_id(ctx, field) + case "name": + return ec.fieldContext_OneToMany_name(ctx, field) + case "field2": + return ec.fieldContext_OneToMany_field2(ctx, field) + case "parent": + return ec.fieldContext_OneToMany_parent(ctx, field) + case "children": + return ec.fieldContext_OneToMany_children(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type OneToMany", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _OneToManyConnection_edges(ctx context.Context, field graphql.CollectedField, obj *ent.OneToManyConnection) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_OneToManyConnection_edges(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Edges, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.([]*ent.OneToManyEdge) + fc.Result = res + return ec.marshalOOneToManyEdge2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToManyEdge(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_OneToManyConnection_edges(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "OneToManyConnection", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "node": + return ec.fieldContext_OneToManyEdge_node(ctx, field) + case "cursor": + return ec.fieldContext_OneToManyEdge_cursor(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type OneToManyEdge", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _OneToManyConnection_pageInfo(ctx context.Context, field graphql.CollectedField, obj *ent.OneToManyConnection) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_OneToManyConnection_pageInfo(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.PageInfo, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(entgql.PageInfo[int]) + fc.Result = res + return ec.marshalNPageInfo2entgoᚗioᚋcontribᚋentgqlᚐPageInfo(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_OneToManyConnection_pageInfo(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "OneToManyConnection", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "hasNextPage": + return ec.fieldContext_PageInfo_hasNextPage(ctx, field) + case "hasPreviousPage": + return ec.fieldContext_PageInfo_hasPreviousPage(ctx, field) + case "startCursor": + return ec.fieldContext_PageInfo_startCursor(ctx, field) + case "endCursor": + return ec.fieldContext_PageInfo_endCursor(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type PageInfo", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _OneToManyConnection_totalCount(ctx context.Context, field graphql.CollectedField, obj *ent.OneToManyConnection) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_OneToManyConnection_totalCount(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.TotalCount, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(int) + fc.Result = res + return ec.marshalNInt2int(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_OneToManyConnection_totalCount(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "OneToManyConnection", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Int does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _OneToManyEdge_node(ctx context.Context, field graphql.CollectedField, obj *ent.OneToManyEdge) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_OneToManyEdge_node(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Node, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*ent.OneToMany) + fc.Result = res + return ec.marshalOOneToMany2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToMany(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_OneToManyEdge_node(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "OneToManyEdge", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_OneToMany_id(ctx, field) + case "name": + return ec.fieldContext_OneToMany_name(ctx, field) + case "field2": + return ec.fieldContext_OneToMany_field2(ctx, field) + case "parent": + return ec.fieldContext_OneToMany_parent(ctx, field) + case "children": + return ec.fieldContext_OneToMany_children(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type OneToMany", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _OneToManyEdge_cursor(ctx context.Context, field graphql.CollectedField, obj *ent.OneToManyEdge) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_OneToManyEdge_cursor(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Cursor, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(entgql.Cursor[int]) + fc.Result = res + return ec.marshalNCursor2entgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_OneToManyEdge_cursor(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "OneToManyEdge", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Cursor does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Organization_id(ctx context.Context, field graphql.CollectedField, obj *ent.Workspace) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Organization_id(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.ID, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(int) + fc.Result = res + return ec.marshalNID2int(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Organization_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Organization", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Organization_name(ctx context.Context, field graphql.CollectedField, obj *ent.Workspace) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Organization_name(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Name, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalNString2string(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Organization_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Organization", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _PageInfo_hasNextPage(ctx context.Context, field graphql.CollectedField, obj *entgql.PageInfo[int]) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_PageInfo_hasNextPage(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.HasNextPage, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(bool) + fc.Result = res + return ec.marshalNBoolean2bool(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_PageInfo_hasNextPage(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "PageInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _PageInfo_hasPreviousPage(ctx context.Context, field graphql.CollectedField, obj *entgql.PageInfo[int]) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_PageInfo_hasPreviousPage(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.HasPreviousPage, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(bool) + fc.Result = res + return ec.marshalNBoolean2bool(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_PageInfo_hasPreviousPage(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "PageInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _PageInfo_startCursor(ctx context.Context, field graphql.CollectedField, obj *entgql.PageInfo[int]) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_PageInfo_startCursor(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.StartCursor, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*entgql.Cursor[int]) + fc.Result = res + return ec.marshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_PageInfo_startCursor(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "PageInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Cursor does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _PageInfo_endCursor(ctx context.Context, field graphql.CollectedField, obj *entgql.PageInfo[int]) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_PageInfo_endCursor(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.EndCursor, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*entgql.Cursor[int]) + fc.Result = res + return ec.marshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_PageInfo_endCursor(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "PageInfo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Cursor does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Project_id(ctx context.Context, field graphql.CollectedField, obj *ent.Project) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Project_id(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.ID, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(int) + fc.Result = res + return ec.marshalNID2int(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Project_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Project", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Project_todos(ctx context.Context, field graphql.CollectedField, obj *ent.Project) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Project_todos(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Todos(ctx, fc.Args["after"].(*entgql.Cursor[int]), fc.Args["first"].(*int), fc.Args["before"].(*entgql.Cursor[int]), fc.Args["last"].(*int), fc.Args["orderBy"].([]*ent.TodoOrder), fc.Args["where"].(*ent.TodoWhereInput)) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*ent.TodoConnection) + fc.Result = res + return ec.marshalNTodoConnection2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoConnection(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Project_todos(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Project", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "edges": + return ec.fieldContext_TodoConnection_edges(ctx, field) + case "pageInfo": + return ec.fieldContext_TodoConnection_pageInfo(ctx, field) + case "totalCount": + return ec.fieldContext_TodoConnection_totalCount(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type TodoConnection", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Project_todos_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Query_node(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Query_node(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return ec.resolvers.Query().Node(rctx, fc.Args["id"].(int)) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(ent.Noder) + fc.Result = res + return ec.marshalONode2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐNoder(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Query_node(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("FieldContext.Child cannot be called on type INTERFACE") + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_node_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Query_nodes(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Query_nodes(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return ec.resolvers.Query().Nodes(rctx, fc.Args["ids"].([]int)) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.([]ent.Noder) + fc.Result = res + return ec.marshalNNode2ᚕentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐNoder(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Query_nodes(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("FieldContext.Child cannot be called on type INTERFACE") + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_nodes_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Query_billProducts(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Query_billProducts(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return ec.resolvers.Query().BillProducts(rctx) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.([]*ent.BillProduct) + fc.Result = res + return ec.marshalNBillProduct2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐBillProductᚄ(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Query_billProducts(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_BillProduct_id(ctx, field) + case "name": + return ec.fieldContext_BillProduct_name(ctx, field) + case "sku": + return ec.fieldContext_BillProduct_sku(ctx, field) + case "quantity": + return ec.fieldContext_BillProduct_quantity(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type BillProduct", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _Query_categories(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Query_categories(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return ec.resolvers.Query().Categories(rctx, fc.Args["after"].(*entgql.Cursor[int]), fc.Args["first"].(*int), fc.Args["before"].(*entgql.Cursor[int]), fc.Args["last"].(*int), fc.Args["orderBy"].([]*ent.CategoryOrder), fc.Args["where"].(*ent.CategoryWhereInput)) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*ent.CategoryConnection) + fc.Result = res + return ec.marshalNCategoryConnection2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategoryConnection(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Query_categories(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "edges": + return ec.fieldContext_CategoryConnection_edges(ctx, field) + case "pageInfo": + return ec.fieldContext_CategoryConnection_pageInfo(ctx, field) + case "totalCount": + return ec.fieldContext_CategoryConnection_totalCount(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type CategoryConnection", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_categories_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Query_groups(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Query_groups(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return ec.resolvers.Query().Groups(rctx, fc.Args["after"].(*entgql.Cursor[int]), fc.Args["first"].(*int), fc.Args["before"].(*entgql.Cursor[int]), fc.Args["last"].(*int), fc.Args["where"].(*ent.GroupWhereInput)) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*ent.GroupConnection) + fc.Result = res + return ec.marshalNGroupConnection2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐGroupConnection(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Query_groups(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "edges": + return ec.fieldContext_GroupConnection_edges(ctx, field) + case "pageInfo": + return ec.fieldContext_GroupConnection_pageInfo(ctx, field) + case "totalCount": + return ec.fieldContext_GroupConnection_totalCount(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type GroupConnection", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_groups_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Query_oneToMany(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Query_oneToMany(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return ec.resolvers.Query().OneToMany(rctx, fc.Args["after"].(*entgql.Cursor[int]), fc.Args["first"].(*int), fc.Args["before"].(*entgql.Cursor[int]), fc.Args["last"].(*int), fc.Args["orderBy"].(*ent.OneToManyOrder), fc.Args["where"].(*ent.OneToManyWhereInput)) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*ent.OneToManyConnection) + fc.Result = res + return ec.marshalNOneToManyConnection2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToManyConnection(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Query_oneToMany(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "edges": + return ec.fieldContext_OneToManyConnection_edges(ctx, field) + case "pageInfo": + return ec.fieldContext_OneToManyConnection_pageInfo(ctx, field) + case "totalCount": + return ec.fieldContext_OneToManyConnection_totalCount(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type OneToManyConnection", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_oneToMany_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Query_todos(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Query_todos(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return ec.resolvers.Query().Todos(rctx, fc.Args["after"].(*entgql.Cursor[int]), fc.Args["first"].(*int), fc.Args["before"].(*entgql.Cursor[int]), fc.Args["last"].(*int), fc.Args["orderBy"].([]*ent.TodoOrder), fc.Args["where"].(*ent.TodoWhereInput)) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*ent.TodoConnection) + fc.Result = res + return ec.marshalNTodoConnection2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoConnection(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Query_todos(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "edges": + return ec.fieldContext_TodoConnection_edges(ctx, field) + case "pageInfo": + return ec.fieldContext_TodoConnection_pageInfo(ctx, field) + case "totalCount": + return ec.fieldContext_TodoConnection_totalCount(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type TodoConnection", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_todos_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Query_users(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Query_users(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return ec.resolvers.Query().Users(rctx, fc.Args["after"].(*entgql.Cursor[int]), fc.Args["first"].(*int), fc.Args["before"].(*entgql.Cursor[int]), fc.Args["last"].(*int), fc.Args["orderBy"].(*ent.UserOrder), fc.Args["where"].(*ent.UserWhereInput)) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*ent.UserConnection) + fc.Result = res + return ec.marshalNUserConnection2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUserConnection(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Query_users(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "edges": + return ec.fieldContext_UserConnection_edges(ctx, field) + case "pageInfo": + return ec.fieldContext_UserConnection_pageInfo(ctx, field) + case "totalCount": + return ec.fieldContext_UserConnection_totalCount(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type UserConnection", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_users_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Query_ping(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Query_ping(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return ec.resolvers.Query().Ping(rctx) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalNString2string(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Query_ping(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Query_todosWithJoins(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Query_todosWithJoins(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return ec.resolvers.Query().TodosWithJoins(rctx, fc.Args["after"].(*entgql.Cursor[int]), fc.Args["first"].(*int), fc.Args["before"].(*entgql.Cursor[int]), fc.Args["last"].(*int), fc.Args["orderBy"].([]*ent.TodoOrder), fc.Args["where"].(*ent.TodoWhereInput)) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*ent.TodoConnection) + fc.Result = res + return ec.marshalNTodoConnection2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoConnection(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Query_todosWithJoins(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "edges": + return ec.fieldContext_TodoConnection_edges(ctx, field) + case "pageInfo": + return ec.fieldContext_TodoConnection_pageInfo(ctx, field) + case "totalCount": + return ec.fieldContext_TodoConnection_totalCount(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type TodoConnection", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query_todosWithJoins_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Query___type(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Query___type(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return ec.introspectType(fc.Args["name"].(string)) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*introspection.Type) + fc.Result = res + return ec.marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Query___type(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "kind": + return ec.fieldContext___Type_kind(ctx, field) + case "name": + return ec.fieldContext___Type_name(ctx, field) + case "description": + return ec.fieldContext___Type_description(ctx, field) + case "fields": + return ec.fieldContext___Type_fields(ctx, field) + case "interfaces": + return ec.fieldContext___Type_interfaces(ctx, field) + case "possibleTypes": + return ec.fieldContext___Type_possibleTypes(ctx, field) + case "enumValues": + return ec.fieldContext___Type_enumValues(ctx, field) + case "inputFields": + return ec.fieldContext___Type_inputFields(ctx, field) + case "ofType": + return ec.fieldContext___Type_ofType(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Query___type_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Query___schema(ctx context.Context, field graphql.CollectedField) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Query___schema(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return ec.introspectSchema() + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*introspection.Schema) + fc.Result = res + return ec.marshalO__Schema2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐSchema(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Query___schema(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Query", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "description": + return ec.fieldContext___Schema_description(ctx, field) + case "types": + return ec.fieldContext___Schema_types(ctx, field) + case "queryType": + return ec.fieldContext___Schema_queryType(ctx, field) + case "mutationType": + return ec.fieldContext___Schema_mutationType(ctx, field) + case "subscriptionType": + return ec.fieldContext___Schema_subscriptionType(ctx, field) + case "directives": + return ec.fieldContext___Schema_directives(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __Schema", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _Todo_id(ctx context.Context, field graphql.CollectedField, obj *ent.Todo) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Todo_id(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.ID, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(int) + fc.Result = res + return ec.marshalNID2int(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Todo_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Todo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Todo_createdAt(ctx context.Context, field graphql.CollectedField, obj *ent.Todo) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Todo_createdAt(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.CreatedAt, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(time.Time) + fc.Result = res + return ec.marshalNTime2timeᚐTime(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Todo_createdAt(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Todo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Time does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Todo_status(ctx context.Context, field graphql.CollectedField, obj *ent.Todo) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Todo_status(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Status, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(todo.Status) + fc.Result = res + return ec.marshalNTodoStatus2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋtodoᚐStatus(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Todo_status(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Todo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type TodoStatus does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Todo_priorityOrder(ctx context.Context, field graphql.CollectedField, obj *ent.Todo) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Todo_priorityOrder(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Priority, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(int) + fc.Result = res + return ec.marshalNInt2int(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Todo_priorityOrder(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Todo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Int does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Todo_text(ctx context.Context, field graphql.CollectedField, obj *ent.Todo) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Todo_text(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Text, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalNString2string(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Todo_text(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Todo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Todo_categoryID(ctx context.Context, field graphql.CollectedField, obj *ent.Todo) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Todo_categoryID(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.CategoryID, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(int) + fc.Result = res + return ec.marshalOID2int(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Todo_categoryID(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Todo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Todo_category_id(ctx context.Context, field graphql.CollectedField, obj *ent.Todo) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Todo_category_id(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.CategoryID, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(int) + fc.Result = res + return ec.marshalOID2int(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Todo_category_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Todo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Todo_categoryX(ctx context.Context, field graphql.CollectedField, obj *ent.Todo) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Todo_categoryX(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.CategoryID, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(int) + fc.Result = res + return ec.marshalOID2int(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Todo_categoryX(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Todo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Todo_init(ctx context.Context, field graphql.CollectedField, obj *ent.Todo) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Todo_init(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Init, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(map[string]interface{}) + fc.Result = res + return ec.marshalOMap2map(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Todo_init(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Todo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Map does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Todo_custom(ctx context.Context, field graphql.CollectedField, obj *ent.Todo) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Todo_custom(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Custom, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.([]customstruct.Custom) + fc.Result = res + return ec.marshalOCustom2ᚕentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋcustomstructᚐCustomᚄ(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Todo_custom(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Todo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "info": + return ec.fieldContext_Custom_info(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type Custom", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _Todo_customp(ctx context.Context, field graphql.CollectedField, obj *ent.Todo) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Todo_customp(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Customp, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.([]*customstruct.Custom) + fc.Result = res + return ec.marshalOCustom2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋcustomstructᚐCustom(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Todo_customp(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Todo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "info": + return ec.fieldContext_Custom_info(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type Custom", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _Todo_value(ctx context.Context, field graphql.CollectedField, obj *ent.Todo) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Todo_value(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Value, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(int) + fc.Result = res + return ec.marshalNInt2int(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Todo_value(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Todo", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Int does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _Todo_parent(ctx context.Context, field graphql.CollectedField, obj *ent.Todo) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Todo_parent(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Parent(ctx) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*ent.Todo) + fc.Result = res + return ec.marshalOTodo2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodo(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Todo_parent(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Todo", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_Todo_id(ctx, field) + case "createdAt": + return ec.fieldContext_Todo_createdAt(ctx, field) + case "status": + return ec.fieldContext_Todo_status(ctx, field) + case "priorityOrder": + return ec.fieldContext_Todo_priorityOrder(ctx, field) + case "text": + return ec.fieldContext_Todo_text(ctx, field) + case "categoryID": + return ec.fieldContext_Todo_categoryID(ctx, field) + case "category_id": + return ec.fieldContext_Todo_category_id(ctx, field) + case "categoryX": + return ec.fieldContext_Todo_categoryX(ctx, field) + case "init": + return ec.fieldContext_Todo_init(ctx, field) + case "custom": + return ec.fieldContext_Todo_custom(ctx, field) + case "customp": + return ec.fieldContext_Todo_customp(ctx, field) + case "value": + return ec.fieldContext_Todo_value(ctx, field) + case "parent": + return ec.fieldContext_Todo_parent(ctx, field) + case "children": + return ec.fieldContext_Todo_children(ctx, field) + case "category": + return ec.fieldContext_Todo_category(ctx, field) + case "extendedField": + return ec.fieldContext_Todo_extendedField(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type Todo", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _Todo_children(ctx context.Context, field graphql.CollectedField, obj *ent.Todo) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Todo_children(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Children(ctx, fc.Args["after"].(*entgql.Cursor[int]), fc.Args["first"].(*int), fc.Args["before"].(*entgql.Cursor[int]), fc.Args["last"].(*int), fc.Args["orderBy"].([]*ent.TodoOrder), fc.Args["where"].(*ent.TodoWhereInput)) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*ent.TodoConnection) + fc.Result = res + return ec.marshalNTodoConnection2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoConnection(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Todo_children(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Todo", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "edges": + return ec.fieldContext_TodoConnection_edges(ctx, field) + case "pageInfo": + return ec.fieldContext_TodoConnection_pageInfo(ctx, field) + case "totalCount": + return ec.fieldContext_TodoConnection_totalCount(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type TodoConnection", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_Todo_children_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _Todo_category(ctx context.Context, field graphql.CollectedField, obj *ent.Todo) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Todo_category(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Category(ctx) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*ent.Category) + fc.Result = res + return ec.marshalOCategory2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategory(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Todo_category(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Todo", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_Category_id(ctx, field) + case "text": + return ec.fieldContext_Category_text(ctx, field) + case "status": + return ec.fieldContext_Category_status(ctx, field) + case "config": + return ec.fieldContext_Category_config(ctx, field) + case "types": + return ec.fieldContext_Category_types(ctx, field) + case "duration": + return ec.fieldContext_Category_duration(ctx, field) + case "count": + return ec.fieldContext_Category_count(ctx, field) + case "strings": + return ec.fieldContext_Category_strings(ctx, field) + case "todos": + return ec.fieldContext_Category_todos(ctx, field) + case "subCategories": + return ec.fieldContext_Category_subCategories(ctx, field) + case "todosCount": + return ec.fieldContext_Category_todosCount(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type Category", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _Todo_extendedField(ctx context.Context, field graphql.CollectedField, obj *ent.Todo) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_Todo_extendedField(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return ec.resolvers.Todo().ExtendedField(rctx, obj) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*string) + fc.Result = res + return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_Todo_extendedField(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "Todo", + Field: field, + IsMethod: true, + IsResolver: true, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _TodoConnection_edges(ctx context.Context, field graphql.CollectedField, obj *ent.TodoConnection) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_TodoConnection_edges(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Edges, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.([]*ent.TodoEdge) + fc.Result = res + return ec.marshalOTodoEdge2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoEdge(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_TodoConnection_edges(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "TodoConnection", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "node": + return ec.fieldContext_TodoEdge_node(ctx, field) + case "cursor": + return ec.fieldContext_TodoEdge_cursor(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type TodoEdge", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _TodoConnection_pageInfo(ctx context.Context, field graphql.CollectedField, obj *ent.TodoConnection) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_TodoConnection_pageInfo(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.PageInfo, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(entgql.PageInfo[int]) + fc.Result = res + return ec.marshalNPageInfo2entgoᚗioᚋcontribᚋentgqlᚐPageInfo(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_TodoConnection_pageInfo(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "TodoConnection", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "hasNextPage": + return ec.fieldContext_PageInfo_hasNextPage(ctx, field) + case "hasPreviousPage": + return ec.fieldContext_PageInfo_hasPreviousPage(ctx, field) + case "startCursor": + return ec.fieldContext_PageInfo_startCursor(ctx, field) + case "endCursor": + return ec.fieldContext_PageInfo_endCursor(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type PageInfo", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _TodoConnection_totalCount(ctx context.Context, field graphql.CollectedField, obj *ent.TodoConnection) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_TodoConnection_totalCount(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.TotalCount, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(int) + fc.Result = res + return ec.marshalNInt2int(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_TodoConnection_totalCount(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "TodoConnection", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Int does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _TodoEdge_node(ctx context.Context, field graphql.CollectedField, obj *ent.TodoEdge) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_TodoEdge_node(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Node, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*ent.Todo) + fc.Result = res + return ec.marshalOTodo2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodo(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_TodoEdge_node(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "TodoEdge", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_Todo_id(ctx, field) + case "createdAt": + return ec.fieldContext_Todo_createdAt(ctx, field) + case "status": + return ec.fieldContext_Todo_status(ctx, field) + case "priorityOrder": + return ec.fieldContext_Todo_priorityOrder(ctx, field) + case "text": + return ec.fieldContext_Todo_text(ctx, field) + case "categoryID": + return ec.fieldContext_Todo_categoryID(ctx, field) + case "category_id": + return ec.fieldContext_Todo_category_id(ctx, field) + case "categoryX": + return ec.fieldContext_Todo_categoryX(ctx, field) + case "init": + return ec.fieldContext_Todo_init(ctx, field) + case "custom": + return ec.fieldContext_Todo_custom(ctx, field) + case "customp": + return ec.fieldContext_Todo_customp(ctx, field) + case "value": + return ec.fieldContext_Todo_value(ctx, field) + case "parent": + return ec.fieldContext_Todo_parent(ctx, field) + case "children": + return ec.fieldContext_Todo_children(ctx, field) + case "category": + return ec.fieldContext_Todo_category(ctx, field) + case "extendedField": + return ec.fieldContext_Todo_extendedField(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type Todo", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _TodoEdge_cursor(ctx context.Context, field graphql.CollectedField, obj *ent.TodoEdge) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_TodoEdge_cursor(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Cursor, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(entgql.Cursor[int]) + fc.Result = res + return ec.marshalNCursor2entgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_TodoEdge_cursor(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "TodoEdge", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Cursor does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _User_id(ctx context.Context, field graphql.CollectedField, obj *ent.User) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_User_id(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.ID, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(int) + fc.Result = res + return ec.marshalNID2int(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_User_id(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "User", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type ID does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _User_name(ctx context.Context, field graphql.CollectedField, obj *ent.User) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_User_name(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Name, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalNString2string(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_User_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "User", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _User_username(ctx context.Context, field graphql.CollectedField, obj *ent.User) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_User_username(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Username, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(uuid.UUID) + fc.Result = res + return ec.marshalNUUID2githubᚗcomᚋgoogleᚋuuidᚐUUID(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_User_username(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "User", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type UUID does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _User_requiredMetadata(ctx context.Context, field graphql.CollectedField, obj *ent.User) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_User_requiredMetadata(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.RequiredMetadata, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(map[string]interface{}) + fc.Result = res + return ec.marshalNMap2map(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_User_requiredMetadata(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "User", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Map does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _User_metadata(ctx context.Context, field graphql.CollectedField, obj *ent.User) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_User_metadata(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Metadata, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(map[string]interface{}) + fc.Result = res + return ec.marshalOMap2map(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_User_metadata(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "User", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Map does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _User_groups(ctx context.Context, field graphql.CollectedField, obj *ent.User) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_User_groups(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Groups(ctx, fc.Args["after"].(*entgql.Cursor[int]), fc.Args["first"].(*int), fc.Args["before"].(*entgql.Cursor[int]), fc.Args["last"].(*int), fc.Args["where"].(*ent.GroupWhereInput)) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*ent.GroupConnection) + fc.Result = res + return ec.marshalNGroupConnection2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐGroupConnection(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_User_groups(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "User", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "edges": + return ec.fieldContext_GroupConnection_edges(ctx, field) + case "pageInfo": + return ec.fieldContext_GroupConnection_pageInfo(ctx, field) + case "totalCount": + return ec.fieldContext_GroupConnection_totalCount(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type GroupConnection", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_User_groups_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _User_friends(ctx context.Context, field graphql.CollectedField, obj *ent.User) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_User_friends(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Friends(ctx, fc.Args["after"].(*entgql.Cursor[int]), fc.Args["first"].(*int), fc.Args["before"].(*entgql.Cursor[int]), fc.Args["last"].(*int), fc.Args["orderBy"].(*ent.UserOrder), fc.Args["where"].(*ent.UserWhereInput)) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*ent.UserConnection) + fc.Result = res + return ec.marshalNUserConnection2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUserConnection(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_User_friends(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "User", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "edges": + return ec.fieldContext_UserConnection_edges(ctx, field) + case "pageInfo": + return ec.fieldContext_UserConnection_pageInfo(ctx, field) + case "totalCount": + return ec.fieldContext_UserConnection_totalCount(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type UserConnection", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_User_friends_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _User_friendships(ctx context.Context, field graphql.CollectedField, obj *ent.User) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_User_friendships(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Friendships(ctx, fc.Args["after"].(*entgql.Cursor[int]), fc.Args["first"].(*int), fc.Args["before"].(*entgql.Cursor[int]), fc.Args["last"].(*int), fc.Args["where"].(*ent.FriendshipWhereInput)) + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*ent.FriendshipConnection) + fc.Result = res + return ec.marshalNFriendshipConnection2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐFriendshipConnection(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_User_friendships(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "User", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "edges": + return ec.fieldContext_FriendshipConnection_edges(ctx, field) + case "pageInfo": + return ec.fieldContext_FriendshipConnection_pageInfo(ctx, field) + case "totalCount": + return ec.fieldContext_FriendshipConnection_totalCount(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type FriendshipConnection", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field_User_friendships_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) _UserConnection_edges(ctx context.Context, field graphql.CollectedField, obj *ent.UserConnection) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_UserConnection_edges(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Edges, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.([]*ent.UserEdge) + fc.Result = res + return ec.marshalOUserEdge2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUserEdge(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_UserConnection_edges(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "UserConnection", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "node": + return ec.fieldContext_UserEdge_node(ctx, field) + case "cursor": + return ec.fieldContext_UserEdge_cursor(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type UserEdge", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _UserConnection_pageInfo(ctx context.Context, field graphql.CollectedField, obj *ent.UserConnection) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_UserConnection_pageInfo(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.PageInfo, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(entgql.PageInfo[int]) + fc.Result = res + return ec.marshalNPageInfo2entgoᚗioᚋcontribᚋentgqlᚐPageInfo(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_UserConnection_pageInfo(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "UserConnection", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "hasNextPage": + return ec.fieldContext_PageInfo_hasNextPage(ctx, field) + case "hasPreviousPage": + return ec.fieldContext_PageInfo_hasPreviousPage(ctx, field) + case "startCursor": + return ec.fieldContext_PageInfo_startCursor(ctx, field) + case "endCursor": + return ec.fieldContext_PageInfo_endCursor(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type PageInfo", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _UserConnection_totalCount(ctx context.Context, field graphql.CollectedField, obj *ent.UserConnection) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_UserConnection_totalCount(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.TotalCount, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(int) + fc.Result = res + return ec.marshalNInt2int(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_UserConnection_totalCount(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "UserConnection", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Int does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) _UserEdge_node(ctx context.Context, field graphql.CollectedField, obj *ent.UserEdge) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_UserEdge_node(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Node, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*ent.User) + fc.Result = res + return ec.marshalOUser2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUser(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_UserEdge_node(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "UserEdge", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "id": + return ec.fieldContext_User_id(ctx, field) + case "name": + return ec.fieldContext_User_name(ctx, field) + case "username": + return ec.fieldContext_User_username(ctx, field) + case "requiredMetadata": + return ec.fieldContext_User_requiredMetadata(ctx, field) + case "metadata": + return ec.fieldContext_User_metadata(ctx, field) + case "groups": + return ec.fieldContext_User_groups(ctx, field) + case "friends": + return ec.fieldContext_User_friends(ctx, field) + case "friendships": + return ec.fieldContext_User_friendships(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type User", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) _UserEdge_cursor(ctx context.Context, field graphql.CollectedField, obj *ent.UserEdge) (ret graphql.Marshaler) { + fc, err := ec.fieldContext_UserEdge_cursor(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Cursor, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(entgql.Cursor[int]) + fc.Result = res + return ec.marshalNCursor2entgoᚗioᚋcontribᚋentgqlᚐCursor(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext_UserEdge_cursor(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "UserEdge", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Cursor does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___Directive_name(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Directive_name(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Name, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalNString2string(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Directive_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Directive", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___Directive_description(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Directive_description(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Description(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*string) + fc.Result = res + return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Directive_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Directive", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___Directive_locations(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Directive_locations(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Locations, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.([]string) + fc.Result = res + return ec.marshalN__DirectiveLocation2ᚕstringᚄ(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Directive_locations(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Directive", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type __DirectiveLocation does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___Directive_args(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Directive_args(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Args, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.([]introspection.InputValue) + fc.Result = res + return ec.marshalN__InputValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValueᚄ(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Directive_args(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Directive", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "name": + return ec.fieldContext___InputValue_name(ctx, field) + case "description": + return ec.fieldContext___InputValue_description(ctx, field) + case "type": + return ec.fieldContext___InputValue_type(ctx, field) + case "defaultValue": + return ec.fieldContext___InputValue_defaultValue(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __InputValue", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) ___Directive_isRepeatable(ctx context.Context, field graphql.CollectedField, obj *introspection.Directive) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Directive_isRepeatable(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.IsRepeatable, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(bool) + fc.Result = res + return ec.marshalNBoolean2bool(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Directive_isRepeatable(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Directive", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___EnumValue_name(ctx context.Context, field graphql.CollectedField, obj *introspection.EnumValue) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___EnumValue_name(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Name, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalNString2string(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___EnumValue_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__EnumValue", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___EnumValue_description(ctx context.Context, field graphql.CollectedField, obj *introspection.EnumValue) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___EnumValue_description(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Description(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*string) + fc.Result = res + return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___EnumValue_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__EnumValue", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___EnumValue_isDeprecated(ctx context.Context, field graphql.CollectedField, obj *introspection.EnumValue) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___EnumValue_isDeprecated(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.IsDeprecated(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(bool) + fc.Result = res + return ec.marshalNBoolean2bool(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___EnumValue_isDeprecated(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__EnumValue", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___EnumValue_deprecationReason(ctx context.Context, field graphql.CollectedField, obj *introspection.EnumValue) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___EnumValue_deprecationReason(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.DeprecationReason(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*string) + fc.Result = res + return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___EnumValue_deprecationReason(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__EnumValue", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___Field_name(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Field_name(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Name, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalNString2string(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Field_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Field", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___Field_description(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Field_description(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Description(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*string) + fc.Result = res + return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Field_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Field", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___Field_args(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Field_args(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Args, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.([]introspection.InputValue) + fc.Result = res + return ec.marshalN__InputValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValueᚄ(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Field_args(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Field", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "name": + return ec.fieldContext___InputValue_name(ctx, field) + case "description": + return ec.fieldContext___InputValue_description(ctx, field) + case "type": + return ec.fieldContext___InputValue_type(ctx, field) + case "defaultValue": + return ec.fieldContext___InputValue_defaultValue(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __InputValue", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) ___Field_type(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Field_type(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Type, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*introspection.Type) + fc.Result = res + return ec.marshalN__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Field_type(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Field", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "kind": + return ec.fieldContext___Type_kind(ctx, field) + case "name": + return ec.fieldContext___Type_name(ctx, field) + case "description": + return ec.fieldContext___Type_description(ctx, field) + case "fields": + return ec.fieldContext___Type_fields(ctx, field) + case "interfaces": + return ec.fieldContext___Type_interfaces(ctx, field) + case "possibleTypes": + return ec.fieldContext___Type_possibleTypes(ctx, field) + case "enumValues": + return ec.fieldContext___Type_enumValues(ctx, field) + case "inputFields": + return ec.fieldContext___Type_inputFields(ctx, field) + case "ofType": + return ec.fieldContext___Type_ofType(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) ___Field_isDeprecated(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Field_isDeprecated(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.IsDeprecated(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(bool) + fc.Result = res + return ec.marshalNBoolean2bool(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Field_isDeprecated(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Field", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type Boolean does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___Field_deprecationReason(ctx context.Context, field graphql.CollectedField, obj *introspection.Field) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Field_deprecationReason(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.DeprecationReason(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*string) + fc.Result = res + return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Field_deprecationReason(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Field", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___InputValue_name(ctx context.Context, field graphql.CollectedField, obj *introspection.InputValue) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___InputValue_name(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Name, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalNString2string(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___InputValue_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__InputValue", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___InputValue_description(ctx context.Context, field graphql.CollectedField, obj *introspection.InputValue) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___InputValue_description(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Description(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*string) + fc.Result = res + return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___InputValue_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__InputValue", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___InputValue_type(ctx context.Context, field graphql.CollectedField, obj *introspection.InputValue) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___InputValue_type(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Type, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*introspection.Type) + fc.Result = res + return ec.marshalN__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___InputValue_type(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__InputValue", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "kind": + return ec.fieldContext___Type_kind(ctx, field) + case "name": + return ec.fieldContext___Type_name(ctx, field) + case "description": + return ec.fieldContext___Type_description(ctx, field) + case "fields": + return ec.fieldContext___Type_fields(ctx, field) + case "interfaces": + return ec.fieldContext___Type_interfaces(ctx, field) + case "possibleTypes": + return ec.fieldContext___Type_possibleTypes(ctx, field) + case "enumValues": + return ec.fieldContext___Type_enumValues(ctx, field) + case "inputFields": + return ec.fieldContext___Type_inputFields(ctx, field) + case "ofType": + return ec.fieldContext___Type_ofType(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) ___InputValue_defaultValue(ctx context.Context, field graphql.CollectedField, obj *introspection.InputValue) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___InputValue_defaultValue(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.DefaultValue, nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*string) + fc.Result = res + return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___InputValue_defaultValue(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__InputValue", + Field: field, + IsMethod: false, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___Schema_description(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Schema_description(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Description(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*string) + fc.Result = res + return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Schema_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Schema", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___Schema_types(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Schema_types(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Types(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.([]introspection.Type) + fc.Result = res + return ec.marshalN__Type2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐTypeᚄ(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Schema_types(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Schema", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "kind": + return ec.fieldContext___Type_kind(ctx, field) + case "name": + return ec.fieldContext___Type_name(ctx, field) + case "description": + return ec.fieldContext___Type_description(ctx, field) + case "fields": + return ec.fieldContext___Type_fields(ctx, field) + case "interfaces": + return ec.fieldContext___Type_interfaces(ctx, field) + case "possibleTypes": + return ec.fieldContext___Type_possibleTypes(ctx, field) + case "enumValues": + return ec.fieldContext___Type_enumValues(ctx, field) + case "inputFields": + return ec.fieldContext___Type_inputFields(ctx, field) + case "ofType": + return ec.fieldContext___Type_ofType(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) ___Schema_queryType(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Schema_queryType(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.QueryType(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(*introspection.Type) + fc.Result = res + return ec.marshalN__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Schema_queryType(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Schema", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "kind": + return ec.fieldContext___Type_kind(ctx, field) + case "name": + return ec.fieldContext___Type_name(ctx, field) + case "description": + return ec.fieldContext___Type_description(ctx, field) + case "fields": + return ec.fieldContext___Type_fields(ctx, field) + case "interfaces": + return ec.fieldContext___Type_interfaces(ctx, field) + case "possibleTypes": + return ec.fieldContext___Type_possibleTypes(ctx, field) + case "enumValues": + return ec.fieldContext___Type_enumValues(ctx, field) + case "inputFields": + return ec.fieldContext___Type_inputFields(ctx, field) + case "ofType": + return ec.fieldContext___Type_ofType(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) ___Schema_mutationType(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Schema_mutationType(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.MutationType(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*introspection.Type) + fc.Result = res + return ec.marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Schema_mutationType(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Schema", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "kind": + return ec.fieldContext___Type_kind(ctx, field) + case "name": + return ec.fieldContext___Type_name(ctx, field) + case "description": + return ec.fieldContext___Type_description(ctx, field) + case "fields": + return ec.fieldContext___Type_fields(ctx, field) + case "interfaces": + return ec.fieldContext___Type_interfaces(ctx, field) + case "possibleTypes": + return ec.fieldContext___Type_possibleTypes(ctx, field) + case "enumValues": + return ec.fieldContext___Type_enumValues(ctx, field) + case "inputFields": + return ec.fieldContext___Type_inputFields(ctx, field) + case "ofType": + return ec.fieldContext___Type_ofType(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) ___Schema_subscriptionType(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Schema_subscriptionType(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.SubscriptionType(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*introspection.Type) + fc.Result = res + return ec.marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Schema_subscriptionType(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Schema", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "kind": + return ec.fieldContext___Type_kind(ctx, field) + case "name": + return ec.fieldContext___Type_name(ctx, field) + case "description": + return ec.fieldContext___Type_description(ctx, field) + case "fields": + return ec.fieldContext___Type_fields(ctx, field) + case "interfaces": + return ec.fieldContext___Type_interfaces(ctx, field) + case "possibleTypes": + return ec.fieldContext___Type_possibleTypes(ctx, field) + case "enumValues": + return ec.fieldContext___Type_enumValues(ctx, field) + case "inputFields": + return ec.fieldContext___Type_inputFields(ctx, field) + case "ofType": + return ec.fieldContext___Type_ofType(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) ___Schema_directives(ctx context.Context, field graphql.CollectedField, obj *introspection.Schema) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Schema_directives(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Directives(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.([]introspection.Directive) + fc.Result = res + return ec.marshalN__Directive2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐDirectiveᚄ(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Schema_directives(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Schema", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "name": + return ec.fieldContext___Directive_name(ctx, field) + case "description": + return ec.fieldContext___Directive_description(ctx, field) + case "locations": + return ec.fieldContext___Directive_locations(ctx, field) + case "args": + return ec.fieldContext___Directive_args(ctx, field) + case "isRepeatable": + return ec.fieldContext___Directive_isRepeatable(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __Directive", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) ___Type_kind(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Type_kind(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Kind(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + if !graphql.HasFieldError(ctx, fc) { + ec.Errorf(ctx, "must not be null") + } + return graphql.Null + } + res := resTmp.(string) + fc.Result = res + return ec.marshalN__TypeKind2string(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Type_kind(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Type", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type __TypeKind does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___Type_name(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Type_name(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Name(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*string) + fc.Result = res + return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Type_name(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Type", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___Type_description(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Type_description(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Description(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*string) + fc.Result = res + return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Type_description(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Type", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +func (ec *executionContext) ___Type_fields(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Type_fields(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Fields(fc.Args["includeDeprecated"].(bool)), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.([]introspection.Field) + fc.Result = res + return ec.marshalO__Field2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐFieldᚄ(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Type_fields(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Type", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "name": + return ec.fieldContext___Field_name(ctx, field) + case "description": + return ec.fieldContext___Field_description(ctx, field) + case "args": + return ec.fieldContext___Field_args(ctx, field) + case "type": + return ec.fieldContext___Field_type(ctx, field) + case "isDeprecated": + return ec.fieldContext___Field_isDeprecated(ctx, field) + case "deprecationReason": + return ec.fieldContext___Field_deprecationReason(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __Field", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field___Type_fields_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) ___Type_interfaces(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Type_interfaces(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.Interfaces(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.([]introspection.Type) + fc.Result = res + return ec.marshalO__Type2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐTypeᚄ(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Type_interfaces(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Type", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "kind": + return ec.fieldContext___Type_kind(ctx, field) + case "name": + return ec.fieldContext___Type_name(ctx, field) + case "description": + return ec.fieldContext___Type_description(ctx, field) + case "fields": + return ec.fieldContext___Type_fields(ctx, field) + case "interfaces": + return ec.fieldContext___Type_interfaces(ctx, field) + case "possibleTypes": + return ec.fieldContext___Type_possibleTypes(ctx, field) + case "enumValues": + return ec.fieldContext___Type_enumValues(ctx, field) + case "inputFields": + return ec.fieldContext___Type_inputFields(ctx, field) + case "ofType": + return ec.fieldContext___Type_ofType(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) ___Type_possibleTypes(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Type_possibleTypes(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.PossibleTypes(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.([]introspection.Type) + fc.Result = res + return ec.marshalO__Type2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐTypeᚄ(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Type_possibleTypes(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Type", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "kind": + return ec.fieldContext___Type_kind(ctx, field) + case "name": + return ec.fieldContext___Type_name(ctx, field) + case "description": + return ec.fieldContext___Type_description(ctx, field) + case "fields": + return ec.fieldContext___Type_fields(ctx, field) + case "interfaces": + return ec.fieldContext___Type_interfaces(ctx, field) + case "possibleTypes": + return ec.fieldContext___Type_possibleTypes(ctx, field) + case "enumValues": + return ec.fieldContext___Type_enumValues(ctx, field) + case "inputFields": + return ec.fieldContext___Type_inputFields(ctx, field) + case "ofType": + return ec.fieldContext___Type_ofType(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) ___Type_enumValues(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Type_enumValues(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.EnumValues(fc.Args["includeDeprecated"].(bool)), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.([]introspection.EnumValue) + fc.Result = res + return ec.marshalO__EnumValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐEnumValueᚄ(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Type_enumValues(ctx context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Type", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "name": + return ec.fieldContext___EnumValue_name(ctx, field) + case "description": + return ec.fieldContext___EnumValue_description(ctx, field) + case "isDeprecated": + return ec.fieldContext___EnumValue_isDeprecated(ctx, field) + case "deprecationReason": + return ec.fieldContext___EnumValue_deprecationReason(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __EnumValue", field.Name) + }, + } + defer func() { + if r := recover(); r != nil { + err = ec.Recover(ctx, r) + ec.Error(ctx, err) + } + }() + ctx = graphql.WithFieldContext(ctx, fc) + if fc.Args, err = ec.field___Type_enumValues_args(ctx, field.ArgumentMap(ec.Variables)); err != nil { + ec.Error(ctx, err) + return fc, err + } + return fc, nil +} + +func (ec *executionContext) ___Type_inputFields(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Type_inputFields(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.InputFields(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.([]introspection.InputValue) + fc.Result = res + return ec.marshalO__InputValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValueᚄ(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Type_inputFields(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Type", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "name": + return ec.fieldContext___InputValue_name(ctx, field) + case "description": + return ec.fieldContext___InputValue_description(ctx, field) + case "type": + return ec.fieldContext___InputValue_type(ctx, field) + case "defaultValue": + return ec.fieldContext___InputValue_defaultValue(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __InputValue", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) ___Type_ofType(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Type_ofType(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.OfType(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*introspection.Type) + fc.Result = res + return ec.marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Type_ofType(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Type", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + switch field.Name { + case "kind": + return ec.fieldContext___Type_kind(ctx, field) + case "name": + return ec.fieldContext___Type_name(ctx, field) + case "description": + return ec.fieldContext___Type_description(ctx, field) + case "fields": + return ec.fieldContext___Type_fields(ctx, field) + case "interfaces": + return ec.fieldContext___Type_interfaces(ctx, field) + case "possibleTypes": + return ec.fieldContext___Type_possibleTypes(ctx, field) + case "enumValues": + return ec.fieldContext___Type_enumValues(ctx, field) + case "inputFields": + return ec.fieldContext___Type_inputFields(ctx, field) + case "ofType": + return ec.fieldContext___Type_ofType(ctx, field) + case "specifiedByURL": + return ec.fieldContext___Type_specifiedByURL(ctx, field) + } + return nil, fmt.Errorf("no field named %q was found under type __Type", field.Name) + }, + } + return fc, nil +} + +func (ec *executionContext) ___Type_specifiedByURL(ctx context.Context, field graphql.CollectedField, obj *introspection.Type) (ret graphql.Marshaler) { + fc, err := ec.fieldContext___Type_specifiedByURL(ctx, field) + if err != nil { + return graphql.Null + } + ctx = graphql.WithFieldContext(ctx, fc) + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = graphql.Null + } + }() + resTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (any, error) { + ctx = rctx // use context from middleware stack in children + return obj.SpecifiedByURL(), nil + }) + if err != nil { + ec.Error(ctx, err) + return graphql.Null + } + if resTmp == nil { + return graphql.Null + } + res := resTmp.(*string) + fc.Result = res + return ec.marshalOString2ᚖstring(ctx, field.Selections, res) +} + +func (ec *executionContext) fieldContext___Type_specifiedByURL(_ context.Context, field graphql.CollectedField) (fc *graphql.FieldContext, err error) { + fc = &graphql.FieldContext{ + Object: "__Type", + Field: field, + IsMethod: true, + IsResolver: false, + Child: func(ctx context.Context, field graphql.CollectedField) (*graphql.FieldContext, error) { + return nil, errors.New("field of type String does not have child fields") + }, + } + return fc, nil +} + +// endregion **************************** field.gotpl ***************************** + +// region **************************** input.gotpl ***************************** + +func (ec *executionContext) unmarshalInputBillProductWhereInput(ctx context.Context, obj any) (ent.BillProductWhereInput, error) { + var it ent.BillProductWhereInput + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"not", "and", "or", "id", "idNEQ", "idIn", "idNotIn", "idGT", "idGTE", "idLT", "idLTE", "name", "nameNEQ", "nameIn", "nameNotIn", "nameGT", "nameGTE", "nameLT", "nameLTE", "nameContains", "nameHasPrefix", "nameHasSuffix", "nameEqualFold", "nameContainsFold", "sku", "skuNEQ", "skuIn", "skuNotIn", "skuGT", "skuGTE", "skuLT", "skuLTE", "skuContains", "skuHasPrefix", "skuHasSuffix", "skuEqualFold", "skuContainsFold", "quantity", "quantityNEQ", "quantityIn", "quantityNotIn", "quantityGT", "quantityGTE", "quantityLT", "quantityLTE"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "not": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("not")) + data, err := ec.unmarshalOBillProductWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐBillProductWhereInput(ctx, v) + if err != nil { + return it, err + } + it.Not = data + case "and": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("and")) + data, err := ec.unmarshalOBillProductWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐBillProductWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.And = data + case "or": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("or")) + data, err := ec.unmarshalOBillProductWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐBillProductWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.Or = data + case "id": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.ID = data + case "idNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idNEQ")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDNEQ = data + case "idIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idIn")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.IDIn = data + case "idNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idNotIn")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.IDNotIn = data + case "idGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idGT")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDGT = data + case "idGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idGTE")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDGTE = data + case "idLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idLT")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDLT = data + case "idLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idLTE")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDLTE = data + case "name": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("name")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Name = data + case "nameNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameNEQ")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameNEQ = data + case "nameIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameIn")) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.NameIn = data + case "nameNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameNotIn")) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.NameNotIn = data + case "nameGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameGT")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameGT = data + case "nameGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameGTE")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameGTE = data + case "nameLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameLT")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameLT = data + case "nameLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameLTE")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameLTE = data + case "nameContains": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameContains")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameContains = data + case "nameHasPrefix": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameHasPrefix")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameHasPrefix = data + case "nameHasSuffix": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameHasSuffix")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameHasSuffix = data + case "nameEqualFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameEqualFold")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameEqualFold = data + case "nameContainsFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameContainsFold")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameContainsFold = data + case "sku": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("sku")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Sku = data + case "skuNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("skuNEQ")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.SkuNEQ = data + case "skuIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("skuIn")) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.SkuIn = data + case "skuNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("skuNotIn")) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.SkuNotIn = data + case "skuGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("skuGT")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.SkuGT = data + case "skuGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("skuGTE")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.SkuGTE = data + case "skuLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("skuLT")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.SkuLT = data + case "skuLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("skuLTE")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.SkuLTE = data + case "skuContains": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("skuContains")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.SkuContains = data + case "skuHasPrefix": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("skuHasPrefix")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.SkuHasPrefix = data + case "skuHasSuffix": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("skuHasSuffix")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.SkuHasSuffix = data + case "skuEqualFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("skuEqualFold")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.SkuEqualFold = data + case "skuContainsFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("skuContainsFold")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.SkuContainsFold = data + case "quantity": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("quantity")) + data, err := ec.unmarshalOUint642ᚖuint64(ctx, v) + if err != nil { + return it, err + } + it.Quantity = data + case "quantityNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("quantityNEQ")) + data, err := ec.unmarshalOUint642ᚖuint64(ctx, v) + if err != nil { + return it, err + } + it.QuantityNEQ = data + case "quantityIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("quantityIn")) + data, err := ec.unmarshalOUint642ᚕuint64ᚄ(ctx, v) + if err != nil { + return it, err + } + it.QuantityIn = data + case "quantityNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("quantityNotIn")) + data, err := ec.unmarshalOUint642ᚕuint64ᚄ(ctx, v) + if err != nil { + return it, err + } + it.QuantityNotIn = data + case "quantityGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("quantityGT")) + data, err := ec.unmarshalOUint642ᚖuint64(ctx, v) + if err != nil { + return it, err + } + it.QuantityGT = data + case "quantityGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("quantityGTE")) + data, err := ec.unmarshalOUint642ᚖuint64(ctx, v) + if err != nil { + return it, err + } + it.QuantityGTE = data + case "quantityLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("quantityLT")) + data, err := ec.unmarshalOUint642ᚖuint64(ctx, v) + if err != nil { + return it, err + } + it.QuantityLT = data + case "quantityLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("quantityLTE")) + data, err := ec.unmarshalOUint642ᚖuint64(ctx, v) + if err != nil { + return it, err + } + it.QuantityLTE = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputCategoryConfigInput(ctx context.Context, obj any) (schematype.CategoryConfig, error) { + var it schematype.CategoryConfig + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"maxMembers"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "maxMembers": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("maxMembers")) + data, err := ec.unmarshalOInt2int(ctx, v) + if err != nil { + return it, err + } + it.MaxMembers = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputCategoryOrder(ctx context.Context, obj any) (ent.CategoryOrder, error) { + var it ent.CategoryOrder + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { + asMap[k] = v + } + + if _, present := asMap["direction"]; !present { + asMap["direction"] = "ASC" + } + + fieldsInOrder := [...]string{"direction", "field"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "direction": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("direction")) + data, err := ec.unmarshalNOrderDirection2entgoᚗioᚋcontribᚋentgqlᚐOrderDirection(ctx, v) + if err != nil { + return it, err + } + it.Direction = data + case "field": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("field")) + data, err := ec.unmarshalNCategoryOrderField2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategoryOrderField(ctx, v) + if err != nil { + return it, err + } + it.Field = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputCategoryTypesInput(ctx context.Context, obj any) (schematype.CategoryTypes, error) { + var it schematype.CategoryTypes + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"public"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "public": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("public")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.Public = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputCategoryWhereInput(ctx context.Context, obj any) (ent.CategoryWhereInput, error) { + var it ent.CategoryWhereInput + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"not", "and", "or", "id", "idNEQ", "idIn", "idNotIn", "idGT", "idGTE", "idLT", "idLTE", "text", "textNEQ", "textIn", "textNotIn", "textGT", "textGTE", "textLT", "textLTE", "textContains", "textHasPrefix", "textHasSuffix", "textEqualFold", "textContainsFold", "status", "statusNEQ", "statusIn", "statusNotIn", "config", "configNEQ", "configIn", "configNotIn", "configGT", "configGTE", "configLT", "configLTE", "configIsNil", "configNotNil", "duration", "durationNEQ", "durationIn", "durationNotIn", "durationGT", "durationGTE", "durationLT", "durationLTE", "durationIsNil", "durationNotNil", "count", "countNEQ", "countIn", "countNotIn", "countGT", "countGTE", "countLT", "countLTE", "countIsNil", "countNotNil", "hasTodos", "hasTodosWith", "hasSubCategories", "hasSubCategoriesWith"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "not": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("not")) + data, err := ec.unmarshalOCategoryWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategoryWhereInput(ctx, v) + if err != nil { + return it, err + } + it.Not = data + case "and": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("and")) + data, err := ec.unmarshalOCategoryWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategoryWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.And = data + case "or": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("or")) + data, err := ec.unmarshalOCategoryWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategoryWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.Or = data + case "id": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.ID = data + case "idNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idNEQ")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDNEQ = data + case "idIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idIn")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.IDIn = data + case "idNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idNotIn")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.IDNotIn = data + case "idGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idGT")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDGT = data + case "idGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idGTE")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDGTE = data + case "idLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idLT")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDLT = data + case "idLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idLTE")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDLTE = data + case "text": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("text")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Text = data + case "textNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("textNEQ")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.TextNEQ = data + case "textIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("textIn")) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.TextIn = data + case "textNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("textNotIn")) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.TextNotIn = data + case "textGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("textGT")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.TextGT = data + case "textGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("textGTE")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.TextGTE = data + case "textLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("textLT")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.TextLT = data + case "textLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("textLTE")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.TextLTE = data + case "textContains": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("textContains")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.TextContains = data + case "textHasPrefix": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("textHasPrefix")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.TextHasPrefix = data + case "textHasSuffix": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("textHasSuffix")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.TextHasSuffix = data + case "textEqualFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("textEqualFold")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.TextEqualFold = data + case "textContainsFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("textContainsFold")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.TextContainsFold = data + case "status": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("status")) + data, err := ec.unmarshalOCategoryStatus2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋcategoryᚐStatus(ctx, v) + if err != nil { + return it, err + } + it.Status = data + case "statusNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("statusNEQ")) + data, err := ec.unmarshalOCategoryStatus2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋcategoryᚐStatus(ctx, v) + if err != nil { + return it, err + } + it.StatusNEQ = data + case "statusIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("statusIn")) + data, err := ec.unmarshalOCategoryStatus2ᚕentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋcategoryᚐStatusᚄ(ctx, v) + if err != nil { + return it, err + } + it.StatusIn = data + case "statusNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("statusNotIn")) + data, err := ec.unmarshalOCategoryStatus2ᚕentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋcategoryᚐStatusᚄ(ctx, v) + if err != nil { + return it, err + } + it.StatusNotIn = data + case "config": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("config")) + data, err := ec.unmarshalOCategoryConfigInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋschematypeᚐCategoryConfig(ctx, v) + if err != nil { + return it, err + } + it.Config = data + case "configNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("configNEQ")) + data, err := ec.unmarshalOCategoryConfigInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋschematypeᚐCategoryConfig(ctx, v) + if err != nil { + return it, err + } + it.ConfigNEQ = data + case "configIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("configIn")) + data, err := ec.unmarshalOCategoryConfigInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋschematypeᚐCategoryConfigᚄ(ctx, v) + if err != nil { + return it, err + } + it.ConfigIn = data + case "configNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("configNotIn")) + data, err := ec.unmarshalOCategoryConfigInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋschematypeᚐCategoryConfigᚄ(ctx, v) + if err != nil { + return it, err + } + it.ConfigNotIn = data + case "configGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("configGT")) + data, err := ec.unmarshalOCategoryConfigInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋschematypeᚐCategoryConfig(ctx, v) + if err != nil { + return it, err + } + it.ConfigGT = data + case "configGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("configGTE")) + data, err := ec.unmarshalOCategoryConfigInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋschematypeᚐCategoryConfig(ctx, v) + if err != nil { + return it, err + } + it.ConfigGTE = data + case "configLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("configLT")) + data, err := ec.unmarshalOCategoryConfigInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋschematypeᚐCategoryConfig(ctx, v) + if err != nil { + return it, err + } + it.ConfigLT = data + case "configLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("configLTE")) + data, err := ec.unmarshalOCategoryConfigInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋschematypeᚐCategoryConfig(ctx, v) + if err != nil { + return it, err + } + it.ConfigLTE = data + case "configIsNil": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("configIsNil")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.ConfigIsNil = data + case "configNotNil": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("configNotNil")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.ConfigNotNil = data + case "duration": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("duration")) + data, err := ec.unmarshalODuration2ᚖtimeᚐDuration(ctx, v) + if err != nil { + return it, err + } + it.Duration = data + case "durationNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("durationNEQ")) + data, err := ec.unmarshalODuration2ᚖtimeᚐDuration(ctx, v) + if err != nil { + return it, err + } + it.DurationNEQ = data + case "durationIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("durationIn")) + data, err := ec.unmarshalODuration2ᚕtimeᚐDurationᚄ(ctx, v) + if err != nil { + return it, err + } + it.DurationIn = data + case "durationNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("durationNotIn")) + data, err := ec.unmarshalODuration2ᚕtimeᚐDurationᚄ(ctx, v) + if err != nil { + return it, err + } + it.DurationNotIn = data + case "durationGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("durationGT")) + data, err := ec.unmarshalODuration2ᚖtimeᚐDuration(ctx, v) + if err != nil { + return it, err + } + it.DurationGT = data + case "durationGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("durationGTE")) + data, err := ec.unmarshalODuration2ᚖtimeᚐDuration(ctx, v) + if err != nil { + return it, err + } + it.DurationGTE = data + case "durationLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("durationLT")) + data, err := ec.unmarshalODuration2ᚖtimeᚐDuration(ctx, v) + if err != nil { + return it, err + } + it.DurationLT = data + case "durationLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("durationLTE")) + data, err := ec.unmarshalODuration2ᚖtimeᚐDuration(ctx, v) + if err != nil { + return it, err + } + it.DurationLTE = data + case "durationIsNil": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("durationIsNil")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.DurationIsNil = data + case "durationNotNil": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("durationNotNil")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.DurationNotNil = data + case "count": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("count")) + data, err := ec.unmarshalOUint642ᚖuint64(ctx, v) + if err != nil { + return it, err + } + it.Count = data + case "countNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("countNEQ")) + data, err := ec.unmarshalOUint642ᚖuint64(ctx, v) + if err != nil { + return it, err + } + it.CountNEQ = data + case "countIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("countIn")) + data, err := ec.unmarshalOUint642ᚕuint64ᚄ(ctx, v) + if err != nil { + return it, err + } + it.CountIn = data + case "countNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("countNotIn")) + data, err := ec.unmarshalOUint642ᚕuint64ᚄ(ctx, v) + if err != nil { + return it, err + } + it.CountNotIn = data + case "countGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("countGT")) + data, err := ec.unmarshalOUint642ᚖuint64(ctx, v) + if err != nil { + return it, err + } + it.CountGT = data + case "countGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("countGTE")) + data, err := ec.unmarshalOUint642ᚖuint64(ctx, v) + if err != nil { + return it, err + } + it.CountGTE = data + case "countLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("countLT")) + data, err := ec.unmarshalOUint642ᚖuint64(ctx, v) + if err != nil { + return it, err + } + it.CountLT = data + case "countLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("countLTE")) + data, err := ec.unmarshalOUint642ᚖuint64(ctx, v) + if err != nil { + return it, err + } + it.CountLTE = data + case "countIsNil": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("countIsNil")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.CountIsNil = data + case "countNotNil": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("countNotNil")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.CountNotNil = data + case "hasTodos": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hasTodos")) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) + if err != nil { + return it, err + } + it.HasTodos = data + case "hasTodosWith": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hasTodosWith")) + data, err := ec.unmarshalOTodoWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.HasTodosWith = data + case "hasSubCategories": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hasSubCategories")) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) + if err != nil { + return it, err + } + it.HasSubCategories = data + case "hasSubCategoriesWith": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hasSubCategoriesWith")) + data, err := ec.unmarshalOCategoryWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategoryWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.HasSubCategoriesWith = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputCreateCategoryInput(ctx context.Context, obj any) (ent.CreateCategoryInput, error) { + var it ent.CreateCategoryInput + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"text", "status", "config", "types", "duration", "count", "strings", "todoIDs", "subCategoryIDs", "createTodos"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "text": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("text")) + data, err := ec.unmarshalNString2string(ctx, v) + if err != nil { + return it, err + } + it.Text = data + case "status": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("status")) + data, err := ec.unmarshalNCategoryStatus2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋcategoryᚐStatus(ctx, v) + if err != nil { + return it, err + } + it.Status = data + case "config": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("config")) + data, err := ec.unmarshalOCategoryConfigInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋschematypeᚐCategoryConfig(ctx, v) + if err != nil { + return it, err + } + it.Config = data + case "types": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("types")) + data, err := ec.unmarshalOCategoryTypesInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋschematypeᚐCategoryTypes(ctx, v) + if err != nil { + return it, err + } + it.Types = data + case "duration": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("duration")) + data, err := ec.unmarshalODuration2ᚖtimeᚐDuration(ctx, v) + if err != nil { + return it, err + } + it.Duration = data + case "count": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("count")) + data, err := ec.unmarshalOUint642ᚖuint64(ctx, v) + if err != nil { + return it, err + } + it.Count = data + case "strings": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("strings")) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.Strings = data + case "todoIDs": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("todoIDs")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.TodoIDs = data + case "subCategoryIDs": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("subCategoryIDs")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.SubCategoryIDs = data + case "createTodos": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("createTodos")) + data, err := ec.unmarshalOCreateTodoInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCreateTodoInputᚄ(ctx, v) + if err != nil { + return it, err + } + if err = ec.resolvers.CreateCategoryInput().CreateTodos(ctx, &it, data); err != nil { + return it, err + } + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputCreateTodoInput(ctx context.Context, obj any) (ent.CreateTodoInput, error) { + var it ent.CreateTodoInput + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"status", "priority", "text", "init", "value", "parentID", "childIDs", "categoryID", "secretID"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "status": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("status")) + data, err := ec.unmarshalNTodoStatus2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋtodoᚐStatus(ctx, v) + if err != nil { + return it, err + } + it.Status = data + case "priority": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("priority")) + data, err := ec.unmarshalOInt2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.Priority = data + case "text": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("text")) + data, err := ec.unmarshalNString2string(ctx, v) + if err != nil { + return it, err + } + it.Text = data + case "init": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("init")) + data, err := ec.unmarshalOMap2map(ctx, v) + if err != nil { + return it, err + } + it.Init = data + case "value": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("value")) + data, err := ec.unmarshalOInt2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.Value = data + case "parentID": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("parentID")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.ParentID = data + case "childIDs": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("childIDs")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.ChildIDs = data + case "categoryID": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("categoryID")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.CategoryID = data + case "secretID": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("secretID")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.SecretID = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputCreateUserInput(ctx context.Context, obj any) (ent.CreateUserInput, error) { + var it ent.CreateUserInput + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"name", "username", "password", "requiredMetadata", "metadata", "groupIDs", "friendIDs"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "name": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("name")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Name = data + case "username": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("username")) + data, err := ec.unmarshalOUUID2ᚖgithubᚗcomᚋgoogleᚋuuidᚐUUID(ctx, v) + if err != nil { + return it, err + } + it.Username = data + case "password": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("password")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Password = data + case "requiredMetadata": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("requiredMetadata")) + data, err := ec.unmarshalNMap2map(ctx, v) + if err != nil { + return it, err + } + it.RequiredMetadata = data + case "metadata": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("metadata")) + data, err := ec.unmarshalOMap2map(ctx, v) + if err != nil { + return it, err + } + it.Metadata = data + case "groupIDs": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("groupIDs")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.GroupIDs = data + case "friendIDs": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("friendIDs")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.FriendIDs = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputFriendshipWhereInput(ctx context.Context, obj any) (ent.FriendshipWhereInput, error) { + var it ent.FriendshipWhereInput + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"not", "and", "or", "id", "idNEQ", "idIn", "idNotIn", "idGT", "idGTE", "idLT", "idLTE", "createdAt", "createdAtNEQ", "createdAtIn", "createdAtNotIn", "createdAtGT", "createdAtGTE", "createdAtLT", "createdAtLTE"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "not": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("not")) + data, err := ec.unmarshalOFriendshipWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐFriendshipWhereInput(ctx, v) + if err != nil { + return it, err + } + it.Not = data + case "and": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("and")) + data, err := ec.unmarshalOFriendshipWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐFriendshipWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.And = data + case "or": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("or")) + data, err := ec.unmarshalOFriendshipWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐFriendshipWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.Or = data + case "id": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.ID = data + case "idNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idNEQ")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDNEQ = data + case "idIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idIn")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.IDIn = data + case "idNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idNotIn")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.IDNotIn = data + case "idGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idGT")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDGT = data + case "idGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idGTE")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDGTE = data + case "idLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idLT")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDLT = data + case "idLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idLTE")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDLTE = data + case "createdAt": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("createdAt")) + data, err := ec.unmarshalOTime2ᚖtimeᚐTime(ctx, v) + if err != nil { + return it, err + } + it.CreatedAt = data + case "createdAtNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("createdAtNEQ")) + data, err := ec.unmarshalOTime2ᚖtimeᚐTime(ctx, v) + if err != nil { + return it, err + } + it.CreatedAtNEQ = data + case "createdAtIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("createdAtIn")) + data, err := ec.unmarshalOTime2ᚕtimeᚐTimeᚄ(ctx, v) + if err != nil { + return it, err + } + it.CreatedAtIn = data + case "createdAtNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("createdAtNotIn")) + data, err := ec.unmarshalOTime2ᚕtimeᚐTimeᚄ(ctx, v) + if err != nil { + return it, err + } + it.CreatedAtNotIn = data + case "createdAtGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("createdAtGT")) + data, err := ec.unmarshalOTime2ᚖtimeᚐTime(ctx, v) + if err != nil { + return it, err + } + it.CreatedAtGT = data + case "createdAtGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("createdAtGTE")) + data, err := ec.unmarshalOTime2ᚖtimeᚐTime(ctx, v) + if err != nil { + return it, err + } + it.CreatedAtGTE = data + case "createdAtLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("createdAtLT")) + data, err := ec.unmarshalOTime2ᚖtimeᚐTime(ctx, v) + if err != nil { + return it, err + } + it.CreatedAtLT = data + case "createdAtLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("createdAtLTE")) + data, err := ec.unmarshalOTime2ᚖtimeᚐTime(ctx, v) + if err != nil { + return it, err + } + it.CreatedAtLTE = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputGroupWhereInput(ctx context.Context, obj any) (ent.GroupWhereInput, error) { + var it ent.GroupWhereInput + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"not", "and", "or", "id", "idNEQ", "idIn", "idNotIn", "idGT", "idGTE", "idLT", "idLTE", "name", "nameNEQ", "nameIn", "nameNotIn", "nameGT", "nameGTE", "nameLT", "nameLTE", "nameContains", "nameHasPrefix", "nameHasSuffix", "nameEqualFold", "nameContainsFold", "hasUsers", "hasUsersWith"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "not": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("not")) + data, err := ec.unmarshalOGroupWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐGroupWhereInput(ctx, v) + if err != nil { + return it, err + } + it.Not = data + case "and": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("and")) + data, err := ec.unmarshalOGroupWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐGroupWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.And = data + case "or": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("or")) + data, err := ec.unmarshalOGroupWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐGroupWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.Or = data + case "id": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.ID = data + case "idNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idNEQ")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDNEQ = data + case "idIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idIn")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.IDIn = data + case "idNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idNotIn")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.IDNotIn = data + case "idGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idGT")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDGT = data + case "idGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idGTE")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDGTE = data + case "idLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idLT")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDLT = data + case "idLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idLTE")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDLTE = data + case "name": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("name")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Name = data + case "nameNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameNEQ")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameNEQ = data + case "nameIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameIn")) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.NameIn = data + case "nameNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameNotIn")) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.NameNotIn = data + case "nameGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameGT")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameGT = data + case "nameGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameGTE")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameGTE = data + case "nameLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameLT")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameLT = data + case "nameLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameLTE")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameLTE = data + case "nameContains": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameContains")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameContains = data + case "nameHasPrefix": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameHasPrefix")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameHasPrefix = data + case "nameHasSuffix": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameHasSuffix")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameHasSuffix = data + case "nameEqualFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameEqualFold")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameEqualFold = data + case "nameContainsFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameContainsFold")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameContainsFold = data + case "hasUsers": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hasUsers")) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) + if err != nil { + return it, err + } + it.HasUsers = data + case "hasUsersWith": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hasUsersWith")) + data, err := ec.unmarshalOUserWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUserWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.HasUsersWith = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputOneToManyOrder(ctx context.Context, obj any) (ent.OneToManyOrder, error) { + var it ent.OneToManyOrder + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { + asMap[k] = v + } + + if _, present := asMap["direction"]; !present { + asMap["direction"] = "ASC" + } + + fieldsInOrder := [...]string{"direction", "field"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "direction": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("direction")) + data, err := ec.unmarshalNOrderDirection2entgoᚗioᚋcontribᚋentgqlᚐOrderDirection(ctx, v) + if err != nil { + return it, err + } + it.Direction = data + case "field": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("field")) + data, err := ec.unmarshalNOneToManyOrderField2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToManyOrderField(ctx, v) + if err != nil { + return it, err + } + it.Field = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputOneToManyWhereInput(ctx context.Context, obj any) (ent.OneToManyWhereInput, error) { + var it ent.OneToManyWhereInput + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"not", "and", "or", "id", "idNEQ", "idIn", "idNotIn", "idGT", "idGTE", "idLT", "idLTE", "name", "nameNEQ", "nameIn", "nameNotIn", "nameGT", "nameGTE", "nameLT", "nameLTE", "nameContains", "nameHasPrefix", "nameHasSuffix", "nameEqualFold", "nameContainsFold", "field2", "field2NEQ", "field2In", "field2NotIn", "field2GT", "field2GTE", "field2LT", "field2LTE", "field2Contains", "field2HasPrefix", "field2HasSuffix", "field2IsNil", "field2NotNil", "field2EqualFold", "field2ContainsFold", "hasParent", "hasParentWith", "hasChildren", "hasChildrenWith"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "not": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("not")) + data, err := ec.unmarshalOOneToManyWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToManyWhereInput(ctx, v) + if err != nil { + return it, err + } + it.Not = data + case "and": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("and")) + data, err := ec.unmarshalOOneToManyWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToManyWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.And = data + case "or": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("or")) + data, err := ec.unmarshalOOneToManyWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToManyWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.Or = data + case "id": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.ID = data + case "idNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idNEQ")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDNEQ = data + case "idIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idIn")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.IDIn = data + case "idNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idNotIn")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.IDNotIn = data + case "idGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idGT")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDGT = data + case "idGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idGTE")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDGTE = data + case "idLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idLT")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDLT = data + case "idLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idLTE")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDLTE = data + case "name": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("name")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Name = data + case "nameNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameNEQ")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameNEQ = data + case "nameIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameIn")) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.NameIn = data + case "nameNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameNotIn")) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.NameNotIn = data + case "nameGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameGT")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameGT = data + case "nameGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameGTE")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameGTE = data + case "nameLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameLT")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameLT = data + case "nameLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameLTE")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameLTE = data + case "nameContains": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameContains")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameContains = data + case "nameHasPrefix": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameHasPrefix")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameHasPrefix = data + case "nameHasSuffix": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameHasSuffix")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameHasSuffix = data + case "nameEqualFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameEqualFold")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameEqualFold = data + case "nameContainsFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameContainsFold")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameContainsFold = data + case "field2": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("field2")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Field2 = data + case "field2NEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("field2NEQ")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Field2NEQ = data + case "field2In": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("field2In")) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.Field2In = data + case "field2NotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("field2NotIn")) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.Field2NotIn = data + case "field2GT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("field2GT")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Field2GT = data + case "field2GTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("field2GTE")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Field2GTE = data + case "field2LT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("field2LT")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Field2LT = data + case "field2LTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("field2LTE")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Field2LTE = data + case "field2Contains": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("field2Contains")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Field2Contains = data + case "field2HasPrefix": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("field2HasPrefix")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Field2HasPrefix = data + case "field2HasSuffix": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("field2HasSuffix")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Field2HasSuffix = data + case "field2IsNil": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("field2IsNil")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.Field2IsNil = data + case "field2NotNil": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("field2NotNil")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.Field2NotNil = data + case "field2EqualFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("field2EqualFold")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Field2EqualFold = data + case "field2ContainsFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("field2ContainsFold")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Field2ContainsFold = data + case "hasParent": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hasParent")) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) + if err != nil { + return it, err + } + it.HasParent = data + case "hasParentWith": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hasParentWith")) + data, err := ec.unmarshalOOneToManyWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToManyWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.HasParentWith = data + case "hasChildren": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hasChildren")) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) + if err != nil { + return it, err + } + it.HasChildren = data + case "hasChildrenWith": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hasChildrenWith")) + data, err := ec.unmarshalOOneToManyWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToManyWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.HasChildrenWith = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputOrganizationWhereInput(ctx context.Context, obj any) (ent.OrganizationWhereInput, error) { + var it ent.OrganizationWhereInput + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"not", "and", "or", "id", "idNEQ", "idIn", "idNotIn", "idGT", "idGTE", "idLT", "idLTE", "name", "nameNEQ", "nameIn", "nameNotIn", "nameGT", "nameGTE", "nameLT", "nameLTE", "nameContains", "nameHasPrefix", "nameHasSuffix", "nameEqualFold", "nameContainsFold"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "not": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("not")) + data, err := ec.unmarshalOOrganizationWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOrganizationWhereInput(ctx, v) + if err != nil { + return it, err + } + it.Not = data + case "and": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("and")) + data, err := ec.unmarshalOOrganizationWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOrganizationWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.And = data + case "or": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("or")) + data, err := ec.unmarshalOOrganizationWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOrganizationWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.Or = data + case "id": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.ID = data + case "idNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idNEQ")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDNEQ = data + case "idIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idIn")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.IDIn = data + case "idNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idNotIn")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.IDNotIn = data + case "idGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idGT")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDGT = data + case "idGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idGTE")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDGTE = data + case "idLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idLT")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDLT = data + case "idLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idLTE")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDLTE = data + case "name": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("name")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Name = data + case "nameNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameNEQ")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameNEQ = data + case "nameIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameIn")) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.NameIn = data + case "nameNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameNotIn")) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.NameNotIn = data + case "nameGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameGT")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameGT = data + case "nameGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameGTE")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameGTE = data + case "nameLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameLT")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameLT = data + case "nameLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameLTE")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameLTE = data + case "nameContains": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameContains")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameContains = data + case "nameHasPrefix": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameHasPrefix")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameHasPrefix = data + case "nameHasSuffix": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameHasSuffix")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameHasSuffix = data + case "nameEqualFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameEqualFold")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameEqualFold = data + case "nameContainsFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameContainsFold")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameContainsFold = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputProjectWhereInput(ctx context.Context, obj any) (ent.ProjectWhereInput, error) { + var it ent.ProjectWhereInput + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"not", "and", "or", "id", "idNEQ", "idIn", "idNotIn", "idGT", "idGTE", "idLT", "idLTE", "hasTodos", "hasTodosWith"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "not": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("not")) + data, err := ec.unmarshalOProjectWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐProjectWhereInput(ctx, v) + if err != nil { + return it, err + } + it.Not = data + case "and": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("and")) + data, err := ec.unmarshalOProjectWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐProjectWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.And = data + case "or": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("or")) + data, err := ec.unmarshalOProjectWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐProjectWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.Or = data + case "id": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.ID = data + case "idNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idNEQ")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDNEQ = data + case "idIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idIn")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.IDIn = data + case "idNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idNotIn")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.IDNotIn = data + case "idGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idGT")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDGT = data + case "idGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idGTE")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDGTE = data + case "idLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idLT")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDLT = data + case "idLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idLTE")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDLTE = data + case "hasTodos": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hasTodos")) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) + if err != nil { + return it, err + } + it.HasTodos = data + case "hasTodosWith": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hasTodosWith")) + data, err := ec.unmarshalOTodoWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.HasTodosWith = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputTodoOrder(ctx context.Context, obj any) (ent.TodoOrder, error) { + var it ent.TodoOrder + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { + asMap[k] = v + } + + if _, present := asMap["direction"]; !present { + asMap["direction"] = "ASC" + } + + fieldsInOrder := [...]string{"direction", "field"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "direction": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("direction")) + data, err := ec.unmarshalNOrderDirection2entgoᚗioᚋcontribᚋentgqlᚐOrderDirection(ctx, v) + if err != nil { + return it, err + } + it.Direction = data + case "field": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("field")) + data, err := ec.unmarshalNTodoOrderField2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoOrderField(ctx, v) + if err != nil { + return it, err + } + it.Field = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputTodoWhereInput(ctx context.Context, obj any) (ent.TodoWhereInput, error) { + var it ent.TodoWhereInput + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"not", "and", "or", "id", "idNEQ", "idIn", "idNotIn", "idGT", "idGTE", "idLT", "idLTE", "createdAt", "createdAtNEQ", "createdAtIn", "createdAtNotIn", "createdAtGT", "createdAtGTE", "createdAtLT", "createdAtLTE", "status", "statusNEQ", "statusIn", "statusNotIn", "priority", "priorityNEQ", "priorityIn", "priorityNotIn", "priorityGT", "priorityGTE", "priorityLT", "priorityLTE", "text", "textNEQ", "textIn", "textNotIn", "textGT", "textGTE", "textLT", "textLTE", "textContains", "textHasPrefix", "textHasSuffix", "textEqualFold", "textContainsFold", "categoryID", "categoryIDNEQ", "categoryIDIn", "categoryIDNotIn", "categoryIDIsNil", "categoryIDNotNil", "value", "valueNEQ", "valueIn", "valueNotIn", "valueGT", "valueGTE", "valueLT", "valueLTE", "hasParent", "hasParentWith", "hasChildren", "hasChildrenWith", "hasCategory", "hasCategoryWith", "createdToday"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "not": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("not")) + data, err := ec.unmarshalOTodoWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoWhereInput(ctx, v) + if err != nil { + return it, err + } + it.Not = data + case "and": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("and")) + data, err := ec.unmarshalOTodoWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.And = data + case "or": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("or")) + data, err := ec.unmarshalOTodoWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.Or = data + case "id": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.ID = data + case "idNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idNEQ")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDNEQ = data + case "idIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idIn")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.IDIn = data + case "idNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idNotIn")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.IDNotIn = data + case "idGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idGT")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDGT = data + case "idGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idGTE")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDGTE = data + case "idLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idLT")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDLT = data + case "idLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idLTE")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDLTE = data + case "createdAt": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("createdAt")) + data, err := ec.unmarshalOTime2ᚖtimeᚐTime(ctx, v) + if err != nil { + return it, err + } + it.CreatedAt = data + case "createdAtNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("createdAtNEQ")) + data, err := ec.unmarshalOTime2ᚖtimeᚐTime(ctx, v) + if err != nil { + return it, err + } + it.CreatedAtNEQ = data + case "createdAtIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("createdAtIn")) + data, err := ec.unmarshalOTime2ᚕtimeᚐTimeᚄ(ctx, v) + if err != nil { + return it, err + } + it.CreatedAtIn = data + case "createdAtNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("createdAtNotIn")) + data, err := ec.unmarshalOTime2ᚕtimeᚐTimeᚄ(ctx, v) + if err != nil { + return it, err + } + it.CreatedAtNotIn = data + case "createdAtGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("createdAtGT")) + data, err := ec.unmarshalOTime2ᚖtimeᚐTime(ctx, v) + if err != nil { + return it, err + } + it.CreatedAtGT = data + case "createdAtGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("createdAtGTE")) + data, err := ec.unmarshalOTime2ᚖtimeᚐTime(ctx, v) + if err != nil { + return it, err + } + it.CreatedAtGTE = data + case "createdAtLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("createdAtLT")) + data, err := ec.unmarshalOTime2ᚖtimeᚐTime(ctx, v) + if err != nil { + return it, err + } + it.CreatedAtLT = data + case "createdAtLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("createdAtLTE")) + data, err := ec.unmarshalOTime2ᚖtimeᚐTime(ctx, v) + if err != nil { + return it, err + } + it.CreatedAtLTE = data + case "status": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("status")) + data, err := ec.unmarshalOTodoStatus2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋtodoᚐStatus(ctx, v) + if err != nil { + return it, err + } + it.Status = data + case "statusNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("statusNEQ")) + data, err := ec.unmarshalOTodoStatus2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋtodoᚐStatus(ctx, v) + if err != nil { + return it, err + } + it.StatusNEQ = data + case "statusIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("statusIn")) + data, err := ec.unmarshalOTodoStatus2ᚕentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋtodoᚐStatusᚄ(ctx, v) + if err != nil { + return it, err + } + it.StatusIn = data + case "statusNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("statusNotIn")) + data, err := ec.unmarshalOTodoStatus2ᚕentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋtodoᚐStatusᚄ(ctx, v) + if err != nil { + return it, err + } + it.StatusNotIn = data + case "priority": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("priority")) + data, err := ec.unmarshalOInt2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.Priority = data + case "priorityNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("priorityNEQ")) + data, err := ec.unmarshalOInt2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.PriorityNEQ = data + case "priorityIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("priorityIn")) + data, err := ec.unmarshalOInt2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.PriorityIn = data + case "priorityNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("priorityNotIn")) + data, err := ec.unmarshalOInt2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.PriorityNotIn = data + case "priorityGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("priorityGT")) + data, err := ec.unmarshalOInt2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.PriorityGT = data + case "priorityGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("priorityGTE")) + data, err := ec.unmarshalOInt2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.PriorityGTE = data + case "priorityLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("priorityLT")) + data, err := ec.unmarshalOInt2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.PriorityLT = data + case "priorityLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("priorityLTE")) + data, err := ec.unmarshalOInt2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.PriorityLTE = data + case "text": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("text")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Text = data + case "textNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("textNEQ")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.TextNEQ = data + case "textIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("textIn")) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.TextIn = data + case "textNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("textNotIn")) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.TextNotIn = data + case "textGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("textGT")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.TextGT = data + case "textGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("textGTE")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.TextGTE = data + case "textLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("textLT")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.TextLT = data + case "textLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("textLTE")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.TextLTE = data + case "textContains": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("textContains")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.TextContains = data + case "textHasPrefix": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("textHasPrefix")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.TextHasPrefix = data + case "textHasSuffix": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("textHasSuffix")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.TextHasSuffix = data + case "textEqualFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("textEqualFold")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.TextEqualFold = data + case "textContainsFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("textContainsFold")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.TextContainsFold = data + case "categoryID": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("categoryID")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.CategoryID = data + case "categoryIDNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("categoryIDNEQ")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.CategoryIDNEQ = data + case "categoryIDIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("categoryIDIn")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.CategoryIDIn = data + case "categoryIDNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("categoryIDNotIn")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.CategoryIDNotIn = data + case "categoryIDIsNil": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("categoryIDIsNil")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.CategoryIDIsNil = data + case "categoryIDNotNil": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("categoryIDNotNil")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.CategoryIDNotNil = data + case "value": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("value")) + data, err := ec.unmarshalOInt2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.Value = data + case "valueNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("valueNEQ")) + data, err := ec.unmarshalOInt2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.ValueNEQ = data + case "valueIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("valueIn")) + data, err := ec.unmarshalOInt2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.ValueIn = data + case "valueNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("valueNotIn")) + data, err := ec.unmarshalOInt2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.ValueNotIn = data + case "valueGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("valueGT")) + data, err := ec.unmarshalOInt2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.ValueGT = data + case "valueGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("valueGTE")) + data, err := ec.unmarshalOInt2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.ValueGTE = data + case "valueLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("valueLT")) + data, err := ec.unmarshalOInt2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.ValueLT = data + case "valueLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("valueLTE")) + data, err := ec.unmarshalOInt2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.ValueLTE = data + case "hasParent": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hasParent")) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) + if err != nil { + return it, err + } + it.HasParent = data + case "hasParentWith": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hasParentWith")) + data, err := ec.unmarshalOTodoWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.HasParentWith = data + case "hasChildren": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hasChildren")) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) + if err != nil { + return it, err + } + it.HasChildren = data + case "hasChildrenWith": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hasChildrenWith")) + data, err := ec.unmarshalOTodoWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.HasChildrenWith = data + case "hasCategory": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hasCategory")) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) + if err != nil { + return it, err + } + it.HasCategory = data + case "hasCategoryWith": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hasCategoryWith")) + data, err := ec.unmarshalOCategoryWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategoryWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.HasCategoryWith = data + case "createdToday": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("createdToday")) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) + if err != nil { + return it, err + } + if err = ec.resolvers.TodoWhereInput().CreatedToday(ctx, &it, data); err != nil { + return it, err + } + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputUpdateCategoryInput(ctx context.Context, obj any) (ent.UpdateCategoryInput, error) { + var it ent.UpdateCategoryInput + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"text", "status", "config", "clearConfig", "types", "clearTypes", "duration", "clearDuration", "count", "clearCount", "strings", "appendStrings", "clearStrings", "addTodoIDs", "removeTodoIDs", "clearTodos", "addSubCategoryIDs", "removeSubCategoryIDs", "clearSubCategories"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "text": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("text")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Text = data + case "status": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("status")) + data, err := ec.unmarshalOCategoryStatus2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋcategoryᚐStatus(ctx, v) + if err != nil { + return it, err + } + it.Status = data + case "config": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("config")) + data, err := ec.unmarshalOCategoryConfigInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋschematypeᚐCategoryConfig(ctx, v) + if err != nil { + return it, err + } + it.Config = data + case "clearConfig": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("clearConfig")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.ClearConfig = data + case "types": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("types")) + data, err := ec.unmarshalOCategoryTypesInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋschematypeᚐCategoryTypes(ctx, v) + if err != nil { + return it, err + } + it.Types = data + case "clearTypes": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("clearTypes")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.ClearTypes = data + case "duration": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("duration")) + data, err := ec.unmarshalODuration2ᚖtimeᚐDuration(ctx, v) + if err != nil { + return it, err + } + it.Duration = data + case "clearDuration": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("clearDuration")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.ClearDuration = data + case "count": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("count")) + data, err := ec.unmarshalOUint642ᚖuint64(ctx, v) + if err != nil { + return it, err + } + it.Count = data + case "clearCount": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("clearCount")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.ClearCount = data + case "strings": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("strings")) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.Strings = data + case "appendStrings": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("appendStrings")) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.AppendStrings = data + case "clearStrings": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("clearStrings")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.ClearStrings = data + case "addTodoIDs": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("addTodoIDs")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.AddTodoIDs = data + case "removeTodoIDs": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("removeTodoIDs")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.RemoveTodoIDs = data + case "clearTodos": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("clearTodos")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.ClearTodos = data + case "addSubCategoryIDs": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("addSubCategoryIDs")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.AddSubCategoryIDs = data + case "removeSubCategoryIDs": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("removeSubCategoryIDs")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.RemoveSubCategoryIDs = data + case "clearSubCategories": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("clearSubCategories")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.ClearSubCategories = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputUpdateFriendshipInput(ctx context.Context, obj any) (ent.UpdateFriendshipInput, error) { + var it ent.UpdateFriendshipInput + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"createdAt", "userID", "friendID"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "createdAt": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("createdAt")) + data, err := ec.unmarshalOTime2ᚖtimeᚐTime(ctx, v) + if err != nil { + return it, err + } + it.CreatedAt = data + case "userID": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("userID")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.UserID = data + case "friendID": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("friendID")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.FriendID = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputUpdateTodoInput(ctx context.Context, obj any) (ent.UpdateTodoInput, error) { + var it ent.UpdateTodoInput + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"status", "priority", "text", "init", "clearInit", "value", "parentID", "clearParent", "addChildIDs", "removeChildIDs", "clearChildren", "secretID", "clearSecret"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "status": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("status")) + data, err := ec.unmarshalOTodoStatus2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋtodoᚐStatus(ctx, v) + if err != nil { + return it, err + } + it.Status = data + case "priority": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("priority")) + data, err := ec.unmarshalOInt2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.Priority = data + case "text": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("text")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Text = data + case "init": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("init")) + data, err := ec.unmarshalOMap2map(ctx, v) + if err != nil { + return it, err + } + it.Init = data + case "clearInit": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("clearInit")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.ClearInit = data + case "value": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("value")) + data, err := ec.unmarshalOInt2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.Value = data + case "parentID": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("parentID")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.ParentID = data + case "clearParent": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("clearParent")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.ClearParent = data + case "addChildIDs": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("addChildIDs")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.AddChildIDs = data + case "removeChildIDs": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("removeChildIDs")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.RemoveChildIDs = data + case "clearChildren": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("clearChildren")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.ClearChildren = data + case "secretID": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("secretID")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.SecretID = data + case "clearSecret": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("clearSecret")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.ClearSecret = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputUpdateUserInput(ctx context.Context, obj any) (ent.UpdateUserInput, error) { + var it ent.UpdateUserInput + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"name", "username", "password", "clearPassword", "requiredMetadata", "metadata", "clearMetadata", "addGroupIDs", "removeGroupIDs", "clearGroups", "addFriendIDs", "removeFriendIDs", "clearFriends"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "name": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("name")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Name = data + case "username": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("username")) + data, err := ec.unmarshalOUUID2ᚖgithubᚗcomᚋgoogleᚋuuidᚐUUID(ctx, v) + if err != nil { + return it, err + } + it.Username = data + case "password": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("password")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Password = data + case "clearPassword": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("clearPassword")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.ClearPassword = data + case "requiredMetadata": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("requiredMetadata")) + data, err := ec.unmarshalOMap2map(ctx, v) + if err != nil { + return it, err + } + it.RequiredMetadata = data + case "metadata": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("metadata")) + data, err := ec.unmarshalOMap2map(ctx, v) + if err != nil { + return it, err + } + it.Metadata = data + case "clearMetadata": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("clearMetadata")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.ClearMetadata = data + case "addGroupIDs": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("addGroupIDs")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.AddGroupIDs = data + case "removeGroupIDs": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("removeGroupIDs")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.RemoveGroupIDs = data + case "clearGroups": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("clearGroups")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.ClearGroups = data + case "addFriendIDs": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("addFriendIDs")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.AddFriendIDs = data + case "removeFriendIDs": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("removeFriendIDs")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.RemoveFriendIDs = data + case "clearFriends": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("clearFriends")) + data, err := ec.unmarshalOBoolean2bool(ctx, v) + if err != nil { + return it, err + } + it.ClearFriends = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputUserOrder(ctx context.Context, obj any) (ent.UserOrder, error) { + var it ent.UserOrder + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { + asMap[k] = v + } + + if _, present := asMap["direction"]; !present { + asMap["direction"] = "ASC" + } + + fieldsInOrder := [...]string{"direction", "field"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "direction": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("direction")) + data, err := ec.unmarshalNOrderDirection2entgoᚗioᚋcontribᚋentgqlᚐOrderDirection(ctx, v) + if err != nil { + return it, err + } + it.Direction = data + case "field": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("field")) + data, err := ec.unmarshalNUserOrderField2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUserOrderField(ctx, v) + if err != nil { + return it, err + } + it.Field = data + } + } + + return it, nil +} + +func (ec *executionContext) unmarshalInputUserWhereInput(ctx context.Context, obj any) (ent.UserWhereInput, error) { + var it ent.UserWhereInput + asMap := map[string]any{} + for k, v := range obj.(map[string]any) { + asMap[k] = v + } + + fieldsInOrder := [...]string{"not", "and", "or", "id", "idNEQ", "idIn", "idNotIn", "idGT", "idGTE", "idLT", "idLTE", "name", "nameNEQ", "nameIn", "nameNotIn", "nameGT", "nameGTE", "nameLT", "nameLTE", "nameContains", "nameHasPrefix", "nameHasSuffix", "nameEqualFold", "nameContainsFold", "username", "usernameNEQ", "usernameIn", "usernameNotIn", "usernameGT", "usernameGTE", "usernameLT", "usernameLTE", "hasGroups", "hasGroupsWith", "hasFriends", "hasFriendsWith", "hasFriendships", "hasFriendshipsWith"} + for _, k := range fieldsInOrder { + v, ok := asMap[k] + if !ok { + continue + } + switch k { + case "not": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("not")) + data, err := ec.unmarshalOUserWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUserWhereInput(ctx, v) + if err != nil { + return it, err + } + it.Not = data + case "and": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("and")) + data, err := ec.unmarshalOUserWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUserWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.And = data + case "or": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("or")) + data, err := ec.unmarshalOUserWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUserWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.Or = data + case "id": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("id")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.ID = data + case "idNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idNEQ")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDNEQ = data + case "idIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idIn")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.IDIn = data + case "idNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idNotIn")) + data, err := ec.unmarshalOID2ᚕintᚄ(ctx, v) + if err != nil { + return it, err + } + it.IDNotIn = data + case "idGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idGT")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDGT = data + case "idGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idGTE")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDGTE = data + case "idLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idLT")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDLT = data + case "idLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("idLTE")) + data, err := ec.unmarshalOID2ᚖint(ctx, v) + if err != nil { + return it, err + } + it.IDLTE = data + case "name": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("name")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.Name = data + case "nameNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameNEQ")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameNEQ = data + case "nameIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameIn")) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.NameIn = data + case "nameNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameNotIn")) + data, err := ec.unmarshalOString2ᚕstringᚄ(ctx, v) + if err != nil { + return it, err + } + it.NameNotIn = data + case "nameGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameGT")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameGT = data + case "nameGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameGTE")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameGTE = data + case "nameLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameLT")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameLT = data + case "nameLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameLTE")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameLTE = data + case "nameContains": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameContains")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameContains = data + case "nameHasPrefix": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameHasPrefix")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameHasPrefix = data + case "nameHasSuffix": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameHasSuffix")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameHasSuffix = data + case "nameEqualFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameEqualFold")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameEqualFold = data + case "nameContainsFold": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("nameContainsFold")) + data, err := ec.unmarshalOString2ᚖstring(ctx, v) + if err != nil { + return it, err + } + it.NameContainsFold = data + case "username": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("username")) + data, err := ec.unmarshalOUUID2ᚖgithubᚗcomᚋgoogleᚋuuidᚐUUID(ctx, v) + if err != nil { + return it, err + } + it.Username = data + case "usernameNEQ": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("usernameNEQ")) + data, err := ec.unmarshalOUUID2ᚖgithubᚗcomᚋgoogleᚋuuidᚐUUID(ctx, v) + if err != nil { + return it, err + } + it.UsernameNEQ = data + case "usernameIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("usernameIn")) + data, err := ec.unmarshalOUUID2ᚕgithubᚗcomᚋgoogleᚋuuidᚐUUIDᚄ(ctx, v) + if err != nil { + return it, err + } + it.UsernameIn = data + case "usernameNotIn": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("usernameNotIn")) + data, err := ec.unmarshalOUUID2ᚕgithubᚗcomᚋgoogleᚋuuidᚐUUIDᚄ(ctx, v) + if err != nil { + return it, err + } + it.UsernameNotIn = data + case "usernameGT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("usernameGT")) + data, err := ec.unmarshalOUUID2ᚖgithubᚗcomᚋgoogleᚋuuidᚐUUID(ctx, v) + if err != nil { + return it, err + } + it.UsernameGT = data + case "usernameGTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("usernameGTE")) + data, err := ec.unmarshalOUUID2ᚖgithubᚗcomᚋgoogleᚋuuidᚐUUID(ctx, v) + if err != nil { + return it, err + } + it.UsernameGTE = data + case "usernameLT": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("usernameLT")) + data, err := ec.unmarshalOUUID2ᚖgithubᚗcomᚋgoogleᚋuuidᚐUUID(ctx, v) + if err != nil { + return it, err + } + it.UsernameLT = data + case "usernameLTE": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("usernameLTE")) + data, err := ec.unmarshalOUUID2ᚖgithubᚗcomᚋgoogleᚋuuidᚐUUID(ctx, v) + if err != nil { + return it, err + } + it.UsernameLTE = data + case "hasGroups": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hasGroups")) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) + if err != nil { + return it, err + } + it.HasGroups = data + case "hasGroupsWith": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hasGroupsWith")) + data, err := ec.unmarshalOGroupWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐGroupWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.HasGroupsWith = data + case "hasFriends": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hasFriends")) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) + if err != nil { + return it, err + } + it.HasFriends = data + case "hasFriendsWith": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hasFriendsWith")) + data, err := ec.unmarshalOUserWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUserWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.HasFriendsWith = data + case "hasFriendships": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hasFriendships")) + data, err := ec.unmarshalOBoolean2ᚖbool(ctx, v) + if err != nil { + return it, err + } + it.HasFriendships = data + case "hasFriendshipsWith": + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithField("hasFriendshipsWith")) + data, err := ec.unmarshalOFriendshipWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐFriendshipWhereInputᚄ(ctx, v) + if err != nil { + return it, err + } + it.HasFriendshipsWith = data + } + } + + return it, nil +} + +// endregion **************************** input.gotpl ***************************** + +// region ************************** interface.gotpl *************************** + +func (ec *executionContext) _NamedNode(ctx context.Context, sel ast.SelectionSet, obj NamedNode) graphql.Marshaler { + switch obj := (obj).(type) { + case nil: + return graphql.Null + case *ent.Group: + if obj == nil { + return graphql.Null + } + return ec._Group(ctx, sel, obj) + default: + panic(fmt.Errorf("unexpected type %T", obj)) + } +} + +func (ec *executionContext) _Node(ctx context.Context, sel ast.SelectionSet, obj ent.Noder) graphql.Marshaler { + switch obj := (obj).(type) { + case nil: + return graphql.Null + case *ent.Group: + if obj == nil { + return graphql.Null + } + return ec._Group(ctx, sel, obj) + case *ent.BillProduct: + if obj == nil { + return graphql.Null + } + return ec._BillProduct(ctx, sel, obj) + case *ent.Category: + if obj == nil { + return graphql.Null + } + return ec._Category(ctx, sel, obj) + case *ent.Friendship: + if obj == nil { + return graphql.Null + } + return ec._Friendship(ctx, sel, obj) + case *ent.OneToMany: + if obj == nil { + return graphql.Null + } + return ec._OneToMany(ctx, sel, obj) + case *ent.Workspace: + if obj == nil { + return graphql.Null + } + return ec._Organization(ctx, sel, obj) + case *ent.Project: + if obj == nil { + return graphql.Null + } + return ec._Project(ctx, sel, obj) + case *ent.Todo: + if obj == nil { + return graphql.Null + } + return ec._Todo(ctx, sel, obj) + case *ent.User: + if obj == nil { + return graphql.Null + } + return ec._User(ctx, sel, obj) + default: + panic(fmt.Errorf("unexpected type %T", obj)) + } +} + +// endregion ************************** interface.gotpl *************************** + +// region **************************** object.gotpl **************************** + +var billProductImplementors = []string{"BillProduct", "Node"} + +func (ec *executionContext) _BillProduct(ctx context.Context, sel ast.SelectionSet, obj *ent.BillProduct) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, billProductImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("BillProduct") + case "id": + out.Values[i] = ec._BillProduct_id(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "name": + out.Values[i] = ec._BillProduct_name(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "sku": + out.Values[i] = ec._BillProduct_sku(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "quantity": + out.Values[i] = ec._BillProduct_quantity(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var categoryImplementors = []string{"Category", "Node"} + +func (ec *executionContext) _Category(ctx context.Context, sel ast.SelectionSet, obj *ent.Category) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, categoryImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("Category") + case "id": + out.Values[i] = ec._Category_id(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) + } + case "text": + out.Values[i] = ec._Category_text(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) + } + case "status": + out.Values[i] = ec._Category_status(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) + } + case "config": + out.Values[i] = ec._Category_config(ctx, field, obj) + case "types": + out.Values[i] = ec._Category_types(ctx, field, obj) + case "duration": + out.Values[i] = ec._Category_duration(ctx, field, obj) + case "count": + out.Values[i] = ec._Category_count(ctx, field, obj) + case "strings": + out.Values[i] = ec._Category_strings(ctx, field, obj) + case "todos": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Category_todos(ctx, field, obj) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + if field.Deferrable != nil { + dfs, ok := deferred[field.Deferrable.Label] + di := 0 + if ok { + dfs.AddField(field) + di = len(dfs.Values) - 1 + } else { + dfs = graphql.NewFieldSet([]graphql.CollectedField{field}) + deferred[field.Deferrable.Label] = dfs + } + dfs.Concurrently(di, func(ctx context.Context) graphql.Marshaler { + return innerFunc(ctx, dfs) + }) + + // don't run the out.Concurrently() call below + out.Values[i] = graphql.Null + continue + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + case "subCategories": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Category_subCategories(ctx, field, obj) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + if field.Deferrable != nil { + dfs, ok := deferred[field.Deferrable.Label] + di := 0 + if ok { + dfs.AddField(field) + di = len(dfs.Values) - 1 + } else { + dfs = graphql.NewFieldSet([]graphql.CollectedField{field}) + deferred[field.Deferrable.Label] = dfs + } + dfs.Concurrently(di, func(ctx context.Context) graphql.Marshaler { + return innerFunc(ctx, dfs) + }) + + // don't run the out.Concurrently() call below + out.Values[i] = graphql.Null + continue + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + case "todosCount": + field := field + + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Category_todosCount(ctx, field, obj) + return res + } + + if field.Deferrable != nil { + dfs, ok := deferred[field.Deferrable.Label] + di := 0 + if ok { + dfs.AddField(field) + di = len(dfs.Values) - 1 + } else { + dfs = graphql.NewFieldSet([]graphql.CollectedField{field}) + deferred[field.Deferrable.Label] = dfs + } + dfs.Concurrently(di, func(ctx context.Context) graphql.Marshaler { + return innerFunc(ctx, dfs) + }) + + // don't run the out.Concurrently() call below + out.Values[i] = graphql.Null + continue + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var categoryConfigImplementors = []string{"CategoryConfig"} + +func (ec *executionContext) _CategoryConfig(ctx context.Context, sel ast.SelectionSet, obj *schematype.CategoryConfig) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, categoryConfigImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("CategoryConfig") + case "maxMembers": + out.Values[i] = ec._CategoryConfig_maxMembers(ctx, field, obj) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var categoryConnectionImplementors = []string{"CategoryConnection"} + +func (ec *executionContext) _CategoryConnection(ctx context.Context, sel ast.SelectionSet, obj *ent.CategoryConnection) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, categoryConnectionImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("CategoryConnection") + case "edges": + out.Values[i] = ec._CategoryConnection_edges(ctx, field, obj) + case "pageInfo": + out.Values[i] = ec._CategoryConnection_pageInfo(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "totalCount": + out.Values[i] = ec._CategoryConnection_totalCount(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var categoryEdgeImplementors = []string{"CategoryEdge"} + +func (ec *executionContext) _CategoryEdge(ctx context.Context, sel ast.SelectionSet, obj *ent.CategoryEdge) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, categoryEdgeImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("CategoryEdge") + case "node": + out.Values[i] = ec._CategoryEdge_node(ctx, field, obj) + case "cursor": + out.Values[i] = ec._CategoryEdge_cursor(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var categoryTypesImplementors = []string{"CategoryTypes"} + +func (ec *executionContext) _CategoryTypes(ctx context.Context, sel ast.SelectionSet, obj *schematype.CategoryTypes) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, categoryTypesImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("CategoryTypes") + case "public": + out.Values[i] = ec._CategoryTypes_public(ctx, field, obj) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var customImplementors = []string{"Custom"} + +func (ec *executionContext) _Custom(ctx context.Context, sel ast.SelectionSet, obj *customstruct.Custom) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, customImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("Custom") + case "info": + out.Values[i] = ec._Custom_info(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var friendshipImplementors = []string{"Friendship", "Node"} + +func (ec *executionContext) _Friendship(ctx context.Context, sel ast.SelectionSet, obj *ent.Friendship) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, friendshipImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("Friendship") + case "id": + out.Values[i] = ec._Friendship_id(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) + } + case "createdAt": + out.Values[i] = ec._Friendship_createdAt(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) + } + case "userID": + out.Values[i] = ec._Friendship_userID(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) + } + case "friendID": + out.Values[i] = ec._Friendship_friendID(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) + } + case "user": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Friendship_user(ctx, field, obj) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + if field.Deferrable != nil { + dfs, ok := deferred[field.Deferrable.Label] + di := 0 + if ok { + dfs.AddField(field) + di = len(dfs.Values) - 1 + } else { + dfs = graphql.NewFieldSet([]graphql.CollectedField{field}) + deferred[field.Deferrable.Label] = dfs + } + dfs.Concurrently(di, func(ctx context.Context) graphql.Marshaler { + return innerFunc(ctx, dfs) + }) + + // don't run the out.Concurrently() call below + out.Values[i] = graphql.Null + continue + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + case "friend": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Friendship_friend(ctx, field, obj) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + if field.Deferrable != nil { + dfs, ok := deferred[field.Deferrable.Label] + di := 0 + if ok { + dfs.AddField(field) + di = len(dfs.Values) - 1 + } else { + dfs = graphql.NewFieldSet([]graphql.CollectedField{field}) + deferred[field.Deferrable.Label] = dfs + } + dfs.Concurrently(di, func(ctx context.Context) graphql.Marshaler { + return innerFunc(ctx, dfs) + }) + + // don't run the out.Concurrently() call below + out.Values[i] = graphql.Null + continue + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var friendshipConnectionImplementors = []string{"FriendshipConnection"} + +func (ec *executionContext) _FriendshipConnection(ctx context.Context, sel ast.SelectionSet, obj *ent.FriendshipConnection) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, friendshipConnectionImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("FriendshipConnection") + case "edges": + out.Values[i] = ec._FriendshipConnection_edges(ctx, field, obj) + case "pageInfo": + out.Values[i] = ec._FriendshipConnection_pageInfo(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "totalCount": + out.Values[i] = ec._FriendshipConnection_totalCount(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var friendshipEdgeImplementors = []string{"FriendshipEdge"} + +func (ec *executionContext) _FriendshipEdge(ctx context.Context, sel ast.SelectionSet, obj *ent.FriendshipEdge) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, friendshipEdgeImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("FriendshipEdge") + case "node": + out.Values[i] = ec._FriendshipEdge_node(ctx, field, obj) + case "cursor": + out.Values[i] = ec._FriendshipEdge_cursor(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var groupImplementors = []string{"Group", "Node", "NamedNode"} + +func (ec *executionContext) _Group(ctx context.Context, sel ast.SelectionSet, obj *ent.Group) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, groupImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("Group") + case "id": + out.Values[i] = ec._Group_id(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) + } + case "name": + out.Values[i] = ec._Group_name(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) + } + case "users": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Group_users(ctx, field, obj) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + if field.Deferrable != nil { + dfs, ok := deferred[field.Deferrable.Label] + di := 0 + if ok { + dfs.AddField(field) + di = len(dfs.Values) - 1 + } else { + dfs = graphql.NewFieldSet([]graphql.CollectedField{field}) + deferred[field.Deferrable.Label] = dfs + } + dfs.Concurrently(di, func(ctx context.Context) graphql.Marshaler { + return innerFunc(ctx, dfs) + }) + + // don't run the out.Concurrently() call below + out.Values[i] = graphql.Null + continue + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var groupConnectionImplementors = []string{"GroupConnection"} + +func (ec *executionContext) _GroupConnection(ctx context.Context, sel ast.SelectionSet, obj *ent.GroupConnection) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, groupConnectionImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("GroupConnection") + case "edges": + out.Values[i] = ec._GroupConnection_edges(ctx, field, obj) + case "pageInfo": + out.Values[i] = ec._GroupConnection_pageInfo(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "totalCount": + out.Values[i] = ec._GroupConnection_totalCount(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var groupEdgeImplementors = []string{"GroupEdge"} + +func (ec *executionContext) _GroupEdge(ctx context.Context, sel ast.SelectionSet, obj *ent.GroupEdge) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, groupEdgeImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("GroupEdge") + case "node": + out.Values[i] = ec._GroupEdge_node(ctx, field, obj) + case "cursor": + out.Values[i] = ec._GroupEdge_cursor(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var mutationImplementors = []string{"Mutation"} + +func (ec *executionContext) _Mutation(ctx context.Context, sel ast.SelectionSet) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, mutationImplementors) + ctx = graphql.WithFieldContext(ctx, &graphql.FieldContext{ + Object: "Mutation", + }) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + innerCtx := graphql.WithRootFieldContext(ctx, &graphql.RootFieldContext{ + Object: field.Name, + Field: field, + }) + + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("Mutation") + case "createCategory": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_createCategory(ctx, field) + }) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "createTodo": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_createTodo(ctx, field) + }) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "updateTodo": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_updateTodo(ctx, field) + }) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "clearTodos": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_clearTodos(ctx, field) + }) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "updateFriendship": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Mutation_updateFriendship(ctx, field) + }) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var oneToManyImplementors = []string{"OneToMany", "Node"} + +func (ec *executionContext) _OneToMany(ctx context.Context, sel ast.SelectionSet, obj *ent.OneToMany) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, oneToManyImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("OneToMany") + case "id": + out.Values[i] = ec._OneToMany_id(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) + } + case "name": + out.Values[i] = ec._OneToMany_name(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) + } + case "field2": + out.Values[i] = ec._OneToMany_field2(ctx, field, obj) + case "parent": + field := field + + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._OneToMany_parent(ctx, field, obj) + return res + } + + if field.Deferrable != nil { + dfs, ok := deferred[field.Deferrable.Label] + di := 0 + if ok { + dfs.AddField(field) + di = len(dfs.Values) - 1 + } else { + dfs = graphql.NewFieldSet([]graphql.CollectedField{field}) + deferred[field.Deferrable.Label] = dfs + } + dfs.Concurrently(di, func(ctx context.Context) graphql.Marshaler { + return innerFunc(ctx, dfs) + }) + + // don't run the out.Concurrently() call below + out.Values[i] = graphql.Null + continue + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + case "children": + field := field + + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._OneToMany_children(ctx, field, obj) + return res + } + + if field.Deferrable != nil { + dfs, ok := deferred[field.Deferrable.Label] + di := 0 + if ok { + dfs.AddField(field) + di = len(dfs.Values) - 1 + } else { + dfs = graphql.NewFieldSet([]graphql.CollectedField{field}) + deferred[field.Deferrable.Label] = dfs + } + dfs.Concurrently(di, func(ctx context.Context) graphql.Marshaler { + return innerFunc(ctx, dfs) + }) + + // don't run the out.Concurrently() call below + out.Values[i] = graphql.Null + continue + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var oneToManyConnectionImplementors = []string{"OneToManyConnection"} + +func (ec *executionContext) _OneToManyConnection(ctx context.Context, sel ast.SelectionSet, obj *ent.OneToManyConnection) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, oneToManyConnectionImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("OneToManyConnection") + case "edges": + out.Values[i] = ec._OneToManyConnection_edges(ctx, field, obj) + case "pageInfo": + out.Values[i] = ec._OneToManyConnection_pageInfo(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "totalCount": + out.Values[i] = ec._OneToManyConnection_totalCount(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var oneToManyEdgeImplementors = []string{"OneToManyEdge"} + +func (ec *executionContext) _OneToManyEdge(ctx context.Context, sel ast.SelectionSet, obj *ent.OneToManyEdge) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, oneToManyEdgeImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("OneToManyEdge") + case "node": + out.Values[i] = ec._OneToManyEdge_node(ctx, field, obj) + case "cursor": + out.Values[i] = ec._OneToManyEdge_cursor(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var organizationImplementors = []string{"Organization", "Node"} + +func (ec *executionContext) _Organization(ctx context.Context, sel ast.SelectionSet, obj *ent.Workspace) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, organizationImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("Organization") + case "id": + out.Values[i] = ec._Organization_id(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "name": + out.Values[i] = ec._Organization_name(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var pageInfoImplementors = []string{"PageInfo"} + +func (ec *executionContext) _PageInfo(ctx context.Context, sel ast.SelectionSet, obj *entgql.PageInfo[int]) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, pageInfoImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("PageInfo") + case "hasNextPage": + out.Values[i] = ec._PageInfo_hasNextPage(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "hasPreviousPage": + out.Values[i] = ec._PageInfo_hasPreviousPage(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "startCursor": + out.Values[i] = ec._PageInfo_startCursor(ctx, field, obj) + case "endCursor": + out.Values[i] = ec._PageInfo_endCursor(ctx, field, obj) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var projectImplementors = []string{"Project", "Node"} + +func (ec *executionContext) _Project(ctx context.Context, sel ast.SelectionSet, obj *ent.Project) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, projectImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("Project") + case "id": + out.Values[i] = ec._Project_id(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) + } + case "todos": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Project_todos(ctx, field, obj) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + if field.Deferrable != nil { + dfs, ok := deferred[field.Deferrable.Label] + di := 0 + if ok { + dfs.AddField(field) + di = len(dfs.Values) - 1 + } else { + dfs = graphql.NewFieldSet([]graphql.CollectedField{field}) + deferred[field.Deferrable.Label] = dfs + } + dfs.Concurrently(di, func(ctx context.Context) graphql.Marshaler { + return innerFunc(ctx, dfs) + }) + + // don't run the out.Concurrently() call below + out.Values[i] = graphql.Null + continue + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var queryImplementors = []string{"Query"} + +func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, queryImplementors) + ctx = graphql.WithFieldContext(ctx, &graphql.FieldContext{ + Object: "Query", + }) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + innerCtx := graphql.WithRootFieldContext(ctx, &graphql.RootFieldContext{ + Object: field.Name, + Field: field, + }) + + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("Query") + case "node": + field := field + + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_node(ctx, field) + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "nodes": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_nodes(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "billProducts": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_billProducts(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "categories": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_categories(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "groups": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_groups(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "oneToMany": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_oneToMany(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "todos": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_todos(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "users": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_users(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "ping": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_ping(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "todosWithJoins": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Query_todosWithJoins(ctx, field) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + rrm := func(ctx context.Context) graphql.Marshaler { + return ec.OperationContext.RootResolverMiddleware(ctx, + func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return rrm(innerCtx) }) + case "__type": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Query___type(ctx, field) + }) + case "__schema": + out.Values[i] = ec.OperationContext.RootResolverMiddleware(innerCtx, func(ctx context.Context) (res graphql.Marshaler) { + return ec._Query___schema(ctx, field) + }) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var todoImplementors = []string{"Todo", "Node"} + +func (ec *executionContext) _Todo(ctx context.Context, sel ast.SelectionSet, obj *ent.Todo) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, todoImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("Todo") + case "id": + out.Values[i] = ec._Todo_id(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) + } + case "createdAt": + out.Values[i] = ec._Todo_createdAt(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) + } + case "status": + out.Values[i] = ec._Todo_status(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) + } + case "priorityOrder": + out.Values[i] = ec._Todo_priorityOrder(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) + } + case "text": + out.Values[i] = ec._Todo_text(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) + } + case "categoryID": + out.Values[i] = ec._Todo_categoryID(ctx, field, obj) + case "category_id": + out.Values[i] = ec._Todo_category_id(ctx, field, obj) + case "categoryX": + out.Values[i] = ec._Todo_categoryX(ctx, field, obj) + case "init": + out.Values[i] = ec._Todo_init(ctx, field, obj) + case "custom": + out.Values[i] = ec._Todo_custom(ctx, field, obj) + case "customp": + out.Values[i] = ec._Todo_customp(ctx, field, obj) + case "value": + out.Values[i] = ec._Todo_value(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) + } + case "parent": + field := field + + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Todo_parent(ctx, field, obj) + return res + } + + if field.Deferrable != nil { + dfs, ok := deferred[field.Deferrable.Label] + di := 0 + if ok { + dfs.AddField(field) + di = len(dfs.Values) - 1 + } else { + dfs = graphql.NewFieldSet([]graphql.CollectedField{field}) + deferred[field.Deferrable.Label] = dfs + } + dfs.Concurrently(di, func(ctx context.Context) graphql.Marshaler { + return innerFunc(ctx, dfs) + }) + + // don't run the out.Concurrently() call below + out.Values[i] = graphql.Null + continue + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + case "children": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Todo_children(ctx, field, obj) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + if field.Deferrable != nil { + dfs, ok := deferred[field.Deferrable.Label] + di := 0 + if ok { + dfs.AddField(field) + di = len(dfs.Values) - 1 + } else { + dfs = graphql.NewFieldSet([]graphql.CollectedField{field}) + deferred[field.Deferrable.Label] = dfs + } + dfs.Concurrently(di, func(ctx context.Context) graphql.Marshaler { + return innerFunc(ctx, dfs) + }) + + // don't run the out.Concurrently() call below + out.Values[i] = graphql.Null + continue + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + case "category": + field := field + + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Todo_category(ctx, field, obj) + return res + } + + if field.Deferrable != nil { + dfs, ok := deferred[field.Deferrable.Label] + di := 0 + if ok { + dfs.AddField(field) + di = len(dfs.Values) - 1 + } else { + dfs = graphql.NewFieldSet([]graphql.CollectedField{field}) + deferred[field.Deferrable.Label] = dfs + } + dfs.Concurrently(di, func(ctx context.Context) graphql.Marshaler { + return innerFunc(ctx, dfs) + }) + + // don't run the out.Concurrently() call below + out.Values[i] = graphql.Null + continue + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + case "extendedField": + field := field + + innerFunc := func(ctx context.Context, _ *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._Todo_extendedField(ctx, field, obj) + return res + } + + if field.Deferrable != nil { + dfs, ok := deferred[field.Deferrable.Label] + di := 0 + if ok { + dfs.AddField(field) + di = len(dfs.Values) - 1 + } else { + dfs = graphql.NewFieldSet([]graphql.CollectedField{field}) + deferred[field.Deferrable.Label] = dfs + } + dfs.Concurrently(di, func(ctx context.Context) graphql.Marshaler { + return innerFunc(ctx, dfs) + }) + + // don't run the out.Concurrently() call below + out.Values[i] = graphql.Null + continue + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var todoConnectionImplementors = []string{"TodoConnection"} + +func (ec *executionContext) _TodoConnection(ctx context.Context, sel ast.SelectionSet, obj *ent.TodoConnection) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, todoConnectionImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("TodoConnection") + case "edges": + out.Values[i] = ec._TodoConnection_edges(ctx, field, obj) + case "pageInfo": + out.Values[i] = ec._TodoConnection_pageInfo(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "totalCount": + out.Values[i] = ec._TodoConnection_totalCount(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var todoEdgeImplementors = []string{"TodoEdge"} + +func (ec *executionContext) _TodoEdge(ctx context.Context, sel ast.SelectionSet, obj *ent.TodoEdge) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, todoEdgeImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("TodoEdge") + case "node": + out.Values[i] = ec._TodoEdge_node(ctx, field, obj) + case "cursor": + out.Values[i] = ec._TodoEdge_cursor(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var userImplementors = []string{"User", "Node"} + +func (ec *executionContext) _User(ctx context.Context, sel ast.SelectionSet, obj *ent.User) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, userImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("User") + case "id": + out.Values[i] = ec._User_id(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) + } + case "name": + out.Values[i] = ec._User_name(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) + } + case "username": + out.Values[i] = ec._User_username(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) + } + case "requiredMetadata": + out.Values[i] = ec._User_requiredMetadata(ctx, field, obj) + if out.Values[i] == graphql.Null { + atomic.AddUint32(&out.Invalids, 1) + } + case "metadata": + out.Values[i] = ec._User_metadata(ctx, field, obj) + case "groups": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._User_groups(ctx, field, obj) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + if field.Deferrable != nil { + dfs, ok := deferred[field.Deferrable.Label] + di := 0 + if ok { + dfs.AddField(field) + di = len(dfs.Values) - 1 + } else { + dfs = graphql.NewFieldSet([]graphql.CollectedField{field}) + deferred[field.Deferrable.Label] = dfs + } + dfs.Concurrently(di, func(ctx context.Context) graphql.Marshaler { + return innerFunc(ctx, dfs) + }) + + // don't run the out.Concurrently() call below + out.Values[i] = graphql.Null + continue + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + case "friends": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._User_friends(ctx, field, obj) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + if field.Deferrable != nil { + dfs, ok := deferred[field.Deferrable.Label] + di := 0 + if ok { + dfs.AddField(field) + di = len(dfs.Values) - 1 + } else { + dfs = graphql.NewFieldSet([]graphql.CollectedField{field}) + deferred[field.Deferrable.Label] = dfs + } + dfs.Concurrently(di, func(ctx context.Context) graphql.Marshaler { + return innerFunc(ctx, dfs) + }) + + // don't run the out.Concurrently() call below + out.Values[i] = graphql.Null + continue + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + case "friendships": + field := field + + innerFunc := func(ctx context.Context, fs *graphql.FieldSet) (res graphql.Marshaler) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + } + }() + res = ec._User_friendships(ctx, field, obj) + if res == graphql.Null { + atomic.AddUint32(&fs.Invalids, 1) + } + return res + } + + if field.Deferrable != nil { + dfs, ok := deferred[field.Deferrable.Label] + di := 0 + if ok { + dfs.AddField(field) + di = len(dfs.Values) - 1 + } else { + dfs = graphql.NewFieldSet([]graphql.CollectedField{field}) + deferred[field.Deferrable.Label] = dfs + } + dfs.Concurrently(di, func(ctx context.Context) graphql.Marshaler { + return innerFunc(ctx, dfs) + }) + + // don't run the out.Concurrently() call below + out.Values[i] = graphql.Null + continue + } + + out.Concurrently(i, func(ctx context.Context) graphql.Marshaler { return innerFunc(ctx, out) }) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var userConnectionImplementors = []string{"UserConnection"} + +func (ec *executionContext) _UserConnection(ctx context.Context, sel ast.SelectionSet, obj *ent.UserConnection) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, userConnectionImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("UserConnection") + case "edges": + out.Values[i] = ec._UserConnection_edges(ctx, field, obj) + case "pageInfo": + out.Values[i] = ec._UserConnection_pageInfo(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "totalCount": + out.Values[i] = ec._UserConnection_totalCount(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var userEdgeImplementors = []string{"UserEdge"} + +func (ec *executionContext) _UserEdge(ctx context.Context, sel ast.SelectionSet, obj *ent.UserEdge) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, userEdgeImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("UserEdge") + case "node": + out.Values[i] = ec._UserEdge_node(ctx, field, obj) + case "cursor": + out.Values[i] = ec._UserEdge_cursor(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var __DirectiveImplementors = []string{"__Directive"} + +func (ec *executionContext) ___Directive(ctx context.Context, sel ast.SelectionSet, obj *introspection.Directive) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, __DirectiveImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("__Directive") + case "name": + out.Values[i] = ec.___Directive_name(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "description": + out.Values[i] = ec.___Directive_description(ctx, field, obj) + case "locations": + out.Values[i] = ec.___Directive_locations(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "args": + out.Values[i] = ec.___Directive_args(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "isRepeatable": + out.Values[i] = ec.___Directive_isRepeatable(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var __EnumValueImplementors = []string{"__EnumValue"} + +func (ec *executionContext) ___EnumValue(ctx context.Context, sel ast.SelectionSet, obj *introspection.EnumValue) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, __EnumValueImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("__EnumValue") + case "name": + out.Values[i] = ec.___EnumValue_name(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "description": + out.Values[i] = ec.___EnumValue_description(ctx, field, obj) + case "isDeprecated": + out.Values[i] = ec.___EnumValue_isDeprecated(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "deprecationReason": + out.Values[i] = ec.___EnumValue_deprecationReason(ctx, field, obj) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var __FieldImplementors = []string{"__Field"} + +func (ec *executionContext) ___Field(ctx context.Context, sel ast.SelectionSet, obj *introspection.Field) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, __FieldImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("__Field") + case "name": + out.Values[i] = ec.___Field_name(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "description": + out.Values[i] = ec.___Field_description(ctx, field, obj) + case "args": + out.Values[i] = ec.___Field_args(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "type": + out.Values[i] = ec.___Field_type(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "isDeprecated": + out.Values[i] = ec.___Field_isDeprecated(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "deprecationReason": + out.Values[i] = ec.___Field_deprecationReason(ctx, field, obj) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var __InputValueImplementors = []string{"__InputValue"} + +func (ec *executionContext) ___InputValue(ctx context.Context, sel ast.SelectionSet, obj *introspection.InputValue) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, __InputValueImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("__InputValue") + case "name": + out.Values[i] = ec.___InputValue_name(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "description": + out.Values[i] = ec.___InputValue_description(ctx, field, obj) + case "type": + out.Values[i] = ec.___InputValue_type(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "defaultValue": + out.Values[i] = ec.___InputValue_defaultValue(ctx, field, obj) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var __SchemaImplementors = []string{"__Schema"} + +func (ec *executionContext) ___Schema(ctx context.Context, sel ast.SelectionSet, obj *introspection.Schema) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, __SchemaImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("__Schema") + case "description": + out.Values[i] = ec.___Schema_description(ctx, field, obj) + case "types": + out.Values[i] = ec.___Schema_types(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "queryType": + out.Values[i] = ec.___Schema_queryType(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "mutationType": + out.Values[i] = ec.___Schema_mutationType(ctx, field, obj) + case "subscriptionType": + out.Values[i] = ec.___Schema_subscriptionType(ctx, field, obj) + case "directives": + out.Values[i] = ec.___Schema_directives(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +var __TypeImplementors = []string{"__Type"} + +func (ec *executionContext) ___Type(ctx context.Context, sel ast.SelectionSet, obj *introspection.Type) graphql.Marshaler { + fields := graphql.CollectFields(ec.OperationContext, sel, __TypeImplementors) + + out := graphql.NewFieldSet(fields) + deferred := make(map[string]*graphql.FieldSet) + for i, field := range fields { + switch field.Name { + case "__typename": + out.Values[i] = graphql.MarshalString("__Type") + case "kind": + out.Values[i] = ec.___Type_kind(ctx, field, obj) + if out.Values[i] == graphql.Null { + out.Invalids++ + } + case "name": + out.Values[i] = ec.___Type_name(ctx, field, obj) + case "description": + out.Values[i] = ec.___Type_description(ctx, field, obj) + case "fields": + out.Values[i] = ec.___Type_fields(ctx, field, obj) + case "interfaces": + out.Values[i] = ec.___Type_interfaces(ctx, field, obj) + case "possibleTypes": + out.Values[i] = ec.___Type_possibleTypes(ctx, field, obj) + case "enumValues": + out.Values[i] = ec.___Type_enumValues(ctx, field, obj) + case "inputFields": + out.Values[i] = ec.___Type_inputFields(ctx, field, obj) + case "ofType": + out.Values[i] = ec.___Type_ofType(ctx, field, obj) + case "specifiedByURL": + out.Values[i] = ec.___Type_specifiedByURL(ctx, field, obj) + default: + panic("unknown field " + strconv.Quote(field.Name)) + } + } + out.Dispatch(ctx) + if out.Invalids > 0 { + return graphql.Null + } + + atomic.AddInt32(&ec.deferred, int32(len(deferred))) + + for label, dfs := range deferred { + ec.processDeferredGroup(graphql.DeferredGroup{ + Label: label, + Path: graphql.GetPath(ctx), + FieldSet: dfs, + Context: ctx, + }) + } + + return out +} + +// endregion **************************** object.gotpl **************************** + +// region ***************************** type.gotpl ***************************** + +func (ec *executionContext) marshalNBillProduct2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐBillProductᚄ(ctx context.Context, sel ast.SelectionSet, v []*ent.BillProduct) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalNBillProduct2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐBillProduct(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) marshalNBillProduct2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐBillProduct(ctx context.Context, sel ast.SelectionSet, v *ent.BillProduct) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._BillProduct(ctx, sel, v) +} + +func (ec *executionContext) unmarshalNBillProductWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐBillProductWhereInput(ctx context.Context, v any) (*ent.BillProductWhereInput, error) { + res, err := ec.unmarshalInputBillProductWhereInput(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) unmarshalNBoolean2bool(ctx context.Context, v any) (bool, error) { + res, err := graphql.UnmarshalBoolean(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNBoolean2bool(ctx context.Context, sel ast.SelectionSet, v bool) graphql.Marshaler { + res := graphql.MarshalBoolean(v) + if res == graphql.Null { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + } + return res +} + +func (ec *executionContext) marshalNCategory2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategory(ctx context.Context, sel ast.SelectionSet, v ent.Category) graphql.Marshaler { + return ec._Category(ctx, sel, &v) +} + +func (ec *executionContext) marshalNCategory2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategory(ctx context.Context, sel ast.SelectionSet, v *ent.Category) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._Category(ctx, sel, v) +} + +func (ec *executionContext) unmarshalNCategoryConfigInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋschematypeᚐCategoryConfig(ctx context.Context, v any) (*schematype.CategoryConfig, error) { + res, err := ec.unmarshalInputCategoryConfigInput(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNCategoryConnection2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategoryConnection(ctx context.Context, sel ast.SelectionSet, v ent.CategoryConnection) graphql.Marshaler { + return ec._CategoryConnection(ctx, sel, &v) +} + +func (ec *executionContext) marshalNCategoryConnection2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategoryConnection(ctx context.Context, sel ast.SelectionSet, v *ent.CategoryConnection) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._CategoryConnection(ctx, sel, v) +} + +func (ec *executionContext) unmarshalNCategoryOrder2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategoryOrder(ctx context.Context, v any) (*ent.CategoryOrder, error) { + res, err := ec.unmarshalInputCategoryOrder(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) unmarshalNCategoryOrderField2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategoryOrderField(ctx context.Context, v any) (*ent.CategoryOrderField, error) { + var res = new(ent.CategoryOrderField) + err := res.UnmarshalGQL(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNCategoryOrderField2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategoryOrderField(ctx context.Context, sel ast.SelectionSet, v *ent.CategoryOrderField) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return v +} + +func (ec *executionContext) unmarshalNCategoryStatus2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋcategoryᚐStatus(ctx context.Context, v any) (category.Status, error) { + var res category.Status + err := res.UnmarshalGQL(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNCategoryStatus2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋcategoryᚐStatus(ctx context.Context, sel ast.SelectionSet, v category.Status) graphql.Marshaler { + return v +} + +func (ec *executionContext) unmarshalNCategoryWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategoryWhereInput(ctx context.Context, v any) (*ent.CategoryWhereInput, error) { + res, err := ec.unmarshalInputCategoryWhereInput(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) unmarshalNCreateCategoryInput2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCreateCategoryInput(ctx context.Context, v any) (ent.CreateCategoryInput, error) { + res, err := ec.unmarshalInputCreateCategoryInput(ctx, v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) unmarshalNCreateTodoInput2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCreateTodoInput(ctx context.Context, v any) (ent.CreateTodoInput, error) { + res, err := ec.unmarshalInputCreateTodoInput(ctx, v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) unmarshalNCreateTodoInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCreateTodoInput(ctx context.Context, v any) (*ent.CreateTodoInput, error) { + res, err := ec.unmarshalInputCreateTodoInput(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) unmarshalNCursor2entgoᚗioᚋcontribᚋentgqlᚐCursor(ctx context.Context, v any) (entgql.Cursor[int], error) { + var res entgql.Cursor[int] + err := res.UnmarshalGQL(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNCursor2entgoᚗioᚋcontribᚋentgqlᚐCursor(ctx context.Context, sel ast.SelectionSet, v entgql.Cursor[int]) graphql.Marshaler { + return v +} + +func (ec *executionContext) marshalNCustom2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋcustomstructᚐCustom(ctx context.Context, sel ast.SelectionSet, v customstruct.Custom) graphql.Marshaler { + return ec._Custom(ctx, sel, &v) +} + +func (ec *executionContext) unmarshalNDuration2timeᚐDuration(ctx context.Context, v any) (time.Duration, error) { + res, err := durationgql.UnmarshalDuration(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNDuration2timeᚐDuration(ctx context.Context, sel ast.SelectionSet, v time.Duration) graphql.Marshaler { + res := durationgql.MarshalDuration(v) + if res == graphql.Null { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + } + return res +} + +func (ec *executionContext) marshalNFriendship2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐFriendship(ctx context.Context, sel ast.SelectionSet, v ent.Friendship) graphql.Marshaler { + return ec._Friendship(ctx, sel, &v) +} + +func (ec *executionContext) marshalNFriendship2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐFriendship(ctx context.Context, sel ast.SelectionSet, v *ent.Friendship) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._Friendship(ctx, sel, v) +} + +func (ec *executionContext) marshalNFriendshipConnection2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐFriendshipConnection(ctx context.Context, sel ast.SelectionSet, v *ent.FriendshipConnection) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._FriendshipConnection(ctx, sel, v) +} + +func (ec *executionContext) unmarshalNFriendshipWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐFriendshipWhereInput(ctx context.Context, v any) (*ent.FriendshipWhereInput, error) { + res, err := ec.unmarshalInputFriendshipWhereInput(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNGroupConnection2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐGroupConnection(ctx context.Context, sel ast.SelectionSet, v ent.GroupConnection) graphql.Marshaler { + return ec._GroupConnection(ctx, sel, &v) +} + +func (ec *executionContext) marshalNGroupConnection2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐGroupConnection(ctx context.Context, sel ast.SelectionSet, v *ent.GroupConnection) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._GroupConnection(ctx, sel, v) +} + +func (ec *executionContext) unmarshalNGroupWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐGroupWhereInput(ctx context.Context, v any) (*ent.GroupWhereInput, error) { + res, err := ec.unmarshalInputGroupWhereInput(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) unmarshalNID2int(ctx context.Context, v any) (int, error) { + res, err := graphql.UnmarshalIntID(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNID2int(ctx context.Context, sel ast.SelectionSet, v int) graphql.Marshaler { + res := graphql.MarshalIntID(v) + if res == graphql.Null { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + } + return res +} + +func (ec *executionContext) unmarshalNID2ᚕintᚄ(ctx context.Context, v any) ([]int, error) { + var vSlice []any + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]int, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNID2int(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) marshalNID2ᚕintᚄ(ctx context.Context, sel ast.SelectionSet, v []int) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + for i := range v { + ret[i] = ec.marshalNID2int(ctx, sel, v[i]) + } + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) unmarshalNInt2int(ctx context.Context, v any) (int, error) { + res, err := graphql.UnmarshalInt(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNInt2int(ctx context.Context, sel ast.SelectionSet, v int) graphql.Marshaler { + res := graphql.MarshalInt(v) + if res == graphql.Null { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + } + return res +} + +func (ec *executionContext) unmarshalNMap2map(ctx context.Context, v any) (map[string]interface{}, error) { + res, err := graphql.UnmarshalMap(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNMap2map(ctx context.Context, sel ast.SelectionSet, v map[string]interface{}) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + res := graphql.MarshalMap(v) + if res == graphql.Null { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + } + return res +} + +func (ec *executionContext) marshalNNode2ᚕentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐNoder(ctx context.Context, sel ast.SelectionSet, v []ent.Noder) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalONode2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐNoder(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + return ret +} + +func (ec *executionContext) marshalNOneToMany2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToMany(ctx context.Context, sel ast.SelectionSet, v *ent.OneToMany) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._OneToMany(ctx, sel, v) +} + +func (ec *executionContext) marshalNOneToManyConnection2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToManyConnection(ctx context.Context, sel ast.SelectionSet, v ent.OneToManyConnection) graphql.Marshaler { + return ec._OneToManyConnection(ctx, sel, &v) +} + +func (ec *executionContext) marshalNOneToManyConnection2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToManyConnection(ctx context.Context, sel ast.SelectionSet, v *ent.OneToManyConnection) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._OneToManyConnection(ctx, sel, v) +} + +func (ec *executionContext) unmarshalNOneToManyOrderField2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToManyOrderField(ctx context.Context, v any) (*ent.OneToManyOrderField, error) { + var res = new(ent.OneToManyOrderField) + err := res.UnmarshalGQL(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNOneToManyOrderField2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToManyOrderField(ctx context.Context, sel ast.SelectionSet, v *ent.OneToManyOrderField) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return v +} + +func (ec *executionContext) unmarshalNOneToManyWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToManyWhereInput(ctx context.Context, v any) (*ent.OneToManyWhereInput, error) { + res, err := ec.unmarshalInputOneToManyWhereInput(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) unmarshalNOrderDirection2entgoᚗioᚋcontribᚋentgqlᚐOrderDirection(ctx context.Context, v any) (entgql.OrderDirection, error) { + var res entgql.OrderDirection + err := res.UnmarshalGQL(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNOrderDirection2entgoᚗioᚋcontribᚋentgqlᚐOrderDirection(ctx context.Context, sel ast.SelectionSet, v entgql.OrderDirection) graphql.Marshaler { + return v +} + +func (ec *executionContext) unmarshalNOrganizationWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOrganizationWhereInput(ctx context.Context, v any) (*ent.OrganizationWhereInput, error) { + res, err := ec.unmarshalInputOrganizationWhereInput(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNPageInfo2entgoᚗioᚋcontribᚋentgqlᚐPageInfo(ctx context.Context, sel ast.SelectionSet, v entgql.PageInfo[int]) graphql.Marshaler { + return ec._PageInfo(ctx, sel, &v) +} + +func (ec *executionContext) unmarshalNProjectWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐProjectWhereInput(ctx context.Context, v any) (*ent.ProjectWhereInput, error) { + res, err := ec.unmarshalInputProjectWhereInput(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) unmarshalNString2string(ctx context.Context, v any) (string, error) { + res, err := graphql.UnmarshalString(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNString2string(ctx context.Context, sel ast.SelectionSet, v string) graphql.Marshaler { + res := graphql.MarshalString(v) + if res == graphql.Null { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + } + return res +} + +func (ec *executionContext) unmarshalNString2ᚕstringᚄ(ctx context.Context, v any) ([]string, error) { + var vSlice []any + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]string, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNString2string(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) marshalNString2ᚕstringᚄ(ctx context.Context, sel ast.SelectionSet, v []string) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + for i := range v { + ret[i] = ec.marshalNString2string(ctx, sel, v[i]) + } + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) unmarshalNTime2timeᚐTime(ctx context.Context, v any) (time.Time, error) { + res, err := graphql.UnmarshalTime(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNTime2timeᚐTime(ctx context.Context, sel ast.SelectionSet, v time.Time) graphql.Marshaler { + res := graphql.MarshalTime(v) + if res == graphql.Null { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + } + return res +} + +func (ec *executionContext) marshalNTodo2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodo(ctx context.Context, sel ast.SelectionSet, v ent.Todo) graphql.Marshaler { + return ec._Todo(ctx, sel, &v) +} + +func (ec *executionContext) marshalNTodo2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodo(ctx context.Context, sel ast.SelectionSet, v *ent.Todo) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._Todo(ctx, sel, v) +} + +func (ec *executionContext) marshalNTodoConnection2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoConnection(ctx context.Context, sel ast.SelectionSet, v ent.TodoConnection) graphql.Marshaler { + return ec._TodoConnection(ctx, sel, &v) +} + +func (ec *executionContext) marshalNTodoConnection2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoConnection(ctx context.Context, sel ast.SelectionSet, v *ent.TodoConnection) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._TodoConnection(ctx, sel, v) +} + +func (ec *executionContext) unmarshalNTodoOrder2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoOrder(ctx context.Context, v any) (*ent.TodoOrder, error) { + res, err := ec.unmarshalInputTodoOrder(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) unmarshalNTodoOrderField2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoOrderField(ctx context.Context, v any) (*ent.TodoOrderField, error) { + var res = new(ent.TodoOrderField) + err := res.UnmarshalGQL(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNTodoOrderField2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoOrderField(ctx context.Context, sel ast.SelectionSet, v *ent.TodoOrderField) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return v +} + +func (ec *executionContext) unmarshalNTodoStatus2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋtodoᚐStatus(ctx context.Context, v any) (todo.Status, error) { + var res todo.Status + err := res.UnmarshalGQL(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNTodoStatus2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋtodoᚐStatus(ctx context.Context, sel ast.SelectionSet, v todo.Status) graphql.Marshaler { + return v +} + +func (ec *executionContext) unmarshalNTodoWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoWhereInput(ctx context.Context, v any) (*ent.TodoWhereInput, error) { + res, err := ec.unmarshalInputTodoWhereInput(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) unmarshalNUUID2githubᚗcomᚋgoogleᚋuuidᚐUUID(ctx context.Context, v any) (uuid.UUID, error) { + res, err := uuidgql.UnmarshalUUID(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNUUID2githubᚗcomᚋgoogleᚋuuidᚐUUID(ctx context.Context, sel ast.SelectionSet, v uuid.UUID) graphql.Marshaler { + res := uuidgql.MarshalUUID(v) + if res == graphql.Null { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + } + return res +} + +func (ec *executionContext) unmarshalNUint642uint64(ctx context.Context, v any) (uint64, error) { + res, err := graphql.UnmarshalUint64(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNUint642uint64(ctx context.Context, sel ast.SelectionSet, v uint64) graphql.Marshaler { + res := graphql.MarshalUint64(v) + if res == graphql.Null { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + } + return res +} + +func (ec *executionContext) unmarshalNUpdateFriendshipInput2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUpdateFriendshipInput(ctx context.Context, v any) (ent.UpdateFriendshipInput, error) { + res, err := ec.unmarshalInputUpdateFriendshipInput(ctx, v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) unmarshalNUpdateTodoInput2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUpdateTodoInput(ctx context.Context, v any) (ent.UpdateTodoInput, error) { + res, err := ec.unmarshalInputUpdateTodoInput(ctx, v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNUser2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUser(ctx context.Context, sel ast.SelectionSet, v *ent.User) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._User(ctx, sel, v) +} + +func (ec *executionContext) marshalNUserConnection2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUserConnection(ctx context.Context, sel ast.SelectionSet, v ent.UserConnection) graphql.Marshaler { + return ec._UserConnection(ctx, sel, &v) +} + +func (ec *executionContext) marshalNUserConnection2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUserConnection(ctx context.Context, sel ast.SelectionSet, v *ent.UserConnection) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec._UserConnection(ctx, sel, v) +} + +func (ec *executionContext) unmarshalNUserOrderField2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUserOrderField(ctx context.Context, v any) (*ent.UserOrderField, error) { + var res = new(ent.UserOrderField) + err := res.UnmarshalGQL(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalNUserOrderField2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUserOrderField(ctx context.Context, sel ast.SelectionSet, v *ent.UserOrderField) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return v +} + +func (ec *executionContext) unmarshalNUserWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUserWhereInput(ctx context.Context, v any) (*ent.UserWhereInput, error) { + res, err := ec.unmarshalInputUserWhereInput(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalN__Directive2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐDirective(ctx context.Context, sel ast.SelectionSet, v introspection.Directive) graphql.Marshaler { + return ec.___Directive(ctx, sel, &v) +} + +func (ec *executionContext) marshalN__Directive2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐDirectiveᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.Directive) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalN__Directive2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐDirective(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) unmarshalN__DirectiveLocation2string(ctx context.Context, v any) (string, error) { + res, err := graphql.UnmarshalString(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalN__DirectiveLocation2string(ctx context.Context, sel ast.SelectionSet, v string) graphql.Marshaler { + res := graphql.MarshalString(v) + if res == graphql.Null { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + } + return res +} + +func (ec *executionContext) unmarshalN__DirectiveLocation2ᚕstringᚄ(ctx context.Context, v any) ([]string, error) { + var vSlice []any + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]string, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalN__DirectiveLocation2string(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) marshalN__DirectiveLocation2ᚕstringᚄ(ctx context.Context, sel ast.SelectionSet, v []string) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalN__DirectiveLocation2string(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) marshalN__EnumValue2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐEnumValue(ctx context.Context, sel ast.SelectionSet, v introspection.EnumValue) graphql.Marshaler { + return ec.___EnumValue(ctx, sel, &v) +} + +func (ec *executionContext) marshalN__Field2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐField(ctx context.Context, sel ast.SelectionSet, v introspection.Field) graphql.Marshaler { + return ec.___Field(ctx, sel, &v) +} + +func (ec *executionContext) marshalN__InputValue2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValue(ctx context.Context, sel ast.SelectionSet, v introspection.InputValue) graphql.Marshaler { + return ec.___InputValue(ctx, sel, &v) +} + +func (ec *executionContext) marshalN__InputValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValueᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.InputValue) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalN__InputValue2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValue(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) marshalN__Type2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx context.Context, sel ast.SelectionSet, v introspection.Type) graphql.Marshaler { + return ec.___Type(ctx, sel, &v) +} + +func (ec *executionContext) marshalN__Type2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐTypeᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.Type) graphql.Marshaler { + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalN__Type2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) marshalN__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx context.Context, sel ast.SelectionSet, v *introspection.Type) graphql.Marshaler { + if v == nil { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + return graphql.Null + } + return ec.___Type(ctx, sel, v) +} + +func (ec *executionContext) unmarshalN__TypeKind2string(ctx context.Context, v any) (string, error) { + res, err := graphql.UnmarshalString(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalN__TypeKind2string(ctx context.Context, sel ast.SelectionSet, v string) graphql.Marshaler { + res := graphql.MarshalString(v) + if res == graphql.Null { + if !graphql.HasFieldError(ctx, graphql.GetFieldContext(ctx)) { + ec.Errorf(ctx, "the requested element is null which the schema does not allow") + } + } + return res +} + +func (ec *executionContext) unmarshalOBillProductWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐBillProductWhereInputᚄ(ctx context.Context, v any) ([]*ent.BillProductWhereInput, error) { + if v == nil { + return nil, nil + } + var vSlice []any + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]*ent.BillProductWhereInput, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNBillProductWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐBillProductWhereInput(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) unmarshalOBillProductWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐBillProductWhereInput(ctx context.Context, v any) (*ent.BillProductWhereInput, error) { + if v == nil { + return nil, nil + } + res, err := ec.unmarshalInputBillProductWhereInput(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) unmarshalOBoolean2bool(ctx context.Context, v any) (bool, error) { + res, err := graphql.UnmarshalBoolean(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalOBoolean2bool(ctx context.Context, sel ast.SelectionSet, v bool) graphql.Marshaler { + res := graphql.MarshalBoolean(v) + return res +} + +func (ec *executionContext) unmarshalOBoolean2ᚖbool(ctx context.Context, v any) (*bool, error) { + if v == nil { + return nil, nil + } + res, err := graphql.UnmarshalBoolean(v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalOBoolean2ᚖbool(ctx context.Context, sel ast.SelectionSet, v *bool) graphql.Marshaler { + if v == nil { + return graphql.Null + } + res := graphql.MarshalBoolean(*v) + return res +} + +func (ec *executionContext) marshalOCategory2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategory(ctx context.Context, sel ast.SelectionSet, v *ent.Category) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return ec._Category(ctx, sel, v) +} + +func (ec *executionContext) marshalOCategoryConfig2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋschematypeᚐCategoryConfig(ctx context.Context, sel ast.SelectionSet, v *schematype.CategoryConfig) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return ec._CategoryConfig(ctx, sel, v) +} + +func (ec *executionContext) unmarshalOCategoryConfigInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋschematypeᚐCategoryConfigᚄ(ctx context.Context, v any) ([]*schematype.CategoryConfig, error) { + if v == nil { + return nil, nil + } + var vSlice []any + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]*schematype.CategoryConfig, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNCategoryConfigInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋschematypeᚐCategoryConfig(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) unmarshalOCategoryConfigInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋschematypeᚐCategoryConfig(ctx context.Context, v any) (*schematype.CategoryConfig, error) { + if v == nil { + return nil, nil + } + res, err := ec.unmarshalInputCategoryConfigInput(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalOCategoryEdge2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategoryEdge(ctx context.Context, sel ast.SelectionSet, v []*ent.CategoryEdge) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalOCategoryEdge2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategoryEdge(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + return ret +} + +func (ec *executionContext) marshalOCategoryEdge2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategoryEdge(ctx context.Context, sel ast.SelectionSet, v *ent.CategoryEdge) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return ec._CategoryEdge(ctx, sel, v) +} + +func (ec *executionContext) unmarshalOCategoryOrder2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategoryOrderᚄ(ctx context.Context, v any) ([]*ent.CategoryOrder, error) { + if v == nil { + return nil, nil + } + var vSlice []any + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]*ent.CategoryOrder, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNCategoryOrder2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategoryOrder(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) unmarshalOCategoryStatus2ᚕentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋcategoryᚐStatusᚄ(ctx context.Context, v any) ([]category.Status, error) { + if v == nil { + return nil, nil + } + var vSlice []any + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]category.Status, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNCategoryStatus2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋcategoryᚐStatus(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) marshalOCategoryStatus2ᚕentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋcategoryᚐStatusᚄ(ctx context.Context, sel ast.SelectionSet, v []category.Status) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalNCategoryStatus2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋcategoryᚐStatus(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) unmarshalOCategoryStatus2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋcategoryᚐStatus(ctx context.Context, v any) (*category.Status, error) { + if v == nil { + return nil, nil + } + var res = new(category.Status) + err := res.UnmarshalGQL(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalOCategoryStatus2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋcategoryᚐStatus(ctx context.Context, sel ast.SelectionSet, v *category.Status) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return v +} + +func (ec *executionContext) marshalOCategoryTypes2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋschematypeᚐCategoryTypes(ctx context.Context, sel ast.SelectionSet, v *schematype.CategoryTypes) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return ec._CategoryTypes(ctx, sel, v) +} + +func (ec *executionContext) unmarshalOCategoryTypesInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋschematypeᚐCategoryTypes(ctx context.Context, v any) (*schematype.CategoryTypes, error) { + if v == nil { + return nil, nil + } + res, err := ec.unmarshalInputCategoryTypesInput(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) unmarshalOCategoryWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategoryWhereInputᚄ(ctx context.Context, v any) ([]*ent.CategoryWhereInput, error) { + if v == nil { + return nil, nil + } + var vSlice []any + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]*ent.CategoryWhereInput, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNCategoryWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategoryWhereInput(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) unmarshalOCategoryWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCategoryWhereInput(ctx context.Context, v any) (*ent.CategoryWhereInput, error) { + if v == nil { + return nil, nil + } + res, err := ec.unmarshalInputCategoryWhereInput(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) unmarshalOCreateTodoInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCreateTodoInputᚄ(ctx context.Context, v any) ([]*ent.CreateTodoInput, error) { + if v == nil { + return nil, nil + } + var vSlice []any + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]*ent.CreateTodoInput, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNCreateTodoInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐCreateTodoInput(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) unmarshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx context.Context, v any) (*entgql.Cursor[int], error) { + if v == nil { + return nil, nil + } + var res = new(entgql.Cursor[int]) + err := res.UnmarshalGQL(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalOCursor2ᚖentgoᚗioᚋcontribᚋentgqlᚐCursor(ctx context.Context, sel ast.SelectionSet, v *entgql.Cursor[int]) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return v +} + +func (ec *executionContext) marshalOCustom2ᚕentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋcustomstructᚐCustomᚄ(ctx context.Context, sel ast.SelectionSet, v []customstruct.Custom) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalNCustom2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋcustomstructᚐCustom(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) marshalOCustom2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋcustomstructᚐCustom(ctx context.Context, sel ast.SelectionSet, v []*customstruct.Custom) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalOCustom2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋcustomstructᚐCustom(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + return ret +} + +func (ec *executionContext) marshalOCustom2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋschemaᚋcustomstructᚐCustom(ctx context.Context, sel ast.SelectionSet, v *customstruct.Custom) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return ec._Custom(ctx, sel, v) +} + +func (ec *executionContext) unmarshalODuration2timeᚐDuration(ctx context.Context, v any) (time.Duration, error) { + res, err := durationgql.UnmarshalDuration(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalODuration2timeᚐDuration(ctx context.Context, sel ast.SelectionSet, v time.Duration) graphql.Marshaler { + res := durationgql.MarshalDuration(v) + return res +} + +func (ec *executionContext) unmarshalODuration2ᚕtimeᚐDurationᚄ(ctx context.Context, v any) ([]time.Duration, error) { + if v == nil { + return nil, nil + } + var vSlice []any + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]time.Duration, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNDuration2timeᚐDuration(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) marshalODuration2ᚕtimeᚐDurationᚄ(ctx context.Context, sel ast.SelectionSet, v []time.Duration) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + for i := range v { + ret[i] = ec.marshalNDuration2timeᚐDuration(ctx, sel, v[i]) + } + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) unmarshalODuration2ᚖtimeᚐDuration(ctx context.Context, v any) (*time.Duration, error) { + if v == nil { + return nil, nil + } + res, err := durationgql.UnmarshalDuration(v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalODuration2ᚖtimeᚐDuration(ctx context.Context, sel ast.SelectionSet, v *time.Duration) graphql.Marshaler { + if v == nil { + return graphql.Null + } + res := durationgql.MarshalDuration(*v) + return res +} + +func (ec *executionContext) marshalOFriendship2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐFriendship(ctx context.Context, sel ast.SelectionSet, v *ent.Friendship) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return ec._Friendship(ctx, sel, v) +} + +func (ec *executionContext) marshalOFriendshipEdge2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐFriendshipEdge(ctx context.Context, sel ast.SelectionSet, v []*ent.FriendshipEdge) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalOFriendshipEdge2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐFriendshipEdge(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + return ret +} + +func (ec *executionContext) marshalOFriendshipEdge2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐFriendshipEdge(ctx context.Context, sel ast.SelectionSet, v *ent.FriendshipEdge) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return ec._FriendshipEdge(ctx, sel, v) +} + +func (ec *executionContext) unmarshalOFriendshipWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐFriendshipWhereInputᚄ(ctx context.Context, v any) ([]*ent.FriendshipWhereInput, error) { + if v == nil { + return nil, nil + } + var vSlice []any + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]*ent.FriendshipWhereInput, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNFriendshipWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐFriendshipWhereInput(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) unmarshalOFriendshipWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐFriendshipWhereInput(ctx context.Context, v any) (*ent.FriendshipWhereInput, error) { + if v == nil { + return nil, nil + } + res, err := ec.unmarshalInputFriendshipWhereInput(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalOGroup2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐGroup(ctx context.Context, sel ast.SelectionSet, v *ent.Group) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return ec._Group(ctx, sel, v) +} + +func (ec *executionContext) marshalOGroupEdge2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐGroupEdge(ctx context.Context, sel ast.SelectionSet, v []*ent.GroupEdge) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalOGroupEdge2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐGroupEdge(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + return ret +} + +func (ec *executionContext) marshalOGroupEdge2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐGroupEdge(ctx context.Context, sel ast.SelectionSet, v *ent.GroupEdge) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return ec._GroupEdge(ctx, sel, v) +} + +func (ec *executionContext) unmarshalOGroupWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐGroupWhereInputᚄ(ctx context.Context, v any) ([]*ent.GroupWhereInput, error) { + if v == nil { + return nil, nil + } + var vSlice []any + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]*ent.GroupWhereInput, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNGroupWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐGroupWhereInput(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) unmarshalOGroupWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐGroupWhereInput(ctx context.Context, v any) (*ent.GroupWhereInput, error) { + if v == nil { + return nil, nil + } + res, err := ec.unmarshalInputGroupWhereInput(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) unmarshalOID2int(ctx context.Context, v any) (int, error) { + res, err := graphql.UnmarshalIntID(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalOID2int(ctx context.Context, sel ast.SelectionSet, v int) graphql.Marshaler { + res := graphql.MarshalIntID(v) + return res +} + +func (ec *executionContext) unmarshalOID2ᚕintᚄ(ctx context.Context, v any) ([]int, error) { + if v == nil { + return nil, nil + } + var vSlice []any + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]int, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNID2int(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) marshalOID2ᚕintᚄ(ctx context.Context, sel ast.SelectionSet, v []int) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + for i := range v { + ret[i] = ec.marshalNID2int(ctx, sel, v[i]) + } + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) unmarshalOID2ᚖint(ctx context.Context, v any) (*int, error) { + if v == nil { + return nil, nil + } + res, err := graphql.UnmarshalIntID(v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalOID2ᚖint(ctx context.Context, sel ast.SelectionSet, v *int) graphql.Marshaler { + if v == nil { + return graphql.Null + } + res := graphql.MarshalIntID(*v) + return res +} + +func (ec *executionContext) unmarshalOInt2int(ctx context.Context, v any) (int, error) { + res, err := graphql.UnmarshalInt(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalOInt2int(ctx context.Context, sel ast.SelectionSet, v int) graphql.Marshaler { + res := graphql.MarshalInt(v) + return res +} + +func (ec *executionContext) unmarshalOInt2ᚕintᚄ(ctx context.Context, v any) ([]int, error) { + if v == nil { + return nil, nil + } + var vSlice []any + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]int, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNInt2int(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) marshalOInt2ᚕintᚄ(ctx context.Context, sel ast.SelectionSet, v []int) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + for i := range v { + ret[i] = ec.marshalNInt2int(ctx, sel, v[i]) + } + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) unmarshalOInt2ᚖint(ctx context.Context, v any) (*int, error) { + if v == nil { + return nil, nil + } + res, err := graphql.UnmarshalInt(v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalOInt2ᚖint(ctx context.Context, sel ast.SelectionSet, v *int) graphql.Marshaler { + if v == nil { + return graphql.Null + } + res := graphql.MarshalInt(*v) + return res +} + +func (ec *executionContext) unmarshalOMap2map(ctx context.Context, v any) (map[string]interface{}, error) { + if v == nil { + return nil, nil + } + res, err := graphql.UnmarshalMap(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalOMap2map(ctx context.Context, sel ast.SelectionSet, v map[string]interface{}) graphql.Marshaler { + if v == nil { + return graphql.Null + } + res := graphql.MarshalMap(v) + return res +} + +func (ec *executionContext) marshalONode2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐNoder(ctx context.Context, sel ast.SelectionSet, v ent.Noder) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return ec._Node(ctx, sel, v) +} + +func (ec *executionContext) marshalOOneToMany2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToManyᚄ(ctx context.Context, sel ast.SelectionSet, v []*ent.OneToMany) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalNOneToMany2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToMany(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) marshalOOneToMany2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToMany(ctx context.Context, sel ast.SelectionSet, v *ent.OneToMany) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return ec._OneToMany(ctx, sel, v) +} + +func (ec *executionContext) marshalOOneToManyEdge2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToManyEdge(ctx context.Context, sel ast.SelectionSet, v []*ent.OneToManyEdge) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalOOneToManyEdge2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToManyEdge(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + return ret +} + +func (ec *executionContext) marshalOOneToManyEdge2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToManyEdge(ctx context.Context, sel ast.SelectionSet, v *ent.OneToManyEdge) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return ec._OneToManyEdge(ctx, sel, v) +} + +func (ec *executionContext) unmarshalOOneToManyOrder2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToManyOrder(ctx context.Context, v any) (*ent.OneToManyOrder, error) { + if v == nil { + return nil, nil + } + res, err := ec.unmarshalInputOneToManyOrder(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) unmarshalOOneToManyWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToManyWhereInputᚄ(ctx context.Context, v any) ([]*ent.OneToManyWhereInput, error) { + if v == nil { + return nil, nil + } + var vSlice []any + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]*ent.OneToManyWhereInput, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNOneToManyWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToManyWhereInput(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) unmarshalOOneToManyWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOneToManyWhereInput(ctx context.Context, v any) (*ent.OneToManyWhereInput, error) { + if v == nil { + return nil, nil + } + res, err := ec.unmarshalInputOneToManyWhereInput(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) unmarshalOOrganizationWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOrganizationWhereInputᚄ(ctx context.Context, v any) ([]*ent.OrganizationWhereInput, error) { + if v == nil { + return nil, nil + } + var vSlice []any + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]*ent.OrganizationWhereInput, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNOrganizationWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOrganizationWhereInput(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) unmarshalOOrganizationWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐOrganizationWhereInput(ctx context.Context, v any) (*ent.OrganizationWhereInput, error) { + if v == nil { + return nil, nil + } + res, err := ec.unmarshalInputOrganizationWhereInput(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) unmarshalOProjectWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐProjectWhereInputᚄ(ctx context.Context, v any) ([]*ent.ProjectWhereInput, error) { + if v == nil { + return nil, nil + } + var vSlice []any + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]*ent.ProjectWhereInput, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNProjectWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐProjectWhereInput(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) unmarshalOProjectWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐProjectWhereInput(ctx context.Context, v any) (*ent.ProjectWhereInput, error) { + if v == nil { + return nil, nil + } + res, err := ec.unmarshalInputProjectWhereInput(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) unmarshalOString2string(ctx context.Context, v any) (string, error) { + res, err := graphql.UnmarshalString(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalOString2string(ctx context.Context, sel ast.SelectionSet, v string) graphql.Marshaler { + res := graphql.MarshalString(v) + return res +} + +func (ec *executionContext) unmarshalOString2ᚕstringᚄ(ctx context.Context, v any) ([]string, error) { + if v == nil { + return nil, nil + } + var vSlice []any + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]string, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNString2string(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) marshalOString2ᚕstringᚄ(ctx context.Context, sel ast.SelectionSet, v []string) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + for i := range v { + ret[i] = ec.marshalNString2string(ctx, sel, v[i]) + } + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) unmarshalOString2ᚖstring(ctx context.Context, v any) (*string, error) { + if v == nil { + return nil, nil + } + res, err := graphql.UnmarshalString(v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalOString2ᚖstring(ctx context.Context, sel ast.SelectionSet, v *string) graphql.Marshaler { + if v == nil { + return graphql.Null + } + res := graphql.MarshalString(*v) + return res +} + +func (ec *executionContext) unmarshalOTime2ᚕtimeᚐTimeᚄ(ctx context.Context, v any) ([]time.Time, error) { + if v == nil { + return nil, nil + } + var vSlice []any + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]time.Time, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNTime2timeᚐTime(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) marshalOTime2ᚕtimeᚐTimeᚄ(ctx context.Context, sel ast.SelectionSet, v []time.Time) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + for i := range v { + ret[i] = ec.marshalNTime2timeᚐTime(ctx, sel, v[i]) + } + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) unmarshalOTime2ᚖtimeᚐTime(ctx context.Context, v any) (*time.Time, error) { + if v == nil { + return nil, nil + } + res, err := graphql.UnmarshalTime(v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalOTime2ᚖtimeᚐTime(ctx context.Context, sel ast.SelectionSet, v *time.Time) graphql.Marshaler { + if v == nil { + return graphql.Null + } + res := graphql.MarshalTime(*v) + return res +} + +func (ec *executionContext) marshalOTodo2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodo(ctx context.Context, sel ast.SelectionSet, v *ent.Todo) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return ec._Todo(ctx, sel, v) +} + +func (ec *executionContext) marshalOTodoEdge2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoEdge(ctx context.Context, sel ast.SelectionSet, v []*ent.TodoEdge) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalOTodoEdge2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoEdge(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + return ret +} + +func (ec *executionContext) marshalOTodoEdge2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoEdge(ctx context.Context, sel ast.SelectionSet, v *ent.TodoEdge) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return ec._TodoEdge(ctx, sel, v) +} + +func (ec *executionContext) unmarshalOTodoOrder2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoOrderᚄ(ctx context.Context, v any) ([]*ent.TodoOrder, error) { + if v == nil { + return nil, nil + } + var vSlice []any + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]*ent.TodoOrder, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNTodoOrder2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoOrder(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) unmarshalOTodoStatus2ᚕentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋtodoᚐStatusᚄ(ctx context.Context, v any) ([]todo.Status, error) { + if v == nil { + return nil, nil + } + var vSlice []any + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]todo.Status, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNTodoStatus2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋtodoᚐStatus(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) marshalOTodoStatus2ᚕentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋtodoᚐStatusᚄ(ctx context.Context, sel ast.SelectionSet, v []todo.Status) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalNTodoStatus2entgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋtodoᚐStatus(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) unmarshalOTodoStatus2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋtodoᚐStatus(ctx context.Context, v any) (*todo.Status, error) { + if v == nil { + return nil, nil + } + var res = new(todo.Status) + err := res.UnmarshalGQL(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalOTodoStatus2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚋtodoᚐStatus(ctx context.Context, sel ast.SelectionSet, v *todo.Status) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return v +} + +func (ec *executionContext) unmarshalOTodoWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoWhereInputᚄ(ctx context.Context, v any) ([]*ent.TodoWhereInput, error) { + if v == nil { + return nil, nil + } + var vSlice []any + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]*ent.TodoWhereInput, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNTodoWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoWhereInput(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) unmarshalOTodoWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐTodoWhereInput(ctx context.Context, v any) (*ent.TodoWhereInput, error) { + if v == nil { + return nil, nil + } + res, err := ec.unmarshalInputTodoWhereInput(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) unmarshalOUUID2ᚕgithubᚗcomᚋgoogleᚋuuidᚐUUIDᚄ(ctx context.Context, v any) ([]uuid.UUID, error) { + if v == nil { + return nil, nil + } + var vSlice []any + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]uuid.UUID, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNUUID2githubᚗcomᚋgoogleᚋuuidᚐUUID(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) marshalOUUID2ᚕgithubᚗcomᚋgoogleᚋuuidᚐUUIDᚄ(ctx context.Context, sel ast.SelectionSet, v []uuid.UUID) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + for i := range v { + ret[i] = ec.marshalNUUID2githubᚗcomᚋgoogleᚋuuidᚐUUID(ctx, sel, v[i]) + } + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) unmarshalOUUID2ᚖgithubᚗcomᚋgoogleᚋuuidᚐUUID(ctx context.Context, v any) (*uuid.UUID, error) { + if v == nil { + return nil, nil + } + res, err := uuidgql.UnmarshalUUID(v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalOUUID2ᚖgithubᚗcomᚋgoogleᚋuuidᚐUUID(ctx context.Context, sel ast.SelectionSet, v *uuid.UUID) graphql.Marshaler { + if v == nil { + return graphql.Null + } + res := uuidgql.MarshalUUID(*v) + return res +} + +func (ec *executionContext) unmarshalOUint642uint64(ctx context.Context, v any) (uint64, error) { + res, err := graphql.UnmarshalUint64(v) + return res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalOUint642uint64(ctx context.Context, sel ast.SelectionSet, v uint64) graphql.Marshaler { + res := graphql.MarshalUint64(v) + return res +} + +func (ec *executionContext) unmarshalOUint642ᚕuint64ᚄ(ctx context.Context, v any) ([]uint64, error) { + if v == nil { + return nil, nil + } + var vSlice []any + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]uint64, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNUint642uint64(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) marshalOUint642ᚕuint64ᚄ(ctx context.Context, sel ast.SelectionSet, v []uint64) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + for i := range v { + ret[i] = ec.marshalNUint642uint64(ctx, sel, v[i]) + } + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) unmarshalOUint642ᚖuint64(ctx context.Context, v any) (*uint64, error) { + if v == nil { + return nil, nil + } + res, err := graphql.UnmarshalUint64(v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalOUint642ᚖuint64(ctx context.Context, sel ast.SelectionSet, v *uint64) graphql.Marshaler { + if v == nil { + return graphql.Null + } + res := graphql.MarshalUint64(*v) + return res +} + +func (ec *executionContext) marshalOUser2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUser(ctx context.Context, sel ast.SelectionSet, v *ent.User) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return ec._User(ctx, sel, v) +} + +func (ec *executionContext) marshalOUserEdge2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUserEdge(ctx context.Context, sel ast.SelectionSet, v []*ent.UserEdge) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalOUserEdge2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUserEdge(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + return ret +} + +func (ec *executionContext) marshalOUserEdge2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUserEdge(ctx context.Context, sel ast.SelectionSet, v *ent.UserEdge) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return ec._UserEdge(ctx, sel, v) +} + +func (ec *executionContext) unmarshalOUserOrder2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUserOrder(ctx context.Context, v any) (*ent.UserOrder, error) { + if v == nil { + return nil, nil + } + res, err := ec.unmarshalInputUserOrder(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) unmarshalOUserWhereInput2ᚕᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUserWhereInputᚄ(ctx context.Context, v any) ([]*ent.UserWhereInput, error) { + if v == nil { + return nil, nil + } + var vSlice []any + if v != nil { + vSlice = graphql.CoerceList(v) + } + var err error + res := make([]*ent.UserWhereInput, len(vSlice)) + for i := range vSlice { + ctx := graphql.WithPathContext(ctx, graphql.NewPathWithIndex(i)) + res[i], err = ec.unmarshalNUserWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUserWhereInput(ctx, vSlice[i]) + if err != nil { + return nil, err + } + } + return res, nil +} + +func (ec *executionContext) unmarshalOUserWhereInput2ᚖentgoᚗioᚋcontribᚋentgqlᚋinternalᚋtodoglobalidᚋentᚐUserWhereInput(ctx context.Context, v any) (*ent.UserWhereInput, error) { + if v == nil { + return nil, nil + } + res, err := ec.unmarshalInputUserWhereInput(ctx, v) + return &res, graphql.ErrorOnPath(ctx, err) +} + +func (ec *executionContext) marshalO__EnumValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐEnumValueᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.EnumValue) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalN__EnumValue2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐEnumValue(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) marshalO__Field2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐFieldᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.Field) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalN__Field2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐField(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) marshalO__InputValue2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValueᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.InputValue) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalN__InputValue2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐInputValue(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) marshalO__Schema2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐSchema(ctx context.Context, sel ast.SelectionSet, v *introspection.Schema) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return ec.___Schema(ctx, sel, v) +} + +func (ec *executionContext) marshalO__Type2ᚕgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐTypeᚄ(ctx context.Context, sel ast.SelectionSet, v []introspection.Type) graphql.Marshaler { + if v == nil { + return graphql.Null + } + ret := make(graphql.Array, len(v)) + var wg sync.WaitGroup + isLen1 := len(v) == 1 + if !isLen1 { + wg.Add(len(v)) + } + for i := range v { + i := i + fc := &graphql.FieldContext{ + Index: &i, + Result: &v[i], + } + ctx := graphql.WithFieldContext(ctx, fc) + f := func(i int) { + defer func() { + if r := recover(); r != nil { + ec.Error(ctx, ec.Recover(ctx, r)) + ret = nil + } + }() + if !isLen1 { + defer wg.Done() + } + ret[i] = ec.marshalN__Type2githubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx, sel, v[i]) + } + if isLen1 { + f(i) + } else { + go f(i) + } + + } + wg.Wait() + + for _, e := range ret { + if e == graphql.Null { + return graphql.Null + } + } + + return ret +} + +func (ec *executionContext) marshalO__Type2ᚖgithubᚗcomᚋ99designsᚋgqlgenᚋgraphqlᚋintrospectionᚐType(ctx context.Context, sel ast.SelectionSet, v *introspection.Type) graphql.Marshaler { + if v == nil { + return graphql.Null + } + return ec.___Type(ctx, sel, v) +} + +// endregion ***************************** type.gotpl ***************************** diff --git a/entgql/internal/todoglobalid/gqlgen.yml b/entgql/internal/todoglobalid/gqlgen.yml new file mode 100644 index 000000000..55705238b --- /dev/null +++ b/entgql/internal/todoglobalid/gqlgen.yml @@ -0,0 +1,57 @@ +# Copyright (c) 2004-present Facebook All rights reserved. +# Use of this source code is governed by a BSD-style +# license that can be found in the LICENSE file. + +schema: + - todo.graphql + # The ent.graphql schema was generated by Ent. + - ent.graphql + +resolver: + layout: follow-schema + preserve_resolver: false + dir: . + +autobind: + # Fix binding for the `Field` interface. + - github.com/99designs/gqlgen/graphql/introspection + - entgo.io/contrib/entgql/internal/todoglobalid/ent + # Auto-bind the generated `Status` enum to GraphQL. + - entgo.io/contrib/entgql/internal/todoglobalid/ent/todo + - entgo.io/contrib/entgql/internal/todoglobalid/ent/schema/customstruct + +# Disable the generated getters for all models and interfaces. +omit_getters: true +models: + ID: + model: + - github.com/99designs/gqlgen/graphql.IntID + Uint64: + model: + - github.com/99designs/gqlgen/graphql.Uint64 + Duration: + model: + - entgo.io/contrib/entgql/internal/todoglobalid/ent/schema/durationgql.Duration + Map: + model: + - github.com/99designs/gqlgen/graphql.Map + Node: + model: + - entgo.io/contrib/entgql/internal/todoglobalid/ent.Noder + # Custom mapping from GraphQL `CategoryConfig` and + # `CategoryConfigInput` to `schematype.CategoryConfig`. + CategoryConfig: + model: + - entgo.io/contrib/entgql/internal/todoglobalid/ent/schema/schematype.CategoryConfig + CategoryConfigInput: + model: + - entgo.io/contrib/entgql/internal/todoglobalid/ent/schema/schematype.CategoryConfig + CategoryTypes: + model: + - entgo.io/contrib/entgql/internal/todoglobalid/ent/schema/schematype.CategoryTypes + CategoryTypesInput: + model: + - entgo.io/contrib/entgql/internal/todoglobalid/ent/schema/schematype.CategoryTypes + UUID: + model: + - entgo.io/contrib/entgql/internal/todouuid/ent/schema/uuidgql.UUID diff --git a/entgql/internal/todoglobalid/has_permission.go b/entgql/internal/todoglobalid/has_permission.go new file mode 100644 index 000000000..0d28e10ef --- /dev/null +++ b/entgql/internal/todoglobalid/has_permission.go @@ -0,0 +1,33 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package todo + +import ( + "context" + + "github.com/99designs/gqlgen/graphql" +) + +func HasPermission() func(context.Context, interface{}, graphql.Resolver, []string) (interface{}, error) { + return func( + ctx context.Context, + obj interface{}, + next graphql.Resolver, + permissions []string, + ) (res interface{}, err error) { + // you can do your thing here for permissions + return next(ctx) + } +} diff --git a/entgql/internal/todoglobalid/models_gen.go b/entgql/internal/todoglobalid/models_gen.go new file mode 100644 index 000000000..f7072f773 --- /dev/null +++ b/entgql/internal/todoglobalid/models_gen.go @@ -0,0 +1,7 @@ +// Code generated by github.com/99designs/gqlgen, DO NOT EDIT. + +package todo + +type NamedNode interface { + IsNamedNode() +} diff --git a/entgql/internal/todoglobalid/resolver.go b/entgql/internal/todoglobalid/resolver.go new file mode 100644 index 000000000..6bd1c909e --- /dev/null +++ b/entgql/internal/todoglobalid/resolver.go @@ -0,0 +1,33 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package todo + +import ( + "entgo.io/contrib/entgql/internal/todoglobalid/ent" + "github.com/99designs/gqlgen/graphql" +) + +// Resolver is the resolver root. +type Resolver struct{ client *ent.Client } + +// NewSchema creates a graphql executable schema. +func NewSchema(client *ent.Client) graphql.ExecutableSchema { + return NewExecutableSchema(Config{ + Resolvers: &Resolver{client}, + Directives: DirectiveRoot{ + HasPermissions: HasPermission(), + }, + }) +} diff --git a/entgql/internal/todoglobalid/schema/annotation/has_permissions.go b/entgql/internal/todoglobalid/schema/annotation/has_permissions.go new file mode 100644 index 000000000..e2f380fa3 --- /dev/null +++ b/entgql/internal/todoglobalid/schema/annotation/has_permissions.go @@ -0,0 +1,42 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package annotation + +import ( + "entgo.io/contrib/entgql" + "github.com/vektah/gqlparser/v2/ast" +) + +func HasPermissions(permissions []string) entgql.Directive { + children := make(ast.ChildValueList, 0, len(permissions)) + for _, p := range permissions { + children = append(children, &ast.ChildValue{ + Value: &ast.Value{ + Raw: p, + Kind: ast.StringValue, + }, + }) + } + return entgql.NewDirective( + "hasPermissions", + &ast.Argument{ + Name: "permissions", + Value: &ast.Value{ + Children: children, + Kind: ast.ListValue, + }, + }, + ) +} diff --git a/entgql/internal/todoglobalid/schema/billproduct.go b/entgql/internal/todoglobalid/schema/billproduct.go new file mode 100644 index 000000000..372c21f9e --- /dev/null +++ b/entgql/internal/todoglobalid/schema/billproduct.go @@ -0,0 +1,43 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package schema + +import ( + "entgo.io/contrib/entgql" + "entgo.io/ent" + "entgo.io/ent/schema" + "entgo.io/ent/schema/field" +) + +// BillProduct holds the schema definition for the BillProduct entity. +type BillProduct struct { + ent.Schema +} + +// Fields of the BillProduct. +func (BillProduct) Fields() []ent.Field { + return []ent.Field{ + field.String("name"), + field.String("sku"), + field.Uint64("quantity").Annotations(entgql.Type("Uint64")), + } +} + +// Annotations returns BillProduct annotations. +func (BillProduct) Annotations() []schema.Annotation { + return []schema.Annotation{ + entgql.QueryField(), + } +} diff --git a/entgql/internal/todoglobalid/schema/category.go b/entgql/internal/todoglobalid/schema/category.go new file mode 100644 index 000000000..9e667219e --- /dev/null +++ b/entgql/internal/todoglobalid/schema/category.go @@ -0,0 +1,105 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package schema + +import ( + "time" + + "entgo.io/contrib/entgql" + "entgo.io/ent" + "entgo.io/ent/dialect" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/schema/schematype" +) + +// Category holds the schema definition for the Category entity. +type Category struct { + ent.Schema +} + +// Fields of the Category. +func (Category) Fields() []ent.Field { + return []ent.Field{ + field.Int("id"). + Annotations( + // Setting the OrderField explicitly on the "ID" + // field, adds it to the generated GraphQL schema. + entgql.OrderField("ID"), + ), + field.Text("text"). + NotEmpty(). + Annotations( + entgql.OrderField("TEXT"), + ), + field.Enum("status"). + NamedValues( + "Enabled", "ENABLED", + "Disabled", "DISABLED", + ). + Annotations( + entgql.Type("CategoryStatus"), + entgql.OrderField("STATUS"), + ), + field.Other("config", &schematype.CategoryConfig{}). + SchemaType(map[string]string{ + dialect.SQLite: "json", + }). + Optional(), + field.JSON("types", &schematype.CategoryTypes{}). + Optional(), + field.Int64("duration"). + GoType(time.Duration(0)). + Optional(). + Annotations( + entgql.OrderField("DURATION"), + entgql.Type("Duration"), + ), + field.Uint64("count"). + Optional(). + Annotations( + entgql.OrderField("COUNT"), + entgql.Type("Uint64"), + ), + field.Strings("strings"). + Optional(). + Deprecated("use `string` instead"), + } +} + +// Edges of the Category. +func (Category) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("todos", Todo.Type). + Annotations( + entgql.RelayConnection(), + entgql.OrderField("TODOS_COUNT"), + ), + edge.To("sub_categories", Category.Type). + Annotations(entgql.RelayConnection()), + } +} + +// Annotations returns Todo annotations. +func (Category) Annotations() []schema.Annotation { + return []schema.Annotation{ + entgql.QueryField(), + entgql.RelayConnection(), + entgql.Mutations(entgql.MutationCreate(), entgql.MutationUpdate()), + entgql.MultiOrder(), + } +} diff --git a/entgql/internal/todoglobalid/schema/customstruct/custom.go b/entgql/internal/todoglobalid/schema/customstruct/custom.go new file mode 100644 index 000000000..fa525613c --- /dev/null +++ b/entgql/internal/todoglobalid/schema/customstruct/custom.go @@ -0,0 +1,19 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package customstruct + +type Custom struct { + Info string +} diff --git a/entgql/internal/todoglobalid/schema/durationgql/durationgql.go b/entgql/internal/todoglobalid/schema/durationgql/durationgql.go new file mode 100644 index 000000000..04574034c --- /dev/null +++ b/entgql/internal/todoglobalid/schema/durationgql/durationgql.go @@ -0,0 +1,48 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package durationgql + +import ( + "encoding/json" + "fmt" + "io" + "strconv" + "time" + + "github.com/99designs/gqlgen/graphql" +) + +func MarshalDuration(t time.Duration) graphql.Marshaler { + return graphql.WriterFunc(func(w io.Writer) { + _, _ = io.WriteString(w, strconv.FormatInt(int64(t), 10)) + }) +} + +func UnmarshalDuration(v interface{}) (time.Duration, error) { + switch v := v.(type) { + case int64: + return time.Duration(v), nil + case string: + return time.ParseDuration(v) + case json.Number: + i, err := v.Int64() + if err != nil { + return 0, err + } + return time.Duration(i), nil + default: + return 0, fmt.Errorf("invalid type %T, expect string", v) + } +} diff --git a/entgql/internal/todoglobalid/schema/friendship.go b/entgql/internal/todoglobalid/schema/friendship.go new file mode 100644 index 000000000..c41664c15 --- /dev/null +++ b/entgql/internal/todoglobalid/schema/friendship.go @@ -0,0 +1,64 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package schema + +import ( + "time" + + "entgo.io/contrib/entgql" + "entgo.io/ent" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" +) + +// Friendship holds the edge schema definition of the Friendship relationship. +type Friendship struct { + ent.Schema +} + +// Fields of the Friendship. +func (Friendship) Fields() []ent.Field { + return []ent.Field{ + field.Time("created_at"). + Default(time.Now), + field.Int("user_id"), + field.Int("friend_id"), + } +} + +// Edges of the Friendship. +func (Friendship) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("user", User.Type). + Required(). + Unique(). + Field("user_id"), + edge.To("friend", User.Type). + Required(). + Unique(). + Field("friend_id"), + } +} + +// Annotations of the Friendship. +func (Friendship) Annotations() []schema.Annotation { + return []schema.Annotation{ + entgql.RelayConnection(), + entgql.Mutations( + entgql.MutationUpdate(), + ), + } +} diff --git a/entgql/internal/todoglobalid/schema/group.go b/entgql/internal/todoglobalid/schema/group.go new file mode 100644 index 000000000..87ba62935 --- /dev/null +++ b/entgql/internal/todoglobalid/schema/group.go @@ -0,0 +1,59 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package schema + +import ( + "entgo.io/contrib/entgql" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/schema/annotation" + "entgo.io/ent" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" +) + +// Group holds the schema definition for the Group entity. +type Group struct { + ent.Schema +} + +// Fields of the Group. +func (Group) Fields() []ent.Field { + return []ent.Field{ + field.String("name"). + Default("Unknown"), + } +} + +// Edges of the Group. +func (Group) Edges() []ent.Edge { + return []ent.Edge{ + edge.From("users", User.Type). + Ref("groups"). + Annotations(entgql.RelayConnection()), + } +} + +// Annotations returns Group annotations. +func (Group) Annotations() []schema.Annotation { + return []schema.Annotation{ + entgql.RelayConnection(), + entgql.QueryField(), + entgql.Directives( + annotation.HasPermissions([]string{"ADMIN", "MODERATOR"}), + ), + entgql.MultiOrder(), + entgql.Implements("NamedNode"), + } +} diff --git a/entgql/internal/todoglobalid/schema/mixin.go b/entgql/internal/todoglobalid/schema/mixin.go new file mode 100644 index 000000000..8cc04f4f1 --- /dev/null +++ b/entgql/internal/todoglobalid/schema/mixin.go @@ -0,0 +1,69 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package schema + +import "entgo.io/ent" + +type filterFields struct { + ent.Interface + fields map[string]struct{} +} + +func (f *filterFields) Fields() []ent.Field { + fields := f.Interface.Fields() + result := make([]ent.Field, 0, len(fields)) + for _, field := range fields { + if _, ok := f.fields[field.Descriptor().Name]; !ok { + result = append(result, field) + } + } + + return result +} + +func FilterFields(s ent.Interface, filters ...string) ent.Interface { + fields := make(map[string]struct{}) + for _, filter := range filters { + fields[filter] = struct{}{} + } + + return &filterFields{Interface: s, fields: fields} +} + +type filterEdges struct { + ent.Interface + edges map[string]struct{} +} + +func (f *filterEdges) Edges() []ent.Edge { + edges := f.Interface.Edges() + result := make([]ent.Edge, 0, len(edges)) + for _, field := range edges { + if _, ok := f.edges[field.Descriptor().Name]; !ok { + result = append(result, field) + } + } + + return result +} + +func FilterEdges(s ent.Interface, filters ...string) ent.Interface { + edges := make(map[string]struct{}) + for _, filter := range filters { + edges[filter] = struct{}{} + } + + return &filterEdges{Interface: s, edges: edges} +} diff --git a/entgql/internal/todoglobalid/schema/onetomany.go b/entgql/internal/todoglobalid/schema/onetomany.go new file mode 100644 index 000000000..16eeb1004 --- /dev/null +++ b/entgql/internal/todoglobalid/schema/onetomany.go @@ -0,0 +1,63 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package schema + +import ( + "entgo.io/contrib/entgql" + "entgo.io/ent" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" +) + +// OneToMany holds the schema definition for the OneToMany entity. +type OneToMany struct { + ent.Schema +} + +// Fields of the OneToMany. +func (OneToMany) Fields() []ent.Field { + return []ent.Field{ + field.String("name"). + NotEmpty(). + Annotations( + entgql.OrderField("NAME"), + ), + field.String("field2"). + Optional(), + field.Int("parent_id"). + Optional(). + Annotations( + entgql.Skip(entgql.SkipAll), + ), + } +} + +// Edges of the OneToMany. +func (OneToMany) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("children", OneToMany.Type). + From("parent"). + Field("parent_id"). + Unique(), + } +} + +func (OneToMany) Annotations() []schema.Annotation { + return []schema.Annotation{ + entgql.QueryField("oneToMany"), + entgql.RelayConnection(), + } +} diff --git a/entgql/internal/todoglobalid/schema/project.go b/entgql/internal/todoglobalid/schema/project.go new file mode 100644 index 000000000..9fe1a9cf5 --- /dev/null +++ b/entgql/internal/todoglobalid/schema/project.go @@ -0,0 +1,36 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package schema + +import ( + "entgo.io/contrib/entgql" + "entgo.io/ent" + "entgo.io/ent/schema/edge" +) + +// Project holds the schema definition for the GroupTodo entity. +type Project struct { + ent.Schema +} + +// Note, this schema intentionally does not have any fields. + +// Edges of the Project. +func (Project) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("todos", Todo.Type). + Annotations(entgql.RelayConnection()), + } +} diff --git a/entgql/internal/todoglobalid/schema/schematype/schematype.go b/entgql/internal/todoglobalid/schema/schematype/schematype.go new file mode 100644 index 000000000..000782edc --- /dev/null +++ b/entgql/internal/todoglobalid/schema/schematype/schematype.go @@ -0,0 +1,45 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package schematype provides custom types for ent/schema. +package schematype + +import ( + "database/sql/driver" + "encoding/json" +) + +// CategoryConfig implements the field.ValueScanner interface. +type CategoryConfig struct { + MaxMembers int `json:"maxMembers,omitempty"` +} + +func (t *CategoryConfig) Scan(v interface{}) (err error) { + switch v := v.(type) { + case string: + err = json.Unmarshal([]byte(v), t) + case []byte: + err = json.Unmarshal(v, t) + } + return +} + +func (t *CategoryConfig) Value() (driver.Value, error) { + return json.Marshal(t) +} + +// CategoryTypes is a simple JSON type. +type CategoryTypes struct { + Public bool `json:"public,omitempty"` +} diff --git a/entgql/internal/todoglobalid/schema/todo.go b/entgql/internal/todoglobalid/schema/todo.go new file mode 100644 index 000000000..89f85f44d --- /dev/null +++ b/entgql/internal/todoglobalid/schema/todo.go @@ -0,0 +1,132 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package schema + +import ( + "time" + + "entgo.io/contrib/entgql" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/schema/customstruct" + "entgo.io/ent" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" +) + +// Todo defines the todo type schema. +type Todo struct { + ent.Schema +} + +// Fields returns todo fields. +func (Todo) Fields() []ent.Field { + return []ent.Field{ + field.Time("created_at"). + Default(time.Now). + Immutable(). + Annotations( + entgql.OrderField("CREATED_AT"), + entgql.Skip(entgql.SkipMutationCreateInput), + ), + field.Enum("status"). + NamedValues( + "InProgress", "IN_PROGRESS", + "Completed", "COMPLETED", + "Pending", "PENDING", + ). + Annotations( + entgql.OrderField("STATUS"), + ), + field.Int("priority"). + Default(0). + Annotations( + entgql.OrderField("PRIORITY_ORDER"), + entgql.MapsTo("priorityOrder"), + ), + field.Text("text"). + NotEmpty(). + Annotations( + entgql.OrderField("TEXT"), + ), + field.Bytes("blob"). + Annotations( + entgql.Skip(), + ). + Optional(), + field.Int("category_id"). + Optional(). + Immutable(). + Annotations( + entgql.MapsTo("categoryID", "category_id", "categoryX"), + ), + field.JSON("init", map[string]any{}). + Optional(). + Annotations(entgql.Type("Map")), + field.JSON("custom", []customstruct.Custom{}). + Annotations( + entgql.Skip(entgql.SkipMutationCreateInput), + entgql.Skip(entgql.SkipMutationUpdateInput), + ). + Optional(), + field.JSON("customp", []*customstruct.Custom{}). + Annotations( + entgql.Skip(entgql.SkipMutationCreateInput), + entgql.Skip(entgql.SkipMutationUpdateInput), + ). + Optional(), + field.Int("value"). + Default(0), + } +} + +// Edges returns todo edges. +func (Todo) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("children", Todo.Type). + Annotations( + entgql.RelayConnection(), + // For non-unique edges, the order field can be only on edge count. + // The convention is "UPPER()_COUNT". + entgql.OrderField("CHILDREN_COUNT"), + ). + From("parent"). + Annotations( + // For unique edges, the order field can be on the edge field that is defined + // as entgql.OrderField. The convention is "UPPER()_". + entgql.OrderField("PARENT_STATUS"), + ). + Unique(), + edge.From("category", Category.Type). + Ref("todos"). + Field("category_id"). + Unique(). + Immutable(). + Annotations( + entgql.OrderField("CATEGORY_TEXT"), + ), + edge.To("secret", VerySecret.Type). + Unique(), + } +} + +// Annotations returns Todo annotations. +func (Todo) Annotations() []schema.Annotation { + return []schema.Annotation{ + entgql.RelayConnection(), + entgql.QueryField().Description("This is the todo item"), + entgql.Mutations(entgql.MutationCreate(), entgql.MutationUpdate()), + entgql.MultiOrder(), + } +} diff --git a/entgql/internal/todoglobalid/schema/user.go b/entgql/internal/todoglobalid/schema/user.go new file mode 100644 index 000000000..c37be6637 --- /dev/null +++ b/entgql/internal/todoglobalid/schema/user.go @@ -0,0 +1,72 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package schema + +import ( + "entgo.io/contrib/entgql" + "entgo.io/ent" + "entgo.io/ent/schema" + "entgo.io/ent/schema/edge" + "entgo.io/ent/schema/field" + "github.com/google/uuid" +) + +// User holds the schema definition for the User entity. +type User struct { + ent.Schema +} + +// Fields of the User. +func (User) Fields() []ent.Field { + return []ent.Field{ + field.String("name"). + Default("Anonymous"), + field.UUID("username", uuid.UUID{}). + Default(uuid.New), + field.String("password"). + Sensitive(). + Optional(), + field.JSON("required_metadata", map[string]any{}), + field.JSON("metadata", map[string]any{}). + Optional(), + } +} + +// Edges of the User. +func (User) Edges() []ent.Edge { + return []ent.Edge{ + edge.To("groups", Group.Type). + Comment("The groups of the user"). + Annotations( + entgql.RelayConnection(), + entgql.OrderField("GROUPS_COUNT"), + ), + edge.To("friends", User.Type). + Through("friendships", Friendship.Type). + Annotations(entgql.RelayConnection()), + } +} + +// Annotations returns User annotations. +func (User) Annotations() []schema.Annotation { + return []schema.Annotation{ + entgql.RelayConnection(), + entgql.QueryField(), + entgql.Mutations( + entgql.MutationCreate(), + entgql.MutationUpdate(), + ), + } +} diff --git a/entgql/internal/todoglobalid/schema/verysecret.go b/entgql/internal/todoglobalid/schema/verysecret.go new file mode 100644 index 000000000..9081e6a79 --- /dev/null +++ b/entgql/internal/todoglobalid/schema/verysecret.go @@ -0,0 +1,40 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package schema + +import ( + "entgo.io/contrib/entgql" + "entgo.io/ent" + "entgo.io/ent/schema" + "entgo.io/ent/schema/field" +) + +// VerySecret defines the very secret type schema. +type VerySecret struct { + ent.Schema +} + +// Fields returns private fields. +func (VerySecret) Fields() []ent.Field { + return []ent.Field{ + field.String("password"), + } +} + +func (VerySecret) Annotations() []schema.Annotation { + return []schema.Annotation{ + entgql.Skip(), + } +} diff --git a/entgql/internal/todoglobalid/schema/workspace.go b/entgql/internal/todoglobalid/schema/workspace.go new file mode 100644 index 000000000..eacbe9801 --- /dev/null +++ b/entgql/internal/todoglobalid/schema/workspace.go @@ -0,0 +1,42 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package schema + +import ( + "entgo.io/contrib/entgql" + "entgo.io/ent" + "entgo.io/ent/schema" + "entgo.io/ent/schema/field" +) + +// Workspace defines the workspace type schema. +type Workspace struct { + ent.Schema +} + +// Fields returns workspace fields. +func (Workspace) Fields() []ent.Field { + return []ent.Field{ + field.String("name"), + } +} + +func (Workspace) Annotations() []schema.Annotation { + return []schema.Annotation{ + // Intentionally change the type + // name to test fields collection. + entgql.Type("Organization"), + } +} diff --git a/entgql/internal/todoglobalid/server/server.go b/entgql/internal/todoglobalid/server/server.go new file mode 100644 index 000000000..db0aed521 --- /dev/null +++ b/entgql/internal/todoglobalid/server/server.go @@ -0,0 +1,77 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package main + +import ( + "context" + "net/http" + "time" + + "entgo.io/contrib/entgql" + "entgo.io/contrib/entgql/internal/todoglobalid" + "entgo.io/contrib/entgql/internal/todoglobalid/ent" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/migrate" + "github.com/99designs/gqlgen/graphql/handler" + "github.com/99designs/gqlgen/graphql/handler/debug" + "github.com/99designs/gqlgen/graphql/playground" + "github.com/alecthomas/kong" + "go.uber.org/zap" + + _ "entgo.io/contrib/entgql/internal/todoglobalid/ent/runtime" + _ "github.com/mattn/go-sqlite3" +) + +func main() { + var cli struct { + Addr string `name:"address" default:":8081" help:"Address to listen on."` + Debug bool `name:"debug" help:"Enable debugging mode."` + } + kong.Parse(&cli) + + log, _ := zap.NewDevelopment() + client, err := ent.Open( + "sqlite3", + "file:ent?mode=memory&cache=shared&_fk=1", + ) + if err != nil { + log.Fatal("opening ent client", zap.Error(err)) + } + if err := client.Schema.Create( + context.Background(), + migrate.WithGlobalUniqueID(true), + ); err != nil { + log.Fatal("running schema migration", zap.Error(err)) + } + + srv := handler.NewDefaultServer(todo.NewSchema(client)) + srv.Use(entgql.Transactioner{TxOpener: client}) + if cli.Debug { + srv.Use(&debug.Tracer{}) + } + + http.Handle("/", + playground.Handler("Todo", "/query"), + ) + http.Handle("/query", srv) + + log.Info("listening on", zap.String("address", cli.Addr)) + server := &http.Server{ + Addr: cli.Addr, + ReadHeaderTimeout: 30 * time.Second, + } + if err := server.ListenAndServe(); err != nil { + log.Error("http server terminated", zap.Error(err)) + } +} diff --git a/entgql/internal/todoglobalid/todo.graphql b/entgql/internal/todoglobalid/todo.graphql new file mode 100644 index 000000000..12d192821 --- /dev/null +++ b/entgql/internal/todoglobalid/todo.graphql @@ -0,0 +1,83 @@ +directive @hasPermissions(permissions: [String!]!) on OBJECT | FIELD_DEFINITION + +type CategoryConfig { + maxMembers: Int +} + +input CategoryConfigInput { + maxMembers: Int +} + +type CategoryTypes { + public: Boolean +} + +input CategoryTypesInput { + public: Boolean +} + +scalar Duration +scalar UUID + +extend input TodoWhereInput { + createdToday: Boolean +} + +extend type Category { + """ + Expose the TODOS_COUNT order field in case it was added in orderBy. + """ + todosCount: Int +} + +extend type Todo { + extendedField: String +} + +extend type Query { + """ + This field is an example of extending the built-in Query type from Ent. + """ + ping: String! + + """This is the todo item""" + todosWithJoins( + """Returns the elements in the list that come after the specified cursor.""" + after: Cursor + + """Returns the first _n_ elements from the list.""" + first: Int + + """Returns the elements in the list that come before the specified cursor.""" + before: Cursor + + """Returns the last _n_ elements from the list.""" + last: Int + + """Ordering options for Todos returned from the connection.""" + orderBy: [TodoOrder!] + + """Filtering options for Todos returned from the connection.""" + where: TodoWhereInput +): TodoConnection! +} + +type Mutation { + createCategory(input: CreateCategoryInput!): Category! + createTodo(input: CreateTodoInput!): Todo! + updateTodo(id: ID!, input: UpdateTodoInput!): Todo! + clearTodos: Int! + updateFriendship(id: ID!, input: UpdateFriendshipInput!): Friendship! +} + +type Custom { + info: String! +} + +extend input CreateCategoryInput { + createTodos: [CreateTodoInput!] +} + +interface NamedNode { + name: String! +} \ No newline at end of file diff --git a/entgql/internal/todoglobalid/todo.resolvers.go b/entgql/internal/todoglobalid/todo.resolvers.go new file mode 100644 index 000000000..b7c028c44 --- /dev/null +++ b/entgql/internal/todoglobalid/todo.resolvers.go @@ -0,0 +1,147 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package todo + +// This file will be automatically regenerated based on the schema, any resolver implementations +// will be copied through when generating and any unknown code will be moved to the end. +// Code generated by github.com/99designs/gqlgen version v0.17.63 + +import ( + "context" + "time" + + "entgo.io/contrib/entgql" + "entgo.io/contrib/entgql/internal/todoglobalid/ent" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/category" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/todo" + "entgo.io/ent/dialect/sql" +) + +// TodosCount is the resolver for the todosCount field. +func (r *categoryResolver) TodosCount(ctx context.Context, obj *ent.Category) (*int, error) { + v, err := ent.CategoryOrderFieldTodosCount.Value(obj) + if err != nil { + return nil, err + } + // We expect to beautify this API in the future. + i, ok := v.(int64) + if !ok { + return nil, nil + } + vi := int(i) + return &vi, nil +} + +// CreateCategory is the resolver for the createCategory field. +func (r *mutationResolver) CreateCategory(ctx context.Context, input ent.CreateCategoryInput) (*ent.Category, error) { + return ent.FromContext(ctx).Category.Create().SetInput(input).Save(ctx) +} + +// CreateTodo is the resolver for the createTodo field. +func (r *mutationResolver) CreateTodo(ctx context.Context, input ent.CreateTodoInput) (*ent.Todo, error) { + return ent.FromContext(ctx).Todo. + Create(). + SetInput(input). + Save(ctx) +} + +// UpdateTodo is the resolver for the updateTodo field. +func (r *mutationResolver) UpdateTodo(ctx context.Context, id int, input ent.UpdateTodoInput) (*ent.Todo, error) { + return ent.FromContext(ctx).Todo. + UpdateOneID(id). + SetInput(input). + Save(ctx) +} + +// ClearTodos is the resolver for the clearTodos field. +func (r *mutationResolver) ClearTodos(ctx context.Context) (int, error) { + client := ent.FromContext(ctx) + return client.Todo. + Delete(). + Exec(ctx) +} + +// UpdateFriendship is the resolver for the updateFriendship field. +func (r *mutationResolver) UpdateFriendship(ctx context.Context, id int, input ent.UpdateFriendshipInput) (*ent.Friendship, error) { + return r.client.Friendship. + UpdateOneID(id). + SetInput(input). + Save(ctx) +} + +// Ping is the resolver for the ping field. +func (r *queryResolver) Ping(ctx context.Context) (string, error) { + return "pong", nil +} + +// TodosWithJoins is the resolver for the todosWithJoins field. +func (r *queryResolver) TodosWithJoins(ctx context.Context, after *entgql.Cursor[int], first *int, before *entgql.Cursor[int], last *int, orderBy []*ent.TodoOrder, where *ent.TodoWhereInput) (*ent.TodoConnection, error) { + return r.client.Todo.Query(). + Modify(func(s *sql.Selector) { + cats := sql.Table(category.Table) + s. + LeftJoin(cats). + On(s.C(todo.FieldCategoryID), cats.C(category.FieldID)). + GroupBy(s.C(category.FieldID)) + }). + Paginate(ctx, after, first, before, last, + ent.WithTodoOrder(orderBy), + ent.WithTodoFilter(where.Filter), + ) +} + +// ExtendedField is the resolver for the extendedField field. +func (r *todoResolver) ExtendedField(ctx context.Context, obj *ent.Todo) (*string, error) { + return &obj.Text, nil +} + +// CreateTodos is the resolver for the createTodos field. +func (r *createCategoryInputResolver) CreateTodos(ctx context.Context, obj *ent.CreateCategoryInput, data []*ent.CreateTodoInput) error { + e := ent.FromContext(ctx) + builders := make([]*ent.TodoCreate, len(data)) + for i, input := range data { + builders[i] = e.Todo.Create().SetInput(*input) + } + todos, err := e.Todo.CreateBulk(builders...).Save(ctx) + if err != nil { + return err + } + ids := make([]int, len(todos)) + for i := range todos { + ids[i] = todos[i].ID + } + obj.TodoIDs = append(obj.TodoIDs, ids...) + return nil +} + +// CreatedToday is the resolver for the createdToday field. +func (r *todoWhereInputResolver) CreatedToday(ctx context.Context, obj *ent.TodoWhereInput, data *bool) error { + if data == nil { + return nil + } + startOfDay := time.Now().Truncate(24 * time.Hour) + endOfDay := startOfDay.Add(24*time.Hour - 1) + if *data { + obj.AddPredicates(todo.And(todo.CreatedAtGTE(startOfDay), todo.CreatedAtLTE(endOfDay))) + } else { + obj.AddPredicates(todo.Or(todo.CreatedAtLT(startOfDay), todo.CreatedAtGT(endOfDay))) + } + return nil +} + +// Mutation returns MutationResolver implementation. +func (r *Resolver) Mutation() MutationResolver { return &mutationResolver{r} } + +type mutationResolver struct{ *Resolver } diff --git a/entgql/internal/todoglobalid/todo_test.go b/entgql/internal/todoglobalid/todo_test.go new file mode 100644 index 000000000..407cf7155 --- /dev/null +++ b/entgql/internal/todoglobalid/todo_test.go @@ -0,0 +1,3094 @@ +// Copyright 2019-present Facebook +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package todo_test + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "math" + "sort" + "strconv" + "strings" + "sync/atomic" + "testing" + "time" + + "entgo.io/contrib/entgql/internal/todoglobalid/ent/migrate" + "entgo.io/ent/dialect/sql" + "github.com/AlekSi/pointer" + "github.com/stretchr/testify/require" + + "entgo.io/contrib/entgql" + gen "entgo.io/contrib/entgql/internal/todoglobalid" + "entgo.io/contrib/entgql/internal/todoglobalid/ent" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/category" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/enttest" + "entgo.io/contrib/entgql/internal/todoglobalid/ent/todo" + "entgo.io/ent/dialect" + "github.com/99designs/gqlgen/client" + "github.com/99designs/gqlgen/graphql" + "github.com/99designs/gqlgen/graphql/handler" + "github.com/stretchr/testify/suite" + "github.com/vektah/gqlparser/v2/gqlerror" + + _ "github.com/mattn/go-sqlite3" +) + +type todoTestSuite struct { + suite.Suite + *client.Client + ent *ent.Client +} + +const ( + queryAll = `query { + todos { + totalCount + edges { + node { + id + status + } + cursor + } + pageInfo { + hasNextPage + hasPreviousPage + startCursor + endCursor + } + } + }` + maxTodos = 32 + idOffset = 6 << 32 +) + +func (s *todoTestSuite) SetupTest() { + time.Local = time.UTC + s.ent = enttest.Open(s.T(), dialect.SQLite, + fmt.Sprintf("file:%s-%d?mode=memory&cache=shared&_fk=1", + s.T().Name(), time.Now().UnixNano(), + ), + ) + + srv := handler.NewDefaultServer(gen.NewSchema(s.ent)) + srv.Use(entgql.Transactioner{TxOpener: s.ent}) + s.Client = client.New(srv) + + const mutation = `mutation($priority: Int!, $text: String!, $parent: ID) { + createTodo(input: {status: COMPLETED, priority: $priority, text: $text, parentID: $parent}) { + id + } + }` + var ( + rsp struct { + CreateTodo struct { + ID string + } + } + root = idOffset + 1 + ) + for i := 1; i <= maxTodos; i++ { + id := strconv.Itoa(idOffset + i) + var parent *int + if i != 1 { + if i%2 != 0 { + parent = pointer.ToInt(idOffset + i - 2) + } else { + parent = pointer.ToInt(root) + } + } + err := s.Post(mutation, &rsp, + client.Var("priority", i), + client.Var("text", id), + client.Var("parent", parent), + ) + s.Require().NoError(err) + s.Require().Equal(id, rsp.CreateTodo.ID) + } +} + +func TestTodo(t *testing.T) { + suite.Run(t, &todoTestSuite{}) +} + +type response struct { + Todos struct { + TotalCount int + Edges []struct { + Node struct { + ID string + CreatedAt string + PriorityOrder int + Status todo.Status + Text string + Parent struct { + ID string + } + } + Cursor string + } + PageInfo struct { + HasNextPage bool + HasPreviousPage bool + StartCursor *string + EndCursor *string + } + } +} + +func (s *todoTestSuite) TestQueryEmpty() { + { + var rsp struct{ ClearTodos int } + err := s.Post(`mutation { clearTodos }`, &rsp) + s.Require().NoError(err) + s.Require().Equal(maxTodos, rsp.ClearTodos) + } + var rsp response + err := s.Post(queryAll, &rsp) + s.Require().NoError(err) + s.Require().Zero(rsp.Todos.TotalCount) + s.Require().Empty(rsp.Todos.Edges) + s.Require().False(rsp.Todos.PageInfo.HasNextPage) + s.Require().False(rsp.Todos.PageInfo.HasPreviousPage) + s.Require().Nil(rsp.Todos.PageInfo.StartCursor) + s.Require().Nil(rsp.Todos.PageInfo.EndCursor) +} + +func (s *todoTestSuite) TestQueryAll() { + var rsp response + err := s.Post(queryAll, &rsp) + s.Require().NoError(err) + + s.Require().Equal(maxTodos, rsp.Todos.TotalCount) + s.Require().Len(rsp.Todos.Edges, maxTodos) + s.Require().False(rsp.Todos.PageInfo.HasNextPage) + s.Require().False(rsp.Todos.PageInfo.HasPreviousPage) + s.Require().Equal( + rsp.Todos.Edges[0].Cursor, + *rsp.Todos.PageInfo.StartCursor, + ) + s.Require().Equal( + rsp.Todos.Edges[len(rsp.Todos.Edges)-1].Cursor, + *rsp.Todos.PageInfo.EndCursor, + ) + for i, edge := range rsp.Todos.Edges { + s.Require().Equal(strconv.Itoa(idOffset+i+1), edge.Node.ID) + s.Require().EqualValues(todo.StatusCompleted, edge.Node.Status) + s.Require().NotEmpty(edge.Cursor) + } +} + +func (s *todoTestSuite) TestPageForward() { + const ( + query = `query($after: Cursor, $first: Int) { + todos(after: $after, first: $first) { + totalCount + edges { + node { + id + } + cursor + } + pageInfo { + hasNextPage + endCursor + } + } + }` + first = 5 + ) + var ( + after interface{} + rsp response + id = idOffset + 1 + ) + for i := 0; i < maxTodos/first; i++ { + err := s.Post(query, &rsp, + client.Var("after", after), + client.Var("first", first), + ) + s.Require().NoError(err) + s.Require().Equal(maxTodos, rsp.Todos.TotalCount) + s.Require().Len(rsp.Todos.Edges, first) + s.Require().True(rsp.Todos.PageInfo.HasNextPage) + s.Require().NotEmpty(rsp.Todos.PageInfo.EndCursor) + + for _, edge := range rsp.Todos.Edges { + s.Require().Equal(strconv.Itoa(id), edge.Node.ID) + s.Require().NotEmpty(edge.Cursor) + id++ + } + after = rsp.Todos.PageInfo.EndCursor + } + + err := s.Post(query, &rsp, + client.Var("after", rsp.Todos.PageInfo.EndCursor), + client.Var("first", first), + ) + s.Require().NoError(err) + s.Require().Equal(maxTodos, rsp.Todos.TotalCount) + s.Require().NotEmpty(rsp.Todos.Edges) + s.Require().Len(rsp.Todos.Edges, maxTodos%first) + s.Require().False(rsp.Todos.PageInfo.HasNextPage) + s.Require().NotEmpty(rsp.Todos.PageInfo.EndCursor) + + for _, edge := range rsp.Todos.Edges { + s.Require().Equal(strconv.Itoa(id), edge.Node.ID) + s.Require().NotEmpty(edge.Cursor) + id++ + } + + after = rsp.Todos.PageInfo.EndCursor + rsp = response{} + err = s.Post(query, &rsp, + client.Var("after", after), + client.Var("first", first), + ) + s.Require().NoError(err) + s.Require().Equal(maxTodos, rsp.Todos.TotalCount) + s.Require().Empty(rsp.Todos.Edges) + s.Require().Empty(rsp.Todos.PageInfo.EndCursor) + s.Require().False(rsp.Todos.PageInfo.HasNextPage) +} + +func (s *todoTestSuite) TestPageBackwards() { + const ( + query = `query($before: Cursor, $last: Int) { + todos(before: $before, last: $last) { + totalCount + edges { + node { + id + } + cursor + } + pageInfo { + hasPreviousPage + startCursor + } + } + }` + last = 7 + ) + var ( + before interface{} + rsp response + id = idOffset + maxTodos + ) + for i := 0; i < maxTodos/last; i++ { + err := s.Post(query, &rsp, + client.Var("before", before), + client.Var("last", last), + ) + s.Require().NoError(err) + s.Require().Equal(maxTodos, rsp.Todos.TotalCount) + s.Require().Len(rsp.Todos.Edges, last) + s.Require().True(rsp.Todos.PageInfo.HasPreviousPage) + s.Require().NotEmpty(rsp.Todos.PageInfo.StartCursor) + + for i := len(rsp.Todos.Edges) - 1; i >= 0; i-- { + edge := &rsp.Todos.Edges[i] + s.Require().Equal(strconv.Itoa(id), edge.Node.ID) + s.Require().NotEmpty(edge.Cursor) + id-- + } + before = rsp.Todos.PageInfo.StartCursor + } + + err := s.Post(query, &rsp, + client.Var("before", rsp.Todos.PageInfo.StartCursor), + client.Var("last", last), + ) + s.Require().NoError(err) + s.Require().Equal(maxTodos, rsp.Todos.TotalCount) + s.Require().NotEmpty(rsp.Todos.Edges) + s.Require().Len(rsp.Todos.Edges, maxTodos%last) + s.Require().False(rsp.Todos.PageInfo.HasPreviousPage) + s.Require().NotEmpty(rsp.Todos.PageInfo.StartCursor) + + for i := len(rsp.Todos.Edges) - 1; i >= 0; i-- { + edge := &rsp.Todos.Edges[i] + s.Require().Equal(strconv.Itoa(id), edge.Node.ID) + s.Require().NotEmpty(edge.Cursor) + id-- + } + s.Require().Equal(idOffset, id) + + before = rsp.Todos.PageInfo.StartCursor + rsp = response{} + err = s.Post(query, &rsp, + client.Var("before", before), + client.Var("last", last), + ) + s.Require().NoError(err) + s.Require().Equal(maxTodos, rsp.Todos.TotalCount) + s.Require().Empty(rsp.Todos.Edges) + s.Require().Empty(rsp.Todos.PageInfo.StartCursor) + s.Require().False(rsp.Todos.PageInfo.HasPreviousPage) +} + +func (s *todoTestSuite) TestPaginationOrder() { + const ( + query = `query($after: Cursor, $first: Int, $before: Cursor, $last: Int, $direction: OrderDirection!, $field: TodoOrderField!) { + todos(after: $after, first: $first, before: $before, last: $last, orderBy: { direction: $direction, field: $field }) { + totalCount + edges { + node { + id + createdAt + priorityOrder + status + text + } + cursor + } + pageInfo { + hasNextPage + hasPreviousPage + startCursor + endCursor + } + } + }` + step = 5 + steps = maxTodos/step + 1 + ) + s.Run("ForwardAscending", func() { + var ( + rsp response + endText string + ) + for i := 0; i < steps; i++ { + err := s.Post(query, &rsp, + client.Var("after", rsp.Todos.PageInfo.EndCursor), + client.Var("first", step), + client.Var("direction", "ASC"), + client.Var("field", "TEXT"), + ) + s.Require().NoError(err) + s.Require().Equal(maxTodos, rsp.Todos.TotalCount) + if i < steps-1 { + s.Require().Len(rsp.Todos.Edges, step) + s.Require().True(rsp.Todos.PageInfo.HasNextPage) + } else { + s.Require().Len(rsp.Todos.Edges, maxTodos%step) + s.Require().False(rsp.Todos.PageInfo.HasNextPage) + } + s.Require().True(sort.SliceIsSorted(rsp.Todos.Edges, func(i, j int) bool { + return rsp.Todos.Edges[i].Node.Text < rsp.Todos.Edges[j].Node.Text + })) + s.Require().NotNil(rsp.Todos.PageInfo.StartCursor) + s.Require().Equal(*rsp.Todos.PageInfo.StartCursor, rsp.Todos.Edges[0].Cursor) + s.Require().NotNil(rsp.Todos.PageInfo.EndCursor) + end := rsp.Todos.Edges[len(rsp.Todos.Edges)-1] + s.Require().Equal(*rsp.Todos.PageInfo.EndCursor, end.Cursor) + if i > 0 { + s.Require().Less(endText, rsp.Todos.Edges[0].Node.Text) + } + endText = end.Node.Text + } + }) + s.Run("ForwardDescending", func() { + var ( + rsp response + endID int + ) + for i := 0; i < steps; i++ { + err := s.Post(query, &rsp, + client.Var("after", rsp.Todos.PageInfo.EndCursor), + client.Var("first", step), + client.Var("direction", "DESC"), + client.Var("field", "CREATED_AT"), + ) + s.Require().NoError(err) + s.Require().Equal(maxTodos, rsp.Todos.TotalCount) + if i < steps-1 { + s.Require().Len(rsp.Todos.Edges, step) + s.Require().True(rsp.Todos.PageInfo.HasNextPage) + } else { + s.Require().Len(rsp.Todos.Edges, maxTodos%step) + s.Require().False(rsp.Todos.PageInfo.HasNextPage) + } + s.Require().True(sort.SliceIsSorted(rsp.Todos.Edges, func(i, j int) bool { + left, _ := strconv.Atoi(rsp.Todos.Edges[i].Node.ID) + right, _ := strconv.Atoi(rsp.Todos.Edges[j].Node.ID) + return left > right + })) + s.Require().NotNil(rsp.Todos.PageInfo.StartCursor) + s.Require().Equal(*rsp.Todos.PageInfo.StartCursor, rsp.Todos.Edges[0].Cursor) + s.Require().NotNil(rsp.Todos.PageInfo.EndCursor) + end := rsp.Todos.Edges[len(rsp.Todos.Edges)-1] + s.Require().Equal(*rsp.Todos.PageInfo.EndCursor, end.Cursor) + if i > 0 { + id, _ := strconv.Atoi(rsp.Todos.Edges[0].Node.ID) + s.Require().Greater(endID, id) + } + endID, _ = strconv.Atoi(end.Node.ID) + } + }) + s.Run("BackwardAscending", func() { + var ( + rsp response + startPriority int + ) + for i := 0; i < steps; i++ { + err := s.Post(query, &rsp, + client.Var("before", rsp.Todos.PageInfo.StartCursor), + client.Var("last", step), + client.Var("direction", "ASC"), + client.Var("field", "PRIORITY_ORDER"), + ) + s.Require().NoError(err) + s.Require().Equal(maxTodos, rsp.Todos.TotalCount) + if i < steps-1 { + s.Require().Len(rsp.Todos.Edges, step) + s.Require().True(rsp.Todos.PageInfo.HasPreviousPage) + } else { + s.Require().Len(rsp.Todos.Edges, maxTodos%step) + s.Require().False(rsp.Todos.PageInfo.HasPreviousPage) + } + s.Require().True(sort.SliceIsSorted(rsp.Todos.Edges, func(i, j int) bool { + return rsp.Todos.Edges[i].Node.PriorityOrder < rsp.Todos.Edges[j].Node.PriorityOrder + })) + s.Require().NotNil(rsp.Todos.PageInfo.StartCursor) + start := rsp.Todos.Edges[0] + s.Require().Equal(*rsp.Todos.PageInfo.StartCursor, start.Cursor) + s.Require().NotNil(rsp.Todos.PageInfo.EndCursor) + end := rsp.Todos.Edges[len(rsp.Todos.Edges)-1] + s.Require().Equal(*rsp.Todos.PageInfo.EndCursor, end.Cursor) + if i > 0 { + s.Require().Greater(startPriority, end.Node.PriorityOrder) + } + startPriority = start.Node.PriorityOrder + } + }) + s.Run("BackwardDescending", func() { + var ( + rsp response + startCreatedAt time.Time + ) + for i := 0; i < steps; i++ { + err := s.Post(query, &rsp, + client.Var("before", rsp.Todos.PageInfo.StartCursor), + client.Var("last", step), + client.Var("direction", "DESC"), + client.Var("field", "CREATED_AT"), + ) + s.Require().NoError(err) + s.Require().Equal(maxTodos, rsp.Todos.TotalCount) + if i < steps-1 { + s.Require().Len(rsp.Todos.Edges, step) + s.Require().True(rsp.Todos.PageInfo.HasPreviousPage) + } else { + s.Require().Len(rsp.Todos.Edges, maxTodos%step) + s.Require().False(rsp.Todos.PageInfo.HasPreviousPage) + } + s.Require().True(sort.SliceIsSorted(rsp.Todos.Edges, func(i, j int) bool { + left, _ := time.Parse(time.RFC3339, rsp.Todos.Edges[i].Node.CreatedAt) + right, _ := time.Parse(time.RFC3339, rsp.Todos.Edges[j].Node.CreatedAt) + return left.After(right) + })) + s.Require().NotNil(rsp.Todos.PageInfo.StartCursor) + start := rsp.Todos.Edges[0] + s.Require().Equal(*rsp.Todos.PageInfo.StartCursor, start.Cursor) + s.Require().NotNil(rsp.Todos.PageInfo.EndCursor) + end := rsp.Todos.Edges[len(rsp.Todos.Edges)-1] + s.Require().Equal(*rsp.Todos.PageInfo.EndCursor, end.Cursor) + if i > 0 { + endCreatedAt, _ := time.Parse(time.RFC3339, end.Node.CreatedAt) + s.Require().True(startCreatedAt.Before(endCreatedAt) || startCreatedAt.Equal(endCreatedAt)) + } + startCreatedAt, _ = time.Parse(time.RFC3339, start.Node.CreatedAt) + } + }) +} + +func (s *todoTestSuite) TestPaginationFiltering() { + const ( + query = `query($after: Cursor, $first: Int, $before: Cursor, $last: Int, $status: TodoStatus, $hasParent: Boolean, $hasCategory: Boolean) { + todos(after: $after, first: $first, before: $before, last: $last, where: {status: $status, hasParent: $hasParent, hasCategory: $hasCategory}) { + totalCount + edges { + node { + id + parent { + id + } + } + cursor + } + pageInfo { + hasNextPage + hasPreviousPage + startCursor + endCursor + } + } + }` + step = 5 + steps = maxTodos/step + 1 + ) + s.Run("StatusInProgress", func() { + var rsp response + err := s.Post(query, &rsp, + client.Var("first", step), + client.Var("status", todo.StatusInProgress), + ) + s.NoError(err) + s.Zero(rsp.Todos.TotalCount) + }) + s.Run("StatusCompleted", func() { + var rsp response + for i := 0; i < steps; i++ { + err := s.Post(query, &rsp, + client.Var("after", rsp.Todos.PageInfo.EndCursor), + client.Var("first", step), + client.Var("status", todo.StatusCompleted), + ) + s.Require().NoError(err) + s.Require().Equal(maxTodos, rsp.Todos.TotalCount) + if i < steps-1 { + s.Require().Len(rsp.Todos.Edges, step) + s.Require().True(rsp.Todos.PageInfo.HasNextPage) + } else { + s.Require().Len(rsp.Todos.Edges, maxTodos%step) + s.Require().False(rsp.Todos.PageInfo.HasNextPage) + } + } + }) + s.Run("WithParent", func() { + var rsp response + err := s.Post(query, &rsp, + client.Var("first", step), + client.Var("status", todo.StatusCompleted), + client.Var("hasParent", true), + ) + s.Require().NoError(err) + s.Require().Equal(maxTodos-1, rsp.Todos.TotalCount, "All todo items without the root") + }) + s.Run("WithoutParent", func() { + var rsp response + err := s.Post(query, &rsp, + client.Var("first", step), + client.Var("status", todo.StatusCompleted), + client.Var("hasParent", false), + ) + s.Require().NoError(err) + s.Require().Equal(1, rsp.Todos.TotalCount, "Only the root item") + }) + s.Run("WithoutCategory", func() { + var rsp response + err := s.Post(query, &rsp, + client.Var("first", step), + client.Var("status", todo.StatusCompleted), + client.Var("hasCategory", true), + ) + s.Require().NoError(err) + s.Require().Equal(0, rsp.Todos.TotalCount) + }) + + s.Run("WithCategory", func() { + ctx := context.Background() + id := s.ent.Todo.Query().Order(ent.Asc(todo.FieldID)).FirstIDX(ctx) + s.ent.Category.Create().SetText("Disabled").SetStatus(category.StatusDisabled).AddTodoIDs(id).SetDuration(time.Second).ExecX(ctx) + + var ( + rsp response + query = `query($duration: Duration) { + todos(where:{hasCategoryWith: {duration: $duration}}) { + totalCount + } + }` + ) + err := s.Post(query, &rsp, client.Var("duration", time.Second)) + s.NoError(err) + s.Equal(1, rsp.Todos.TotalCount) + err = s.Post(query, &rsp, client.Var("duration", time.Second*2)) + s.NoError(err) + s.Zero(rsp.Todos.TotalCount) + }) + + s.Run("EmptyFilter", func() { + var ( + rsp response + query = `query { + todos(where:{}) { + totalCount + } + }` + ) + err := s.Post(query, &rsp) + s.NoError(err) + s.Equal(s.ent.Todo.Query().CountX(context.Background()), rsp.Todos.TotalCount) + }) + + s.Run("Zero first", func() { + var ( + rsp response + query = `query { + todos(first: 0) { + totalCount + } + }` + ) + err := s.Post(query, &rsp) + s.NoError(err) + s.Equal(s.ent.Todo.Query().CountX(context.Background()), rsp.Todos.TotalCount) + }) + + s.Run("Zero last", func() { + var ( + rsp response + query = `query { + todos(last: 0) { + totalCount + } + }` + ) + err := s.Post(query, &rsp) + s.NoError(err) + s.Equal(s.ent.Todo.Query().CountX(context.Background()), rsp.Todos.TotalCount) + }) +} + +func (s *todoTestSuite) TestFilteringWithCustomPredicate() { + ctx := context.Background() + td1 := s.ent.Todo.Create(). + SetStatus(todo.StatusCompleted). + SetText("test1"). + SetCreatedAt(time.Now(). + Add(48 * time.Hour)). + SaveX(ctx) + td2 := s.ent.Todo.Create(). + SetStatus(todo.StatusCompleted). + SetText("test2"). + SetCreatedAt(time.Now().Add(-48 * time.Hour)). + SaveX(ctx) + td3 := s.ent.Todo.Create(). + SetStatus(todo.StatusCompleted). + SetText("test2"). + SetCreatedAt(time.Now()). + SaveX(ctx) + td4 := s.ent.Todo.Create(). + SetStatus(todo.StatusCompleted). + SetText("test3"). + SetCreatedAt(time.Now().Add(-48*time.Hour)). + AddChildren(td1, td2, td3). + SaveX(ctx) + + s.Run("createdToday true using interface", func() { + var rsp struct { + Todo struct { + Children struct { + TotalCount int + } + } + } + err := s.Post(`query($id: ID!, $createdToday: Boolean) { + todo: node(id: $id) { + ... on Todo { + children (where: {createdToday: $createdToday}) { + totalCount + } + } + } + }`, &rsp, + client.Var("id", td4.ID), + client.Var("createdToday", true), + ) + s.NoError(err) + s.Equal(1, rsp.Todo.Children.TotalCount) + }) + + s.Run("createdToday false using interface", func() { + var rsp struct { + Todo struct { + Children struct { + TotalCount int + } + } + } + err := s.Post(`query($id: ID!, $createdToday: Boolean) { + todo: node(id: $id) { + ... on Todo { + children (where: {createdToday: $createdToday}) { + totalCount + } + } + } + }`, &rsp, + client.Var("id", td4.ID), + client.Var("createdToday", false), + ) + s.NoError(err) + s.Equal(2, rsp.Todo.Children.TotalCount) + }) + + s.Run("createdToday true", func() { + var rsp response + err := s.Post(`query($createdToday: Boolean) { + todos(where: {createdToday: $createdToday}) { + totalCount + } + }`, &rsp, + client.Var("createdToday", true), + ) + s.NoError(err) + s.Equal(maxTodos+1, rsp.Todos.TotalCount) + }) + + s.Run("createdToday false", func() { + var rsp response + err := s.Post(`query($createdToday: Boolean) { + todos(where: {createdToday: $createdToday}) { + totalCount + } + }`, &rsp, + client.Var("createdToday", false), + ) + s.NoError(err) + s.Equal(3, rsp.Todos.TotalCount) + }) + + s.Run("not createdToday true", func() { + var rsp response + err := s.Post(`query($createdToday: Boolean) { + todos(where: {not:{createdToday: $createdToday}}) { + totalCount + } + }`, &rsp, + client.Var("createdToday", true), + ) + s.NoError(err) + s.Equal(3, rsp.Todos.TotalCount) + }) + + s.Run("not createdToday false", func() { + var rsp response + err := s.Post(`query($createdToday: Boolean) { + todos(where: {not:{createdToday: $createdToday}}) { + totalCount + } + }`, &rsp, + client.Var("createdToday", false), + ) + s.NoError(err) + s.Equal(maxTodos+1, rsp.Todos.TotalCount) + }) + + s.Run("or createdToday", func() { + var rsp response + err := s.Post(`query($createdToday1: Boolean, $createdToday2: Boolean) { + todos(where: {or:[{createdToday: $createdToday1}, {createdToday: $createdToday2}]}) { + totalCount + } + }`, &rsp, + client.Var("createdToday1", true), + client.Var("createdToday2", false), + ) + s.NoError(err) + s.Equal(maxTodos+4, rsp.Todos.TotalCount) + }) + + s.Run("and createdToday", func() { + var rsp response + err := s.Post(`query($createdToday1: Boolean, $createdToday2: Boolean) { + todos(where: {and:[{createdToday: $createdToday1}, {createdToday: $createdToday2}]}) { + totalCount + } + }`, &rsp, + client.Var("createdToday1", true), + client.Var("createdToday2", false), + ) + s.NoError(err) + s.Equal(0, rsp.Todos.TotalCount) + }) +} + +func (s *todoTestSuite) TestNode() { + const ( + query = `query($id: ID!) { + todo: node(id: $id) { + ... on Todo { + priorityOrder + } + } + }` + ) + var rsp struct{ Todo struct{ PriorityOrder int } } + err := s.Post(query, &rsp, client.Var("id", idOffset+maxTodos)) + s.Require().NoError(err) + err = s.Post(query, &rsp, client.Var("id", -1)) + var jerr client.RawJsonError + s.Require().True(errors.As(err, &jerr)) + var errs gqlerror.List + err = json.Unmarshal(jerr.RawMessage, &errs) + s.Require().NoError(err) + s.Require().Len(errs, 1) + s.Require().Equal("Could not resolve to a node with the global id of '-1'", errs[0].Message) + s.Require().Equal("NOT_FOUND", errs[0].Extensions["code"]) +} + +func (s *todoTestSuite) TestNodes() { + const ( + query = `query($ids: [ID!]!) { + todos: nodes(ids: $ids) { + ... on Todo { + text + } + } + }` + ) + var rsp struct{ Todos []*struct{ Text string } } + ids := []int{1, 2, 3, 3, 3, maxTodos + 1, 2, 2, maxTodos + 5} + for i := range ids { + ids[i] = idOffset + ids[i] + } + err := s.Post(query, &rsp, client.Var("ids", ids)) + s.Require().Error(err) + s.Require().Len(rsp.Todos, len(ids)) + errmsgs := make([]string, 0, 2) + for i, id := range ids { + if id <= idOffset+maxTodos { + s.Require().Equal(strconv.Itoa(id), rsp.Todos[i].Text) + } else { + s.Require().Nil(rsp.Todos[i]) + errmsgs = append(errmsgs, + fmt.Sprintf("Could not resolve to a node with the global id of '%d'", id), + ) + } + } + + var jerr client.RawJsonError + s.Require().True(errors.As(err, &jerr)) + var errs gqlerror.List + err = json.Unmarshal(jerr.RawMessage, &errs) + s.Require().NoError(err) + s.Require().Len(errs, len(errmsgs)) + for i, err := range errs { + s.Require().Equal(errmsgs[i], err.Message) + s.Require().Equal("NOT_FOUND", err.Extensions["code"]) + } +} + +func (s *todoTestSuite) TestNodeCollection() { + const ( + query = `query($id: ID!) { + todo: node(id: $id) { + ... on Todo { + parent { + text + parent { + text + } + } + children { + edges { + node { + text + children { + edges { + node { + text + } + } + } + } + } + } + } + } + }` + ) + var rsp struct { + Todo struct { + Parent *struct { + Text string + Parent *struct { + Text string + } + } + Children struct { + Edges []struct { + Node struct { + Text string + Children struct { + Edges []struct { + Node struct { + Text string + } + } + } + } + } + } + } + } + err := s.Post(query, &rsp, client.Var("id", idOffset+1)) + s.Require().NoError(err) + s.Require().Nil(rsp.Todo.Parent) + s.Require().Len(rsp.Todo.Children.Edges, maxTodos/2+1) + s.Require().Condition(func() bool { + for _, child := range rsp.Todo.Children.Edges { + if child.Node.Text == strconv.Itoa(idOffset+3) { + s.Require().Len(child.Node.Children.Edges, 1) + s.Require().Equal(strconv.Itoa(idOffset+5), child.Node.Children.Edges[0].Node.Text) + return true + } + } + return false + }) + + err = s.Post(query, &rsp, client.Var("id", idOffset+4)) + s.Require().NoError(err) + s.Require().NotNil(rsp.Todo.Parent) + s.Require().Equal(strconv.Itoa(idOffset+1), rsp.Todo.Parent.Text) + s.Require().Empty(rsp.Todo.Children.Edges) + + err = s.Post(query, &rsp, client.Var("id", strconv.Itoa(idOffset+5))) + s.Require().NoError(err) + s.Require().NotNil(rsp.Todo.Parent) + s.Require().Equal(strconv.Itoa(idOffset+3), rsp.Todo.Parent.Text) + s.Require().NotNil(rsp.Todo.Parent.Parent) + s.Require().Equal(strconv.Itoa(idOffset+1), rsp.Todo.Parent.Parent.Text) + s.Require().Len(rsp.Todo.Children.Edges, 1) + s.Require().Equal(strconv.Itoa(idOffset+7), rsp.Todo.Children.Edges[0].Node.Text) +} + +func (s *todoTestSuite) TestConnCollection() { + const ( + query = `query { + todos { + edges { + node { + id + parent { + id + } + children { + edges { + node { + id + } + } + } + } + } + } + }` + ) + var rsp struct { + Todos struct { + Edges []struct { + Node struct { + ID string + Parent *struct { + ID string + } + Children struct { + Edges []struct { + Node struct { + ID string + } + } + } + } + } + } + } + + err := s.Post(query, &rsp) + s.Require().NoError(err) + s.Require().Len(rsp.Todos.Edges, maxTodos) + + for i, edge := range rsp.Todos.Edges { + switch { + case i == 0: + s.Require().Nil(edge.Node.Parent) + s.Require().Len(edge.Node.Children.Edges, maxTodos/2+1) + case i%2 == 0: + s.Require().NotNil(edge.Node.Parent) + id, err := strconv.Atoi(edge.Node.Parent.ID) + s.Require().NoError(err) + s.Require().Equal(idOffset+i-1, id) + if i < len(rsp.Todos.Edges)-2 { + s.Require().Len(edge.Node.Children.Edges, 1) + } else { + s.Require().Empty(edge.Node.Children.Edges) + } + case i%2 != 0: + s.Require().NotNil(edge.Node.Parent) + s.Require().Equal(strconv.Itoa(idOffset+1), edge.Node.Parent.ID) + s.Require().Empty(edge.Node.Children.Edges) + } + } +} + +func (s *todoTestSuite) TestEnumEncoding() { + s.Run("Encode", func() { + const status = todo.StatusCompleted + s.Require().Implements((*graphql.Marshaler)(nil), status) + var b strings.Builder + status.MarshalGQL(&b) + str := b.String() + const quote = `"` + s.Require().Equal(quote, str[:1]) + s.Require().Equal(quote, str[len(str)-1:]) + str = str[1 : len(str)-1] + s.Require().EqualValues(status, str) + }) + s.Run("Decode", func() { + const want = todo.StatusInProgress + var got todo.Status + s.Require().Implements((*graphql.Unmarshaler)(nil), &got) + err := got.UnmarshalGQL(want.String()) + s.Require().NoError(err) + s.Require().Equal(want, got) + }) +} + +func (s *todoTestSuite) TestNodeOptions() { + ctx := context.Background() + td := s.ent.Todo.Create().SetText("text").SetStatus(todo.StatusInProgress).SaveX(ctx) + + nr, err := s.ent.Noder(ctx, td.ID) + s.Require().NoError(err) + s.Require().IsType(nr, (*ent.Todo)(nil)) + s.Require().Equal(td.ID, nr.(*ent.Todo).ID) + + nr, err = s.ent.Noder(ctx, td.ID, ent.WithFixedNodeType(todo.Table)) + s.Require().NoError(err) + s.Require().IsType(nr, (*ent.Todo)(nil)) + s.Require().Equal(td.ID, nr.(*ent.Todo).ID) + + _, err = s.ent.Noder(ctx, td.ID, ent.WithNodeType(func(context.Context, int) (string, error) { + return "", errors.New("bad node type") + })) + s.Require().EqualError(err, "bad node type") +} + +func (s *todoTestSuite) TestMutationFieldCollection() { + var rsp struct { + CreateTodo struct { + Text string + Parent struct { + ID string + Text string + } + } + } + err := s.Post(`mutation ($parentID: ID!) { + createTodo(input: { status: IN_PROGRESS, priority: 0, text: "OKE", parentID: $parentID }) { + parent { + id + text + } + text + } + }`, &rsp, client.Var("parentID", strconv.Itoa(idOffset+1))) + s.Require().NoError(err) + s.Require().Equal("OKE", rsp.CreateTodo.Text) + s.Require().Equal(strconv.Itoa(idOffset+1), rsp.CreateTodo.Parent.ID) + s.Require().Equal(strconv.Itoa(idOffset+1), rsp.CreateTodo.Parent.Text) +} + +func (s *todoTestSuite) TestQueryJSONFields() { + var ( + ctx = context.Background() + cat = s.ent.Category.Create().SetText("Disabled").SetStatus(category.StatusDisabled).SetStrings([]string{"a", "b"}).SetText("category").SaveX(ctx) + rsp struct { + Node struct { + Text string + Strings []string + } + } + ) + err := s.Post(`query node($id: ID!) { + node(id: $id) { + ... on Category { + text + strings + } + } + }`, &rsp, client.Var("id", cat.ID)) + s.Require().NoError(err) + s.Require().Equal(cat.Text, rsp.Node.Text) + s.Require().Equal(cat.Strings, rsp.Node.Strings) +} + +func TestPageInfo(t *testing.T) { + ctx := context.Background() + ec := enttest.Open(t, dialect.SQLite, fmt.Sprintf("file:%s?mode=memory&cache=shared&_fk=1", t.Name())) + for i := 1; i <= 5; i++ { + ec.Todo.Create().SetText(strconv.Itoa(i)).SetStatus(todo.StatusInProgress).SaveX(ctx) + } + + var ( + srv = handler.NewDefaultServer(gen.NewSchema(ec)) + gqlc = client.New(srv) + query = `query ($after: Cursor, $first: Int, $before: Cursor, $last: Int $direction: OrderDirection!, $field: TodoOrderField!) { + todos(after: $after, first: $first, before: $before, last: $last, orderBy: { direction: $direction, field: $field }) { + edges { + cursor + node { + text + } + } + pageInfo { + startCursor + endCursor + hasNextPage + hasPreviousPage + } + totalCount + } + }` + rsp struct { + Todos struct { + TotalCount int + Edges []struct { + Cursor string + Node struct { + Text string + } + } + PageInfo struct { + HasNextPage bool + HasPreviousPage bool + StartCursor *string + EndCursor *string + } + } + } + ascOrder = []client.Option{client.Var("direction", "ASC"), client.Var("field", "TEXT")} + descOrder = []client.Option{client.Var("direction", "DESC"), client.Var("field", "TEXT")} + texts = func() (s []string) { + for _, n := range rsp.Todos.Edges { + s = append(s, n.Node.Text) + } + return + } + ) + + err := gqlc.Post(query, &rsp, ascOrder...) + require.NoError(t, err) + require.Equal(t, []string{"1", "2", "3", "4", "5"}, texts()) + require.Equal(t, 5, rsp.Todos.TotalCount) + require.False(t, rsp.Todos.PageInfo.HasNextPage) + require.False(t, rsp.Todos.PageInfo.HasPreviousPage) + + err = gqlc.Post(query, &rsp, append(ascOrder, client.Var("first", 2))...) + require.NoError(t, err) + require.Equal(t, []string{"1", "2"}, texts()) + require.Equal(t, 5, rsp.Todos.TotalCount) + require.True(t, rsp.Todos.PageInfo.HasNextPage) + require.False(t, rsp.Todos.PageInfo.HasPreviousPage) + require.Equal(t, rsp.Todos.Edges[0].Cursor, *rsp.Todos.PageInfo.StartCursor) + require.Equal(t, rsp.Todos.Edges[1].Cursor, *rsp.Todos.PageInfo.EndCursor) + + err = gqlc.Post(query, &rsp, append(ascOrder, client.Var("first", 2), client.Var("after", rsp.Todos.PageInfo.EndCursor))...) + require.NoError(t, err) + require.Equal(t, []string{"3", "4"}, texts()) + require.Equal(t, 5, rsp.Todos.TotalCount) + require.True(t, rsp.Todos.PageInfo.HasNextPage) + require.True(t, rsp.Todos.PageInfo.HasPreviousPage) + + err = gqlc.Post(query, &rsp, append(ascOrder, client.Var("first", 2), client.Var("after", rsp.Todos.PageInfo.EndCursor))...) + require.NoError(t, err) + require.Equal(t, []string{"5"}, texts()) + require.Equal(t, 5, rsp.Todos.TotalCount) + require.False(t, rsp.Todos.PageInfo.HasNextPage) + require.True(t, rsp.Todos.PageInfo.HasPreviousPage) + + err = gqlc.Post(query, &rsp, append(ascOrder, client.Var("last", 2), client.Var("before", rsp.Todos.PageInfo.EndCursor))...) + require.NoError(t, err) + require.Equal(t, []string{"3", "4"}, texts()) + require.Equal(t, 5, rsp.Todos.TotalCount) + require.True(t, rsp.Todos.PageInfo.HasNextPage) + require.True(t, rsp.Todos.PageInfo.HasPreviousPage) + + err = gqlc.Post(query, &rsp, append(ascOrder, client.Var("last", 2), client.Var("before", rsp.Todos.PageInfo.StartCursor))...) + require.NoError(t, err) + require.Equal(t, []string{"1", "2"}, texts()) + require.Equal(t, 5, rsp.Todos.TotalCount) + require.True(t, rsp.Todos.PageInfo.HasNextPage) + require.False(t, rsp.Todos.PageInfo.HasPreviousPage) + + err = gqlc.Post(query, &rsp, descOrder...) + require.NoError(t, err) + require.Equal(t, []string{"5", "4", "3", "2", "1"}, texts()) + require.Equal(t, 5, rsp.Todos.TotalCount) + require.False(t, rsp.Todos.PageInfo.HasNextPage) + require.False(t, rsp.Todos.PageInfo.HasPreviousPage) + + err = gqlc.Post(query, &rsp, append(descOrder, client.Var("first", 2))...) + require.NoError(t, err) + require.Equal(t, []string{"5", "4"}, texts()) + require.Equal(t, 5, rsp.Todos.TotalCount) + require.True(t, rsp.Todos.PageInfo.HasNextPage) + require.False(t, rsp.Todos.PageInfo.HasPreviousPage) + + err = gqlc.Post(query, &rsp, append(descOrder, client.Var("first", 2), client.Var("after", rsp.Todos.PageInfo.EndCursor))...) + require.NoError(t, err) + require.Equal(t, []string{"3", "2"}, texts()) + require.Equal(t, 5, rsp.Todos.TotalCount) + require.True(t, rsp.Todos.PageInfo.HasNextPage) + require.True(t, rsp.Todos.PageInfo.HasPreviousPage) + + err = gqlc.Post(query, &rsp, append(descOrder, client.Var("first", 2), client.Var("after", rsp.Todos.PageInfo.EndCursor))...) + require.NoError(t, err) + require.Equal(t, []string{"1"}, texts()) + require.Equal(t, 5, rsp.Todos.TotalCount) + require.False(t, rsp.Todos.PageInfo.HasNextPage) + require.True(t, rsp.Todos.PageInfo.HasPreviousPage) + + err = gqlc.Post(query, &rsp, append(descOrder, client.Var("last", 2), client.Var("before", rsp.Todos.PageInfo.EndCursor))...) + require.NoError(t, err) + require.Equal(t, []string{"3", "2"}, texts()) + require.Equal(t, 5, rsp.Todos.TotalCount) + require.True(t, rsp.Todos.PageInfo.HasNextPage) + require.True(t, rsp.Todos.PageInfo.HasPreviousPage) + + err = gqlc.Post(query, &rsp, append(descOrder, client.Var("last", 2), client.Var("before", rsp.Todos.PageInfo.StartCursor))...) + require.NoError(t, err) + require.Equal(t, []string{"5", "4"}, texts()) + require.Equal(t, 5, rsp.Todos.TotalCount) + require.True(t, rsp.Todos.PageInfo.HasNextPage) + require.False(t, rsp.Todos.PageInfo.HasPreviousPage) +} + +type queryCount struct { + n uint64 + dialect.Driver +} + +func (q *queryCount) reset() { atomic.StoreUint64(&q.n, 0) } +func (q *queryCount) value() uint64 { return atomic.LoadUint64(&q.n) } + +func (q *queryCount) Query(ctx context.Context, query string, args, v interface{}) error { + atomic.AddUint64(&q.n, 1) + return q.Driver.Query(ctx, query, args, v) +} + +func TestNestedConnection(t *testing.T) { + ctx := context.Background() + drv, err := sql.Open(dialect.SQLite, fmt.Sprintf("file:%s?mode=memory&cache=shared&_fk=1", t.Name())) + require.NoError(t, err) + count := &queryCount{Driver: drv} + ec := enttest.NewClient(t, enttest.WithOptions(ent.Driver(count))) + srv := handler.NewDefaultServer(gen.NewSchema(ec)) + gqlc := client.New(srv) + + bulkG := make([]*ent.GroupCreate, 10) + for i := range bulkG { + bulkG[i] = ec.Group.Create().SetName(fmt.Sprintf("group-%d", i)) + } + groups := ec.Group.CreateBulk(bulkG...).SaveX(ctx) + bulkU := make([]*ent.UserCreate, 10) + for i := range bulkU { + bulkU[i] = ec.User.Create(). + SetName(fmt.Sprintf("user-%d", i)). + AddGroups(groups[:len(groups)-i]...). + SetRequiredMetadata(map[string]any{}) + } + users := ec.User.CreateBulk(bulkU...).SaveX(ctx) + users[0].Update().AddFriends(users[1:]...).SaveX(ctx) // user 0 is friends with all + users[1].Update().AddFriends(users[2:]...).SaveX(ctx) // user 1 is friends with all + + t.Run("After Cursor", func(t *testing.T) { + var ( + query = `query ($id: ID!, $after: Cursor) { + user: node(id: $id) { + ... on User { + id + name + friends(after: $after) { + totalCount + edges { + cursor + node { + id + name + friends { + totalCount + edges { + node { + id + name + } + } + } + } + } + } + } + } + }` + rsp struct { + User struct { + ID string + Name string + Friends struct { + TotalCount int + Edges []struct { + Cursor string + Node struct { + ID string + Name string + Friends struct { + TotalCount int + Edges []struct { + Node struct { + ID string + Name string + } + } + } + } + } + } + } + } + after any + ) + err = gqlc.Post(query, &rsp, client.Var("id", users[0].ID), client.Var("after", after)) + require.NoError(t, err) + require.Equal(t, 9, rsp.User.Friends.TotalCount) + require.Len(t, rsp.User.Friends.Edges, 9, "All users are friends with user 0") + // First friend of user 0 is user 1. + require.Equal(t, strconv.Itoa(users[1].ID), rsp.User.Friends.Edges[0].Node.ID) + require.Len(t, rsp.User.Friends.Edges[0].Node.Friends.Edges, 9, "All users are friends with user 1") + // All other users have 2 friends (user 0 and user 1). + for _, u := range rsp.User.Friends.Edges[1:] { + require.Len(t, u.Node.Friends.Edges, 2) + } + + // Paginate over the friends of user 0. + n := len(rsp.User.Friends.Edges) + for i := 0; i < n; i++ { + err = gqlc.Post(query, &rsp, client.Var("id", users[0].ID), client.Var("after", after)) + require.NoError(t, err) + require.Equal(t, 9, rsp.User.Friends.TotalCount) + require.Lenf(t, rsp.User.Friends.Edges, n-i, "There are %d friends after %v", n-i, after) + after = rsp.User.Friends.Edges[0].Cursor + } + }) + + t.Run("TotalCount", func(t *testing.T) { + var ( + query = `query ($first: Int) { + users (first: $first) { + totalCount + edges { + node { + name + groups { + totalCount + } + friends { + edges { + node { + name + } + } + } + } + } + } + }` + rsp struct { + Users struct { + TotalCount int + Edges []struct { + Node struct { + Name string + Groups struct { + TotalCount int + } + Friends struct { + Edges []struct { + Node struct { + Name string + } + } + } + } + } + } + } + ) + count.reset() + err = gqlc.Post(query, &rsp, client.Var("first", nil)) + require.NoError(t, err) + // One query for loading all users, and one for getting the groups of each user. + // The totalCount of the root query can be inferred from the length of the user edges. + require.EqualValues(t, 3, count.value()) + require.Equal(t, 10, rsp.Users.TotalCount) + require.Equal(t, 9, len(rsp.Users.Edges[0].Node.Friends.Edges)) + + for n := 1; n <= 10; n++ { + count.reset() + err = gqlc.Post(query, &rsp, client.Var("first", n)) + require.NoError(t, err) + // Two queries for getting the users and their totalCount. + // And another one for getting the totalCount of each user. + require.EqualValues(t, 4, count.value()) + require.Equal(t, 10, rsp.Users.TotalCount) + for i, e := range rsp.Users.Edges { + require.Equal(t, users[i].Name, e.Node.Name) + // Each user i, is connected to 10-i groups. + require.Equal(t, 10-i, e.Node.Groups.TotalCount) + } + } + }) + + t.Run("FirstN", func(t *testing.T) { + var ( + query = `query ($first: Int) { + users { + totalCount + edges { + node { + name + groups (first: $first) { + totalCount + edges { + node { + name + } + } + } + } + } + } + }` + rsp struct { + Users struct { + TotalCount int + Edges []struct { + Node struct { + Name string + Groups struct { + TotalCount int + Edges []struct { + Node struct { + Name string + } + } + } + } + } + } + } + ) + count.reset() + err = gqlc.Post(query, &rsp, client.Var("first", nil)) + require.NoError(t, err) + // One for getting all users, and one for getting all groups. + // The totalCount is derived from len(User.Edges.Groups). + require.EqualValues(t, 2, count.value()) + require.Equal(t, 10, rsp.Users.TotalCount) + + for n := 1; n <= 10; n++ { + count.reset() + err = gqlc.Post(query, &rsp, client.Var("first", n)) + require.NoError(t, err) + // One query for getting the users (totalCount is derived), and another + // two queries for getting the groups and the totalCount of each user. + require.EqualValues(t, 3, count.value()) + require.Equal(t, 10, rsp.Users.TotalCount) + for i, e := range rsp.Users.Edges { + require.Equal(t, users[i].Name, e.Node.Name) + require.Equal(t, 10-i, e.Node.Groups.TotalCount) + require.Len(t, e.Node.Groups.Edges, int(math.Min(float64(n), float64(10-i)))) + for j, g := range e.Node.Groups.Edges { + require.Equal(t, groups[j].Name, g.Node.Name) + } + } + } + }) + + t.Run("Paginate", func(t *testing.T) { + var ( + query = `query ($first: Int, $after: Cursor) { + users (first: 1) { + totalCount + edges { + node { + name + groups (first: $first, after: $after) { + totalCount + edges { + node { + name + users (first: 1) { + edges { + node { + name + } + } + } + } + cursor + } + } + } + } + } + }` + rsp struct { + Users struct { + TotalCount int + Edges []struct { + Node struct { + Name string + Groups struct { + TotalCount int + Edges []struct { + Node struct { + Name string + Users struct { + Edges []struct { + Node struct { + Name string + } + } + } + } + Cursor string + } + } + } + } + } + } + after interface{} + ) + for i := 0; i < 10; i++ { + count.reset() + err = gqlc.Post(query, &rsp, client.Var("first", 1), client.Var("after", after)) + require.NoError(t, err) + require.EqualValues(t, 5, count.value()) + require.Len(t, rsp.Users.Edges, 1) + require.Len(t, rsp.Users.Edges[0].Node.Groups.Edges, 1) + require.Equal(t, groups[i].Name, rsp.Users.Edges[0].Node.Groups.Edges[0].Node.Name) + require.Len(t, rsp.Users.Edges[0].Node.Groups.Edges[0].Node.Users.Edges, 1) + require.Equal(t, users[0].Name, rsp.Users.Edges[0].Node.Groups.Edges[0].Node.Users.Edges[0].Node.Name) + after = rsp.Users.Edges[0].Node.Groups.Edges[0].Cursor + } + }) + + t.Run("Nodes", func(t *testing.T) { + var ( + query = `query ($ids: [ID!]!) { + groups: nodes(ids: $ids) { + ... on Group { + name + users(last: 1) { + totalCount + edges { + node { + name + } + } + } + } + } + }` + rsp struct { + Groups []struct { + Name string + Users struct { + TotalCount int + Edges []struct { + Node struct { + Name string + } + } + } + } + } + ) + // One query to trigger the loading of the ent_types content. + err = gqlc.Post(query, &rsp, client.Var("ids", []int{groups[0].ID})) + require.NoError(t, err) + for i := 1; i <= 10; i++ { + ids := make([]int, 0, i) + for _, g := range groups { + ids = append(ids, g.ID) + } + count.reset() + err = gqlc.Post(query, &rsp, client.Var("ids", ids)) + require.NoError(t, err) + require.Len(t, rsp.Groups, 10) + for _, g := range rsp.Groups { + require.Len(t, g.Users.Edges, 1) + } + require.EqualValues(t, 3, count.value()) + } + }) + + t.Run("Node-cursor", func(t *testing.T) { + var ( + query = `query ($id: ID!, $cursor: Cursor) { + group: node(id: $id) { + ... on Group { + name + users(last: 1, before: $cursor) { + totalCount + edges { + cursor + node { + name + } + } + } + } + } + }` + rsp struct { + Group struct { + Name string + Users struct { + TotalCount int + Edges []struct { + Cursor string + Node struct { + Name string + } + } + } + } + } + ) + err = gqlc.Post(query, &rsp, + client.Var("id", groups[0].ID), + client.Var("cursor", "gaFpzwAAAAcAAAAJ"), + ) + require.NoError(t, err) + require.Equal(t, 1, len(rsp.Group.Users.Edges)) + require.Equal(t, "gaFpzwAAAAcAAAAI", rsp.Group.Users.Edges[0].Cursor) + }) +} + +func TestEdgesFiltering(t *testing.T) { + ctx := context.Background() + drv, err := sql.Open(dialect.SQLite, fmt.Sprintf("file:%s?mode=memory&cache=shared&_fk=1", t.Name())) + require.NoError(t, err) + count := &queryCount{Driver: drv} + ec := enttest.NewClient(t, enttest.WithOptions(ent.Driver(count))) + srv := handler.NewDefaultServer(gen.NewSchema(ec)) + gqlc := client.New(srv) + + root := ec.Todo.CreateBulk( + ec.Todo.Create().SetText("t0.1").SetStatus(todo.StatusInProgress), + ec.Todo.Create().SetText("t0.2").SetStatus(todo.StatusInProgress), + ec.Todo.Create().SetText("t0.3").SetStatus(todo.StatusCompleted), + ).SaveX(ctx) + + child := ec.Todo.CreateBulk( + ec.Todo.Create().SetText("t1.1").SetParent(root[0]).SetStatus(todo.StatusInProgress), + ec.Todo.Create().SetText("t1.2").SetParent(root[0]).SetStatus(todo.StatusCompleted), + ec.Todo.Create().SetText("t1.3").SetParent(root[0]).SetStatus(todo.StatusCompleted), + ).SaveX(ctx) + + grandchild := ec.Todo.CreateBulk( + ec.Todo.Create().SetText("t2.1").SetParent(child[0]).SetStatus(todo.StatusCompleted), + ec.Todo.Create().SetText("t2.2").SetParent(child[0]).SetStatus(todo.StatusCompleted), + ec.Todo.Create().SetText("t2.3").SetParent(child[0]).SetStatus(todo.StatusInProgress), + ec.Todo.Create().SetText("t2.4").SetParent(child[1]).SetStatus(todo.StatusInProgress), + ec.Todo.Create().SetText("t2.5").SetParent(child[1]).SetStatus(todo.StatusInProgress), + ).SaveX(ctx) + + ec.Todo.CreateBulk( + ec.Todo.Create().SetText("t3.1").SetParent(grandchild[0]).SetStatus(todo.StatusInProgress), + ec.Todo.Create().SetText("t3.2").SetParent(grandchild[0]).SetStatus(todo.StatusInProgress), + ec.Todo.Create().SetText("t3.3").SetParent(grandchild[0]).SetStatus(todo.StatusCompleted), + ec.Todo.Create().SetText("t3.4").SetParent(grandchild[1]).SetStatus(todo.StatusInProgress), + ec.Todo.Create().SetText("t3.5").SetParent(grandchild[1]).SetStatus(todo.StatusInProgress), + ec.Todo.Create().SetText("t3.6").SetParent(grandchild[1]).SetStatus(todo.StatusCompleted), + ec.Todo.Create().SetText("t3.7").SetParent(grandchild[1]).SetStatus(todo.StatusCompleted), + ).ExecX(ctx) + + query := `query todos($id: ID!, $lv2Status: TodoStatus!) { + todos(where:{id: $id}) { + edges { + node { + children(where: {statusNEQ: COMPLETED}) { + totalCount + edges { + node { + text + children(where: {statusNEQ: $lv2Status}) { + totalCount + edges { + node { + text + children { + totalCount + } + } + } + } + } + } + } + } + } + } + }` + + var rsp struct { + Todos struct { + Edges []struct { + Node struct { + Children struct { + TotalCount int + Edges []struct { + Node struct { + Text string + Children struct { + TotalCount int + Edges []struct { + Node struct { + Text string + Children struct { + TotalCount int + } + } + } + } + } + } + } + } + } + } + } + + t.Run("query level 2 NEQ IN_PROGRESS", func(t *testing.T) { + count.reset() + err := gqlc.Post(query, &rsp, client.Var("id", root[0].ID), client.Var("lv2Status", "IN_PROGRESS")) + require.NoError(t, err) + + require.Equal(t, 1, rsp.Todos.Edges[0].Node.Children.TotalCount) + require.Equal(t, child[0].Text, rsp.Todos.Edges[0].Node.Children.Edges[0].Node.Text) + + n := rsp.Todos.Edges[0].Node.Children.Edges[0].Node + require.Equal(t, 2, n.Children.TotalCount) + require.Equal(t, grandchild[0].Text, n.Children.Edges[0].Node.Text) + require.Equal(t, 3, n.Children.Edges[0].Node.Children.TotalCount) + require.Equal(t, grandchild[1].Text, n.Children.Edges[1].Node.Text) + require.Equal(t, 4, n.Children.Edges[1].Node.Children.TotalCount) + + // Top-level todos, children, grand-children and totalCount of great-children. + require.EqualValues(t, 4, count.n) + }) + + t.Run("query level 2 NEQ COMPLETED", func(t *testing.T) { + count.reset() + err := gqlc.Post(query, &rsp, client.Var("id", root[0].ID), client.Var("lv2Status", "COMPLETED")) + require.NoError(t, err) + + require.Equal(t, 1, rsp.Todos.Edges[0].Node.Children.TotalCount) + require.Equal(t, child[0].Text, rsp.Todos.Edges[0].Node.Children.Edges[0].Node.Text) + + n := rsp.Todos.Edges[0].Node.Children.Edges[0].Node + require.Equal(t, 1, n.Children.TotalCount) + require.Equal(t, grandchild[2].Text, n.Children.Edges[0].Node.Text) + require.Zero(t, n.Children.Edges[0].Node.Children.TotalCount) + + // Top-level todos, children, grand-children and totalCount of great-children. + require.EqualValues(t, 4, count.n) + }) + + query = `query todos($id: ID!) { + todos(where:{id: $id}) { + edges { + node { + completed: children(where: {status: COMPLETED}) { + totalCount + edges { + node { + text + } + } + } + inProgress: children(where: {statusNEQ: COMPLETED}) { + totalCount + edges { + node { + text + } + } + } + } + } + } + }` + + var rsp2 struct { + Todos struct { + Edges []struct { + Node struct { + Completed struct { + TotalCount int + Edges []struct { + Node struct { + Text string + } + } + } + InProgress struct { + TotalCount int + Edges []struct { + Node struct { + Text string + } + } + } + } + } + } + } + + t.Run("filter connection with alias", func(t *testing.T) { + count.reset() + err := gqlc.Post(query, &rsp2, client.Var("id", root[0].ID), client.Var("lv2Status", "IN_PROGRESS")) + require.NoError(t, err) + + require.Equal(t, 2, rsp2.Todos.Edges[0].Node.Completed.TotalCount) + n := rsp2.Todos.Edges[0].Node.Completed + require.Equal(t, "t1.2", n.Edges[0].Node.Text) + require.Equal(t, "t1.3", n.Edges[1].Node.Text) + + require.Equal(t, 1, rsp2.Todos.Edges[0].Node.InProgress.TotalCount) + n = rsp2.Todos.Edges[0].Node.InProgress + require.Equal(t, "t1.1", n.Edges[0].Node.Text) + }) +} + +func TestMutation_CreateCategory(t *testing.T) { + ec := enttest.Open(t, dialect.SQLite, fmt.Sprintf("file:%s?mode=memory&cache=shared&_fk=1", t.Name())) + srv := handler.NewDefaultServer(gen.NewSchema(ec)) + srv.Use(entgql.Transactioner{TxOpener: ec}) + gqlc := client.New(srv) + + // Create a category. + var rsp struct { + CreateCategory struct { + ID string + Text string + Status string + Todos struct { + TotalCount int + Edges []struct { + Node struct { + Text string + Status string + } + } + } + } + } + err := gqlc.Post(` + mutation createCategory { + createCategory(input: { + text: "cate1" + status: ENABLED + createTodos: [ + { status: IN_PROGRESS, text: "c1.t1" }, + { status: IN_PROGRESS, text: "c1.t2" } + ] + }) { + id + text + status + todos { + totalCount + edges { + node { + text + status + } + } + } + } + } + `, &rsp) + require.NoError(t, err) + + require.Equal(t, 2, rsp.CreateCategory.Todos.TotalCount) + n := rsp.CreateCategory.Todos + require.Equal(t, "c1.t1", n.Edges[0].Node.Text) + require.Equal(t, "c1.t2", n.Edges[1].Node.Text) +} + +func TestMutation_ClearChildren(t *testing.T) { + ec := enttest.Open(t, dialect.SQLite, fmt.Sprintf("file:%s?mode=memory&cache=shared&_fk=1", t.Name())) + srv := handler.NewDefaultServer(gen.NewSchema(ec)) + srv.Use(entgql.Transactioner{TxOpener: ec}) + gqlc := client.New(srv) + + ctx := context.Background() + root := ec.Todo.Create().SetText("t0.1").SetStatus(todo.StatusInProgress).SaveX(ctx) + ec.Todo.CreateBulk( + ec.Todo.Create().SetText("t1.1").SetParent(root).SetStatus(todo.StatusInProgress), + ec.Todo.Create().SetText("t1.2").SetParent(root).SetStatus(todo.StatusCompleted), + ec.Todo.Create().SetText("t1.3").SetParent(root).SetStatus(todo.StatusCompleted), + ).ExecX(ctx) + require.True(t, root.QueryChildren().ExistX(ctx)) + + var rsp struct { + UpdateTodo struct { + ID string + } + } + err := gqlc.Post(` + mutation cleanChildren($id: ID!){ + updateTodo(id: $id, input: {clearChildren: true}) { + id + } + } + `, &rsp, client.Var("id", root.ID)) + require.NoError(t, err) + require.Equal(t, strconv.Itoa(root.ID), rsp.UpdateTodo.ID) + require.False(t, root.QueryChildren().ExistX(ctx)) +} + +func TestMutation_ClearFriend(t *testing.T) { + ec := enttest.Open(t, dialect.SQLite, fmt.Sprintf("file:%s?mode=memory&cache=shared&_fk=1", t.Name())) + srv := handler.NewDefaultServer(gen.NewSchema(ec)) + srv.Use(entgql.Transactioner{TxOpener: ec}) + gqlc := client.New(srv) + + ctx := context.Background() + user := ec.User.Create().SetRequiredMetadata(map[string]any{}).SaveX(ctx) + friend := ec.User.Create().SetRequiredMetadata(map[string]any{}).AddFriends(user).SaveX(ctx) + friendship := user.QueryFriendships().FirstX(ctx) + + require.True(t, user.QueryFriends().ExistX(ctx)) + require.True(t, friend.QueryFriends().ExistX(ctx)) + + var rsp struct { + UpdateFriendship struct { + ID string + } + } + err := gqlc.Post(` + mutation clearFriend($id: ID!){ + updateFriendship(id: $id, input: {clearFriend: true}) { + id + } + } + `, &rsp, client.Var("id", friendship.ID)) + + require.ErrorContains(t, err, "\\\"clearFriend\\\" is not defined by type \\\"UpdateFriendshipInput\\\"") +} + +func TestDescendingIDs(t *testing.T) { + ctx := context.Background() + ec := enttest.Open(t, dialect.SQLite, fmt.Sprintf("file:%s?mode=memory&_fk=1", t.Name())) + srv := handler.NewDefaultServer(gen.NewSchema(ec)) + srv.Use(entgql.Transactioner{TxOpener: ec}) + ec.Category.CreateBulk( + ec.Category.Create().SetID(1).SetText("c1").SetStatus(category.StatusEnabled), + ec.Category.Create().SetID(2).SetText("c2").SetStatus(category.StatusEnabled), + ec.Category.Create().SetID(3).SetText("c3").SetStatus(category.StatusEnabled), + ).SaveX(ctx) + + var ( + gqlc = client.New(srv) + // language=GraphQL + query = `query ($after: Cursor){ + categories(orderBy: [{direction: DESC, field: ID}], first: 2, after: $after) { + edges { + node { + id + } + cursor + } + } + }` + rsp struct { + Categories struct { + Edges []struct { + Node struct { + ID string + } + Cursor string + } + } + } + after any + ) + err := gqlc.Post(query, &rsp, client.Var("after", after)) + require.NoError(t, err) + require.Equal(t, "3", rsp.Categories.Edges[0].Node.ID) + require.Equal(t, "2", rsp.Categories.Edges[1].Node.ID) + after = rsp.Categories.Edges[1].Cursor + + err = gqlc.Post(query, &rsp, client.Var("after", after)) + require.NoError(t, err) + require.Len(t, rsp.Categories.Edges, 1) + require.Equal(t, "1", rsp.Categories.Edges[0].Node.ID) + after = rsp.Categories.Edges[0].Cursor + + err = gqlc.Post(query, &rsp, client.Var("after", after)) + require.NoError(t, err) + require.Empty(t, rsp.Categories.Edges) +} + +func TestMultiFieldsOrder(t *testing.T) { + ctx := context.Background() + ec := enttest.Open(t, dialect.SQLite, fmt.Sprintf("file:%s?mode=memory&_fk=1", t.Name())) + srv := handler.NewDefaultServer(gen.NewSchema(ec)) + srv.Use(entgql.Transactioner{TxOpener: ec}) + cats := ec.Category.CreateBulk( + ec.Category.Create().SetID(1).SetText("category-1").SetCount(2).SetStatus(category.StatusDisabled), + ec.Category.Create().SetID(2).SetText("category-1").SetCount(1).SetStatus(category.StatusDisabled), + ec.Category.Create().SetID(3).SetText("category-2").SetCount(2).SetStatus(category.StatusDisabled), + ec.Category.Create().SetID(4).SetText("category-2").SetCount(1).SetStatus(category.StatusDisabled), + ec.Category.Create().SetID(5).SetText("category-3").SetCount(2).SetStatus(category.StatusDisabled), + ec.Category.Create().SetID(6).SetText("category-3").SetCount(1).SetStatus(category.StatusDisabled), + ).SaveX(ctx) + require.Len(t, cats, 6) + + var ( + gqlc = client.New(srv) + // language=GraphQL + query = `query ($after: Cursor, $before: Cursor, $first: Int, $last: Int, $textDirection: OrderDirection = ASC, $countDirection: OrderDirection = ASC){ + categories( + after: $after, + before: $before, + first: $first, + last: $last, + orderBy: [{field: TEXT, direction: $textDirection}, {field: COUNT, direction: $countDirection}], + ) { + edges { + node { + id + } + cursor + } + pageInfo { + hasNextPage + hasPreviousPage + startCursor + endCursor + } + } + }` + rsp struct { + Categories struct { + Edges []struct { + Node struct { + ID string + } + Cursor string + } + PageInfo struct { + HasNextPage bool + HasPreviousPage bool + StartCursor *string + EndCursor *string + } + } + } + ids = func() (s []string) { + for _, n := range rsp.Categories.Edges { + s = append(s, n.Node.ID) + } + return + } + after, before any + ) + t.Run("CountAsc", func(t *testing.T) { + err := gqlc.Post(query, &rsp, client.Var("after", after), client.Var("before", before), client.Var("first", 3)) + require.NoError(t, err) + require.Len(t, rsp.Categories.Edges, 3) + // cats[1], cats[0], cats[3]. + require.Equal(t, []string{"2", "1", "4"}, ids()) + require.True(t, rsp.Categories.PageInfo.HasNextPage) + + after = rsp.Categories.PageInfo.EndCursor + err = gqlc.Post(query, &rsp, client.Var("after", after), client.Var("first", 3)) + require.NoError(t, err) + require.Len(t, rsp.Categories.Edges, 3) + // cats[2], cats[5], cats[4]. + require.Equal(t, []string{"3", "6", "5"}, ids()) + require.False(t, rsp.Categories.PageInfo.HasNextPage) + + after = rsp.Categories.PageInfo.EndCursor + err = gqlc.Post(query, &rsp, client.Var("after", after)) + require.NoError(t, err) + require.Empty(t, rsp.Categories.Edges) + require.False(t, rsp.Categories.PageInfo.HasNextPage) + }) + + t.Run("CountDesc", func(t *testing.T) { + err := gqlc.Post(query, &rsp, client.Var("countDirection", "DESC"), client.Var("first", 3)) + require.NoError(t, err) + require.Len(t, rsp.Categories.Edges, 3) + // cats[0], cats[1], cats[2]. + require.Equal(t, []string{"1", "2", "3"}, ids()) + require.True(t, rsp.Categories.PageInfo.HasNextPage) + + after = rsp.Categories.PageInfo.EndCursor + err = gqlc.Post(query, &rsp, client.Var("after", after), client.Var("countDirection", "DESC"), client.Var("first", 3)) + require.NoError(t, err) + require.Len(t, rsp.Categories.Edges, 3) + // cats[3], cats[4], cats[5]. + require.Equal(t, []string{"4", "5", "6"}, ids()) + require.False(t, rsp.Categories.PageInfo.HasNextPage) + + after = rsp.Categories.PageInfo.EndCursor + err = gqlc.Post(query, &rsp, client.Var("after", after), client.Var("countDirection", "DESC")) + require.NoError(t, err) + require.Empty(t, rsp.Categories.Edges) + require.False(t, rsp.Categories.PageInfo.HasNextPage) + }) + + t.Run("TextCountDesc", func(t *testing.T) { + // Page forward. + err := gqlc.Post(query, &rsp, client.Var("textDirection", "DESC"), client.Var("countDirection", "DESC"), client.Var("first", 3)) + require.NoError(t, err) + require.Len(t, rsp.Categories.Edges, 3) + // cats[4], cats[5], cats[2]. + require.Equal(t, []string{"5", "6", "3"}, ids()) + require.True(t, rsp.Categories.PageInfo.HasNextPage) + + after = rsp.Categories.PageInfo.EndCursor + err = gqlc.Post(query, &rsp, client.Var("after", after), client.Var("textDirection", "DESC"), client.Var("countDirection", "DESC"), client.Var("first", 3)) + require.NoError(t, err) + require.Len(t, rsp.Categories.Edges, 3) + // cats[3], cats[0], cats[1]. + require.Equal(t, []string{"4", "1", "2"}, ids()) + require.False(t, rsp.Categories.PageInfo.HasNextPage) + + after = rsp.Categories.PageInfo.EndCursor + err = gqlc.Post(query, &rsp, client.Var("after", after), client.Var("textDirection", "DESC"), client.Var("countDirection", "DESC")) + require.NoError(t, err) + require.Empty(t, rsp.Categories.Edges) + require.False(t, rsp.Categories.PageInfo.HasNextPage) + + // All categories. + err = gqlc.Post(query, &rsp, client.Var("textDirection", "DESC"), client.Var("countDirection", "DESC")) + require.NoError(t, err) + require.Len(t, rsp.Categories.Edges, 6) + // cats[4], cats[5], cats[2], cats[3], cats[0], cats[1]. + require.Equal(t, []string{"5", "6", "3", "4", "1", "2"}, ids()) + require.False(t, rsp.Categories.PageInfo.HasNextPage) + + // Page backward. + err = gqlc.Post(query, &rsp, client.Var("textDirection", "DESC"), client.Var("countDirection", "DESC"), client.Var("last", 3)) + require.NoError(t, err) + require.Len(t, rsp.Categories.Edges, 3) + // cats[3], cats[0], cats[1]. + require.Equal(t, []string{"4", "1", "2"}, ids()) + require.True(t, rsp.Categories.PageInfo.HasPreviousPage) + + before = rsp.Categories.PageInfo.StartCursor + err = gqlc.Post(query, &rsp, client.Var("before", before), client.Var("textDirection", "DESC"), client.Var("countDirection", "DESC"), client.Var("last", 3)) + require.NoError(t, err) + require.Len(t, rsp.Categories.Edges, 3) + // cats[4], cats[5], cats[2]. + require.Equal(t, []string{"5", "6", "3"}, ids()) + require.False(t, rsp.Categories.PageInfo.HasPreviousPage) + }) +} + +type queryRecorder struct { + queries []string + dialect.Driver +} + +func (r *queryRecorder) reset() { + r.queries = nil +} + +func (r *queryRecorder) Query(ctx context.Context, query string, args, v interface{}) error { + r.queries = append(r.queries, query) + return r.Driver.Query(ctx, query, args, v) +} + +func TestReduceQueryComplexity(t *testing.T) { + ctx := context.Background() + drv, err := sql.Open(dialect.SQLite, fmt.Sprintf("file:%s?mode=memory&cache=shared&_fk=1", t.Name())) + require.NoError(t, err) + rec := &queryRecorder{Driver: drv} + ec := enttest.NewClient(t, + enttest.WithOptions(ent.Driver(rec)), + ) + var ( + // language=GraphQL + query = `query Todo($id: ID!) { + node(id: $id) { + ... on Todo { + text + children (first: 10) { + edges { + node { + text + } + } + } + } + } + }` + gqlc = client.New(handler.NewDefaultServer(gen.NewSchema(ec))) + ) + t1 := ec.Todo.Create().SetText("t1").SetStatus(todo.StatusInProgress).SaveX(ctx) + rec.reset() + require.NoError(t, gqlc.Post(query, new(any), client.Var("id", t1.ID))) + require.Equal(t, []string{ + // Top-level todo. + "SELECT `todos`.`id`, `todos`.`text` FROM `todos` WHERE `todos`.`id` = ? LIMIT 2", + // Children todos (without CTE). + "SELECT `todos`.`id`, `todos`.`text`, `todos`.`project_todos`, `todos`.`todo_children`, `todos`.`todo_secret` FROM `todos` WHERE `todos`.`todo_children` IN (?) ORDER BY `todos`.`id` LIMIT 11", + }, rec.queries) + + // language=GraphQL + query = `query Todos($ids: [ID!]!) { + todos: nodes (ids: $ids) { + ... on Todo { + text + children (first: 10) { + edges { + node { + text + } + } + } + } + } + }` + rec.reset() + require.NoError(t, gqlc.Post(query, new(any), client.Var("ids", []int{t1.ID}))) + // A single ID is implemented by the `node` query. + require.Equal(t, []string{ + // Top-level todo. + "SELECT `todos`.`id`, `todos`.`text` FROM `todos` WHERE `todos`.`id` = ? LIMIT 2", + // Children todos (without CTE). + "SELECT `todos`.`id`, `todos`.`text`, `todos`.`project_todos`, `todos`.`todo_children`, `todos`.`todo_secret` FROM `todos` WHERE `todos`.`todo_children` IN (?) ORDER BY `todos`.`id` LIMIT 11", + }, rec.queries) + + rec.reset() + require.NoError(t, gqlc.Post(query, new(any), client.Var("ids", []int{t1.ID, t1.ID}))) + require.Equal(t, []string{ + // Top-level todo. + "SELECT `todos`.`id`, `todos`.`text` FROM `todos` WHERE `todos`.`id` IN (?, ?)", + // Children todos (with CTE). + "WITH `src_query` AS (SELECT `todos`.`id`, `todos`.`text`, `todos`.`project_todos`, `todos`.`todo_children`, `todos`.`todo_secret` FROM `todos` WHERE `todos`.`todo_children` IN (?)), `limited_query` AS (SELECT *, (ROW_NUMBER() OVER (PARTITION BY `todo_children` ORDER BY `id` ASC)) AS `row_number` FROM `src_query`) SELECT `id`, `text`, `project_todos`, `todo_children`, `todo_secret` FROM `limited_query` AS `todos` WHERE `todos`.`row_number` <= ?", + }, rec.queries) + + // Propagate uniqueness to one-child edges. + // language=GraphQL + query = `query Todo($id: ID!) { + node(id: $id) { + ... on Todo { + parent { + text + children (first: 5) { + edges { + node { + text + } + } + } + } + category { + text + todos (first: 10) { + edges { + node { + text + } + } + } + } + } + } + }` + ec.Todo.Create().SetText("t0").SetStatus(todo.StatusInProgress).AddChildren(t1).SaveX(ctx) + ec.Category.Create().AddTodos(t1).SetText("c0").SetStatus(category.StatusEnabled).SaveX(ctx) + rec.reset() + require.NoError(t, gqlc.Post(query, new(any), client.Var("id", t1.ID))) + require.Equal(t, []string{ + // Top-level todo. + "SELECT `todos`.`id`, `todos`.`category_id`, `todos`.`project_todos`, `todos`.`todo_children`, `todos`.`todo_secret` FROM `todos` WHERE `todos`.`id` = ? LIMIT 2", + // Parent todo. + "SELECT `todos`.`id`, `todos`.`text` FROM `todos` WHERE `todos`.`id` IN (?)", + // Parent children. + "SELECT `todos`.`id`, `todos`.`text`, `todos`.`project_todos`, `todos`.`todo_children`, `todos`.`todo_secret` FROM `todos` WHERE `todos`.`todo_children` IN (?) ORDER BY `todos`.`id` LIMIT 6", + // Category. + "SELECT `categories`.`id`, `categories`.`text` FROM `categories` WHERE `categories`.`id` IN (?)", + // Category todos. + "SELECT `todos`.`id`, `todos`.`text`, `todos`.`category_id`, `todos`.`project_todos`, `todos`.`todo_children`, `todos`.`todo_secret` FROM `todos` WHERE `todos`.`category_id` IN (?) ORDER BY `todos`.`id` LIMIT 11", + }, rec.queries) + + // Same as above, but with multiple IDs. + // language=GraphQL + query = `query Todo($id: ID!) { + nodes(ids: [$id, $id]) { + ... on Todo { + parent { + text + children (first: 5) { + edges { + node { + text + } + } + } + } + category { + text + todos (first: 10) { + edges { + node { + text + } + } + } + } + } + } + }` + rec.reset() + require.NoError(t, gqlc.Post(query, new(any), client.Var("id", t1.ID))) + require.Equal(t, []string{ + // Root nodes. + "SELECT `todos`.`id`, `todos`.`category_id`, `todos`.`project_todos`, `todos`.`todo_children`, `todos`.`todo_secret` FROM `todos` WHERE `todos`.`id` IN (?, ?)", + // Their parents (2 max). + "SELECT `todos`.`id`, `todos`.`text` FROM `todos` WHERE `todos`.`id` IN (?)", + // 5 children for each parent. + "WITH `src_query` AS (SELECT `todos`.`id`, `todos`.`text`, `todos`.`project_todos`, `todos`.`todo_children`, `todos`.`todo_secret` FROM `todos` WHERE `todos`.`todo_children` IN (?)), `limited_query` AS (SELECT *, (ROW_NUMBER() OVER (PARTITION BY `todo_children` ORDER BY `id` ASC)) AS `row_number` FROM `src_query`) SELECT `id`, `text`, `project_todos`, `todo_children`, `todo_secret` FROM `limited_query` AS `todos` WHERE `todos`.`row_number` <= ?", + // Category. + "SELECT `categories`.`id`, `categories`.`text` FROM `categories` WHERE `categories`.`id` IN (?)", + // 10 todos for each category. + "WITH `src_query` AS (SELECT `todos`.`id`, `todos`.`text`, `todos`.`category_id`, `todos`.`project_todos`, `todos`.`todo_children`, `todos`.`todo_secret` FROM `todos` WHERE `todos`.`category_id` IN (?)), `limited_query` AS (SELECT *, (ROW_NUMBER() OVER (PARTITION BY `category_id` ORDER BY `id` ASC)) AS `row_number` FROM `src_query`) SELECT `id`, `text`, `category_id`, `project_todos`, `todo_children`, `todo_secret` FROM `limited_query` AS `todos` WHERE `todos`.`row_number` <= ?", + }, rec.queries) +} + +func TestFieldSelection(t *testing.T) { + ctx := context.Background() + drv, err := sql.Open(dialect.SQLite, fmt.Sprintf("file:%s?mode=memory&cache=shared&_fk=1", t.Name())) + require.NoError(t, err) + rec := &queryRecorder{Driver: drv} + ec := enttest.NewClient(t, enttest.WithOptions(ent.Driver(rec))) + root := ec.Todo.CreateBulk( + ec.Todo.Create().SetText("t0.1").SetStatus(todo.StatusInProgress), + ec.Todo.Create().SetText("t0.2").SetStatus(todo.StatusInProgress), + ec.Todo.Create().SetText("t0.3").SetStatus(todo.StatusCompleted), + ).SaveX(ctx) + ec.Todo.CreateBulk( + ec.Todo.Create().SetText("t1.1").SetParent(root[0]).SetStatus(todo.StatusInProgress), + ec.Todo.Create().SetText("t1.2").SetParent(root[0]).SetStatus(todo.StatusCompleted), + ec.Todo.Create().SetText("t1.3").SetParent(root[0]).SetStatus(todo.StatusCompleted), + ).SaveX(ctx) + var ( + // language=GraphQL + query = `query { + todos { + edges { + node { + children { + totalCount + edges { + node { + text + } + } + } + } + } + } + }` + rsp struct { + Todos struct { + Edges []struct { + Node struct { + Children struct { + TotalCount int + Edges []struct { + Node struct { + Text string + } + } + } + } + } + } + } + gqlc = client.New(handler.NewDefaultServer(gen.NewSchema(ec))) + ) + rec.reset() + gqlc.MustPost(query, &rsp) + require.Equal(t, []string{ + // No fields were selected besides the "id" field. + "SELECT `todos`.`id` FROM `todos` ORDER BY `todos`.`id`", + // The "id" and the "text" fields were selected + all foreign keys (see, `withFKs` query field). + "SELECT `todos`.`id`, `todos`.`text`, `todos`.`project_todos`, `todos`.`todo_children`, `todos`.`todo_secret` FROM `todos` WHERE `todos`.`todo_children` IN (?, ?, ?, ?, ?, ?) ORDER BY `todos`.`id`", + }, rec.queries) + + ec.Category.CreateBulk( + ec.Category.Create().AddTodos(root[0]).SetText("c0").SetStatus(category.StatusEnabled), + ec.Category.Create().AddTodos(root[1]).SetText("c1").SetStatus(category.StatusEnabled), + ec.Category.Create().AddTodos(root[2]).SetText("c2").SetStatus(category.StatusEnabled), + ).SaveX(ctx) + var ( + // language=GraphQL + query2 = `query { + todos { + edges { + node { + category { + text + } + } + } + } + }` + rsp2 struct { + Todos struct { + Edges []struct { + Node struct { + Category struct { + Text string + } + } + } + } + } + ) + rec.reset() + client.New(handler.NewDefaultServer(gen.NewSchema(ec))). + MustPost(query2, &rsp2) + require.Equal(t, []string{ + // Also query the "category_id" field for the "category" selection. + "SELECT `todos`.`id`, `todos`.`category_id` FROM `todos` ORDER BY `todos`.`id`", + // Select the "text" field for the "category" selection. + "SELECT `categories`.`id`, `categories`.`text` FROM `categories` WHERE `categories`.`id` IN (?, ?, ?, ?)", + }, rec.queries) + + var ( + // language=GraphQL + query3 = `query { + todos { + edges { + node { + __typename + text + } + } + } + }` + rsp3 struct { + Todos struct { + Edges []struct { + Node struct { + TypeName string `json:"__typename"` + Text string + } + } + } + } + ) + rec.reset() + client.New(handler.NewDefaultServer(gen.NewSchema(ec))). + MustPost(query3, &rsp3) + require.Equal(t, []string{ + // Ignore the __typename meta field. + "SELECT `todos`.`id`, `todos`.`text` FROM `todos` ORDER BY `todos`.`id`", + }, rec.queries) + + var ( + // language=GraphQL + query4 = `query { + todos { + edges { + node { + text + extendedField + } + } + } + }` + rsp4 struct { + Todos struct { + Edges []struct { + Node struct { + Text string + ExtendedField string + } + } + } + } + ) + rec.reset() + client.New(handler.NewDefaultServer(gen.NewSchema(ec))). + MustPost(query4, &rsp4) + require.Equal(t, []string{ + // Unknown fields enforce query all columns. + "SELECT `todos`.`id`, `todos`.`created_at`, `todos`.`status`, " + + "`todos`.`priority`, `todos`.`text`, `todos`.`blob`, " + + "`todos`.`category_id`, `todos`.`init`, `todos`.`custom`, " + + "`todos`.`customp`, `todos`.`value` FROM `todos` ORDER BY `todos`.`id`", + }, rec.queries) + + rootO2M := ec.OneToMany.CreateBulk( + ec.OneToMany.Create().SetName("t0.1"), + ec.OneToMany.Create().SetName("t0.2"), + ec.OneToMany.Create().SetName("t0.3"), + ).SaveX(ctx) + ec.OneToMany.CreateBulk( + ec.OneToMany.Create().SetName("t1.1").SetParent(rootO2M[0]), + ec.OneToMany.Create().SetName("t1.2").SetParent(rootO2M[0]), + ec.OneToMany.Create().SetName("t1.3").SetParent(rootO2M[0]), + ).SaveX(ctx) + var ( + // language=GraphQL + queryO2M = `query { + oneToMany { + edges { + node { + id + name + children { + name + } + } + } + } + }` + rspO2M struct { + OneToMany struct { + Edges []struct { + Node struct { + ID string + Name string + Children []struct { + ID string + Name string + } + } + } + } + } + gqlcO2M = client.New(handler.NewDefaultServer(gen.NewSchema(ec))) + ) + rec.reset() + gqlcO2M.MustPost(queryO2M, &rspO2M) + require.Equal(t, []string{ + "SELECT `one_to_manies`.`id`, `one_to_manies`.`name` FROM `one_to_manies` ORDER BY `one_to_manies`.`id`", + "SELECT `one_to_manies`.`id`, `one_to_manies`.`name`, `one_to_manies`.`parent_id` FROM `one_to_manies` WHERE `one_to_manies`.`parent_id` IN (?, ?, ?, ?, ?, ?)", + }, rec.queries) +} + +func TestOrderByEdgeCount(t *testing.T) { + ctx := context.Background() + ec := enttest.Open(t, dialect.SQLite, fmt.Sprintf("file:%s?mode=memory&cache=shared&_fk=1", t.Name())) + gqlc := client.New(handler.NewDefaultServer(gen.NewSchema(ec))) + cats := ec.Category.CreateBulk( + ec.Category.Create().SetText("parents").SetStatus(category.StatusEnabled), + ec.Category.Create().SetText("children").SetStatus(category.StatusEnabled), + ).SaveX(ctx) + root := ec.Todo.CreateBulk( + ec.Todo.Create().SetText("t0.1").SetStatus(todo.StatusPending).SetCategory(cats[0]), + ec.Todo.Create().SetText("t0.2").SetStatus(todo.StatusInProgress).SetCategory(cats[0]), + ec.Todo.Create().SetText("t0.3").SetStatus(todo.StatusCompleted).SetCategory(cats[0]), + ).SaveX(ctx) + ec.Todo.CreateBulk( + ec.Todo.Create().SetText("t1.1").SetParent(root[0]).SetStatus(todo.StatusInProgress).SetCategory(cats[1]), + ec.Todo.Create().SetText("t1.2").SetParent(root[0]).SetStatus(todo.StatusCompleted).SetCategory(cats[1]), + ec.Todo.Create().SetText("t1.3").SetParent(root[0]).SetStatus(todo.StatusCompleted).SetCategory(cats[1]), + ec.Todo.Create().SetText("t2.1").SetParent(root[1]).SetStatus(todo.StatusInProgress).SetCategory(cats[1]), + ec.Todo.Create().SetText("t2.2").SetParent(root[1]).SetStatus(todo.StatusCompleted).SetCategory(cats[1]), + ec.Todo.Create().SetText("t3.1").SetParent(root[2]).SetStatus(todo.StatusInProgress).SetCategory(cats[1]), + ).SaveX(ctx) + + t.Run("ChildrenCount", func(t *testing.T) { + var ( + // language=GraphQL + query = `query TodosByChildCount($direction: OrderDirection = ASC){ + todos( + # Filter only those with children. + where: {hasChildren: true}, + orderBy: {field: CHILDREN_COUNT, direction: $direction}, + ) { + edges { + node { + id + } + } + } + }` + rsp struct { + Todos struct { + Edges []struct { + Node struct { + ID string + } + } + } + } + ) + gqlc.MustPost(query, &rsp, client.Var("direction", "DESC")) + require.Len(t, rsp.Todos.Edges, 3) + for i, r := range root { + require.Equal(t, rsp.Todos.Edges[i].Node.ID, strconv.Itoa(r.ID)) + } + gqlc.MustPost(query, &rsp, client.Var("direction", "ASC")) + require.Len(t, rsp.Todos.Edges, 3) + for i, r := range root { + require.Equal(t, rsp.Todos.Edges[len(rsp.Todos.Edges)-i-1].Node.ID, strconv.Itoa(r.ID)) + } + }) + + t.Run("NestedEdgeCountOrdering", func(t *testing.T) { + var ( + // language=GraphQL + query = `query CategoryByTodosCount { + categories( + orderBy: {field: TODOS_COUNT, direction: DESC}, + ) { + edges { + node { + id + todos(orderBy: {field: CHILDREN_COUNT, direction: DESC}) { + edges { + node { + id + } + } + } + } + } + } + }` + rsp struct { + Categories struct { + Edges []struct { + Node struct { + ID string + Todos struct { + Edges []struct { + Node struct { + ID string + } + } + } + } + } + } + } + ) + gqlc.MustPost(query, &rsp) + require.Len(t, rsp.Categories.Edges, 2) + childC, parentC := rsp.Categories.Edges[0].Node, rsp.Categories.Edges[1].Node + // Second categories holds todos without children. + require.Equal(t, childC.ID, strconv.Itoa(cats[1].ID)) + require.Len(t, childC.Todos.Edges, 6) + // First categories holds parent todos. + require.Equal(t, parentC.ID, strconv.Itoa(cats[0].ID)) + require.Len(t, parentC.Todos.Edges, 3) + for i, r := range root { + require.Equal(t, parentC.Todos.Edges[i].Node.ID, strconv.Itoa(r.ID)) + } + }) + + t.Run("EdgeFieldOrdering", func(t *testing.T) { + var ( + // language=GraphQL + query = `query TodosByParentStatus($direction: OrderDirection = ASC) { + todos( + # Filter out parent todos. + where: {hasParent: true}, + orderBy: {field: PARENT_STATUS, direction: $direction}, + ) { + edges { + node { + parent { + status + } + } + } + } + }` + rsp struct { + Todos struct { + Edges []struct { + Node struct { + Parent struct { + Status todo.Status + } + } + } + } + } + expected = []todo.Status{ + todo.StatusCompleted, todo.StatusInProgress, todo.StatusInProgress, + todo.StatusPending, todo.StatusPending, todo.StatusPending, + } + ) + gqlc.MustPost(query, &rsp, client.Var("direction", "ASC")) + require.Len(t, rsp.Todos.Edges, 6) + for i, p := range rsp.Todos.Edges { + require.Equal(t, expected[i], p.Node.Parent.Status) + } + // Reverse the order. + gqlc.MustPost(query, &rsp, client.Var("direction", "DESC")) + require.Len(t, rsp.Todos.Edges, 6) + for i, p := range rsp.Todos.Edges { + require.Equal(t, expected[len(expected)-i-1], p.Node.Parent.Status) + } + }) + + t.Run("ExposeOrderField", func(t *testing.T) { + var ( + // language=GraphQL + query = `query CategoryByTodosCount { + categories( + orderBy: {field: TODOS_COUNT, direction: DESC}, + ) { + edges { + node { + todosCount + } + } + } + }` + rsp struct { + Categories struct { + Edges []struct { + Node struct { + TodosCount int + } + } + } + } + ) + gqlc.MustPost(query, &rsp) + require.Len(t, rsp.Categories.Edges, 2) + require.Equal(t, rsp.Categories.Edges[0].Node.TodosCount, 6) + require.Equal(t, rsp.Categories.Edges[1].Node.TodosCount, 3) + }) +} + +func TestSatisfiesFragments(t *testing.T) { + ctx := context.Background() + ec := enttest.Open(t, dialect.SQLite, fmt.Sprintf("file:%s?mode=memory&cache=shared&_fk=1", t.Name())) + gqlc := client.New(handler.NewDefaultServer(gen.NewSchema(ec))) + cat := ec.Category.Create().SetText("cat").SetStatus(category.StatusEnabled).SaveX(ctx) + todos := ec.Todo.CreateBulk( + ec.Todo.Create().SetText("t1").SetStatus(todo.StatusPending).SetCategory(cat), + ec.Todo.Create().SetText("t2").SetStatus(todo.StatusInProgress).SetCategory(cat), + ec.Todo.Create().SetText("t3").SetStatus(todo.StatusCompleted).SetCategory(cat), + ).SaveX(ctx) + var ( + // language=GraphQL + query = `query CategoryTodo($id: ID!) { + category: node(id: $id) { + __typename + id + ... on Category { + text + ...CategoryTodos + } + } + } + + fragment CategoryTodos on Category { + todos (orderBy: {field: TEXT}) { + edges { + node { + id + ...TodoFields + } + } + } + } + + fragment TodoFields on Todo { + id + text + createdAt + } + ` + rsp struct { + Category struct { + TypeName string `json:"__typename"` + ID, Text string + Todos struct { + Edges []struct { + Node struct { + ID, Text, CreatedAt string + } + } + } + } + } + ) + gqlc.MustPost(query, &rsp, client.Var("id", cat.ID)) + require.Equal(t, strconv.Itoa(cat.ID), rsp.Category.ID) + require.Len(t, rsp.Category.Todos.Edges, 3) + for i := range todos { + require.Equal(t, strconv.Itoa(todos[i].ID), rsp.Category.Todos.Edges[i].Node.ID) + require.Equal(t, todos[i].Text, rsp.Category.Todos.Edges[i].Node.Text) + ts, err := todos[i].CreatedAt.MarshalText() + require.NoError(t, err) + require.Equal(t, string(ts), rsp.Category.Todos.Edges[i].Node.CreatedAt) + } +} + +func TestSatisfiesDeeperFragments(t *testing.T) { + ctx := context.Background() + ec := enttest.Open(t, dialect.SQLite, fmt.Sprintf("file:%s?mode=memory&cache=shared&_fk=1", t.Name())) + gqlc := client.New(handler.NewDefaultServer(gen.NewSchema(ec))) + cat := ec.Category.Create().SetText("cat").SetStatus(category.StatusEnabled).SaveX(ctx) + todos := ec.Todo.CreateBulk( + ec.Todo.Create().SetText("t1").SetStatus(todo.StatusPending).SetCategory(cat), + ec.Todo.Create().SetText("t2").SetStatus(todo.StatusInProgress).SetCategory(cat), + ec.Todo.Create().SetText("t3").SetStatus(todo.StatusCompleted).SetCategory(cat), + ).SaveX(ctx) + var ( + // language=GraphQL + query = `query Node($id: ID!) { + todo: node(id: $id) { + __typename + ... on Todo { + ... MainFra + } + id + } + } + + fragment MainFra on Todo { + ...Child1 + id + category { + id + } + } + + fragment Child2 on Category { + id + text + } + + fragment Child1 on Todo { + text + category { + id + ... Child2 + } + }` + rsp struct { + Todo struct { + TypeName string `json:"__typename"` + ID, Text string + Category struct { + ID, Text string + } + } + } + ) + + gqlc.MustPost(query, &rsp, client.Var("id", todos[0].ID)) + require.Equal(t, "cat", cat.Text) + require.Equal(t, "cat", rsp.Todo.Category.Text) +} + +func TestRenamedType(t *testing.T) { + ctx := context.Background() + ec := enttest.Open(t, dialect.SQLite, fmt.Sprintf("file:%s?mode=memory&cache=shared&_fk=1", t.Name())) + gqlc := client.New(handler.NewDefaultServer(gen.NewSchema(ec))) + wr := ec.Workspace.Create().SetName("Ariga").SaveX(ctx) + var ( + // language=GraphQL + query = `query Node($id: ID!) { + text: node(id: $id) { + id + ... on Organization { + name + } + } + }` + rsp struct { + Text struct { + ID, Name string + } + } + ) + gqlc.MustPost(query, &rsp, client.Var("id", wr.ID)) + require.Equal(t, "Ariga", rsp.Text.Name) +} + +func TestSatisfiesNodeFragments(t *testing.T) { + ctx := context.Background() + ec := enttest.Open(t, dialect.SQLite, fmt.Sprintf("file:%s?mode=memory&cache=shared&_fk=1", t.Name())) + gqlc := client.New(handler.NewDefaultServer(gen.NewSchema(ec))) + t1 := ec.Todo.Create().SetText("t1").SetStatus(todo.StatusPending).SaveX(ctx) + var ( + // language=GraphQL + query = `query Node($id: ID!) { + todo: node(id: $id) { + id + ...NodeFragment + } + } + fragment NodeFragment on Node { + ... on Todo { + createdAt + status + text + } + }` + rsp struct { + Todo struct { + ID, Text, CreatedAt string + Status todo.Status + } + } + ) + gqlc.MustPost(query, &rsp, client.Var("id", t1.ID)) + require.Equal(t, strconv.Itoa(t1.ID), rsp.Todo.ID) + require.Equal(t, "t1", rsp.Todo.Text) + require.NotEmpty(t, rsp.Todo.Status) + require.NotEmpty(t, rsp.Todo.CreatedAt) + + g1 := ec.Group.Create().SetName("g1").SaveX(ctx) + var ( + // language=GraphQL + query1 = `query Node($id: ID!) { + group: node(id: $id) { + id + ...NamedNodeFragment + } + } + fragment NamedNodeFragment on NamedNode { + ... on Group { + name + } + }` + rsp1 struct { + Group struct { + ID, Name string + } + } + ) + gqlc.MustPost(query1, &rsp1, client.Var("id", g1.ID)) + require.Equal(t, strconv.Itoa(g1.ID), rsp1.Group.ID) + require.Equal(t, "g1", rsp1.Group.Name) +} + +func TestPaginate(t *testing.T) { + ctx := context.Background() + ec := enttest.Open(t, dialect.SQLite, fmt.Sprintf("file:%s?mode=memory&cache=shared&_fk=1", t.Name())) + first := 1 + // Ensure that the pagination query compiles. + _, err := ec.Todo.Query(). + Select(todo.FieldPriority, todo.FieldStatus). + Paginate(ctx, nil, &first, nil, nil) + require.NoError(t, err) +} + +func TestMutualExclusive_UniqueGlobalID_GlobalID(t *testing.T) { + c, err := ent.Open(dialect.SQLite, fmt.Sprintf("file:%s?mode=memory&cache=shared&_fk=1", t.Name())) + require.NoError(t, err) + err = c.Schema.Create(context.Background(), migrate.WithGlobalUniqueID(true)) + require.EqualError(t, err, "sql/schema: universal id and increment start annotation are mutually exclusive") +} + +func TestPrivateFieldSelectionForPagination(t *testing.T) { + ctx := context.Background() + drv, err := sql.Open(dialect.SQLite, fmt.Sprintf("file:%s?mode=memory&cache=shared&_fk=1", t.Name())) + require.NoError(t, err) + rec := &queryRecorder{Driver: drv} + ec := enttest.NewClient(t, enttest.WithOptions(ent.Driver(rec))) + ec.Todo.CreateBulk( + ec.Todo.Create().SetText("t0.1").SetStatus(todo.StatusInProgress), + ec.Todo.Create().SetText("t0.2").SetStatus(todo.StatusInProgress), + ec.Todo.Create().SetText("t0.3").SetStatus(todo.StatusCompleted), + ec.Todo.Create().SetText("t0.4").SetStatus(todo.StatusCompleted), + ec.Todo.Create().SetText("t0.5").SetStatus(todo.StatusCompleted), + ).SaveX(ctx) + + var ( + // language=GraphQL + query = `query { + todosWithJoins(first: 2, orderBy: [{direction: DESC, field: STATUS}]) { + edges { + cursor + node { + text + } + } + } + }` + rsp struct { + TodosWithJoins struct { + Edges []struct { + Cursor string + Node struct { + Text string + } + } + } + } + gqlc = client.New(handler.NewDefaultServer(gen.NewSchema(ec))) + ) + rec.reset() + gqlc.MustPost(query, &rsp) + require.Equal(t, []string{ + "SELECT `todos`.`id`, `todos`.`text`, `todos`.`status` FROM `todos` LEFT JOIN `categories` AS `t1` ON `todos`.`category_id` = `t1`.`id` GROUP BY `todos`.`id` ORDER BY `todos`.`status` DESC, `todos`.`id` LIMIT 3", + }, rec.queries) + + t.Log(rsp.TodosWithJoins) + + var ( + // language=GraphQL + query2 = `query { + todosWithJoins(first: 2, after: "gqFp0wAAAAYAAAACoXaRq0lOX1BST0dSRVNT", orderBy: [{direction: DESC, field: STATUS}]) { + edges { + cursor + node { + text + } + } + } + }` + rsp2 struct { + TodosWithJoins struct { + Edges []struct { + Cursor string + Node struct { + Text string + } + } + } + } + ) + rec.reset() + gqlc.MustPost(query2, &rsp2) + require.Equal(t, []string{ + // BEFORE: "SELECT `todos`.`id`, `todos`.`text`, `todos`.`status` FROM `todos` LEFT JOIN `categories` AS `t1` ON `todos`.`category_id` = `t1`.`id` WHERE `status` < ? OR (`status` = ? AND `id` > ?) GROUP BY `todos`.`id` ORDER BY `todos`.`status` DESC, `todos`.`id` LIMIT 3", + "SELECT `todos`.`id`, `todos`.`text`, `todos`.`status` FROM `todos` LEFT JOIN `categories` AS `t1` ON `todos`.`category_id` = `t1`.`id` WHERE `todos`.`status` < ? OR (`todos`.`status` = ? AND `todos`.`id` > ?) GROUP BY `todos`.`id` ORDER BY `todos`.`status` DESC, `todos`.`id` LIMIT 3", + }, rec.queries) +} diff --git a/entgql/internal/todogotype/ent/ent.go b/entgql/internal/todogotype/ent/ent.go index 58f244e93..bf1ce494f 100644 --- a/entgql/internal/todogotype/ent/ent.go +++ b/entgql/internal/todogotype/ent/ent.go @@ -90,7 +90,7 @@ var ( columnCheck sql.ColumnCheck ) -// columnChecker checks if the column exists in the given table. +// checkColumn checks if the column exists in the given table. func checkColumn(table, column string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ diff --git a/entgql/internal/todogotype/ent/runtime/runtime.go b/entgql/internal/todogotype/ent/runtime/runtime.go index fe250a9ab..a89a1ef4f 100644 --- a/entgql/internal/todogotype/ent/runtime/runtime.go +++ b/entgql/internal/todogotype/ent/runtime/runtime.go @@ -19,6 +19,6 @@ package runtime // The schema-stitching logic is generated in entgo.io/contrib/entgql/internal/todogotype/ent/runtime.go const ( - Version = "v0.13.2-0.20240717044502-34158f2c129b" // Version of ent codegen. - Sum = "h1:kC+uzL8UFWwtXQ+yY0wUdvVUgPlJPGU3Fx1uttM8PJA=" // Sum of ent codegen. + Version = "v0.14.2-0.20250116103911-b91f8daf0e32" // Version of ent codegen. + Sum = "h1:caGPxY54QfxAj6W9Msw3vgOPDved92NoZjHXYiTRFHI=" // Sum of ent codegen. ) diff --git a/entgql/internal/todopulid/ent/ent.go b/entgql/internal/todopulid/ent/ent.go index ffa64b859..a2d56cd5f 100644 --- a/entgql/internal/todopulid/ent/ent.go +++ b/entgql/internal/todopulid/ent/ent.go @@ -89,7 +89,7 @@ var ( columnCheck sql.ColumnCheck ) -// columnChecker checks if the column exists in the given table. +// checkColumn checks if the column exists in the given table. func checkColumn(table, column string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ diff --git a/entgql/internal/todopulid/ent/runtime/runtime.go b/entgql/internal/todopulid/ent/runtime/runtime.go index 267dff534..f989840ab 100644 --- a/entgql/internal/todopulid/ent/runtime/runtime.go +++ b/entgql/internal/todopulid/ent/runtime/runtime.go @@ -19,6 +19,6 @@ package runtime // The schema-stitching logic is generated in entgo.io/contrib/entgql/internal/todopulid/ent/runtime.go const ( - Version = "v0.13.2-0.20240717044502-34158f2c129b" // Version of ent codegen. - Sum = "h1:kC+uzL8UFWwtXQ+yY0wUdvVUgPlJPGU3Fx1uttM8PJA=" // Sum of ent codegen. + Version = "v0.14.2-0.20250116103911-b91f8daf0e32" // Version of ent codegen. + Sum = "h1:caGPxY54QfxAj6W9Msw3vgOPDved92NoZjHXYiTRFHI=" // Sum of ent codegen. ) diff --git a/entgql/internal/todouuid/ent/ent.go b/entgql/internal/todouuid/ent/ent.go index 5f9142969..633ceaf97 100644 --- a/entgql/internal/todouuid/ent/ent.go +++ b/entgql/internal/todouuid/ent/ent.go @@ -89,7 +89,7 @@ var ( columnCheck sql.ColumnCheck ) -// columnChecker checks if the column exists in the given table. +// checkColumn checks if the column exists in the given table. func checkColumn(table, column string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ diff --git a/entgql/internal/todouuid/ent/runtime/runtime.go b/entgql/internal/todouuid/ent/runtime/runtime.go index 8606b79a2..09382a1f6 100644 --- a/entgql/internal/todouuid/ent/runtime/runtime.go +++ b/entgql/internal/todouuid/ent/runtime/runtime.go @@ -19,6 +19,6 @@ package runtime // The schema-stitching logic is generated in entgo.io/contrib/entgql/internal/todouuid/ent/runtime.go const ( - Version = "v0.13.2-0.20240717044502-34158f2c129b" // Version of ent codegen. - Sum = "h1:kC+uzL8UFWwtXQ+yY0wUdvVUgPlJPGU3Fx1uttM8PJA=" // Sum of ent codegen. + Version = "v0.14.2-0.20250116103911-b91f8daf0e32" // Version of ent codegen. + Sum = "h1:caGPxY54QfxAj6W9Msw3vgOPDved92NoZjHXYiTRFHI=" // Sum of ent codegen. ) diff --git a/entgql/template/node.tmpl b/entgql/template/node.tmpl index 1cc67765f..80c88b6e5 100644 --- a/entgql/template/node.tmpl +++ b/entgql/template/node.tmpl @@ -20,8 +20,12 @@ in the LICENSE file in the root directory of this source tree. {{ template "import" $ }} import ( - "sync" - "sync/atomic" + {{- if $.Config.FeatureEnabled "sql/globalid" }} + "encoding/json" + {{- else if $idType.Numeric }} + "sync" + "sync/atomic" + {{- end }} {{- range $n := $.Nodes }} "{{ $.Config.Package }}/{{ $n.Package }}" @@ -29,6 +33,9 @@ import ( {{- with $package := $idType.PkgPath }} "{{ $package }}" {{- end }} + {{- if $.Config.FeatureEnabled "sql/globalid" }} + "{{ $.Config.Package }}/internal" + {{- end }} "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/schema" @@ -91,6 +98,23 @@ type nodeOptions struct { nodeType func(context.Context, {{ $idType }}) (string, error) } +{{- if $.Config.FeatureEnabled "sql/globalid"}} +// Each node has a range of 1<<32 ids. Pre-computing a map of node starting +// value to node type ensures node type resolution happens in O(1) complexity. +var nodeTypes = func () map[int]string { + var is map[string]int + if err := json.Unmarshal([]byte(internal.IncrementStarts), &is); err != nil { + panic(err) + } + // Get a map of range starting value to node type. + m := make(map[int]string, len(is)) + for k, v := range is { + m[v] = k // ent ensures there are no duplicate starting values + } + return m +}() + +{{- end }} func (c *Client) newNodeOpts(opts []NodeOption) *nodeOptions { nopts := &nodeOptions{} for _, opt := range opts { @@ -99,7 +123,15 @@ func (c *Client) newNodeOpts(opts []NodeOption) *nodeOptions { if nopts.nodeType == nil { nopts.nodeType = func(ctx context.Context, id {{ $idType }}) (string, error) { {{- if $idType.Numeric }} - return c.tables.nodeType(ctx, c.driver, id) + {{- if $.Config.FeatureEnabled "sql/globalid"}} + t, ok := nodeTypes[int(id/(1<<32-1))<<32] + if !ok { + return "", fmt.Errorf("cannot resolve table from id %v: %w", id, errNodeInvalidID) + } + return t, nil + {{- else }} + return c.tables.nodeType(ctx, c.driver, id) + {{- end }} {{- else }} return "", fmt.Errorf("cannot resolve noder (%v) without its type", id) {{- end }} @@ -258,7 +290,7 @@ func (c *Client) noders(ctx context.Context, table string, ids []{{ $idType }}) return noders, nil } -{{ if $idType.Numeric }} +{{ if and (not ($.Config.FeatureEnabled "sql/globalid")) $idType.Numeric }} type tables struct { once sync.Once sem *semaphore.Weighted @@ -315,7 +347,7 @@ func (c *Client) noders(ctx context.Context, table string, ids []{{ $idType }}) {{ define "client/fields/additional" }} {{- $idType := gqlIDType (filterNodes $.Nodes (skipMode "type")) $.IDType }} - {{- if $idType.Numeric }} + {{- if and (not ($.Config.FeatureEnabled "sql/globalid")) $idType.Numeric }} // additional fields for node api tables tables {{- end }} diff --git a/entoas/internal/cycle/ent.go b/entoas/internal/cycle/ent.go index 18bce860f..d89c7d944 100644 --- a/entoas/internal/cycle/ent.go +++ b/entoas/internal/cycle/ent.go @@ -69,7 +69,7 @@ var ( columnCheck sql.ColumnCheck ) -// columnChecker checks if the column exists in the given table. +// checkColumn checks if the column exists in the given table. func checkColumn(table, column string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ diff --git a/entoas/internal/cycle/runtime/runtime.go b/entoas/internal/cycle/runtime/runtime.go index cec335618..07166e876 100644 --- a/entoas/internal/cycle/runtime/runtime.go +++ b/entoas/internal/cycle/runtime/runtime.go @@ -5,6 +5,6 @@ package runtime // The schema-stitching logic is generated in entgo.io/contrib/entoas/internal/cycle/runtime.go const ( - Version = "v0.13.2-0.20240717044502-34158f2c129b" // Version of ent codegen. - Sum = "h1:kC+uzL8UFWwtXQ+yY0wUdvVUgPlJPGU3Fx1uttM8PJA=" // Sum of ent codegen. + Version = "v0.14.2-0.20250116103911-b91f8daf0e32" // Version of ent codegen. + Sum = "h1:caGPxY54QfxAj6W9Msw3vgOPDved92NoZjHXYiTRFHI=" // Sum of ent codegen. ) diff --git a/entoas/internal/oastypes/ent.go b/entoas/internal/oastypes/ent.go index 955ba4d89..b2ae0d5e1 100644 --- a/entoas/internal/oastypes/ent.go +++ b/entoas/internal/oastypes/ent.go @@ -69,7 +69,7 @@ var ( columnCheck sql.ColumnCheck ) -// columnChecker checks if the column exists in the given table. +// checkColumn checks if the column exists in the given table. func checkColumn(table, column string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ diff --git a/entoas/internal/oastypes/runtime/runtime.go b/entoas/internal/oastypes/runtime/runtime.go index 3eea14fe9..461473126 100644 --- a/entoas/internal/oastypes/runtime/runtime.go +++ b/entoas/internal/oastypes/runtime/runtime.go @@ -5,6 +5,6 @@ package runtime // The schema-stitching logic is generated in entgo.io/contrib/entoas/internal/oastypes/runtime.go const ( - Version = "v0.13.2-0.20240717044502-34158f2c129b" // Version of ent codegen. - Sum = "h1:kC+uzL8UFWwtXQ+yY0wUdvVUgPlJPGU3Fx1uttM8PJA=" // Sum of ent codegen. + Version = "v0.14.2-0.20250116103911-b91f8daf0e32" // Version of ent codegen. + Sum = "h1:caGPxY54QfxAj6W9Msw3vgOPDved92NoZjHXYiTRFHI=" // Sum of ent codegen. ) diff --git a/entoas/internal/pets/ent.go b/entoas/internal/pets/ent.go index a2485be55..ee68f11d8 100644 --- a/entoas/internal/pets/ent.go +++ b/entoas/internal/pets/ent.go @@ -71,7 +71,7 @@ var ( columnCheck sql.ColumnCheck ) -// columnChecker checks if the column exists in the given table. +// checkColumn checks if the column exists in the given table. func checkColumn(table, column string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ diff --git a/entoas/internal/pets/runtime/runtime.go b/entoas/internal/pets/runtime/runtime.go index 54b71f6d8..dd9d8a100 100644 --- a/entoas/internal/pets/runtime/runtime.go +++ b/entoas/internal/pets/runtime/runtime.go @@ -5,6 +5,6 @@ package runtime // The schema-stitching logic is generated in entgo.io/contrib/entoas/internal/pets/runtime.go const ( - Version = "v0.13.2-0.20240717044502-34158f2c129b" // Version of ent codegen. - Sum = "h1:kC+uzL8UFWwtXQ+yY0wUdvVUgPlJPGU3Fx1uttM8PJA=" // Sum of ent codegen. + Version = "v0.14.2-0.20250116103911-b91f8daf0e32" // Version of ent codegen. + Sum = "h1:caGPxY54QfxAj6W9Msw3vgOPDved92NoZjHXYiTRFHI=" // Sum of ent codegen. ) diff --git a/entoas/internal/simple/ent.go b/entoas/internal/simple/ent.go index 6f5411d33..add2881c3 100644 --- a/entoas/internal/simple/ent.go +++ b/entoas/internal/simple/ent.go @@ -71,7 +71,7 @@ var ( columnCheck sql.ColumnCheck ) -// columnChecker checks if the column exists in the given table. +// checkColumn checks if the column exists in the given table. func checkColumn(table, column string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ diff --git a/entoas/internal/simple/runtime/runtime.go b/entoas/internal/simple/runtime/runtime.go index 6f0013007..eb022571b 100644 --- a/entoas/internal/simple/runtime/runtime.go +++ b/entoas/internal/simple/runtime/runtime.go @@ -5,6 +5,6 @@ package runtime // The schema-stitching logic is generated in entgo.io/contrib/entoas/internal/simple/runtime.go const ( - Version = "v0.13.2-0.20240717044502-34158f2c129b" // Version of ent codegen. - Sum = "h1:kC+uzL8UFWwtXQ+yY0wUdvVUgPlJPGU3Fx1uttM8PJA=" // Sum of ent codegen. + Version = "v0.14.2-0.20250116103911-b91f8daf0e32" // Version of ent codegen. + Sum = "h1:caGPxY54QfxAj6W9Msw3vgOPDved92NoZjHXYiTRFHI=" // Sum of ent codegen. ) diff --git a/entproto/Dockerfile b/entproto/Dockerfile index 62085e9d6..4820f5a42 100644 --- a/entproto/Dockerfile +++ b/entproto/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.22.5 +FROM golang:1.23.4 RUN apt update && apt install unzip RUN curl -LO https://github.com/protocolbuffers/protobuf/releases/download/v3.19.4/protoc-3.19.4-linux-x86_64.zip && \ unzip -o protoc-3.19.4-linux-x86_64.zip -d ./proto && \ diff --git a/entproto/README.md b/entproto/README.md index 23914246b..418234b02 100644 --- a/entproto/README.md +++ b/entproto/README.md @@ -506,7 +506,7 @@ Build the image: ```shell cd entproto -docker build --platform=linux/x86_64 -t entproto-dev . +docker build `--platform=linux/x86_64` -t entproto-dev . cd .. ``` @@ -521,8 +521,8 @@ From within the Docker image, compile and install your current `protoc-gen-entgr binary, regenerate all code and run the tests. ```shell -go install ./cmd/protoc-gen-entgrpc && - go install ./cmd/protoc-gen-ent && +go install -buildvcs=false ./cmd/protoc-gen-entgrpc && + go install -buildvcs=false ./cmd/protoc-gen-ent && go generate ./... && go test ./... ``` diff --git a/entproto/cmd/protoc-gen-ent/internal/todo/ent/ent.go b/entproto/cmd/protoc-gen-ent/internal/todo/ent/ent.go index cdeb7673a..45cfc63bc 100644 --- a/entproto/cmd/protoc-gen-ent/internal/todo/ent/ent.go +++ b/entproto/cmd/protoc-gen-ent/internal/todo/ent/ent.go @@ -72,7 +72,7 @@ var ( columnCheck sql.ColumnCheck ) -// columnChecker checks if the column exists in the given table. +// checkColumn checks if the column exists in the given table. func checkColumn(table, column string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ diff --git a/entproto/cmd/protoc-gen-ent/internal/todo/ent/runtime/runtime.go b/entproto/cmd/protoc-gen-ent/internal/todo/ent/runtime/runtime.go index 4be389266..663d9f9be 100644 --- a/entproto/cmd/protoc-gen-ent/internal/todo/ent/runtime/runtime.go +++ b/entproto/cmd/protoc-gen-ent/internal/todo/ent/runtime/runtime.go @@ -5,6 +5,6 @@ package runtime // The schema-stitching logic is generated in entgo.io/contrib/entproto/cmd/protoc-gen-ent/internal/todo/ent/runtime.go const ( - Version = "v0.13.2-0.20240717044502-34158f2c129b" // Version of ent codegen. - Sum = "h1:kC+uzL8UFWwtXQ+yY0wUdvVUgPlJPGU3Fx1uttM8PJA=" // Sum of ent codegen. + Version = "v0.14.2-0.20250116103911-b91f8daf0e32" // Version of ent codegen. + Sum = "h1:caGPxY54QfxAj6W9Msw3vgOPDved92NoZjHXYiTRFHI=" // Sum of ent codegen. ) diff --git a/entproto/internal/altdir/ent/ent.go b/entproto/internal/altdir/ent/ent.go index 4a33fb986..96d75a60d 100644 --- a/entproto/internal/altdir/ent/ent.go +++ b/entproto/internal/altdir/ent/ent.go @@ -69,7 +69,7 @@ var ( columnCheck sql.ColumnCheck ) -// columnChecker checks if the column exists in the given table. +// checkColumn checks if the column exists in the given table. func checkColumn(table, column string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ diff --git a/entproto/internal/altdir/ent/runtime/runtime.go b/entproto/internal/altdir/ent/runtime/runtime.go index 984f68c09..ce01bee48 100644 --- a/entproto/internal/altdir/ent/runtime/runtime.go +++ b/entproto/internal/altdir/ent/runtime/runtime.go @@ -5,6 +5,6 @@ package runtime // The schema-stitching logic is generated in entgo.io/contrib/entproto/internal/altdir/ent/runtime.go const ( - Version = "v0.13.2-0.20240717044502-34158f2c129b" // Version of ent codegen. - Sum = "h1:kC+uzL8UFWwtXQ+yY0wUdvVUgPlJPGU3Fx1uttM8PJA=" // Sum of ent codegen. + Version = "v0.14.2-0.20250116103911-b91f8daf0e32" // Version of ent codegen. + Sum = "h1:caGPxY54QfxAj6W9Msw3vgOPDved92NoZjHXYiTRFHI=" // Sum of ent codegen. ) diff --git a/entproto/internal/bare/ent/ent.go b/entproto/internal/bare/ent/ent.go index be98c0fec..165324592 100644 --- a/entproto/internal/bare/ent/ent.go +++ b/entproto/internal/bare/ent/ent.go @@ -69,7 +69,7 @@ var ( columnCheck sql.ColumnCheck ) -// columnChecker checks if the column exists in the given table. +// checkColumn checks if the column exists in the given table. func checkColumn(table, column string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ diff --git a/entproto/internal/bare/ent/runtime/runtime.go b/entproto/internal/bare/ent/runtime/runtime.go index 763f141b4..34e66fba9 100644 --- a/entproto/internal/bare/ent/runtime/runtime.go +++ b/entproto/internal/bare/ent/runtime/runtime.go @@ -5,6 +5,6 @@ package runtime // The schema-stitching logic is generated in entgo.io/contrib/entproto/internal/bare/ent/runtime.go const ( - Version = "v0.13.2-0.20240717044502-34158f2c129b" // Version of ent codegen. - Sum = "h1:kC+uzL8UFWwtXQ+yY0wUdvVUgPlJPGU3Fx1uttM8PJA=" // Sum of ent codegen. + Version = "v0.14.2-0.20250116103911-b91f8daf0e32" // Version of ent codegen. + Sum = "h1:caGPxY54QfxAj6W9Msw3vgOPDved92NoZjHXYiTRFHI=" // Sum of ent codegen. ) diff --git a/entproto/internal/entprototest/ent/ent.go b/entproto/internal/entprototest/ent/ent.go index 63b352a9f..f6118d604 100644 --- a/entproto/internal/entprototest/ent/ent.go +++ b/entproto/internal/entprototest/ent/ent.go @@ -92,7 +92,7 @@ var ( columnCheck sql.ColumnCheck ) -// columnChecker checks if the column exists in the given table. +// checkColumn checks if the column exists in the given table. func checkColumn(table, column string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ diff --git a/entproto/internal/entprototest/ent/runtime/runtime.go b/entproto/internal/entprototest/ent/runtime/runtime.go index c15fdabb6..67c95388d 100644 --- a/entproto/internal/entprototest/ent/runtime/runtime.go +++ b/entproto/internal/entprototest/ent/runtime/runtime.go @@ -5,6 +5,6 @@ package runtime // The schema-stitching logic is generated in entgo.io/contrib/entproto/internal/entprototest/ent/runtime.go const ( - Version = "v0.13.2-0.20240717044502-34158f2c129b" // Version of ent codegen. - Sum = "h1:kC+uzL8UFWwtXQ+yY0wUdvVUgPlJPGU3Fx1uttM8PJA=" // Sum of ent codegen. + Version = "v0.14.2-0.20250116103911-b91f8daf0e32" // Version of ent codegen. + Sum = "h1:caGPxY54QfxAj6W9Msw3vgOPDved92NoZjHXYiTRFHI=" // Sum of ent codegen. ) diff --git a/entproto/internal/todo/ent/ent.go b/entproto/internal/todo/ent/ent.go index 5e89e72e2..1f36689a3 100644 --- a/entproto/internal/todo/ent/ent.go +++ b/entproto/internal/todo/ent/ent.go @@ -77,7 +77,7 @@ var ( columnCheck sql.ColumnCheck ) -// columnChecker checks if the column exists in the given table. +// checkColumn checks if the column exists in the given table. func checkColumn(table, column string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ diff --git a/entproto/internal/todo/ent/runtime/runtime.go b/entproto/internal/todo/ent/runtime/runtime.go index 9903c6255..29eff6799 100644 --- a/entproto/internal/todo/ent/runtime/runtime.go +++ b/entproto/internal/todo/ent/runtime/runtime.go @@ -5,6 +5,6 @@ package runtime // The schema-stitching logic is generated in entgo.io/contrib/entproto/internal/todo/ent/runtime.go const ( - Version = "v0.13.2-0.20240717044502-34158f2c129b" // Version of ent codegen. - Sum = "h1:kC+uzL8UFWwtXQ+yY0wUdvVUgPlJPGU3Fx1uttM8PJA=" // Sum of ent codegen. + Version = "v0.14.2-0.20250116103911-b91f8daf0e32" // Version of ent codegen. + Sum = "h1:caGPxY54QfxAj6W9Msw3vgOPDved92NoZjHXYiTRFHI=" // Sum of ent codegen. ) diff --git a/go.mod b/go.mod index 1be883947..955446e17 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module entgo.io/contrib go 1.23.4 require ( - entgo.io/ent v0.13.2-0.20240717044502-34158f2c129b + entgo.io/ent v0.14.2-0.20250116103911-b91f8daf0e32 github.com/99designs/gqlgen v0.17.63 github.com/AlekSi/pointer v1.1.0 github.com/alecthomas/kong v0.7.0 @@ -32,7 +32,7 @@ require ( require github.com/golang/protobuf v1.5.4 // indirect require ( - ariga.io/atlas v0.25.1-0.20240717145915-af51d3945208 // indirect + ariga.io/atlas v0.27.1-0.20240912191503-92195304dbe1 // indirect github.com/agext/levenshtein v1.2.1 // indirect github.com/agnivade/levenshtein v1.2.0 // indirect github.com/apparentlymart/go-textseg/v13 v13.0.0 // indirect diff --git a/go.sum b/go.sum index a5bdfe40f..8d7fa3678 100644 --- a/go.sum +++ b/go.sum @@ -1,8 +1,8 @@ -ariga.io/atlas v0.25.1-0.20240717145915-af51d3945208 h1:ixs1c/fAXGS3mTdalyKQrtvfkFjgChih/unX66YTzYk= -ariga.io/atlas v0.25.1-0.20240717145915-af51d3945208/go.mod h1:KPLc7Zj+nzoXfWshrcY1RwlOh94dsATQEy4UPrF2RkM= +ariga.io/atlas v0.27.1-0.20240912191503-92195304dbe1 h1:tqUmxmE7r2qqWmgczyNZNOyhzXLqmdUpRhVSuvCUqTU= +ariga.io/atlas v0.27.1-0.20240912191503-92195304dbe1/go.mod h1:cpxrs2J9HTrjMrfNKFmUpONY9L0vzAHZ1pY++nTtVw0= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= -entgo.io/ent v0.13.2-0.20240717044502-34158f2c129b h1:kC+uzL8UFWwtXQ+yY0wUdvVUgPlJPGU3Fx1uttM8PJA= -entgo.io/ent v0.13.2-0.20240717044502-34158f2c129b/go.mod h1:qCEmo+biw3ccBn9OyL4ZK5dfpwg++l1Gxwac5B1206A= +entgo.io/ent v0.14.2-0.20250116103911-b91f8daf0e32 h1:caGPxY54QfxAj6W9Msw3vgOPDved92NoZjHXYiTRFHI= +entgo.io/ent v0.14.2-0.20250116103911-b91f8daf0e32/go.mod h1:nPwpHTcyAjBMt+hT6q7Y/SdF41e6IJudQPbTj1P5nYY= github.com/99designs/gqlgen v0.17.63 h1:HCdaYDPd9HqUXRchEvmE3EFzELRwLlaJ8DBuyC8Cqto= github.com/99designs/gqlgen v0.17.63/go.mod h1:sVCM2iwIZisJjTI/DEC3fpH+HFgxY1496ZJ+jbT9IjA= github.com/AlekSi/pointer v1.1.0 h1:SSDMPcXD9jSl8FPy9cRzoRaMJtm9g9ggGTxecRUbQoI= diff --git a/schemast/internal/loadtest/ent/ent.go b/schemast/internal/loadtest/ent/ent.go index 59c40df2f..874d810cc 100644 --- a/schemast/internal/loadtest/ent/ent.go +++ b/schemast/internal/loadtest/ent/ent.go @@ -69,7 +69,7 @@ var ( columnCheck sql.ColumnCheck ) -// columnChecker checks if the column exists in the given table. +// checkColumn checks if the column exists in the given table. func checkColumn(table, column string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ diff --git a/schemast/internal/loadtest/ent/runtime/runtime.go b/schemast/internal/loadtest/ent/runtime/runtime.go index bd1127dc1..501ac8938 100644 --- a/schemast/internal/loadtest/ent/runtime/runtime.go +++ b/schemast/internal/loadtest/ent/runtime/runtime.go @@ -5,6 +5,6 @@ package runtime // The schema-stitching logic is generated in entgo.io/contrib/schemast/internal/loadtest/ent/runtime.go const ( - Version = "v0.13.2-0.20240717044502-34158f2c129b" // Version of ent codegen. - Sum = "h1:kC+uzL8UFWwtXQ+yY0wUdvVUgPlJPGU3Fx1uttM8PJA=" // Sum of ent codegen. + Version = "v0.14.2-0.20250116103911-b91f8daf0e32" // Version of ent codegen. + Sum = "h1:caGPxY54QfxAj6W9Msw3vgOPDved92NoZjHXYiTRFHI=" // Sum of ent codegen. ) diff --git a/schemast/internal/mutatetest/ent/ent.go b/schemast/internal/mutatetest/ent/ent.go index a927a0f45..e8b434c1c 100644 --- a/schemast/internal/mutatetest/ent/ent.go +++ b/schemast/internal/mutatetest/ent/ent.go @@ -73,7 +73,7 @@ var ( columnCheck sql.ColumnCheck ) -// columnChecker checks if the column exists in the given table. +// checkColumn checks if the column exists in the given table. func checkColumn(table, column string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ diff --git a/schemast/internal/mutatetest/ent/runtime/runtime.go b/schemast/internal/mutatetest/ent/runtime/runtime.go index 644337289..3675610e7 100644 --- a/schemast/internal/mutatetest/ent/runtime/runtime.go +++ b/schemast/internal/mutatetest/ent/runtime/runtime.go @@ -5,6 +5,6 @@ package runtime // The schema-stitching logic is generated in entgo.io/contrib/schemast/internal/mutatetest/ent/runtime.go const ( - Version = "v0.13.2-0.20240717044502-34158f2c129b" // Version of ent codegen. - Sum = "h1:kC+uzL8UFWwtXQ+yY0wUdvVUgPlJPGU3Fx1uttM8PJA=" // Sum of ent codegen. + Version = "v0.14.2-0.20250116103911-b91f8daf0e32" // Version of ent codegen. + Sum = "h1:caGPxY54QfxAj6W9Msw3vgOPDved92NoZjHXYiTRFHI=" // Sum of ent codegen. ) diff --git a/schemast/internal/printtest/ent/ent.go b/schemast/internal/printtest/ent/ent.go index 1b7524452..43c2bc6a7 100644 --- a/schemast/internal/printtest/ent/ent.go +++ b/schemast/internal/printtest/ent/ent.go @@ -70,7 +70,7 @@ var ( columnCheck sql.ColumnCheck ) -// columnChecker checks if the column exists in the given table. +// checkColumn checks if the column exists in the given table. func checkColumn(table, column string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ diff --git a/schemast/internal/printtest/ent/runtime/runtime.go b/schemast/internal/printtest/ent/runtime/runtime.go index b9613e488..c13d4a08d 100644 --- a/schemast/internal/printtest/ent/runtime/runtime.go +++ b/schemast/internal/printtest/ent/runtime/runtime.go @@ -5,6 +5,6 @@ package runtime // The schema-stitching logic is generated in entgo.io/contrib/schemast/internal/printtest/ent/runtime.go const ( - Version = "v0.13.2-0.20240717044502-34158f2c129b" // Version of ent codegen. - Sum = "h1:kC+uzL8UFWwtXQ+yY0wUdvVUgPlJPGU3Fx1uttM8PJA=" // Sum of ent codegen. + Version = "v0.14.2-0.20250116103911-b91f8daf0e32" // Version of ent codegen. + Sum = "h1:caGPxY54QfxAj6W9Msw3vgOPDved92NoZjHXYiTRFHI=" // Sum of ent codegen. )