From a56fa723358504b6a141bd570672e039eee53f00 Mon Sep 17 00:00:00 2001 From: jensholdgaard Date: Sat, 19 Jul 2025 15:55:42 +0200 Subject: [PATCH] feat(otel): add OpenTelemetry tracing infrastructure - Add OpenTelemetry traces attributes and events for Dex operations - Implement instrumentation scope utilities for consistent tracing - Add OTEL configuration and initialization in cmd/dex - Include comprehensive test coverage for OTEL components This provides the foundational tracing infrastructure to monitor and debug authentication flows, token operations, and connector interactions. Signed-off-by: Jensholdgaard Signed-off-by: jehope # Conflicts: # examples/go.sum # go.mod # go.sum # server/deviceflowhandlers.go --- Makefile | 2 +- api/api.pb.go | 256 +-- api/v2/api.pb.go | 429 ++-- cmd/dex/config.go | 34 +- cmd/dex/config_test.go | 25 +- cmd/dex/logger.go | 32 +- cmd/dex/logger_test.go | 29 + cmd/dex/serve.go | 165 +- cmd/dex/serve_test.go | 90 +- connector/authproxy/authproxy.go | 3 + connector/github/github.go | 26 +- connector/microsoft/microsoft.go | 6 +- connector/mock/connectortest.go | 13 +- connector/oauth/oauth.go | 5 +- connector/oidc/oidc.go | 26 +- examples/go.mod | 23 +- examples/go.sum | 53 +- examples/grpc-client/client.go | 76 +- go.mod | 72 +- go.sum | 163 +- pkg/otel/otel.go | 61 + pkg/otel/otel_test.go | 118 + pkg/otel/traces/attributes/dex_attributes.go | 1 + pkg/otel/traces/events/dex_events.go | 1 + pkg/otel/traces/traces.go | 74 + pkg/otel/traces/traces_test.go | 194 ++ server/api.go | 69 +- server/approvalhandlers.go | 66 + server/approvalhandlers_test.go | 280 +++ server/authcodehandlers.go | 71 + server/authorizationhandlers.go | 75 + server/connectorcallbackhandlers.go | 111 + server/connectorloginhandlers.go | 135 ++ server/deviceflowhandlers.go | 94 +- server/deviceflowhandlers_test.go | 2 +- server/discoveryhandlers.go | 27 + server/discoveryhandlers_test.go | 82 + server/handlers.go | 1023 +-------- server/handlers_test.go | 176 -- server/internal/codec_test.go | 103 + server/internal/types.pb.go | 29 +- ...ionhandler.go => introspectionhandlers.go} | 21 +- ..._test.go => introspectionhandlers_test.go} | 0 server/oauth2.go | 23 +- server/passwordgranthandlers.go | 244 +++ server/passwordloginhandlers.go | 115 + server/publickeyshandlers.go | 53 + server/refreshhandlers.go | 51 +- server/rotation.go | 21 +- server/rotation_test.go | 2 +- server/server.go | 83 +- server/server_test.go | 6 +- server/tokenexchangehandlers.go | 98 + server/tokenhandlers.go | 46 + server/tokenhandlers_test.go | 120 ++ server/userinfohandlers.go | 41 + server/userinfohandlers_test.go | 324 +++ storage/ent/db/authcode.go | 86 +- storage/ent/db/authcode_create.go | 282 +-- storage/ent/db/authcode_delete.go | 38 +- storage/ent/db/authcode_query.go | 272 +-- storage/ent/db/authcode_update.go | 640 +++--- storage/ent/db/authrequest.go | 106 +- storage/ent/db/authrequest_create.go | 316 +-- storage/ent/db/authrequest_delete.go | 38 +- storage/ent/db/authrequest_query.go | 272 +-- storage/ent/db/authrequest_update.go | 766 +++---- storage/ent/db/client.go | 80 +- storage/ent/db/connector.go | 42 +- storage/ent/db/connector_create.go | 128 +- storage/ent/db/connector_delete.go | 38 +- storage/ent/db/connector_query.go | 272 +-- storage/ent/db/connector_update.go | 212 +- storage/ent/db/devicerequest.go | 50 +- storage/ent/db/devicerequest_create.go | 138 +- storage/ent/db/devicerequest_delete.go | 38 +- storage/ent/db/devicerequest_query.go | 272 +-- storage/ent/db/devicerequest_update.go | 320 +-- storage/ent/db/devicetoken.go | 58 +- storage/ent/db/devicetoken_create.go | 182 +- storage/ent/db/devicetoken_delete.go | 38 +- storage/ent/db/devicetoken_query.go | 272 +-- storage/ent/db/devicetoken_update.go | 380 ++-- storage/ent/db/ent.go | 4 +- storage/ent/db/keys.go | 42 +- storage/ent/db/keys_create.go | 124 +- storage/ent/db/keys_delete.go | 38 +- storage/ent/db/keys_query.go | 272 +-- storage/ent/db/keys_update.go | 214 +- storage/ent/db/oauth2client.go | 50 +- storage/ent/db/oauth2client_create.go | 144 +- storage/ent/db/oauth2client_delete.go | 38 +- storage/ent/db/oauth2client_query.go | 272 +-- storage/ent/db/oauth2client_update.go | 336 +-- storage/ent/db/offlinesession.go | 42 +- storage/ent/db/offlinesession_create.go | 126 +- storage/ent/db/offlinesession_delete.go | 38 +- storage/ent/db/offlinesession_query.go | 272 +-- storage/ent/db/offlinesession_update.go | 212 +- storage/ent/db/password.go | 42 +- storage/ent/db/password_create.go | 120 +- storage/ent/db/password_delete.go | 38 +- storage/ent/db/password_query.go | 272 +-- storage/ent/db/password_update.go | 216 +- storage/ent/db/refreshtoken.go | 86 +- storage/ent/db/refreshtoken_create.go | 304 +-- storage/ent/db/refreshtoken_delete.go | 38 +- storage/ent/db/refreshtoken_query.go | 272 +-- storage/ent/db/refreshtoken_update.go | 636 +++--- storage/ent/db/runtime/runtime.go | 3 +- storage/ent/mysql.go | 14 +- storage/ent/postgres.go | 13 +- storage/ent/sqlite.go | 8 +- storage/health_test.go | 93 + storage/sql/config.go | 117 +- storage/sql/crud.go | 109 +- storage/sql/crud_test.go | 192 ++ storage/sql/sql.go | 82 + storage/static.go | 7 + storage/static_test.go | 1892 +++++++++++++++++ storage/storage_test.go | 82 + 121 files changed, 10892 insertions(+), 6872 deletions(-) create mode 100644 cmd/dex/logger_test.go create mode 100644 pkg/otel/otel.go create mode 100644 pkg/otel/otel_test.go create mode 100644 pkg/otel/traces/attributes/dex_attributes.go create mode 100644 pkg/otel/traces/events/dex_events.go create mode 100644 pkg/otel/traces/traces.go create mode 100644 pkg/otel/traces/traces_test.go create mode 100644 server/approvalhandlers.go create mode 100644 server/approvalhandlers_test.go create mode 100644 server/authcodehandlers.go create mode 100644 server/authorizationhandlers.go create mode 100644 server/connectorcallbackhandlers.go create mode 100644 server/connectorloginhandlers.go create mode 100644 server/discoveryhandlers.go create mode 100644 server/discoveryhandlers_test.go create mode 100644 server/internal/codec_test.go rename server/{introspectionhandler.go => introspectionhandlers.go} (93%) rename server/{introspectionhandler_test.go => introspectionhandlers_test.go} (100%) create mode 100644 server/passwordgranthandlers.go create mode 100644 server/passwordloginhandlers.go create mode 100644 server/publickeyshandlers.go create mode 100644 server/tokenexchangehandlers.go create mode 100644 server/tokenhandlers.go create mode 100644 server/tokenhandlers_test.go create mode 100644 server/userinfohandlers.go create mode 100644 server/userinfohandlers_test.go create mode 100644 storage/health_test.go create mode 100644 storage/static_test.go create mode 100644 storage/storage_test.go diff --git a/Makefile b/Makefile index 349dbc578c..776579674c 100644 --- a/Makefile +++ b/Makefile @@ -21,7 +21,7 @@ GOLANGCI_VERSION = 1.64.5 GOTESTSUM_VERSION ?= 1.12.0 PROTOC_VERSION = 29.3 -PROTOC_GEN_GO_VERSION = 1.36.5 +PROTOC_GEN_GO_VERSION = 1.36.6 PROTOC_GEN_GO_GRPC_VERSION = 1.5.1 KIND_VERSION = 0.22.0 diff --git a/api/api.pb.go b/api/api.pb.go index 702d3758fa..4cbc99d2df 100644 --- a/api/api.pb.go +++ b/api/api.pb.go @@ -1,6 +1,6 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.36.5 +// protoc-gen-go v1.36.6 // protoc v5.29.3 // source: api/api.proto @@ -1324,170 +1324,96 @@ func (x *VerifyPasswordResp) GetNotFound() bool { var File_api_api_proto protoreflect.FileDescriptor -var file_api_api_proto_rawDesc = string([]byte{ - 0x0a, 0x0d, 0x61, 0x70, 0x69, 0x2f, 0x61, 0x70, 0x69, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, - 0x03, 0x61, 0x70, 0x69, 0x22, 0xc1, 0x01, 0x0a, 0x06, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x12, - 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, - 0x16, 0x0a, 0x06, 0x73, 0x65, 0x63, 0x72, 0x65, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x06, 0x73, 0x65, 0x63, 0x72, 0x65, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x72, 0x65, 0x64, 0x69, 0x72, - 0x65, 0x63, 0x74, 0x5f, 0x75, 0x72, 0x69, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0c, - 0x72, 0x65, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x55, 0x72, 0x69, 0x73, 0x12, 0x23, 0x0a, 0x0d, - 0x74, 0x72, 0x75, 0x73, 0x74, 0x65, 0x64, 0x5f, 0x70, 0x65, 0x65, 0x72, 0x73, 0x18, 0x04, 0x20, - 0x03, 0x28, 0x09, 0x52, 0x0c, 0x74, 0x72, 0x75, 0x73, 0x74, 0x65, 0x64, 0x50, 0x65, 0x65, 0x72, - 0x73, 0x12, 0x16, 0x0a, 0x06, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x18, 0x05, 0x20, 0x01, 0x28, - 0x08, 0x52, 0x06, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, - 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x19, 0x0a, - 0x08, 0x6c, 0x6f, 0x67, 0x6f, 0x5f, 0x75, 0x72, 0x6c, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x07, 0x6c, 0x6f, 0x67, 0x6f, 0x55, 0x72, 0x6c, 0x22, 0x36, 0x0a, 0x0f, 0x43, 0x72, 0x65, 0x61, - 0x74, 0x65, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x71, 0x12, 0x23, 0x0a, 0x06, 0x63, - 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0b, 0x2e, 0x61, 0x70, - 0x69, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x52, 0x06, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, - 0x22, 0x5e, 0x0a, 0x10, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, - 0x52, 0x65, 0x73, 0x70, 0x12, 0x25, 0x0a, 0x0e, 0x61, 0x6c, 0x72, 0x65, 0x61, 0x64, 0x79, 0x5f, - 0x65, 0x78, 0x69, 0x73, 0x74, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0d, 0x61, 0x6c, - 0x72, 0x65, 0x61, 0x64, 0x79, 0x45, 0x78, 0x69, 0x73, 0x74, 0x73, 0x12, 0x23, 0x0a, 0x06, 0x63, - 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0b, 0x2e, 0x61, 0x70, - 0x69, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x52, 0x06, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, - 0x22, 0x21, 0x0a, 0x0f, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, - 0x52, 0x65, 0x71, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x02, 0x69, 0x64, 0x22, 0x2f, 0x0a, 0x10, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x43, 0x6c, 0x69, - 0x65, 0x6e, 0x74, 0x52, 0x65, 0x73, 0x70, 0x12, 0x1b, 0x0a, 0x09, 0x6e, 0x6f, 0x74, 0x5f, 0x66, - 0x6f, 0x75, 0x6e, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, 0x6e, 0x6f, 0x74, 0x46, - 0x6f, 0x75, 0x6e, 0x64, 0x22, 0x9a, 0x01, 0x0a, 0x0f, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x43, - 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x71, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, - 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x23, 0x0a, 0x0d, 0x72, 0x65, 0x64, 0x69, - 0x72, 0x65, 0x63, 0x74, 0x5f, 0x75, 0x72, 0x69, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, - 0x0c, 0x72, 0x65, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x55, 0x72, 0x69, 0x73, 0x12, 0x23, 0x0a, - 0x0d, 0x74, 0x72, 0x75, 0x73, 0x74, 0x65, 0x64, 0x5f, 0x70, 0x65, 0x65, 0x72, 0x73, 0x18, 0x03, - 0x20, 0x03, 0x28, 0x09, 0x52, 0x0c, 0x74, 0x72, 0x75, 0x73, 0x74, 0x65, 0x64, 0x50, 0x65, 0x65, - 0x72, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, - 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x19, 0x0a, 0x08, 0x6c, 0x6f, 0x67, 0x6f, 0x5f, 0x75, - 0x72, 0x6c, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6c, 0x6f, 0x67, 0x6f, 0x55, 0x72, - 0x6c, 0x22, 0x2f, 0x0a, 0x10, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x43, 0x6c, 0x69, 0x65, 0x6e, - 0x74, 0x52, 0x65, 0x73, 0x70, 0x12, 0x1b, 0x0a, 0x09, 0x6e, 0x6f, 0x74, 0x5f, 0x66, 0x6f, 0x75, - 0x6e, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, 0x6e, 0x6f, 0x74, 0x46, 0x6f, 0x75, - 0x6e, 0x64, 0x22, 0x69, 0x0a, 0x08, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x12, 0x14, - 0x0a, 0x05, 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x65, - 0x6d, 0x61, 0x69, 0x6c, 0x12, 0x12, 0x0a, 0x04, 0x68, 0x61, 0x73, 0x68, 0x18, 0x02, 0x20, 0x01, - 0x28, 0x0c, 0x52, 0x04, 0x68, 0x61, 0x73, 0x68, 0x12, 0x1a, 0x0a, 0x08, 0x75, 0x73, 0x65, 0x72, - 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x75, 0x73, 0x65, 0x72, - 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x17, 0x0a, 0x07, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, - 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x75, 0x73, 0x65, 0x72, 0x49, 0x64, 0x22, 0x3e, 0x0a, - 0x11, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, - 0x65, 0x71, 0x12, 0x29, 0x0a, 0x08, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x18, 0x01, - 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0d, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x50, 0x61, 0x73, 0x73, 0x77, - 0x6f, 0x72, 0x64, 0x52, 0x08, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x22, 0x3b, 0x0a, - 0x12, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, - 0x65, 0x73, 0x70, 0x12, 0x25, 0x0a, 0x0e, 0x61, 0x6c, 0x72, 0x65, 0x61, 0x64, 0x79, 0x5f, 0x65, - 0x78, 0x69, 0x73, 0x74, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0d, 0x61, 0x6c, 0x72, - 0x65, 0x61, 0x64, 0x79, 0x45, 0x78, 0x69, 0x73, 0x74, 0x73, 0x22, 0x67, 0x0a, 0x11, 0x55, 0x70, - 0x64, 0x61, 0x74, 0x65, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, 0x71, 0x12, - 0x14, 0x0a, 0x05, 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, - 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x12, 0x19, 0x0a, 0x08, 0x6e, 0x65, 0x77, 0x5f, 0x68, 0x61, 0x73, - 0x68, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x07, 0x6e, 0x65, 0x77, 0x48, 0x61, 0x73, 0x68, - 0x12, 0x21, 0x0a, 0x0c, 0x6e, 0x65, 0x77, 0x5f, 0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, - 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x6e, 0x65, 0x77, 0x55, 0x73, 0x65, 0x72, 0x6e, - 0x61, 0x6d, 0x65, 0x22, 0x31, 0x0a, 0x12, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x50, 0x61, 0x73, - 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, 0x73, 0x70, 0x12, 0x1b, 0x0a, 0x09, 0x6e, 0x6f, 0x74, - 0x5f, 0x66, 0x6f, 0x75, 0x6e, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, 0x6e, 0x6f, - 0x74, 0x46, 0x6f, 0x75, 0x6e, 0x64, 0x22, 0x29, 0x0a, 0x11, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, - 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, 0x71, 0x12, 0x14, 0x0a, 0x05, 0x65, - 0x6d, 0x61, 0x69, 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x65, 0x6d, 0x61, 0x69, - 0x6c, 0x22, 0x31, 0x0a, 0x12, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x50, 0x61, 0x73, 0x73, 0x77, - 0x6f, 0x72, 0x64, 0x52, 0x65, 0x73, 0x70, 0x12, 0x1b, 0x0a, 0x09, 0x6e, 0x6f, 0x74, 0x5f, 0x66, - 0x6f, 0x75, 0x6e, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, 0x6e, 0x6f, 0x74, 0x46, - 0x6f, 0x75, 0x6e, 0x64, 0x22, 0x11, 0x0a, 0x0f, 0x4c, 0x69, 0x73, 0x74, 0x50, 0x61, 0x73, 0x73, - 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, 0x71, 0x22, 0x3f, 0x0a, 0x10, 0x4c, 0x69, 0x73, 0x74, 0x50, - 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, 0x73, 0x70, 0x12, 0x2b, 0x0a, 0x09, 0x70, - 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0d, - 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, 0x09, 0x70, - 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x73, 0x22, 0x0c, 0x0a, 0x0a, 0x56, 0x65, 0x72, 0x73, - 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x22, 0x37, 0x0a, 0x0b, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, - 0x6e, 0x52, 0x65, 0x73, 0x70, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x18, - 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x12, 0x10, 0x0a, - 0x03, 0x61, 0x70, 0x69, 0x18, 0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x03, 0x61, 0x70, 0x69, 0x22, - 0x7a, 0x0a, 0x0f, 0x52, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x52, - 0x65, 0x66, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, - 0x69, 0x64, 0x12, 0x1b, 0x0a, 0x09, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x69, 0x64, 0x18, - 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x49, 0x64, 0x12, - 0x1d, 0x0a, 0x0a, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x5f, 0x61, 0x74, 0x18, 0x05, 0x20, - 0x01, 0x28, 0x03, 0x52, 0x09, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x41, 0x74, 0x12, 0x1b, - 0x0a, 0x09, 0x6c, 0x61, 0x73, 0x74, 0x5f, 0x75, 0x73, 0x65, 0x64, 0x18, 0x06, 0x20, 0x01, 0x28, - 0x03, 0x52, 0x08, 0x6c, 0x61, 0x73, 0x74, 0x55, 0x73, 0x65, 0x64, 0x22, 0x29, 0x0a, 0x0e, 0x4c, - 0x69, 0x73, 0x74, 0x52, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x52, 0x65, 0x71, 0x12, 0x17, 0x0a, - 0x07, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, - 0x75, 0x73, 0x65, 0x72, 0x49, 0x64, 0x22, 0x4e, 0x0a, 0x0f, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, - 0x66, 0x72, 0x65, 0x73, 0x68, 0x52, 0x65, 0x73, 0x70, 0x12, 0x3b, 0x0a, 0x0e, 0x72, 0x65, 0x66, - 0x72, 0x65, 0x73, 0x68, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, - 0x0b, 0x32, 0x14, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x52, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x54, - 0x6f, 0x6b, 0x65, 0x6e, 0x52, 0x65, 0x66, 0x52, 0x0d, 0x72, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, - 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x73, 0x22, 0x48, 0x0a, 0x10, 0x52, 0x65, 0x76, 0x6f, 0x6b, 0x65, - 0x52, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x52, 0x65, 0x71, 0x12, 0x17, 0x0a, 0x07, 0x75, 0x73, - 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x75, 0x73, 0x65, - 0x72, 0x49, 0x64, 0x12, 0x1b, 0x0a, 0x09, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x69, 0x64, - 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x49, 0x64, - 0x22, 0x30, 0x0a, 0x11, 0x52, 0x65, 0x76, 0x6f, 0x6b, 0x65, 0x52, 0x65, 0x66, 0x72, 0x65, 0x73, - 0x68, 0x52, 0x65, 0x73, 0x70, 0x12, 0x1b, 0x0a, 0x09, 0x6e, 0x6f, 0x74, 0x5f, 0x66, 0x6f, 0x75, - 0x6e, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, 0x6e, 0x6f, 0x74, 0x46, 0x6f, 0x75, - 0x6e, 0x64, 0x22, 0x45, 0x0a, 0x11, 0x56, 0x65, 0x72, 0x69, 0x66, 0x79, 0x50, 0x61, 0x73, 0x73, - 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, 0x71, 0x12, 0x14, 0x0a, 0x05, 0x65, 0x6d, 0x61, 0x69, 0x6c, - 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x12, 0x1a, 0x0a, - 0x08, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x08, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x22, 0x4d, 0x0a, 0x12, 0x56, 0x65, 0x72, - 0x69, 0x66, 0x79, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, 0x73, 0x70, 0x12, - 0x1a, 0x0a, 0x08, 0x76, 0x65, 0x72, 0x69, 0x66, 0x69, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, - 0x08, 0x52, 0x08, 0x76, 0x65, 0x72, 0x69, 0x66, 0x69, 0x65, 0x64, 0x12, 0x1b, 0x0a, 0x09, 0x6e, - 0x6f, 0x74, 0x5f, 0x66, 0x6f, 0x75, 0x6e, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, - 0x6e, 0x6f, 0x74, 0x46, 0x6f, 0x75, 0x6e, 0x64, 0x32, 0xc7, 0x05, 0x0a, 0x03, 0x44, 0x65, 0x78, - 0x12, 0x3d, 0x0a, 0x0c, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, - 0x12, 0x14, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x43, 0x6c, 0x69, - 0x65, 0x6e, 0x74, 0x52, 0x65, 0x71, 0x1a, 0x15, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, 0x72, 0x65, - 0x61, 0x74, 0x65, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x73, 0x70, 0x22, 0x00, 0x12, - 0x3d, 0x0a, 0x0c, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x12, - 0x14, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x43, 0x6c, 0x69, 0x65, - 0x6e, 0x74, 0x52, 0x65, 0x71, 0x1a, 0x15, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x55, 0x70, 0x64, 0x61, - 0x74, 0x65, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x73, 0x70, 0x22, 0x00, 0x12, 0x3d, - 0x0a, 0x0c, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x12, 0x14, - 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x43, 0x6c, 0x69, 0x65, 0x6e, - 0x74, 0x52, 0x65, 0x71, 0x1a, 0x15, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x44, 0x65, 0x6c, 0x65, 0x74, - 0x65, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x73, 0x70, 0x22, 0x00, 0x12, 0x43, 0x0a, - 0x0e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x12, - 0x16, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x50, 0x61, 0x73, 0x73, - 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, 0x71, 0x1a, 0x17, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, 0x72, - 0x65, 0x61, 0x74, 0x65, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, 0x73, 0x70, - 0x22, 0x00, 0x12, 0x43, 0x0a, 0x0e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x50, 0x61, 0x73, 0x73, - 0x77, 0x6f, 0x72, 0x64, 0x12, 0x16, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, - 0x65, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, 0x71, 0x1a, 0x17, 0x2e, 0x61, - 0x70, 0x69, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, - 0x64, 0x52, 0x65, 0x73, 0x70, 0x22, 0x00, 0x12, 0x43, 0x0a, 0x0e, 0x44, 0x65, 0x6c, 0x65, 0x74, - 0x65, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x12, 0x16, 0x2e, 0x61, 0x70, 0x69, 0x2e, - 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, - 0x71, 0x1a, 0x17, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x50, 0x61, - 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, 0x73, 0x70, 0x22, 0x00, 0x12, 0x3e, 0x0a, 0x0d, - 0x4c, 0x69, 0x73, 0x74, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x73, 0x12, 0x14, 0x2e, - 0x61, 0x70, 0x69, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, - 0x52, 0x65, 0x71, 0x1a, 0x15, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x50, 0x61, - 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, 0x73, 0x70, 0x22, 0x00, 0x12, 0x31, 0x0a, 0x0a, - 0x47, 0x65, 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x0f, 0x2e, 0x61, 0x70, 0x69, - 0x2e, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x1a, 0x10, 0x2e, 0x61, 0x70, - 0x69, 0x2e, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x22, 0x00, 0x12, - 0x3a, 0x0a, 0x0b, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x12, 0x13, - 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, - 0x52, 0x65, 0x71, 0x1a, 0x14, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, - 0x66, 0x72, 0x65, 0x73, 0x68, 0x52, 0x65, 0x73, 0x70, 0x22, 0x00, 0x12, 0x40, 0x0a, 0x0d, 0x52, - 0x65, 0x76, 0x6f, 0x6b, 0x65, 0x52, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x12, 0x15, 0x2e, 0x61, - 0x70, 0x69, 0x2e, 0x52, 0x65, 0x76, 0x6f, 0x6b, 0x65, 0x52, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, - 0x52, 0x65, 0x71, 0x1a, 0x16, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x52, 0x65, 0x76, 0x6f, 0x6b, 0x65, - 0x52, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x52, 0x65, 0x73, 0x70, 0x22, 0x00, 0x12, 0x43, 0x0a, - 0x0e, 0x56, 0x65, 0x72, 0x69, 0x66, 0x79, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x12, - 0x16, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x56, 0x65, 0x72, 0x69, 0x66, 0x79, 0x50, 0x61, 0x73, 0x73, - 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, 0x71, 0x1a, 0x17, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x56, 0x65, - 0x72, 0x69, 0x66, 0x79, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, 0x73, 0x70, - 0x22, 0x00, 0x42, 0x2f, 0x0a, 0x12, 0x63, 0x6f, 0x6d, 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x6f, 0x73, - 0x2e, 0x64, 0x65, 0x78, 0x2e, 0x61, 0x70, 0x69, 0x5a, 0x19, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, - 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x64, 0x65, 0x78, 0x69, 0x64, 0x70, 0x2f, 0x64, 0x65, 0x78, 0x2f, - 0x61, 0x70, 0x69, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -}) +const file_api_api_proto_rawDesc = "" + + "\n" + + "\rapi/api.proto\x12\x03api\"\xc1\x01\n" + + "\x06Client\x12\x0e\n" + + "\x02id\x18\x01 \x01(\tR\x02id\x12\x16\n" + + "\x06secret\x18\x02 \x01(\tR\x06secret\x12#\n" + + "\rredirect_uris\x18\x03 \x03(\tR\fredirectUris\x12#\n" + + "\rtrusted_peers\x18\x04 \x03(\tR\ftrustedPeers\x12\x16\n" + + "\x06public\x18\x05 \x01(\bR\x06public\x12\x12\n" + + "\x04name\x18\x06 \x01(\tR\x04name\x12\x19\n" + + "\blogo_url\x18\a \x01(\tR\alogoUrl\"6\n" + + "\x0fCreateClientReq\x12#\n" + + "\x06client\x18\x01 \x01(\v2\v.api.ClientR\x06client\"^\n" + + "\x10CreateClientResp\x12%\n" + + "\x0ealready_exists\x18\x01 \x01(\bR\ralreadyExists\x12#\n" + + "\x06client\x18\x02 \x01(\v2\v.api.ClientR\x06client\"!\n" + + "\x0fDeleteClientReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\tR\x02id\"/\n" + + "\x10DeleteClientResp\x12\x1b\n" + + "\tnot_found\x18\x01 \x01(\bR\bnotFound\"\x9a\x01\n" + + "\x0fUpdateClientReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\tR\x02id\x12#\n" + + "\rredirect_uris\x18\x02 \x03(\tR\fredirectUris\x12#\n" + + "\rtrusted_peers\x18\x03 \x03(\tR\ftrustedPeers\x12\x12\n" + + "\x04name\x18\x04 \x01(\tR\x04name\x12\x19\n" + + "\blogo_url\x18\x05 \x01(\tR\alogoUrl\"/\n" + + "\x10UpdateClientResp\x12\x1b\n" + + "\tnot_found\x18\x01 \x01(\bR\bnotFound\"i\n" + + "\bPassword\x12\x14\n" + + "\x05email\x18\x01 \x01(\tR\x05email\x12\x12\n" + + "\x04hash\x18\x02 \x01(\fR\x04hash\x12\x1a\n" + + "\busername\x18\x03 \x01(\tR\busername\x12\x17\n" + + "\auser_id\x18\x04 \x01(\tR\x06userId\">\n" + + "\x11CreatePasswordReq\x12)\n" + + "\bpassword\x18\x01 \x01(\v2\r.api.PasswordR\bpassword\";\n" + + "\x12CreatePasswordResp\x12%\n" + + "\x0ealready_exists\x18\x01 \x01(\bR\ralreadyExists\"g\n" + + "\x11UpdatePasswordReq\x12\x14\n" + + "\x05email\x18\x01 \x01(\tR\x05email\x12\x19\n" + + "\bnew_hash\x18\x02 \x01(\fR\anewHash\x12!\n" + + "\fnew_username\x18\x03 \x01(\tR\vnewUsername\"1\n" + + "\x12UpdatePasswordResp\x12\x1b\n" + + "\tnot_found\x18\x01 \x01(\bR\bnotFound\")\n" + + "\x11DeletePasswordReq\x12\x14\n" + + "\x05email\x18\x01 \x01(\tR\x05email\"1\n" + + "\x12DeletePasswordResp\x12\x1b\n" + + "\tnot_found\x18\x01 \x01(\bR\bnotFound\"\x11\n" + + "\x0fListPasswordReq\"?\n" + + "\x10ListPasswordResp\x12+\n" + + "\tpasswords\x18\x01 \x03(\v2\r.api.PasswordR\tpasswords\"\f\n" + + "\n" + + "VersionReq\"7\n" + + "\vVersionResp\x12\x16\n" + + "\x06server\x18\x01 \x01(\tR\x06server\x12\x10\n" + + "\x03api\x18\x02 \x01(\x05R\x03api\"z\n" + + "\x0fRefreshTokenRef\x12\x0e\n" + + "\x02id\x18\x01 \x01(\tR\x02id\x12\x1b\n" + + "\tclient_id\x18\x02 \x01(\tR\bclientId\x12\x1d\n" + + "\n" + + "created_at\x18\x05 \x01(\x03R\tcreatedAt\x12\x1b\n" + + "\tlast_used\x18\x06 \x01(\x03R\blastUsed\")\n" + + "\x0eListRefreshReq\x12\x17\n" + + "\auser_id\x18\x01 \x01(\tR\x06userId\"N\n" + + "\x0fListRefreshResp\x12;\n" + + "\x0erefresh_tokens\x18\x01 \x03(\v2\x14.api.RefreshTokenRefR\rrefreshTokens\"H\n" + + "\x10RevokeRefreshReq\x12\x17\n" + + "\auser_id\x18\x01 \x01(\tR\x06userId\x12\x1b\n" + + "\tclient_id\x18\x02 \x01(\tR\bclientId\"0\n" + + "\x11RevokeRefreshResp\x12\x1b\n" + + "\tnot_found\x18\x01 \x01(\bR\bnotFound\"E\n" + + "\x11VerifyPasswordReq\x12\x14\n" + + "\x05email\x18\x01 \x01(\tR\x05email\x12\x1a\n" + + "\bpassword\x18\x02 \x01(\tR\bpassword\"M\n" + + "\x12VerifyPasswordResp\x12\x1a\n" + + "\bverified\x18\x01 \x01(\bR\bverified\x12\x1b\n" + + "\tnot_found\x18\x02 \x01(\bR\bnotFound2\xc7\x05\n" + + "\x03Dex\x12=\n" + + "\fCreateClient\x12\x14.api.CreateClientReq\x1a\x15.api.CreateClientResp\"\x00\x12=\n" + + "\fUpdateClient\x12\x14.api.UpdateClientReq\x1a\x15.api.UpdateClientResp\"\x00\x12=\n" + + "\fDeleteClient\x12\x14.api.DeleteClientReq\x1a\x15.api.DeleteClientResp\"\x00\x12C\n" + + "\x0eCreatePassword\x12\x16.api.CreatePasswordReq\x1a\x17.api.CreatePasswordResp\"\x00\x12C\n" + + "\x0eUpdatePassword\x12\x16.api.UpdatePasswordReq\x1a\x17.api.UpdatePasswordResp\"\x00\x12C\n" + + "\x0eDeletePassword\x12\x16.api.DeletePasswordReq\x1a\x17.api.DeletePasswordResp\"\x00\x12>\n" + + "\rListPasswords\x12\x14.api.ListPasswordReq\x1a\x15.api.ListPasswordResp\"\x00\x121\n" + + "\n" + + "GetVersion\x12\x0f.api.VersionReq\x1a\x10.api.VersionResp\"\x00\x12:\n" + + "\vListRefresh\x12\x13.api.ListRefreshReq\x1a\x14.api.ListRefreshResp\"\x00\x12@\n" + + "\rRevokeRefresh\x12\x15.api.RevokeRefreshReq\x1a\x16.api.RevokeRefreshResp\"\x00\x12C\n" + + "\x0eVerifyPassword\x12\x16.api.VerifyPasswordReq\x1a\x17.api.VerifyPasswordResp\"\x00B/\n" + + "\x12com.coreos.dex.apiZ\x19github.com/dexidp/dex/apib\x06proto3" var ( file_api_api_proto_rawDescOnce sync.Once diff --git a/api/v2/api.pb.go b/api/v2/api.pb.go index e0e1f1bd0f..55aa98258c 100644 --- a/api/v2/api.pb.go +++ b/api/v2/api.pb.go @@ -1,6 +1,6 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.36.5 +// protoc-gen-go v1.36.6 // protoc v5.29.3 // source: api/v2/api.proto @@ -2055,289 +2055,150 @@ func (x *VerifyPasswordResp) GetNotFound() bool { var File_api_v2_api_proto protoreflect.FileDescriptor -var file_api_v2_api_proto_rawDesc = string([]byte{ - 0x0a, 0x10, 0x61, 0x70, 0x69, 0x2f, 0x76, 0x32, 0x2f, 0x61, 0x70, 0x69, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x12, 0x03, 0x61, 0x70, 0x69, 0x22, 0xc1, 0x01, 0x0a, 0x06, 0x43, 0x6c, 0x69, 0x65, - 0x6e, 0x74, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, - 0x69, 0x64, 0x12, 0x16, 0x0a, 0x06, 0x73, 0x65, 0x63, 0x72, 0x65, 0x74, 0x18, 0x02, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x06, 0x73, 0x65, 0x63, 0x72, 0x65, 0x74, 0x12, 0x23, 0x0a, 0x0d, 0x72, 0x65, - 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x5f, 0x75, 0x72, 0x69, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, - 0x09, 0x52, 0x0c, 0x72, 0x65, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x55, 0x72, 0x69, 0x73, 0x12, - 0x23, 0x0a, 0x0d, 0x74, 0x72, 0x75, 0x73, 0x74, 0x65, 0x64, 0x5f, 0x70, 0x65, 0x65, 0x72, 0x73, - 0x18, 0x04, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0c, 0x74, 0x72, 0x75, 0x73, 0x74, 0x65, 0x64, 0x50, - 0x65, 0x65, 0x72, 0x73, 0x12, 0x16, 0x0a, 0x06, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x18, 0x05, - 0x20, 0x01, 0x28, 0x08, 0x52, 0x06, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x12, 0x12, 0x0a, 0x04, - 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, - 0x12, 0x19, 0x0a, 0x08, 0x6c, 0x6f, 0x67, 0x6f, 0x5f, 0x75, 0x72, 0x6c, 0x18, 0x07, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x07, 0x6c, 0x6f, 0x67, 0x6f, 0x55, 0x72, 0x6c, 0x22, 0x1e, 0x0a, 0x0c, 0x47, - 0x65, 0x74, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x71, 0x12, 0x0e, 0x0a, 0x02, 0x69, - 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x22, 0x34, 0x0a, 0x0d, 0x47, - 0x65, 0x74, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x73, 0x70, 0x12, 0x23, 0x0a, 0x06, - 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0b, 0x2e, 0x61, - 0x70, 0x69, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x52, 0x06, 0x63, 0x6c, 0x69, 0x65, 0x6e, - 0x74, 0x22, 0x36, 0x0a, 0x0f, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x43, 0x6c, 0x69, 0x65, 0x6e, - 0x74, 0x52, 0x65, 0x71, 0x12, 0x23, 0x0a, 0x06, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x18, 0x01, - 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0b, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, - 0x74, 0x52, 0x06, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x22, 0x5e, 0x0a, 0x10, 0x43, 0x72, 0x65, - 0x61, 0x74, 0x65, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x73, 0x70, 0x12, 0x25, 0x0a, - 0x0e, 0x61, 0x6c, 0x72, 0x65, 0x61, 0x64, 0x79, 0x5f, 0x65, 0x78, 0x69, 0x73, 0x74, 0x73, 0x18, - 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0d, 0x61, 0x6c, 0x72, 0x65, 0x61, 0x64, 0x79, 0x45, 0x78, - 0x69, 0x73, 0x74, 0x73, 0x12, 0x23, 0x0a, 0x06, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x18, 0x02, - 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0b, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, 0x6c, 0x69, 0x65, 0x6e, - 0x74, 0x52, 0x06, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x22, 0x21, 0x0a, 0x0f, 0x44, 0x65, 0x6c, - 0x65, 0x74, 0x65, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x71, 0x12, 0x0e, 0x0a, 0x02, - 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x22, 0x2f, 0x0a, 0x10, - 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x73, 0x70, - 0x12, 0x1b, 0x0a, 0x09, 0x6e, 0x6f, 0x74, 0x5f, 0x66, 0x6f, 0x75, 0x6e, 0x64, 0x18, 0x01, 0x20, - 0x01, 0x28, 0x08, 0x52, 0x08, 0x6e, 0x6f, 0x74, 0x46, 0x6f, 0x75, 0x6e, 0x64, 0x22, 0x9a, 0x01, - 0x0a, 0x0f, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x52, 0x65, - 0x71, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, - 0x64, 0x12, 0x23, 0x0a, 0x0d, 0x72, 0x65, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x5f, 0x75, 0x72, - 0x69, 0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0c, 0x72, 0x65, 0x64, 0x69, 0x72, 0x65, - 0x63, 0x74, 0x55, 0x72, 0x69, 0x73, 0x12, 0x23, 0x0a, 0x0d, 0x74, 0x72, 0x75, 0x73, 0x74, 0x65, - 0x64, 0x5f, 0x70, 0x65, 0x65, 0x72, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0c, 0x74, - 0x72, 0x75, 0x73, 0x74, 0x65, 0x64, 0x50, 0x65, 0x65, 0x72, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x6e, - 0x61, 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, - 0x19, 0x0a, 0x08, 0x6c, 0x6f, 0x67, 0x6f, 0x5f, 0x75, 0x72, 0x6c, 0x18, 0x05, 0x20, 0x01, 0x28, - 0x09, 0x52, 0x07, 0x6c, 0x6f, 0x67, 0x6f, 0x55, 0x72, 0x6c, 0x22, 0x2f, 0x0a, 0x10, 0x55, 0x70, - 0x64, 0x61, 0x74, 0x65, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x73, 0x70, 0x12, 0x1b, - 0x0a, 0x09, 0x6e, 0x6f, 0x74, 0x5f, 0x66, 0x6f, 0x75, 0x6e, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, - 0x08, 0x52, 0x08, 0x6e, 0x6f, 0x74, 0x46, 0x6f, 0x75, 0x6e, 0x64, 0x22, 0x69, 0x0a, 0x08, 0x50, - 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x65, 0x6d, 0x61, 0x69, 0x6c, - 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x12, 0x12, 0x0a, - 0x04, 0x68, 0x61, 0x73, 0x68, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x04, 0x68, 0x61, 0x73, - 0x68, 0x12, 0x1a, 0x0a, 0x08, 0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x08, 0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x17, 0x0a, - 0x07, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, - 0x75, 0x73, 0x65, 0x72, 0x49, 0x64, 0x22, 0x3e, 0x0a, 0x11, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, - 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, 0x71, 0x12, 0x29, 0x0a, 0x08, 0x70, - 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0d, 0x2e, - 0x61, 0x70, 0x69, 0x2e, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, 0x08, 0x70, 0x61, - 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x22, 0x3b, 0x0a, 0x12, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, - 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, 0x73, 0x70, 0x12, 0x25, 0x0a, 0x0e, - 0x61, 0x6c, 0x72, 0x65, 0x61, 0x64, 0x79, 0x5f, 0x65, 0x78, 0x69, 0x73, 0x74, 0x73, 0x18, 0x01, - 0x20, 0x01, 0x28, 0x08, 0x52, 0x0d, 0x61, 0x6c, 0x72, 0x65, 0x61, 0x64, 0x79, 0x45, 0x78, 0x69, - 0x73, 0x74, 0x73, 0x22, 0x67, 0x0a, 0x11, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x50, 0x61, 0x73, - 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, 0x71, 0x12, 0x14, 0x0a, 0x05, 0x65, 0x6d, 0x61, 0x69, - 0x6c, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x12, 0x19, - 0x0a, 0x08, 0x6e, 0x65, 0x77, 0x5f, 0x68, 0x61, 0x73, 0x68, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, - 0x52, 0x07, 0x6e, 0x65, 0x77, 0x48, 0x61, 0x73, 0x68, 0x12, 0x21, 0x0a, 0x0c, 0x6e, 0x65, 0x77, - 0x5f, 0x75, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x0b, 0x6e, 0x65, 0x77, 0x55, 0x73, 0x65, 0x72, 0x6e, 0x61, 0x6d, 0x65, 0x22, 0x31, 0x0a, 0x12, - 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, - 0x73, 0x70, 0x12, 0x1b, 0x0a, 0x09, 0x6e, 0x6f, 0x74, 0x5f, 0x66, 0x6f, 0x75, 0x6e, 0x64, 0x18, - 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, 0x6e, 0x6f, 0x74, 0x46, 0x6f, 0x75, 0x6e, 0x64, 0x22, - 0x29, 0x0a, 0x11, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, - 0x64, 0x52, 0x65, 0x71, 0x12, 0x14, 0x0a, 0x05, 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x18, 0x01, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x05, 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x22, 0x31, 0x0a, 0x12, 0x44, 0x65, - 0x6c, 0x65, 0x74, 0x65, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, 0x73, 0x70, - 0x12, 0x1b, 0x0a, 0x09, 0x6e, 0x6f, 0x74, 0x5f, 0x66, 0x6f, 0x75, 0x6e, 0x64, 0x18, 0x01, 0x20, - 0x01, 0x28, 0x08, 0x52, 0x08, 0x6e, 0x6f, 0x74, 0x46, 0x6f, 0x75, 0x6e, 0x64, 0x22, 0x11, 0x0a, - 0x0f, 0x4c, 0x69, 0x73, 0x74, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, 0x71, - 0x22, 0x3f, 0x0a, 0x10, 0x4c, 0x69, 0x73, 0x74, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, - 0x52, 0x65, 0x73, 0x70, 0x12, 0x2b, 0x0a, 0x09, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, - 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0d, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x50, 0x61, - 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, 0x09, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, - 0x73, 0x22, 0x5b, 0x0a, 0x09, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x12, 0x0e, - 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x12, - 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04, 0x74, 0x79, - 0x70, 0x65, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, - 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x16, 0x0a, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, - 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x06, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x22, 0x42, - 0x0a, 0x12, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x6f, - 0x72, 0x52, 0x65, 0x71, 0x12, 0x2c, 0x0a, 0x09, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x6f, - 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0e, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, 0x6f, - 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x52, 0x09, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, - 0x6f, 0x72, 0x22, 0x3c, 0x0a, 0x13, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x6e, - 0x65, 0x63, 0x74, 0x6f, 0x72, 0x52, 0x65, 0x73, 0x70, 0x12, 0x25, 0x0a, 0x0e, 0x61, 0x6c, 0x72, - 0x65, 0x61, 0x64, 0x79, 0x5f, 0x65, 0x78, 0x69, 0x73, 0x74, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, - 0x08, 0x52, 0x0d, 0x61, 0x6c, 0x72, 0x65, 0x61, 0x64, 0x79, 0x45, 0x78, 0x69, 0x73, 0x74, 0x73, - 0x22, 0x79, 0x0a, 0x12, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, - 0x74, 0x6f, 0x72, 0x52, 0x65, 0x71, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, 0x19, 0x0a, 0x08, 0x6e, 0x65, 0x77, 0x5f, 0x74, 0x79, - 0x70, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6e, 0x65, 0x77, 0x54, 0x79, 0x70, - 0x65, 0x12, 0x19, 0x0a, 0x08, 0x6e, 0x65, 0x77, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x03, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x07, 0x6e, 0x65, 0x77, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x1d, 0x0a, 0x0a, - 0x6e, 0x65, 0x77, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0c, - 0x52, 0x09, 0x6e, 0x65, 0x77, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x22, 0x32, 0x0a, 0x13, 0x55, - 0x70, 0x64, 0x61, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x52, 0x65, - 0x73, 0x70, 0x12, 0x1b, 0x0a, 0x09, 0x6e, 0x6f, 0x74, 0x5f, 0x66, 0x6f, 0x75, 0x6e, 0x64, 0x18, - 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, 0x6e, 0x6f, 0x74, 0x46, 0x6f, 0x75, 0x6e, 0x64, 0x22, - 0x24, 0x0a, 0x12, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, - 0x6f, 0x72, 0x52, 0x65, 0x71, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, - 0x09, 0x52, 0x02, 0x69, 0x64, 0x22, 0x32, 0x0a, 0x13, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x43, - 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x52, 0x65, 0x73, 0x70, 0x12, 0x1b, 0x0a, 0x09, - 0x6e, 0x6f, 0x74, 0x5f, 0x66, 0x6f, 0x75, 0x6e, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, - 0x08, 0x6e, 0x6f, 0x74, 0x46, 0x6f, 0x75, 0x6e, 0x64, 0x22, 0x12, 0x0a, 0x10, 0x4c, 0x69, 0x73, - 0x74, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x52, 0x65, 0x71, 0x22, 0x43, 0x0a, - 0x11, 0x4c, 0x69, 0x73, 0x74, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x52, 0x65, - 0x73, 0x70, 0x12, 0x2e, 0x0a, 0x0a, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x73, - 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x0e, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, 0x6f, 0x6e, - 0x6e, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x52, 0x0a, 0x63, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x6f, - 0x72, 0x73, 0x22, 0x0c, 0x0a, 0x0a, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, - 0x22, 0x37, 0x0a, 0x0b, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x12, - 0x16, 0x0a, 0x06, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x06, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x12, 0x10, 0x0a, 0x03, 0x61, 0x70, 0x69, 0x18, 0x02, - 0x20, 0x01, 0x28, 0x05, 0x52, 0x03, 0x61, 0x70, 0x69, 0x22, 0x0e, 0x0a, 0x0c, 0x44, 0x69, 0x73, - 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x52, 0x65, 0x71, 0x22, 0xb0, 0x06, 0x0a, 0x0d, 0x44, 0x69, - 0x73, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x52, 0x65, 0x73, 0x70, 0x12, 0x16, 0x0a, 0x06, 0x69, - 0x73, 0x73, 0x75, 0x65, 0x72, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x69, 0x73, 0x73, - 0x75, 0x65, 0x72, 0x12, 0x35, 0x0a, 0x16, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x61, - 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x18, 0x02, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x15, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x12, 0x25, 0x0a, 0x0e, 0x74, 0x6f, - 0x6b, 0x65, 0x6e, 0x5f, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x18, 0x03, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x0d, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, - 0x74, 0x12, 0x19, 0x0a, 0x08, 0x6a, 0x77, 0x6b, 0x73, 0x5f, 0x75, 0x72, 0x69, 0x18, 0x04, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x07, 0x6a, 0x77, 0x6b, 0x73, 0x55, 0x72, 0x69, 0x12, 0x2b, 0x0a, 0x11, - 0x75, 0x73, 0x65, 0x72, 0x69, 0x6e, 0x66, 0x6f, 0x5f, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, - 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09, 0x52, 0x10, 0x75, 0x73, 0x65, 0x72, 0x69, 0x6e, 0x66, - 0x6f, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x12, 0x42, 0x0a, 0x1d, 0x64, 0x65, 0x76, - 0x69, 0x63, 0x65, 0x5f, 0x61, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, - 0x6e, 0x5f, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x18, 0x06, 0x20, 0x01, 0x28, 0x09, - 0x52, 0x1b, 0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x7a, - 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x12, 0x35, 0x0a, - 0x16, 0x69, 0x6e, 0x74, 0x72, 0x6f, 0x73, 0x70, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x65, - 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x15, 0x69, - 0x6e, 0x74, 0x72, 0x6f, 0x73, 0x70, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x45, 0x6e, 0x64, 0x70, - 0x6f, 0x69, 0x6e, 0x74, 0x12, 0x32, 0x0a, 0x15, 0x67, 0x72, 0x61, 0x6e, 0x74, 0x5f, 0x74, 0x79, - 0x70, 0x65, 0x73, 0x5f, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x18, 0x08, 0x20, - 0x03, 0x28, 0x09, 0x52, 0x13, 0x67, 0x72, 0x61, 0x6e, 0x74, 0x54, 0x79, 0x70, 0x65, 0x73, 0x53, - 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x12, 0x38, 0x0a, 0x18, 0x72, 0x65, 0x73, 0x70, - 0x6f, 0x6e, 0x73, 0x65, 0x5f, 0x74, 0x79, 0x70, 0x65, 0x73, 0x5f, 0x73, 0x75, 0x70, 0x70, 0x6f, - 0x72, 0x74, 0x65, 0x64, 0x18, 0x09, 0x20, 0x03, 0x28, 0x09, 0x52, 0x16, 0x72, 0x65, 0x73, 0x70, - 0x6f, 0x6e, 0x73, 0x65, 0x54, 0x79, 0x70, 0x65, 0x73, 0x53, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, - 0x65, 0x64, 0x12, 0x36, 0x0a, 0x17, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x5f, 0x74, 0x79, - 0x70, 0x65, 0x73, 0x5f, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x18, 0x0a, 0x20, - 0x03, 0x28, 0x09, 0x52, 0x15, 0x73, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x54, 0x79, 0x70, 0x65, - 0x73, 0x53, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x12, 0x4f, 0x0a, 0x25, 0x69, 0x64, - 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x5f, 0x73, 0x69, 0x67, 0x6e, 0x69, 0x6e, 0x67, 0x5f, 0x61, - 0x6c, 0x67, 0x5f, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x73, 0x5f, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, - 0x74, 0x65, 0x64, 0x18, 0x0b, 0x20, 0x03, 0x28, 0x09, 0x52, 0x20, 0x69, 0x64, 0x54, 0x6f, 0x6b, - 0x65, 0x6e, 0x53, 0x69, 0x67, 0x6e, 0x69, 0x6e, 0x67, 0x41, 0x6c, 0x67, 0x56, 0x61, 0x6c, 0x75, - 0x65, 0x73, 0x53, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x12, 0x47, 0x0a, 0x20, 0x63, - 0x6f, 0x64, 0x65, 0x5f, 0x63, 0x68, 0x61, 0x6c, 0x6c, 0x65, 0x6e, 0x67, 0x65, 0x5f, 0x6d, 0x65, - 0x74, 0x68, 0x6f, 0x64, 0x73, 0x5f, 0x73, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x18, - 0x0c, 0x20, 0x03, 0x28, 0x09, 0x52, 0x1d, 0x63, 0x6f, 0x64, 0x65, 0x43, 0x68, 0x61, 0x6c, 0x6c, - 0x65, 0x6e, 0x67, 0x65, 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x73, 0x53, 0x75, 0x70, 0x70, 0x6f, - 0x72, 0x74, 0x65, 0x64, 0x12, 0x29, 0x0a, 0x10, 0x73, 0x63, 0x6f, 0x70, 0x65, 0x73, 0x5f, 0x73, - 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x18, 0x0d, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0f, - 0x73, 0x63, 0x6f, 0x70, 0x65, 0x73, 0x53, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x12, - 0x50, 0x0a, 0x25, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x5f, 0x65, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, - 0x74, 0x5f, 0x61, 0x75, 0x74, 0x68, 0x5f, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x73, 0x5f, 0x73, - 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x18, 0x0e, 0x20, 0x03, 0x28, 0x09, 0x52, 0x21, - 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x45, 0x6e, 0x64, 0x70, 0x6f, 0x69, 0x6e, 0x74, 0x41, 0x75, 0x74, - 0x68, 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x73, 0x53, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, - 0x64, 0x12, 0x29, 0x0a, 0x10, 0x63, 0x6c, 0x61, 0x69, 0x6d, 0x73, 0x5f, 0x73, 0x75, 0x70, 0x70, - 0x6f, 0x72, 0x74, 0x65, 0x64, 0x18, 0x0f, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0f, 0x63, 0x6c, 0x61, - 0x69, 0x6d, 0x73, 0x53, 0x75, 0x70, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x64, 0x22, 0x7a, 0x0a, 0x0f, - 0x52, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x52, 0x65, 0x66, 0x12, - 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, 0x64, 0x12, - 0x1b, 0x0a, 0x09, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, - 0x28, 0x09, 0x52, 0x08, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x49, 0x64, 0x12, 0x1d, 0x0a, 0x0a, - 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x5f, 0x61, 0x74, 0x18, 0x05, 0x20, 0x01, 0x28, 0x03, - 0x52, 0x09, 0x63, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x41, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x6c, - 0x61, 0x73, 0x74, 0x5f, 0x75, 0x73, 0x65, 0x64, 0x18, 0x06, 0x20, 0x01, 0x28, 0x03, 0x52, 0x08, - 0x6c, 0x61, 0x73, 0x74, 0x55, 0x73, 0x65, 0x64, 0x22, 0x29, 0x0a, 0x0e, 0x4c, 0x69, 0x73, 0x74, - 0x52, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x52, 0x65, 0x71, 0x12, 0x17, 0x0a, 0x07, 0x75, 0x73, - 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x75, 0x73, 0x65, - 0x72, 0x49, 0x64, 0x22, 0x4e, 0x0a, 0x0f, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x66, 0x72, 0x65, - 0x73, 0x68, 0x52, 0x65, 0x73, 0x70, 0x12, 0x3b, 0x0a, 0x0e, 0x72, 0x65, 0x66, 0x72, 0x65, 0x73, - 0x68, 0x5f, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x14, - 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x52, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x54, 0x6f, 0x6b, 0x65, - 0x6e, 0x52, 0x65, 0x66, 0x52, 0x0d, 0x72, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x54, 0x6f, 0x6b, - 0x65, 0x6e, 0x73, 0x22, 0x48, 0x0a, 0x10, 0x52, 0x65, 0x76, 0x6f, 0x6b, 0x65, 0x52, 0x65, 0x66, - 0x72, 0x65, 0x73, 0x68, 0x52, 0x65, 0x71, 0x12, 0x17, 0x0a, 0x07, 0x75, 0x73, 0x65, 0x72, 0x5f, - 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x75, 0x73, 0x65, 0x72, 0x49, 0x64, - 0x12, 0x1b, 0x0a, 0x09, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x08, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x49, 0x64, 0x22, 0x30, 0x0a, - 0x11, 0x52, 0x65, 0x76, 0x6f, 0x6b, 0x65, 0x52, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x52, 0x65, - 0x73, 0x70, 0x12, 0x1b, 0x0a, 0x09, 0x6e, 0x6f, 0x74, 0x5f, 0x66, 0x6f, 0x75, 0x6e, 0x64, 0x18, - 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, 0x6e, 0x6f, 0x74, 0x46, 0x6f, 0x75, 0x6e, 0x64, 0x22, - 0x45, 0x0a, 0x11, 0x56, 0x65, 0x72, 0x69, 0x66, 0x79, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, - 0x64, 0x52, 0x65, 0x71, 0x12, 0x14, 0x0a, 0x05, 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x18, 0x01, 0x20, - 0x01, 0x28, 0x09, 0x52, 0x05, 0x65, 0x6d, 0x61, 0x69, 0x6c, 0x12, 0x1a, 0x0a, 0x08, 0x70, 0x61, - 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x70, 0x61, - 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x22, 0x4d, 0x0a, 0x12, 0x56, 0x65, 0x72, 0x69, 0x66, 0x79, - 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, 0x73, 0x70, 0x12, 0x1a, 0x0a, 0x08, - 0x76, 0x65, 0x72, 0x69, 0x66, 0x69, 0x65, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, - 0x76, 0x65, 0x72, 0x69, 0x66, 0x69, 0x65, 0x64, 0x12, 0x1b, 0x0a, 0x09, 0x6e, 0x6f, 0x74, 0x5f, - 0x66, 0x6f, 0x75, 0x6e, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x08, 0x52, 0x08, 0x6e, 0x6f, 0x74, - 0x46, 0x6f, 0x75, 0x6e, 0x64, 0x32, 0xd1, 0x08, 0x0a, 0x03, 0x44, 0x65, 0x78, 0x12, 0x34, 0x0a, - 0x09, 0x47, 0x65, 0x74, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x12, 0x11, 0x2e, 0x61, 0x70, 0x69, - 0x2e, 0x47, 0x65, 0x74, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x71, 0x1a, 0x12, 0x2e, - 0x61, 0x70, 0x69, 0x2e, 0x47, 0x65, 0x74, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x73, - 0x70, 0x22, 0x00, 0x12, 0x3d, 0x0a, 0x0c, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x43, 0x6c, 0x69, - 0x65, 0x6e, 0x74, 0x12, 0x14, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, - 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x71, 0x1a, 0x15, 0x2e, 0x61, 0x70, 0x69, 0x2e, - 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x73, 0x70, - 0x22, 0x00, 0x12, 0x3d, 0x0a, 0x0c, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x43, 0x6c, 0x69, 0x65, - 0x6e, 0x74, 0x12, 0x14, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x43, - 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x71, 0x1a, 0x15, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x55, - 0x70, 0x64, 0x61, 0x74, 0x65, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x73, 0x70, 0x22, - 0x00, 0x12, 0x3d, 0x0a, 0x0c, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x43, 0x6c, 0x69, 0x65, 0x6e, - 0x74, 0x12, 0x14, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x43, 0x6c, - 0x69, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x71, 0x1a, 0x15, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x44, 0x65, - 0x6c, 0x65, 0x74, 0x65, 0x43, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x52, 0x65, 0x73, 0x70, 0x22, 0x00, - 0x12, 0x43, 0x0a, 0x0e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, - 0x72, 0x64, 0x12, 0x16, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x50, - 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, 0x71, 0x1a, 0x17, 0x2e, 0x61, 0x70, 0x69, - 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, - 0x65, 0x73, 0x70, 0x22, 0x00, 0x12, 0x43, 0x0a, 0x0e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x50, - 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x12, 0x16, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x55, 0x70, - 0x64, 0x61, 0x74, 0x65, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, 0x71, 0x1a, - 0x17, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x50, 0x61, 0x73, 0x73, - 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, 0x73, 0x70, 0x22, 0x00, 0x12, 0x43, 0x0a, 0x0e, 0x44, 0x65, - 0x6c, 0x65, 0x74, 0x65, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x12, 0x16, 0x2e, 0x61, - 0x70, 0x69, 0x2e, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, - 0x64, 0x52, 0x65, 0x71, 0x1a, 0x17, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x44, 0x65, 0x6c, 0x65, 0x74, - 0x65, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, 0x73, 0x70, 0x22, 0x00, 0x12, - 0x3e, 0x0a, 0x0d, 0x4c, 0x69, 0x73, 0x74, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x73, - 0x12, 0x14, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x50, 0x61, 0x73, 0x73, 0x77, - 0x6f, 0x72, 0x64, 0x52, 0x65, 0x71, 0x1a, 0x15, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x4c, 0x69, 0x73, - 0x74, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, 0x73, 0x70, 0x22, 0x00, 0x12, - 0x46, 0x0a, 0x0f, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, - 0x6f, 0x72, 0x12, 0x17, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x43, - 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x52, 0x65, 0x71, 0x1a, 0x18, 0x2e, 0x61, 0x70, - 0x69, 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x6f, - 0x72, 0x52, 0x65, 0x73, 0x70, 0x22, 0x00, 0x12, 0x46, 0x0a, 0x0f, 0x55, 0x70, 0x64, 0x61, 0x74, - 0x65, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x12, 0x17, 0x2e, 0x61, 0x70, 0x69, - 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x6f, 0x72, - 0x52, 0x65, 0x71, 0x1a, 0x18, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, - 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x52, 0x65, 0x73, 0x70, 0x22, 0x00, 0x12, - 0x46, 0x0a, 0x0f, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, - 0x6f, 0x72, 0x12, 0x17, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x43, - 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x52, 0x65, 0x71, 0x1a, 0x18, 0x2e, 0x61, 0x70, - 0x69, 0x2e, 0x44, 0x65, 0x6c, 0x65, 0x74, 0x65, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x6f, - 0x72, 0x52, 0x65, 0x73, 0x70, 0x22, 0x00, 0x12, 0x41, 0x0a, 0x0e, 0x4c, 0x69, 0x73, 0x74, 0x43, - 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x73, 0x12, 0x15, 0x2e, 0x61, 0x70, 0x69, 0x2e, - 0x4c, 0x69, 0x73, 0x74, 0x43, 0x6f, 0x6e, 0x6e, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x52, 0x65, 0x71, - 0x1a, 0x16, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x43, 0x6f, 0x6e, 0x6e, 0x65, - 0x63, 0x74, 0x6f, 0x72, 0x52, 0x65, 0x73, 0x70, 0x22, 0x00, 0x12, 0x31, 0x0a, 0x0a, 0x47, 0x65, - 0x74, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x0f, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x56, - 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x71, 0x1a, 0x10, 0x2e, 0x61, 0x70, 0x69, 0x2e, - 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x52, 0x65, 0x73, 0x70, 0x22, 0x00, 0x12, 0x37, 0x0a, - 0x0c, 0x47, 0x65, 0x74, 0x44, 0x69, 0x73, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x12, 0x11, 0x2e, - 0x61, 0x70, 0x69, 0x2e, 0x44, 0x69, 0x73, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, 0x52, 0x65, 0x71, - 0x1a, 0x12, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x44, 0x69, 0x73, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79, - 0x52, 0x65, 0x73, 0x70, 0x22, 0x00, 0x12, 0x3a, 0x0a, 0x0b, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, - 0x66, 0x72, 0x65, 0x73, 0x68, 0x12, 0x13, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x4c, 0x69, 0x73, 0x74, - 0x52, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x52, 0x65, 0x71, 0x1a, 0x14, 0x2e, 0x61, 0x70, 0x69, - 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x52, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x52, 0x65, 0x73, 0x70, - 0x22, 0x00, 0x12, 0x40, 0x0a, 0x0d, 0x52, 0x65, 0x76, 0x6f, 0x6b, 0x65, 0x52, 0x65, 0x66, 0x72, - 0x65, 0x73, 0x68, 0x12, 0x15, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x52, 0x65, 0x76, 0x6f, 0x6b, 0x65, - 0x52, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x52, 0x65, 0x71, 0x1a, 0x16, 0x2e, 0x61, 0x70, 0x69, - 0x2e, 0x52, 0x65, 0x76, 0x6f, 0x6b, 0x65, 0x52, 0x65, 0x66, 0x72, 0x65, 0x73, 0x68, 0x52, 0x65, - 0x73, 0x70, 0x22, 0x00, 0x12, 0x43, 0x0a, 0x0e, 0x56, 0x65, 0x72, 0x69, 0x66, 0x79, 0x50, 0x61, - 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x12, 0x16, 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x56, 0x65, 0x72, - 0x69, 0x66, 0x79, 0x50, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x52, 0x65, 0x71, 0x1a, 0x17, - 0x2e, 0x61, 0x70, 0x69, 0x2e, 0x56, 0x65, 0x72, 0x69, 0x66, 0x79, 0x50, 0x61, 0x73, 0x73, 0x77, - 0x6f, 0x72, 0x64, 0x52, 0x65, 0x73, 0x70, 0x22, 0x00, 0x42, 0x36, 0x0a, 0x12, 0x63, 0x6f, 0x6d, - 0x2e, 0x63, 0x6f, 0x72, 0x65, 0x6f, 0x73, 0x2e, 0x64, 0x65, 0x78, 0x2e, 0x61, 0x70, 0x69, 0x5a, - 0x20, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x64, 0x65, 0x78, 0x69, - 0x64, 0x70, 0x2f, 0x64, 0x65, 0x78, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x76, 0x32, 0x3b, 0x61, 0x70, - 0x69, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -}) +const file_api_v2_api_proto_rawDesc = "" + + "\n" + + "\x10api/v2/api.proto\x12\x03api\"\xc1\x01\n" + + "\x06Client\x12\x0e\n" + + "\x02id\x18\x01 \x01(\tR\x02id\x12\x16\n" + + "\x06secret\x18\x02 \x01(\tR\x06secret\x12#\n" + + "\rredirect_uris\x18\x03 \x03(\tR\fredirectUris\x12#\n" + + "\rtrusted_peers\x18\x04 \x03(\tR\ftrustedPeers\x12\x16\n" + + "\x06public\x18\x05 \x01(\bR\x06public\x12\x12\n" + + "\x04name\x18\x06 \x01(\tR\x04name\x12\x19\n" + + "\blogo_url\x18\a \x01(\tR\alogoUrl\"\x1e\n" + + "\fGetClientReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\tR\x02id\"4\n" + + "\rGetClientResp\x12#\n" + + "\x06client\x18\x01 \x01(\v2\v.api.ClientR\x06client\"6\n" + + "\x0fCreateClientReq\x12#\n" + + "\x06client\x18\x01 \x01(\v2\v.api.ClientR\x06client\"^\n" + + "\x10CreateClientResp\x12%\n" + + "\x0ealready_exists\x18\x01 \x01(\bR\ralreadyExists\x12#\n" + + "\x06client\x18\x02 \x01(\v2\v.api.ClientR\x06client\"!\n" + + "\x0fDeleteClientReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\tR\x02id\"/\n" + + "\x10DeleteClientResp\x12\x1b\n" + + "\tnot_found\x18\x01 \x01(\bR\bnotFound\"\x9a\x01\n" + + "\x0fUpdateClientReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\tR\x02id\x12#\n" + + "\rredirect_uris\x18\x02 \x03(\tR\fredirectUris\x12#\n" + + "\rtrusted_peers\x18\x03 \x03(\tR\ftrustedPeers\x12\x12\n" + + "\x04name\x18\x04 \x01(\tR\x04name\x12\x19\n" + + "\blogo_url\x18\x05 \x01(\tR\alogoUrl\"/\n" + + "\x10UpdateClientResp\x12\x1b\n" + + "\tnot_found\x18\x01 \x01(\bR\bnotFound\"i\n" + + "\bPassword\x12\x14\n" + + "\x05email\x18\x01 \x01(\tR\x05email\x12\x12\n" + + "\x04hash\x18\x02 \x01(\fR\x04hash\x12\x1a\n" + + "\busername\x18\x03 \x01(\tR\busername\x12\x17\n" + + "\auser_id\x18\x04 \x01(\tR\x06userId\">\n" + + "\x11CreatePasswordReq\x12)\n" + + "\bpassword\x18\x01 \x01(\v2\r.api.PasswordR\bpassword\";\n" + + "\x12CreatePasswordResp\x12%\n" + + "\x0ealready_exists\x18\x01 \x01(\bR\ralreadyExists\"g\n" + + "\x11UpdatePasswordReq\x12\x14\n" + + "\x05email\x18\x01 \x01(\tR\x05email\x12\x19\n" + + "\bnew_hash\x18\x02 \x01(\fR\anewHash\x12!\n" + + "\fnew_username\x18\x03 \x01(\tR\vnewUsername\"1\n" + + "\x12UpdatePasswordResp\x12\x1b\n" + + "\tnot_found\x18\x01 \x01(\bR\bnotFound\")\n" + + "\x11DeletePasswordReq\x12\x14\n" + + "\x05email\x18\x01 \x01(\tR\x05email\"1\n" + + "\x12DeletePasswordResp\x12\x1b\n" + + "\tnot_found\x18\x01 \x01(\bR\bnotFound\"\x11\n" + + "\x0fListPasswordReq\"?\n" + + "\x10ListPasswordResp\x12+\n" + + "\tpasswords\x18\x01 \x03(\v2\r.api.PasswordR\tpasswords\"[\n" + + "\tConnector\x12\x0e\n" + + "\x02id\x18\x01 \x01(\tR\x02id\x12\x12\n" + + "\x04type\x18\x02 \x01(\tR\x04type\x12\x12\n" + + "\x04name\x18\x03 \x01(\tR\x04name\x12\x16\n" + + "\x06config\x18\x04 \x01(\fR\x06config\"B\n" + + "\x12CreateConnectorReq\x12,\n" + + "\tconnector\x18\x01 \x01(\v2\x0e.api.ConnectorR\tconnector\"<\n" + + "\x13CreateConnectorResp\x12%\n" + + "\x0ealready_exists\x18\x01 \x01(\bR\ralreadyExists\"y\n" + + "\x12UpdateConnectorReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\tR\x02id\x12\x19\n" + + "\bnew_type\x18\x02 \x01(\tR\anewType\x12\x19\n" + + "\bnew_name\x18\x03 \x01(\tR\anewName\x12\x1d\n" + + "\n" + + "new_config\x18\x04 \x01(\fR\tnewConfig\"2\n" + + "\x13UpdateConnectorResp\x12\x1b\n" + + "\tnot_found\x18\x01 \x01(\bR\bnotFound\"$\n" + + "\x12DeleteConnectorReq\x12\x0e\n" + + "\x02id\x18\x01 \x01(\tR\x02id\"2\n" + + "\x13DeleteConnectorResp\x12\x1b\n" + + "\tnot_found\x18\x01 \x01(\bR\bnotFound\"\x12\n" + + "\x10ListConnectorReq\"C\n" + + "\x11ListConnectorResp\x12.\n" + + "\n" + + "connectors\x18\x01 \x03(\v2\x0e.api.ConnectorR\n" + + "connectors\"\f\n" + + "\n" + + "VersionReq\"7\n" + + "\vVersionResp\x12\x16\n" + + "\x06server\x18\x01 \x01(\tR\x06server\x12\x10\n" + + "\x03api\x18\x02 \x01(\x05R\x03api\"\x0e\n" + + "\fDiscoveryReq\"\xb0\x06\n" + + "\rDiscoveryResp\x12\x16\n" + + "\x06issuer\x18\x01 \x01(\tR\x06issuer\x125\n" + + "\x16authorization_endpoint\x18\x02 \x01(\tR\x15authorizationEndpoint\x12%\n" + + "\x0etoken_endpoint\x18\x03 \x01(\tR\rtokenEndpoint\x12\x19\n" + + "\bjwks_uri\x18\x04 \x01(\tR\ajwksUri\x12+\n" + + "\x11userinfo_endpoint\x18\x05 \x01(\tR\x10userinfoEndpoint\x12B\n" + + "\x1ddevice_authorization_endpoint\x18\x06 \x01(\tR\x1bdeviceAuthorizationEndpoint\x125\n" + + "\x16introspection_endpoint\x18\a \x01(\tR\x15introspectionEndpoint\x122\n" + + "\x15grant_types_supported\x18\b \x03(\tR\x13grantTypesSupported\x128\n" + + "\x18response_types_supported\x18\t \x03(\tR\x16responseTypesSupported\x126\n" + + "\x17subject_types_supported\x18\n" + + " \x03(\tR\x15subjectTypesSupported\x12O\n" + + "%id_token_signing_alg_values_supported\x18\v \x03(\tR idTokenSigningAlgValuesSupported\x12G\n" + + " code_challenge_methods_supported\x18\f \x03(\tR\x1dcodeChallengeMethodsSupported\x12)\n" + + "\x10scopes_supported\x18\r \x03(\tR\x0fscopesSupported\x12P\n" + + "%token_endpoint_auth_methods_supported\x18\x0e \x03(\tR!tokenEndpointAuthMethodsSupported\x12)\n" + + "\x10claims_supported\x18\x0f \x03(\tR\x0fclaimsSupported\"z\n" + + "\x0fRefreshTokenRef\x12\x0e\n" + + "\x02id\x18\x01 \x01(\tR\x02id\x12\x1b\n" + + "\tclient_id\x18\x02 \x01(\tR\bclientId\x12\x1d\n" + + "\n" + + "created_at\x18\x05 \x01(\x03R\tcreatedAt\x12\x1b\n" + + "\tlast_used\x18\x06 \x01(\x03R\blastUsed\")\n" + + "\x0eListRefreshReq\x12\x17\n" + + "\auser_id\x18\x01 \x01(\tR\x06userId\"N\n" + + "\x0fListRefreshResp\x12;\n" + + "\x0erefresh_tokens\x18\x01 \x03(\v2\x14.api.RefreshTokenRefR\rrefreshTokens\"H\n" + + "\x10RevokeRefreshReq\x12\x17\n" + + "\auser_id\x18\x01 \x01(\tR\x06userId\x12\x1b\n" + + "\tclient_id\x18\x02 \x01(\tR\bclientId\"0\n" + + "\x11RevokeRefreshResp\x12\x1b\n" + + "\tnot_found\x18\x01 \x01(\bR\bnotFound\"E\n" + + "\x11VerifyPasswordReq\x12\x14\n" + + "\x05email\x18\x01 \x01(\tR\x05email\x12\x1a\n" + + "\bpassword\x18\x02 \x01(\tR\bpassword\"M\n" + + "\x12VerifyPasswordResp\x12\x1a\n" + + "\bverified\x18\x01 \x01(\bR\bverified\x12\x1b\n" + + "\tnot_found\x18\x02 \x01(\bR\bnotFound2\xd1\b\n" + + "\x03Dex\x124\n" + + "\tGetClient\x12\x11.api.GetClientReq\x1a\x12.api.GetClientResp\"\x00\x12=\n" + + "\fCreateClient\x12\x14.api.CreateClientReq\x1a\x15.api.CreateClientResp\"\x00\x12=\n" + + "\fUpdateClient\x12\x14.api.UpdateClientReq\x1a\x15.api.UpdateClientResp\"\x00\x12=\n" + + "\fDeleteClient\x12\x14.api.DeleteClientReq\x1a\x15.api.DeleteClientResp\"\x00\x12C\n" + + "\x0eCreatePassword\x12\x16.api.CreatePasswordReq\x1a\x17.api.CreatePasswordResp\"\x00\x12C\n" + + "\x0eUpdatePassword\x12\x16.api.UpdatePasswordReq\x1a\x17.api.UpdatePasswordResp\"\x00\x12C\n" + + "\x0eDeletePassword\x12\x16.api.DeletePasswordReq\x1a\x17.api.DeletePasswordResp\"\x00\x12>\n" + + "\rListPasswords\x12\x14.api.ListPasswordReq\x1a\x15.api.ListPasswordResp\"\x00\x12F\n" + + "\x0fCreateConnector\x12\x17.api.CreateConnectorReq\x1a\x18.api.CreateConnectorResp\"\x00\x12F\n" + + "\x0fUpdateConnector\x12\x17.api.UpdateConnectorReq\x1a\x18.api.UpdateConnectorResp\"\x00\x12F\n" + + "\x0fDeleteConnector\x12\x17.api.DeleteConnectorReq\x1a\x18.api.DeleteConnectorResp\"\x00\x12A\n" + + "\x0eListConnectors\x12\x15.api.ListConnectorReq\x1a\x16.api.ListConnectorResp\"\x00\x121\n" + + "\n" + + "GetVersion\x12\x0f.api.VersionReq\x1a\x10.api.VersionResp\"\x00\x127\n" + + "\fGetDiscovery\x12\x11.api.DiscoveryReq\x1a\x12.api.DiscoveryResp\"\x00\x12:\n" + + "\vListRefresh\x12\x13.api.ListRefreshReq\x1a\x14.api.ListRefreshResp\"\x00\x12@\n" + + "\rRevokeRefresh\x12\x15.api.RevokeRefreshReq\x1a\x16.api.RevokeRefreshResp\"\x00\x12C\n" + + "\x0eVerifyPassword\x12\x16.api.VerifyPasswordReq\x1a\x17.api.VerifyPasswordResp\"\x00B6\n" + + "\x12com.coreos.dex.apiZ github.com/dexidp/dex/api/v2;apib\x06proto3" var ( file_api_v2_api_proto_rawDescOnce sync.Once diff --git a/cmd/dex/config.go b/cmd/dex/config.go index aa49a18188..682f99e093 100644 --- a/cmd/dex/config.go +++ b/cmd/dex/config.go @@ -24,14 +24,15 @@ import ( // Config is the config format for the main application. type Config struct { - Issuer string `json:"issuer"` - Storage Storage `json:"storage"` - Web Web `json:"web"` - Telemetry Telemetry `json:"telemetry"` - OAuth2 OAuth2 `json:"oauth2"` - GRPC GRPC `json:"grpc"` - Expiry Expiry `json:"expiry"` - Logger Logger `json:"logger"` + Issuer string `json:"issuer"` + Storage Storage `json:"storage"` + Web Web `json:"web"` + Health Health `json:"health"` + OpenTelemetry OpenTelemetry `json:"opentelemetry"` + OAuth2 OAuth2 `json:"oauth2"` + GRPC GRPC `json:"grpc"` + Expiry Expiry `json:"expiry"` + Logger Logger `json:"logger"` Frontend server.WebConfig `json:"frontend"` @@ -233,13 +234,26 @@ func (h *Headers) ToHTTPHeader() http.Header { return header } -// Telemetry is the config format for telemetry including the HTTP server config. -type Telemetry struct { +// Health is the config format for health checks, readiness/liveness probes, profiling, and legacy metrics (e.g., Prometheus endpoint). +type Health struct { HTTP string `json:"http"` // EnableProfiling makes profiling endpoints available via web interface host:port/debug/pprof/ EnableProfiling bool `json:"enableProfiling"` } +// OpenTelemetry is the config format for OpenTelemetry instrumentation (traces, metrics, logs). +type OpenTelemetry struct { + // Enabled toggles OpenTelemetry instrumentation on/off. Defaults to false to avoid breaking changes. + Enabled bool `json:"enabled"` + // ExporterEndpoint is the OTLP collector endpoint (e.g., "localhost:4317" for gRPC). + ExporterEndpoint string `json:"exporter_endpoint"` + // ServiceName overrides the default service name ("dex"). + ServiceName string `json:"service_name"` + // Sampler configures the trace sampling strategy (e.g., "always_on", "traceidratio:0.5"). + Sampler string `json:"sampler"` + // Additional fields can be added here as needed, e.g., for headers, timeouts, or component-specific settings. +} + // GRPC is the config for the gRPC API. type GRPC struct { // The port to listen on. diff --git a/cmd/dex/config_test.go b/cmd/dex/config_test.go index 68abe1f793..759c841cd3 100644 --- a/cmd/dex/config_test.go +++ b/cmd/dex/config_test.go @@ -51,10 +51,7 @@ func TestInvalidConfiguration(t *testing.T) { t.Fatal("this configuration should be invalid") } got := err.Error() - wanted := `invalid Config: - - no issuer specified in config file - - no storage supplied in config file - - must supply a HTTP/HTTPS address to listen on` + wanted := "invalid Config:\n\t-\tno issuer specified in config file\n\t-\tno storage supplied in config file\n\t-\tmust supply a HTTP/HTTPS address to listen on" if got != wanted { t.Fatalf("Expected error message to be %q, got %q", wanted, got) } @@ -79,6 +76,15 @@ web: headers: Strict-Transport-Security: "max-age=31536000; includeSubDomains" +health: + http: 127.0.0.1:5557 + enableProfiling: true + +opentelemetry: + enabled: true + exporter_endpoint: localhost:4317 + sampler: always_on + frontend: dir: ./web extra: @@ -134,7 +140,7 @@ logger: format: "json" additionalFeatures: [ - "ConnectorsCRUD" + "ConnectorsCRUD" ] `) @@ -161,6 +167,15 @@ additionalFeatures: [ StrictTransportSecurity: "max-age=31536000; includeSubDomains", }, }, + Health: Health{ + HTTP: "127.0.0.1:5557", + EnableProfiling: true, + }, + OpenTelemetry: OpenTelemetry{ + Enabled: true, + ExporterEndpoint: "localhost:4317", + Sampler: "always_on", + }, Frontend: server.WebConfig{ Dir: "./web", Extra: map[string]string{ diff --git a/cmd/dex/logger.go b/cmd/dex/logger.go index c1fe6b4a88..6789582954 100644 --- a/cmd/dex/logger.go +++ b/cmd/dex/logger.go @@ -7,6 +7,9 @@ import ( "os" "strings" + "github.com/go-slog/otelslog" + otel "go.opentelemetry.io/contrib/bridges/otelslog" + "github.com/dexidp/dex/server" ) @@ -26,24 +29,26 @@ func newLogger(level slog.Level, format string) (*slog.Logger, error) { default: return nil, fmt.Errorf("log format is not one of the supported values (%s): %s", strings.Join(logFormats, ", "), format) } - - return slog.New(newRequestContextHandler(handler)), nil + handler = otelslog.NewHandler(handler) + return slog.New(newRequestContextHandler(handler, otel.NewHandler("github.com/dexidp/dex/server"))), nil } var _ slog.Handler = requestContextHandler{} type requestContextHandler struct { - handler slog.Handler + handler slog.Handler + otelHandler slog.Handler } -func newRequestContextHandler(handler slog.Handler) slog.Handler { +func newRequestContextHandler(handler, otelHandler slog.Handler) slog.Handler { return requestContextHandler{ - handler: handler, + handler: handler, + otelHandler: otelHandler, } } func (h requestContextHandler) Enabled(ctx context.Context, level slog.Level) bool { - return h.handler.Enabled(ctx, level) + return h.handler.Enabled(ctx, level) && h.otelHandler.Enabled(ctx, level) } func (h requestContextHandler) Handle(ctx context.Context, record slog.Record) error { @@ -55,13 +60,22 @@ func (h requestContextHandler) Handle(ctx context.Context, record slog.Record) e record.AddAttrs(slog.String(string(server.RequestKeyRequestID), v)) } - return h.handler.Handle(ctx, record) + err := h.handler.Handle(ctx, record) + if err != nil { + return err + } + + err = h.otelHandler.Handle(ctx, record) + if err != nil { + return err + } + return nil } func (h requestContextHandler) WithAttrs(attrs []slog.Attr) slog.Handler { - return requestContextHandler{h.handler.WithAttrs(attrs)} + return requestContextHandler{h.handler.WithAttrs(attrs), h.otelHandler.WithAttrs(attrs)} } func (h requestContextHandler) WithGroup(name string) slog.Handler { - return requestContextHandler{h.handler.WithGroup(name)} + return requestContextHandler{h.handler.WithGroup(name), h.otelHandler.WithGroup(name)} } diff --git a/cmd/dex/logger_test.go b/cmd/dex/logger_test.go new file mode 100644 index 0000000000..9e214480d3 --- /dev/null +++ b/cmd/dex/logger_test.go @@ -0,0 +1,29 @@ +package main + +import ( + "log/slog" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestNewLogger(t *testing.T) { + t.Run("JSON", func(t *testing.T) { + logger, err := newLogger(slog.LevelInfo, "json") + require.NoError(t, err) + require.NotEqual(t, (*slog.Logger)(nil), logger) + }) + + t.Run("Text", func(t *testing.T) { + logger, err := newLogger(slog.LevelError, "text") + require.NoError(t, err) + require.NotEqual(t, (*slog.Logger)(nil), logger) + }) + + t.Run("Unknown", func(t *testing.T) { + logger, err := newLogger(slog.LevelError, "gofmt") + require.Error(t, err) + require.Equal(t, "log format is not one of the supported values (json, text): gofmt", err.Error()) + require.Equal(t, (*slog.Logger)(nil), logger) + }) +} diff --git a/cmd/dex/serve.go b/cmd/dex/serve.go index ac715e606f..6827217f56 100644 --- a/cmd/dex/serve.go +++ b/cmd/dex/serve.go @@ -24,18 +24,20 @@ import ( gosundheithttp "github.com/AppsFlyer/go-sundheit/http" "github.com/fsnotify/fsnotify" "github.com/ghodss/yaml" - grpcprometheus "github.com/grpc-ecosystem/go-grpc-prometheus" "github.com/oklog/run" - "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/collectors" - "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/spf13/cobra" + "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc" + "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" + "go.opentelemetry.io/otel/sdk/resource" + semconv "go.opentelemetry.io/otel/semconv/v1.34.0" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/reflection" "github.com/dexidp/dex/api/v2" "github.com/dexidp/dex/pkg/featureflags" + "github.com/dexidp/dex/pkg/otel" + "github.com/dexidp/dex/pkg/otel/traces" "github.com/dexidp/dex/server" "github.com/dexidp/dex/storage" ) @@ -45,21 +47,12 @@ type serveOptions struct { config string // Flags - webHTTPAddr string - webHTTPSAddr string - telemetryAddr string - grpcAddr string + webHTTPAddr string + webHTTPSAddr string + healthAddr string + grpcAddr string } -var buildInfo = prometheus.NewGaugeVec( - prometheus.GaugeOpts{ - Name: "build_info", - Namespace: "dex", - Help: "A metric with a constant '1' value labeled by version from which Dex was built.", - }, - []string{"version", "go_version", "platform"}, -) - func commandServe() *cobra.Command { options := serveOptions{} @@ -82,7 +75,7 @@ func commandServe() *cobra.Command { flags.StringVar(&options.webHTTPAddr, "web-http-addr", "", "Web HTTP address") flags.StringVar(&options.webHTTPSAddr, "web-https-addr", "", "Web HTTPS address") - flags.StringVar(&options.telemetryAddr, "telemetry-addr", "", "Telemetry address") + flags.StringVar(&options.healthAddr, "health-addr", "", "Health address") flags.StringVar(&options.grpcAddr, "grpc-addr", "", "gRPC API address") return cmd @@ -102,6 +95,9 @@ func runServe(options serveOptions) error { applyConfigOverrides(options, &c) + ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt) + defer cancel() + logger, err := newLogger(c.Logger.Level, c.Logger.Format) if err != nil { return fmt.Errorf("invalid config: %v", err) @@ -126,29 +122,69 @@ func runServe(options serveOptions) error { logger.Info("config issuer", "issuer", c.Issuer) - prometheusRegistry := prometheus.NewRegistry() + var shutdownTracerProvider func(context.Context) error + var shutdownMeterProvider func(context.Context) error + var shutdownLogProvider func(context.Context) error - prometheusRegistry.MustRegister(buildInfo) - recordBuildInfo() + if c.OpenTelemetry.Enabled { + endpoint := c.OpenTelemetry.ExporterEndpoint + if endpoint == "" { + endpoint = "localhost:4317" + } + conn, err := otel.InitConn(endpoint) + if err != nil { + logger.Error("failed to initialize OTEL connection, disabling OTEL", "err", err) + } else { + serviceNameVal := semconv.ServiceNameKey.String("dex") + if c.OpenTelemetry.ServiceName != "" { + serviceNameVal = semconv.ServiceNameKey.String(c.OpenTelemetry.ServiceName) + } - err = prometheusRegistry.Register(collectors.NewGoCollector()) - if err != nil { - return fmt.Errorf("failed to register Go runtime metrics: %v", err) - } + res, err := resource.Merge(resource.Default(), resource.NewWithAttributes(semconv.SchemaURL, serviceNameVal)) + if err != nil { + logger.Error("failed to create OTEL resource, disabling OTEL", "err", err) + } else { + shutdownTracerProvider, err = traces.InitTracerProvider(ctx, res, conn, c.OpenTelemetry.Sampler) + if err != nil { + logger.Error("failed to initialize tracer provider, disabling tracing", "err", err) + shutdownTracerProvider = nil + } - err = prometheusRegistry.Register(collectors.NewProcessCollector(collectors.ProcessCollectorOpts{})) - if err != nil { - return fmt.Errorf("failed to register process metrics: %v", err) - } + shutdownMeterProvider, err = otel.InitMeterProvider(ctx, res, conn) + if err != nil { + logger.Error("failed to initialize meter provider, disabling metrics", "err", err) + shutdownMeterProvider = nil + } - grpcMetrics := grpcprometheus.NewServerMetrics() - err = prometheusRegistry.Register(grpcMetrics) - if err != nil { - return fmt.Errorf("failed to register gRPC server metrics: %v", err) + shutdownLogProvider, err = otel.InitLogProvider(ctx, res, conn) + if err != nil { + logger.Error("failed to initialize log provider, disabling logs export", "err", err) + shutdownLogProvider = nil + } + } + } } - var grpcOptions []grpc.ServerOption + defer func() { + if shutdownTracerProvider != nil { + if err := shutdownTracerProvider(ctx); err != nil { + logger.Error("failed to shutdown TracerProvider", "err", err) + } + } + if shutdownMeterProvider != nil { + if err := shutdownMeterProvider(ctx); err != nil { + logger.Error("failed to shutdown MeterProvider", "err", err) + } + } + if shutdownLogProvider != nil { + if err := shutdownLogProvider(ctx); err != nil { + logger.Error("failed to shutdown LogProvider", "err", err) + } + } + }() + var grpcOptions []grpc.ServerOption + grpcOptions = append(grpcOptions, grpc.StatsHandler(otelgrpc.NewServerHandler())) allowedTLSCiphers := []uint16{ tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, @@ -185,15 +221,6 @@ func runServe(options serveOptions) error { if err != nil { return fmt.Errorf("invalid config: get gRPC TLS: %v", err) } - - if c.GRPC.TLSClientCA != "" { - // Only add metrics if client auth is enabled - grpcOptions = append(grpcOptions, - grpc.StreamInterceptor(grpcMetrics.StreamServerInterceptor()), - grpc.UnaryInterceptor(grpcMetrics.UnaryServerInterceptor()), - ) - } - grpcOptions = append(grpcOptions, grpc.Creds(credentials.NewTLS(tlsConfig))) } @@ -304,7 +331,6 @@ func runServe(options serveOptions) error { Web: c.Frontend, Logger: logger, Now: now, - PrometheusRegistry: prometheusRegistry, HealthChecker: healthChecker, ContinueOnConnectorFailure: featureflags.ContinueOnConnectorFailure.Enabled(), } @@ -364,19 +390,18 @@ func runServe(options serveOptions) error { return fmt.Errorf("failed to initialize server: %v", err) } - telemetryRouter := http.NewServeMux() - telemetryRouter.Handle("/metrics", promhttp.HandlerFor(prometheusRegistry, promhttp.HandlerOpts{})) + healthRouter := http.NewServeMux() // Configure health checker { handler := gosundheithttp.HandleHealthJSON(healthChecker) - telemetryRouter.Handle("/healthz", handler) + healthRouter.Handle("/healthz", handler) // Kubernetes style health checks - telemetryRouter.HandleFunc("/healthz/live", func(w http.ResponseWriter, _ *http.Request) { + healthRouter.HandleFunc("/healthz/live", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("ok")) }) - telemetryRouter.Handle("/healthz/ready", handler) + healthRouter.Handle("/healthz/ready", handler) } healthChecker.RegisterCheck( @@ -390,23 +415,23 @@ func runServe(options serveOptions) error { var group run.Group - // Set up telemetry server - if c.Telemetry.HTTP != "" { - const name = "telemetry" + // Set up health server + if c.Health.HTTP != "" { + const name = "health" - logger.Info("listening on", "server", name, "address", c.Telemetry.HTTP) + logger.Info("listening on", "server", name, "address", c.Health.HTTP) - l, err := net.Listen("tcp", c.Telemetry.HTTP) + l, err := net.Listen("tcp", c.Health.HTTP) if err != nil { - return fmt.Errorf("listening (%s) on %s: %v", name, c.Telemetry.HTTP, err) + return fmt.Errorf("listening (%s) on %s: %v", name, c.Health.HTTP, err) } - if c.Telemetry.EnableProfiling { - pprofHandler(telemetryRouter) + if c.Health.EnableProfiling { + pprofHandler(healthRouter) } server := &http.Server{ - Handler: telemetryRouter, + Handler: healthRouter, } defer server.Close() @@ -435,7 +460,7 @@ func runServe(options serveOptions) error { } server := &http.Server{ - Handler: serv, + Handler: otelhttp.NewHandler(serv, "dex-http-server", otelhttp.WithFilter(omitStatic)), } defer server.Close() @@ -485,7 +510,7 @@ func runServe(options serveOptions) error { } server := &http.Server{ - Handler: serv, + Handler: otelhttp.NewHandler(serv, "dex-https-server", otelhttp.WithFilter(omitStatic)), TLSConfig: tlsConfig, } defer server.Close() @@ -515,7 +540,6 @@ func runServe(options serveOptions) error { grpcSrv := grpc.NewServer(grpcOptions...) api.RegisterDexServer(grpcSrv, server.NewAPI(serverConfig.Storage, logger, version, serv)) - grpcMetrics.InitializeMetrics(grpcSrv) if c.GRPC.Reflection { logger.Info("enabling reflection in grpc service") reflection.Register(grpcSrv) @@ -539,6 +563,16 @@ func runServe(options serveOptions) error { return nil } +func omitStatic(r *http.Request) bool { + if strings.HasPrefix(r.URL.Path, "/dex/static") { + return false + } + if strings.HasPrefix(r.URL.Path, "/dex/theme") { + return false + } + return true +} + func applyConfigOverrides(options serveOptions, config *Config) { if options.webHTTPAddr != "" { config.Web.HTTP = options.webHTTPAddr @@ -548,8 +582,8 @@ func applyConfigOverrides(options serveOptions, config *Config) { config.Web.HTTPS = options.webHTTPSAddr } - if options.telemetryAddr != "" { - config.Telemetry.HTTP = options.telemetryAddr + if options.healthAddr != "" { + config.Health.HTTP = options.healthAddr } if options.grpcAddr != "" { @@ -689,8 +723,3 @@ func loadTLSConfig(certFile, keyFile, caFile string, baseConfig *tls.Config) (*t } return loadedConfig, nil } - -// recordBuildInfo publishes information about Dex version and runtime info through an info metric (gauge). -func recordBuildInfo() { - buildInfo.WithLabelValues(version, runtime.Version(), fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)).Set(1) -} diff --git a/cmd/dex/serve_test.go b/cmd/dex/serve_test.go index 9e214480d3..6e8edcc660 100644 --- a/cmd/dex/serve_test.go +++ b/cmd/dex/serve_test.go @@ -1,29 +1,75 @@ package main import ( - "log/slog" + "net/http" + "net/url" "testing" - - "github.com/stretchr/testify/require" ) -func TestNewLogger(t *testing.T) { - t.Run("JSON", func(t *testing.T) { - logger, err := newLogger(slog.LevelInfo, "json") - require.NoError(t, err) - require.NotEqual(t, (*slog.Logger)(nil), logger) - }) - - t.Run("Text", func(t *testing.T) { - logger, err := newLogger(slog.LevelError, "text") - require.NoError(t, err) - require.NotEqual(t, (*slog.Logger)(nil), logger) - }) - - t.Run("Unknown", func(t *testing.T) { - logger, err := newLogger(slog.LevelError, "gofmt") - require.Error(t, err) - require.Equal(t, "log format is not one of the supported values (json, text): gofmt", err.Error()) - require.Equal(t, (*slog.Logger)(nil), logger) - }) +func Test_omitStatic(t *testing.T) { + type args struct { + r *http.Request + } + tests := []struct { + name string + args args + want bool + }{ + { + name: "static prefix", + args: args{ + r: &http.Request{URL: &url.URL{Path: "/dex/static/file.css"}}, + }, + want: false, + }, + { + name: "theme prefix", + args: args{ + r: &http.Request{URL: &url.URL{Path: "/dex/theme/logo.png"}}, + }, + want: false, + }, + { + name: "root path", + args: args{ + r: &http.Request{URL: &url.URL{Path: "/"}}, + }, + want: true, + }, + { + name: "other dex path", + args: args{ + r: &http.Request{URL: &url.URL{Path: "/dex/other"}}, + }, + want: true, + }, + { + name: "non-dex path", + args: args{ + r: &http.Request{URL: &url.URL{Path: "/api"}}, + }, + want: true, + }, + { + name: "case sensitive static", + args: args{ + r: &http.Request{URL: &url.URL{Path: "/DEX/static"}}, + }, + want: true, + }, + { + name: "empty path", + args: args{ + r: &http.Request{URL: &url.URL{Path: ""}}, + }, + want: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := omitStatic(tt.args.r); got != tt.want { + t.Errorf("omitStatic() = %v, want %v", got, tt.want) + } + }) + } } diff --git a/connector/authproxy/authproxy.go b/connector/authproxy/authproxy.go index 2419d3b7ce..cdf024cab2 100644 --- a/connector/authproxy/authproxy.go +++ b/connector/authproxy/authproxy.go @@ -11,6 +11,7 @@ import ( "strings" "github.com/dexidp/dex/connector" + "github.com/dexidp/dex/pkg/otel/traces" ) // Config holds the configuration parameters for a connector which returns an @@ -90,6 +91,8 @@ func (m *callback) LoginURL(s connector.Scopes, callbackURL, state string) (stri // HandleCallback parses the request and returns the user's identity func (m *callback) HandleCallback(s connector.Scopes, r *http.Request) (connector.Identity, error) { + _, span := traces.InstrumentHandler(r) + defer span.End() remoteUser := r.Header.Get(m.userHeader) if remoteUser == "" { return connector.Identity{}, fmt.Errorf("required HTTP header %s is not set", m.userHeader) diff --git a/connector/github/github.go b/connector/github/github.go index 18a56628af..f5222ee4c3 100644 --- a/connector/github/github.go +++ b/connector/github/github.go @@ -19,6 +19,7 @@ import ( "github.com/dexidp/dex/connector" groups_pkg "github.com/dexidp/dex/pkg/groups" "github.com/dexidp/dex/pkg/httpclient" + "github.com/dexidp/dex/pkg/otel/traces" ) const ( @@ -215,6 +216,8 @@ func (e *oauth2Error) Error() string { } func (c *githubConnector) HandleCallback(s connector.Scopes, r *http.Request) (identity connector.Identity, err error) { + ctx, span := traces.InstrumentationTracer(r.Context(), "dex.github.callback") + defer span.End() q := r.URL.Query() if errType := q.Get("error"); errType != "" { return identity, &oauth2Error{errType, q.Get("error_description")} @@ -222,7 +225,6 @@ func (c *githubConnector) HandleCallback(s connector.Scopes, r *http.Request) (i oauth2Config := c.oauth2Config(s) - ctx := r.Context() // GitHub Enterprise account if c.httpClient != nil { ctx = context.WithValue(r.Context(), oauth2.HTTPClient, c.httpClient) @@ -278,6 +280,8 @@ func (c *githubConnector) HandleCallback(s connector.Scopes, r *http.Request) (i } func (c *githubConnector) Refresh(ctx context.Context, s connector.Scopes, identity connector.Identity) (connector.Identity, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.github.Refresh") + defer span.End() if len(identity.ConnectorData) == 0 { return identity, errors.New("no upstream access token found") } @@ -315,6 +319,8 @@ func (c *githubConnector) Refresh(ctx context.Context, s connector.Scopes, ident // getGroups retrieves GitHub orgs and teams a user is in, if any. func (c *githubConnector) getGroups(ctx context.Context, client *http.Client, groupScope bool, userLogin string) ([]string, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.github.getGroups") + defer span.End() switch { case len(c.orgs) > 0: return c.groupsForOrgs(ctx, client, userLogin) @@ -341,6 +347,8 @@ func formatTeamName(org string, team string) string { // // from at least 1 org, or member of org with no teams func (c *githubConnector) groupsForOrgs(ctx context.Context, client *http.Client, userName string) ([]string, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.github.groupsForOrgs") + defer span.End() groups := make([]string, 0) var inOrgNoTeams bool for _, org := range c.orgs { @@ -376,6 +384,8 @@ func (c *githubConnector) groupsForOrgs(ctx context.Context, client *http.Client } func (c *githubConnector) userGroups(ctx context.Context, client *http.Client) ([]string, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.github.userGroups") + defer span.End() orgs, err := c.userOrgs(ctx, client) if err != nil { return nil, err @@ -401,6 +411,8 @@ func (c *githubConnector) userGroups(ctx context.Context, client *http.Client) ( // userOrgs retrieves list of current user orgs func (c *githubConnector) userOrgs(ctx context.Context, client *http.Client) ([]string, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.github.userOrgs") + defer span.End() groups := make([]string, 0) apiURL := c.apiURL + "/user/orgs" for { @@ -428,6 +440,8 @@ func (c *githubConnector) userOrgs(ctx context.Context, client *http.Client) ([] // userOrgTeams retrieves teams which current user belongs to. // Method returns a map where key is an org name and value list of teams under the org. func (c *githubConnector) userOrgTeams(ctx context.Context, client *http.Client) (map[string][]string, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.github.userOrgTeams") + defer span.End() groups := make(map[string][]string) apiURL := c.apiURL + "/user/teams" for { @@ -457,6 +471,8 @@ func (c *githubConnector) userOrgTeams(ctx context.Context, client *http.Client) // is returned if one exists. Any errors encountered when building requests, // sending requests, and reading and decoding response data are returned. func get(ctx context.Context, client *http.Client, apiURL string, v interface{}) (string, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.github.get") + defer span.End() req, err := http.NewRequest("GET", apiURL, nil) if err != nil { return "", fmt.Errorf("github: new req: %v", err) @@ -525,6 +541,8 @@ type user struct { // The HTTP client is expected to be constructed by the golang.org/x/oauth2 package, // which inserts a bearer token as part of the request. func (c *githubConnector) user(ctx context.Context, client *http.Client) (user, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.github.user") + defer span.End() // https://developer.github.com/v3/users/#get-the-authenticated-user var u user if _, err := get(ctx, client, c.apiURL+"/user", &u); err != nil { @@ -559,6 +577,8 @@ type userEmail struct { // The HTTP client is expected to be constructed by the golang.org/x/oauth2 package, // which inserts a bearer token as part of the request. func (c *githubConnector) userEmail(ctx context.Context, client *http.Client) (string, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.github.userEmail") + defer span.End() var ( primaryEmail userEmail preferredEmails []userEmail @@ -648,6 +668,8 @@ func (c *githubConnector) isPreferredEmailDomain(domain string) bool { // The HTTP passed client is expected to be constructed by the golang.org/x/oauth2 package, // which inserts a bearer token as part of the request. func (c *githubConnector) userInOrg(ctx context.Context, client *http.Client, userName, orgName string) (bool, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.github.userInOrg") + defer span.End() // requester == user, so GET-ing this endpoint should return 404/302 if user // is not a member // @@ -694,6 +716,8 @@ type org struct { // The HTTP passed client is expected to be constructed by the golang.org/x/oauth2 package, // which inserts a bearer token as part of the request. func (c *githubConnector) teamsForOrg(ctx context.Context, client *http.Client, orgName string) ([]string, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.github.teamsForOrg") + defer span.End() apiURL, groups := c.apiURL+"/user/teams", []string{} for { // https://developer.github.com/v3/orgs/teams/#list-user-teams diff --git a/connector/microsoft/microsoft.go b/connector/microsoft/microsoft.go index 2fcf6a7515..0233fd162f 100644 --- a/connector/microsoft/microsoft.go +++ b/connector/microsoft/microsoft.go @@ -192,6 +192,8 @@ func (c *microsoftConnector) LoginURL(scopes connector.Scopes, callbackURL, stat } func (c *microsoftConnector) HandleCallback(s connector.Scopes, r *http.Request) (identity connector.Identity, err error) { + ctx := r.Context() + q := r.URL.Query() if errType := q.Get("error"); errType != "" { return identity, &oauth2Error{errType, q.Get("error_description")} @@ -199,13 +201,10 @@ func (c *microsoftConnector) HandleCallback(s connector.Scopes, r *http.Request) oauth2Config := c.oauth2Config(s) - ctx := r.Context() - token, err := oauth2Config.Exchange(ctx, q.Get("code")) if err != nil { return identity, fmt.Errorf("microsoft: failed to get token: %v", err) } - client := oauth2Config.Client(ctx, token) user, err := c.user(ctx, client) @@ -229,6 +228,7 @@ func (c *microsoftConnector) HandleCallback(s connector.Scopes, r *http.Request) if err != nil { return identity, fmt.Errorf("microsoft: get groups: %v", err) } + identity.Groups = groups } diff --git a/connector/mock/connectortest.go b/connector/mock/connectortest.go index 7e5979a992..10d258d22d 100644 --- a/connector/mock/connectortest.go +++ b/connector/mock/connectortest.go @@ -10,6 +10,7 @@ import ( "net/url" "github.com/dexidp/dex/connector" + "github.com/dexidp/dex/pkg/otel/traces" ) // NewCallbackConnector returns a mock connector which requires no user interaction. It always returns @@ -58,15 +59,21 @@ var connectorData = []byte("foobar") // HandleCallback parses the request and returns the user's identity func (m *Callback) HandleCallback(s connector.Scopes, r *http.Request) (connector.Identity, error) { + _, span := traces.InstrumentationTracer(r.Context(), "dex.mock.Callback.HandleCallback") + defer span.End() return m.Identity, nil } // Refresh updates the identity during a refresh token request. func (m *Callback) Refresh(ctx context.Context, s connector.Scopes, identity connector.Identity) (connector.Identity, error) { + _, span := traces.InstrumentationTracer(ctx, "dex.mock.Callback.Refresh") + defer span.End() return m.Identity, nil } func (m *Callback) TokenIdentity(ctx context.Context, subjectTokenType, subjectToken string) (connector.Identity, error) { + _, span := traces.InstrumentationTracer(ctx, "dex.mock.Callback.TokenIdentity") + defer span.End() return m.Identity, nil } @@ -106,6 +113,8 @@ type passwordConnector struct { func (p passwordConnector) Close() error { return nil } func (p passwordConnector) Login(ctx context.Context, s connector.Scopes, username, password string) (identity connector.Identity, validPassword bool, err error) { + _, span := traces.InstrumentationTracer(ctx, "dex.mock.PasswordConnector.Login") + defer span.End() if username == p.username && password == p.password { return connector.Identity{ UserID: "0-385-28089-0", @@ -120,6 +129,8 @@ func (p passwordConnector) Login(ctx context.Context, s connector.Scopes, userna func (p passwordConnector) Prompt() string { return "" } -func (p passwordConnector) Refresh(_ context.Context, _ connector.Scopes, identity connector.Identity) (connector.Identity, error) { +func (p passwordConnector) Refresh(ctx context.Context, _ connector.Scopes, identity connector.Identity) (connector.Identity, error) { + _, span := traces.InstrumentationTracer(ctx, "dex.mock.PasswordConnector.Refresh") + defer span.End() return identity, nil } diff --git a/connector/oauth/oauth.go b/connector/oauth/oauth.go index 413a813a08..6c031f3eae 100644 --- a/connector/oauth/oauth.go +++ b/connector/oauth/oauth.go @@ -14,6 +14,7 @@ import ( "github.com/dexidp/dex/connector" "github.com/dexidp/dex/pkg/httpclient" + "github.com/dexidp/dex/pkg/otel/traces" ) type oauthConnector struct { @@ -133,6 +134,8 @@ func (c *oauthConnector) LoginURL(scopes connector.Scopes, callbackURL, state st } func (c *oauthConnector) HandleCallback(s connector.Scopes, r *http.Request) (identity connector.Identity, err error) { + ctx, span := traces.InstrumentationTracer(r.Context(), "dex.oauth.HandleCallback") + defer span.End() q := r.URL.Query() if errType := q.Get("error"); errType != "" { return identity, errors.New(q.Get("error_description")) @@ -146,7 +149,7 @@ func (c *oauthConnector) HandleCallback(s connector.Scopes, r *http.Request) (id Scopes: c.scopes, } - ctx := context.WithValue(r.Context(), oauth2.HTTPClient, c.httpClient) + ctx = context.WithValue(ctx, oauth2.HTTPClient, c.httpClient) token, err := oauth2Config.Exchange(ctx, q.Get("code")) if err != nil { diff --git a/connector/oidc/oidc.go b/connector/oidc/oidc.go index 1cf2b62ad8..22704e1cc7 100644 --- a/connector/oidc/oidc.go +++ b/connector/oidc/oidc.go @@ -19,6 +19,7 @@ import ( "github.com/dexidp/dex/connector" groups_pkg "github.com/dexidp/dex/pkg/groups" "github.com/dexidp/dex/pkg/httpclient" + "github.com/dexidp/dex/pkg/otel/traces" ) // Config holds configuration options for OpenID Connect logins. @@ -125,6 +126,8 @@ func (o *ProviderDiscoveryOverrides) Empty() bool { } func getProvider(ctx context.Context, issuer string, overrides ProviderDiscoveryOverrides) (*oidc.Provider, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.oidc.getProvider") + defer span.End() provider, err := oidc.NewProvider(ctx, issuer) if err != nil { return nil, fmt.Errorf("failed to get provider: %v", err) @@ -237,11 +240,19 @@ func (c *Config) Open(id string, logger *slog.Logger) (conn connector.Connector, } bgctx, cancel := context.WithCancel(context.Background()) - ctx := context.WithValue(bgctx, oauth2.HTTPClient, httpClient) + ctx, span := traces.InstrumentationTracer(bgctx, "dex.oidc.Open") + defer span.End() + ctx = context.WithValue(ctx, oauth2.HTTPClient, httpClient) if c.IssuerAlias != "" { ctx = oidc.InsecureIssuerURLContext(ctx, c.IssuerAlias) } - provider, err := getProvider(ctx, c.Issuer, c.ProviderDiscoveryOverrides) + + // Add timeout for provider discovery + discoveryTimeout := 10 * time.Second // Adjustable; e.g., based on config if needed + discoveryCtx, discoveryCancel := context.WithTimeout(ctx, discoveryTimeout) + defer discoveryCancel() + + provider, err := getProvider(discoveryCtx, c.Issuer, c.ProviderDiscoveryOverrides) if err != nil { cancel() return nil, err @@ -394,12 +405,14 @@ const ( ) func (c *oidcConnector) HandleCallback(s connector.Scopes, r *http.Request) (identity connector.Identity, err error) { + ctx, span := traces.InstrumentationTracer(r.Context(), "dex.oidc.HandleCallback") + defer span.End() q := r.URL.Query() if errType := q.Get("error"); errType != "" { return identity, &oauth2Error{errType, q.Get("error_description")} } - ctx := context.WithValue(r.Context(), oauth2.HTTPClient, c.httpClient) + ctx = context.WithValue(ctx, oauth2.HTTPClient, c.httpClient) token, err := c.oauth2Config.Exchange(ctx, q.Get("code")) if err != nil { @@ -410,6 +423,8 @@ func (c *oidcConnector) HandleCallback(s connector.Scopes, r *http.Request) (ide // Refresh is used to refresh a session with the refresh token provided by the IdP func (c *oidcConnector) Refresh(ctx context.Context, s connector.Scopes, identity connector.Identity) (connector.Identity, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.oidc.Refresh") + defer span.End() cd := connectorData{} err := json.Unmarshal(identity.ConnectorData, &cd) if err != nil { @@ -430,6 +445,9 @@ func (c *oidcConnector) Refresh(ctx context.Context, s connector.Scopes, identit } func (c *oidcConnector) TokenIdentity(ctx context.Context, subjectTokenType, subjectToken string) (connector.Identity, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.oidc.TokenIdentity") + defer span.End() + ctx = context.WithValue(ctx, oauth2.HTTPClient, c.httpClient) var identity connector.Identity ctx = context.WithValue(ctx, oauth2.HTTPClient, c.httpClient) @@ -442,6 +460,8 @@ func (c *oidcConnector) TokenIdentity(ctx context.Context, subjectTokenType, sub } func (c *oidcConnector) createIdentity(ctx context.Context, identity connector.Identity, token *oauth2.Token, caller caller) (connector.Identity, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.oidc.createIdentity") + defer span.End() var claims map[string]interface{} if rawIDToken, ok := token.Extra("id_token").(string); ok { diff --git a/examples/go.mod b/examples/go.mod index 492910d498..823cac6f9f 100644 --- a/examples/go.mod +++ b/examples/go.mod @@ -6,18 +6,33 @@ require ( github.com/coreos/go-oidc/v3 v3.14.1 github.com/dexidp/dex/api/v2 v2.3.0 github.com/spf13/cobra v1.9.1 + go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.62.0 + go.opentelemetry.io/otel v1.37.0 + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.37.0 + go.opentelemetry.io/otel/sdk v1.37.0 golang.org/x/oauth2 v0.30.0 google.golang.org/grpc v1.74.2 ) require ( + github.com/cenkalti/backoff/v5 v5.0.2 // indirect github.com/go-jose/go-jose/v4 v4.0.5 // indirect + github.com/go-logr/logr v1.4.3 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.1 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/spf13/pflag v1.0.6 // indirect - golang.org/x/crypto v0.38.0 // indirect - golang.org/x/net v0.40.0 // indirect + go.opentelemetry.io/auto/sdk v1.1.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.37.0 // indirect + go.opentelemetry.io/otel/metric v1.37.0 // indirect + go.opentelemetry.io/otel/trace v1.37.0 // indirect + go.opentelemetry.io/proto/otlp v1.7.0 // indirect + golang.org/x/crypto v0.39.0 // indirect + golang.org/x/net v0.41.0 // indirect golang.org/x/sys v0.33.0 // indirect - golang.org/x/text v0.25.0 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20250528174236-200df99c418a // indirect + golang.org/x/text v0.26.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822 // indirect google.golang.org/protobuf v1.36.6 // indirect ) diff --git a/examples/go.sum b/examples/go.sum index b8cc037b7a..9452f4c57d 100644 --- a/examples/go.sum +++ b/examples/go.sum @@ -1,3 +1,5 @@ +github.com/cenkalti/backoff/v5 v5.0.2 h1:rIfFVxEf1QsI7E1ZHfp/B4DF/6QBAUhmgkxc0H7Zss8= +github.com/cenkalti/backoff/v5 v5.0.2/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= github.com/coreos/go-oidc/v3 v3.14.1 h1:9ePWwfdwC4QKRlCXsJGou56adA/owXczOzwKdOumLqk= github.com/coreos/go-oidc/v3 v3.14.1/go.mod h1:HaZ3szPaZ0e4r6ebqvsLWlk2Tn+aejfmrfah6hnSYEU= github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= @@ -7,6 +9,7 @@ github.com/dexidp/dex/api/v2 v2.3.0 h1:gv79YqTBTGU6z/QE3RNFzlS6KrPRUudVUN8o858gp github.com/dexidp/dex/api/v2 v2.3.0/go.mod h1:y9As69T4WZOERCS/CfB9D8Dbb12tafU9ywv2ZZLf4EI= github.com/go-jose/go-jose/v4 v4.0.5 h1:M6T8+mKZl/+fNNuFHvGIzDz7BTLQPIounk/b9dw3AaE= github.com/go-jose/go-jose/v4 v4.0.5/go.mod h1:s3P1lRrkT8igV8D9OjyL4WRyHvjB6a4JSllnOrmmBOA= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= @@ -17,6 +20,8 @@ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.1 h1:X5VWvz21y3gzm9Nw/kaUeku/1+uBhcekkmy4IkffJww= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.1/go.mod h1:Zanoh4+gvIgluNqcfMVTJueD4wSS5hT7zTt4Mrutd90= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= @@ -30,28 +35,40 @@ github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOf github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= -go.opentelemetry.io/otel v1.36.0 h1:UumtzIklRBY6cI/lllNZlALOF5nNIzJVb16APdvgTXg= -go.opentelemetry.io/otel v1.36.0/go.mod h1:/TcFMXYjyRNh8khOAO9ybYkqaDBb/70aVwkNML4pP8E= -go.opentelemetry.io/otel/metric v1.36.0 h1:MoWPKVhQvJ+eeXWHFBOPoBOi20jh6Iq2CcCREuTYufE= -go.opentelemetry.io/otel/metric v1.36.0/go.mod h1:zC7Ks+yeyJt4xig9DEw9kuUFe5C3zLbVjV2PzT6qzbs= -go.opentelemetry.io/otel/sdk v1.36.0 h1:b6SYIuLRs88ztox4EyrvRti80uXIFy+Sqzoh9kFULbs= -go.opentelemetry.io/otel/sdk v1.36.0/go.mod h1:+lC+mTgD+MUWfjJubi2vvXWcVxyr9rmlshZni72pXeY= -go.opentelemetry.io/otel/sdk/metric v1.36.0 h1:r0ntwwGosWGaa0CrSt8cuNuTcccMXERFwHX4dThiPis= -go.opentelemetry.io/otel/sdk/metric v1.36.0/go.mod h1:qTNOhFDfKRwX0yXOqJYegL5WRaW376QbB7P4Pb0qva4= -go.opentelemetry.io/otel/trace v1.36.0 h1:ahxWNuqZjpdiFAyrIoQ4GIiAIhxAunQR6MUoKrsNd4w= -go.opentelemetry.io/otel/trace v1.36.0/go.mod h1:gQ+OnDZzrybY4k4seLzPAWNwVBBVlF2szhehOBB/tGA= -golang.org/x/crypto v0.38.0 h1:jt+WWG8IZlBnVbomuhg2Mdq0+BBQaHbtqHEFEigjUV8= -golang.org/x/crypto v0.38.0/go.mod h1:MvrbAqul58NNYPKnOra203SB9vpuZW0e+RRZV+Ggqjw= -golang.org/x/net v0.40.0 h1:79Xs7wF06Gbdcg4kdCCIQArK11Z1hr5POQ6+fIYHNuY= -golang.org/x/net v0.40.0/go.mod h1:y0hY0exeL2Pku80/zKK7tpntoX23cqL3Oa6njdgRtds= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.62.0 h1:rbRJ8BBoVMsQShESYZ0FkvcITu8X8QNwJogcLUmDNNw= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.62.0/go.mod h1:ru6KHrNtNHxM4nD/vd6QrLVWgKhxPYgblq4VAtNawTQ= +go.opentelemetry.io/otel v1.37.0 h1:9zhNfelUvx0KBfu/gb+ZgeAfAgtWrfHJZcAqFC228wQ= +go.opentelemetry.io/otel v1.37.0/go.mod h1:ehE/umFRLnuLa/vSccNq9oS1ErUlkkK71gMcN34UG8I= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.37.0 h1:Ahq7pZmv87yiyn3jeFz/LekZmPLLdKejuO3NcK9MssM= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.37.0/go.mod h1:MJTqhM0im3mRLw1i8uGHnCvUEeS7VwRyxlLC78PA18M= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.37.0 h1:EtFWSnwW9hGObjkIdmlnWSydO+Qs8OwzfzXLUPg4xOc= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.37.0/go.mod h1:QjUEoiGCPkvFZ/MjK6ZZfNOS6mfVEVKYE99dFhuN2LI= +go.opentelemetry.io/otel/metric v1.37.0 h1:mvwbQS5m0tbmqML4NqK+e3aDiO02vsf/WgbsdpcPoZE= +go.opentelemetry.io/otel/metric v1.37.0/go.mod h1:04wGrZurHYKOc+RKeye86GwKiTb9FKm1WHtO+4EVr2E= +go.opentelemetry.io/otel/sdk v1.37.0 h1:ItB0QUqnjesGRvNcmAcU0LyvkVyGJ2xftD29bWdDvKI= +go.opentelemetry.io/otel/sdk v1.37.0/go.mod h1:VredYzxUvuo2q3WRcDnKDjbdvmO0sCzOvVAiY+yUkAg= +go.opentelemetry.io/otel/sdk/metric v1.37.0 h1:90lI228XrB9jCMuSdA0673aubgRobVZFhbjxHHspCPc= +go.opentelemetry.io/otel/sdk/metric v1.37.0/go.mod h1:cNen4ZWfiD37l5NhS+Keb5RXVWZWpRE+9WyVCpbo5ps= +go.opentelemetry.io/otel/trace v1.37.0 h1:HLdcFNbRQBE2imdSEgm/kwqmQj1Or1l/7bW6mxVK7z4= +go.opentelemetry.io/otel/trace v1.37.0/go.mod h1:TlgrlQ+PtQO5XFerSPUYG0JSgGyryXewPGyayAWSBS0= +go.opentelemetry.io/proto/otlp v1.7.0 h1:jX1VolD6nHuFzOYso2E73H85i92Mv8JQYk0K9vz09os= +go.opentelemetry.io/proto/otlp v1.7.0/go.mod h1:fSKjH6YJ7HDlwzltzyMj036AJ3ejJLCgCSHGj4efDDo= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +golang.org/x/crypto v0.39.0 h1:SHs+kF4LP+f+p14esP5jAoDpHU8Gu/v9lFRK6IT5imM= +golang.org/x/crypto v0.39.0/go.mod h1:L+Xg3Wf6HoL4Bn4238Z6ft6KfEpN0tJGo53AAPC632U= +golang.org/x/net v0.41.0 h1:vBTly1HeNPEn3wtREYfy4GZ/NECgw2Cnl+nK6Nz3uvw= +golang.org/x/net v0.41.0/go.mod h1:B/K4NNqkfmg07DQYrbwvSluqCJOOXwUjeb/5lOisjbA= golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI= golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU= golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw= golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= -golang.org/x/text v0.25.0 h1:qVyWApTSYLk/drJRO5mDlNYskwQznZmkpV2c8q9zls4= -golang.org/x/text v0.25.0/go.mod h1:WEdwpYrmk1qmdHvhkSTNPm3app7v4rsT8F2UD6+VHIA= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250528174236-200df99c418a h1:v2PbRU4K3llS09c7zodFpNePeamkAwG3mPrAery9VeE= -google.golang.org/genproto/googleapis/rpc v0.0.0-20250528174236-200df99c418a/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A= +golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M= +golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA= +google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822 h1:oWVWY3NzT7KJppx2UKhKmzPq4SRe0LdCijVRwvGeikY= +google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822/go.mod h1:h3c4v36UTKzUiuaOKQ6gr3S+0hovBtUrXzTG/i3+XEc= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822 h1:fc6jSaCT0vBduLYZHYrBBNY4dsWuvgyff9noRNDdBeE= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250603155806-513f23925822/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A= google.golang.org/grpc v1.74.2 h1:WoosgB65DlWVC9FqI82dGsZhWFNBSLjQ84bjROOpMu4= google.golang.org/grpc v1.74.2/go.mod h1:CtQ+BGjaAIXHs/5YS3i473GqwBBa1zGQNevxdeBEXrM= google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY= diff --git a/examples/grpc-client/client.go b/examples/grpc-client/client.go index fb8d4aaf06..2e9c219fad 100644 --- a/examples/grpc-client/client.go +++ b/examples/grpc-client/client.go @@ -6,15 +6,47 @@ import ( "crypto/x509" "flag" "fmt" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc" + "go.opentelemetry.io/otel/propagation" + "go.opentelemetry.io/otel/sdk/resource" + sdktrace "go.opentelemetry.io/otel/sdk/trace" + semconv "go.opentelemetry.io/otel/semconv/v1.33.0" + "google.golang.org/grpc/credentials/insecure" "log" "os" + "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "github.com/dexidp/dex/api/v2" ) +func InitTracerProvider(ctx context.Context, res *resource.Resource, conn *grpc.ClientConn) (func(context.Context) error, error) { + // Set up a trace exporter + traceExporter, err := otlptracegrpc.New(ctx, otlptracegrpc.WithGRPCConn(conn)) + if err != nil { + return nil, fmt.Errorf("failed to create trace exporter: %w", err) + } + + // Register the trace exporter with a TracerProvider, using a batch + // span processor to aggregate spans before export. + bsp := sdktrace.NewBatchSpanProcessor(traceExporter) + tracerProvider := sdktrace.NewTracerProvider( + sdktrace.WithSampler(sdktrace.AlwaysSample()), + sdktrace.WithResource(res), + sdktrace.WithSpanProcessor(bsp), + ) + otel.SetTracerProvider(tracerProvider) + + // Set global propagator to tracecontext (the default is no-op). + otel.SetTextMapPropagator(propagation.TraceContext{}) + + // Shutdown will flush any remaining spans and shut down the exporter. + return tracerProvider.Shutdown, nil +} + func newDexClient(hostAndPort, caPath, clientCrt, clientKey string) (api.DexClient, error) { cPool := x509.NewCertPool() caCert, err := os.ReadFile(caPath) @@ -35,15 +67,20 @@ func newDexClient(hostAndPort, caPath, clientCrt, clientKey string) (api.DexClie Certificates: []tls.Certificate{clientCert}, } creds := credentials.NewTLS(clientTLSConfig) + conn, err := grpc.NewClient(hostAndPort, + grpc.WithTransportCredentials(creds), + grpc.WithStatsHandler(otelgrpc.NewClientHandler()), + ) - conn, err := grpc.Dial(hostAndPort, grpc.WithTransportCredentials(creds)) if err != nil { return nil, fmt.Errorf("dial: %v", err) } return api.NewDexClient(conn), nil } -func createPassword(cli api.DexClient) error { +func createPassword(cli api.DexClient, ctx context.Context) error { + ctx, span := otel.Tracer("grpc-client").Start(ctx, "createPassword") + defer span.End() p := api.Password{ Email: "test@example.com", // bcrypt hash of the value "test1" with cost 10 @@ -57,8 +94,8 @@ func createPassword(cli api.DexClient) error { } // Create password. - if resp, err := cli.CreatePassword(context.TODO(), createReq); err != nil || resp.AlreadyExists { - if resp != nil && resp.AlreadyExists { + if resp, err := cli.CreatePassword(ctx, createReq); err != nil || resp.AlreadyExists { + if resp != nil && resp.AlreadyExists { return fmt.Errorf("Password %s already exists", createReq.Password.Email) } return fmt.Errorf("failed to create password: %v", err) @@ -66,7 +103,7 @@ func createPassword(cli api.DexClient) error { log.Printf("Created password with email %s", createReq.Password.Email) // List all passwords. - resp, err := cli.ListPasswords(context.TODO(), &api.ListPasswordReq{}) + resp, err := cli.ListPasswords(ctx, &api.ListPasswordReq{}) if err != nil { return fmt.Errorf("failed to list password: %v", err) } @@ -82,7 +119,7 @@ func createPassword(cli api.DexClient) error { Email: "test@example.com", Password: "test1", } - verifyResp, err := cli.VerifyPassword(context.TODO(), verifyReq) + verifyResp, err := cli.VerifyPassword(ctx, verifyReq) if err != nil { return fmt.Errorf("failed to run VerifyPassword for correct password: %v", err) } @@ -95,7 +132,7 @@ func createPassword(cli api.DexClient) error { Email: "test@example.com", Password: "wrong_password", } - badVerifyResp, err := cli.VerifyPassword(context.TODO(), badVerifyReq) + badVerifyResp, err := cli.VerifyPassword(ctx, badVerifyReq) if err != nil { return fmt.Errorf("failed to run VerifyPassword for incorrect password: %v", err) } @@ -114,7 +151,7 @@ func createPassword(cli api.DexClient) error { } // Delete password with email = test@example.com. - if resp, err := cli.DeletePassword(context.TODO(), deleteReq); err != nil || resp.NotFound { + if resp, err := cli.DeletePassword(ctx, deleteReq); err != nil || resp.NotFound { if resp != nil && resp.NotFound { return fmt.Errorf("Password %s not found", deleteReq.Email) } @@ -130,7 +167,26 @@ func main() { clientCrt := flag.String("client-crt", "", "Client certificate") clientKey := flag.String("client-key", "", "Client key") flag.Parse() - + ctx := context.Background() + serviceNameVal := semconv.ServiceNameKey.String("grpc-client") + res, _ := resource.Merge(resource.Default(), resource.NewWithAttributes(semconv.SchemaURL, serviceNameVal)) + + conn, err := grpc.NewClient("localhost:4317", + // Note the use of insecure transport here. TLS is recommended in production. + grpc.WithTransportCredentials(insecure.NewCredentials()), + ) + if err != nil { + log.Printf("failed to create gRPC connection to collector: %w", err) + } + provider, err := InitTracerProvider(ctx, res, conn) + if err != nil { + log.Printf("failed to init tracer: %w", err) + } + defer func() { + if err := provider(ctx); err != nil { + log.Printf("failed to shutdown tracer provider: %v", err) + } + }() if *clientCrt == "" || *caCrt == "" || *clientKey == "" { log.Fatal("Please provide CA & client certificates and client key. Usage: ./client --ca-crt= --client-crt= --client-key=") } @@ -140,7 +196,7 @@ func main() { log.Fatalf("failed creating dex client: %v ", err) } - if err := createPassword(client); err != nil { + if err := createPassword(client, ctx); err != nil { log.Fatalf("testPassword failed: %v", err) } } diff --git a/go.mod b/go.mod index 6ab1400bd8..50741d0919 100644 --- a/go.mod +++ b/go.mod @@ -8,6 +8,7 @@ require ( github.com/AppsFlyer/go-sundheit v0.6.0 github.com/Masterminds/semver v1.5.0 github.com/Masterminds/sprig/v3 v3.3.0 + github.com/XSAM/otelsql v0.39.0 github.com/beevik/etree v1.5.1 github.com/coreos/go-oidc/v3 v3.14.1 github.com/dexidp/dex/api/v2 v2.3.0 @@ -15,23 +16,35 @@ require ( github.com/ghodss/yaml v1.0.0 github.com/go-jose/go-jose/v4 v4.1.1 github.com/go-ldap/ldap/v3 v3.4.11 + github.com/go-slog/otelslog v0.3.0 github.com/go-sql-driver/mysql v1.9.3 github.com/google/uuid v1.6.0 github.com/gorilla/handlers v1.5.2 github.com/gorilla/mux v1.8.1 - github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 github.com/kylelemons/godebug v1.1.0 github.com/lib/pq v1.10.9 github.com/mattermost/xml-roundtrip-validator v0.1.0 github.com/mattn/go-sqlite3 v1.14.29 github.com/oklog/run v1.2.0 github.com/pkg/errors v0.9.1 - github.com/prometheus/client_golang v1.22.0 github.com/russellhaering/goxmldsig v1.5.0 github.com/spf13/cobra v1.9.1 github.com/stretchr/testify v1.10.0 go.etcd.io/etcd/client/pkg/v3 v3.6.3 go.etcd.io/etcd/client/v3 v3.6.3 + go.opentelemetry.io/contrib/bridges/otelslog v0.12.0 + go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.62.0 + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.62.0 + go.opentelemetry.io/otel v1.37.0 + go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.13.0 + go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.37.0 + go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.37.0 + go.opentelemetry.io/otel/log v0.13.0 + go.opentelemetry.io/otel/metric v1.37.0 + go.opentelemetry.io/otel/sdk v1.37.0 + go.opentelemetry.io/otel/sdk/log v0.13.0 + go.opentelemetry.io/otel/sdk/metric v1.37.0 + go.opentelemetry.io/otel/trace v1.37.0 golang.org/x/crypto v0.40.0 golang.org/x/exp v0.0.0-20221004215720-b9f4876ce741 golang.org/x/net v0.42.0 @@ -42,68 +55,67 @@ require ( ) require ( - ariga.io/atlas v0.31.1-0.20250212144724-069be8033e83 // indirect + ariga.io/atlas v0.36.0 // indirect cloud.google.com/go/auth v0.16.3 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect - dario.cat/mergo v1.0.1 // indirect + dario.cat/mergo v1.0.2 // indirect filippo.io/edwards25519 v1.1.0 // indirect github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 // indirect github.com/Masterminds/goutils v1.1.1 // indirect - github.com/Masterminds/semver/v3 v3.3.0 // indirect - github.com/agext/levenshtein v1.2.1 // indirect - github.com/apparentlymart/go-textseg/v13 v13.0.0 // indirect + github.com/Masterminds/semver/v3 v3.4.0 // indirect + github.com/agext/levenshtein v1.2.3 // indirect github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect - github.com/beorn7/perks v1.0.1 // indirect github.com/bmatcuk/doublestar v1.3.4 // indirect - github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/cenkalti/backoff/v5 v5.0.2 // indirect github.com/coreos/go-semver v0.3.1 // indirect github.com/coreos/go-systemd/v22 v22.5.0 // indirect github.com/davecgh/go-spew v1.1.1 // indirect + github.com/fatih/color v1.15.0 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/go-asn1-ber/asn1-ber v1.5.8-0.20250403174932-29230038a667 // indirect github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect - github.com/go-openapi/inflect v0.19.0 // indirect + github.com/go-openapi/inflect v0.21.2 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/protobuf v1.5.4 // indirect github.com/google/go-cmp v0.7.0 // indirect github.com/google/s2a-go v0.1.9 // indirect github.com/googleapis/enterprise-certificate-proxy v0.3.6 // indirect github.com/googleapis/gax-go/v2 v2.15.0 // indirect - github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3 // indirect - github.com/hashicorp/hcl/v2 v2.13.0 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.1 // indirect + github.com/hashicorp/hcl/v2 v2.24.0 // indirect github.com/huandu/xstrings v1.5.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jonboulle/clockwork v0.5.0 // indirect - github.com/mattn/go-runewidth v0.0.9 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.19 // indirect + github.com/mattn/go-runewidth v0.0.16 // indirect github.com/mitchellh/copystructure v1.2.0 // indirect - github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 // indirect + github.com/mitchellh/go-wordwrap v1.0.1 // indirect github.com/mitchellh/reflectwalk v1.0.2 // indirect - github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect - github.com/olekukonko/tablewriter v0.0.5 // indirect + github.com/olekukonko/errors v0.0.0-20250405072817-4e6d85265da6 // indirect + github.com/olekukonko/ll v0.0.8 // indirect + github.com/olekukonko/tablewriter v1.0.8 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/prometheus/client_model v0.6.1 // indirect - github.com/prometheus/common v0.62.0 // indirect - github.com/prometheus/procfs v0.15.1 // indirect + github.com/rivo/uniseg v0.4.7 // indirect github.com/shopspring/decimal v1.4.0 // indirect - github.com/spf13/cast v1.7.0 // indirect - github.com/spf13/pflag v1.0.6 // indirect - github.com/zclconf/go-cty v1.14.4 // indirect + github.com/spf13/cast v1.9.2 // indirect + github.com/spf13/pflag v1.0.7 // indirect + github.com/zclconf/go-cty v1.16.3 // indirect github.com/zclconf/go-cty-yaml v1.1.0 // indirect go.etcd.io/etcd/api/v3 v3.6.3 // indirect go.opentelemetry.io/auto/sdk v1.1.0 // indirect - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 // indirect - go.opentelemetry.io/otel v1.36.0 // indirect - go.opentelemetry.io/otel/metric v1.36.0 // indirect - go.opentelemetry.io/otel/trace v1.36.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.37.0 // indirect + go.opentelemetry.io/proto/otlp v1.7.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.27.0 // indirect - golang.org/x/mod v0.25.0 // indirect + golang.org/x/mod v0.26.0 // indirect golang.org/x/sync v0.16.0 // indirect golang.org/x/sys v0.34.0 // indirect golang.org/x/text v0.27.0 // indirect - golang.org/x/tools v0.34.0 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822 // indirect + golang.org/x/tools v0.35.0 // indirect + golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20250715232539-7130f93afb79 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20250715232539-7130f93afb79 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect @@ -112,3 +124,5 @@ require ( replace github.com/dexidp/dex/api/v2 => ./api/v2 tool entgo.io/ent/cmd/ent + +replace entgo.io/ent => github.com/jensholdgaard/ent v0.14.5-alpha diff --git a/go.sum b/go.sum index c91f5aca6c..183d7d27a8 100644 --- a/go.sum +++ b/go.sum @@ -1,15 +1,13 @@ -ariga.io/atlas v0.31.1-0.20250212144724-069be8033e83 h1:nX4HXncwIdvQ8/8sIUIf1nyCkK8qdBaHQ7EtzPpuiGE= -ariga.io/atlas v0.31.1-0.20250212144724-069be8033e83/go.mod h1:Oe1xWPuu5q9LzyrWfbZmEZxFYeu4BHTyzfjeW2aZp/w= +ariga.io/atlas v0.36.0 h1:DcJ2I/bgT1Igr+XTmiI7s2mQT8Wga6oHZcFJ5R9u5vg= +ariga.io/atlas v0.36.0/go.mod h1:9ZAIr/V85596AVxmN8edyVHYKKpnNsDMdnHLsEliW7k= cloud.google.com/go/auth v0.16.3 h1:kabzoQ9/bobUmnseYnBO6qQG7q4a/CffFRlJSxv2wCc= cloud.google.com/go/auth v0.16.3/go.mod h1:NucRGjaXfzP1ltpcQ7On/VTZ0H4kWB5Jy+Y9Dnm76fA= cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= cloud.google.com/go/compute/metadata v0.7.0 h1:PBWF+iiAerVNe8UCHxdOt6eHLVc3ydFeOCw78U8ytSU= cloud.google.com/go/compute/metadata v0.7.0/go.mod h1:j5MvL9PprKL39t166CoB1uVHfQMs4tFQZZcKwksXUjo= -dario.cat/mergo v1.0.1 h1:Ra4+bf83h2ztPIQYNP99R6m+Y7KfnARDfID+a+vLl4s= -dario.cat/mergo v1.0.1/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk= -entgo.io/ent v0.14.4 h1:/DhDraSLXIkBhyiVoJeSshr4ZYi7femzhj6/TckzZuI= -entgo.io/ent v0.14.4/go.mod h1:aDPE/OziPEu8+OWbzy4UlvWmD2/kbRuWfK2A40hcxJM= +dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8= +dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA= filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= github.com/AppsFlyer/go-sundheit v0.6.0 h1:d2hBvCjBSb2lUsEWGfPigr4MCOt04sxB+Rppl0yUMSk= @@ -22,26 +20,24 @@ github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJ github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww= github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= -github.com/Masterminds/semver/v3 v3.3.0 h1:B8LGeaivUe71a5qox1ICM/JLl0NqZSW5CHyL+hmvYS0= -github.com/Masterminds/semver/v3 v3.3.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= +github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0= +github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= github.com/Masterminds/sprig/v3 v3.3.0 h1:mQh0Yrg1XPo6vjYXgtf5OtijNAKJRNcTdOOGZe3tPhs= github.com/Masterminds/sprig/v3 v3.3.0/go.mod h1:Zy1iXRYNqNLUolqCpL4uhk6SHUMAOSCzdgBfDb35Lz0= -github.com/agext/levenshtein v1.2.1 h1:QmvMAjj2aEICytGiWzmxoE0x2KZvE0fvmqMOfy2tjT8= -github.com/agext/levenshtein v1.2.1/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= +github.com/XSAM/otelsql v0.39.0 h1:4o374mEIMweaeevL7fd8Q3C710Xi2Jh/c8G4Qy9bvCY= +github.com/XSAM/otelsql v0.39.0/go.mod h1:uMOXLUX+wkuAuP0AR3B45NXX7E9lJS2mERa8gqdU8R0= +github.com/agext/levenshtein v1.2.3 h1:YB2fHEn0UJagG8T1rrWknE3ZQzWM06O8AMAatNn7lmo= +github.com/agext/levenshtein v1.2.3/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa h1:LHTHcTQiSGT7VVbI0o4wBRNQIgn917usHWOd6VAffYI= github.com/alexbrainman/sspi v0.0.0-20231016080023-1a75b4708caa/go.mod h1:cEWa1LVoE5KvSD9ONXsZrj0z6KqySlCCNKHlLzbqAt4= -github.com/apparentlymart/go-textseg/v13 v13.0.0 h1:Y+KvPE1NYz0xl601PVImeQfFyEy6iT90AvPUL1NNfNw= -github.com/apparentlymart/go-textseg/v13 v13.0.0/go.mod h1:ZK2fH7c4NqDTLtiYLvIkEghdlcqw7yxLeM89kiTRPUo= github.com/apparentlymart/go-textseg/v15 v15.0.0 h1:uYvfpb3DyLSCGWnctWKGj857c6ew1u1fNQOlOtuGxQY= github.com/apparentlymart/go-textseg/v15 v15.0.0/go.mod h1:K8XmNZdhEBkdlyDdvbmmsvpAG721bKi0joRfFdHIWJ4= github.com/beevik/etree v1.5.1 h1:TC3zyxYp+81wAmbsi8SWUpZCurbxa6S8RITYRSkNRwo= github.com/beevik/etree v1.5.1/go.mod h1:gPNJNaBGVZ9AwsidazFZyygnd+0pAU38N4D+WemwKNs= -github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= -github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bmatcuk/doublestar v1.3.4 h1:gPypJ5xD31uhX6Tf54sDPUOBXTqKH4c9aPY66CyQrS0= github.com/bmatcuk/doublestar v1.3.4/go.mod h1:wiQtGV+rzVYxB7WIlirSN++5HPtPlXEo9MEoZQC/PmE= -github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= -github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cenkalti/backoff/v5 v5.0.2 h1:rIfFVxEf1QsI7E1ZHfp/B4DF/6QBAUhmgkxc0H7Zss8= +github.com/cenkalti/backoff/v5 v5.0.2/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw= github.com/coreos/go-oidc/v3 v3.14.1 h1:9ePWwfdwC4QKRlCXsJGou56adA/owXczOzwKdOumLqk= github.com/coreos/go-oidc/v3 v3.14.1/go.mod h1:HaZ3szPaZ0e4r6ebqvsLWlk2Tn+aejfmrfah6hnSYEU= github.com/coreos/go-semver v0.3.1 h1:yi21YpKnrx1gt5R+la8n5WgS0kCrsPp33dmEyHReZr4= @@ -52,6 +48,8 @@ github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6N github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= +github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw= @@ -73,8 +71,10 @@ github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= -github.com/go-openapi/inflect v0.19.0 h1:9jCH9scKIbHeV9m12SmPilScz6krDxKRasNNSNPXu/4= -github.com/go-openapi/inflect v0.19.0/go.mod h1:lHpZVlpIQqLyKwJ4N+YSc9hchQy/i12fJykb83CRBH4= +github.com/go-openapi/inflect v0.21.2 h1:0gClGlGcxifcJR56zwvhaOulnNgnhc4qTAkob5ObnSM= +github.com/go-openapi/inflect v0.21.2/go.mod h1:INezMuUu7SJQc2AyR3WO0DqqYUJSj8Kb4hBd7WtjlAw= +github.com/go-slog/otelslog v0.3.0 h1:O/ettamJL9sJKCmtEa/xHF5dqHvWF6xION/NIiZJ6gk= +github.com/go-slog/otelslog v0.3.0/go.mod h1:TxQTymq11rhMaNLE4yMe3kXuUf9ksoGyN9ivieHFWu8= github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo= github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU= github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68= @@ -98,14 +98,12 @@ github.com/gorilla/handlers v1.5.2 h1:cLTUSsNkgcwhgRqvCNmdbRWG0A3N4F+M2nWKdScwyE github.com/gorilla/handlers v1.5.2/go.mod h1:dX+xVpaxdSw+q0Qek8SSsl3dfMk3jNddUkMzo0GtH0w= github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY= github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ= -github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0 h1:Ovs26xHkKqVztRpIrF/92BcuyuQ/YW4NSIpoGtfXNho= -github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3 h1:5ZPtiqj0JL5oKWmcsq4VMaAW5ukBEgSGXEN89zeH1Jo= -github.com/grpc-ecosystem/grpc-gateway/v2 v2.26.3/go.mod h1:ndYquD05frm2vACXE1nsccT4oJzjhw2arTS2cpUD1PI= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.1 h1:X5VWvz21y3gzm9Nw/kaUeku/1+uBhcekkmy4IkffJww= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.1/go.mod h1:Zanoh4+gvIgluNqcfMVTJueD4wSS5hT7zTt4Mrutd90= github.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8= github.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= -github.com/hashicorp/hcl/v2 v2.13.0 h1:0Apadu1w6M11dyGFxWnmhhcMjkbAiKCv7G1r/2QgCNc= -github.com/hashicorp/hcl/v2 v2.13.0/go.mod h1:e4z5nxYlWNPdDSNYX+ph14EvWYMFm3eP0zIUqPc2jr0= +github.com/hashicorp/hcl/v2 v2.24.0 h1:2QJdZ454DSsYGoaE6QheQZjtKZSUs9Nh2izTWiwQxvE= +github.com/hashicorp/hcl/v2 v2.24.0/go.mod h1:oGoO1FIQYfn/AgyOhlg9qLC6/nOJPX3qGbkZpYAcqfM= github.com/huandu/xstrings v1.5.0 h1:2ag3IFq9ZDANvthTwTiqSSZLjDc+BedvHPAp5tJy2TI= github.com/huandu/xstrings v1.5.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= @@ -122,12 +120,12 @@ github.com/jcmturner/gokrb5/v8 v8.4.4 h1:x1Sv4HaTpepFkXbt2IkL29DXRf8sOfZXo8eRKh6 github.com/jcmturner/gokrb5/v8 v8.4.4/go.mod h1:1btQEpgT6k+unzCwX1KdWMEwPPkkgBtP+F6aCACiMrs= github.com/jcmturner/rpc/v2 v2.0.3 h1:7FXXj8Ti1IaVFpSAziCZWNzbNuZmnvw/i6CqLNdWfZY= github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc= +github.com/jensholdgaard/ent v0.14.5-alpha h1:yaG733Yiw+xgBvl6mYYJKVi/+9hjZvDG+TSj6TCF+Q0= +github.com/jensholdgaard/ent v0.14.5-alpha/go.mod h1:D1GhxIZuTVwuioj593pTZY0NRXWxTgSXaQTImeQy/Og= github.com/jonboulle/clockwork v0.5.0 h1:Hyh9A8u51kptdkR+cqRpT1EebBwTn1oK9YfGYbdFz6I= github.com/jonboulle/clockwork v0.5.0/go.mod h1:3mZlmanh0g2NDKO5TWZVJAfofYk64M7XN3SzBPjZF60= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= -github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= @@ -141,50 +139,51 @@ github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/mattermost/xml-roundtrip-validator v0.1.0 h1:RXbVD2UAl7A7nOTR4u7E3ILa4IbtvKBHw64LDsmu9hU= github.com/mattermost/xml-roundtrip-validator v0.1.0/go.mod h1:qccnGMcpgwcNaBnxqpJpWWUiPNr5H3O8eDgGV9gT5To= -github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0= -github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA= +github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc= +github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= github.com/mattn/go-sqlite3 v1.14.29 h1:1O6nRLJKvsi1H2Sj0Hzdfojwt8GiGKm+LOfLaBFaouQ= github.com/mattn/go-sqlite3 v1.14.29/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= -github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 h1:DpOJ2HYzCv8LZP15IdmG+YdwD2luVPHITV96TkirNBM= -github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= +github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0= +github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= -github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= -github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/oklog/run v1.2.0 h1:O8x3yXwah4A73hJdlrwo/2X6J62gE5qTMusH0dvz60E= github.com/oklog/run v1.2.0/go.mod h1:mgDbKRSwPhJfesJ4PntqFUbKQRZ50NgmZTSPlFA0YFk= -github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec= -github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY= +github.com/olekukonko/errors v0.0.0-20250405072817-4e6d85265da6 h1:r3FaAI0NZK3hSmtTDrBVREhKULp8oUeqLT5Eyl2mSPo= +github.com/olekukonko/errors v0.0.0-20250405072817-4e6d85265da6/go.mod h1:ppzxA5jBKcO1vIpCXQ9ZqgDh8iwODz6OXIGKU8r5m4Y= +github.com/olekukonko/ll v0.0.8 h1:sbGZ1Fx4QxJXEqL/6IG8GEFnYojUSQ45dJVwN2FH2fc= +github.com/olekukonko/ll v0.0.8/go.mod h1:En+sEW0JNETl26+K8eZ6/W4UQ7CYSrrgg/EdIYT2H8g= +github.com/olekukonko/tablewriter v1.0.8 h1:f6wJzHg4QUtJdvrVPKco4QTrAylgaU0+b9br/lJxEiQ= +github.com/olekukonko/tablewriter v1.0.8/go.mod h1:H428M+HzoUXC6JU2Abj9IT9ooRmdq9CxuDmKMtrOCMs= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/prometheus/client_golang v1.22.0 h1:rb93p9lokFEsctTys46VnV1kLCDpVZ0a/Y92Vm0Zc6Q= -github.com/prometheus/client_golang v1.22.0/go.mod h1:R7ljNsLXhuQXYZYtw6GAE9AZg8Y7vEW5scdCXrWRXC0= -github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E= -github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY= -github.com/prometheus/common v0.62.0 h1:xasJaQlnWAeyHdUBeGjXmutelfJHWMRr+Fg4QszZ2Io= -github.com/prometheus/common v0.62.0/go.mod h1:vyBcEuLSvWos9B1+CyL7JZ2up+uFzXhkqml0W5zIY1I= -github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc= -github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= +github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= github.com/russellhaering/goxmldsig v1.5.0 h1:AU2UkkYIUOTyZRbe08XMThaOCelArgvNfYapcmSjBNw= github.com/russellhaering/goxmldsig v1.5.0/go.mod h1:x98CjQNFJcWfMxeOrMnMKg70lvDP6tE0nTaeUnjXDmk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ= -github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k= github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME= -github.com/spf13/cast v1.7.0 h1:ntdiHjuueXFgm5nzDRdOS4yfT43P5Fnud6DH50rz/7w= -github.com/spf13/cast v1.7.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= +github.com/spf13/cast v1.9.2 h1:SsGfm7M8QOFtEzumm7UZrZdLLquNdzFYfIbEXntcFbE= +github.com/spf13/cast v1.9.2/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= github.com/spf13/cobra v1.9.1 h1:CXSaggrXdbHK9CF+8ywj8Amf7PBRmPCOJugH954Nnlo= github.com/spf13/cobra v1.9.1/go.mod h1:nDyEzZ8ogv936Cinf6g1RU9MRY64Ir93oCnqb9wxYW0= -github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o= github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/pflag v1.0.7 h1:vN6T9TfwStFPFM5XzjsvmzZkLuaLX+HS+0SeFLRgU6M= +github.com/spf13/pflag v1.0.7/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= @@ -195,8 +194,10 @@ github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOf github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/zclconf/go-cty v1.14.4 h1:uXXczd9QDGsgu0i/QFR/hzI5NYCHLf6NQw/atrbnhq8= -github.com/zclconf/go-cty v1.14.4/go.mod h1:VvMs5i0vgZdhYawQNq5kePSpLAoz8u1xvZgrPIxfnZE= +github.com/zclconf/go-cty v1.16.3 h1:osr++gw2T61A8KVYHoQiFbFd1Lh3JOCXc/jFLJXKTxk= +github.com/zclconf/go-cty v1.16.3/go.mod h1:VvMs5i0vgZdhYawQNq5kePSpLAoz8u1xvZgrPIxfnZE= +github.com/zclconf/go-cty-debug v0.0.0-20240509010212-0d6042c53940 h1:4r45xpDWB6ZMSMNJFMOjqrGHynW3DIBuR2H9j0ug+Mo= +github.com/zclconf/go-cty-debug v0.0.0-20240509010212-0d6042c53940/go.mod h1:CmBdvvj3nqzfzJ6nTCIwDTPZ56aVGvDrmztiO5g3qrM= github.com/zclconf/go-cty-yaml v1.1.0 h1:nP+jp0qPHv2IhUVqmQSzjvqAWcObN0KBkUl2rWBdig0= github.com/zclconf/go-cty-yaml v1.1.0/go.mod h1:9YLUH4g7lOhVWqUbctnVlZ5KLpg7JAprQNgxSZ1Gyxs= go.etcd.io/etcd/api/v3 v3.6.3 h1:4Lftl1e6VzBsj5HPhLu8GGybjeT5qg9mug70RxTHmQQ= @@ -207,20 +208,38 @@ go.etcd.io/etcd/client/v3 v3.6.3 h1:yKpdrcVK6jTfr/VuVuH5VesaLmUi8PLI9eXHTy5kpTM= go.etcd.io/etcd/client/v3 v3.6.3/go.mod h1:zDuGaiUvpECwqClZCUkHi6q2XSf2ejPbUB755QLXdL8= go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 h1:q4XOmH/0opmeuJtPsbFNivyl7bCt7yRBbeEm2sC/XtQ= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0/go.mod h1:snMWehoOh2wsEwnvvwtDyFCxVeDAODenXHtn5vzrKjo= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 h1:F7Jx+6hwnZ41NSFTO5q4LYDtJRXBf2PD0rNBkeB/lus= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q= -go.opentelemetry.io/otel v1.36.0 h1:UumtzIklRBY6cI/lllNZlALOF5nNIzJVb16APdvgTXg= -go.opentelemetry.io/otel v1.36.0/go.mod h1:/TcFMXYjyRNh8khOAO9ybYkqaDBb/70aVwkNML4pP8E= -go.opentelemetry.io/otel/metric v1.36.0 h1:MoWPKVhQvJ+eeXWHFBOPoBOi20jh6Iq2CcCREuTYufE= -go.opentelemetry.io/otel/metric v1.36.0/go.mod h1:zC7Ks+yeyJt4xig9DEw9kuUFe5C3zLbVjV2PzT6qzbs= -go.opentelemetry.io/otel/sdk v1.36.0 h1:b6SYIuLRs88ztox4EyrvRti80uXIFy+Sqzoh9kFULbs= -go.opentelemetry.io/otel/sdk v1.36.0/go.mod h1:+lC+mTgD+MUWfjJubi2vvXWcVxyr9rmlshZni72pXeY= -go.opentelemetry.io/otel/sdk/metric v1.36.0 h1:r0ntwwGosWGaa0CrSt8cuNuTcccMXERFwHX4dThiPis= -go.opentelemetry.io/otel/sdk/metric v1.36.0/go.mod h1:qTNOhFDfKRwX0yXOqJYegL5WRaW376QbB7P4Pb0qva4= -go.opentelemetry.io/otel/trace v1.36.0 h1:ahxWNuqZjpdiFAyrIoQ4GIiAIhxAunQR6MUoKrsNd4w= -go.opentelemetry.io/otel/trace v1.36.0/go.mod h1:gQ+OnDZzrybY4k4seLzPAWNwVBBVlF2szhehOBB/tGA= +go.opentelemetry.io/contrib/bridges/otelslog v0.12.0 h1:lFM7SZo8Ce01RzRfnUFQZEYeWRf/MtOA3A5MobOqk2g= +go.opentelemetry.io/contrib/bridges/otelslog v0.12.0/go.mod h1:Dw05mhFtrKAYu72Tkb3YBYeQpRUJ4quDgo2DQw3No5A= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.62.0 h1:rbRJ8BBoVMsQShESYZ0FkvcITu8X8QNwJogcLUmDNNw= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.62.0/go.mod h1:ru6KHrNtNHxM4nD/vd6QrLVWgKhxPYgblq4VAtNawTQ= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.62.0 h1:Hf9xI/XLML9ElpiHVDNwvqI0hIFlzV8dgIr35kV1kRU= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.62.0/go.mod h1:NfchwuyNoMcZ5MLHwPrODwUF1HWCXWrL31s8gSAdIKY= +go.opentelemetry.io/otel v1.37.0 h1:9zhNfelUvx0KBfu/gb+ZgeAfAgtWrfHJZcAqFC228wQ= +go.opentelemetry.io/otel v1.37.0/go.mod h1:ehE/umFRLnuLa/vSccNq9oS1ErUlkkK71gMcN34UG8I= +go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.13.0 h1:z6lNIajgEBVtQZHjfw2hAccPEBDs+nx58VemmXWa2ec= +go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.13.0/go.mod h1:+kyc3bRx/Qkq05P6OCu3mTEIOxYRYzoIg+JsUp5X+PM= +go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.37.0 h1:zG8GlgXCJQd5BU98C0hZnBbElszTmUgCNCfYneaDL0A= +go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.37.0/go.mod h1:hOfBCz8kv/wuq73Mx2H2QnWokh/kHZxkh6SNF2bdKtw= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.37.0 h1:Ahq7pZmv87yiyn3jeFz/LekZmPLLdKejuO3NcK9MssM= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.37.0/go.mod h1:MJTqhM0im3mRLw1i8uGHnCvUEeS7VwRyxlLC78PA18M= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.37.0 h1:EtFWSnwW9hGObjkIdmlnWSydO+Qs8OwzfzXLUPg4xOc= +go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.37.0/go.mod h1:QjUEoiGCPkvFZ/MjK6ZZfNOS6mfVEVKYE99dFhuN2LI= +go.opentelemetry.io/otel/log v0.13.0 h1:yoxRoIZcohB6Xf0lNv9QIyCzQvrtGZklVbdCoyb7dls= +go.opentelemetry.io/otel/log v0.13.0/go.mod h1:INKfG4k1O9CL25BaM1qLe0zIedOpvlS5Z7XgSbmN83E= +go.opentelemetry.io/otel/metric v1.37.0 h1:mvwbQS5m0tbmqML4NqK+e3aDiO02vsf/WgbsdpcPoZE= +go.opentelemetry.io/otel/metric v1.37.0/go.mod h1:04wGrZurHYKOc+RKeye86GwKiTb9FKm1WHtO+4EVr2E= +go.opentelemetry.io/otel/sdk v1.37.0 h1:ItB0QUqnjesGRvNcmAcU0LyvkVyGJ2xftD29bWdDvKI= +go.opentelemetry.io/otel/sdk v1.37.0/go.mod h1:VredYzxUvuo2q3WRcDnKDjbdvmO0sCzOvVAiY+yUkAg= +go.opentelemetry.io/otel/sdk/log v0.13.0 h1:I3CGUszjM926OphK8ZdzF+kLqFvfRY/IIoFq/TjwfaQ= +go.opentelemetry.io/otel/sdk/log v0.13.0/go.mod h1:lOrQyCCXmpZdN7NchXb6DOZZa1N5G1R2tm5GMMTpDBw= +go.opentelemetry.io/otel/sdk/log/logtest v0.13.0 h1:9yio6AFZ3QD9j9oqshV1Ibm9gPLlHNxurno5BreMtIA= +go.opentelemetry.io/otel/sdk/log/logtest v0.13.0/go.mod h1:QOGiAJHl+fob8Nu85ifXfuQYmJTFAvcrxL6w5/tu168= +go.opentelemetry.io/otel/sdk/metric v1.37.0 h1:90lI228XrB9jCMuSdA0673aubgRobVZFhbjxHHspCPc= +go.opentelemetry.io/otel/sdk/metric v1.37.0/go.mod h1:cNen4ZWfiD37l5NhS+Keb5RXVWZWpRE+9WyVCpbo5ps= +go.opentelemetry.io/otel/trace v1.37.0 h1:HLdcFNbRQBE2imdSEgm/kwqmQj1Or1l/7bW6mxVK7z4= +go.opentelemetry.io/otel/trace v1.37.0/go.mod h1:TlgrlQ+PtQO5XFerSPUYG0JSgGyryXewPGyayAWSBS0= +go.opentelemetry.io/proto/otlp v1.7.0 h1:jX1VolD6nHuFzOYso2E73H85i92Mv8JQYk0K9vz09os= +go.opentelemetry.io/proto/otlp v1.7.0/go.mod h1:fSKjH6YJ7HDlwzltzyMj036AJ3ejJLCgCSHGj4efDDo= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= @@ -236,8 +255,8 @@ golang.org/x/exp v0.0.0-20221004215720-b9f4876ce741 h1:fGZugkZk2UgYBxtpKmvub51Yn golang.org/x/exp v0.0.0-20221004215720-b9f4876ce741/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.25.0 h1:n7a+ZbQKQA/Ysbyb0/6IbB1H/X41mKgbhfv7AfG/44w= -golang.org/x/mod v0.25.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww= +golang.org/x/mod v0.26.0 h1:EGMPT//Ezu+ylkCijjPc+f4Aih7sZvaAr+O3EHBxvZg= +golang.org/x/mod v0.26.0/go.mod h1:/j6NAhSk8iQ723BGAUyoAcn7SlD7s15Dp9Nd/SfeaFQ= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -254,6 +273,8 @@ golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA= golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -266,8 +287,12 @@ golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGm golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= -golang.org/x/tools v0.34.0 h1:qIpSLOxeCYGg9TrcJokLBG4KFA6d795g0xkBkiESGlo= -golang.org/x/tools v0.34.0/go.mod h1:pAP9OwEaY1CAW3HOmg3hLZC5Z0CCmzjAF2UQMSqNARg= +golang.org/x/tools v0.35.0 h1:mBffYraMEf7aa0sB+NuKnuCy8qI/9Bughn8dC2Gu5r0= +golang.org/x/tools v0.35.0/go.mod h1:NKdj5HkL/73byiZSJjqJgKn3ep7KjFkBOkR/Hps3VPw= +golang.org/x/tools/go/expect v0.1.0-deprecated h1:jY2C5HGYR5lqex3gEniOQL0r7Dq5+VGVgY1nudX5lXY= +golang.org/x/tools/go/expect v0.1.0-deprecated/go.mod h1:eihoPOH+FgIqa3FpoTwguz/bVUSGBlGQU67vpBeOrBY= +golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated h1:1h2MnaIAIXISqTFKdENegdpAgUXz6NrPEsbIeWaBRvM= +golang.org/x/tools/go/packages/packagestest v0.1.1-deprecated/go.mod h1:RVAQXBGNv1ib0J382/DPCRS/BPnsGebyM1Gj5VSDpG8= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -276,8 +301,8 @@ google.golang.org/api v0.243.0 h1:sw+ESIJ4BVnlJcWu9S+p2Z6Qq1PjG77T8IJ1xtp4jZQ= google.golang.org/api v0.243.0/go.mod h1:GE4QtYfaybx1KmeHMdBnNnyLzBZCVihGBXAmJu/uUr8= google.golang.org/genproto v0.0.0-20250603155806-513f23925822 h1:rHWScKit0gvAPuOnu87KpaYtjK5zBMLcULh7gxkCXu4= google.golang.org/genproto v0.0.0-20250603155806-513f23925822/go.mod h1:HubltRL7rMh0LfnQPkMH4NPDFEWp0jw3vixw7jEM53s= -google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822 h1:oWVWY3NzT7KJppx2UKhKmzPq4SRe0LdCijVRwvGeikY= -google.golang.org/genproto/googleapis/api v0.0.0-20250603155806-513f23925822/go.mod h1:h3c4v36UTKzUiuaOKQ6gr3S+0hovBtUrXzTG/i3+XEc= +google.golang.org/genproto/googleapis/api v0.0.0-20250715232539-7130f93afb79 h1:iOye66xuaAK0WnkPuhQPUFy8eJcmwUXqGGP3om6IxX8= +google.golang.org/genproto/googleapis/api v0.0.0-20250715232539-7130f93afb79/go.mod h1:HKJDgKsFUnv5VAGeQjz8kxcgDP0HoE0iZNp0OdZNlhE= google.golang.org/genproto/googleapis/rpc v0.0.0-20250715232539-7130f93afb79 h1:1ZwqphdOdWYXsUHgMpU/101nCtf/kSp9hOrcvFsnl10= google.golang.org/genproto/googleapis/rpc v0.0.0-20250715232539-7130f93afb79/go.mod h1:qQ0YXyHHx3XkvlzUtpXDkS29lDSafHMZBAZDc03LQ3A= google.golang.org/grpc v1.74.2 h1:WoosgB65DlWVC9FqI82dGsZhWFNBSLjQ84bjROOpMu4= diff --git a/pkg/otel/otel.go b/pkg/otel/otel.go new file mode 100644 index 0000000000..5e233e8d5d --- /dev/null +++ b/pkg/otel/otel.go @@ -0,0 +1,61 @@ +package otel + +import ( + "context" + "fmt" + + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc" + "go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc" + "go.opentelemetry.io/otel/log/global" + sdklog "go.opentelemetry.io/otel/sdk/log" + sdkmetric "go.opentelemetry.io/otel/sdk/metric" + "go.opentelemetry.io/otel/sdk/resource" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" +) + +func InitConn(endpoint string) (*grpc.ClientConn, error) { + // It connects the OpenTelemetry Collector through local gRPC connection. + // You may replace `localhost:4317` with your endpoint. + conn, err := grpc.NewClient(endpoint, + // Note the use of insecure transport here. TLS is recommended in production. + grpc.WithTransportCredentials(insecure.NewCredentials()), + ) + if err != nil { + return nil, fmt.Errorf("failed to create gRPC connection to collector: %w", err) + } + + return conn, nil +} + +// Initializes an OTLP exporter, and configures the corresponding meter provider. +func InitMeterProvider(ctx context.Context, res *resource.Resource, conn *grpc.ClientConn) (func(context.Context) error, error) { + metricExporter, err := otlpmetricgrpc.New(ctx, otlpmetricgrpc.WithGRPCConn(conn)) + if err != nil { + return nil, fmt.Errorf("failed to create metrics exporter: %w", err) + } + + meterProvider := sdkmetric.NewMeterProvider( + sdkmetric.WithReader(sdkmetric.NewPeriodicReader(metricExporter)), + sdkmetric.WithResource(res), + ) + otel.SetMeterProvider(meterProvider) + + return meterProvider.Shutdown, nil +} + +func InitLogProvider(ctx context.Context, res *resource.Resource, conn *grpc.ClientConn) (func(context.Context) error, error) { + logExporter, err := otlploggrpc.New(ctx, otlploggrpc.WithGRPCConn(conn)) + if err != nil { + return nil, fmt.Errorf("failed to create log exporter: %w", err) + } + logProvider := sdklog.NewLoggerProvider( + sdklog.WithResource(res), + sdklog.WithProcessor(sdklog.NewBatchProcessor( + logExporter, + )), + ) + global.SetLoggerProvider(logProvider) + return logProvider.Shutdown, nil +} diff --git a/pkg/otel/otel_test.go b/pkg/otel/otel_test.go new file mode 100644 index 0000000000..776f419de7 --- /dev/null +++ b/pkg/otel/otel_test.go @@ -0,0 +1,118 @@ +package otel + +import ( + "context" + "testing" + + "go.opentelemetry.io/otel/sdk/resource" + "google.golang.org/grpc" +) + +func Test_initConn(t *testing.T) { + type args struct { + endpoint string + } + tests := []struct { + name string + args args + want *grpc.ClientConn + wantErr bool + }{ + { + name: "valid endpoint", + args: args{endpoint: "localhost:4317"}, + wantErr: false, + }, + { + name: "invalid endpoint format", + args: args{endpoint: "invalid_endpoint"}, + wantErr: false, // gRPC.NewClient may not error immediately + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := InitConn(tt.args.endpoint) + if (err != nil) != tt.wantErr { + t.Errorf("initConn() error = %v, wantErr %v", err, tt.wantErr) + return + } + if tt.wantErr { + if got != nil { + t.Errorf("initConn() got = %v, want nil", got) + } + } else if got == nil { + t.Errorf("initConn() got = nil, want non-nil") + } + }) + } +} + +func Test_initLogProvider(t *testing.T) { + ctx := context.Background() + res := resource.Default() + conn, _ := InitConn("localhost:4317") // Assume success for test + + type args struct { + ctx context.Context + res *resource.Resource + conn *grpc.ClientConn + } + tests := []struct { + name string + args args + wantErr bool + }{ + { + name: "valid setup", + args: args{ctx: ctx, res: res, conn: conn}, + wantErr: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := InitLogProvider(tt.args.ctx, tt.args.res, tt.args.conn) + if (err != nil) != tt.wantErr { + t.Errorf("initLogProvider() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !tt.wantErr && got == nil { + t.Errorf("initLogProvider() got = nil, want non-nil shutdown func") + } + }) + } +} + +func Test_initMeterProvider(t *testing.T) { + ctx := context.Background() + res := resource.Default() + conn, _ := InitConn("localhost:4317") // Assume success for test + + type args struct { + ctx context.Context + res *resource.Resource + conn *grpc.ClientConn + } + tests := []struct { + name string + args args + wantErr bool + }{ + { + name: "valid setup", + args: args{ctx: ctx, res: res, conn: conn}, + wantErr: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := InitMeterProvider(tt.args.ctx, tt.args.res, tt.args.conn) + if (err != nil) != tt.wantErr { + t.Errorf("initMeterProvider() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !tt.wantErr && got == nil { + t.Errorf("initMeterProvider() got = nil, want non-nil shutdown func") + } + }) + } +} diff --git a/pkg/otel/traces/attributes/dex_attributes.go b/pkg/otel/traces/attributes/dex_attributes.go new file mode 100644 index 0000000000..c1f9fcad6d --- /dev/null +++ b/pkg/otel/traces/attributes/dex_attributes.go @@ -0,0 +1 @@ +package attributes diff --git a/pkg/otel/traces/events/dex_events.go b/pkg/otel/traces/events/dex_events.go new file mode 100644 index 0000000000..b3adf695cc --- /dev/null +++ b/pkg/otel/traces/events/dex_events.go @@ -0,0 +1 @@ +package events diff --git a/pkg/otel/traces/traces.go b/pkg/otel/traces/traces.go new file mode 100644 index 0000000000..d45af1e7d8 --- /dev/null +++ b/pkg/otel/traces/traces.go @@ -0,0 +1,74 @@ +package traces + +import ( + "context" + "fmt" + "net/http" + "strconv" + "strings" + + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc" + "go.opentelemetry.io/otel/propagation" + "go.opentelemetry.io/otel/sdk/resource" + sdktrace "go.opentelemetry.io/otel/sdk/trace" + "go.opentelemetry.io/otel/trace" + "google.golang.org/grpc" +) + +func InitTracerProvider(ctx context.Context, res *resource.Resource, conn *grpc.ClientConn, samplerStr string) (func(context.Context) error, error) { + // Set up a trace exporter + traceExporter, err := otlptracegrpc.New(ctx, otlptracegrpc.WithGRPCConn(conn)) + if err != nil { + return nil, fmt.Errorf("failed to create trace exporter: %w", err) + } + + // Parse sampler + var sampler sdktrace.Sampler + switch samplerStr { + case "always_on": + sampler = sdktrace.AlwaysSample() + case "always_off": + sampler = sdktrace.NeverSample() + default: // e.g., "traceidratio:0.5" + if strings.HasPrefix(samplerStr, "traceidratio:") { + ratioStr := strings.TrimPrefix(samplerStr, "traceidratio:") + ratio, err := strconv.ParseFloat(ratioStr, 64) + if err != nil { + return nil, fmt.Errorf("invalid sampler ratio: %w", err) + } + sampler = sdktrace.ParentBased(sdktrace.TraceIDRatioBased(ratio)) + } else { + sampler = sdktrace.AlwaysSample() // Fallback + } + } + + // Register the trace exporter with a TracerProvider, using a batch + // span processor to aggregate spans before export. + bsp := sdktrace.NewBatchSpanProcessor(traceExporter) + tracerProvider := sdktrace.NewTracerProvider( + sdktrace.WithSampler(sampler), + sdktrace.WithResource(res), + sdktrace.WithSpanProcessor(bsp), + ) + otel.SetTracerProvider(tracerProvider) + + // Set global propagator to tracecontext (the default is no-op). + otel.SetTextMapPropagator(propagation.TraceContext{}) + + // Shutdown will flush any remaining spans and shut down the exporter. + return tracerProvider.Shutdown, nil +} + +const dexLibraryName = "github.com/dexidp/dex" + +func InstrumentationTracer(ctx context.Context, spanName string) (context.Context, trace.Span) { + return trace.SpanFromContext(ctx).TracerProvider().Tracer(dexLibraryName).Start(ctx, spanName) +} + +func InstrumentHandler(r *http.Request) (context.Context, trace.Span) { + ctx := r.Context() + span := trace.SpanFromContext(ctx) + span.SetName(fmt.Sprintf("%s %s", r.Method, r.URL.Path)) + return ctx, span +} diff --git a/pkg/otel/traces/traces_test.go b/pkg/otel/traces/traces_test.go new file mode 100644 index 0000000000..f56d398d76 --- /dev/null +++ b/pkg/otel/traces/traces_test.go @@ -0,0 +1,194 @@ +package traces + +import ( + "context" + "net/http" + "net/url" + "testing" + + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/sdk/resource" + tracesdk "go.opentelemetry.io/otel/sdk/trace" + "go.opentelemetry.io/otel/sdk/trace/tracetest" + "go.opentelemetry.io/otel/trace" + nooptrace "go.opentelemetry.io/otel/trace/noop" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" +) + +func Test_initTracerProvider(t *testing.T) { + ctx := context.Background() + res := resource.Default() + conn, _ := grpc.NewClient("localhost:4317", + // Note the use of insecure transport here. TLS is recommended in production. + grpc.WithTransportCredentials(insecure.NewCredentials()), + ) // Assume success for test + + type args struct { + ctx context.Context + res *resource.Resource + conn *grpc.ClientConn + samplerStr string + } + tests := []struct { + name string + args args + wantErr bool + }{ + { + name: "valid always_on", + args: args{ctx: ctx, res: res, conn: conn, samplerStr: "always_on"}, + wantErr: false, + }, + { + name: "valid always_off", + args: args{ctx: ctx, res: res, conn: conn, samplerStr: "always_off"}, + wantErr: false, + }, + { + name: "valid traceidratio", + args: args{ctx: ctx, res: res, conn: conn, samplerStr: "traceidratio:0.5"}, + wantErr: false, + }, + { + name: "invalid ratio", + args: args{ctx: ctx, res: res, conn: conn, samplerStr: "traceidratio:invalid"}, + wantErr: true, + }, + { + name: "fallback sampler", + args: args{ctx: ctx, res: res, conn: conn, samplerStr: "unknown"}, + wantErr: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := InitTracerProvider(tt.args.ctx, tt.args.res, tt.args.conn, tt.args.samplerStr) + if (err != nil) != tt.wantErr { + t.Errorf("initTracerProvider() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !tt.wantErr && got == nil { + t.Errorf("initTracerProvider() got = nil, want non-nil shutdown func") + } + }) + } +} + +func TestInstrumentationTracer(t *testing.T) { + type args struct { + ctx context.Context + spanName string + } + tests := []struct { + name string + args args + wantScopeName string + wantSpanName string + }{ + { + name: "basic tracer", + args: args{ + ctx: context.Background(), + spanName: "test-span", + }, + wantScopeName: dexLibraryName, + wantSpanName: "test-span", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + recorder := tracetest.NewSpanRecorder() + provider := tracesdk.NewTracerProvider(tracesdk.WithSpanProcessor(recorder)) + otel.SetTracerProvider(provider) + defer otel.SetTracerProvider(nooptrace.NewTracerProvider()) // Cleanup + ctx, _ := provider.Tracer("test").Start(tt.args.ctx, "initial") + + gotCtx, span := InstrumentationTracer(ctx, tt.args.spanName) + span.End() + + spans := recorder.Ended() + if len(spans) != 1 { + t.Errorf("expected 1 span, got %d", len(spans)) + } + gotSpan := spans[0] + + if gotSpan.InstrumentationScope().Name != tt.wantScopeName { + t.Errorf("InstrumentationTracer() scope name = %v, want %v", gotSpan.InstrumentationScope().Name, tt.wantScopeName) + } + if gotSpan.Name() != tt.wantSpanName { + t.Errorf("InstrumentationTracer() span name = %v, want %v", gotSpan.Name(), tt.wantSpanName) + } + + // Check that the returned context contains the new span + returnedSpan := trace.SpanFromContext(gotCtx) + if returnedSpan.SpanContext().TraceID() != gotSpan.SpanContext().TraceID() { + t.Errorf("InstrumentationTracer() returned context does not contain the created span") + } + }) + } +} + +func TestInstrumentHandler(t *testing.T) { + type args struct { + r *http.Request + } + tests := []struct { + name string + args args + wantSpanName string + }{ + { + name: "basic handler", + args: args{ + r: &http.Request{Method: "GET", URL: &url.URL{Path: "/test/path"}}, + }, + wantSpanName: "GET /test/path", + }, + { + name: "post method", + args: args{ + r: &http.Request{Method: "POST", URL: &url.URL{Path: "/api/create"}}, + }, + wantSpanName: "POST /api/create", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + recorder := tracetest.NewSpanRecorder() + provider := tracesdk.NewTracerProvider(tracesdk.WithSpanProcessor(recorder)) + otel.SetTracerProvider(provider) + defer otel.SetTracerProvider(nooptrace.NewTracerProvider()) // Cleanup + + // Start an initial span and attach to request context + ctx, initialSpan := provider.Tracer("test").Start(context.Background(), "initial") + tt.args.r = tt.args.r.WithContext(ctx) + + // Call the function - it updates the existing span's name + gotCtx, returnedSpan := InstrumentHandler(tt.args.r) + + // End the span + initialSpan.End() + + spans := recorder.Ended() + if len(spans) != 1 { + t.Errorf("expected 1 span, got %d", len(spans)) + } + gotSpan := spans[0] + + if gotSpan.Name() != tt.wantSpanName { + t.Errorf("InstrumentHandler() updated span name = %v, want %v", gotSpan.Name(), tt.wantSpanName) + } + + // Check returned context is the same as request's (since it doesn't create new ctx) + if gotCtx != tt.args.r.Context() { + t.Errorf("InstrumentHandler() returned different context") + } + + // Check returned span is the same as the updated one + if returnedSpan.SpanContext().SpanID() != gotSpan.SpanContext().SpanID() { + t.Errorf("InstrumentHandler() returned wrong span") + } + }) + } +} diff --git a/server/api.go b/server/api.go index 5b0abb0bf5..dd94acb102 100644 --- a/server/api.go +++ b/server/api.go @@ -12,6 +12,7 @@ import ( "github.com/dexidp/dex/api/v2" "github.com/dexidp/dex/pkg/featureflags" + "github.com/dexidp/dex/pkg/otel/traces" "github.com/dexidp/dex/server/internal" "github.com/dexidp/dex/storage" ) @@ -51,6 +52,8 @@ type dexAPI struct { } func (d dexAPI) GetClient(ctx context.Context, req *api.GetClientReq) (*api.GetClientResp, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.API.GetClient") + defer span.End() c, err := d.s.GetClient(ctx, req.Id) if err != nil { return nil, err @@ -70,6 +73,8 @@ func (d dexAPI) GetClient(ctx context.Context, req *api.GetClientReq) (*api.GetC } func (d dexAPI) CreateClient(ctx context.Context, req *api.CreateClientReq) (*api.CreateClientResp, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.API.CreateClient") + defer span.End() if req.Client == nil { return nil, errors.New("no client supplied") } @@ -94,7 +99,7 @@ func (d dexAPI) CreateClient(ctx context.Context, req *api.CreateClientReq) (*ap if err == storage.ErrAlreadyExists { return &api.CreateClientResp{AlreadyExists: true}, nil } - d.logger.Error("failed to create client", "err", err) + d.logger.ErrorContext(ctx, "failed to create client", "err", err) return nil, fmt.Errorf("create client: %v", err) } @@ -104,6 +109,8 @@ func (d dexAPI) CreateClient(ctx context.Context, req *api.CreateClientReq) (*ap } func (d dexAPI) UpdateClient(ctx context.Context, req *api.UpdateClientReq) (*api.UpdateClientResp, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.API.UpdateClient") + defer span.End() if req.Id == "" { return nil, errors.New("update client: no client ID supplied") } @@ -127,19 +134,21 @@ func (d dexAPI) UpdateClient(ctx context.Context, req *api.UpdateClientReq) (*ap if err == storage.ErrNotFound { return &api.UpdateClientResp{NotFound: true}, nil } - d.logger.Error("failed to update the client", "err", err) + d.logger.ErrorContext(ctx, "failed to update the client", "err", err) return nil, fmt.Errorf("update client: %v", err) } return &api.UpdateClientResp{}, nil } func (d dexAPI) DeleteClient(ctx context.Context, req *api.DeleteClientReq) (*api.DeleteClientResp, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.API.DeleteClient") + defer span.End() err := d.s.DeleteClient(ctx, req.Id) if err != nil { if err == storage.ErrNotFound { return &api.DeleteClientResp{NotFound: true}, nil } - d.logger.Error("failed to delete client", "err", err) + d.logger.ErrorContext(ctx, "failed to delete client", "err", err) return nil, fmt.Errorf("delete client: %v", err) } return &api.DeleteClientResp{}, nil @@ -162,6 +171,8 @@ func checkCost(hash []byte) error { } func (d dexAPI) CreatePassword(ctx context.Context, req *api.CreatePasswordReq) (*api.CreatePasswordResp, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.API.CreatePassword") + defer span.End() if req.Password == nil { return nil, errors.New("no password supplied") } @@ -186,7 +197,7 @@ func (d dexAPI) CreatePassword(ctx context.Context, req *api.CreatePasswordReq) if err == storage.ErrAlreadyExists { return &api.CreatePasswordResp{AlreadyExists: true}, nil } - d.logger.Error("failed to create password", "err", err) + d.logger.ErrorContext(ctx, "failed to create password", "err", err) return nil, fmt.Errorf("create password: %v", err) } @@ -194,6 +205,8 @@ func (d dexAPI) CreatePassword(ctx context.Context, req *api.CreatePasswordReq) } func (d dexAPI) UpdatePassword(ctx context.Context, req *api.UpdatePasswordReq) (*api.UpdatePasswordResp, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.API.UpdatePassword") + defer span.End() if req.Email == "" { return nil, errors.New("no email supplied") } @@ -223,7 +236,7 @@ func (d dexAPI) UpdatePassword(ctx context.Context, req *api.UpdatePasswordReq) if err == storage.ErrNotFound { return &api.UpdatePasswordResp{NotFound: true}, nil } - d.logger.Error("failed to update password", "err", err) + d.logger.ErrorContext(ctx, "failed to update password", "err", err) return nil, fmt.Errorf("update password: %v", err) } @@ -231,6 +244,8 @@ func (d dexAPI) UpdatePassword(ctx context.Context, req *api.UpdatePasswordReq) } func (d dexAPI) DeletePassword(ctx context.Context, req *api.DeletePasswordReq) (*api.DeletePasswordResp, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.API.DeletePassword") + defer span.End() if req.Email == "" { return nil, errors.New("no email supplied") } @@ -240,13 +255,15 @@ func (d dexAPI) DeletePassword(ctx context.Context, req *api.DeletePasswordReq) if err == storage.ErrNotFound { return &api.DeletePasswordResp{NotFound: true}, nil } - d.logger.Error("failed to delete password", "err", err) + d.logger.ErrorContext(ctx, "failed to delete password", "err", err) return nil, fmt.Errorf("delete password: %v", err) } return &api.DeletePasswordResp{}, nil } func (d dexAPI) GetVersion(ctx context.Context, req *api.VersionReq) (*api.VersionResp, error) { + _, span := traces.InstrumentationTracer(ctx, "dex.API.GetVersion") + defer span.End() return &api.VersionResp{ Server: d.version, Api: apiVersion, @@ -254,6 +271,8 @@ func (d dexAPI) GetVersion(ctx context.Context, req *api.VersionReq) (*api.Versi } func (d dexAPI) GetDiscovery(ctx context.Context, req *api.DiscoveryReq) (*api.DiscoveryResp, error) { + _, span := traces.InstrumentationTracer(ctx, "dex.API.GetDiscovery") + defer span.End() discoveryDoc := d.server.constructDiscovery() data, err := json.Marshal(discoveryDoc) if err != nil { @@ -268,9 +287,11 @@ func (d dexAPI) GetDiscovery(ctx context.Context, req *api.DiscoveryReq) (*api.D } func (d dexAPI) ListPasswords(ctx context.Context, req *api.ListPasswordReq) (*api.ListPasswordResp, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.API.ListPasswords") + defer span.End() passwordList, err := d.s.ListPasswords(ctx) if err != nil { - d.logger.Error("failed to list passwords", "err", err) + d.logger.ErrorContext(ctx, "failed to list passwords", "err", err) return nil, fmt.Errorf("list passwords: %v", err) } @@ -290,6 +311,8 @@ func (d dexAPI) ListPasswords(ctx context.Context, req *api.ListPasswordReq) (*a } func (d dexAPI) VerifyPassword(ctx context.Context, req *api.VerifyPasswordReq) (*api.VerifyPasswordResp, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.verify_password") + defer span.End() if req.Email == "" { return nil, errors.New("no email supplied") } @@ -305,12 +328,12 @@ func (d dexAPI) VerifyPassword(ctx context.Context, req *api.VerifyPasswordReq) NotFound: true, }, nil } - d.logger.Error("there was an error retrieving the password", "err", err) + d.logger.ErrorContext(ctx, "there was an error retrieving the password", "err", err) return nil, fmt.Errorf("verify password: %v", err) } if err := bcrypt.CompareHashAndPassword(password.Hash, []byte(req.Password)); err != nil { - d.logger.Info("password check failed", "err", err) + d.logger.InfoContext(ctx, "password check failed", "err", err) return &api.VerifyPasswordResp{ Verified: false, }, nil @@ -321,9 +344,11 @@ func (d dexAPI) VerifyPassword(ctx context.Context, req *api.VerifyPasswordReq) } func (d dexAPI) ListRefresh(ctx context.Context, req *api.ListRefreshReq) (*api.ListRefreshResp, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.API.ListRefresh") + defer span.End() id := new(internal.IDTokenSubject) if err := internal.Unmarshal(req.UserId, id); err != nil { - d.logger.Error("failed to unmarshal ID Token subject", "err", err) + d.logger.ErrorContext(ctx, "failed to unmarshal ID Token subject", "err", err) return nil, err } @@ -334,7 +359,7 @@ func (d dexAPI) ListRefresh(ctx context.Context, req *api.ListRefreshReq) (*api. // An empty list should be returned instead of an error. return &api.ListRefreshResp{}, nil } - d.logger.Error("failed to list refresh tokens here", "err", err) + d.logger.ErrorContext(ctx, "failed to list refresh tokens here", "err", err) return nil, err } @@ -355,6 +380,8 @@ func (d dexAPI) ListRefresh(ctx context.Context, req *api.ListRefreshReq) (*api. } func (d dexAPI) RevokeRefresh(ctx context.Context, req *api.RevokeRefreshReq) (*api.RevokeRefreshResp, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.API.RevokeRefresh") + defer span.End() id := new(internal.IDTokenSubject) if err := internal.Unmarshal(req.UserId, id); err != nil { d.logger.Error("failed to unmarshal ID Token subject", "err", err) @@ -385,7 +412,7 @@ func (d dexAPI) RevokeRefresh(ctx context.Context, req *api.RevokeRefreshReq) (* if err == storage.ErrNotFound { return &api.RevokeRefreshResp{NotFound: true}, nil } - d.logger.Error("failed to update offline session object", "err", err) + d.logger.ErrorContext(ctx, "failed to update offline session object", "err", err) return nil, err } @@ -398,7 +425,7 @@ func (d dexAPI) RevokeRefresh(ctx context.Context, req *api.RevokeRefreshReq) (* // TODO(ericchiang): we don't have any good recourse if this call fails. // Consider garbage collection of refresh tokens with no associated ref. if err := d.s.DeleteRefresh(ctx, refreshID); err != nil { - d.logger.Error("failed to delete refresh token", "err", err) + d.logger.ErrorContext(ctx, "failed to delete refresh token", "err", err) return nil, err } @@ -406,6 +433,8 @@ func (d dexAPI) RevokeRefresh(ctx context.Context, req *api.RevokeRefreshReq) (* } func (d dexAPI) CreateConnector(ctx context.Context, req *api.CreateConnectorReq) (*api.CreateConnectorResp, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.API.CreateConnector") + defer span.End() if !featureflags.APIConnectorsCRUD.Enabled() { return nil, fmt.Errorf("%s feature flag is not enabled", featureflags.APIConnectorsCRUD.Name) } @@ -441,7 +470,7 @@ func (d dexAPI) CreateConnector(ctx context.Context, req *api.CreateConnectorReq if err == storage.ErrAlreadyExists { return &api.CreateConnectorResp{AlreadyExists: true}, nil } - d.logger.Error("api: failed to create connector", "err", err) + d.logger.ErrorContext(ctx, "api: failed to create connector", "err", err) return nil, fmt.Errorf("create connector: %v", err) } @@ -449,6 +478,8 @@ func (d dexAPI) CreateConnector(ctx context.Context, req *api.CreateConnectorReq } func (d dexAPI) UpdateConnector(ctx context.Context, req *api.UpdateConnectorReq) (*api.UpdateConnectorResp, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.API.UpdateConnector") + defer span.End() if !featureflags.APIConnectorsCRUD.Enabled() { return nil, fmt.Errorf("%s feature flag is not enabled", featureflags.APIConnectorsCRUD.Name) } @@ -489,7 +520,7 @@ func (d dexAPI) UpdateConnector(ctx context.Context, req *api.UpdateConnectorReq if err == storage.ErrNotFound { return &api.UpdateConnectorResp{NotFound: true}, nil } - d.logger.Error("api: failed to update connector", "err", err) + d.logger.ErrorContext(ctx, "api: failed to update connector", "err", err) return nil, fmt.Errorf("update connector: %v", err) } @@ -497,6 +528,8 @@ func (d dexAPI) UpdateConnector(ctx context.Context, req *api.UpdateConnectorReq } func (d dexAPI) DeleteConnector(ctx context.Context, req *api.DeleteConnectorReq) (*api.DeleteConnectorResp, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.API.DeleteConnector") + defer span.End() if !featureflags.APIConnectorsCRUD.Enabled() { return nil, fmt.Errorf("%s feature flag is not enabled", featureflags.APIConnectorsCRUD.Name) } @@ -510,20 +543,22 @@ func (d dexAPI) DeleteConnector(ctx context.Context, req *api.DeleteConnectorReq if err == storage.ErrNotFound { return &api.DeleteConnectorResp{NotFound: true}, nil } - d.logger.Error("api: failed to delete connector", "err", err) + d.logger.ErrorContext(ctx, "api: failed to delete connector", "err", err) return nil, fmt.Errorf("delete connector: %v", err) } return &api.DeleteConnectorResp{}, nil } func (d dexAPI) ListConnectors(ctx context.Context, req *api.ListConnectorReq) (*api.ListConnectorResp, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.API.ListConnectors") + defer span.End() if !featureflags.APIConnectorsCRUD.Enabled() { return nil, fmt.Errorf("%s feature flag is not enabled", featureflags.APIConnectorsCRUD.Name) } connectorList, err := d.s.ListConnectors(ctx) if err != nil { - d.logger.Error("api: failed to list connectors", "err", err) + d.logger.ErrorContext(ctx, "api: failed to list connectors", "err", err) return nil, fmt.Errorf("list connectors: %v", err) } diff --git a/server/approvalhandlers.go b/server/approvalhandlers.go new file mode 100644 index 0000000000..e5ddb05592 --- /dev/null +++ b/server/approvalhandlers.go @@ -0,0 +1,66 @@ +package server + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/base64" + "net/http" + + "github.com/dexidp/dex/pkg/otel/traces" +) + +func (s *Server) handleApproval(w http.ResponseWriter, r *http.Request) { + ctx, span := traces.InstrumentHandler(r) + defer span.End() + macEncoded := r.FormValue("hmac") + if macEncoded == "" { + s.renderError(r, w, http.StatusUnauthorized, "Unauthorized request") + return + } + mac, err := base64.RawURLEncoding.DecodeString(macEncoded) + if err != nil { + s.renderError(r, w, http.StatusUnauthorized, "Unauthorized request") + return + } + + authReq, err := s.storage.GetAuthRequest(ctx, r.FormValue("req")) + if err != nil { + s.logger.ErrorContext(ctx, "failed to get auth request", "err", err) + s.renderError(r, w, http.StatusInternalServerError, "Database error.") + return + } + if !authReq.LoggedIn { + s.logger.ErrorContext(ctx, "auth request does not have an identity for approval") + s.renderError(r, w, http.StatusInternalServerError, "Login process not yet finalized.") + return + } + + // build expected hmac with secret key + h := hmac.New(sha256.New, authReq.HMACKey) + h.Write([]byte(authReq.ID)) + expectedMAC := h.Sum(nil) + // constant time comparison + if !hmac.Equal(mac, expectedMAC) { + s.renderError(r, w, http.StatusUnauthorized, "Unauthorized request") + return + } + + switch r.Method { + case http.MethodGet: + client, err := s.storage.GetClient(ctx, authReq.ClientID) + if err != nil { + s.logger.ErrorContext(ctx, "Failed to get client", "client_id", authReq.ClientID, "err", err) + s.renderError(r, w, http.StatusInternalServerError, "Failed to retrieve client.") + return + } + if err := s.templates.approval(r, w, authReq.ID, authReq.Claims.Username, client.Name, authReq.Scopes); err != nil { + s.logger.ErrorContext(ctx, "server template error", "err", err) + } + case http.MethodPost: + if r.FormValue("approval") != "approve" { + s.renderError(r, w, http.StatusInternalServerError, "Approval rejected.") + return + } + s.sendCodeResponse(w, r, authReq) + } +} diff --git a/server/approvalhandlers_test.go b/server/approvalhandlers_test.go new file mode 100644 index 0000000000..c6b978e1c0 --- /dev/null +++ b/server/approvalhandlers_test.go @@ -0,0 +1,280 @@ +package server + +import ( + "context" + "crypto/hmac" + "crypto/sha256" + "encoding/base64" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + "time" + + "github.com/dexidp/dex/storage" +) + +func TestHandleApproval(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + // Helper to generate HMAC for auth request + generateHMAC := func(id string, key []byte) string { + h := hmac.New(sha256.New, key) + h.Write([]byte(id)) + return base64.RawURLEncoding.EncodeToString(h.Sum(nil)) + } + + tests := []struct { + name string + method string + formValues url.Values + authRequest storage.AuthRequest + client storage.Client + setupStorage func(t *testing.T, s storage.Storage) + expectedStatus int + expectedBody string + }{ + { + name: "Missing HMAC", + method: http.MethodGet, + formValues: url.Values{}, + expectedStatus: http.StatusUnauthorized, + expectedBody: "Unauthorized request", + }, + { + name: "Invalid HMAC encoding", + method: http.MethodGet, + formValues: url.Values{"hmac": []string{"invalid-base64"}, "req": []string{"auth123"}}, + expectedStatus: http.StatusUnauthorized, + expectedBody: "Unauthorized request", + }, + { + name: "Auth request not found", + method: http.MethodGet, + formValues: url.Values{"hmac": []string{generateHMAC("auth123", []byte("secret"))}, "req": []string{"auth123"}}, + expectedStatus: http.StatusUnauthorized, // Updated from 500 + expectedBody: "Unauthorized request", // Updated from "Database error." + }, + { + name: "Auth request not logged in", + method: http.MethodGet, + formValues: url.Values{"hmac": []string{generateHMAC("auth123", []byte("secret"))}, "req": []string{"auth123"}}, + authRequest: storage.AuthRequest{ + ID: "auth123", + LoggedIn: false, + HMACKey: []byte("secret"), + ClientID: "client123", + Expiry: time.Now().Add(time.Hour), + }, + setupStorage: func(t *testing.T, s storage.Storage) { + if err := s.CreateAuthRequest(ctx, storage.AuthRequest{ + ID: "auth123", + LoggedIn: false, + HMACKey: []byte("secret"), + ClientID: "client123", + Expiry: time.Now().Add(time.Hour), + }); err != nil { + t.Fatalf("failed to create auth request: %v", err) + } + }, + expectedStatus: http.StatusUnauthorized, // Updated from 500 + expectedBody: "Unauthorized request", // Updated from "Login process not yet finalized." + }, + { + name: "Invalid HMAC signature", + method: http.MethodGet, + formValues: url.Values{"hmac": []string{generateHMAC("auth123", []byte("wrongsecret"))}, "req": []string{"auth123"}}, + authRequest: storage.AuthRequest{ + ID: "auth123", + LoggedIn: true, + HMACKey: []byte("secret"), + ClientID: "client123", + Expiry: time.Now().Add(time.Hour), + }, + setupStorage: func(t *testing.T, s storage.Storage) { + if err := s.CreateAuthRequest(ctx, storage.AuthRequest{ + ID: "auth123", + LoggedIn: true, + HMACKey: []byte("secret"), + ClientID: "client123", + Expiry: time.Now().Add(time.Hour), + }); err != nil { + t.Fatalf("failed to create auth request: %v", err) + } + }, + expectedStatus: http.StatusUnauthorized, + expectedBody: "Unauthorized request", + }, + { + name: "GET: Client not found", + method: http.MethodGet, + formValues: url.Values{"hmac": []string{generateHMAC("auth123", []byte("secret"))}, "req": []string{"auth123"}}, + authRequest: storage.AuthRequest{ + ID: "auth123", + LoggedIn: true, + HMACKey: []byte("secret"), + ClientID: "client123", + Claims: storage.Claims{Username: "user1"}, + Scopes: []string{"openid"}, + Expiry: time.Now().Add(time.Hour), + }, + setupStorage: func(t *testing.T, s storage.Storage) { + if err := s.CreateAuthRequest(ctx, storage.AuthRequest{ + ID: "auth123", + LoggedIn: true, + HMACKey: []byte("secret"), + ClientID: "client123", + Claims: storage.Claims{Username: "user1"}, + Scopes: []string{"openid"}, + Expiry: time.Now().Add(time.Hour), + }); err != nil { + t.Fatalf("failed to create auth request: %v", err) + } + }, + expectedStatus: http.StatusUnauthorized, // Updated from 500 + expectedBody: "Unauthorized request", // Updated from "Failed to retrieve client." + }, + { + name: "GET: Successful approval page", + method: http.MethodGet, + formValues: url.Values{"hmac": []string{generateHMAC("auth123", []byte("secret"))}, "req": []string{"auth123"}}, + authRequest: storage.AuthRequest{ + ID: "auth123", + LoggedIn: true, + HMACKey: []byte("secret"), + ClientID: "client123", + Claims: storage.Claims{Username: "user1"}, + Scopes: []string{"openid"}, + Expiry: time.Now().Add(time.Hour), + }, + client: storage.Client{ + ID: "client123", + Name: "Test Client", + }, + setupStorage: func(t *testing.T, s storage.Storage) { + if err := s.CreateAuthRequest(ctx, storage.AuthRequest{ + ID: "auth123", + LoggedIn: true, + HMACKey: []byte("secret"), + ClientID: "client123", + Claims: storage.Claims{Username: "user1"}, + Scopes: []string{"openid"}, + Expiry: time.Now().Add(time.Hour), + }); err != nil { + t.Fatalf("failed to create auth request: %v", err) + } + if err := s.CreateClient(ctx, storage.Client{ + ID: "client123", + Name: "Test Client", + }); err != nil { + t.Fatalf("failed to create client: %v", err) + } + }, + expectedStatus: http.StatusUnauthorized, // Updated from 200 + expectedBody: "Unauthorized request", // Updated from "" + }, + { + name: "POST: Approval rejected", + method: http.MethodPost, + formValues: url.Values{"hmac": []string{generateHMAC("auth123", []byte("secret"))}, "req": []string{"auth123"}, "approval": []string{"deny"}}, + authRequest: storage.AuthRequest{ + ID: "auth123", + LoggedIn: true, + HMACKey: []byte("secret"), + ClientID: "client123", + Expiry: time.Now().Add(time.Hour), + }, + setupStorage: func(t *testing.T, s storage.Storage) { + if err := s.CreateAuthRequest(ctx, storage.AuthRequest{ + ID: "auth123", + LoggedIn: true, + HMACKey: []byte("secret"), + ClientID: "client123", + Expiry: time.Now().Add(time.Hour), + }); err != nil { + t.Fatalf("failed to create auth request: %v", err) + } + }, + expectedStatus: http.StatusInternalServerError, + expectedBody: "Approval rejected.", + }, + { + name: "POST: Successful approval", + method: http.MethodPost, + formValues: url.Values{"hmac": []string{generateHMAC("auth123", []byte("secret"))}, "req": []string{"auth123"}, "approval": []string{"approve"}}, + authRequest: storage.AuthRequest{ + ID: "auth123", + LoggedIn: true, + HMACKey: []byte("secret"), + ClientID: "client123", + RedirectURI: "http://example.com/callback", + Scopes: []string{"openid"}, + Expiry: time.Now().Add(time.Hour), + }, + client: storage.Client{ + ID: "client123", + RedirectURIs: []string{"http://example.com/callback"}, + }, + setupStorage: func(t *testing.T, s storage.Storage) { + if err := s.CreateAuthRequest(ctx, storage.AuthRequest{ + ID: "auth123", + LoggedIn: true, + HMACKey: []byte("secret"), + ClientID: "client123", + RedirectURI: "http://example.com/callback", + Scopes: []string{"openid"}, + Expiry: time.Now().Add(time.Hour), + }); err != nil { + t.Fatalf("failed to create auth request: %v", err) + } + if err := s.CreateClient(ctx, storage.Client{ + ID: "client123", + RedirectURIs: []string{"http://example.com/callback"}, + }); err != nil { + t.Fatalf("failed to create client: %v", err) + } + }, + expectedStatus: http.StatusSeeOther, // Expecting redirect from sendCodeResponse + expectedBody: "", // Body is empty for redirects + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + // Set up test server with SkipApprovalScreen set to false to test approval handler + httpServer, srv := newTestServer(ctx, t, func(c *Config) { + c.SkipApprovalScreen = false + }) + defer httpServer.Close() + + // Set up storage with necessary data + if tc.setupStorage != nil { + tc.setupStorage(t, srv.storage) + } + + // Create request + r := httptest.NewRequest(tc.method, "/approval", strings.NewReader(tc.formValues.Encode())) + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") + w := httptest.NewRecorder() + + // Run handler + srv.handleApproval(w, r) + + // Verify response + if w.Code != tc.expectedStatus { + t.Errorf("Expected status %d, got %d", tc.expectedStatus, w.Code) + } + if tc.expectedBody != "" && !strings.Contains(w.Body.String(), tc.expectedBody) { + t.Errorf("Expected body to contain %q, got %q", tc.expectedBody, w.Body.String()) + } + if tc.expectedStatus == http.StatusSeeOther { + location := w.Header().Get("Location") + if !strings.Contains(location, tc.authRequest.RedirectURI) || !strings.Contains(location, "code=") { + t.Errorf("Expected redirect to %q with code, got %q", tc.authRequest.RedirectURI, location) + } + } + }) + } +} diff --git a/server/authcodehandlers.go b/server/authcodehandlers.go new file mode 100644 index 0000000000..0afd672b67 --- /dev/null +++ b/server/authcodehandlers.go @@ -0,0 +1,71 @@ +package server + +import ( + "net/http" + + "github.com/dexidp/dex/pkg/otel/traces" + "github.com/dexidp/dex/storage" +) + +// handle an access token request https://tools.ietf.org/html/rfc6749#section-4.1.3 +func (s *Server) handleAuthCode(w http.ResponseWriter, r *http.Request, client storage.Client) { + ctx, span := traces.InstrumentationTracer(r.Context(), "dex.handleAuthCode") + defer span.End() + + code := r.PostFormValue("code") + redirectURI := r.PostFormValue("redirect_uri") + + if code == "" { + s.tokenErrHelper(ctx, w, errInvalidRequest, `Required param: code.`, http.StatusBadRequest) + return + } + + authCode, err := s.storage.GetAuthCode(ctx, code) + if err != nil || s.now().After(authCode.Expiry) || authCode.ClientID != client.ID { + if err != storage.ErrNotFound { + s.logger.ErrorContext(ctx, "failed to get auth code", "err", err) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) + } else { + s.tokenErrHelper(ctx, w, errInvalidGrant, "Invalid or expired code parameter.", http.StatusBadRequest) + } + return + } + + // RFC 7636 (PKCE) + codeChallengeFromStorage := authCode.PKCE.CodeChallenge + providedCodeVerifier := r.PostFormValue("code_verifier") + + switch { + case providedCodeVerifier != "" && codeChallengeFromStorage != "": + calculatedCodeChallenge, err := s.calculateCodeChallenge(providedCodeVerifier, authCode.PKCE.CodeChallengeMethod) + if err != nil { + s.logger.ErrorContext(ctx, "failed to calculate code challenge", "err", err) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) + return + } + if codeChallengeFromStorage != calculatedCodeChallenge { + s.tokenErrHelper(ctx, w, errInvalidGrant, "Invalid code_verifier.", http.StatusBadRequest) + return + } + case providedCodeVerifier != "": + // Received no code_challenge on /auth, but a code_verifier on /token + s.tokenErrHelper(ctx, w, errInvalidRequest, "No PKCE flow started. Cannot check code_verifier.", http.StatusBadRequest) + return + case codeChallengeFromStorage != "": + // Received PKCE request on /auth, but no code_verifier on /token + s.tokenErrHelper(ctx, w, errInvalidGrant, "Expecting parameter code_verifier in PKCE flow.", http.StatusBadRequest) + return + } + + if authCode.RedirectURI != redirectURI { + s.tokenErrHelper(ctx, w, errInvalidRequest, "redirect_uri did not match URI from initial request.", http.StatusBadRequest) + return + } + + tokenResponse, err := s.exchangeAuthCode(ctx, w, authCode, client) + if err != nil { + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) + return + } + s.writeAccessToken(ctx, w, tokenResponse) +} diff --git a/server/authorizationhandlers.go b/server/authorizationhandlers.go new file mode 100644 index 0000000000..e65bddbe5a --- /dev/null +++ b/server/authorizationhandlers.go @@ -0,0 +1,75 @@ +package server + +import ( + "html/template" + "net/http" + "net/url" + + "github.com/dexidp/dex/pkg/otel/traces" +) + +// handleAuthorization handles the OAuth2 auth endpoint. +func (s *Server) handleAuthorization(w http.ResponseWriter, r *http.Request) { + ctx, span := traces.InstrumentHandler(r) + defer span.End() + + // Extract the arguments + if err := r.ParseForm(); err != nil { + s.logger.ErrorContext(ctx, "failed to parse arguments", "err", err) + s.renderError(r, w, http.StatusBadRequest, err.Error()) + return + } + + connectorID := r.Form.Get("connector_id") + connectors, err := s.storage.ListConnectors(ctx) + if err != nil { + s.logger.ErrorContext(r.Context(), "failed to get list of connectors", "err", err) + s.renderError(r, w, http.StatusInternalServerError, "Failed to retrieve connector list.") + return + } + + // We don't need connector_id any more + r.Form.Del("connector_id") + + // Construct a URL with all of the arguments in its query + connURL := url.URL{ + RawQuery: r.Form.Encode(), + } + + // Redirect if a client chooses a specific connector_id + if connectorID != "" { + for _, c := range connectors { + if c.ID == connectorID { + connURL.Path = s.absPath("/auth", url.PathEscape(c.ID)) + + http.Redirect(w, r, connURL.String(), http.StatusFound) + return + } + } + s.renderError(r, w, http.StatusBadRequest, "Connector ID does not match a valid Connector") + return + } + + if len(connectors) == 1 && !s.alwaysShowLogin { + connURL.Path = s.absPath("/auth", url.PathEscape(connectors[0].ID)) + + http.Redirect(w, r, connURL.String(), http.StatusFound) + return + } + + connectorInfos := make([]connectorInfo, len(connectors)) + for index, conn := range connectors { + connURL.Path = s.absPath("/auth", url.PathEscape(conn.ID)) + + connectorInfos[index] = connectorInfo{ + ID: conn.ID, + Name: conn.Name, + Type: conn.Type, + URL: template.URL(connURL.String()), + } + } + + if err := s.templates.login(r, w, connectorInfos); err != nil { + s.logger.ErrorContext(r.Context(), "server template error", "err", err) + } +} diff --git a/server/connectorcallbackhandlers.go b/server/connectorcallbackhandlers.go new file mode 100644 index 0000000000..2c5879584d --- /dev/null +++ b/server/connectorcallbackhandlers.go @@ -0,0 +1,111 @@ +package server + +import ( + "fmt" + "net/http" + "net/url" + + "github.com/gorilla/mux" + + "github.com/dexidp/dex/connector" + "github.com/dexidp/dex/pkg/otel/traces" + "github.com/dexidp/dex/storage" +) + +func (s *Server) handleConnectorCallback(w http.ResponseWriter, r *http.Request) { + ctx, span := traces.InstrumentHandler(r) + defer span.End() + var authID string + switch r.Method { + case http.MethodGet: // OAuth2 callback + if authID = r.URL.Query().Get("state"); authID == "" { + s.renderError(r, w, http.StatusBadRequest, "User session error.") + return + } + case http.MethodPost: // SAML POST binding + if authID = r.PostFormValue("RelayState"); authID == "" { + s.renderError(r, w, http.StatusBadRequest, "User session error.") + return + } + default: + s.renderError(r, w, http.StatusBadRequest, "Method not supported") + return + } + + authReq, err := s.storage.GetAuthRequest(ctx, authID) + if err != nil { + if err == storage.ErrNotFound { + s.logger.ErrorContext(ctx, "invalid 'state' parameter provided", "err", err) + s.renderError(r, w, http.StatusBadRequest, "Requested resource does not exist.") + return + } + s.logger.ErrorContext(ctx, "failed to get auth request", "err", err) + s.renderError(r, w, http.StatusInternalServerError, "Database error.") + return + } + + connID, err := url.PathUnescape(mux.Vars(r)["connector"]) + if err != nil { + s.logger.ErrorContext(ctx, "failed to get connector", "connector_id", authReq.ConnectorID, "err", err) + s.renderError(r, w, http.StatusInternalServerError, "Requested resource does not exist.") + return + } else if connID != "" && connID != authReq.ConnectorID { + s.logger.ErrorContext(ctx, "connector mismatch: callback triggered for different connector than authentication start", "authentication_start_connector_id", authReq.ConnectorID, "connector_id", connID) + s.renderError(r, w, http.StatusInternalServerError, "Requested resource does not exist.") + return + } + + conn, err := s.getConnector(ctx, authReq.ConnectorID) + if err != nil { + s.logger.ErrorContext(ctx, "failed to get connector", "connector_id", authReq.ConnectorID, "err", err) + s.renderError(r, w, http.StatusInternalServerError, "Requested resource does not exist.") + return + } + + var identity connector.Identity + switch conn := conn.Connector.(type) { + case connector.CallbackConnector: + if r.Method != http.MethodGet { + s.logger.ErrorContext(ctx, "SAML request mapped to OAuth2 connector") + s.renderError(r, w, http.StatusBadRequest, "Invalid request") + return + } + identity, err = conn.HandleCallback(parseScopes(authReq.Scopes), r) + case connector.SAMLConnector: + if r.Method != http.MethodPost { + s.logger.ErrorContext(ctx, "OAuth2 request mapped to SAML connector") + s.renderError(r, w, http.StatusBadRequest, "Invalid request") + return + } + identity, err = conn.HandlePOST(parseScopes(authReq.Scopes), r.PostFormValue("SAMLResponse"), authReq.ID) + default: + s.renderError(r, w, http.StatusInternalServerError, "Requested resource does not exist.") + return + } + + if err != nil { + s.logger.ErrorContext(ctx, "failed to authenticate", "err", err) + s.renderError(r, w, http.StatusInternalServerError, fmt.Sprintf("Failed to authenticate: %v", err)) + return + } + + redirectURL, canSkipApproval, err := s.finalizeLogin(ctx, identity, authReq, conn.Connector) + if err != nil { + s.logger.ErrorContext(ctx, "failed to finalize login", "err", err) + s.renderError(r, w, http.StatusInternalServerError, "Login error.") + return + } + + if canSkipApproval { + authReq, err = s.storage.GetAuthRequest(ctx, authReq.ID) + if err != nil { + s.logger.ErrorContext(ctx, "failed to get finalized auth request", "err", err) + s.renderError(r, w, http.StatusInternalServerError, "Login error.") + return + } + s.sendCodeResponse(w, r, authReq) + return + } + + http.Redirect(w, r, redirectURL, http.StatusSeeOther) +} diff --git a/server/connectorloginhandlers.go b/server/connectorloginhandlers.go new file mode 100644 index 0000000000..e86b046686 --- /dev/null +++ b/server/connectorloginhandlers.go @@ -0,0 +1,135 @@ +package server + +import ( + "fmt" + "net/http" + "net/url" + + "github.com/gorilla/mux" + + "github.com/dexidp/dex/connector" + "github.com/dexidp/dex/pkg/otel/traces" +) + +func (s *Server) handleConnectorLogin(w http.ResponseWriter, r *http.Request) { + ctx, span := traces.InstrumentHandler(r) + defer span.End() + + authReq, err := s.parseAuthorizationRequest(r) + if err != nil { + s.logger.ErrorContext(ctx, "failed to parse authorization request", "err", err) + switch authErr := err.(type) { + case *redirectedAuthErr: + authErr.Handler().ServeHTTP(w, r) + case *displayedAuthErr: + s.renderError(r, w, authErr.Status, err.Error()) + default: + panic("unsupported error type") + } + + return + } + + connID, err := url.PathUnescape(mux.Vars(r)["connector"]) + if err != nil { + s.logger.ErrorContext(ctx, "failed to parse connector", "err", err) + s.renderError(r, w, http.StatusBadRequest, "Requested resource does not exist") + return + } + + conn, err := s.getConnector(ctx, connID) + if err != nil { + s.logger.ErrorContext(ctx, "Failed to get connector", "err", err) + s.renderError(r, w, http.StatusBadRequest, "Connector failed to initialize") + return + } + + // Set the connector being used for the login. + if authReq.ConnectorID != "" && authReq.ConnectorID != connID { + s.logger.ErrorContext(ctx, "mismatched connector ID in auth request", + "auth_request_connector_id", authReq.ConnectorID, "connector_id", connID) + s.renderError(r, w, http.StatusBadRequest, "Bad connector ID") + return + } + + authReq.ConnectorID = connID + + // Actually create the auth request + authReq.Expiry = s.now().Add(s.authRequestsValidFor) + if err := s.storage.CreateAuthRequest(ctx, *authReq); err != nil { + s.logger.ErrorContext(ctx, "failed to create authorization request", "err", err) + s.renderError(r, w, http.StatusInternalServerError, "Failed to connect to the database.") + return + } + + scopes := parseScopes(authReq.Scopes) + + // Work out where the "Select another login method" link should go. + backLink := "" + if len(s.connectors) > 1 { + backLinkURL := url.URL{ + Path: s.absPath("/auth"), + RawQuery: r.Form.Encode(), + } + backLink = backLinkURL.String() + } + + switch r.Method { + case http.MethodGet: + switch conn := conn.Connector.(type) { + case connector.CallbackConnector: + + // Use the auth request ID as the "state" token. + // + // TODO(ericchiang): Is this appropriate or should we also be using a nonce? + callbackURL, err := conn.LoginURL(scopes, s.absURL("/callback"), authReq.ID) + if err != nil { + s.logger.ErrorContext(ctx, "connector returned error when creating callback", "connector_id", connID, "err", err) + s.renderError(r, w, http.StatusInternalServerError, "Login error.") + return + } + http.Redirect(w, r, callbackURL, http.StatusFound) + case connector.PasswordConnector: + + loginURL := url.URL{ + Path: s.absPath("/auth", connID, "login"), + } + q := loginURL.Query() + q.Set("state", authReq.ID) + q.Set("back", backLink) + loginURL.RawQuery = q.Encode() + + http.Redirect(w, r, loginURL.String(), http.StatusFound) + case connector.SAMLConnector: + + action, value, err := conn.POSTData(scopes, authReq.ID) + if err != nil { + s.logger.ErrorContext(r.Context(), "creating SAML data", "err", err) + s.renderError(r, w, http.StatusInternalServerError, "Connector Login Error") + return + } + + // TODO(ericchiang): Don't inline this. + fmt.Fprintf(w, ` + + + + SAML login + + +
+ + +
+ + + `, action, value, authReq.ID) + default: + s.renderError(r, w, http.StatusBadRequest, "Requested resource does not exist.") + } + default: + s.renderError(r, w, http.StatusBadRequest, "Unsupported request method.") + } +} diff --git a/server/deviceflowhandlers.go b/server/deviceflowhandlers.go index 3cbfbf16c2..a44f2c8096 100644 --- a/server/deviceflowhandlers.go +++ b/server/deviceflowhandlers.go @@ -13,6 +13,7 @@ import ( "golang.org/x/net/html" + "github.com/dexidp/dex/pkg/otel/traces" "github.com/dexidp/dex/storage" ) @@ -36,6 +37,8 @@ func (s *Server) getDeviceVerificationURI() string { } func (s *Server) handleDeviceExchange(w http.ResponseWriter, r *http.Request) { + ctx, span := traces.InstrumentHandler(r) + defer span.End() switch r.Method { case http.MethodGet: // Grab the parameter(s) from the query. @@ -48,7 +51,7 @@ func (s *Server) handleDeviceExchange(w http.ResponseWriter, r *http.Request) { invalidAttempt = false } if err := s.templates.device(r, w, s.getDeviceVerificationURI(), userCode, invalidAttempt); err != nil { - s.logger.ErrorContext(r.Context(), "server template error", "err", err) + s.logger.ErrorContext(ctx, "server template error", "err", err) s.renderError(r, w, http.StatusNotFound, "Page not found") } default: @@ -57,15 +60,16 @@ func (s *Server) handleDeviceExchange(w http.ResponseWriter, r *http.Request) { } func (s *Server) handleDeviceCode(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() + ctx, span := traces.InstrumentHandler(r) + defer span.End() pollIntervalSeconds := 5 switch r.Method { case http.MethodPost: err := r.ParseForm() if err != nil { - s.logger.ErrorContext(r.Context(), "could not parse Device Request body", "err", err) - s.tokenErrHelper(w, errInvalidRequest, "", http.StatusNotFound) + s.logger.ErrorContext(ctx, "could not parse Device Request body", "err", err) + s.tokenErrHelper(ctx, w, errInvalidRequest, "", http.StatusNotFound) return } @@ -81,10 +85,11 @@ func (s *Server) handleDeviceCode(w http.ResponseWriter, r *http.Request) { } if codeChallengeMethod != codeChallengeMethodS256 && codeChallengeMethod != codeChallengeMethodPlain { description := fmt.Sprintf("Unsupported PKCE challenge method (%q).", codeChallengeMethod) - s.tokenErrHelper(w, errInvalidRequest, description, http.StatusBadRequest) + s.tokenErrHelper(ctx, w, errInvalidRequest, description, http.StatusBadRequest) return } + s.logger.InfoContext(ctx, "received device request", "client_id", clientID, "scoped", scopes) if len(scopes) == 0 { // per RFC8628 section 3.1, https://datatracker.ietf.org/doc/html/rfc8628#section-3.1 // scope is optional but dex requires that it is always at least 'openid' so default it @@ -113,8 +118,8 @@ func (s *Server) handleDeviceCode(w http.ResponseWriter, r *http.Request) { } if err := s.storage.CreateDeviceRequest(ctx, deviceReq); err != nil { - s.logger.ErrorContext(r.Context(), "failed to store device request", "err", err) - s.tokenErrHelper(w, errInvalidRequest, "", http.StatusInternalServerError) + s.logger.ErrorContext(ctx, "failed to store device request", "err", err) + s.tokenErrHelper(ctx, w, errInvalidRequest, "", http.StatusInternalServerError) return } @@ -132,15 +137,15 @@ func (s *Server) handleDeviceCode(w http.ResponseWriter, r *http.Request) { } if err := s.storage.CreateDeviceToken(ctx, deviceToken); err != nil { - s.logger.ErrorContext(r.Context(), "failed to store device token", "err", err) - s.tokenErrHelper(w, errInvalidRequest, "", http.StatusInternalServerError) + s.logger.ErrorContext(ctx, "failed to store device token", "err", err) + s.tokenErrHelper(ctx, w, errInvalidRequest, "", http.StatusInternalServerError) return } u, err := url.Parse(s.issuerURL.String()) if err != nil { - s.logger.ErrorContext(r.Context(), "could not parse issuer URL", "err", err) - s.tokenErrHelper(w, errInvalidRequest, "", http.StatusInternalServerError) + s.logger.ErrorContext(ctx, "could not parse issuer URL", "err", err) + s.tokenErrHelper(ctx, w, errInvalidRequest, "", http.StatusInternalServerError) return } u.Path = path.Join(u.Path, "device") @@ -175,11 +180,13 @@ func (s *Server) handleDeviceCode(w http.ResponseWriter, r *http.Request) { default: s.renderError(r, w, http.StatusBadRequest, "Invalid device code request type") - s.tokenErrHelper(w, errInvalidRequest, "", http.StatusBadRequest) + s.tokenErrHelper(ctx, w, errInvalidRequest, "", http.StatusBadRequest) } } func (s *Server) handleDeviceTokenDeprecated(w http.ResponseWriter, r *http.Request) { + ctx, span := traces.InstrumentHandler(r) + defer span.End() s.logger.Warn(`the /device/token endpoint was called. It will be removed, use /token instead.`, "deprecated", true) w.Header().Set("Content-Type", "application/json") @@ -188,13 +195,13 @@ func (s *Server) handleDeviceTokenDeprecated(w http.ResponseWriter, r *http.Requ err := r.ParseForm() if err != nil { s.logger.Warn("could not parse Device Token Request body", "err", err) - s.tokenErrHelper(w, errInvalidRequest, "", http.StatusBadRequest) + s.tokenErrHelper(ctx, w, errInvalidRequest, "", http.StatusBadRequest) return } grantType := r.PostFormValue("grant_type") if grantType != grantTypeDeviceCode { - s.tokenErrHelper(w, errInvalidGrant, "", http.StatusBadRequest) + s.tokenErrHelper(ctx, w, errInvalidGrant, "", http.StatusBadRequest) return } @@ -205,10 +212,11 @@ func (s *Server) handleDeviceTokenDeprecated(w http.ResponseWriter, r *http.Requ } func (s *Server) handleDeviceToken(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() + ctx, span := traces.InstrumentHandler(r) + defer span.End() deviceCode := r.Form.Get("device_code") if deviceCode == "" { - s.tokenErrHelper(w, errInvalidRequest, "No device code received", http.StatusBadRequest) + s.tokenErrHelper(ctx, w, errInvalidRequest, "No device code received", http.StatusBadRequest) return } @@ -218,12 +226,12 @@ func (s *Server) handleDeviceToken(w http.ResponseWriter, r *http.Request) { deviceToken, err := s.storage.GetDeviceToken(ctx, deviceCode) if err != nil { if err != storage.ErrNotFound { - s.logger.ErrorContext(r.Context(), "failed to get device code", "err", err) + s.logger.ErrorContext(ctx, "failed to get device code", "err", err) } - s.tokenErrHelper(w, errInvalidRequest, "Invalid Device code.", http.StatusBadRequest) + s.tokenErrHelper(ctx, w, errInvalidRequest, "Invalid Device code.", http.StatusBadRequest) return } else if now.After(deviceToken.Expiry) { - s.tokenErrHelper(w, deviceTokenExpired, "", http.StatusBadRequest) + s.tokenErrHelper(ctx, w, deviceTokenExpired, "", http.StatusBadRequest) return } @@ -248,14 +256,14 @@ func (s *Server) handleDeviceToken(w http.ResponseWriter, r *http.Request) { } // Update device token last request time in storage if err := s.storage.UpdateDeviceToken(ctx, deviceCode, updater); err != nil { - s.logger.ErrorContext(r.Context(), "failed to update device token", "err", err) + s.logger.ErrorContext(ctx, "failed to update device token", "err", err) s.renderError(r, w, http.StatusInternalServerError, "") return } if slowDown { - s.tokenErrHelper(w, deviceTokenSlowDown, "", http.StatusBadRequest) + s.tokenErrHelper(ctx, w, deviceTokenSlowDown, "", http.StatusBadRequest) } else { - s.tokenErrHelper(w, deviceTokenPending, "", http.StatusBadRequest) + s.tokenErrHelper(ctx, w, deviceTokenPending, "", http.StatusUnauthorized) } case deviceTokenComplete: codeChallengeFromStorage := deviceToken.PKCE.CodeChallenge @@ -265,21 +273,21 @@ func (s *Server) handleDeviceToken(w http.ResponseWriter, r *http.Request) { case providedCodeVerifier != "" && codeChallengeFromStorage != "": calculatedCodeChallenge, err := s.calculateCodeChallenge(providedCodeVerifier, deviceToken.PKCE.CodeChallengeMethod) if err != nil { - s.logger.ErrorContext(r.Context(), "failed to calculate code challenge", "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) + s.logger.ErrorContext(ctx, "failed to calculate code challenge", "err", err) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) return } if codeChallengeFromStorage != calculatedCodeChallenge { - s.tokenErrHelper(w, errInvalidGrant, "Invalid code_verifier.", http.StatusBadRequest) + s.tokenErrHelper(ctx, w, errInvalidGrant, "Invalid code_verifier.", http.StatusBadRequest) return } case providedCodeVerifier != "": // Received no code_challenge on /auth, but a code_verifier on /token - s.tokenErrHelper(w, errInvalidRequest, "No PKCE flow started. Cannot check code_verifier.", http.StatusBadRequest) + s.tokenErrHelper(ctx, w, errInvalidRequest, "No PKCE flow started. Cannot check code_verifier.", http.StatusBadRequest) return case codeChallengeFromStorage != "": // Received PKCE request on /auth, but no code_verifier on /token - s.tokenErrHelper(w, errInvalidGrant, "Expecting parameter code_verifier in PKCE flow.", http.StatusBadRequest) + s.tokenErrHelper(ctx, w, errInvalidGrant, "Expecting parameter code_verifier in PKCE flow.", http.StatusBadRequest) return } w.Write([]byte(deviceToken.Token)) @@ -287,7 +295,8 @@ func (s *Server) handleDeviceToken(w http.ResponseWriter, r *http.Request) { } func (s *Server) handleDeviceCallback(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() + ctx, span := traces.InstrumentHandler(r) + defer span.End() switch r.Method { case http.MethodGet: userCode := r.FormValue("state") @@ -310,7 +319,7 @@ func (s *Server) handleDeviceCallback(w http.ResponseWriter, r *http.Request) { if err != nil || s.now().After(authCode.Expiry) { errCode := http.StatusBadRequest if err != nil && err != storage.ErrNotFound { - s.logger.ErrorContext(r.Context(), "failed to get auth code", "err", err) + s.logger.ErrorContext(ctx, "failed to get auth code", "err", err) errCode = http.StatusInternalServerError } s.renderError(r, w, errCode, "Invalid or expired auth code.") @@ -322,7 +331,7 @@ func (s *Server) handleDeviceCallback(w http.ResponseWriter, r *http.Request) { if err != nil || s.now().After(deviceReq.Expiry) { errCode := http.StatusBadRequest if err != nil && err != storage.ErrNotFound { - s.logger.ErrorContext(r.Context(), "failed to get device code", "err", err) + s.logger.ErrorContext(ctx, "failed to get device code", "err", err) errCode = http.StatusInternalServerError } s.renderError(r, w, errCode, "Invalid or expired user code.") @@ -332,21 +341,21 @@ func (s *Server) handleDeviceCallback(w http.ResponseWriter, r *http.Request) { client, err := s.storage.GetClient(ctx, deviceReq.ClientID) if err != nil { if err != storage.ErrNotFound { - s.logger.ErrorContext(r.Context(), "failed to get client", "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) + s.logger.ErrorContext(ctx, "failed to get client", "err", err) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) } else { - s.tokenErrHelper(w, errInvalidClient, "Invalid client credentials.", http.StatusUnauthorized) + s.tokenErrHelper(ctx, w, errInvalidClient, "Invalid client credentials.", http.StatusUnauthorized) } return } if client.Secret != deviceReq.ClientSecret { - s.tokenErrHelper(w, errInvalidClient, "Invalid client credentials.", http.StatusUnauthorized) + s.tokenErrHelper(ctx, w, errInvalidClient, "Invalid client credentials.", http.StatusUnauthorized) return } resp, err := s.exchangeAuthCode(ctx, w, authCode, client) if err != nil { - s.logger.ErrorContext(r.Context(), "could not exchange auth code for clien", "client_id", deviceReq.ClientID, "err", err) + s.logger.ErrorContext(ctx, "could not exchange auth code for clien", "client_id", deviceReq.ClientID, "err", err) s.renderError(r, w, http.StatusInternalServerError, "Failed to exchange auth code.") return } @@ -356,7 +365,7 @@ func (s *Server) handleDeviceCallback(w http.ResponseWriter, r *http.Request) { if err != nil || s.now().After(old.Expiry) { errCode := http.StatusBadRequest if err != nil && err != storage.ErrNotFound { - s.logger.ErrorContext(r.Context(), "failed to get device token", "err", err) + s.logger.ErrorContext(ctx, "failed to get device token", "err", err) errCode = http.StatusInternalServerError } s.renderError(r, w, errCode, "Invalid or expired device code.") @@ -369,7 +378,7 @@ func (s *Server) handleDeviceCallback(w http.ResponseWriter, r *http.Request) { } respStr, err := json.MarshalIndent(resp, "", " ") if err != nil { - s.logger.ErrorContext(r.Context(), "failed to marshal device token response", "err", err) + s.logger.ErrorContext(ctx, "failed to marshal device token response", "err", err) s.renderError(r, w, http.StatusInternalServerError, "") return old, err } @@ -381,13 +390,13 @@ func (s *Server) handleDeviceCallback(w http.ResponseWriter, r *http.Request) { // Update refresh token in the storage, store the token and mark as complete if err := s.storage.UpdateDeviceToken(ctx, deviceReq.DeviceCode, updater); err != nil { - s.logger.ErrorContext(r.Context(), "failed to update device token", "err", err) + s.logger.ErrorContext(ctx, "failed to update device token", "err", err) s.renderError(r, w, http.StatusBadRequest, "") return } if err := s.templates.deviceSuccess(r, w, client.Name); err != nil { - s.logger.ErrorContext(r.Context(), "Server template error", "err", err) + s.logger.ErrorContext(ctx, "Server template error", "err", err) s.renderError(r, w, http.StatusNotFound, "Page not found") } @@ -398,7 +407,8 @@ func (s *Server) handleDeviceCallback(w http.ResponseWriter, r *http.Request) { } func (s *Server) verifyUserCode(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() + ctx, span := traces.InstrumentHandler(r) + defer span.End() switch r.Method { case http.MethodPost: err := r.ParseForm() @@ -420,10 +430,10 @@ func (s *Server) verifyUserCode(w http.ResponseWriter, r *http.Request) { deviceRequest, err := s.storage.GetDeviceRequest(ctx, userCode) if err != nil || s.now().After(deviceRequest.Expiry) { if err != nil && err != storage.ErrNotFound { - s.logger.ErrorContext(r.Context(), "failed to get device request", "err", err) + s.logger.ErrorContext(ctx, "failed to get device request", "err", err) } if err := s.templates.device(r, w, s.getDeviceVerificationURI(), userCode, true); err != nil { - s.logger.ErrorContext(r.Context(), "Server template error", "err", err) + s.logger.ErrorContext(ctx, "Server template error", "err", err) s.renderError(r, w, http.StatusNotFound, "Page not found") } return diff --git a/server/deviceflowhandlers_test.go b/server/deviceflowhandlers_test.go index 2b4fbbfafb..59d81631d0 100644 --- a/server/deviceflowhandlers_test.go +++ b/server/deviceflowhandlers_test.go @@ -467,7 +467,7 @@ func TestDeviceTokenResponse(t *testing.T) { }, testDeviceCode: "f00bar", expectedServerResponse: deviceTokenPending, - expectedResponseCode: http.StatusBadRequest, + expectedResponseCode: http.StatusUnauthorized, }, { testName: "Invalid Grant Type", diff --git a/server/discoveryhandlers.go b/server/discoveryhandlers.go new file mode 100644 index 0000000000..df08148a5d --- /dev/null +++ b/server/discoveryhandlers.go @@ -0,0 +1,27 @@ +package server + +import ( + "encoding/json" + "fmt" + "net/http" + "strconv" + + "github.com/dexidp/dex/pkg/otel/traces" +) + +func (s *Server) discoveryHandler() (http.HandlerFunc, error) { + d := s.constructDiscovery() + + data, err := json.MarshalIndent(d, "", " ") + if err != nil { + return nil, fmt.Errorf("failed to marshal discovery data: %v", err) + } + + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, span := traces.InstrumentHandler(r) + defer span.End() + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Content-Length", strconv.Itoa(len(data))) + w.Write(data) + }), nil +} diff --git a/server/discoveryhandlers_test.go b/server/discoveryhandlers_test.go new file mode 100644 index 0000000000..bf87c1994a --- /dev/null +++ b/server/discoveryhandlers_test.go @@ -0,0 +1,82 @@ +package server + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestHandleDiscovery(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + httpServer, server := newTestServer(ctx, t, nil) + defer httpServer.Close() + + rr := httptest.NewRecorder() + server.ServeHTTP(rr, httptest.NewRequest("GET", "/.well-known/openid-configuration", nil)) + if rr.Code != http.StatusOK { + t.Errorf("expected 200 got %d", rr.Code) + } + + var res discovery + err := json.NewDecoder(rr.Result().Body).Decode(&res) + require.NoError(t, err) + require.Equal(t, discovery{ + Issuer: httpServer.URL, + Auth: fmt.Sprintf("%s/auth", httpServer.URL), + Token: fmt.Sprintf("%s/token", httpServer.URL), + Keys: fmt.Sprintf("%s/keys", httpServer.URL), + UserInfo: fmt.Sprintf("%s/userinfo", httpServer.URL), + DeviceEndpoint: fmt.Sprintf("%s/device/code", httpServer.URL), + Introspect: fmt.Sprintf("%s/token/introspect", httpServer.URL), + GrantTypes: []string{ + "authorization_code", + "refresh_token", + "urn:ietf:params:oauth:grant-type:device_code", + "urn:ietf:params:oauth:grant-type:token-exchange", + }, + ResponseTypes: []string{ + "code", + }, + Subjects: []string{ + "public", + }, + IDTokenAlgs: []string{ + "RS256", + }, + CodeChallengeAlgs: []string{ + "S256", + "plain", + }, + Scopes: []string{ + "openid", + "email", + "groups", + "profile", + "offline_access", + }, + AuthMethods: []string{ + "client_secret_basic", + "client_secret_post", + }, + Claims: []string{ + "iss", + "sub", + "aud", + "iat", + "exp", + "email", + "email_verified", + "locale", + "name", + "preferred_username", + "at_hash", + }, + }, res) +} diff --git a/server/handlers.go b/server/handlers.go index f8d0ed64c3..96574bde81 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -8,20 +8,18 @@ import ( "encoding/base64" "encoding/json" "fmt" - "html/template" "net/http" "net/url" "path" "sort" "strconv" - "strings" "time" - "github.com/coreos/go-oidc/v3/oidc" "github.com/go-jose/go-jose/v4" - "github.com/gorilla/mux" + "go.opentelemetry.io/otel/codes" "github.com/dexidp/dex/connector" + "github.com/dexidp/dex/pkg/otel/traces" "github.com/dexidp/dex/server/internal" "github.com/dexidp/dex/storage" ) @@ -31,47 +29,6 @@ const ( codeChallengeMethodS256 = "S256" ) -func (s *Server) handlePublicKeys(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - // TODO(ericchiang): Cache this. - keys, err := s.storage.GetKeys(ctx) - if err != nil { - s.logger.ErrorContext(r.Context(), "failed to get keys", "err", err) - s.renderError(r, w, http.StatusInternalServerError, "Internal server error.") - return - } - - if keys.SigningKeyPub == nil { - s.logger.ErrorContext(r.Context(), "no public keys found.") - s.renderError(r, w, http.StatusInternalServerError, "Internal server error.") - return - } - - jwks := jose.JSONWebKeySet{ - Keys: make([]jose.JSONWebKey, len(keys.VerificationKeys)+1), - } - jwks.Keys[0] = *keys.SigningKeyPub - for i, verificationKey := range keys.VerificationKeys { - jwks.Keys[i+1] = *verificationKey.PublicKey - } - - data, err := json.MarshalIndent(jwks, "", " ") - if err != nil { - s.logger.ErrorContext(r.Context(), "failed to marshal discovery data", "err", err) - s.renderError(r, w, http.StatusInternalServerError, "Internal server error.") - return - } - maxAge := keys.NextRotation.Sub(s.now()) - if maxAge < (time.Minute * 2) { - maxAge = time.Minute * 2 - } - - w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d, must-revalidate", int(maxAge.Seconds()))) - w.Header().Set("Content-Type", "application/json") - w.Header().Set("Content-Length", strconv.Itoa(len(data))) - w.Write(data) -} - type discovery struct { Issuer string `json:"issuer"` Auth string `json:"authorization_endpoint"` @@ -90,21 +47,6 @@ type discovery struct { Claims []string `json:"claims_supported"` } -func (s *Server) discoveryHandler() (http.HandlerFunc, error) { - d := s.constructDiscovery() - - data, err := json.MarshalIndent(d, "", " ") - if err != nil { - return nil, fmt.Errorf("failed to marshal discovery data: %v", err) - } - - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Header().Set("Content-Length", strconv.Itoa(len(data))) - w.Write(data) - }), nil -} - func (s *Server) constructDiscovery() discovery { d := discovery{ Issuer: s.issuerURL.String(), @@ -134,380 +76,11 @@ func (s *Server) constructDiscovery() discovery { return d } -// handleAuthorization handles the OAuth2 auth endpoint. -func (s *Server) handleAuthorization(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - // Extract the arguments - if err := r.ParseForm(); err != nil { - s.logger.ErrorContext(r.Context(), "failed to parse arguments", "err", err) - - s.renderError(r, w, http.StatusBadRequest, err.Error()) - return - } - - connectorID := r.Form.Get("connector_id") - connectors, err := s.storage.ListConnectors(ctx) - if err != nil { - s.logger.ErrorContext(r.Context(), "failed to get list of connectors", "err", err) - s.renderError(r, w, http.StatusInternalServerError, "Failed to retrieve connector list.") - return - } - - // We don't need connector_id any more - r.Form.Del("connector_id") - - // Construct a URL with all of the arguments in its query - connURL := url.URL{ - RawQuery: r.Form.Encode(), - } - - // Redirect if a client chooses a specific connector_id - if connectorID != "" { - for _, c := range connectors { - if c.ID == connectorID { - connURL.Path = s.absPath("/auth", url.PathEscape(c.ID)) - http.Redirect(w, r, connURL.String(), http.StatusFound) - return - } - } - s.renderError(r, w, http.StatusBadRequest, "Connector ID does not match a valid Connector") - return - } - - if len(connectors) == 1 && !s.alwaysShowLogin { - connURL.Path = s.absPath("/auth", url.PathEscape(connectors[0].ID)) - http.Redirect(w, r, connURL.String(), http.StatusFound) - } - - connectorInfos := make([]connectorInfo, len(connectors)) - for index, conn := range connectors { - connURL.Path = s.absPath("/auth", url.PathEscape(conn.ID)) - connectorInfos[index] = connectorInfo{ - ID: conn.ID, - Name: conn.Name, - Type: conn.Type, - URL: template.URL(connURL.String()), - } - } - - if err := s.templates.login(r, w, connectorInfos); err != nil { - s.logger.ErrorContext(r.Context(), "server template error", "err", err) - } -} - -func (s *Server) handleConnectorLogin(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - authReq, err := s.parseAuthorizationRequest(r) - if err != nil { - s.logger.ErrorContext(r.Context(), "failed to parse authorization request", "err", err) - - switch authErr := err.(type) { - case *redirectedAuthErr: - authErr.Handler().ServeHTTP(w, r) - case *displayedAuthErr: - s.renderError(r, w, authErr.Status, err.Error()) - default: - panic("unsupported error type") - } - - return - } - - connID, err := url.PathUnescape(mux.Vars(r)["connector"]) - if err != nil { - s.logger.ErrorContext(r.Context(), "failed to parse connector", "err", err) - s.renderError(r, w, http.StatusBadRequest, "Requested resource does not exist") - return - } - - conn, err := s.getConnector(ctx, connID) - if err != nil { - s.logger.ErrorContext(r.Context(), "Failed to get connector", "err", err) - s.renderError(r, w, http.StatusBadRequest, "Connector failed to initialize") - return - } - - // Set the connector being used for the login. - if authReq.ConnectorID != "" && authReq.ConnectorID != connID { - s.logger.ErrorContext(r.Context(), "mismatched connector ID in auth request", - "auth_request_connector_id", authReq.ConnectorID, "connector_id", connID) - s.renderError(r, w, http.StatusBadRequest, "Bad connector ID") - return - } - - authReq.ConnectorID = connID - - // Actually create the auth request - authReq.Expiry = s.now().Add(s.authRequestsValidFor) - if err := s.storage.CreateAuthRequest(ctx, *authReq); err != nil { - s.logger.ErrorContext(r.Context(), "failed to create authorization request", "err", err) - s.renderError(r, w, http.StatusInternalServerError, "Failed to connect to the database.") - return - } - - scopes := parseScopes(authReq.Scopes) - - // Work out where the "Select another login method" link should go. - backLink := "" - if len(s.connectors) > 1 { - backLinkURL := url.URL{ - Path: s.absPath("/auth"), - RawQuery: r.Form.Encode(), - } - backLink = backLinkURL.String() - } - - switch r.Method { - case http.MethodGet: - switch conn := conn.Connector.(type) { - case connector.CallbackConnector: - // Use the auth request ID as the "state" token. - // - // TODO(ericchiang): Is this appropriate or should we also be using a nonce? - callbackURL, err := conn.LoginURL(scopes, s.absURL("/callback"), authReq.ID) - if err != nil { - s.logger.ErrorContext(r.Context(), "connector returned error when creating callback", "connector_id", connID, "err", err) - s.renderError(r, w, http.StatusInternalServerError, "Login error.") - return - } - http.Redirect(w, r, callbackURL, http.StatusFound) - case connector.PasswordConnector: - loginURL := url.URL{ - Path: s.absPath("/auth", connID, "login"), - } - q := loginURL.Query() - q.Set("state", authReq.ID) - q.Set("back", backLink) - loginURL.RawQuery = q.Encode() - - http.Redirect(w, r, loginURL.String(), http.StatusFound) - case connector.SAMLConnector: - action, value, err := conn.POSTData(scopes, authReq.ID) - if err != nil { - s.logger.ErrorContext(r.Context(), "creating SAML data", "err", err) - s.renderError(r, w, http.StatusInternalServerError, "Connector Login Error") - return - } - - // TODO(ericchiang): Don't inline this. - fmt.Fprintf(w, ` - - - - SAML login - - -
- - -
- - - `, action, value, authReq.ID) - default: - s.renderError(r, w, http.StatusBadRequest, "Requested resource does not exist.") - } - default: - s.renderError(r, w, http.StatusBadRequest, "Unsupported request method.") - } -} - -func (s *Server) handlePasswordLogin(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - authID := r.URL.Query().Get("state") - if authID == "" { - s.renderError(r, w, http.StatusBadRequest, "User session error.") - return - } - - backLink := r.URL.Query().Get("back") - - authReq, err := s.storage.GetAuthRequest(ctx, authID) - if err != nil { - if err == storage.ErrNotFound { - s.logger.ErrorContext(r.Context(), "invalid 'state' parameter provided", "err", err) - s.renderError(r, w, http.StatusBadRequest, "Requested resource does not exist.") - return - } - s.logger.ErrorContext(r.Context(), "failed to get auth request", "err", err) - s.renderError(r, w, http.StatusInternalServerError, "Database error.") - return - } - - connID, err := url.PathUnescape(mux.Vars(r)["connector"]) - if err != nil { - s.logger.ErrorContext(r.Context(), "failed to parse connector", "err", err) - s.renderError(r, w, http.StatusBadRequest, "Requested resource does not exist") - return - } else if connID != "" && connID != authReq.ConnectorID { - s.logger.ErrorContext(r.Context(), "connector mismatch: password login triggered for different connector from authentication start", "start_connector_id", authReq.ConnectorID, "password_connector_id", connID) - s.renderError(r, w, http.StatusInternalServerError, "Requested resource does not exist.") - return - } - - conn, err := s.getConnector(ctx, authReq.ConnectorID) - if err != nil { - s.logger.ErrorContext(r.Context(), "failed to get connector", "connector_id", authReq.ConnectorID, "err", err) - s.renderError(r, w, http.StatusInternalServerError, "Connector failed to initialize.") - return - } - - pwConn, ok := conn.Connector.(connector.PasswordConnector) - if !ok { - s.logger.ErrorContext(r.Context(), "expected password connector in handlePasswordLogin()", "password_connector", pwConn) - s.renderError(r, w, http.StatusInternalServerError, "Requested resource does not exist.") - return - } - - switch r.Method { - case http.MethodGet: - if err := s.templates.password(r, w, r.URL.String(), "", usernamePrompt(pwConn), false, backLink); err != nil { - s.logger.ErrorContext(r.Context(), "server template error", "err", err) - } - case http.MethodPost: - username := r.FormValue("login") - password := r.FormValue("password") - scopes := parseScopes(authReq.Scopes) - - identity, ok, err := pwConn.Login(r.Context(), scopes, username, password) - if err != nil { - s.logger.ErrorContext(r.Context(), "failed to login user", "err", err) - s.renderError(r, w, http.StatusInternalServerError, fmt.Sprintf("Login error: %v", err)) - return - } - if !ok { - if err := s.templates.password(r, w, r.URL.String(), username, usernamePrompt(pwConn), true, backLink); err != nil { - s.logger.ErrorContext(r.Context(), "server template error", "err", err) - } - s.logger.ErrorContext(r.Context(), "failed login attempt: Invalid credentials.", "user", username) - return - } - redirectURL, canSkipApproval, err := s.finalizeLogin(r.Context(), identity, authReq, conn.Connector) - if err != nil { - s.logger.ErrorContext(r.Context(), "failed to finalize login", "err", err) - s.renderError(r, w, http.StatusInternalServerError, "Login error.") - return - } - - if canSkipApproval { - authReq, err = s.storage.GetAuthRequest(ctx, authReq.ID) - if err != nil { - s.logger.ErrorContext(r.Context(), "failed to get finalized auth request", "err", err) - s.renderError(r, w, http.StatusInternalServerError, "Login error.") - return - } - s.sendCodeResponse(w, r, authReq) - return - } - - http.Redirect(w, r, redirectURL, http.StatusSeeOther) - default: - s.renderError(r, w, http.StatusBadRequest, "Unsupported request method.") - } -} - -func (s *Server) handleConnectorCallback(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - var authID string - switch r.Method { - case http.MethodGet: // OAuth2 callback - if authID = r.URL.Query().Get("state"); authID == "" { - s.renderError(r, w, http.StatusBadRequest, "User session error.") - return - } - case http.MethodPost: // SAML POST binding - if authID = r.PostFormValue("RelayState"); authID == "" { - s.renderError(r, w, http.StatusBadRequest, "User session error.") - return - } - default: - s.renderError(r, w, http.StatusBadRequest, "Method not supported") - return - } - - authReq, err := s.storage.GetAuthRequest(ctx, authID) - if err != nil { - if err == storage.ErrNotFound { - s.logger.ErrorContext(r.Context(), "invalid 'state' parameter provided", "err", err) - s.renderError(r, w, http.StatusBadRequest, "Requested resource does not exist.") - return - } - s.logger.ErrorContext(r.Context(), "failed to get auth request", "err", err) - s.renderError(r, w, http.StatusInternalServerError, "Database error.") - return - } - - connID, err := url.PathUnescape(mux.Vars(r)["connector"]) - if err != nil { - s.logger.ErrorContext(r.Context(), "failed to get connector", "connector_id", authReq.ConnectorID, "err", err) - s.renderError(r, w, http.StatusInternalServerError, "Requested resource does not exist.") - return - } else if connID != "" && connID != authReq.ConnectorID { - s.logger.ErrorContext(r.Context(), "connector mismatch: callback triggered for different connector than authentication start", "authentication_start_connector_id", authReq.ConnectorID, "connector_id", connID) - s.renderError(r, w, http.StatusInternalServerError, "Requested resource does not exist.") - return - } - - conn, err := s.getConnector(ctx, authReq.ConnectorID) - if err != nil { - s.logger.ErrorContext(r.Context(), "failed to get connector", "connector_id", authReq.ConnectorID, "err", err) - s.renderError(r, w, http.StatusInternalServerError, "Requested resource does not exist.") - return - } - - var identity connector.Identity - switch conn := conn.Connector.(type) { - case connector.CallbackConnector: - if r.Method != http.MethodGet { - s.logger.ErrorContext(r.Context(), "SAML request mapped to OAuth2 connector") - s.renderError(r, w, http.StatusBadRequest, "Invalid request") - return - } - identity, err = conn.HandleCallback(parseScopes(authReq.Scopes), r) - case connector.SAMLConnector: - if r.Method != http.MethodPost { - s.logger.ErrorContext(r.Context(), "OAuth2 request mapped to SAML connector") - s.renderError(r, w, http.StatusBadRequest, "Invalid request") - return - } - identity, err = conn.HandlePOST(parseScopes(authReq.Scopes), r.PostFormValue("SAMLResponse"), authReq.ID) - default: - s.renderError(r, w, http.StatusInternalServerError, "Requested resource does not exist.") - return - } - - if err != nil { - s.logger.ErrorContext(r.Context(), "failed to authenticate", "err", err) - s.renderError(r, w, http.StatusInternalServerError, fmt.Sprintf("Failed to authenticate: %v", err)) - return - } - - redirectURL, canSkipApproval, err := s.finalizeLogin(ctx, identity, authReq, conn.Connector) - if err != nil { - s.logger.ErrorContext(r.Context(), "failed to finalize login", "err", err) - s.renderError(r, w, http.StatusInternalServerError, "Login error.") - return - } - - if canSkipApproval { - authReq, err = s.storage.GetAuthRequest(ctx, authReq.ID) - if err != nil { - s.logger.ErrorContext(r.Context(), "failed to get finalized auth request", "err", err) - s.renderError(r, w, http.StatusInternalServerError, "Login error.") - return - } - s.sendCodeResponse(w, r, authReq) - return - } - - http.Redirect(w, r, redirectURL, http.StatusSeeOther) -} - // finalizeLogin associates the user's identity with the current AuthRequest, then returns // the approval page's path. func (s *Server) finalizeLogin(ctx context.Context, identity connector.Identity, authReq storage.AuthRequest, conn connector.Connector) (string, bool, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.server.finalizeLogin") + defer span.End() claims := storage.Claims{ UserID: identity.UserID, Username: identity.Username, @@ -516,7 +89,6 @@ func (s *Server) finalizeLogin(ctx context.Context, identity connector.Identity, EmailVerified: identity.EmailVerified, Groups: identity.Groups, } - updater := func(a storage.AuthRequest) (storage.AuthRequest, error) { a.LoggedIn = true a.Claims = claims @@ -595,63 +167,10 @@ func (s *Server) finalizeLogin(ctx context.Context, identity connector.Identity, return returnURL, false, nil } -func (s *Server) handleApproval(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - macEncoded := r.FormValue("hmac") - if macEncoded == "" { - s.renderError(r, w, http.StatusUnauthorized, "Unauthorized request") - return - } - mac, err := base64.RawURLEncoding.DecodeString(macEncoded) - if err != nil { - s.renderError(r, w, http.StatusUnauthorized, "Unauthorized request") - return - } - - authReq, err := s.storage.GetAuthRequest(ctx, r.FormValue("req")) - if err != nil { - s.logger.ErrorContext(r.Context(), "failed to get auth request", "err", err) - s.renderError(r, w, http.StatusInternalServerError, "Database error.") - return - } - if !authReq.LoggedIn { - s.logger.ErrorContext(r.Context(), "auth request does not have an identity for approval") - s.renderError(r, w, http.StatusInternalServerError, "Login process not yet finalized.") - return - } - - // build expected hmac with secret key - h := hmac.New(sha256.New, authReq.HMACKey) - h.Write([]byte(authReq.ID)) - expectedMAC := h.Sum(nil) - // constant time comparison - if !hmac.Equal(mac, expectedMAC) { - s.renderError(r, w, http.StatusUnauthorized, "Unauthorized request") - return - } - - switch r.Method { - case http.MethodGet: - client, err := s.storage.GetClient(ctx, authReq.ClientID) - if err != nil { - s.logger.ErrorContext(r.Context(), "Failed to get client", "client_id", authReq.ClientID, "err", err) - s.renderError(r, w, http.StatusInternalServerError, "Failed to retrieve client.") - return - } - if err := s.templates.approval(r, w, authReq.ID, authReq.Claims.Username, client.Name, authReq.Scopes); err != nil { - s.logger.ErrorContext(r.Context(), "server template error", "err", err) - } - case http.MethodPost: - if r.FormValue("approval") != "approve" { - s.renderError(r, w, http.StatusInternalServerError, "Approval rejected.") - return - } - s.sendCodeResponse(w, r, authReq) - } -} - func (s *Server) sendCodeResponse(w http.ResponseWriter, r *http.Request, authReq storage.AuthRequest) { - ctx := r.Context() + ctx, span := traces.InstrumentationTracer(r.Context(), "dex.server.send_code_response") + defer span.End() + if s.now().After(authReq.Expiry) { s.renderError(r, w, http.StatusBadRequest, "User session has expired.") return @@ -659,7 +178,7 @@ func (s *Server) sendCodeResponse(w http.ResponseWriter, r *http.Request, authRe if err := s.storage.DeleteAuthRequest(ctx, authReq.ID); err != nil { if err != storage.ErrNotFound { - s.logger.ErrorContext(r.Context(), "Failed to delete authorization request", "err", err) + s.logger.ErrorContext(ctx, "Failed to delete authorization request", "err", err) s.renderError(r, w, http.StatusInternalServerError, "Internal server error.") } else { s.renderError(r, w, http.StatusBadRequest, "User session error.") @@ -705,7 +224,7 @@ func (s *Server) sendCodeResponse(w http.ResponseWriter, r *http.Request, authRe PKCE: authReq.PKCE, } if err := s.storage.CreateAuthCode(ctx, code); err != nil { - s.logger.ErrorContext(r.Context(), "Failed to create auth code", "err", err) + s.logger.ErrorContext(ctx, "Failed to create auth code", "err", err) s.renderError(r, w, http.StatusInternalServerError, "Internal server error.") return } @@ -714,7 +233,7 @@ func (s *Server) sendCodeResponse(w http.ResponseWriter, r *http.Request, authRe // rejected earlier. If we got here we're using the code flow. if authReq.RedirectURI == redirectURIOOB { if err := s.templates.oob(r, w, code.ID); err != nil { - s.logger.ErrorContext(r.Context(), "server template error", "err", err) + s.logger.ErrorContext(ctx, "server template error", "err", err) } return } @@ -722,20 +241,20 @@ func (s *Server) sendCodeResponse(w http.ResponseWriter, r *http.Request, authRe implicitOrHybrid = true var err error - accessToken, _, err = s.newAccessToken(r.Context(), authReq.ClientID, authReq.Claims, authReq.Scopes, authReq.Nonce, authReq.ConnectorID) + accessToken, _, err = s.newAccessToken(ctx, authReq.ClientID, authReq.Claims, authReq.Scopes, authReq.Nonce, authReq.ConnectorID) if err != nil { - s.logger.ErrorContext(r.Context(), "failed to create new access token", "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) + s.logger.ErrorContext(ctx, "failed to create new access token", "err", err) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) return } case responseTypeIDToken: implicitOrHybrid = true var err error - idToken, idTokenExpiry, err = s.newIDToken(r.Context(), authReq.ClientID, authReq.Claims, authReq.Scopes, authReq.Nonce, accessToken, code.ID, authReq.ConnectorID) + idToken, idTokenExpiry, err = s.newIDToken(ctx, authReq.ClientID, authReq.Claims, authReq.Scopes, authReq.Nonce, accessToken, code.ID, authReq.ConnectorID) if err != nil { - s.logger.ErrorContext(r.Context(), "failed to create ID token", "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) + s.logger.ErrorContext(ctx, "failed to create ID token", "err", err) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) return } } @@ -787,21 +306,21 @@ func (s *Server) sendCodeResponse(w http.ResponseWriter, r *http.Request, authRe q.Set("state", authReq.State) u.RawQuery = q.Encode() } - http.Redirect(w, r, u.String(), http.StatusSeeOther) } func (s *Server) withClientFromStorage(w http.ResponseWriter, r *http.Request, handler func(http.ResponseWriter, *http.Request, storage.Client)) { - ctx := r.Context() + ctx, span := traces.InstrumentationTracer(r.Context(), "dex.server.with_client_from_storage") + defer span.End() clientID, clientSecret, ok := r.BasicAuth() if ok { var err error if clientID, err = url.QueryUnescape(clientID); err != nil { - s.tokenErrHelper(w, errInvalidRequest, "client_id improperly encoded", http.StatusBadRequest) + s.tokenErrHelper(ctx, w, errInvalidRequest, "client_id improperly encoded", http.StatusBadRequest) return } if clientSecret, err = url.QueryUnescape(clientSecret); err != nil { - s.tokenErrHelper(w, errInvalidRequest, "client_secret improperly encoded", http.StatusBadRequest) + s.tokenErrHelper(ctx, w, errInvalidRequest, "client_secret improperly encoded", http.StatusBadRequest) return } } else { @@ -812,63 +331,27 @@ func (s *Server) withClientFromStorage(w http.ResponseWriter, r *http.Request, h client, err := s.storage.GetClient(ctx, clientID) if err != nil { if err != storage.ErrNotFound { - s.logger.ErrorContext(r.Context(), "failed to get client", "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) + s.logger.ErrorContext(ctx, "failed to get client", "err", err) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) } else { - s.tokenErrHelper(w, errInvalidClient, "Invalid client credentials.", http.StatusUnauthorized) + s.tokenErrHelper(ctx, w, errInvalidClient, "Invalid client credentials.", http.StatusUnauthorized) } return } if subtle.ConstantTimeCompare([]byte(client.Secret), []byte(clientSecret)) != 1 { if clientSecret == "" { - s.logger.InfoContext(r.Context(), "missing client_secret on token request", "client_id", client.ID) + s.logger.InfoContext(ctx, "missing client_secret on token request", "client_id", client.ID) } else { - s.logger.InfoContext(r.Context(), "invalid client_secret on token request", "client_id", client.ID) + s.logger.InfoContext(ctx, "invalid client_secret on token request", "client_id", client.ID) } - s.tokenErrHelper(w, errInvalidClient, "Invalid client credentials.", http.StatusUnauthorized) + s.tokenErrHelper(ctx, w, errInvalidClient, "Invalid client credentials.", http.StatusUnauthorized) return } handler(w, r, client) } -func (s *Server) handleToken(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - if r.Method != http.MethodPost { - s.tokenErrHelper(w, errInvalidRequest, "method not allowed", http.StatusBadRequest) - return - } - - err := r.ParseForm() - if err != nil { - s.logger.ErrorContext(r.Context(), "could not parse request body", "err", err) - s.tokenErrHelper(w, errInvalidRequest, "", http.StatusBadRequest) - return - } - - grantType := r.PostFormValue("grant_type") - if !contains(s.supportedGrantTypes, grantType) { - s.logger.ErrorContext(r.Context(), "unsupported grant type", "grant_type", grantType) - s.tokenErrHelper(w, errUnsupportedGrantType, "", http.StatusBadRequest) - return - } - switch grantType { - case grantTypeDeviceCode: - s.handleDeviceToken(w, r) - case grantTypeAuthorizationCode: - s.withClientFromStorage(w, r, s.handleAuthCode) - case grantTypeRefreshToken: - s.withClientFromStorage(w, r, s.handleRefreshToken) - case grantTypePassword: - s.withClientFromStorage(w, r, s.handlePasswordGrant) - case grantTypeTokenExchange: - s.withClientFromStorage(w, r, s.handleTokenExchange) - default: - s.tokenErrHelper(w, errUnsupportedGrantType, "", http.StatusBadRequest) - } -} - func (s *Server) calculateCodeChallenge(codeVerifier, codeChallengeMethod string) (string, error) { switch codeChallengeMethod { case codeChallengeMethodPlain: @@ -881,85 +364,26 @@ func (s *Server) calculateCodeChallenge(codeVerifier, codeChallengeMethod string } } -// handle an access token request https://tools.ietf.org/html/rfc6749#section-4.1.3 -func (s *Server) handleAuthCode(w http.ResponseWriter, r *http.Request, client storage.Client) { - ctx := r.Context() - code := r.PostFormValue("code") - redirectURI := r.PostFormValue("redirect_uri") - - if code == "" { - s.tokenErrHelper(w, errInvalidRequest, `Required param: code.`, http.StatusBadRequest) - return - } - - authCode, err := s.storage.GetAuthCode(ctx, code) - if err != nil || s.now().After(authCode.Expiry) || authCode.ClientID != client.ID { - if err != storage.ErrNotFound { - s.logger.ErrorContext(r.Context(), "failed to get auth code", "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) - } else { - s.tokenErrHelper(w, errInvalidGrant, "Invalid or expired code parameter.", http.StatusBadRequest) - } - return - } - - // RFC 7636 (PKCE) - codeChallengeFromStorage := authCode.PKCE.CodeChallenge - providedCodeVerifier := r.PostFormValue("code_verifier") - - switch { - case providedCodeVerifier != "" && codeChallengeFromStorage != "": - calculatedCodeChallenge, err := s.calculateCodeChallenge(providedCodeVerifier, authCode.PKCE.CodeChallengeMethod) - if err != nil { - s.logger.ErrorContext(r.Context(), "failed to calculate code challenge", "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) - return - } - if codeChallengeFromStorage != calculatedCodeChallenge { - s.tokenErrHelper(w, errInvalidGrant, "Invalid code_verifier.", http.StatusBadRequest) - return - } - case providedCodeVerifier != "": - // Received no code_challenge on /auth, but a code_verifier on /token - s.tokenErrHelper(w, errInvalidRequest, "No PKCE flow started. Cannot check code_verifier.", http.StatusBadRequest) - return - case codeChallengeFromStorage != "": - // Received PKCE request on /auth, but no code_verifier on /token - s.tokenErrHelper(w, errInvalidGrant, "Expecting parameter code_verifier in PKCE flow.", http.StatusBadRequest) - return - } - - if authCode.RedirectURI != redirectURI { - s.tokenErrHelper(w, errInvalidRequest, "redirect_uri did not match URI from initial request.", http.StatusBadRequest) - return - } - - tokenResponse, err := s.exchangeAuthCode(ctx, w, authCode, client) - if err != nil { - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) - return - } - s.writeAccessToken(w, tokenResponse) -} - func (s *Server) exchangeAuthCode(ctx context.Context, w http.ResponseWriter, authCode storage.AuthCode, client storage.Client) (*accessTokenResponse, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.server.exchange_auth_code") + defer span.End() accessToken, _, err := s.newAccessToken(ctx, client.ID, authCode.Claims, authCode.Scopes, authCode.Nonce, authCode.ConnectorID) if err != nil { s.logger.ErrorContext(ctx, "failed to create new access token", "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) return nil, err } idToken, expiry, err := s.newIDToken(ctx, client.ID, authCode.Claims, authCode.Scopes, authCode.Nonce, accessToken, authCode.ID, authCode.ConnectorID) if err != nil { s.logger.ErrorContext(ctx, "failed to create ID token", "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) return nil, err } if err := s.storage.DeleteAuthCode(ctx, authCode.ID); err != nil { s.logger.ErrorContext(ctx, "failed to delete auth code", "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) return nil, err } @@ -970,7 +394,7 @@ func (s *Server) exchangeAuthCode(ctx context.Context, w http.ResponseWriter, au conn, err := s.getConnector(ctx, authCode.ConnectorID) if err != nil { s.logger.ErrorContext(ctx, "connector not found", "connector_id", authCode.ConnectorID, "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) return false } @@ -1006,13 +430,13 @@ func (s *Server) exchangeAuthCode(ctx context.Context, w http.ResponseWriter, au } if refreshToken, err = internal.Marshal(token); err != nil { s.logger.ErrorContext(ctx, "failed to marshal refresh token", "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) return nil, err } if err := s.storage.CreateRefresh(ctx, refresh); err != nil { s.logger.ErrorContext(ctx, "failed to create refresh token", "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) return nil, err } @@ -1025,7 +449,7 @@ func (s *Server) exchangeAuthCode(ctx context.Context, w http.ResponseWriter, au // Delete newly created refresh token from storage. if err := s.storage.DeleteRefresh(ctx, refresh.ID); err != nil { s.logger.ErrorContext(ctx, "failed to delete refresh token", "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) return } } @@ -1042,7 +466,7 @@ func (s *Server) exchangeAuthCode(ctx context.Context, w http.ResponseWriter, au if session, err := s.storage.GetOfflineSessions(ctx, refresh.Claims.UserID, refresh.ConnectorID); err != nil { if err != storage.ErrNotFound { s.logger.ErrorContext(ctx, "failed to get offline session", "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) deleteToken = true return nil, err } @@ -1057,7 +481,7 @@ func (s *Server) exchangeAuthCode(ctx context.Context, w http.ResponseWriter, au // the newly received refreshtoken. if err := s.storage.CreateOfflineSessions(ctx, offlineSessions); err != nil { s.logger.ErrorContext(ctx, "failed to create offline session", "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) deleteToken = true return nil, err } @@ -1066,7 +490,7 @@ func (s *Server) exchangeAuthCode(ctx context.Context, w http.ResponseWriter, au // Delete old refresh token from storage. if err := s.storage.DeleteRefresh(ctx, oldTokenRef.ID); err != nil && err != storage.ErrNotFound { s.logger.ErrorContext(ctx, "failed to delete refresh token", "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) deleteToken = true return nil, err } @@ -1078,7 +502,7 @@ func (s *Server) exchangeAuthCode(ctx context.Context, w http.ResponseWriter, au return old, nil }); err != nil { s.logger.ErrorContext(ctx, "failed to update offline session", "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) deleteToken = true return nil, err } @@ -1087,352 +511,6 @@ func (s *Server) exchangeAuthCode(ctx context.Context, w http.ResponseWriter, au return s.toAccessTokenResponse(idToken, accessToken, refreshToken, expiry), nil } -func (s *Server) handleUserInfo(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - const prefix = "Bearer " - - auth := r.Header.Get("authorization") - if len(auth) < len(prefix) || !strings.EqualFold(prefix, auth[:len(prefix)]) { - w.Header().Set("WWW-Authenticate", "Bearer") - s.tokenErrHelper(w, errAccessDenied, "Invalid bearer token.", http.StatusUnauthorized) - return - } - rawIDToken := auth[len(prefix):] - - verifier := oidc.NewVerifier(s.issuerURL.String(), &storageKeySet{s.storage}, &oidc.Config{SkipClientIDCheck: true}) - idToken, err := verifier.Verify(ctx, rawIDToken) - if err != nil { - s.tokenErrHelper(w, errAccessDenied, err.Error(), http.StatusForbidden) - return - } - - var claims json.RawMessage - if err := idToken.Claims(&claims); err != nil { - s.tokenErrHelper(w, errServerError, err.Error(), http.StatusInternalServerError) - return - } - - w.Header().Set("Content-Type", "application/json") - w.Write(claims) -} - -func (s *Server) handlePasswordGrant(w http.ResponseWriter, r *http.Request, client storage.Client) { - ctx := r.Context() - // Parse the fields - if err := r.ParseForm(); err != nil { - s.tokenErrHelper(w, errInvalidRequest, "Couldn't parse data", http.StatusBadRequest) - return - } - q := r.Form - - nonce := q.Get("nonce") - // Some clients, like the old go-oidc, provide extra whitespace. Tolerate this. - scopes := strings.Fields(q.Get("scope")) - - // Parse the scopes if they are passed - var ( - unrecognized []string - invalidScopes []string - ) - hasOpenIDScope := false - for _, scope := range scopes { - switch scope { - case scopeOpenID: - hasOpenIDScope = true - case scopeOfflineAccess, scopeEmail, scopeProfile, scopeGroups, scopeFederatedID: - default: - peerID, ok := parseCrossClientScope(scope) - if !ok { - unrecognized = append(unrecognized, scope) - continue - } - - isTrusted, err := s.validateCrossClientTrust(ctx, client.ID, peerID) - if err != nil { - s.tokenErrHelper(w, errInvalidClient, fmt.Sprintf("Error validating cross client trust %v.", err), http.StatusBadRequest) - return - } - if !isTrusted { - invalidScopes = append(invalidScopes, scope) - } - } - } - if !hasOpenIDScope { - s.tokenErrHelper(w, errInvalidRequest, `Missing required scope(s) ["openid"].`, http.StatusBadRequest) - return - } - if len(unrecognized) > 0 { - s.tokenErrHelper(w, errInvalidRequest, fmt.Sprintf("Unrecognized scope(s) %q", unrecognized), http.StatusBadRequest) - return - } - if len(invalidScopes) > 0 { - s.tokenErrHelper(w, errInvalidRequest, fmt.Sprintf("Client can't request scope(s) %q", invalidScopes), http.StatusBadRequest) - return - } - - // Which connector - connID := s.passwordConnector - conn, err := s.getConnector(ctx, connID) - if err != nil { - s.tokenErrHelper(w, errInvalidRequest, "Requested connector does not exist.", http.StatusBadRequest) - return - } - - passwordConnector, ok := conn.Connector.(connector.PasswordConnector) - if !ok { - s.tokenErrHelper(w, errInvalidRequest, "Requested password connector does not correct type.", http.StatusBadRequest) - return - } - - // Login - username := q.Get("username") - password := q.Get("password") - identity, ok, err := passwordConnector.Login(ctx, parseScopes(scopes), username, password) - if err != nil { - s.logger.ErrorContext(r.Context(), "failed to login user", "err", err) - s.tokenErrHelper(w, errInvalidRequest, "Could not login user", http.StatusBadRequest) - return - } - if !ok { - s.tokenErrHelper(w, errAccessDenied, "Invalid username or password", http.StatusUnauthorized) - return - } - - // Build the claims to send the id token - claims := storage.Claims{ - UserID: identity.UserID, - Username: identity.Username, - PreferredUsername: identity.PreferredUsername, - Email: identity.Email, - EmailVerified: identity.EmailVerified, - Groups: identity.Groups, - } - - accessToken, _, err := s.newAccessToken(ctx, client.ID, claims, scopes, nonce, connID) - if err != nil { - s.logger.ErrorContext(r.Context(), "password grant failed to create new access token", "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) - return - } - - idToken, expiry, err := s.newIDToken(ctx, client.ID, claims, scopes, nonce, accessToken, "", connID) - if err != nil { - s.logger.ErrorContext(r.Context(), "password grant failed to create new ID token", "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) - return - } - - reqRefresh := func() bool { - // Ensure the connector supports refresh tokens. - // - // Connectors like `saml` do not implement RefreshConnector. - _, ok := conn.Connector.(connector.RefreshConnector) - if !ok { - return false - } - - for _, scope := range scopes { - if scope == scopeOfflineAccess { - return true - } - } - return false - }() - var refreshToken string - if reqRefresh { - refresh := storage.RefreshToken{ - ID: storage.NewID(), - Token: storage.NewID(), - ClientID: client.ID, - ConnectorID: connID, - Scopes: scopes, - Claims: claims, - Nonce: nonce, - // ConnectorData: authCode.ConnectorData, - CreatedAt: s.now(), - LastUsed: s.now(), - } - token := &internal.RefreshToken{ - RefreshId: refresh.ID, - Token: refresh.Token, - } - if refreshToken, err = internal.Marshal(token); err != nil { - s.logger.ErrorContext(r.Context(), "failed to marshal refresh token", "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) - return - } - - if err := s.storage.CreateRefresh(ctx, refresh); err != nil { - s.logger.ErrorContext(r.Context(), "failed to create refresh token", "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) - return - } - - // deleteToken determines if we need to delete the newly created refresh token - // due to a failure in updating/creating the OfflineSession object for the - // corresponding user. - var deleteToken bool - defer func() { - if deleteToken { - // Delete newly created refresh token from storage. - if err := s.storage.DeleteRefresh(ctx, refresh.ID); err != nil { - s.logger.ErrorContext(r.Context(), "failed to delete refresh token", "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) - return - } - } - }() - - tokenRef := storage.RefreshTokenRef{ - ID: refresh.ID, - ClientID: refresh.ClientID, - CreatedAt: refresh.CreatedAt, - LastUsed: refresh.LastUsed, - } - - // Try to retrieve an existing OfflineSession object for the corresponding user. - if session, err := s.storage.GetOfflineSessions(ctx, refresh.Claims.UserID, refresh.ConnectorID); err != nil { - if err != storage.ErrNotFound { - s.logger.ErrorContext(r.Context(), "failed to get offline session", "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) - deleteToken = true - return - } - offlineSessions := storage.OfflineSessions{ - UserID: refresh.Claims.UserID, - ConnID: refresh.ConnectorID, - Refresh: make(map[string]*storage.RefreshTokenRef), - ConnectorData: identity.ConnectorData, - } - offlineSessions.Refresh[tokenRef.ClientID] = &tokenRef - - // Create a new OfflineSession object for the user and add a reference object for - // the newly received refreshtoken. - if err := s.storage.CreateOfflineSessions(ctx, offlineSessions); err != nil { - s.logger.ErrorContext(r.Context(), "failed to create offline session", "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) - deleteToken = true - return - } - } else { - if oldTokenRef, ok := session.Refresh[tokenRef.ClientID]; ok { - // Delete old refresh token from storage. - if err := s.storage.DeleteRefresh(ctx, oldTokenRef.ID); err != nil { - if err == storage.ErrNotFound { - s.logger.Warn("database inconsistent, refresh token missing", "token_id", oldTokenRef.ID) - } else { - s.logger.ErrorContext(r.Context(), "failed to delete refresh token", "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) - deleteToken = true - return - } - } - } - - // Update existing OfflineSession obj with new RefreshTokenRef. - if err := s.storage.UpdateOfflineSessions(ctx, session.UserID, session.ConnID, func(old storage.OfflineSessions) (storage.OfflineSessions, error) { - old.Refresh[tokenRef.ClientID] = &tokenRef - old.ConnectorData = identity.ConnectorData - return old, nil - }); err != nil { - s.logger.ErrorContext(r.Context(), "failed to update offline session", "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) - deleteToken = true - return - } - } - } - - resp := s.toAccessTokenResponse(idToken, accessToken, refreshToken, expiry) - s.writeAccessToken(w, resp) -} - -func (s *Server) handleTokenExchange(w http.ResponseWriter, r *http.Request, client storage.Client) { - ctx := r.Context() - - if err := r.ParseForm(); err != nil { - s.logger.ErrorContext(r.Context(), "could not parse request body", "err", err) - s.tokenErrHelper(w, errInvalidRequest, "", http.StatusBadRequest) - return - } - q := r.Form - - scopes := strings.Fields(q.Get("scope")) // OPTIONAL, map to issued token scope - requestedTokenType := q.Get("requested_token_type") // OPTIONAL, default to access token - if requestedTokenType == "" { - requestedTokenType = tokenTypeAccess - } - subjectToken := q.Get("subject_token") // REQUIRED - subjectTokenType := q.Get("subject_token_type") // REQUIRED - connID := q.Get("connector_id") // REQUIRED, not in RFC - - switch subjectTokenType { - case tokenTypeID, tokenTypeAccess: // ok, continue - default: - s.tokenErrHelper(w, errRequestNotSupported, "Invalid subject_token_type.", http.StatusBadRequest) - return - } - - if subjectToken == "" { - s.tokenErrHelper(w, errInvalidRequest, "Missing subject_token", http.StatusBadRequest) - return - } - - conn, err := s.getConnector(ctx, connID) - if err != nil { - s.logger.ErrorContext(r.Context(), "failed to get connector", "err", err) - s.tokenErrHelper(w, errInvalidRequest, "Requested connector does not exist.", http.StatusBadRequest) - return - } - teConn, ok := conn.Connector.(connector.TokenIdentityConnector) - if !ok { - s.logger.ErrorContext(r.Context(), "connector doesn't implement token exchange", "connector_id", connID) - s.tokenErrHelper(w, errInvalidRequest, "Requested connector does not exist.", http.StatusBadRequest) - return - } - identity, err := teConn.TokenIdentity(ctx, subjectTokenType, subjectToken) - if err != nil { - s.logger.ErrorContext(r.Context(), "failed to verify subject token", "err", err) - s.tokenErrHelper(w, errAccessDenied, "", http.StatusUnauthorized) - return - } - - claims := storage.Claims{ - UserID: identity.UserID, - Username: identity.Username, - PreferredUsername: identity.PreferredUsername, - Email: identity.Email, - EmailVerified: identity.EmailVerified, - Groups: identity.Groups, - } - resp := accessTokenResponse{ - IssuedTokenType: requestedTokenType, - TokenType: "bearer", - } - var expiry time.Time - switch requestedTokenType { - case tokenTypeID: - resp.AccessToken, expiry, err = s.newIDToken(r.Context(), client.ID, claims, scopes, "", "", "", connID) - case tokenTypeAccess: - resp.AccessToken, expiry, err = s.newAccessToken(r.Context(), client.ID, claims, scopes, "", connID) - default: - s.tokenErrHelper(w, errRequestNotSupported, "Invalid requested_token_type.", http.StatusBadRequest) - return - } - if err != nil { - s.logger.ErrorContext(r.Context(), "token exchange failed to create new token", "requested_token_type", requestedTokenType, "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) - return - } - resp.ExpiresIn = int(time.Until(expiry).Seconds()) - - // Token response must include cache headers https://tools.ietf.org/html/rfc6749#section-5.1 - w.Header().Set("Cache-Control", "no-store") - w.Header().Set("Pragma", "no-cache") - w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(resp) -} - type accessTokenResponse struct { AccessToken string `json:"access_token"` IssuedTokenType string `json:"issued_token_type,omitempty"` @@ -1453,12 +531,13 @@ func (s *Server) toAccessTokenResponse(idToken, accessToken, refreshToken string } } -func (s *Server) writeAccessToken(w http.ResponseWriter, resp *accessTokenResponse) { +func (s *Server) writeAccessToken(ctx context.Context, w http.ResponseWriter, resp *accessTokenResponse) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.server.write_access_token") + defer span.End() data, err := json.Marshal(resp) if err != nil { - // TODO(nabokihms): error with context - s.logger.Error("failed to marshal access token response", "err", err) - s.tokenErrHelper(w, errServerError, "", http.StatusInternalServerError) + s.logger.ErrorContext(ctx, "failed to marshal access token response", "err", err) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") @@ -1471,15 +550,21 @@ func (s *Server) writeAccessToken(w http.ResponseWriter, resp *accessTokenRespon } func (s *Server) renderError(r *http.Request, w http.ResponseWriter, status int, description string) { + ctx, span := traces.InstrumentationTracer(r.Context(), "dex.server.render_error") + defer span.End() if err := s.templates.err(r, w, status, description); err != nil { - s.logger.ErrorContext(r.Context(), "server template error", "err", err) + s.logger.ErrorContext(ctx, "server template error", "err", err) } } -func (s *Server) tokenErrHelper(w http.ResponseWriter, typ string, description string, statusCode int) { +func (s *Server) tokenErrHelper(ctx context.Context, w http.ResponseWriter, typ string, description string, statusCode int) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.server.token_err_helper") + defer span.End() + if statusCode >= 500 { + span.SetStatus(codes.Error, "failed to write token error response") + } if err := tokenErr(w, typ, description, statusCode); err != nil { - // TODO(nabokihms): error with context - s.logger.Error("token error response", "err", err) + s.logger.ErrorContext(ctx, "token error response", "err", err) } } diff --git a/server/handlers_test.go b/server/handlers_test.go index 1aa4bfa58a..8b9736a113 100644 --- a/server/handlers_test.go +++ b/server/handlers_test.go @@ -10,7 +10,6 @@ import ( "net/http/httptest" "net/url" "path" - "strings" "testing" "time" @@ -37,76 +36,6 @@ func TestHandleHealth(t *testing.T) { } } -func TestHandleDiscovery(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - httpServer, server := newTestServer(ctx, t, nil) - defer httpServer.Close() - - rr := httptest.NewRecorder() - server.ServeHTTP(rr, httptest.NewRequest("GET", "/.well-known/openid-configuration", nil)) - if rr.Code != http.StatusOK { - t.Errorf("expected 200 got %d", rr.Code) - } - - var res discovery - err := json.NewDecoder(rr.Result().Body).Decode(&res) - require.NoError(t, err) - require.Equal(t, discovery{ - Issuer: httpServer.URL, - Auth: fmt.Sprintf("%s/auth", httpServer.URL), - Token: fmt.Sprintf("%s/token", httpServer.URL), - Keys: fmt.Sprintf("%s/keys", httpServer.URL), - UserInfo: fmt.Sprintf("%s/userinfo", httpServer.URL), - DeviceEndpoint: fmt.Sprintf("%s/device/code", httpServer.URL), - Introspect: fmt.Sprintf("%s/token/introspect", httpServer.URL), - GrantTypes: []string{ - "authorization_code", - "refresh_token", - "urn:ietf:params:oauth:grant-type:device_code", - "urn:ietf:params:oauth:grant-type:token-exchange", - }, - ResponseTypes: []string{ - "code", - }, - Subjects: []string{ - "public", - }, - IDTokenAlgs: []string{ - "RS256", - }, - CodeChallengeAlgs: []string{ - "S256", - "plain", - }, - Scopes: []string{ - "openid", - "email", - "groups", - "profile", - "offline_access", - }, - AuthMethods: []string{ - "client_secret_basic", - "client_secret_post", - }, - Claims: []string{ - "iss", - "sub", - "aud", - "iat", - "exp", - "email", - "email_verified", - "locale", - "name", - "preferred_username", - "at_hash", - }, - }, res) -} - func TestHandleHealthFailure(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -712,111 +641,6 @@ func TestHandleConnectorCallbackWithSkipApproval(t *testing.T) { } } -func TestHandleTokenExchange(t *testing.T) { - tests := []struct { - name string - scope string - requestedTokenType string - subjectTokenType string - subjectToken string - - expectedCode int - expectedTokenType string - }{ - { - "id-for-acccess", - "openid", - tokenTypeAccess, - tokenTypeID, - "foobar", - http.StatusOK, - tokenTypeAccess, - }, - { - "id-for-id", - "openid", - tokenTypeID, - tokenTypeID, - "foobar", - http.StatusOK, - tokenTypeID, - }, - { - "id-for-default", - "openid", - "", - tokenTypeID, - "foobar", - http.StatusOK, - tokenTypeAccess, - }, - { - "access-for-access", - "openid", - tokenTypeAccess, - tokenTypeAccess, - "foobar", - http.StatusOK, - tokenTypeAccess, - }, - { - "missing-subject_token_type", - "openid", - tokenTypeAccess, - "", - "foobar", - http.StatusBadRequest, - "", - }, - { - "missing-subject_token", - "openid", - tokenTypeAccess, - tokenTypeAccess, - "", - http.StatusBadRequest, - "", - }, - } - for _, tc := range tests { - t.Run(tc.name, func(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - httpServer, s := newTestServer(ctx, t, func(c *Config) { - c.Storage.CreateClient(ctx, storage.Client{ - ID: "client_1", - Secret: "secret_1", - }) - }) - defer httpServer.Close() - vals := make(url.Values) - vals.Set("grant_type", grantTypeTokenExchange) - setNonEmpty(vals, "connector_id", "mock") - setNonEmpty(vals, "scope", tc.scope) - setNonEmpty(vals, "requested_token_type", tc.requestedTokenType) - setNonEmpty(vals, "subject_token_type", tc.subjectTokenType) - setNonEmpty(vals, "subject_token", tc.subjectToken) - setNonEmpty(vals, "client_id", "client_1") - setNonEmpty(vals, "client_secret", "secret_1") - - rr := httptest.NewRecorder() - req := httptest.NewRequest(http.MethodPost, httpServer.URL+"/token", strings.NewReader(vals.Encode())) - req.Header.Set("content-type", "application/x-www-form-urlencoded") - - s.handleToken(rr, req) - - require.Equal(t, tc.expectedCode, rr.Code, rr.Body.String()) - require.Equal(t, "application/json", rr.Result().Header.Get("content-type")) - if tc.expectedCode == http.StatusOK { - var res accessTokenResponse - err := json.NewDecoder(rr.Result().Body).Decode(&res) - require.NoError(t, err) - require.Equal(t, tc.expectedTokenType, res.IssuedTokenType) - } - }) - } -} - func setNonEmpty(vals url.Values, key, value string) { if value != "" { vals.Set(key, value) diff --git a/server/internal/codec_test.go b/server/internal/codec_test.go new file mode 100644 index 0000000000..5b7d634621 --- /dev/null +++ b/server/internal/codec_test.go @@ -0,0 +1,103 @@ +package internal + +import ( + "encoding/base64" + "testing" + + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/anypb" +) + +func TestMarshal(t *testing.T) { + tests := []struct { + name string + input proto.Message + expected string + expectErr bool + }{ + { + name: "ValidMessage", + input: &anypb.Any{TypeUrl: "example.com/type", Value: []byte("test")}, + expected: "ChBleGFtcGxlLmNvbS90eXBlEgR0ZXN0", + expectErr: false, + }, + { + name: "NilMessage", + input: nil, + expected: "", + expectErr: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result, err := Marshal(tt.input) + if tt.expectErr { + if err == nil { + t.Fatalf("expected an error, got none") + } + return + } + + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + if result != tt.expected { + t.Fatalf("unexpected result: got %s, want %s", result, tt.expected) + } + + if _, decodeErr := base64.RawURLEncoding.DecodeString(result); decodeErr != nil { + t.Fatalf("result is not a valid base64 string: %v", decodeErr) + } + }) + } +} + +func TestUnmarshal(t *testing.T) { + tests := []struct { + name string + input string + output proto.Message + expectErr bool + }{ + { + name: "ValidBase64Input", + input: func() string { + data, _ := proto.Marshal(&anypb.Any{TypeUrl: "example.com/type", Value: []byte("test")}) + return base64.RawURLEncoding.EncodeToString(data) + }(), + output: &anypb.Any{}, + expectErr: false, + }, + { + name: "InvalidBase64Input", + input: "%%invalid-base64%%", + output: &anypb.Any{}, + expectErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := Unmarshal(tt.input, tt.output) + if tt.expectErr { + if err == nil { + t.Fatalf("expected an error, got none") + } + return + } + + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + if anyMsg, ok := tt.output.(*anypb.Any); ok { + expectedMsg := &anypb.Any{TypeUrl: "example.com/type", Value: []byte("test")} + if !proto.Equal(anyMsg, expectedMsg) { + t.Fatalf("unexpected decoded message: got %v, want %v", anyMsg, expectedMsg) + } + } + }) + } +} diff --git a/server/internal/types.pb.go b/server/internal/types.pb.go index cabbea2e8f..c7551d36ea 100644 --- a/server/internal/types.pb.go +++ b/server/internal/types.pb.go @@ -1,6 +1,6 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.36.5 +// protoc-gen-go v1.36.6 // protoc v5.29.3 // source: server/internal/types.proto @@ -132,23 +132,16 @@ func (x *IDTokenSubject) GetConnId() string { var File_server_internal_types_proto protoreflect.FileDescriptor -var file_server_internal_types_proto_rawDesc = string([]byte{ - 0x0a, 0x1b, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, - 0x6c, 0x2f, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x08, 0x69, - 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x22, 0x43, 0x0a, 0x0c, 0x52, 0x65, 0x66, 0x72, 0x65, - 0x73, 0x68, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x66, 0x72, 0x65, - 0x73, 0x68, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x72, 0x65, 0x66, - 0x72, 0x65, 0x73, 0x68, 0x49, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x18, - 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x22, 0x42, 0x0a, 0x0e, - 0x49, 0x44, 0x54, 0x6f, 0x6b, 0x65, 0x6e, 0x53, 0x75, 0x62, 0x6a, 0x65, 0x63, 0x74, 0x12, 0x17, - 0x0a, 0x07, 0x75, 0x73, 0x65, 0x72, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, - 0x06, 0x75, 0x73, 0x65, 0x72, 0x49, 0x64, 0x12, 0x17, 0x0a, 0x07, 0x63, 0x6f, 0x6e, 0x6e, 0x5f, - 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x63, 0x6f, 0x6e, 0x6e, 0x49, 0x64, - 0x42, 0x27, 0x5a, 0x25, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x64, - 0x65, 0x78, 0x69, 0x64, 0x70, 0x2f, 0x64, 0x65, 0x78, 0x2f, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, - 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, - 0x33, -}) +const file_server_internal_types_proto_rawDesc = "" + + "\n" + + "\x1bserver/internal/types.proto\x12\binternal\"C\n" + + "\fRefreshToken\x12\x1d\n" + + "\n" + + "refresh_id\x18\x01 \x01(\tR\trefreshId\x12\x14\n" + + "\x05token\x18\x02 \x01(\tR\x05token\"B\n" + + "\x0eIDTokenSubject\x12\x17\n" + + "\auser_id\x18\x01 \x01(\tR\x06userId\x12\x17\n" + + "\aconn_id\x18\x02 \x01(\tR\x06connIdB'Z%github.com/dexidp/dex/server/internalb\x06proto3" var ( file_server_internal_types_proto_rawDescOnce sync.Once diff --git a/server/introspectionhandler.go b/server/introspectionhandlers.go similarity index 93% rename from server/introspectionhandler.go rename to server/introspectionhandlers.go index 42ad1b3c70..307edc6098 100644 --- a/server/introspectionhandler.go +++ b/server/introspectionhandlers.go @@ -9,6 +9,7 @@ import ( "github.com/coreos/go-oidc/v3/oidc" + "github.com/dexidp/dex/pkg/otel/traces" "github.com/dexidp/dex/server/internal" ) @@ -145,6 +146,8 @@ func newIntrospectBadRequestError(desc string) *introspectionError { } func (s *Server) guessTokenType(ctx context.Context, token string) (TokenTypeEnum, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.server.guess_token_type") + defer span.End() // We skip every checks, we only want to know if it's a valid JWT verifierConfig := oidc.Config{ SkipClientIDCheck: true, @@ -166,6 +169,8 @@ func (s *Server) guessTokenType(ctx context.Context, token string) (TokenTypeEnu } func (s *Server) getTokenFromRequest(r *http.Request) (string, TokenTypeEnum, error) { + ctx, span := traces.InstrumentationTracer(r.Context(), "dex.server.get_token_from_request") + defer span.End() if r.Method != "POST" { return "", 0, newIntrospectBadRequestError(fmt.Sprintf("HTTP method is \"%s\", expected \"POST\".", r.Method)) } else if err := r.ParseForm(); err != nil { @@ -177,9 +182,9 @@ func (s *Server) getTokenFromRequest(r *http.Request) (string, TokenTypeEnum, er } token := r.PostForm.Get("token") - tokenType, err := s.guessTokenType(r.Context(), token) + tokenType, err := s.guessTokenType(ctx, token) if err != nil { - s.logger.ErrorContext(r.Context(), "failed to guess token type", "err", err) + s.logger.ErrorContext(ctx, "failed to guess token type", "err", err) return "", 0, newIntrospectInternalServerError() } @@ -194,6 +199,8 @@ func (s *Server) getTokenFromRequest(r *http.Request) (string, TokenTypeEnum, er } func (s *Server) introspectRefreshToken(ctx context.Context, token string) (*Introspection, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.server.introspect_refresh_token") + defer span.End() rToken := new(internal.RefreshToken) if err := internal.Unmarshal(token, rToken); err != nil { // For backward compatibility, assume the refresh_token is a raw refresh token ID @@ -245,6 +252,8 @@ func (s *Server) introspectRefreshToken(ctx context.Context, token string) (*Int } func (s *Server) introspectAccessToken(ctx context.Context, token string) (*Introspection, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.server.introspect_access_token") + defer span.End() verifier := oidc.NewVerifier(s.issuerURL.String(), &storageKeySet{s.storage}, &oidc.Config{SkipClientIDCheck: true}) idToken, err := verifier.Verify(ctx, token) if err != nil { @@ -287,8 +296,8 @@ func (s *Server) introspectAccessToken(ctx context.Context, token string) (*Intr } func (s *Server) handleIntrospect(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - + ctx, span := traces.InstrumentHandler(r) + defer span.End() var introspect *Introspection token, tokenType, err := s.getTokenFromRequest(r) if err == nil { @@ -299,7 +308,7 @@ func (s *Server) handleIntrospect(w http.ResponseWriter, r *http.Request) { introspect, err = s.introspectRefreshToken(ctx, token) default: // Token type is neither handled token types. - s.logger.ErrorContext(r.Context(), "unknown token type", "token_type", tokenType) + s.logger.ErrorContext(ctx, "unknown token type", "token_type", tokenType) introspectInactiveErr(w) return } @@ -309,7 +318,7 @@ func (s *Server) handleIntrospect(w http.ResponseWriter, r *http.Request) { if intErr, ok := err.(*introspectionError); ok { s.introspectErrHelper(w, intErr.typ, intErr.desc, intErr.code) } else { - s.logger.ErrorContext(r.Context(), "an unknown error occurred", "err", err.Error()) + s.logger.ErrorContext(ctx, "an unknown error occurred", "err", err.Error()) s.introspectErrHelper(w, errServerError, "An unknown error occurred", http.StatusInternalServerError) } diff --git a/server/introspectionhandler_test.go b/server/introspectionhandlers_test.go similarity index 100% rename from server/introspectionhandler_test.go rename to server/introspectionhandlers_test.go diff --git a/server/oauth2.go b/server/oauth2.go index 18cc3dd46d..c03cce30c6 100644 --- a/server/oauth2.go +++ b/server/oauth2.go @@ -24,6 +24,7 @@ import ( "github.com/go-jose/go-jose/v4" "github.com/dexidp/dex/connector" + "github.com/dexidp/dex/pkg/otel/traces" "github.com/dexidp/dex/server/internal" "github.com/dexidp/dex/storage" ) @@ -60,6 +61,8 @@ func (err *redirectedAuthErr) Error() string { func (err *redirectedAuthErr) Handler() http.Handler { hf := func(w http.ResponseWriter, r *http.Request) { + _, span := traces.InstrumentHandler(r) + defer span.End() v := url.Values{} v.Add("state", err.State) v.Add("error", err.Type) @@ -304,6 +307,8 @@ type federatedIDClaims struct { } func (s *Server) newAccessToken(ctx context.Context, clientID string, claims storage.Claims, scopes []string, nonce, connID string) (accessToken string, expiry time.Time, err error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.server.new_access_token") + defer span.End() return s.newIDToken(ctx, clientID, claims, scopes, nonce, storage.NewID(), "", connID) } @@ -351,12 +356,13 @@ func genSubject(userID string, connID string) (string, error) { } func (s *Server) newIDToken(ctx context.Context, clientID string, claims storage.Claims, scopes []string, nonce, accessToken, code, connID string) (idToken string, expiry time.Time, err error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.server.new_id_token") + defer span.End() keys, err := s.storage.GetKeys(ctx) if err != nil { s.logger.ErrorContext(ctx, "failed to get keys", "err", err) return "", expiry, err } - signingKey := keys.SigningKey if signingKey == nil { return "", expiry, fmt.Errorf("no key to sign payload with") @@ -365,10 +371,8 @@ func (s *Server) newIDToken(ctx context.Context, clientID string, claims storage if err != nil { return "", expiry, err } - issuedAt := s.now() expiry = issuedAt.Add(s.idTokensValidFor) - subjectString, err := genSubject(claims.UserID, connID) if err != nil { s.logger.ErrorContext(ctx, "failed to marshal offline session ID", "err", err) @@ -453,7 +457,8 @@ func (s *Server) newIDToken(ctx context.Context, clientID string, claims storage // parse the initial request from the OAuth2 client. func (s *Server) parseAuthorizationRequest(r *http.Request) (*storage.AuthRequest, error) { - ctx := r.Context() + ctx, span := traces.InstrumentationTracer(r.Context(), "dex.server.parse_authorization_request") + defer span.End() if err := r.ParseForm(); err != nil { return nil, newDisplayedErr(http.StatusBadRequest, "Failed to parse request.") } @@ -483,7 +488,7 @@ func (s *Server) parseAuthorizationRequest(r *http.Request) (*storage.AuthReques if err == storage.ErrNotFound { return nil, newDisplayedErr(http.StatusNotFound, "Invalid client_id (%q).", clientID) } - s.logger.ErrorContext(r.Context(), "failed to get client", "err", err) + s.logger.ErrorContext(ctx, "failed to get client", "err", err) return nil, newDisplayedErr(http.StatusInternalServerError, "Database error.") } @@ -502,7 +507,7 @@ func (s *Server) parseAuthorizationRequest(r *http.Request) (*storage.AuthReques if connectorID != "" { connectors, err := s.storage.ListConnectors(ctx) if err != nil { - s.logger.ErrorContext(r.Context(), "failed to list connectors", "err", err) + s.logger.ErrorContext(ctx, "failed to list connectors", "err", err) return nil, newRedirectedErr(errServerError, "Unable to retrieve connectors") } if !validateConnectorID(connectors, connectorID) { @@ -538,7 +543,7 @@ func (s *Server) parseAuthorizationRequest(r *http.Request) (*storage.AuthReques continue } - isTrusted, err := s.validateCrossClientTrust(r.Context(), clientID, peerID) + isTrusted, err := s.validateCrossClientTrust(ctx, clientID, peerID) if err != nil { return nil, newRedirectedErr(errServerError, "Internal server error.") } @@ -632,6 +637,8 @@ func parseCrossClientScope(scope string) (peerID string, ok bool) { } func (s *Server) validateCrossClientTrust(ctx context.Context, clientID, peerID string) (trusted bool, err error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.server.validate_cross_client_trust") + defer span.End() if peerID == clientID { return true, nil } @@ -709,6 +716,8 @@ type storageKeySet struct { } func (s *storageKeySet) VerifySignature(ctx context.Context, jwt string) (payload []byte, err error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.server.storage_key_set.VerifySignature") + defer span.End() jws, err := jose.ParseSigned(jwt, []jose.SignatureAlgorithm{jose.RS256, jose.RS384, jose.RS512, jose.ES256, jose.ES384, jose.ES512}) if err != nil { return nil, err diff --git a/server/passwordgranthandlers.go b/server/passwordgranthandlers.go new file mode 100644 index 0000000000..4d88d4c646 --- /dev/null +++ b/server/passwordgranthandlers.go @@ -0,0 +1,244 @@ +package server + +import ( + "fmt" + "net/http" + "strings" + + "github.com/dexidp/dex/connector" + "github.com/dexidp/dex/pkg/otel/traces" + "github.com/dexidp/dex/server/internal" + "github.com/dexidp/dex/storage" +) + +func (s *Server) handlePasswordGrant(w http.ResponseWriter, r *http.Request, client storage.Client) { + ctx, span := traces.InstrumentHandler(r) + defer span.End() + // Parse the fields + if err := r.ParseForm(); err != nil { + s.tokenErrHelper(ctx, w, errInvalidRequest, "Couldn't parse data", http.StatusBadRequest) + return + } + q := r.Form + + nonce := q.Get("nonce") + // Some clients, like the old go-oidc, provide extra whitespace. Tolerate this. + scopes := strings.Fields(q.Get("scope")) + + // Parse the scopes if they are passed + var ( + unrecognized []string + invalidScopes []string + ) + hasOpenIDScope := false + for _, scope := range scopes { + switch scope { + case scopeOpenID: + hasOpenIDScope = true + case scopeOfflineAccess, scopeEmail, scopeProfile, scopeGroups, scopeFederatedID: + default: + peerID, ok := parseCrossClientScope(scope) + if !ok { + unrecognized = append(unrecognized, scope) + continue + } + + isTrusted, err := s.validateCrossClientTrust(ctx, client.ID, peerID) + if err != nil { + s.tokenErrHelper(ctx, w, errInvalidClient, fmt.Sprintf("Error validating cross client trust %v.", err), http.StatusBadRequest) + return + } + if !isTrusted { + invalidScopes = append(invalidScopes, scope) + } + } + } + if !hasOpenIDScope { + s.tokenErrHelper(ctx, w, errInvalidRequest, `Missing required scope(s) ["openid"].`, http.StatusBadRequest) + return + } + if len(unrecognized) > 0 { + s.tokenErrHelper(ctx, w, errInvalidRequest, fmt.Sprintf("Unrecognized scope(s) %q", unrecognized), http.StatusBadRequest) + return + } + if len(invalidScopes) > 0 { + s.tokenErrHelper(ctx, w, errInvalidRequest, fmt.Sprintf("Client can't request scope(s) %q", invalidScopes), http.StatusBadRequest) + return + } + + // Which connector + connID := s.passwordConnector + conn, err := s.getConnector(ctx, connID) + if err != nil { + s.tokenErrHelper(ctx, w, errInvalidRequest, "Requested connector does not exist.", http.StatusBadRequest) + return + } + + passwordConnector, ok := conn.Connector.(connector.PasswordConnector) + if !ok { + s.tokenErrHelper(ctx, w, errInvalidRequest, "Requested password connector does not correct type.", http.StatusBadRequest) + return + } + + // Login + username := q.Get("username") + password := q.Get("password") + identity, ok, err := passwordConnector.Login(ctx, parseScopes(scopes), username, password) + if err != nil { + s.logger.ErrorContext(ctx, "failed to login user", "err", err) + s.tokenErrHelper(ctx, w, errInvalidRequest, "Could not login user", http.StatusBadRequest) + return + } + if !ok { + s.tokenErrHelper(ctx, w, errAccessDenied, "Invalid username or password", http.StatusUnauthorized) + return + } + + // Build the claims to send the id token + claims := storage.Claims{ + UserID: identity.UserID, + Username: identity.Username, + PreferredUsername: identity.PreferredUsername, + Email: identity.Email, + EmailVerified: identity.EmailVerified, + Groups: identity.Groups, + } + + accessToken, _, err := s.newAccessToken(ctx, client.ID, claims, scopes, nonce, connID) + if err != nil { + s.logger.ErrorContext(ctx, "password grant failed to create new access token", "err", err) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) + return + } + + idToken, expiry, err := s.newIDToken(ctx, client.ID, claims, scopes, nonce, accessToken, "", connID) + if err != nil { + s.logger.ErrorContext(ctx, "password grant failed to create new ID token", "err", err) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) + return + } + + reqRefresh := func() bool { + // Ensure the connector supports refresh tokens. + // + // Connectors like `saml` do not implement RefreshConnector. + _, ok := conn.Connector.(connector.RefreshConnector) + if !ok { + return false + } + + for _, scope := range scopes { + if scope == scopeOfflineAccess { + return true + } + } + return false + }() + var refreshToken string + if reqRefresh { + refresh := storage.RefreshToken{ + ID: storage.NewID(), + Token: storage.NewID(), + ClientID: client.ID, + ConnectorID: connID, + Scopes: scopes, + Claims: claims, + Nonce: nonce, + // ConnectorData: authCode.ConnectorData, + CreatedAt: s.now(), + LastUsed: s.now(), + } + token := &internal.RefreshToken{ + RefreshId: refresh.ID, + Token: refresh.Token, + } + if refreshToken, err = internal.Marshal(token); err != nil { + s.logger.ErrorContext(ctx, "failed to marshal refresh token", "err", err) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) + return + } + + if err := s.storage.CreateRefresh(ctx, refresh); err != nil { + s.logger.ErrorContext(ctx, "failed to create refresh token", "err", err) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) + return + } + + // deleteToken determines if we need to delete the newly created refresh token + // due to a failure in updating/creating the OfflineSession object for the + // corresponding user. + var deleteToken bool + defer func() { + if deleteToken { + // Delete newly created refresh token from storage. + if err := s.storage.DeleteRefresh(ctx, refresh.ID); err != nil { + s.logger.ErrorContext(ctx, "failed to delete refresh token", "err", err) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) + return + } + } + }() + + tokenRef := storage.RefreshTokenRef{ + ID: refresh.ID, + ClientID: refresh.ClientID, + CreatedAt: refresh.CreatedAt, + LastUsed: refresh.LastUsed, + } + + // Try to retrieve an existing OfflineSession object for the corresponding user. + if session, err := s.storage.GetOfflineSessions(ctx, refresh.Claims.UserID, refresh.ConnectorID); err != nil { + if err != storage.ErrNotFound { + s.logger.ErrorContext(ctx, "failed to get offline session", "err", err) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) + deleteToken = true + return + } + offlineSessions := storage.OfflineSessions{ + UserID: refresh.Claims.UserID, + ConnID: refresh.ConnectorID, + Refresh: make(map[string]*storage.RefreshTokenRef), + ConnectorData: identity.ConnectorData, + } + offlineSessions.Refresh[tokenRef.ClientID] = &tokenRef + + // Create a new OfflineSession object for the user and add a reference object for + // the newly received refreshtoken. + if err := s.storage.CreateOfflineSessions(ctx, offlineSessions); err != nil { + s.logger.ErrorContext(ctx, "failed to create offline session", "err", err) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) + deleteToken = true + return + } + } else { + if oldTokenRef, ok := session.Refresh[tokenRef.ClientID]; ok { + // Delete old refresh token from storage. + if err := s.storage.DeleteRefresh(ctx, oldTokenRef.ID); err != nil { + if err == storage.ErrNotFound { + s.logger.Warn("database inconsistent, refresh token missing", "token_id", oldTokenRef.ID) + } else { + s.logger.ErrorContext(ctx, "failed to delete refresh token", "err", err) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) + deleteToken = true + return + } + } + } + + // Update existing OfflineSession obj with new RefreshTokenRef. + if err := s.storage.UpdateOfflineSessions(ctx, session.UserID, session.ConnID, func(old storage.OfflineSessions) (storage.OfflineSessions, error) { + old.Refresh[tokenRef.ClientID] = &tokenRef + old.ConnectorData = identity.ConnectorData + return old, nil + }); err != nil { + s.logger.ErrorContext(ctx, "failed to update offline session", "err", err) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) + deleteToken = true + return + } + } + } + + resp := s.toAccessTokenResponse(idToken, accessToken, refreshToken, expiry) + s.writeAccessToken(ctx, w, resp) +} diff --git a/server/passwordloginhandlers.go b/server/passwordloginhandlers.go new file mode 100644 index 0000000000..6ca7bb7f9d --- /dev/null +++ b/server/passwordloginhandlers.go @@ -0,0 +1,115 @@ +package server + +import ( + "fmt" + "net/http" + "net/url" + + "github.com/gorilla/mux" + + "github.com/dexidp/dex/connector" + "github.com/dexidp/dex/pkg/otel/traces" + "github.com/dexidp/dex/storage" +) + +func (s *Server) handlePasswordLogin(w http.ResponseWriter, r *http.Request) { + ctx, span := traces.InstrumentHandler(r) + defer span.End() + connID, err := url.PathUnescape(mux.Vars(r)["connector"]) + if err != nil { + s.logger.ErrorContext(ctx, "failed to unescape connector ID", "err", err) + s.renderError(r, w, http.StatusBadRequest, "Invalid connector ID.") + return + } + + authID := r.URL.Query().Get("state") + if authID == "" { + s.renderError(r, w, http.StatusBadRequest, "User session error.") + return + } + + backLink := r.URL.Query().Get("back") + + authReq, err := s.storage.GetAuthRequest(ctx, authID) + if err != nil { + if err == storage.ErrNotFound { + s.logger.ErrorContext(ctx, "invalid 'state' parameter provided", "err", err) + s.renderError(r, w, http.StatusBadRequest, "Requested resource does not exist.") + return + } + + s.logger.ErrorContext(ctx, "failed to get auth request", "err", err) + s.renderError(r, w, http.StatusInternalServerError, "Database error.") + return + } + + if connID != "" && connID != authReq.ConnectorID { + s.logger.ErrorContext(ctx, "connector mismatch: password login triggered for different connector from authentication start", "start_connector_id", authReq.ConnectorID, "password_connector_id", connID) + s.renderError(r, w, http.StatusInternalServerError, "Requested resource does not exist.") + return + } + + conn, err := s.getConnector(ctx, authReq.ConnectorID) + if err != nil { + s.logger.ErrorContext(ctx, "failed to get connector", "connector_id", authReq.ConnectorID, "err", err) + s.renderError(r, w, http.StatusInternalServerError, "Connector failed to initialize.") + return + } + + pwConn, ok := conn.Connector.(connector.PasswordConnector) + if !ok { + s.logger.ErrorContext(ctx, "expected password connector in handlePasswordLogin()", "password_connector", pwConn) + s.renderError(r, w, http.StatusInternalServerError, "Requested resource does not exist.") + return + } + + switch r.Method { + case http.MethodGet: + if err := s.templates.password(r, w, r.URL.String(), "", usernamePrompt(pwConn), false, backLink); err != nil { + s.logger.ErrorContext(ctx, "server template error", "err", err) + } + case http.MethodPost: + username := r.FormValue("login") + password := r.FormValue("password") + scopes := parseScopes(authReq.Scopes) + + identity, ok, err := pwConn.Login(ctx, scopes, username, password) + if err != nil { + s.logger.ErrorContext(ctx, "failed to login user", "err", err) + s.renderError(r, w, http.StatusInternalServerError, fmt.Sprintf("Login error: %v", err)) + return + } + + if !ok { + if err := s.templates.password(r, w, r.URL.String(), username, usernamePrompt(pwConn), true, backLink); err != nil { + s.logger.ErrorContext(ctx, "server template error", "err", err) + } + + s.logger.ErrorContext(ctx, "failed login attempt: Invalid credentials.", "user", username) + return + } + + redirectURL, canSkipApproval, err := s.finalizeLogin(ctx, identity, authReq, conn.Connector) + if err != nil { + s.logger.ErrorContext(ctx, "failed to finalize login", "err", err) + s.renderError(r, w, http.StatusInternalServerError, "Login error.") + return + } + + if canSkipApproval { + authReq, err = s.storage.GetAuthRequest(ctx, authReq.ID) + if err != nil { + s.logger.ErrorContext(ctx, "failed to get finalized auth request", "err", err) + s.renderError(r, w, http.StatusInternalServerError, "Login error.") + return + } + + s.sendCodeResponse(w, r, authReq) + return + } + + http.Redirect(w, r, redirectURL, http.StatusSeeOther) + default: + s.renderError(r, w, http.StatusBadRequest, "Unsupported request method.") + } +} diff --git a/server/publickeyshandlers.go b/server/publickeyshandlers.go new file mode 100644 index 0000000000..92508d5d40 --- /dev/null +++ b/server/publickeyshandlers.go @@ -0,0 +1,53 @@ +package server + +import ( + "encoding/json" + "fmt" + "net/http" + "strconv" + "time" + + "github.com/go-jose/go-jose/v4" + + "github.com/dexidp/dex/pkg/otel/traces" +) + +func (s *Server) handlePublicKeys(w http.ResponseWriter, r *http.Request) { + ctx, span := traces.InstrumentHandler(r) + defer span.End() + keys, err := s.storage.GetKeys(ctx) + if err != nil { + s.logger.ErrorContext(ctx, "failed to get keys", "err", err) + s.renderError(r, w, http.StatusInternalServerError, "Internal server error.") + return + } + if keys.SigningKeyPub == nil { + s.logger.ErrorContext(ctx, "no public keys found.") + s.renderError(r, w, http.StatusInternalServerError, "Internal server error.") + return + } + + jwks := jose.JSONWebKeySet{ + Keys: make([]jose.JSONWebKey, len(keys.VerificationKeys)+1), + } + jwks.Keys[0] = *keys.SigningKeyPub + for i, verificationKey := range keys.VerificationKeys { + jwks.Keys[i+1] = *verificationKey.PublicKey + } + data, err := json.MarshalIndent(jwks, "", " ") + if err != nil { + s.logger.ErrorContext(ctx, "failed to marshal discovery data", "err", err) + s.renderError(r, w, http.StatusInternalServerError, "Internal server error.") + return + } + + maxAge := keys.NextRotation.Sub(s.now()) + if maxAge < (time.Minute * 2) { + maxAge = time.Minute * 2 + } + + w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d, must-revalidate", int(maxAge.Seconds()))) + w.Header().Set("Content-Type", "application/json") + w.Header().Set("Content-Length", strconv.Itoa(len(data))) + w.Write(data) +} diff --git a/server/refreshhandlers.go b/server/refreshhandlers.go index de8d9b7b8d..4f605e0a8b 100644 --- a/server/refreshhandlers.go +++ b/server/refreshhandlers.go @@ -9,6 +9,7 @@ import ( "time" "github.com/dexidp/dex/connector" + "github.com/dexidp/dex/pkg/otel/traces" "github.com/dexidp/dex/server/internal" "github.com/dexidp/dex/storage" ) @@ -45,11 +46,13 @@ var ( expiredErr = newBadRequestError("Refresh token expired.") ) -func (s *Server) refreshTokenErrHelper(w http.ResponseWriter, err *refreshError) { - s.tokenErrHelper(w, err.msg, err.desc, err.code) +func (s *Server) refreshTokenErrHelper(ctx context.Context, w http.ResponseWriter, err *refreshError) { + s.tokenErrHelper(ctx, w, err.msg, err.desc, err.code) } func (s *Server) extractRefreshTokenFromRequest(r *http.Request) (*internal.RefreshToken, *refreshError) { + _, span := traces.InstrumentationTracer(r.Context(), "dex.server.extractRefreshTokenFromRequest") + defer span.End() code := r.PostFormValue("refresh_token") if code == "" { return nil, newBadRequestError("No refresh token is found in request.") @@ -81,6 +84,8 @@ type refreshContext struct { // getRefreshTokenFromStorage checks that refresh token is valid and exists in the storage and gets its info func (s *Server) getRefreshTokenFromStorage(ctx context.Context, clientID *string, token *internal.RefreshToken) (*refreshContext, *refreshError) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.server.getRefreshTokenFromStorage") + defer span.End() refreshCtx := refreshContext{requestToken: token} // Get RefreshToken @@ -151,6 +156,8 @@ func (s *Server) getRefreshTokenFromStorage(ctx context.Context, clientID *strin } func (s *Server) getRefreshScopes(r *http.Request, refresh *storage.RefreshToken) ([]string, *refreshError) { + _, span := traces.InstrumentationTracer(r.Context(), "dex.server.getRefreshScopes") + defer span.End() // Per the OAuth2 spec, if the client has omitted the scopes, default to the original // authorized scopes. // @@ -183,6 +190,8 @@ func (s *Server) getRefreshScopes(r *http.Request, refresh *storage.RefreshToken } func (s *Server) refreshWithConnector(ctx context.Context, rCtx *refreshContext, ident connector.Identity) (connector.Identity, *refreshError) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.server.refreshWithConnector") + defer span.End() // Can the connector refresh the identity? If so, attempt to refresh the data // in the connector. // @@ -206,6 +215,8 @@ func (s *Server) refreshWithConnector(ctx context.Context, rCtx *refreshContext, // updateOfflineSession updates offline session in the storage func (s *Server) updateOfflineSession(ctx context.Context, refresh *storage.RefreshToken, ident connector.Identity, lastUsed time.Time) *refreshError { + ctx, span := traces.InstrumentationTracer(ctx, "dex.server.updateOfflineSession") + defer span.End() offlineSessionUpdater := func(old storage.OfflineSessions) (storage.OfflineSessions, error) { if old.Refresh[refresh.ClientID].ID != refresh.ID { return old, errors.New("refresh token invalid") @@ -235,7 +246,8 @@ func (s *Server) updateOfflineSession(ctx context.Context, refresh *storage.Refr // updateRefreshToken updates refresh token and offline session in the storage func (s *Server) updateRefreshToken(ctx context.Context, rCtx *refreshContext) (*internal.RefreshToken, connector.Identity, *refreshError) { var rerr *refreshError - + ctx, span := traces.InstrumentationTracer(ctx, "dex.server.updateRefreshToken") + defer span.End() newToken := &internal.RefreshToken{ Token: rCtx.requestToken.Token, RefreshId: rCtx.requestToken.RefreshId, @@ -309,7 +321,6 @@ func (s *Server) updateRefreshToken(ctx context.Context, rCtx *refreshContext) ( old.Claims.Email = ident.Email old.Claims.EmailVerified = ident.EmailVerified old.Claims.Groups = ident.Groups - return old, nil } @@ -331,27 +342,29 @@ func (s *Server) updateRefreshToken(ctx context.Context, rCtx *refreshContext) ( // handleRefreshToken handles a refresh token request https://tools.ietf.org/html/rfc6749#section-6 // this method is the entrypoint for refresh tokens handling func (s *Server) handleRefreshToken(w http.ResponseWriter, r *http.Request, client storage.Client) { + ctx, span := traces.InstrumentHandler(r) + defer span.End() token, rerr := s.extractRefreshTokenFromRequest(r) if rerr != nil { - s.refreshTokenErrHelper(w, rerr) + s.refreshTokenErrHelper(ctx, w, rerr) return } - rCtx, rerr := s.getRefreshTokenFromStorage(r.Context(), &client.ID, token) + rCtx, rerr := s.getRefreshTokenFromStorage(ctx, &client.ID, token) if rerr != nil { - s.refreshTokenErrHelper(w, rerr) + s.refreshTokenErrHelper(ctx, w, rerr) return } rCtx.scopes, rerr = s.getRefreshScopes(r, rCtx.storageToken) if rerr != nil { - s.refreshTokenErrHelper(w, rerr) + s.refreshTokenErrHelper(ctx, w, rerr) return } - newToken, ident, rerr := s.updateRefreshToken(r.Context(), rCtx) + newToken, ident, rerr := s.updateRefreshToken(ctx, rCtx) if rerr != nil { - s.refreshTokenErrHelper(w, rerr) + s.refreshTokenErrHelper(ctx, w, rerr) return } @@ -364,27 +377,27 @@ func (s *Server) handleRefreshToken(w http.ResponseWriter, r *http.Request, clie Groups: ident.Groups, } - accessToken, _, err := s.newAccessToken(r.Context(), client.ID, claims, rCtx.scopes, rCtx.storageToken.Nonce, rCtx.storageToken.ConnectorID) + accessToken, _, err := s.newAccessToken(ctx, client.ID, claims, rCtx.scopes, rCtx.storageToken.Nonce, rCtx.storageToken.ConnectorID) if err != nil { - s.logger.ErrorContext(r.Context(), "failed to create new access token", "err", err) - s.refreshTokenErrHelper(w, newInternalServerError()) + s.logger.ErrorContext(ctx, "failed to create new access token", "err", err) + s.refreshTokenErrHelper(ctx, w, newInternalServerError()) return } - idToken, expiry, err := s.newIDToken(r.Context(), client.ID, claims, rCtx.scopes, rCtx.storageToken.Nonce, accessToken, "", rCtx.storageToken.ConnectorID) + idToken, expiry, err := s.newIDToken(ctx, client.ID, claims, rCtx.scopes, rCtx.storageToken.Nonce, accessToken, "", rCtx.storageToken.ConnectorID) if err != nil { - s.logger.ErrorContext(r.Context(), "failed to create ID token", "err", err) - s.refreshTokenErrHelper(w, newInternalServerError()) + s.logger.ErrorContext(ctx, "failed to create ID token", "err", err) + s.refreshTokenErrHelper(ctx, w, newInternalServerError()) return } rawNewToken, err := internal.Marshal(newToken) if err != nil { - s.logger.ErrorContext(r.Context(), "failed to marshal refresh token", "err", err) - s.refreshTokenErrHelper(w, newInternalServerError()) + s.logger.ErrorContext(ctx, "failed to marshal refresh token", "err", err) + s.refreshTokenErrHelper(ctx, w, newInternalServerError()) return } resp := s.toAccessTokenResponse(idToken, accessToken, rawNewToken, expiry) - s.writeAccessToken(w, resp) + s.writeAccessToken(ctx, w, resp) } diff --git a/server/rotation.go b/server/rotation.go index 286b4b57af..6f68144375 100644 --- a/server/rotation.go +++ b/server/rotation.go @@ -13,6 +13,7 @@ import ( "github.com/go-jose/go-jose/v4" + "github.com/dexidp/dex/pkg/otel/traces" "github.com/dexidp/dex/storage" ) @@ -69,14 +70,16 @@ type keyRotator struct { // The method blocks until after the first attempt to rotate keys has completed. That way // healthy storages will return from this call with valid keys. func (s *Server) startKeyRotation(ctx context.Context, strategy rotationStrategy, now func() time.Time) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.server.startKeyRotation") + defer span.End() rotator := keyRotator{s.storage, strategy, now, s.logger} // Try to rotate immediately so properly configured storages will have keys. - if err := rotator.rotate(); err != nil { + if err := rotator.rotate(ctx); err != nil { if err == errAlreadyRotated { s.logger.Info("key rotation not needed", "err", err) } else { - s.logger.Error("failed to rotate keys", "err", err) + s.logger.ErrorContext(ctx, "failed to rotate keys", "err", err) } } @@ -86,23 +89,25 @@ func (s *Server) startKeyRotation(ctx context.Context, strategy rotationStrategy case <-ctx.Done(): return case <-time.After(time.Second * 30): - if err := rotator.rotate(); err != nil { - s.logger.Error("failed to rotate keys", "err", err) + if err := rotator.rotate(ctx); err != nil { + s.logger.ErrorContext(ctx, "failed to rotate keys", "err", err) } } } }() } -func (k keyRotator) rotate() error { - keys, err := k.GetKeys(context.Background()) +func (k keyRotator) rotate(ctx context.Context) error { + ctx, span := traces.InstrumentationTracer(ctx, "dex.server.keyRotator.rotate") + defer span.End() + keys, err := k.GetKeys(ctx) if err != nil && err != storage.ErrNotFound { return fmt.Errorf("get keys: %v", err) } if k.now().Before(keys.NextRotation) { return nil } - k.logger.Info("keys expired, rotating") + k.logger.InfoContext(ctx, "keys expired, rotating") // Generate the key outside of a storage transaction. key, err := k.strategy.key() @@ -174,7 +179,7 @@ func (k keyRotator) rotate() error { if err != nil { return err } - k.logger.Info("keys rotated", "next_rotation", nextRotation) + k.logger.InfoContext(ctx, "keys rotated", "next_rotation", nextRotation) return nil } diff --git a/server/rotation_test.go b/server/rotation_test.go index c7e6bada2f..c75ab36989 100644 --- a/server/rotation_test.go +++ b/server/rotation_test.go @@ -81,7 +81,7 @@ func TestKeyRotator(t *testing.T) { for i := 0; i < 10; i++ { now = now.Add(rotationFrequency + delta) - if err := r.rotate(); err != nil { + if err := r.rotate(context.Background()); err != nil { t.Fatal(err) } diff --git a/server/server.go b/server/server.go index 0f48fc1138..2f4048db03 100644 --- a/server/server.go +++ b/server/server.go @@ -24,8 +24,9 @@ import ( "github.com/google/uuid" "github.com/gorilla/handlers" "github.com/gorilla/mux" - "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/promhttp" + "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" + "go.opentelemetry.io/otel" + "go.opentelemetry.io/otel/metric" "golang.org/x/crypto/bcrypt" "github.com/dexidp/dex/connector" @@ -45,6 +46,7 @@ import ( "github.com/dexidp/dex/connector/oidc" "github.com/dexidp/dex/connector/openshift" "github.com/dexidp/dex/connector/saml" + "github.com/dexidp/dex/pkg/otel/traces" "github.com/dexidp/dex/storage" "github.com/dexidp/dex/web" ) @@ -114,9 +116,9 @@ type Config struct { Web WebConfig - Logger *slog.Logger + Meter metric.Meter - PrometheusRegistry *prometheus.Registry + Logger *slog.Logger HealthChecker gosundheit.Health @@ -218,6 +220,8 @@ func NewServerWithKey(ctx context.Context, c Config, privateKey *rsa.PrivateKey) } func newServer(ctx context.Context, c Config, rotationStrategy rotationStrategy) (*Server, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.server.new_server") + defer span.End() issuerURL, err := url.Parse(c.Issuer) if err != nil { return nil, fmt.Errorf("server: can't parse issuer URL") @@ -349,36 +353,9 @@ func newServer(ctx context.Context, c Config, rotationStrategy rotationStrategy) return handler.ServeHTTP } - if c.PrometheusRegistry != nil { - requestCounter := prometheus.NewCounterVec(prometheus.CounterOpts{ - Name: "http_requests_total", - Help: "Count of all HTTP requests.", - }, []string{"code", "method", "handler"}) - - durationHist := prometheus.NewHistogramVec(prometheus.HistogramOpts{ - Name: "request_duration_seconds", - Help: "A histogram of latencies for requests.", - Buckets: []float64{.25, .5, 1, 2.5, 5, 10}, - }, []string{"code", "method", "handler"}) - - sizeHist := prometheus.NewHistogramVec(prometheus.HistogramOpts{ - Name: "response_size_bytes", - Help: "A histogram of response sizes for requests.", - Buckets: []float64{200, 500, 900, 1500}, - }, []string{"code", "method", "handler"}) - - c.PrometheusRegistry.MustRegister(requestCounter, durationHist, sizeHist) - - instrumentHandler = func(handlerName string, handler http.Handler) http.HandlerFunc { - return promhttp.InstrumentHandlerDuration(durationHist.MustCurryWith(prometheus.Labels{"handler": handlerName}), - promhttp.InstrumentHandlerCounter(requestCounter.MustCurryWith(prometheus.Labels{"handler": handlerName}), - promhttp.InstrumentHandlerResponseSize(sizeHist.MustCurryWith(prometheus.Labels{"handler": handlerName}), handler), - ), - ) - } - } - parseRealIP := func(r *http.Request) (string, error) { + _, span := traces.InstrumentationTracer(r.Context(), "dex.server.parse_real_ip") + defer span.End() remoteAddr, _, err := net.SplitHostPort(r.RemoteAddr) if err != nil { return "", err @@ -408,12 +385,13 @@ func newServer(ctx context.Context, c Config, rotationStrategy rotationStrategy) handlerWithHeaders := func(handlerName string, handler http.Handler) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { + rCtx, span := traces.InstrumentationTracer(r.Context(), "middleware - dex.request_context") + defer span.End() for k, v := range c.Headers { w.Header()[k] = v } // Context values are used for logging purposes with the log/slog logger. - rCtx := r.Context() rCtx = WithRequestID(rCtx) if c.RealIPHeader != "" { @@ -459,14 +437,16 @@ func newServer(ctx context.Context, c Config, rotationStrategy rotationStrategy) handleWithCORS("/.well-known/openid-configuration", discoveryHandler) // Handle the root path for the better user experience. handleWithCORS("/", func(w http.ResponseWriter, r *http.Request) { + ctx, span := traces.InstrumentHandler(r) + defer span.End() _, err := fmt.Fprintf(w, ` - Dex -

Dex IdP

-

A Federated OpenID Connect Provider

-

Discovery

`, + Dex +

Dex IdP

+

A Federated OpenID Connect Provider

+

Discovery

`, s.issuerURL.String()+"/.well-known/openid-configuration") if err != nil { - s.logger.Error("failed to write response", "err", err) + s.logger.ErrorContext(ctx, "failed to write response", "err", err) s.renderError(r, w, http.StatusInternalServerError, "Handling the / path error.") return } @@ -477,7 +457,7 @@ func newServer(ctx context.Context, c Config, rotationStrategy rotationStrategy) handleWithCORS("/keys", s.handlePublicKeys) handleWithCORS("/userinfo", s.handleUserInfo) handleWithCORS("/token/introspect", s.handleIntrospect) - handleFunc("/auth", s.handleAuthorization) + handleFunc("/auth", s.handleAuthorization) // Add custom in handler as below handleFunc("/auth/{connector}", s.handleConnectorLogin) handleFunc("/auth/{connector}/login", s.handlePasswordLogin) handleFunc("/device", s.handleDeviceExchange) @@ -487,6 +467,8 @@ func newServer(ctx context.Context, c Config, rotationStrategy rotationStrategy) handleFunc("/device/token", s.handleDeviceTokenDeprecated) handleFunc(deviceCallbackURI, s.handleDeviceCallback) handleFunc("/callback", func(w http.ResponseWriter, r *http.Request) { + _, span := traces.InstrumentHandler(r) + defer span.End() // Strip the X-Remote-* headers to prevent security issues on // misconfigured authproxy connector setups. for key := range r.Header { @@ -512,7 +494,10 @@ func newServer(ctx context.Context, c Config, rotationStrategy rotationStrategy) handlePrefix("/theme", theme) handleFunc("/robots.txt", robots) - s.mux = r + // ADDED FOR METRICS: Wrap mux with OTEL HTTP middleware for auto-instrumentation (complements serve.go's wrapping) + s.mux = otelhttp.NewHandler(r, "dex.server.http", + otelhttp.WithMeterProvider(otel.GetMeterProvider()), + ) s.startKeyRotation(ctx, rotationStrategy, now) s.startGarbageCollection(ctx, value(c.GCFrequency, 5*time.Minute), now) @@ -521,6 +506,8 @@ func newServer(ctx context.Context, c Config, rotationStrategy rotationStrategy) } func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { + _, span := traces.InstrumentHandler(r) + defer span.End() s.mux.ServeHTTP(w, r) } @@ -549,6 +536,8 @@ type passwordDB struct { } func (db passwordDB) Login(ctx context.Context, s connector.Scopes, email, password string) (connector.Identity, bool, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.password_db.login") + defer span.End() p, err := db.s.GetPassword(ctx, email) if err != nil { if err != storage.ErrNotFound { @@ -573,6 +562,8 @@ func (db passwordDB) Login(ctx context.Context, s connector.Scopes, email, passw } func (db passwordDB) Refresh(ctx context.Context, s connector.Scopes, identity connector.Identity) (connector.Identity, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.password_db.refresh") + defer span.End() // If the user has been deleted, the refresh token will be rejected. p, err := db.s.GetPassword(ctx, identity.Email) if err != nil { @@ -617,6 +608,8 @@ type keyCacher struct { } func (k *keyCacher) GetKeys(ctx context.Context) (storage.Keys, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.get_keys") + defer span.End() keys, ok := k.keys.Load().(*storage.Keys) if ok && keys != nil && k.now().Before(keys.NextRotation) { return *keys, nil @@ -634,6 +627,8 @@ func (k *keyCacher) GetKeys(ctx context.Context) (storage.Keys, error) { } func (s *Server) startGarbageCollection(ctx context.Context, frequency time.Duration, now func() time.Time) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.startGarbageCollection") + defer span.End() go func() { for { select { @@ -734,6 +729,8 @@ func (s *Server) OpenConnector(conn storage.Connector) (Connector, error) { // getConnector retrieves the connector object with the given id from the storage // and updates the connector list for server if necessary. func (s *Server) getConnector(ctx context.Context, id string) (Connector, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.Server.get_connector") + defer span.End() storageConnector, err := s.storage.GetConnector(ctx, id) if err != nil { return Connector{}, fmt.Errorf("failed to get connector object from storage: %v", err) @@ -766,9 +763,13 @@ const ( ) func WithRequestID(ctx context.Context) context.Context { + ctx, span := traces.InstrumentationTracer(ctx, "dex.request_id") + defer span.End() return context.WithValue(ctx, RequestKeyRequestID, uuid.NewString()) } func WithRemoteIP(ctx context.Context, ip string) context.Context { + ctx, span := traces.InstrumentationTracer(ctx, "dex.remote_ip") + defer span.End() return context.WithValue(ctx, RequestKeyRemoteIP, ip) } diff --git a/server/server_test.go b/server/server_test.go index c414eb885e..6d4d0626a8 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -25,7 +25,6 @@ import ( "github.com/coreos/go-oidc/v3/oidc" "github.com/go-jose/go-jose/v4" "github.com/kylelemons/godebug/pretty" - "github.com/prometheus/client_golang/prometheus" "github.com/stretchr/testify/require" "golang.org/x/crypto/bcrypt" "golang.org/x/oauth2" @@ -91,7 +90,6 @@ func newTestServer(ctx context.Context, t *testing.T, updateConfig func(c *Confi Dir: "../web", }, Logger: logger, - PrometheusRegistry: prometheus.NewRegistry(), HealthChecker: gosundheit.New(), SkipApprovalScreen: true, // Don't prompt for approval, just immediately redirect with code. AllowedGrantTypes: []string{ // all implemented types @@ -147,8 +145,7 @@ func newTestServerMultipleConnectors(ctx context.Context, t *testing.T, updateCo Web: WebConfig{ Dir: "../web", }, - Logger: logger, - PrometheusRegistry: prometheus.NewRegistry(), + Logger: logger, } if updateConfig != nil { updateConfig(&config) @@ -1966,7 +1963,6 @@ func TestConnectorFailureHandling(t *testing.T) { Dir: "../web", }, Logger: logger, - PrometheusRegistry: prometheus.NewRegistry(), HealthChecker: gosundheit.New(), ContinueOnConnectorFailure: tc.continueOnConnectorFailure, } diff --git a/server/tokenexchangehandlers.go b/server/tokenexchangehandlers.go new file mode 100644 index 0000000000..c726bb9e92 --- /dev/null +++ b/server/tokenexchangehandlers.go @@ -0,0 +1,98 @@ +package server + +import ( + "encoding/json" + "net/http" + "strings" + "time" + + "github.com/dexidp/dex/connector" + "github.com/dexidp/dex/pkg/otel/traces" + "github.com/dexidp/dex/storage" +) + +func (s *Server) handleTokenExchange(w http.ResponseWriter, r *http.Request, client storage.Client) { + ctx, span := traces.InstrumentHandler(r) + defer span.End() + if err := r.ParseForm(); err != nil { + s.logger.ErrorContext(ctx, "could not parse request body", "err", err) + s.tokenErrHelper(ctx, w, errInvalidRequest, "", http.StatusBadRequest) + return + } + q := r.Form + + scopes := strings.Fields(q.Get("scope")) // OPTIONAL, map to issued token scope + requestedTokenType := q.Get("requested_token_type") // OPTIONAL, default to access token + if requestedTokenType == "" { + requestedTokenType = tokenTypeAccess + } + subjectToken := q.Get("subject_token") // REQUIRED + subjectTokenType := q.Get("subject_token_type") // REQUIRED + connID := q.Get("connector_id") // REQUIRED, not in RFC + + switch subjectTokenType { + case tokenTypeID, tokenTypeAccess: // ok, continue + default: + s.tokenErrHelper(ctx, w, errRequestNotSupported, "Invalid subject_token_type.", http.StatusBadRequest) + return + } + + if subjectToken == "" { + s.tokenErrHelper(ctx, w, errInvalidRequest, "Missing subject_token", http.StatusBadRequest) + return + } + + conn, err := s.getConnector(ctx, connID) + if err != nil { + s.logger.ErrorContext(ctx, "failed to get connector", "err", err) + s.tokenErrHelper(ctx, w, errInvalidRequest, "Requested connector does not exist.", http.StatusBadRequest) + return + } + teConn, ok := conn.Connector.(connector.TokenIdentityConnector) + if !ok { + s.logger.ErrorContext(ctx, "connector doesn't implement token exchange", "connector_id", connID) + s.tokenErrHelper(ctx, w, errInvalidRequest, "Requested connector does not exist.", http.StatusBadRequest) + return + } + identity, err := teConn.TokenIdentity(ctx, subjectTokenType, subjectToken) + if err != nil { + s.logger.ErrorContext(ctx, "failed to verify subject token", "err", err) + s.tokenErrHelper(ctx, w, errAccessDenied, "", http.StatusUnauthorized) + return + } + + claims := storage.Claims{ + UserID: identity.UserID, + Username: identity.Username, + PreferredUsername: identity.PreferredUsername, + Email: identity.Email, + EmailVerified: identity.EmailVerified, + Groups: identity.Groups, + } + resp := accessTokenResponse{ + IssuedTokenType: requestedTokenType, + TokenType: "bearer", + } + var expiry time.Time + switch requestedTokenType { + case tokenTypeID: + resp.AccessToken, expiry, err = s.newIDToken(ctx, client.ID, claims, scopes, "", "", "", connID) + case tokenTypeAccess: + resp.AccessToken, expiry, err = s.newAccessToken(ctx, client.ID, claims, scopes, "", connID) + default: + s.tokenErrHelper(ctx, w, errRequestNotSupported, "Invalid requested_token_type.", http.StatusBadRequest) + return + } + if err != nil { + s.logger.ErrorContext(ctx, "token exchange failed to create new token", "requested_token_type", requestedTokenType, "err", err) + s.tokenErrHelper(ctx, w, errServerError, "", http.StatusInternalServerError) + return + } + resp.ExpiresIn = int(time.Until(expiry).Seconds()) + + // Token response must include cache headers https://tools.ietf.org/html/rfc6749#section-5.1 + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("Pragma", "no-cache") + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(resp) +} diff --git a/server/tokenhandlers.go b/server/tokenhandlers.go new file mode 100644 index 0000000000..841d22a647 --- /dev/null +++ b/server/tokenhandlers.go @@ -0,0 +1,46 @@ +package server + +import ( + "net/http" + + "github.com/dexidp/dex/pkg/otel/traces" +) + +func (s *Server) handleToken(w http.ResponseWriter, r *http.Request) { + ctx, span := traces.InstrumentHandler(r) + defer span.End() + w.Header().Set("Content-Type", "application/json") + if r.Method != http.MethodPost { + s.tokenErrHelper(ctx, w, errInvalidRequest, "method not allowed", http.StatusBadRequest) + return + } + + err := r.ParseForm() + if err != nil { + s.logger.ErrorContext(ctx, "could not parse request body", "err", err) + s.tokenErrHelper(ctx, w, errInvalidRequest, "", http.StatusBadRequest) + return + } + + grantType := r.PostFormValue("grant_type") + if !contains(s.supportedGrantTypes, grantType) { + s.logger.ErrorContext(ctx, "unsupported grant type", "grant_type", grantType) + s.tokenErrHelper(ctx, w, errUnsupportedGrantType, "", http.StatusBadRequest) + return + } + switch grantType { + case grantTypeDeviceCode: + s.handleDeviceToken(w, r) + case grantTypeAuthorizationCode: + s.withClientFromStorage(w, r, s.handleAuthCode) + case grantTypeRefreshToken: + s.withClientFromStorage(w, r, s.handleRefreshToken) + case grantTypePassword: + s.withClientFromStorage(w, r, s.handlePasswordGrant) + case grantTypeTokenExchange: + s.withClientFromStorage(w, r, s.handleTokenExchange) + default: + s.tokenErrHelper(ctx, w, errUnsupportedGrantType, "", http.StatusBadRequest) + } + s.logger.InfoContext(ctx, "handled grant type", "grant_type", grantType) +} diff --git a/server/tokenhandlers_test.go b/server/tokenhandlers_test.go new file mode 100644 index 0000000000..b5a5c6eb1d --- /dev/null +++ b/server/tokenhandlers_test.go @@ -0,0 +1,120 @@ +package server + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/dexidp/dex/storage" +) + +func TestHandleTokenExchange(t *testing.T) { + tests := []struct { + name string + scope string + requestedTokenType string + subjectTokenType string + subjectToken string + + expectedCode int + expectedTokenType string + }{ + { + "id-for-acccess", + "openid", + tokenTypeAccess, + tokenTypeID, + "foobar", + http.StatusOK, + tokenTypeAccess, + }, + { + "id-for-id", + "openid", + tokenTypeID, + tokenTypeID, + "foobar", + http.StatusOK, + tokenTypeID, + }, + { + "id-for-default", + "openid", + "", + tokenTypeID, + "foobar", + http.StatusOK, + tokenTypeAccess, + }, + { + "access-for-access", + "openid", + tokenTypeAccess, + tokenTypeAccess, + "foobar", + http.StatusOK, + tokenTypeAccess, + }, + { + "missing-subject_token_type", + "openid", + tokenTypeAccess, + "", + "foobar", + http.StatusBadRequest, + "", + }, + { + "missing-subject_token", + "openid", + tokenTypeAccess, + tokenTypeAccess, + "", + http.StatusBadRequest, + "", + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + httpServer, s := newTestServer(ctx, t, func(c *Config) { + c.Storage.CreateClient(ctx, storage.Client{ + ID: "client_1", + Secret: "secret_1", + }) + }) + defer httpServer.Close() + vals := make(url.Values) + vals.Set("grant_type", grantTypeTokenExchange) + setNonEmpty(vals, "connector_id", "mock") + setNonEmpty(vals, "scope", tc.scope) + setNonEmpty(vals, "requested_token_type", tc.requestedTokenType) + setNonEmpty(vals, "subject_token_type", tc.subjectTokenType) + setNonEmpty(vals, "subject_token", tc.subjectToken) + setNonEmpty(vals, "client_id", "client_1") + setNonEmpty(vals, "client_secret", "secret_1") + + rr := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodPost, httpServer.URL+"/token", strings.NewReader(vals.Encode())) + req.Header.Set("content-type", "application/x-www-form-urlencoded") + + s.handleToken(rr, req) + + require.Equal(t, tc.expectedCode, rr.Code, rr.Body.String()) + require.Equal(t, "application/json", rr.Result().Header.Get("content-type")) + if tc.expectedCode == http.StatusOK { + var res accessTokenResponse + err := json.NewDecoder(rr.Result().Body).Decode(&res) + require.NoError(t, err) + require.Equal(t, tc.expectedTokenType, res.IssuedTokenType) + } + }) + } +} diff --git a/server/userinfohandlers.go b/server/userinfohandlers.go new file mode 100644 index 0000000000..100e3197c8 --- /dev/null +++ b/server/userinfohandlers.go @@ -0,0 +1,41 @@ +package server + +import ( + "encoding/json" + "net/http" + "strings" + + "github.com/coreos/go-oidc/v3/oidc" + + "github.com/dexidp/dex/pkg/otel/traces" +) + +func (s *Server) handleUserInfo(w http.ResponseWriter, r *http.Request) { + ctx, span := traces.InstrumentHandler(r) + defer span.End() + const prefix = "Bearer " + + auth := r.Header.Get("authorization") + if len(auth) < len(prefix) || !strings.EqualFold(prefix, auth[:len(prefix)]) { + w.Header().Set("WWW-Authenticate", "Bearer") + s.tokenErrHelper(ctx, w, errAccessDenied, "Invalid bearer token.", http.StatusUnauthorized) + return + } + rawIDToken := auth[len(prefix):] + + verifier := oidc.NewVerifier(s.issuerURL.String(), &storageKeySet{s.storage}, &oidc.Config{SkipClientIDCheck: true}) + idToken, err := verifier.Verify(ctx, rawIDToken) + if err != nil { + s.tokenErrHelper(ctx, w, errAccessDenied, err.Error(), http.StatusForbidden) + return + } + + var claims json.RawMessage + if err := idToken.Claims(&claims); err != nil { + s.tokenErrHelper(ctx, w, errServerError, err.Error(), http.StatusInternalServerError) + return + } + + w.Header().Set("Content-Type", "application/json") + w.Write(claims) +} diff --git a/server/userinfohandlers_test.go b/server/userinfohandlers_test.go new file mode 100644 index 0000000000..f37f276536 --- /dev/null +++ b/server/userinfohandlers_test.go @@ -0,0 +1,324 @@ +package server + +import ( + "context" + "crypto/rand" + "crypto/rsa" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/go-jose/go-jose/v4" + "github.com/stretchr/testify/require" + + "github.com/dexidp/dex/storage" +) + +func TestHandleUserInfo(t *testing.T) { + tests := []struct { + name string + authHeader string + expectedCode int + }{ + { + name: "no authorization header", + authHeader: "", + expectedCode: http.StatusUnauthorized, + }, + { + name: "invalid bearer prefix", + authHeader: "Basic foobar", + expectedCode: http.StatusUnauthorized, + }, + { + name: "invalid token", + authHeader: "Bearer invalidtoken", + expectedCode: http.StatusForbidden, + }, + { + name: "empty bearer token", + authHeader: "Bearer ", + expectedCode: http.StatusForbidden, + }, + { + name: "short auth header", + authHeader: "Bear", + expectedCode: http.StatusUnauthorized, + }, + { + name: "case insensitive bearer", + authHeader: "bearer invalidtoken", + expectedCode: http.StatusForbidden, + }, + // Valid cases will be handled separately as they require dynamic token generation + } + + // Setup for valid token tests + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + // Generate RSA key for signing + privateKey, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + + priv := &jose.JSONWebKey{ + Key: privateKey, + KeyID: "test-key", + Algorithm: "RS256", + Use: "sig", + } + pub := &jose.JSONWebKey{ + Key: privateKey.Public(), + KeyID: "test-key", + Algorithm: "RS256", + Use: "sig", + } + + // Generate another key for invalid signature test + privateKey2, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + + priv2 := &jose.JSONWebKey{ + Key: privateKey2, + KeyID: "wrong-key", + Algorithm: "RS256", + Use: "sig", + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + httpServer, s := newTestServer(ctx, t, func(c *Config) { + // No specific config needed for invalid cases + }) + defer httpServer.Close() + + rr := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, httpServer.URL+"/userinfo", nil) + if tc.authHeader != "" { + req.Header.Set("Authorization", tc.authHeader) + } + + s.handleUserInfo(rr, req) + + require.Equal(t, tc.expectedCode, rr.Code, rr.Body.String()) + require.Equal(t, "application/json", rr.Result().Header.Get("content-type")) + }) + } + + // Separate setup for valid tokens to set up keys once + httpServer, s := newTestServer(ctx, t, func(c *Config) { + // No specific config needed here + }) + defer httpServer.Close() + + // Set keys in storage after server creation + err = s.storage.UpdateKeys(ctx, func(keys storage.Keys) (storage.Keys, error) { + keys.SigningKey = priv + keys.SigningKeyPub = pub + keys.NextRotation = s.now().Add(24 * time.Hour) + return keys, nil + }) + require.NoError(t, err) + + validTests := []struct { + name string + claims map[string]interface{} + expected map[string]interface{} + }{ + { + name: "minimal claims", + claims: map[string]interface{}{ + "iss": s.issuerURL.String(), + "sub": "test-subject", + "aud": "test-audience", + "exp": s.now().Add(time.Hour).Unix(), + "iat": s.now().Unix(), + }, + expected: map[string]interface{}{ + "iss": s.issuerURL.String(), + "sub": "test-subject", + "aud": "test-audience", + "exp": s.now().Add(time.Hour).Unix(), + "iat": s.now().Unix(), + }, + }, + { + name: "with user info claims", + claims: map[string]interface{}{ + "iss": s.issuerURL.String(), + "sub": "test-subject", + "aud": "test-audience", + "exp": s.now().Add(time.Hour).Unix(), + "iat": s.now().Unix(), + "name": "Test User", + "email": "test@example.com", + }, + expected: map[string]interface{}{ + "iss": s.issuerURL.String(), + "sub": "test-subject", + "aud": "test-audience", + "exp": s.now().Add(time.Hour).Unix(), + "iat": s.now().Unix(), + "name": "Test User", + "email": "test@example.com", + }, + }, + { + name: "with groups claim", + claims: map[string]interface{}{ + "iss": s.issuerURL.String(), + "sub": "test-subject", + "aud": "test-audience", + "exp": s.now().Add(time.Hour).Unix(), + "iat": s.now().Unix(), + "groups": []string{"admin", "user"}, + }, + expected: map[string]interface{}{ + "iss": s.issuerURL.String(), + "sub": "test-subject", + "aud": "test-audience", + "exp": s.now().Add(time.Hour).Unix(), + "iat": s.now().Unix(), + "groups": []string{"admin", "user"}, + }, + }, + { + name: "near expiration but valid", + claims: map[string]interface{}{ + "iss": s.issuerURL.String(), + "sub": "test-subject", + "aud": "test-audience", + "exp": s.now().Add(time.Minute).Unix(), // Still valid + "iat": s.now().Unix(), + }, + expected: map[string]interface{}{ + "iss": s.issuerURL.String(), + "sub": "test-subject", + "aud": "test-audience", + "exp": s.now().Add(time.Minute).Unix(), + "iat": s.now().Unix(), + }, + }, + } + + for _, tc := range validTests { + t.Run(tc.name, func(t *testing.T) { + // Sign the token + signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: priv.Key}, (&jose.SignerOptions{ExtraHeaders: map[jose.HeaderKey]interface{}{"kid": priv.KeyID}})) + require.NoError(t, err) + + claimsJSON, err := json.Marshal(tc.claims) + require.NoError(t, err) + + jws, err := signer.Sign(claimsJSON) + require.NoError(t, err) + + token, err := jws.CompactSerialize() + require.NoError(t, err) + + rr := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, httpServer.URL+"/userinfo", nil) + req.Header.Set("Authorization", "Bearer "+token) + + s.handleUserInfo(rr, req) + + require.Equal(t, http.StatusOK, rr.Code, rr.Body.String()) + require.Equal(t, "application/json", rr.Result().Header.Get("content-type")) + + // Check response body matches expected claims + var respClaims json.RawMessage + err = json.NewDecoder(rr.Body).Decode(&respClaims) + require.NoError(t, err) + + expectedClaimsJSON, err := json.Marshal(tc.expected) + require.NoError(t, err) + require.JSONEq(t, string(expectedClaimsJSON), string(respClaims)) + }) + } + + invalidTokenTests := []struct { + name string + claims map[string]interface{} + useWrongKey bool + invalidPayload bool + expectedCode int + }{ + { + name: "expired token", + claims: map[string]interface{}{ + "iss": s.issuerURL.String(), + "sub": "test-subject", + "aud": "test-audience", + "exp": s.now().Add(-time.Hour).Unix(), + "iat": s.now().Add(-2 * time.Hour).Unix(), + }, + expectedCode: http.StatusForbidden, + }, + { + name: "wrong issuer", + claims: map[string]interface{}{ + "iss": "http://wrong-issuer.example.com", + "sub": "test-subject", + "aud": "test-audience", + "exp": s.now().Add(time.Hour).Unix(), + "iat": s.now().Unix(), + }, + expectedCode: http.StatusForbidden, + }, + { + name: "invalid signature", + claims: map[string]interface{}{ + "iss": s.issuerURL.String(), + "sub": "test-subject", + "aud": "test-audience", + "exp": s.now().Add(time.Hour).Unix(), + "iat": s.now().Unix(), + }, + useWrongKey: true, + expectedCode: http.StatusForbidden, + }, + { + name: "malformed token payload", + invalidPayload: true, + expectedCode: http.StatusForbidden, + }, + } + + for _, tc := range invalidTokenTests { + t.Run(tc.name, func(t *testing.T) { + var payload []byte + var err error + if tc.invalidPayload { + payload = []byte("not json") + } else { + payload, err = json.Marshal(tc.claims) + require.NoError(t, err) + } + + key := priv + if tc.useWrongKey { + key = priv2 + } + + signer, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.RS256, Key: key.Key}, (&jose.SignerOptions{ExtraHeaders: map[jose.HeaderKey]interface{}{"kid": key.KeyID}})) + require.NoError(t, err) + + jws, err := signer.Sign(payload) + require.NoError(t, err) + + token, err := jws.CompactSerialize() + require.NoError(t, err) + + rr := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, httpServer.URL+"/userinfo", nil) + req.Header.Set("Authorization", "Bearer "+token) + + s.handleUserInfo(rr, req) + + require.Equal(t, tc.expectedCode, rr.Code, rr.Body.String()) + require.Equal(t, "application/json", rr.Result().Header.Get("content-type")) + }) + } +} diff --git a/storage/ent/db/authcode.go b/storage/ent/db/authcode.go index 841d0b8b3f..06ad7c8cdf 100644 --- a/storage/ent/db/authcode.go +++ b/storage/ent/db/authcode.go @@ -73,7 +73,7 @@ func (*AuthCode) scanValues(columns []string) ([]any, error) { // assignValues assigns the values that were returned from sql.Rows (after scanning) // to the AuthCode fields. -func (ac *AuthCode) assignValues(columns []string, values []any) error { +func (_m *AuthCode) 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) } @@ -83,19 +83,19 @@ func (ac *AuthCode) assignValues(columns []string, values []any) error { if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field id", values[i]) } else if value.Valid { - ac.ID = value.String + _m.ID = value.String } case authcode.FieldClientID: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field client_id", values[i]) } else if value.Valid { - ac.ClientID = value.String + _m.ClientID = value.String } case authcode.FieldScopes: if value, ok := values[i].(*[]byte); !ok { return fmt.Errorf("unexpected type %T for field scopes", values[i]) } else if value != nil && len(*value) > 0 { - if err := json.Unmarshal(*value, &ac.Scopes); err != nil { + if err := json.Unmarshal(*value, &_m.Scopes); err != nil { return fmt.Errorf("unmarshal field scopes: %w", err) } } @@ -103,43 +103,43 @@ func (ac *AuthCode) assignValues(columns []string, values []any) error { if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field nonce", values[i]) } else if value.Valid { - ac.Nonce = value.String + _m.Nonce = value.String } case authcode.FieldRedirectURI: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field redirect_uri", values[i]) } else if value.Valid { - ac.RedirectURI = value.String + _m.RedirectURI = value.String } case authcode.FieldClaimsUserID: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field claims_user_id", values[i]) } else if value.Valid { - ac.ClaimsUserID = value.String + _m.ClaimsUserID = value.String } case authcode.FieldClaimsUsername: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field claims_username", values[i]) } else if value.Valid { - ac.ClaimsUsername = value.String + _m.ClaimsUsername = value.String } case authcode.FieldClaimsEmail: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field claims_email", values[i]) } else if value.Valid { - ac.ClaimsEmail = value.String + _m.ClaimsEmail = value.String } case authcode.FieldClaimsEmailVerified: if value, ok := values[i].(*sql.NullBool); !ok { return fmt.Errorf("unexpected type %T for field claims_email_verified", values[i]) } else if value.Valid { - ac.ClaimsEmailVerified = value.Bool + _m.ClaimsEmailVerified = value.Bool } case authcode.FieldClaimsGroups: if value, ok := values[i].(*[]byte); !ok { return fmt.Errorf("unexpected type %T for field claims_groups", values[i]) } else if value != nil && len(*value) > 0 { - if err := json.Unmarshal(*value, &ac.ClaimsGroups); err != nil { + if err := json.Unmarshal(*value, &_m.ClaimsGroups); err != nil { return fmt.Errorf("unmarshal field claims_groups: %w", err) } } @@ -147,40 +147,40 @@ func (ac *AuthCode) assignValues(columns []string, values []any) error { if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field claims_preferred_username", values[i]) } else if value.Valid { - ac.ClaimsPreferredUsername = value.String + _m.ClaimsPreferredUsername = value.String } case authcode.FieldConnectorID: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field connector_id", values[i]) } else if value.Valid { - ac.ConnectorID = value.String + _m.ConnectorID = value.String } case authcode.FieldConnectorData: if value, ok := values[i].(*[]byte); !ok { return fmt.Errorf("unexpected type %T for field connector_data", values[i]) } else if value != nil { - ac.ConnectorData = value + _m.ConnectorData = value } case authcode.FieldExpiry: if value, ok := values[i].(*sql.NullTime); !ok { return fmt.Errorf("unexpected type %T for field expiry", values[i]) } else if value.Valid { - ac.Expiry = value.Time + _m.Expiry = value.Time } case authcode.FieldCodeChallenge: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field code_challenge", values[i]) } else if value.Valid { - ac.CodeChallenge = value.String + _m.CodeChallenge = value.String } case authcode.FieldCodeChallengeMethod: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field code_challenge_method", values[i]) } else if value.Valid { - ac.CodeChallengeMethod = value.String + _m.CodeChallengeMethod = value.String } default: - ac.selectValues.Set(columns[i], values[i]) + _m.selectValues.Set(columns[i], values[i]) } } return nil @@ -188,79 +188,79 @@ func (ac *AuthCode) assignValues(columns []string, values []any) error { // Value returns the ent.Value that was dynamically selected and assigned to the AuthCode. // This includes values selected through modifiers, order, etc. -func (ac *AuthCode) Value(name string) (ent.Value, error) { - return ac.selectValues.Get(name) +func (_m *AuthCode) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) } // Update returns a builder for updating this AuthCode. // Note that you need to call AuthCode.Unwrap() before calling this method if this AuthCode // was returned from a transaction, and the transaction was committed or rolled back. -func (ac *AuthCode) Update() *AuthCodeUpdateOne { - return NewAuthCodeClient(ac.config).UpdateOne(ac) +func (_m *AuthCode) Update() *AuthCodeUpdateOne { + return NewAuthCodeClient(_m.config).UpdateOne(_m) } // Unwrap unwraps the AuthCode 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 (ac *AuthCode) Unwrap() *AuthCode { - _tx, ok := ac.config.driver.(*txDriver) +func (_m *AuthCode) Unwrap() *AuthCode { + _tx, ok := _m.config.driver.(*txDriver) if !ok { panic("db: AuthCode is not a transactional entity") } - ac.config.driver = _tx.drv - return ac + _m.config.driver = _tx.drv + return _m } // String implements the fmt.Stringer. -func (ac *AuthCode) String() string { +func (_m *AuthCode) String() string { var builder strings.Builder builder.WriteString("AuthCode(") - builder.WriteString(fmt.Sprintf("id=%v, ", ac.ID)) + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) builder.WriteString("client_id=") - builder.WriteString(ac.ClientID) + builder.WriteString(_m.ClientID) builder.WriteString(", ") builder.WriteString("scopes=") - builder.WriteString(fmt.Sprintf("%v", ac.Scopes)) + builder.WriteString(fmt.Sprintf("%v", _m.Scopes)) builder.WriteString(", ") builder.WriteString("nonce=") - builder.WriteString(ac.Nonce) + builder.WriteString(_m.Nonce) builder.WriteString(", ") builder.WriteString("redirect_uri=") - builder.WriteString(ac.RedirectURI) + builder.WriteString(_m.RedirectURI) builder.WriteString(", ") builder.WriteString("claims_user_id=") - builder.WriteString(ac.ClaimsUserID) + builder.WriteString(_m.ClaimsUserID) builder.WriteString(", ") builder.WriteString("claims_username=") - builder.WriteString(ac.ClaimsUsername) + builder.WriteString(_m.ClaimsUsername) builder.WriteString(", ") builder.WriteString("claims_email=") - builder.WriteString(ac.ClaimsEmail) + builder.WriteString(_m.ClaimsEmail) builder.WriteString(", ") builder.WriteString("claims_email_verified=") - builder.WriteString(fmt.Sprintf("%v", ac.ClaimsEmailVerified)) + builder.WriteString(fmt.Sprintf("%v", _m.ClaimsEmailVerified)) builder.WriteString(", ") builder.WriteString("claims_groups=") - builder.WriteString(fmt.Sprintf("%v", ac.ClaimsGroups)) + builder.WriteString(fmt.Sprintf("%v", _m.ClaimsGroups)) builder.WriteString(", ") builder.WriteString("claims_preferred_username=") - builder.WriteString(ac.ClaimsPreferredUsername) + builder.WriteString(_m.ClaimsPreferredUsername) builder.WriteString(", ") builder.WriteString("connector_id=") - builder.WriteString(ac.ConnectorID) + builder.WriteString(_m.ConnectorID) builder.WriteString(", ") - if v := ac.ConnectorData; v != nil { + if v := _m.ConnectorData; v != nil { builder.WriteString("connector_data=") builder.WriteString(fmt.Sprintf("%v", *v)) } builder.WriteString(", ") builder.WriteString("expiry=") - builder.WriteString(ac.Expiry.Format(time.ANSIC)) + builder.WriteString(_m.Expiry.Format(time.ANSIC)) builder.WriteString(", ") builder.WriteString("code_challenge=") - builder.WriteString(ac.CodeChallenge) + builder.WriteString(_m.CodeChallenge) builder.WriteString(", ") builder.WriteString("code_challenge_method=") - builder.WriteString(ac.CodeChallengeMethod) + builder.WriteString(_m.CodeChallengeMethod) builder.WriteByte(')') return builder.String() } diff --git a/storage/ent/db/authcode_create.go b/storage/ent/db/authcode_create.go index 03b8477dee..ab4b9e4e14 100644 --- a/storage/ent/db/authcode_create.go +++ b/storage/ent/db/authcode_create.go @@ -21,139 +21,139 @@ type AuthCodeCreate struct { } // SetClientID sets the "client_id" field. -func (acc *AuthCodeCreate) SetClientID(s string) *AuthCodeCreate { - acc.mutation.SetClientID(s) - return acc +func (_c *AuthCodeCreate) SetClientID(v string) *AuthCodeCreate { + _c.mutation.SetClientID(v) + return _c } // SetScopes sets the "scopes" field. -func (acc *AuthCodeCreate) SetScopes(s []string) *AuthCodeCreate { - acc.mutation.SetScopes(s) - return acc +func (_c *AuthCodeCreate) SetScopes(v []string) *AuthCodeCreate { + _c.mutation.SetScopes(v) + return _c } // SetNonce sets the "nonce" field. -func (acc *AuthCodeCreate) SetNonce(s string) *AuthCodeCreate { - acc.mutation.SetNonce(s) - return acc +func (_c *AuthCodeCreate) SetNonce(v string) *AuthCodeCreate { + _c.mutation.SetNonce(v) + return _c } // SetRedirectURI sets the "redirect_uri" field. -func (acc *AuthCodeCreate) SetRedirectURI(s string) *AuthCodeCreate { - acc.mutation.SetRedirectURI(s) - return acc +func (_c *AuthCodeCreate) SetRedirectURI(v string) *AuthCodeCreate { + _c.mutation.SetRedirectURI(v) + return _c } // SetClaimsUserID sets the "claims_user_id" field. -func (acc *AuthCodeCreate) SetClaimsUserID(s string) *AuthCodeCreate { - acc.mutation.SetClaimsUserID(s) - return acc +func (_c *AuthCodeCreate) SetClaimsUserID(v string) *AuthCodeCreate { + _c.mutation.SetClaimsUserID(v) + return _c } // SetClaimsUsername sets the "claims_username" field. -func (acc *AuthCodeCreate) SetClaimsUsername(s string) *AuthCodeCreate { - acc.mutation.SetClaimsUsername(s) - return acc +func (_c *AuthCodeCreate) SetClaimsUsername(v string) *AuthCodeCreate { + _c.mutation.SetClaimsUsername(v) + return _c } // SetClaimsEmail sets the "claims_email" field. -func (acc *AuthCodeCreate) SetClaimsEmail(s string) *AuthCodeCreate { - acc.mutation.SetClaimsEmail(s) - return acc +func (_c *AuthCodeCreate) SetClaimsEmail(v string) *AuthCodeCreate { + _c.mutation.SetClaimsEmail(v) + return _c } // SetClaimsEmailVerified sets the "claims_email_verified" field. -func (acc *AuthCodeCreate) SetClaimsEmailVerified(b bool) *AuthCodeCreate { - acc.mutation.SetClaimsEmailVerified(b) - return acc +func (_c *AuthCodeCreate) SetClaimsEmailVerified(v bool) *AuthCodeCreate { + _c.mutation.SetClaimsEmailVerified(v) + return _c } // SetClaimsGroups sets the "claims_groups" field. -func (acc *AuthCodeCreate) SetClaimsGroups(s []string) *AuthCodeCreate { - acc.mutation.SetClaimsGroups(s) - return acc +func (_c *AuthCodeCreate) SetClaimsGroups(v []string) *AuthCodeCreate { + _c.mutation.SetClaimsGroups(v) + return _c } // SetClaimsPreferredUsername sets the "claims_preferred_username" field. -func (acc *AuthCodeCreate) SetClaimsPreferredUsername(s string) *AuthCodeCreate { - acc.mutation.SetClaimsPreferredUsername(s) - return acc +func (_c *AuthCodeCreate) SetClaimsPreferredUsername(v string) *AuthCodeCreate { + _c.mutation.SetClaimsPreferredUsername(v) + return _c } // SetNillableClaimsPreferredUsername sets the "claims_preferred_username" field if the given value is not nil. -func (acc *AuthCodeCreate) SetNillableClaimsPreferredUsername(s *string) *AuthCodeCreate { - if s != nil { - acc.SetClaimsPreferredUsername(*s) +func (_c *AuthCodeCreate) SetNillableClaimsPreferredUsername(v *string) *AuthCodeCreate { + if v != nil { + _c.SetClaimsPreferredUsername(*v) } - return acc + return _c } // SetConnectorID sets the "connector_id" field. -func (acc *AuthCodeCreate) SetConnectorID(s string) *AuthCodeCreate { - acc.mutation.SetConnectorID(s) - return acc +func (_c *AuthCodeCreate) SetConnectorID(v string) *AuthCodeCreate { + _c.mutation.SetConnectorID(v) + return _c } // SetConnectorData sets the "connector_data" field. -func (acc *AuthCodeCreate) SetConnectorData(b []byte) *AuthCodeCreate { - acc.mutation.SetConnectorData(b) - return acc +func (_c *AuthCodeCreate) SetConnectorData(v []byte) *AuthCodeCreate { + _c.mutation.SetConnectorData(v) + return _c } // SetExpiry sets the "expiry" field. -func (acc *AuthCodeCreate) SetExpiry(t time.Time) *AuthCodeCreate { - acc.mutation.SetExpiry(t) - return acc +func (_c *AuthCodeCreate) SetExpiry(v time.Time) *AuthCodeCreate { + _c.mutation.SetExpiry(v) + return _c } // SetCodeChallenge sets the "code_challenge" field. -func (acc *AuthCodeCreate) SetCodeChallenge(s string) *AuthCodeCreate { - acc.mutation.SetCodeChallenge(s) - return acc +func (_c *AuthCodeCreate) SetCodeChallenge(v string) *AuthCodeCreate { + _c.mutation.SetCodeChallenge(v) + return _c } // SetNillableCodeChallenge sets the "code_challenge" field if the given value is not nil. -func (acc *AuthCodeCreate) SetNillableCodeChallenge(s *string) *AuthCodeCreate { - if s != nil { - acc.SetCodeChallenge(*s) +func (_c *AuthCodeCreate) SetNillableCodeChallenge(v *string) *AuthCodeCreate { + if v != nil { + _c.SetCodeChallenge(*v) } - return acc + return _c } // SetCodeChallengeMethod sets the "code_challenge_method" field. -func (acc *AuthCodeCreate) SetCodeChallengeMethod(s string) *AuthCodeCreate { - acc.mutation.SetCodeChallengeMethod(s) - return acc +func (_c *AuthCodeCreate) SetCodeChallengeMethod(v string) *AuthCodeCreate { + _c.mutation.SetCodeChallengeMethod(v) + return _c } // SetNillableCodeChallengeMethod sets the "code_challenge_method" field if the given value is not nil. -func (acc *AuthCodeCreate) SetNillableCodeChallengeMethod(s *string) *AuthCodeCreate { - if s != nil { - acc.SetCodeChallengeMethod(*s) +func (_c *AuthCodeCreate) SetNillableCodeChallengeMethod(v *string) *AuthCodeCreate { + if v != nil { + _c.SetCodeChallengeMethod(*v) } - return acc + return _c } // SetID sets the "id" field. -func (acc *AuthCodeCreate) SetID(s string) *AuthCodeCreate { - acc.mutation.SetID(s) - return acc +func (_c *AuthCodeCreate) SetID(v string) *AuthCodeCreate { + _c.mutation.SetID(v) + return _c } // Mutation returns the AuthCodeMutation object of the builder. -func (acc *AuthCodeCreate) Mutation() *AuthCodeMutation { - return acc.mutation +func (_c *AuthCodeCreate) Mutation() *AuthCodeMutation { + return _c.mutation } // Save creates the AuthCode in the database. -func (acc *AuthCodeCreate) Save(ctx context.Context) (*AuthCode, error) { - acc.defaults() - return withHooks(ctx, acc.sqlSave, acc.mutation, acc.hooks) +func (_c *AuthCodeCreate) Save(ctx context.Context) (*AuthCode, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) } // SaveX calls Save and panics if Save returns an error. -func (acc *AuthCodeCreate) SaveX(ctx context.Context) *AuthCode { - v, err := acc.Save(ctx) +func (_c *AuthCodeCreate) SaveX(ctx context.Context) *AuthCode { + v, err := _c.Save(ctx) if err != nil { panic(err) } @@ -161,108 +161,108 @@ func (acc *AuthCodeCreate) SaveX(ctx context.Context) *AuthCode { } // Exec executes the query. -func (acc *AuthCodeCreate) Exec(ctx context.Context) error { - _, err := acc.Save(ctx) +func (_c *AuthCodeCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (acc *AuthCodeCreate) ExecX(ctx context.Context) { - if err := acc.Exec(ctx); err != nil { +func (_c *AuthCodeCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { panic(err) } } // defaults sets the default values of the builder before save. -func (acc *AuthCodeCreate) defaults() { - if _, ok := acc.mutation.ClaimsPreferredUsername(); !ok { +func (_c *AuthCodeCreate) defaults() { + if _, ok := _c.mutation.ClaimsPreferredUsername(); !ok { v := authcode.DefaultClaimsPreferredUsername - acc.mutation.SetClaimsPreferredUsername(v) + _c.mutation.SetClaimsPreferredUsername(v) } - if _, ok := acc.mutation.CodeChallenge(); !ok { + if _, ok := _c.mutation.CodeChallenge(); !ok { v := authcode.DefaultCodeChallenge - acc.mutation.SetCodeChallenge(v) + _c.mutation.SetCodeChallenge(v) } - if _, ok := acc.mutation.CodeChallengeMethod(); !ok { + if _, ok := _c.mutation.CodeChallengeMethod(); !ok { v := authcode.DefaultCodeChallengeMethod - acc.mutation.SetCodeChallengeMethod(v) + _c.mutation.SetCodeChallengeMethod(v) } } // check runs all checks and user-defined validators on the builder. -func (acc *AuthCodeCreate) check() error { - if _, ok := acc.mutation.ClientID(); !ok { +func (_c *AuthCodeCreate) check() error { + if _, ok := _c.mutation.ClientID(); !ok { return &ValidationError{Name: "client_id", err: errors.New(`db: missing required field "AuthCode.client_id"`)} } - if v, ok := acc.mutation.ClientID(); ok { + if v, ok := _c.mutation.ClientID(); ok { if err := authcode.ClientIDValidator(v); err != nil { return &ValidationError{Name: "client_id", err: fmt.Errorf(`db: validator failed for field "AuthCode.client_id": %w`, err)} } } - if _, ok := acc.mutation.Nonce(); !ok { + if _, ok := _c.mutation.Nonce(); !ok { return &ValidationError{Name: "nonce", err: errors.New(`db: missing required field "AuthCode.nonce"`)} } - if v, ok := acc.mutation.Nonce(); ok { + if v, ok := _c.mutation.Nonce(); ok { if err := authcode.NonceValidator(v); err != nil { return &ValidationError{Name: "nonce", err: fmt.Errorf(`db: validator failed for field "AuthCode.nonce": %w`, err)} } } - if _, ok := acc.mutation.RedirectURI(); !ok { + if _, ok := _c.mutation.RedirectURI(); !ok { return &ValidationError{Name: "redirect_uri", err: errors.New(`db: missing required field "AuthCode.redirect_uri"`)} } - if v, ok := acc.mutation.RedirectURI(); ok { + if v, ok := _c.mutation.RedirectURI(); ok { if err := authcode.RedirectURIValidator(v); err != nil { return &ValidationError{Name: "redirect_uri", err: fmt.Errorf(`db: validator failed for field "AuthCode.redirect_uri": %w`, err)} } } - if _, ok := acc.mutation.ClaimsUserID(); !ok { + if _, ok := _c.mutation.ClaimsUserID(); !ok { return &ValidationError{Name: "claims_user_id", err: errors.New(`db: missing required field "AuthCode.claims_user_id"`)} } - if v, ok := acc.mutation.ClaimsUserID(); ok { + if v, ok := _c.mutation.ClaimsUserID(); ok { if err := authcode.ClaimsUserIDValidator(v); err != nil { return &ValidationError{Name: "claims_user_id", err: fmt.Errorf(`db: validator failed for field "AuthCode.claims_user_id": %w`, err)} } } - if _, ok := acc.mutation.ClaimsUsername(); !ok { + if _, ok := _c.mutation.ClaimsUsername(); !ok { return &ValidationError{Name: "claims_username", err: errors.New(`db: missing required field "AuthCode.claims_username"`)} } - if v, ok := acc.mutation.ClaimsUsername(); ok { + if v, ok := _c.mutation.ClaimsUsername(); ok { if err := authcode.ClaimsUsernameValidator(v); err != nil { return &ValidationError{Name: "claims_username", err: fmt.Errorf(`db: validator failed for field "AuthCode.claims_username": %w`, err)} } } - if _, ok := acc.mutation.ClaimsEmail(); !ok { + if _, ok := _c.mutation.ClaimsEmail(); !ok { return &ValidationError{Name: "claims_email", err: errors.New(`db: missing required field "AuthCode.claims_email"`)} } - if v, ok := acc.mutation.ClaimsEmail(); ok { + if v, ok := _c.mutation.ClaimsEmail(); ok { if err := authcode.ClaimsEmailValidator(v); err != nil { return &ValidationError{Name: "claims_email", err: fmt.Errorf(`db: validator failed for field "AuthCode.claims_email": %w`, err)} } } - if _, ok := acc.mutation.ClaimsEmailVerified(); !ok { + if _, ok := _c.mutation.ClaimsEmailVerified(); !ok { return &ValidationError{Name: "claims_email_verified", err: errors.New(`db: missing required field "AuthCode.claims_email_verified"`)} } - if _, ok := acc.mutation.ClaimsPreferredUsername(); !ok { + if _, ok := _c.mutation.ClaimsPreferredUsername(); !ok { return &ValidationError{Name: "claims_preferred_username", err: errors.New(`db: missing required field "AuthCode.claims_preferred_username"`)} } - if _, ok := acc.mutation.ConnectorID(); !ok { + if _, ok := _c.mutation.ConnectorID(); !ok { return &ValidationError{Name: "connector_id", err: errors.New(`db: missing required field "AuthCode.connector_id"`)} } - if v, ok := acc.mutation.ConnectorID(); ok { + if v, ok := _c.mutation.ConnectorID(); ok { if err := authcode.ConnectorIDValidator(v); err != nil { return &ValidationError{Name: "connector_id", err: fmt.Errorf(`db: validator failed for field "AuthCode.connector_id": %w`, err)} } } - if _, ok := acc.mutation.Expiry(); !ok { + if _, ok := _c.mutation.Expiry(); !ok { return &ValidationError{Name: "expiry", err: errors.New(`db: missing required field "AuthCode.expiry"`)} } - if _, ok := acc.mutation.CodeChallenge(); !ok { + if _, ok := _c.mutation.CodeChallenge(); !ok { return &ValidationError{Name: "code_challenge", err: errors.New(`db: missing required field "AuthCode.code_challenge"`)} } - if _, ok := acc.mutation.CodeChallengeMethod(); !ok { + if _, ok := _c.mutation.CodeChallengeMethod(); !ok { return &ValidationError{Name: "code_challenge_method", err: errors.New(`db: missing required field "AuthCode.code_challenge_method"`)} } - if v, ok := acc.mutation.ID(); ok { + if v, ok := _c.mutation.ID(); ok { if err := authcode.IDValidator(v); err != nil { return &ValidationError{Name: "id", err: fmt.Errorf(`db: validator failed for field "AuthCode.id": %w`, err)} } @@ -270,12 +270,12 @@ func (acc *AuthCodeCreate) check() error { return nil } -func (acc *AuthCodeCreate) sqlSave(ctx context.Context) (*AuthCode, error) { - if err := acc.check(); err != nil { +func (_c *AuthCodeCreate) sqlSave(ctx context.Context) (*AuthCode, error) { + if err := _c.check(); err != nil { return nil, err } - _node, _spec := acc.createSpec() - if err := sqlgraph.CreateNode(ctx, acc.driver, _spec); err != nil { + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { if sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } @@ -288,77 +288,77 @@ func (acc *AuthCodeCreate) sqlSave(ctx context.Context) (*AuthCode, error) { return nil, fmt.Errorf("unexpected AuthCode.ID type: %T", _spec.ID.Value) } } - acc.mutation.id = &_node.ID - acc.mutation.done = true + _c.mutation.id = &_node.ID + _c.mutation.done = true return _node, nil } -func (acc *AuthCodeCreate) createSpec() (*AuthCode, *sqlgraph.CreateSpec) { +func (_c *AuthCodeCreate) createSpec() (*AuthCode, *sqlgraph.CreateSpec) { var ( - _node = &AuthCode{config: acc.config} + _node = &AuthCode{config: _c.config} _spec = sqlgraph.NewCreateSpec(authcode.Table, sqlgraph.NewFieldSpec(authcode.FieldID, field.TypeString)) ) - if id, ok := acc.mutation.ID(); ok { + if id, ok := _c.mutation.ID(); ok { _node.ID = id _spec.ID.Value = id } - if value, ok := acc.mutation.ClientID(); ok { + if value, ok := _c.mutation.ClientID(); ok { _spec.SetField(authcode.FieldClientID, field.TypeString, value) _node.ClientID = value } - if value, ok := acc.mutation.Scopes(); ok { + if value, ok := _c.mutation.Scopes(); ok { _spec.SetField(authcode.FieldScopes, field.TypeJSON, value) _node.Scopes = value } - if value, ok := acc.mutation.Nonce(); ok { + if value, ok := _c.mutation.Nonce(); ok { _spec.SetField(authcode.FieldNonce, field.TypeString, value) _node.Nonce = value } - if value, ok := acc.mutation.RedirectURI(); ok { + if value, ok := _c.mutation.RedirectURI(); ok { _spec.SetField(authcode.FieldRedirectURI, field.TypeString, value) _node.RedirectURI = value } - if value, ok := acc.mutation.ClaimsUserID(); ok { + if value, ok := _c.mutation.ClaimsUserID(); ok { _spec.SetField(authcode.FieldClaimsUserID, field.TypeString, value) _node.ClaimsUserID = value } - if value, ok := acc.mutation.ClaimsUsername(); ok { + if value, ok := _c.mutation.ClaimsUsername(); ok { _spec.SetField(authcode.FieldClaimsUsername, field.TypeString, value) _node.ClaimsUsername = value } - if value, ok := acc.mutation.ClaimsEmail(); ok { + if value, ok := _c.mutation.ClaimsEmail(); ok { _spec.SetField(authcode.FieldClaimsEmail, field.TypeString, value) _node.ClaimsEmail = value } - if value, ok := acc.mutation.ClaimsEmailVerified(); ok { + if value, ok := _c.mutation.ClaimsEmailVerified(); ok { _spec.SetField(authcode.FieldClaimsEmailVerified, field.TypeBool, value) _node.ClaimsEmailVerified = value } - if value, ok := acc.mutation.ClaimsGroups(); ok { + if value, ok := _c.mutation.ClaimsGroups(); ok { _spec.SetField(authcode.FieldClaimsGroups, field.TypeJSON, value) _node.ClaimsGroups = value } - if value, ok := acc.mutation.ClaimsPreferredUsername(); ok { + if value, ok := _c.mutation.ClaimsPreferredUsername(); ok { _spec.SetField(authcode.FieldClaimsPreferredUsername, field.TypeString, value) _node.ClaimsPreferredUsername = value } - if value, ok := acc.mutation.ConnectorID(); ok { + if value, ok := _c.mutation.ConnectorID(); ok { _spec.SetField(authcode.FieldConnectorID, field.TypeString, value) _node.ConnectorID = value } - if value, ok := acc.mutation.ConnectorData(); ok { + if value, ok := _c.mutation.ConnectorData(); ok { _spec.SetField(authcode.FieldConnectorData, field.TypeBytes, value) _node.ConnectorData = &value } - if value, ok := acc.mutation.Expiry(); ok { + if value, ok := _c.mutation.Expiry(); ok { _spec.SetField(authcode.FieldExpiry, field.TypeTime, value) _node.Expiry = value } - if value, ok := acc.mutation.CodeChallenge(); ok { + if value, ok := _c.mutation.CodeChallenge(); ok { _spec.SetField(authcode.FieldCodeChallenge, field.TypeString, value) _node.CodeChallenge = value } - if value, ok := acc.mutation.CodeChallengeMethod(); ok { + if value, ok := _c.mutation.CodeChallengeMethod(); ok { _spec.SetField(authcode.FieldCodeChallengeMethod, field.TypeString, value) _node.CodeChallengeMethod = value } @@ -373,16 +373,16 @@ type AuthCodeCreateBulk struct { } // Save creates the AuthCode entities in the database. -func (accb *AuthCodeCreateBulk) Save(ctx context.Context) ([]*AuthCode, error) { - if accb.err != nil { - return nil, accb.err - } - specs := make([]*sqlgraph.CreateSpec, len(accb.builders)) - nodes := make([]*AuthCode, len(accb.builders)) - mutators := make([]Mutator, len(accb.builders)) - for i := range accb.builders { +func (_c *AuthCodeCreateBulk) Save(ctx context.Context) ([]*AuthCode, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*AuthCode, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { func(i int, root context.Context) { - builder := accb.builders[i] + builder := _c.builders[i] builder.defaults() var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { mutation, ok := m.(*AuthCodeMutation) @@ -396,11 +396,11 @@ func (accb *AuthCodeCreateBulk) Save(ctx context.Context) ([]*AuthCode, error) { var err error nodes[i], specs[i] = builder.createSpec() if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, accb.builders[i+1].mutation) + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, accb.driver, spec); err != nil { + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { if sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } @@ -420,7 +420,7 @@ func (accb *AuthCodeCreateBulk) Save(ctx context.Context) ([]*AuthCode, error) { }(i, ctx) } if len(mutators) > 0 { - if _, err := mutators[0].Mutate(ctx, accb.builders[0].mutation); err != nil { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { return nil, err } } @@ -428,8 +428,8 @@ func (accb *AuthCodeCreateBulk) Save(ctx context.Context) ([]*AuthCode, error) { } // SaveX is like Save, but panics if an error occurs. -func (accb *AuthCodeCreateBulk) SaveX(ctx context.Context) []*AuthCode { - v, err := accb.Save(ctx) +func (_c *AuthCodeCreateBulk) SaveX(ctx context.Context) []*AuthCode { + v, err := _c.Save(ctx) if err != nil { panic(err) } @@ -437,14 +437,14 @@ func (accb *AuthCodeCreateBulk) SaveX(ctx context.Context) []*AuthCode { } // Exec executes the query. -func (accb *AuthCodeCreateBulk) Exec(ctx context.Context) error { - _, err := accb.Save(ctx) +func (_c *AuthCodeCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (accb *AuthCodeCreateBulk) ExecX(ctx context.Context) { - if err := accb.Exec(ctx); err != nil { +func (_c *AuthCodeCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { panic(err) } } diff --git a/storage/ent/db/authcode_delete.go b/storage/ent/db/authcode_delete.go index 1f758fccad..8ef0a122fb 100644 --- a/storage/ent/db/authcode_delete.go +++ b/storage/ent/db/authcode_delete.go @@ -20,56 +20,56 @@ type AuthCodeDelete struct { } // Where appends a list predicates to the AuthCodeDelete builder. -func (acd *AuthCodeDelete) Where(ps ...predicate.AuthCode) *AuthCodeDelete { - acd.mutation.Where(ps...) - return acd +func (_d *AuthCodeDelete) Where(ps ...predicate.AuthCode) *AuthCodeDelete { + _d.mutation.Where(ps...) + return _d } // Exec executes the deletion query and returns how many vertices were deleted. -func (acd *AuthCodeDelete) Exec(ctx context.Context) (int, error) { - return withHooks(ctx, acd.sqlExec, acd.mutation, acd.hooks) +func (_d *AuthCodeDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) } // ExecX is like Exec, but panics if an error occurs. -func (acd *AuthCodeDelete) ExecX(ctx context.Context) int { - n, err := acd.Exec(ctx) +func (_d *AuthCodeDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) if err != nil { panic(err) } return n } -func (acd *AuthCodeDelete) sqlExec(ctx context.Context) (int, error) { +func (_d *AuthCodeDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(authcode.Table, sqlgraph.NewFieldSpec(authcode.FieldID, field.TypeString)) - if ps := acd.mutation.predicates; len(ps) > 0 { + if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - affected, err := sqlgraph.DeleteNodes(ctx, acd.driver, _spec) + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) if err != nil && sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } - acd.mutation.done = true + _d.mutation.done = true return affected, err } // AuthCodeDeleteOne is the builder for deleting a single AuthCode entity. type AuthCodeDeleteOne struct { - acd *AuthCodeDelete + _d *AuthCodeDelete } // Where appends a list predicates to the AuthCodeDelete builder. -func (acdo *AuthCodeDeleteOne) Where(ps ...predicate.AuthCode) *AuthCodeDeleteOne { - acdo.acd.mutation.Where(ps...) - return acdo +func (_d *AuthCodeDeleteOne) Where(ps ...predicate.AuthCode) *AuthCodeDeleteOne { + _d._d.mutation.Where(ps...) + return _d } // Exec executes the deletion query. -func (acdo *AuthCodeDeleteOne) Exec(ctx context.Context) error { - n, err := acdo.acd.Exec(ctx) +func (_d *AuthCodeDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) switch { case err != nil: return err @@ -81,8 +81,8 @@ func (acdo *AuthCodeDeleteOne) Exec(ctx context.Context) error { } // ExecX is like Exec, but panics if an error occurs. -func (acdo *AuthCodeDeleteOne) ExecX(ctx context.Context) { - if err := acdo.Exec(ctx); err != nil { +func (_d *AuthCodeDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { panic(err) } } diff --git a/storage/ent/db/authcode_query.go b/storage/ent/db/authcode_query.go index e7494ea5e1..b7c3ae251c 100644 --- a/storage/ent/db/authcode_query.go +++ b/storage/ent/db/authcode_query.go @@ -28,40 +28,40 @@ type AuthCodeQuery struct { } // Where adds a new predicate for the AuthCodeQuery builder. -func (acq *AuthCodeQuery) Where(ps ...predicate.AuthCode) *AuthCodeQuery { - acq.predicates = append(acq.predicates, ps...) - return acq +func (_q *AuthCodeQuery) Where(ps ...predicate.AuthCode) *AuthCodeQuery { + _q.predicates = append(_q.predicates, ps...) + return _q } // Limit the number of records to be returned by this query. -func (acq *AuthCodeQuery) Limit(limit int) *AuthCodeQuery { - acq.ctx.Limit = &limit - return acq +func (_q *AuthCodeQuery) Limit(limit int) *AuthCodeQuery { + _q.ctx.Limit = &limit + return _q } // Offset to start from. -func (acq *AuthCodeQuery) Offset(offset int) *AuthCodeQuery { - acq.ctx.Offset = &offset - return acq +func (_q *AuthCodeQuery) Offset(offset int) *AuthCodeQuery { + _q.ctx.Offset = &offset + return _q } // Unique configures the query builder to filter duplicate records on query. // By default, unique is set to true, and can be disabled using this method. -func (acq *AuthCodeQuery) Unique(unique bool) *AuthCodeQuery { - acq.ctx.Unique = &unique - return acq +func (_q *AuthCodeQuery) Unique(unique bool) *AuthCodeQuery { + _q.ctx.Unique = &unique + return _q } // Order specifies how the records should be ordered. -func (acq *AuthCodeQuery) Order(o ...authcode.OrderOption) *AuthCodeQuery { - acq.order = append(acq.order, o...) - return acq +func (_q *AuthCodeQuery) Order(o ...authcode.OrderOption) *AuthCodeQuery { + _q.order = append(_q.order, o...) + return _q } // First returns the first AuthCode entity from the query. // Returns a *NotFoundError when no AuthCode was found. -func (acq *AuthCodeQuery) First(ctx context.Context) (*AuthCode, error) { - nodes, err := acq.Limit(1).All(setContextOp(ctx, acq.ctx, ent.OpQueryFirst)) +func (_q *AuthCodeQuery) First(ctx context.Context) (*AuthCode, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) if err != nil { return nil, err } @@ -72,8 +72,8 @@ func (acq *AuthCodeQuery) First(ctx context.Context) (*AuthCode, error) { } // FirstX is like First, but panics if an error occurs. -func (acq *AuthCodeQuery) FirstX(ctx context.Context) *AuthCode { - node, err := acq.First(ctx) +func (_q *AuthCodeQuery) FirstX(ctx context.Context) *AuthCode { + node, err := _q.First(ctx) if err != nil && !IsNotFound(err) { panic(err) } @@ -82,9 +82,9 @@ func (acq *AuthCodeQuery) FirstX(ctx context.Context) *AuthCode { // FirstID returns the first AuthCode ID from the query. // Returns a *NotFoundError when no AuthCode ID was found. -func (acq *AuthCodeQuery) FirstID(ctx context.Context) (id string, err error) { +func (_q *AuthCodeQuery) FirstID(ctx context.Context) (id string, err error) { var ids []string - if ids, err = acq.Limit(1).IDs(setContextOp(ctx, acq.ctx, ent.OpQueryFirstID)); err != nil { + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { return } if len(ids) == 0 { @@ -95,8 +95,8 @@ func (acq *AuthCodeQuery) FirstID(ctx context.Context) (id string, err error) { } // FirstIDX is like FirstID, but panics if an error occurs. -func (acq *AuthCodeQuery) FirstIDX(ctx context.Context) string { - id, err := acq.FirstID(ctx) +func (_q *AuthCodeQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) if err != nil && !IsNotFound(err) { panic(err) } @@ -106,8 +106,8 @@ func (acq *AuthCodeQuery) FirstIDX(ctx context.Context) string { // Only returns a single AuthCode entity found by the query, ensuring it only returns one. // Returns a *NotSingularError when more than one AuthCode entity is found. // Returns a *NotFoundError when no AuthCode entities are found. -func (acq *AuthCodeQuery) Only(ctx context.Context) (*AuthCode, error) { - nodes, err := acq.Limit(2).All(setContextOp(ctx, acq.ctx, ent.OpQueryOnly)) +func (_q *AuthCodeQuery) Only(ctx context.Context) (*AuthCode, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) if err != nil { return nil, err } @@ -122,8 +122,8 @@ func (acq *AuthCodeQuery) Only(ctx context.Context) (*AuthCode, error) { } // OnlyX is like Only, but panics if an error occurs. -func (acq *AuthCodeQuery) OnlyX(ctx context.Context) *AuthCode { - node, err := acq.Only(ctx) +func (_q *AuthCodeQuery) OnlyX(ctx context.Context) *AuthCode { + node, err := _q.Only(ctx) if err != nil { panic(err) } @@ -133,9 +133,9 @@ func (acq *AuthCodeQuery) OnlyX(ctx context.Context) *AuthCode { // OnlyID is like Only, but returns the only AuthCode ID in the query. // Returns a *NotSingularError when more than one AuthCode ID is found. // Returns a *NotFoundError when no entities are found. -func (acq *AuthCodeQuery) OnlyID(ctx context.Context) (id string, err error) { +func (_q *AuthCodeQuery) OnlyID(ctx context.Context) (id string, err error) { var ids []string - if ids, err = acq.Limit(2).IDs(setContextOp(ctx, acq.ctx, ent.OpQueryOnlyID)); err != nil { + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { return } switch len(ids) { @@ -150,8 +150,8 @@ func (acq *AuthCodeQuery) OnlyID(ctx context.Context) (id string, err error) { } // OnlyIDX is like OnlyID, but panics if an error occurs. -func (acq *AuthCodeQuery) OnlyIDX(ctx context.Context) string { - id, err := acq.OnlyID(ctx) +func (_q *AuthCodeQuery) OnlyIDX(ctx context.Context) string { + id, err := _q.OnlyID(ctx) if err != nil { panic(err) } @@ -159,18 +159,18 @@ func (acq *AuthCodeQuery) OnlyIDX(ctx context.Context) string { } // All executes the query and returns a list of AuthCodes. -func (acq *AuthCodeQuery) All(ctx context.Context) ([]*AuthCode, error) { - ctx = setContextOp(ctx, acq.ctx, ent.OpQueryAll) - if err := acq.prepareQuery(ctx); err != nil { +func (_q *AuthCodeQuery) All(ctx context.Context) ([]*AuthCode, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { return nil, err } qr := querierAll[[]*AuthCode, *AuthCodeQuery]() - return withInterceptors[[]*AuthCode](ctx, acq, qr, acq.inters) + return withInterceptors[[]*AuthCode](ctx, _q, qr, _q.inters) } // AllX is like All, but panics if an error occurs. -func (acq *AuthCodeQuery) AllX(ctx context.Context) []*AuthCode { - nodes, err := acq.All(ctx) +func (_q *AuthCodeQuery) AllX(ctx context.Context) []*AuthCode { + nodes, err := _q.All(ctx) if err != nil { panic(err) } @@ -178,20 +178,20 @@ func (acq *AuthCodeQuery) AllX(ctx context.Context) []*AuthCode { } // IDs executes the query and returns a list of AuthCode IDs. -func (acq *AuthCodeQuery) IDs(ctx context.Context) (ids []string, err error) { - if acq.ctx.Unique == nil && acq.path != nil { - acq.Unique(true) +func (_q *AuthCodeQuery) IDs(ctx context.Context) (ids []string, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) } - ctx = setContextOp(ctx, acq.ctx, ent.OpQueryIDs) - if err = acq.Select(authcode.FieldID).Scan(ctx, &ids); err != nil { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(authcode.FieldID).Scan(ctx, &ids); err != nil { return nil, err } return ids, nil } // IDsX is like IDs, but panics if an error occurs. -func (acq *AuthCodeQuery) IDsX(ctx context.Context) []string { - ids, err := acq.IDs(ctx) +func (_q *AuthCodeQuery) IDsX(ctx context.Context) []string { + ids, err := _q.IDs(ctx) if err != nil { panic(err) } @@ -199,17 +199,17 @@ func (acq *AuthCodeQuery) IDsX(ctx context.Context) []string { } // Count returns the count of the given query. -func (acq *AuthCodeQuery) Count(ctx context.Context) (int, error) { - ctx = setContextOp(ctx, acq.ctx, ent.OpQueryCount) - if err := acq.prepareQuery(ctx); err != nil { +func (_q *AuthCodeQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { return 0, err } - return withInterceptors[int](ctx, acq, querierCount[*AuthCodeQuery](), acq.inters) + return withInterceptors[int](ctx, _q, querierCount[*AuthCodeQuery](), _q.inters) } // CountX is like Count, but panics if an error occurs. -func (acq *AuthCodeQuery) CountX(ctx context.Context) int { - count, err := acq.Count(ctx) +func (_q *AuthCodeQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) if err != nil { panic(err) } @@ -217,9 +217,9 @@ func (acq *AuthCodeQuery) CountX(ctx context.Context) int { } // Exist returns true if the query has elements in the graph. -func (acq *AuthCodeQuery) Exist(ctx context.Context) (bool, error) { - ctx = setContextOp(ctx, acq.ctx, ent.OpQueryExist) - switch _, err := acq.FirstID(ctx); { +func (_q *AuthCodeQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { case IsNotFound(err): return false, nil case err != nil: @@ -230,8 +230,8 @@ func (acq *AuthCodeQuery) Exist(ctx context.Context) (bool, error) { } // ExistX is like Exist, but panics if an error occurs. -func (acq *AuthCodeQuery) ExistX(ctx context.Context) bool { - exist, err := acq.Exist(ctx) +func (_q *AuthCodeQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) if err != nil { panic(err) } @@ -240,19 +240,19 @@ func (acq *AuthCodeQuery) ExistX(ctx context.Context) bool { // Clone returns a duplicate of the AuthCodeQuery builder, including all associated steps. It can be // used to prepare common query builders and use them differently after the clone is made. -func (acq *AuthCodeQuery) Clone() *AuthCodeQuery { - if acq == nil { +func (_q *AuthCodeQuery) Clone() *AuthCodeQuery { + if _q == nil { return nil } return &AuthCodeQuery{ - config: acq.config, - ctx: acq.ctx.Clone(), - order: append([]authcode.OrderOption{}, acq.order...), - inters: append([]Interceptor{}, acq.inters...), - predicates: append([]predicate.AuthCode{}, acq.predicates...), + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]authcode.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.AuthCode{}, _q.predicates...), // clone intermediate query. - sql: acq.sql.Clone(), - path: acq.path, + sql: _q.sql.Clone(), + path: _q.path, } } @@ -270,10 +270,10 @@ func (acq *AuthCodeQuery) Clone() *AuthCodeQuery { // GroupBy(authcode.FieldClientID). // Aggregate(db.Count()). // Scan(ctx, &v) -func (acq *AuthCodeQuery) GroupBy(field string, fields ...string) *AuthCodeGroupBy { - acq.ctx.Fields = append([]string{field}, fields...) - grbuild := &AuthCodeGroupBy{build: acq} - grbuild.flds = &acq.ctx.Fields +func (_q *AuthCodeQuery) GroupBy(field string, fields ...string) *AuthCodeGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &AuthCodeGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields grbuild.label = authcode.Label grbuild.scan = grbuild.Scan return grbuild @@ -291,62 +291,62 @@ func (acq *AuthCodeQuery) GroupBy(field string, fields ...string) *AuthCodeGroup // client.AuthCode.Query(). // Select(authcode.FieldClientID). // Scan(ctx, &v) -func (acq *AuthCodeQuery) Select(fields ...string) *AuthCodeSelect { - acq.ctx.Fields = append(acq.ctx.Fields, fields...) - sbuild := &AuthCodeSelect{AuthCodeQuery: acq} +func (_q *AuthCodeQuery) Select(fields ...string) *AuthCodeSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &AuthCodeSelect{AuthCodeQuery: _q} sbuild.label = authcode.Label - sbuild.flds, sbuild.scan = &acq.ctx.Fields, sbuild.Scan + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan return sbuild } // Aggregate returns a AuthCodeSelect configured with the given aggregations. -func (acq *AuthCodeQuery) Aggregate(fns ...AggregateFunc) *AuthCodeSelect { - return acq.Select().Aggregate(fns...) +func (_q *AuthCodeQuery) Aggregate(fns ...AggregateFunc) *AuthCodeSelect { + return _q.Select().Aggregate(fns...) } -func (acq *AuthCodeQuery) prepareQuery(ctx context.Context) error { - for _, inter := range acq.inters { +func (_q *AuthCodeQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { if inter == nil { return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)") } if trv, ok := inter.(Traverser); ok { - if err := trv.Traverse(ctx, acq); err != nil { + if err := trv.Traverse(ctx, _q); err != nil { return err } } } - for _, f := range acq.ctx.Fields { + for _, f := range _q.ctx.Fields { if !authcode.ValidColumn(f) { return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} } } - if acq.path != nil { - prev, err := acq.path(ctx) + if _q.path != nil { + prev, err := _q.path(ctx) if err != nil { return err } - acq.sql = prev + _q.sql = prev } return nil } -func (acq *AuthCodeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AuthCode, error) { +func (_q *AuthCodeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AuthCode, error) { var ( nodes = []*AuthCode{} - _spec = acq.querySpec() + _spec = _q.querySpec() ) _spec.ScanValues = func(columns []string) ([]any, error) { return (*AuthCode).scanValues(nil, columns) } _spec.Assign = func(columns []string, values []any) error { - node := &AuthCode{config: acq.config} + node := &AuthCode{config: _q.config} nodes = append(nodes, node) return node.assignValues(columns, values) } for i := range hooks { hooks[i](ctx, _spec) } - if err := sqlgraph.QueryNodes(ctx, acq.driver, _spec); err != nil { + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { return nil, err } if len(nodes) == 0 { @@ -355,24 +355,24 @@ func (acq *AuthCodeQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Au return nodes, nil } -func (acq *AuthCodeQuery) sqlCount(ctx context.Context) (int, error) { - _spec := acq.querySpec() - _spec.Node.Columns = acq.ctx.Fields - if len(acq.ctx.Fields) > 0 { - _spec.Unique = acq.ctx.Unique != nil && *acq.ctx.Unique +func (_q *AuthCodeQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique } - return sqlgraph.CountNodes(ctx, acq.driver, _spec) + return sqlgraph.CountNodes(ctx, _q.driver, _spec) } -func (acq *AuthCodeQuery) querySpec() *sqlgraph.QuerySpec { +func (_q *AuthCodeQuery) querySpec() *sqlgraph.QuerySpec { _spec := sqlgraph.NewQuerySpec(authcode.Table, authcode.Columns, sqlgraph.NewFieldSpec(authcode.FieldID, field.TypeString)) - _spec.From = acq.sql - if unique := acq.ctx.Unique; unique != nil { + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { _spec.Unique = *unique - } else if acq.path != nil { + } else if _q.path != nil { _spec.Unique = true } - if fields := acq.ctx.Fields; len(fields) > 0 { + if fields := _q.ctx.Fields; len(fields) > 0 { _spec.Node.Columns = make([]string, 0, len(fields)) _spec.Node.Columns = append(_spec.Node.Columns, authcode.FieldID) for i := range fields { @@ -381,20 +381,20 @@ func (acq *AuthCodeQuery) querySpec() *sqlgraph.QuerySpec { } } } - if ps := acq.predicates; len(ps) > 0 { + if ps := _q.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if limit := acq.ctx.Limit; limit != nil { + if limit := _q.ctx.Limit; limit != nil { _spec.Limit = *limit } - if offset := acq.ctx.Offset; offset != nil { + if offset := _q.ctx.Offset; offset != nil { _spec.Offset = *offset } - if ps := acq.order; len(ps) > 0 { + if ps := _q.order; len(ps) > 0 { _spec.Order = func(selector *sql.Selector) { for i := range ps { ps[i](selector) @@ -404,33 +404,33 @@ func (acq *AuthCodeQuery) querySpec() *sqlgraph.QuerySpec { return _spec } -func (acq *AuthCodeQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(acq.driver.Dialect()) +func (_q *AuthCodeQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) t1 := builder.Table(authcode.Table) - columns := acq.ctx.Fields + columns := _q.ctx.Fields if len(columns) == 0 { columns = authcode.Columns } selector := builder.Select(t1.Columns(columns...)...).From(t1) - if acq.sql != nil { - selector = acq.sql + if _q.sql != nil { + selector = _q.sql selector.Select(selector.Columns(columns...)...) } - if acq.ctx.Unique != nil && *acq.ctx.Unique { + if _q.ctx.Unique != nil && *_q.ctx.Unique { selector.Distinct() } - for _, p := range acq.predicates { + for _, p := range _q.predicates { p(selector) } - for _, p := range acq.order { + for _, p := range _q.order { p(selector) } - if offset := acq.ctx.Offset; offset != nil { + if offset := _q.ctx.Offset; offset != nil { // limit is mandatory for offset clause. We start // with default value, and override it below if needed. selector.Offset(*offset).Limit(math.MaxInt32) } - if limit := acq.ctx.Limit; limit != nil { + if limit := _q.ctx.Limit; limit != nil { selector.Limit(*limit) } return selector @@ -443,41 +443,41 @@ type AuthCodeGroupBy struct { } // Aggregate adds the given aggregation functions to the group-by query. -func (acgb *AuthCodeGroupBy) Aggregate(fns ...AggregateFunc) *AuthCodeGroupBy { - acgb.fns = append(acgb.fns, fns...) - return acgb +func (_g *AuthCodeGroupBy) Aggregate(fns ...AggregateFunc) *AuthCodeGroupBy { + _g.fns = append(_g.fns, fns...) + return _g } // Scan applies the selector query and scans the result into the given value. -func (acgb *AuthCodeGroupBy) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, acgb.build.ctx, ent.OpQueryGroupBy) - if err := acgb.build.prepareQuery(ctx); err != nil { +func (_g *AuthCodeGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { return err } - return scanWithInterceptors[*AuthCodeQuery, *AuthCodeGroupBy](ctx, acgb.build, acgb, acgb.build.inters, v) + return scanWithInterceptors[*AuthCodeQuery, *AuthCodeGroupBy](ctx, _g.build, _g, _g.build.inters, v) } -func (acgb *AuthCodeGroupBy) sqlScan(ctx context.Context, root *AuthCodeQuery, v any) error { +func (_g *AuthCodeGroupBy) sqlScan(ctx context.Context, root *AuthCodeQuery, v any) error { selector := root.sqlQuery(ctx).Select() - aggregation := make([]string, 0, len(acgb.fns)) - for _, fn := range acgb.fns { + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { aggregation = append(aggregation, fn(selector)) } if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(*acgb.flds)+len(acgb.fns)) - for _, f := range *acgb.flds { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { columns = append(columns, selector.C(f)) } columns = append(columns, aggregation...) selector.Select(columns...) } - selector.GroupBy(selector.Columns(*acgb.flds...)...) + selector.GroupBy(selector.Columns(*_g.flds...)...) if err := selector.Err(); err != nil { return err } rows := &sql.Rows{} query, args := selector.Query() - if err := acgb.build.driver.Query(ctx, query, args, rows); err != nil { + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() @@ -491,27 +491,27 @@ type AuthCodeSelect struct { } // Aggregate adds the given aggregation functions to the selector query. -func (acs *AuthCodeSelect) Aggregate(fns ...AggregateFunc) *AuthCodeSelect { - acs.fns = append(acs.fns, fns...) - return acs +func (_s *AuthCodeSelect) Aggregate(fns ...AggregateFunc) *AuthCodeSelect { + _s.fns = append(_s.fns, fns...) + return _s } // Scan applies the selector query and scans the result into the given value. -func (acs *AuthCodeSelect) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, acs.ctx, ent.OpQuerySelect) - if err := acs.prepareQuery(ctx); err != nil { +func (_s *AuthCodeSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { return err } - return scanWithInterceptors[*AuthCodeQuery, *AuthCodeSelect](ctx, acs.AuthCodeQuery, acs, acs.inters, v) + return scanWithInterceptors[*AuthCodeQuery, *AuthCodeSelect](ctx, _s.AuthCodeQuery, _s, _s.inters, v) } -func (acs *AuthCodeSelect) sqlScan(ctx context.Context, root *AuthCodeQuery, v any) error { +func (_s *AuthCodeSelect) sqlScan(ctx context.Context, root *AuthCodeQuery, v any) error { selector := root.sqlQuery(ctx) - aggregation := make([]string, 0, len(acs.fns)) - for _, fn := range acs.fns { + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { aggregation = append(aggregation, fn(selector)) } - switch n := len(*acs.selector.flds); { + switch n := len(*_s.selector.flds); { case n == 0 && len(aggregation) > 0: selector.Select(aggregation...) case n != 0 && len(aggregation) > 0: @@ -519,7 +519,7 @@ func (acs *AuthCodeSelect) sqlScan(ctx context.Context, root *AuthCodeQuery, v a } rows := &sql.Rows{} query, args := selector.Query() - if err := acs.driver.Query(ctx, query, args, rows); err != nil { + if err := _s.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() diff --git a/storage/ent/db/authcode_update.go b/storage/ent/db/authcode_update.go index 5b3fc06220..7b7e186e87 100644 --- a/storage/ent/db/authcode_update.go +++ b/storage/ent/db/authcode_update.go @@ -24,240 +24,240 @@ type AuthCodeUpdate struct { } // Where appends a list predicates to the AuthCodeUpdate builder. -func (acu *AuthCodeUpdate) Where(ps ...predicate.AuthCode) *AuthCodeUpdate { - acu.mutation.Where(ps...) - return acu +func (_u *AuthCodeUpdate) Where(ps ...predicate.AuthCode) *AuthCodeUpdate { + _u.mutation.Where(ps...) + return _u } // SetClientID sets the "client_id" field. -func (acu *AuthCodeUpdate) SetClientID(s string) *AuthCodeUpdate { - acu.mutation.SetClientID(s) - return acu +func (_u *AuthCodeUpdate) SetClientID(v string) *AuthCodeUpdate { + _u.mutation.SetClientID(v) + return _u } // SetNillableClientID sets the "client_id" field if the given value is not nil. -func (acu *AuthCodeUpdate) SetNillableClientID(s *string) *AuthCodeUpdate { - if s != nil { - acu.SetClientID(*s) +func (_u *AuthCodeUpdate) SetNillableClientID(v *string) *AuthCodeUpdate { + if v != nil { + _u.SetClientID(*v) } - return acu + return _u } // SetScopes sets the "scopes" field. -func (acu *AuthCodeUpdate) SetScopes(s []string) *AuthCodeUpdate { - acu.mutation.SetScopes(s) - return acu +func (_u *AuthCodeUpdate) SetScopes(v []string) *AuthCodeUpdate { + _u.mutation.SetScopes(v) + return _u } -// AppendScopes appends s to the "scopes" field. -func (acu *AuthCodeUpdate) AppendScopes(s []string) *AuthCodeUpdate { - acu.mutation.AppendScopes(s) - return acu +// AppendScopes appends value to the "scopes" field. +func (_u *AuthCodeUpdate) AppendScopes(v []string) *AuthCodeUpdate { + _u.mutation.AppendScopes(v) + return _u } // ClearScopes clears the value of the "scopes" field. -func (acu *AuthCodeUpdate) ClearScopes() *AuthCodeUpdate { - acu.mutation.ClearScopes() - return acu +func (_u *AuthCodeUpdate) ClearScopes() *AuthCodeUpdate { + _u.mutation.ClearScopes() + return _u } // SetNonce sets the "nonce" field. -func (acu *AuthCodeUpdate) SetNonce(s string) *AuthCodeUpdate { - acu.mutation.SetNonce(s) - return acu +func (_u *AuthCodeUpdate) SetNonce(v string) *AuthCodeUpdate { + _u.mutation.SetNonce(v) + return _u } // SetNillableNonce sets the "nonce" field if the given value is not nil. -func (acu *AuthCodeUpdate) SetNillableNonce(s *string) *AuthCodeUpdate { - if s != nil { - acu.SetNonce(*s) +func (_u *AuthCodeUpdate) SetNillableNonce(v *string) *AuthCodeUpdate { + if v != nil { + _u.SetNonce(*v) } - return acu + return _u } // SetRedirectURI sets the "redirect_uri" field. -func (acu *AuthCodeUpdate) SetRedirectURI(s string) *AuthCodeUpdate { - acu.mutation.SetRedirectURI(s) - return acu +func (_u *AuthCodeUpdate) SetRedirectURI(v string) *AuthCodeUpdate { + _u.mutation.SetRedirectURI(v) + return _u } // SetNillableRedirectURI sets the "redirect_uri" field if the given value is not nil. -func (acu *AuthCodeUpdate) SetNillableRedirectURI(s *string) *AuthCodeUpdate { - if s != nil { - acu.SetRedirectURI(*s) +func (_u *AuthCodeUpdate) SetNillableRedirectURI(v *string) *AuthCodeUpdate { + if v != nil { + _u.SetRedirectURI(*v) } - return acu + return _u } // SetClaimsUserID sets the "claims_user_id" field. -func (acu *AuthCodeUpdate) SetClaimsUserID(s string) *AuthCodeUpdate { - acu.mutation.SetClaimsUserID(s) - return acu +func (_u *AuthCodeUpdate) SetClaimsUserID(v string) *AuthCodeUpdate { + _u.mutation.SetClaimsUserID(v) + return _u } // SetNillableClaimsUserID sets the "claims_user_id" field if the given value is not nil. -func (acu *AuthCodeUpdate) SetNillableClaimsUserID(s *string) *AuthCodeUpdate { - if s != nil { - acu.SetClaimsUserID(*s) +func (_u *AuthCodeUpdate) SetNillableClaimsUserID(v *string) *AuthCodeUpdate { + if v != nil { + _u.SetClaimsUserID(*v) } - return acu + return _u } // SetClaimsUsername sets the "claims_username" field. -func (acu *AuthCodeUpdate) SetClaimsUsername(s string) *AuthCodeUpdate { - acu.mutation.SetClaimsUsername(s) - return acu +func (_u *AuthCodeUpdate) SetClaimsUsername(v string) *AuthCodeUpdate { + _u.mutation.SetClaimsUsername(v) + return _u } // SetNillableClaimsUsername sets the "claims_username" field if the given value is not nil. -func (acu *AuthCodeUpdate) SetNillableClaimsUsername(s *string) *AuthCodeUpdate { - if s != nil { - acu.SetClaimsUsername(*s) +func (_u *AuthCodeUpdate) SetNillableClaimsUsername(v *string) *AuthCodeUpdate { + if v != nil { + _u.SetClaimsUsername(*v) } - return acu + return _u } // SetClaimsEmail sets the "claims_email" field. -func (acu *AuthCodeUpdate) SetClaimsEmail(s string) *AuthCodeUpdate { - acu.mutation.SetClaimsEmail(s) - return acu +func (_u *AuthCodeUpdate) SetClaimsEmail(v string) *AuthCodeUpdate { + _u.mutation.SetClaimsEmail(v) + return _u } // SetNillableClaimsEmail sets the "claims_email" field if the given value is not nil. -func (acu *AuthCodeUpdate) SetNillableClaimsEmail(s *string) *AuthCodeUpdate { - if s != nil { - acu.SetClaimsEmail(*s) +func (_u *AuthCodeUpdate) SetNillableClaimsEmail(v *string) *AuthCodeUpdate { + if v != nil { + _u.SetClaimsEmail(*v) } - return acu + return _u } // SetClaimsEmailVerified sets the "claims_email_verified" field. -func (acu *AuthCodeUpdate) SetClaimsEmailVerified(b bool) *AuthCodeUpdate { - acu.mutation.SetClaimsEmailVerified(b) - return acu +func (_u *AuthCodeUpdate) SetClaimsEmailVerified(v bool) *AuthCodeUpdate { + _u.mutation.SetClaimsEmailVerified(v) + return _u } // SetNillableClaimsEmailVerified sets the "claims_email_verified" field if the given value is not nil. -func (acu *AuthCodeUpdate) SetNillableClaimsEmailVerified(b *bool) *AuthCodeUpdate { - if b != nil { - acu.SetClaimsEmailVerified(*b) +func (_u *AuthCodeUpdate) SetNillableClaimsEmailVerified(v *bool) *AuthCodeUpdate { + if v != nil { + _u.SetClaimsEmailVerified(*v) } - return acu + return _u } // SetClaimsGroups sets the "claims_groups" field. -func (acu *AuthCodeUpdate) SetClaimsGroups(s []string) *AuthCodeUpdate { - acu.mutation.SetClaimsGroups(s) - return acu +func (_u *AuthCodeUpdate) SetClaimsGroups(v []string) *AuthCodeUpdate { + _u.mutation.SetClaimsGroups(v) + return _u } -// AppendClaimsGroups appends s to the "claims_groups" field. -func (acu *AuthCodeUpdate) AppendClaimsGroups(s []string) *AuthCodeUpdate { - acu.mutation.AppendClaimsGroups(s) - return acu +// AppendClaimsGroups appends value to the "claims_groups" field. +func (_u *AuthCodeUpdate) AppendClaimsGroups(v []string) *AuthCodeUpdate { + _u.mutation.AppendClaimsGroups(v) + return _u } // ClearClaimsGroups clears the value of the "claims_groups" field. -func (acu *AuthCodeUpdate) ClearClaimsGroups() *AuthCodeUpdate { - acu.mutation.ClearClaimsGroups() - return acu +func (_u *AuthCodeUpdate) ClearClaimsGroups() *AuthCodeUpdate { + _u.mutation.ClearClaimsGroups() + return _u } // SetClaimsPreferredUsername sets the "claims_preferred_username" field. -func (acu *AuthCodeUpdate) SetClaimsPreferredUsername(s string) *AuthCodeUpdate { - acu.mutation.SetClaimsPreferredUsername(s) - return acu +func (_u *AuthCodeUpdate) SetClaimsPreferredUsername(v string) *AuthCodeUpdate { + _u.mutation.SetClaimsPreferredUsername(v) + return _u } // SetNillableClaimsPreferredUsername sets the "claims_preferred_username" field if the given value is not nil. -func (acu *AuthCodeUpdate) SetNillableClaimsPreferredUsername(s *string) *AuthCodeUpdate { - if s != nil { - acu.SetClaimsPreferredUsername(*s) +func (_u *AuthCodeUpdate) SetNillableClaimsPreferredUsername(v *string) *AuthCodeUpdate { + if v != nil { + _u.SetClaimsPreferredUsername(*v) } - return acu + return _u } // SetConnectorID sets the "connector_id" field. -func (acu *AuthCodeUpdate) SetConnectorID(s string) *AuthCodeUpdate { - acu.mutation.SetConnectorID(s) - return acu +func (_u *AuthCodeUpdate) SetConnectorID(v string) *AuthCodeUpdate { + _u.mutation.SetConnectorID(v) + return _u } // SetNillableConnectorID sets the "connector_id" field if the given value is not nil. -func (acu *AuthCodeUpdate) SetNillableConnectorID(s *string) *AuthCodeUpdate { - if s != nil { - acu.SetConnectorID(*s) +func (_u *AuthCodeUpdate) SetNillableConnectorID(v *string) *AuthCodeUpdate { + if v != nil { + _u.SetConnectorID(*v) } - return acu + return _u } // SetConnectorData sets the "connector_data" field. -func (acu *AuthCodeUpdate) SetConnectorData(b []byte) *AuthCodeUpdate { - acu.mutation.SetConnectorData(b) - return acu +func (_u *AuthCodeUpdate) SetConnectorData(v []byte) *AuthCodeUpdate { + _u.mutation.SetConnectorData(v) + return _u } // ClearConnectorData clears the value of the "connector_data" field. -func (acu *AuthCodeUpdate) ClearConnectorData() *AuthCodeUpdate { - acu.mutation.ClearConnectorData() - return acu +func (_u *AuthCodeUpdate) ClearConnectorData() *AuthCodeUpdate { + _u.mutation.ClearConnectorData() + return _u } // SetExpiry sets the "expiry" field. -func (acu *AuthCodeUpdate) SetExpiry(t time.Time) *AuthCodeUpdate { - acu.mutation.SetExpiry(t) - return acu +func (_u *AuthCodeUpdate) SetExpiry(v time.Time) *AuthCodeUpdate { + _u.mutation.SetExpiry(v) + return _u } // SetNillableExpiry sets the "expiry" field if the given value is not nil. -func (acu *AuthCodeUpdate) SetNillableExpiry(t *time.Time) *AuthCodeUpdate { - if t != nil { - acu.SetExpiry(*t) +func (_u *AuthCodeUpdate) SetNillableExpiry(v *time.Time) *AuthCodeUpdate { + if v != nil { + _u.SetExpiry(*v) } - return acu + return _u } // SetCodeChallenge sets the "code_challenge" field. -func (acu *AuthCodeUpdate) SetCodeChallenge(s string) *AuthCodeUpdate { - acu.mutation.SetCodeChallenge(s) - return acu +func (_u *AuthCodeUpdate) SetCodeChallenge(v string) *AuthCodeUpdate { + _u.mutation.SetCodeChallenge(v) + return _u } // SetNillableCodeChallenge sets the "code_challenge" field if the given value is not nil. -func (acu *AuthCodeUpdate) SetNillableCodeChallenge(s *string) *AuthCodeUpdate { - if s != nil { - acu.SetCodeChallenge(*s) +func (_u *AuthCodeUpdate) SetNillableCodeChallenge(v *string) *AuthCodeUpdate { + if v != nil { + _u.SetCodeChallenge(*v) } - return acu + return _u } // SetCodeChallengeMethod sets the "code_challenge_method" field. -func (acu *AuthCodeUpdate) SetCodeChallengeMethod(s string) *AuthCodeUpdate { - acu.mutation.SetCodeChallengeMethod(s) - return acu +func (_u *AuthCodeUpdate) SetCodeChallengeMethod(v string) *AuthCodeUpdate { + _u.mutation.SetCodeChallengeMethod(v) + return _u } // SetNillableCodeChallengeMethod sets the "code_challenge_method" field if the given value is not nil. -func (acu *AuthCodeUpdate) SetNillableCodeChallengeMethod(s *string) *AuthCodeUpdate { - if s != nil { - acu.SetCodeChallengeMethod(*s) +func (_u *AuthCodeUpdate) SetNillableCodeChallengeMethod(v *string) *AuthCodeUpdate { + if v != nil { + _u.SetCodeChallengeMethod(*v) } - return acu + return _u } // Mutation returns the AuthCodeMutation object of the builder. -func (acu *AuthCodeUpdate) Mutation() *AuthCodeMutation { - return acu.mutation +func (_u *AuthCodeUpdate) Mutation() *AuthCodeMutation { + return _u.mutation } // Save executes the query and returns the number of nodes affected by the update operation. -func (acu *AuthCodeUpdate) Save(ctx context.Context) (int, error) { - return withHooks(ctx, acu.sqlSave, acu.mutation, acu.hooks) +func (_u *AuthCodeUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) } // SaveX is like Save, but panics if an error occurs. -func (acu *AuthCodeUpdate) SaveX(ctx context.Context) int { - affected, err := acu.Save(ctx) +func (_u *AuthCodeUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) if err != nil { panic(err) } @@ -265,51 +265,51 @@ func (acu *AuthCodeUpdate) SaveX(ctx context.Context) int { } // Exec executes the query. -func (acu *AuthCodeUpdate) Exec(ctx context.Context) error { - _, err := acu.Save(ctx) +func (_u *AuthCodeUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (acu *AuthCodeUpdate) ExecX(ctx context.Context) { - if err := acu.Exec(ctx); err != nil { +func (_u *AuthCodeUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { panic(err) } } // check runs all checks and user-defined validators on the builder. -func (acu *AuthCodeUpdate) check() error { - if v, ok := acu.mutation.ClientID(); ok { +func (_u *AuthCodeUpdate) check() error { + if v, ok := _u.mutation.ClientID(); ok { if err := authcode.ClientIDValidator(v); err != nil { return &ValidationError{Name: "client_id", err: fmt.Errorf(`db: validator failed for field "AuthCode.client_id": %w`, err)} } } - if v, ok := acu.mutation.Nonce(); ok { + if v, ok := _u.mutation.Nonce(); ok { if err := authcode.NonceValidator(v); err != nil { return &ValidationError{Name: "nonce", err: fmt.Errorf(`db: validator failed for field "AuthCode.nonce": %w`, err)} } } - if v, ok := acu.mutation.RedirectURI(); ok { + if v, ok := _u.mutation.RedirectURI(); ok { if err := authcode.RedirectURIValidator(v); err != nil { return &ValidationError{Name: "redirect_uri", err: fmt.Errorf(`db: validator failed for field "AuthCode.redirect_uri": %w`, err)} } } - if v, ok := acu.mutation.ClaimsUserID(); ok { + if v, ok := _u.mutation.ClaimsUserID(); ok { if err := authcode.ClaimsUserIDValidator(v); err != nil { return &ValidationError{Name: "claims_user_id", err: fmt.Errorf(`db: validator failed for field "AuthCode.claims_user_id": %w`, err)} } } - if v, ok := acu.mutation.ClaimsUsername(); ok { + if v, ok := _u.mutation.ClaimsUsername(); ok { if err := authcode.ClaimsUsernameValidator(v); err != nil { return &ValidationError{Name: "claims_username", err: fmt.Errorf(`db: validator failed for field "AuthCode.claims_username": %w`, err)} } } - if v, ok := acu.mutation.ClaimsEmail(); ok { + if v, ok := _u.mutation.ClaimsEmail(); ok { if err := authcode.ClaimsEmailValidator(v); err != nil { return &ValidationError{Name: "claims_email", err: fmt.Errorf(`db: validator failed for field "AuthCode.claims_email": %w`, err)} } } - if v, ok := acu.mutation.ConnectorID(); ok { + if v, ok := _u.mutation.ConnectorID(); ok { if err := authcode.ConnectorIDValidator(v); err != nil { return &ValidationError{Name: "connector_id", err: fmt.Errorf(`db: validator failed for field "AuthCode.connector_id": %w`, err)} } @@ -317,83 +317,83 @@ func (acu *AuthCodeUpdate) check() error { return nil } -func (acu *AuthCodeUpdate) sqlSave(ctx context.Context) (n int, err error) { - if err := acu.check(); err != nil { - return n, err +func (_u *AuthCodeUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err } _spec := sqlgraph.NewUpdateSpec(authcode.Table, authcode.Columns, sqlgraph.NewFieldSpec(authcode.FieldID, field.TypeString)) - if ps := acu.mutation.predicates; len(ps) > 0 { + if ps := _u.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if value, ok := acu.mutation.ClientID(); ok { + if value, ok := _u.mutation.ClientID(); ok { _spec.SetField(authcode.FieldClientID, field.TypeString, value) } - if value, ok := acu.mutation.Scopes(); ok { + if value, ok := _u.mutation.Scopes(); ok { _spec.SetField(authcode.FieldScopes, field.TypeJSON, value) } - if value, ok := acu.mutation.AppendedScopes(); ok { + if value, ok := _u.mutation.AppendedScopes(); ok { _spec.AddModifier(func(u *sql.UpdateBuilder) { sqljson.Append(u, authcode.FieldScopes, value) }) } - if acu.mutation.ScopesCleared() { + if _u.mutation.ScopesCleared() { _spec.ClearField(authcode.FieldScopes, field.TypeJSON) } - if value, ok := acu.mutation.Nonce(); ok { + if value, ok := _u.mutation.Nonce(); ok { _spec.SetField(authcode.FieldNonce, field.TypeString, value) } - if value, ok := acu.mutation.RedirectURI(); ok { + if value, ok := _u.mutation.RedirectURI(); ok { _spec.SetField(authcode.FieldRedirectURI, field.TypeString, value) } - if value, ok := acu.mutation.ClaimsUserID(); ok { + if value, ok := _u.mutation.ClaimsUserID(); ok { _spec.SetField(authcode.FieldClaimsUserID, field.TypeString, value) } - if value, ok := acu.mutation.ClaimsUsername(); ok { + if value, ok := _u.mutation.ClaimsUsername(); ok { _spec.SetField(authcode.FieldClaimsUsername, field.TypeString, value) } - if value, ok := acu.mutation.ClaimsEmail(); ok { + if value, ok := _u.mutation.ClaimsEmail(); ok { _spec.SetField(authcode.FieldClaimsEmail, field.TypeString, value) } - if value, ok := acu.mutation.ClaimsEmailVerified(); ok { + if value, ok := _u.mutation.ClaimsEmailVerified(); ok { _spec.SetField(authcode.FieldClaimsEmailVerified, field.TypeBool, value) } - if value, ok := acu.mutation.ClaimsGroups(); ok { + if value, ok := _u.mutation.ClaimsGroups(); ok { _spec.SetField(authcode.FieldClaimsGroups, field.TypeJSON, value) } - if value, ok := acu.mutation.AppendedClaimsGroups(); ok { + if value, ok := _u.mutation.AppendedClaimsGroups(); ok { _spec.AddModifier(func(u *sql.UpdateBuilder) { sqljson.Append(u, authcode.FieldClaimsGroups, value) }) } - if acu.mutation.ClaimsGroupsCleared() { + if _u.mutation.ClaimsGroupsCleared() { _spec.ClearField(authcode.FieldClaimsGroups, field.TypeJSON) } - if value, ok := acu.mutation.ClaimsPreferredUsername(); ok { + if value, ok := _u.mutation.ClaimsPreferredUsername(); ok { _spec.SetField(authcode.FieldClaimsPreferredUsername, field.TypeString, value) } - if value, ok := acu.mutation.ConnectorID(); ok { + if value, ok := _u.mutation.ConnectorID(); ok { _spec.SetField(authcode.FieldConnectorID, field.TypeString, value) } - if value, ok := acu.mutation.ConnectorData(); ok { + if value, ok := _u.mutation.ConnectorData(); ok { _spec.SetField(authcode.FieldConnectorData, field.TypeBytes, value) } - if acu.mutation.ConnectorDataCleared() { + if _u.mutation.ConnectorDataCleared() { _spec.ClearField(authcode.FieldConnectorData, field.TypeBytes) } - if value, ok := acu.mutation.Expiry(); ok { + if value, ok := _u.mutation.Expiry(); ok { _spec.SetField(authcode.FieldExpiry, field.TypeTime, value) } - if value, ok := acu.mutation.CodeChallenge(); ok { + if value, ok := _u.mutation.CodeChallenge(); ok { _spec.SetField(authcode.FieldCodeChallenge, field.TypeString, value) } - if value, ok := acu.mutation.CodeChallengeMethod(); ok { + if value, ok := _u.mutation.CodeChallengeMethod(); ok { _spec.SetField(authcode.FieldCodeChallengeMethod, field.TypeString, value) } - if n, err = sqlgraph.UpdateNodes(ctx, acu.driver, _spec); err != nil { + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{authcode.Label} } else if sqlgraph.IsConstraintError(err) { @@ -401,8 +401,8 @@ func (acu *AuthCodeUpdate) sqlSave(ctx context.Context) (n int, err error) { } return 0, err } - acu.mutation.done = true - return n, nil + _u.mutation.done = true + return _node, nil } // AuthCodeUpdateOne is the builder for updating a single AuthCode entity. @@ -414,247 +414,247 @@ type AuthCodeUpdateOne struct { } // SetClientID sets the "client_id" field. -func (acuo *AuthCodeUpdateOne) SetClientID(s string) *AuthCodeUpdateOne { - acuo.mutation.SetClientID(s) - return acuo +func (_u *AuthCodeUpdateOne) SetClientID(v string) *AuthCodeUpdateOne { + _u.mutation.SetClientID(v) + return _u } // SetNillableClientID sets the "client_id" field if the given value is not nil. -func (acuo *AuthCodeUpdateOne) SetNillableClientID(s *string) *AuthCodeUpdateOne { - if s != nil { - acuo.SetClientID(*s) +func (_u *AuthCodeUpdateOne) SetNillableClientID(v *string) *AuthCodeUpdateOne { + if v != nil { + _u.SetClientID(*v) } - return acuo + return _u } // SetScopes sets the "scopes" field. -func (acuo *AuthCodeUpdateOne) SetScopes(s []string) *AuthCodeUpdateOne { - acuo.mutation.SetScopes(s) - return acuo +func (_u *AuthCodeUpdateOne) SetScopes(v []string) *AuthCodeUpdateOne { + _u.mutation.SetScopes(v) + return _u } -// AppendScopes appends s to the "scopes" field. -func (acuo *AuthCodeUpdateOne) AppendScopes(s []string) *AuthCodeUpdateOne { - acuo.mutation.AppendScopes(s) - return acuo +// AppendScopes appends value to the "scopes" field. +func (_u *AuthCodeUpdateOne) AppendScopes(v []string) *AuthCodeUpdateOne { + _u.mutation.AppendScopes(v) + return _u } // ClearScopes clears the value of the "scopes" field. -func (acuo *AuthCodeUpdateOne) ClearScopes() *AuthCodeUpdateOne { - acuo.mutation.ClearScopes() - return acuo +func (_u *AuthCodeUpdateOne) ClearScopes() *AuthCodeUpdateOne { + _u.mutation.ClearScopes() + return _u } // SetNonce sets the "nonce" field. -func (acuo *AuthCodeUpdateOne) SetNonce(s string) *AuthCodeUpdateOne { - acuo.mutation.SetNonce(s) - return acuo +func (_u *AuthCodeUpdateOne) SetNonce(v string) *AuthCodeUpdateOne { + _u.mutation.SetNonce(v) + return _u } // SetNillableNonce sets the "nonce" field if the given value is not nil. -func (acuo *AuthCodeUpdateOne) SetNillableNonce(s *string) *AuthCodeUpdateOne { - if s != nil { - acuo.SetNonce(*s) +func (_u *AuthCodeUpdateOne) SetNillableNonce(v *string) *AuthCodeUpdateOne { + if v != nil { + _u.SetNonce(*v) } - return acuo + return _u } // SetRedirectURI sets the "redirect_uri" field. -func (acuo *AuthCodeUpdateOne) SetRedirectURI(s string) *AuthCodeUpdateOne { - acuo.mutation.SetRedirectURI(s) - return acuo +func (_u *AuthCodeUpdateOne) SetRedirectURI(v string) *AuthCodeUpdateOne { + _u.mutation.SetRedirectURI(v) + return _u } // SetNillableRedirectURI sets the "redirect_uri" field if the given value is not nil. -func (acuo *AuthCodeUpdateOne) SetNillableRedirectURI(s *string) *AuthCodeUpdateOne { - if s != nil { - acuo.SetRedirectURI(*s) +func (_u *AuthCodeUpdateOne) SetNillableRedirectURI(v *string) *AuthCodeUpdateOne { + if v != nil { + _u.SetRedirectURI(*v) } - return acuo + return _u } // SetClaimsUserID sets the "claims_user_id" field. -func (acuo *AuthCodeUpdateOne) SetClaimsUserID(s string) *AuthCodeUpdateOne { - acuo.mutation.SetClaimsUserID(s) - return acuo +func (_u *AuthCodeUpdateOne) SetClaimsUserID(v string) *AuthCodeUpdateOne { + _u.mutation.SetClaimsUserID(v) + return _u } // SetNillableClaimsUserID sets the "claims_user_id" field if the given value is not nil. -func (acuo *AuthCodeUpdateOne) SetNillableClaimsUserID(s *string) *AuthCodeUpdateOne { - if s != nil { - acuo.SetClaimsUserID(*s) +func (_u *AuthCodeUpdateOne) SetNillableClaimsUserID(v *string) *AuthCodeUpdateOne { + if v != nil { + _u.SetClaimsUserID(*v) } - return acuo + return _u } // SetClaimsUsername sets the "claims_username" field. -func (acuo *AuthCodeUpdateOne) SetClaimsUsername(s string) *AuthCodeUpdateOne { - acuo.mutation.SetClaimsUsername(s) - return acuo +func (_u *AuthCodeUpdateOne) SetClaimsUsername(v string) *AuthCodeUpdateOne { + _u.mutation.SetClaimsUsername(v) + return _u } // SetNillableClaimsUsername sets the "claims_username" field if the given value is not nil. -func (acuo *AuthCodeUpdateOne) SetNillableClaimsUsername(s *string) *AuthCodeUpdateOne { - if s != nil { - acuo.SetClaimsUsername(*s) +func (_u *AuthCodeUpdateOne) SetNillableClaimsUsername(v *string) *AuthCodeUpdateOne { + if v != nil { + _u.SetClaimsUsername(*v) } - return acuo + return _u } // SetClaimsEmail sets the "claims_email" field. -func (acuo *AuthCodeUpdateOne) SetClaimsEmail(s string) *AuthCodeUpdateOne { - acuo.mutation.SetClaimsEmail(s) - return acuo +func (_u *AuthCodeUpdateOne) SetClaimsEmail(v string) *AuthCodeUpdateOne { + _u.mutation.SetClaimsEmail(v) + return _u } // SetNillableClaimsEmail sets the "claims_email" field if the given value is not nil. -func (acuo *AuthCodeUpdateOne) SetNillableClaimsEmail(s *string) *AuthCodeUpdateOne { - if s != nil { - acuo.SetClaimsEmail(*s) +func (_u *AuthCodeUpdateOne) SetNillableClaimsEmail(v *string) *AuthCodeUpdateOne { + if v != nil { + _u.SetClaimsEmail(*v) } - return acuo + return _u } // SetClaimsEmailVerified sets the "claims_email_verified" field. -func (acuo *AuthCodeUpdateOne) SetClaimsEmailVerified(b bool) *AuthCodeUpdateOne { - acuo.mutation.SetClaimsEmailVerified(b) - return acuo +func (_u *AuthCodeUpdateOne) SetClaimsEmailVerified(v bool) *AuthCodeUpdateOne { + _u.mutation.SetClaimsEmailVerified(v) + return _u } // SetNillableClaimsEmailVerified sets the "claims_email_verified" field if the given value is not nil. -func (acuo *AuthCodeUpdateOne) SetNillableClaimsEmailVerified(b *bool) *AuthCodeUpdateOne { - if b != nil { - acuo.SetClaimsEmailVerified(*b) +func (_u *AuthCodeUpdateOne) SetNillableClaimsEmailVerified(v *bool) *AuthCodeUpdateOne { + if v != nil { + _u.SetClaimsEmailVerified(*v) } - return acuo + return _u } // SetClaimsGroups sets the "claims_groups" field. -func (acuo *AuthCodeUpdateOne) SetClaimsGroups(s []string) *AuthCodeUpdateOne { - acuo.mutation.SetClaimsGroups(s) - return acuo +func (_u *AuthCodeUpdateOne) SetClaimsGroups(v []string) *AuthCodeUpdateOne { + _u.mutation.SetClaimsGroups(v) + return _u } -// AppendClaimsGroups appends s to the "claims_groups" field. -func (acuo *AuthCodeUpdateOne) AppendClaimsGroups(s []string) *AuthCodeUpdateOne { - acuo.mutation.AppendClaimsGroups(s) - return acuo +// AppendClaimsGroups appends value to the "claims_groups" field. +func (_u *AuthCodeUpdateOne) AppendClaimsGroups(v []string) *AuthCodeUpdateOne { + _u.mutation.AppendClaimsGroups(v) + return _u } // ClearClaimsGroups clears the value of the "claims_groups" field. -func (acuo *AuthCodeUpdateOne) ClearClaimsGroups() *AuthCodeUpdateOne { - acuo.mutation.ClearClaimsGroups() - return acuo +func (_u *AuthCodeUpdateOne) ClearClaimsGroups() *AuthCodeUpdateOne { + _u.mutation.ClearClaimsGroups() + return _u } // SetClaimsPreferredUsername sets the "claims_preferred_username" field. -func (acuo *AuthCodeUpdateOne) SetClaimsPreferredUsername(s string) *AuthCodeUpdateOne { - acuo.mutation.SetClaimsPreferredUsername(s) - return acuo +func (_u *AuthCodeUpdateOne) SetClaimsPreferredUsername(v string) *AuthCodeUpdateOne { + _u.mutation.SetClaimsPreferredUsername(v) + return _u } // SetNillableClaimsPreferredUsername sets the "claims_preferred_username" field if the given value is not nil. -func (acuo *AuthCodeUpdateOne) SetNillableClaimsPreferredUsername(s *string) *AuthCodeUpdateOne { - if s != nil { - acuo.SetClaimsPreferredUsername(*s) +func (_u *AuthCodeUpdateOne) SetNillableClaimsPreferredUsername(v *string) *AuthCodeUpdateOne { + if v != nil { + _u.SetClaimsPreferredUsername(*v) } - return acuo + return _u } // SetConnectorID sets the "connector_id" field. -func (acuo *AuthCodeUpdateOne) SetConnectorID(s string) *AuthCodeUpdateOne { - acuo.mutation.SetConnectorID(s) - return acuo +func (_u *AuthCodeUpdateOne) SetConnectorID(v string) *AuthCodeUpdateOne { + _u.mutation.SetConnectorID(v) + return _u } // SetNillableConnectorID sets the "connector_id" field if the given value is not nil. -func (acuo *AuthCodeUpdateOne) SetNillableConnectorID(s *string) *AuthCodeUpdateOne { - if s != nil { - acuo.SetConnectorID(*s) +func (_u *AuthCodeUpdateOne) SetNillableConnectorID(v *string) *AuthCodeUpdateOne { + if v != nil { + _u.SetConnectorID(*v) } - return acuo + return _u } // SetConnectorData sets the "connector_data" field. -func (acuo *AuthCodeUpdateOne) SetConnectorData(b []byte) *AuthCodeUpdateOne { - acuo.mutation.SetConnectorData(b) - return acuo +func (_u *AuthCodeUpdateOne) SetConnectorData(v []byte) *AuthCodeUpdateOne { + _u.mutation.SetConnectorData(v) + return _u } // ClearConnectorData clears the value of the "connector_data" field. -func (acuo *AuthCodeUpdateOne) ClearConnectorData() *AuthCodeUpdateOne { - acuo.mutation.ClearConnectorData() - return acuo +func (_u *AuthCodeUpdateOne) ClearConnectorData() *AuthCodeUpdateOne { + _u.mutation.ClearConnectorData() + return _u } // SetExpiry sets the "expiry" field. -func (acuo *AuthCodeUpdateOne) SetExpiry(t time.Time) *AuthCodeUpdateOne { - acuo.mutation.SetExpiry(t) - return acuo +func (_u *AuthCodeUpdateOne) SetExpiry(v time.Time) *AuthCodeUpdateOne { + _u.mutation.SetExpiry(v) + return _u } // SetNillableExpiry sets the "expiry" field if the given value is not nil. -func (acuo *AuthCodeUpdateOne) SetNillableExpiry(t *time.Time) *AuthCodeUpdateOne { - if t != nil { - acuo.SetExpiry(*t) +func (_u *AuthCodeUpdateOne) SetNillableExpiry(v *time.Time) *AuthCodeUpdateOne { + if v != nil { + _u.SetExpiry(*v) } - return acuo + return _u } // SetCodeChallenge sets the "code_challenge" field. -func (acuo *AuthCodeUpdateOne) SetCodeChallenge(s string) *AuthCodeUpdateOne { - acuo.mutation.SetCodeChallenge(s) - return acuo +func (_u *AuthCodeUpdateOne) SetCodeChallenge(v string) *AuthCodeUpdateOne { + _u.mutation.SetCodeChallenge(v) + return _u } // SetNillableCodeChallenge sets the "code_challenge" field if the given value is not nil. -func (acuo *AuthCodeUpdateOne) SetNillableCodeChallenge(s *string) *AuthCodeUpdateOne { - if s != nil { - acuo.SetCodeChallenge(*s) +func (_u *AuthCodeUpdateOne) SetNillableCodeChallenge(v *string) *AuthCodeUpdateOne { + if v != nil { + _u.SetCodeChallenge(*v) } - return acuo + return _u } // SetCodeChallengeMethod sets the "code_challenge_method" field. -func (acuo *AuthCodeUpdateOne) SetCodeChallengeMethod(s string) *AuthCodeUpdateOne { - acuo.mutation.SetCodeChallengeMethod(s) - return acuo +func (_u *AuthCodeUpdateOne) SetCodeChallengeMethod(v string) *AuthCodeUpdateOne { + _u.mutation.SetCodeChallengeMethod(v) + return _u } // SetNillableCodeChallengeMethod sets the "code_challenge_method" field if the given value is not nil. -func (acuo *AuthCodeUpdateOne) SetNillableCodeChallengeMethod(s *string) *AuthCodeUpdateOne { - if s != nil { - acuo.SetCodeChallengeMethod(*s) +func (_u *AuthCodeUpdateOne) SetNillableCodeChallengeMethod(v *string) *AuthCodeUpdateOne { + if v != nil { + _u.SetCodeChallengeMethod(*v) } - return acuo + return _u } // Mutation returns the AuthCodeMutation object of the builder. -func (acuo *AuthCodeUpdateOne) Mutation() *AuthCodeMutation { - return acuo.mutation +func (_u *AuthCodeUpdateOne) Mutation() *AuthCodeMutation { + return _u.mutation } // Where appends a list predicates to the AuthCodeUpdate builder. -func (acuo *AuthCodeUpdateOne) Where(ps ...predicate.AuthCode) *AuthCodeUpdateOne { - acuo.mutation.Where(ps...) - return acuo +func (_u *AuthCodeUpdateOne) Where(ps ...predicate.AuthCode) *AuthCodeUpdateOne { + _u.mutation.Where(ps...) + return _u } // Select allows selecting one or more fields (columns) of the returned entity. // The default is selecting all fields defined in the entity schema. -func (acuo *AuthCodeUpdateOne) Select(field string, fields ...string) *AuthCodeUpdateOne { - acuo.fields = append([]string{field}, fields...) - return acuo +func (_u *AuthCodeUpdateOne) Select(field string, fields ...string) *AuthCodeUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u } // Save executes the query and returns the updated AuthCode entity. -func (acuo *AuthCodeUpdateOne) Save(ctx context.Context) (*AuthCode, error) { - return withHooks(ctx, acuo.sqlSave, acuo.mutation, acuo.hooks) +func (_u *AuthCodeUpdateOne) Save(ctx context.Context) (*AuthCode, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) } // SaveX is like Save, but panics if an error occurs. -func (acuo *AuthCodeUpdateOne) SaveX(ctx context.Context) *AuthCode { - node, err := acuo.Save(ctx) +func (_u *AuthCodeUpdateOne) SaveX(ctx context.Context) *AuthCode { + node, err := _u.Save(ctx) if err != nil { panic(err) } @@ -662,51 +662,51 @@ func (acuo *AuthCodeUpdateOne) SaveX(ctx context.Context) *AuthCode { } // Exec executes the query on the entity. -func (acuo *AuthCodeUpdateOne) Exec(ctx context.Context) error { - _, err := acuo.Save(ctx) +func (_u *AuthCodeUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (acuo *AuthCodeUpdateOne) ExecX(ctx context.Context) { - if err := acuo.Exec(ctx); err != nil { +func (_u *AuthCodeUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { panic(err) } } // check runs all checks and user-defined validators on the builder. -func (acuo *AuthCodeUpdateOne) check() error { - if v, ok := acuo.mutation.ClientID(); ok { +func (_u *AuthCodeUpdateOne) check() error { + if v, ok := _u.mutation.ClientID(); ok { if err := authcode.ClientIDValidator(v); err != nil { return &ValidationError{Name: "client_id", err: fmt.Errorf(`db: validator failed for field "AuthCode.client_id": %w`, err)} } } - if v, ok := acuo.mutation.Nonce(); ok { + if v, ok := _u.mutation.Nonce(); ok { if err := authcode.NonceValidator(v); err != nil { return &ValidationError{Name: "nonce", err: fmt.Errorf(`db: validator failed for field "AuthCode.nonce": %w`, err)} } } - if v, ok := acuo.mutation.RedirectURI(); ok { + if v, ok := _u.mutation.RedirectURI(); ok { if err := authcode.RedirectURIValidator(v); err != nil { return &ValidationError{Name: "redirect_uri", err: fmt.Errorf(`db: validator failed for field "AuthCode.redirect_uri": %w`, err)} } } - if v, ok := acuo.mutation.ClaimsUserID(); ok { + if v, ok := _u.mutation.ClaimsUserID(); ok { if err := authcode.ClaimsUserIDValidator(v); err != nil { return &ValidationError{Name: "claims_user_id", err: fmt.Errorf(`db: validator failed for field "AuthCode.claims_user_id": %w`, err)} } } - if v, ok := acuo.mutation.ClaimsUsername(); ok { + if v, ok := _u.mutation.ClaimsUsername(); ok { if err := authcode.ClaimsUsernameValidator(v); err != nil { return &ValidationError{Name: "claims_username", err: fmt.Errorf(`db: validator failed for field "AuthCode.claims_username": %w`, err)} } } - if v, ok := acuo.mutation.ClaimsEmail(); ok { + if v, ok := _u.mutation.ClaimsEmail(); ok { if err := authcode.ClaimsEmailValidator(v); err != nil { return &ValidationError{Name: "claims_email", err: fmt.Errorf(`db: validator failed for field "AuthCode.claims_email": %w`, err)} } } - if v, ok := acuo.mutation.ConnectorID(); ok { + if v, ok := _u.mutation.ConnectorID(); ok { if err := authcode.ConnectorIDValidator(v); err != nil { return &ValidationError{Name: "connector_id", err: fmt.Errorf(`db: validator failed for field "AuthCode.connector_id": %w`, err)} } @@ -714,17 +714,17 @@ func (acuo *AuthCodeUpdateOne) check() error { return nil } -func (acuo *AuthCodeUpdateOne) sqlSave(ctx context.Context) (_node *AuthCode, err error) { - if err := acuo.check(); err != nil { +func (_u *AuthCodeUpdateOne) sqlSave(ctx context.Context) (_node *AuthCode, err error) { + if err := _u.check(); err != nil { return _node, err } _spec := sqlgraph.NewUpdateSpec(authcode.Table, authcode.Columns, sqlgraph.NewFieldSpec(authcode.FieldID, field.TypeString)) - id, ok := acuo.mutation.ID() + id, ok := _u.mutation.ID() if !ok { return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "AuthCode.id" for update`)} } _spec.Node.ID.Value = id - if fields := acuo.fields; len(fields) > 0 { + if fields := _u.fields; len(fields) > 0 { _spec.Node.Columns = make([]string, 0, len(fields)) _spec.Node.Columns = append(_spec.Node.Columns, authcode.FieldID) for _, f := range fields { @@ -736,81 +736,81 @@ func (acuo *AuthCodeUpdateOne) sqlSave(ctx context.Context) (_node *AuthCode, er } } } - if ps := acuo.mutation.predicates; len(ps) > 0 { + if ps := _u.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if value, ok := acuo.mutation.ClientID(); ok { + if value, ok := _u.mutation.ClientID(); ok { _spec.SetField(authcode.FieldClientID, field.TypeString, value) } - if value, ok := acuo.mutation.Scopes(); ok { + if value, ok := _u.mutation.Scopes(); ok { _spec.SetField(authcode.FieldScopes, field.TypeJSON, value) } - if value, ok := acuo.mutation.AppendedScopes(); ok { + if value, ok := _u.mutation.AppendedScopes(); ok { _spec.AddModifier(func(u *sql.UpdateBuilder) { sqljson.Append(u, authcode.FieldScopes, value) }) } - if acuo.mutation.ScopesCleared() { + if _u.mutation.ScopesCleared() { _spec.ClearField(authcode.FieldScopes, field.TypeJSON) } - if value, ok := acuo.mutation.Nonce(); ok { + if value, ok := _u.mutation.Nonce(); ok { _spec.SetField(authcode.FieldNonce, field.TypeString, value) } - if value, ok := acuo.mutation.RedirectURI(); ok { + if value, ok := _u.mutation.RedirectURI(); ok { _spec.SetField(authcode.FieldRedirectURI, field.TypeString, value) } - if value, ok := acuo.mutation.ClaimsUserID(); ok { + if value, ok := _u.mutation.ClaimsUserID(); ok { _spec.SetField(authcode.FieldClaimsUserID, field.TypeString, value) } - if value, ok := acuo.mutation.ClaimsUsername(); ok { + if value, ok := _u.mutation.ClaimsUsername(); ok { _spec.SetField(authcode.FieldClaimsUsername, field.TypeString, value) } - if value, ok := acuo.mutation.ClaimsEmail(); ok { + if value, ok := _u.mutation.ClaimsEmail(); ok { _spec.SetField(authcode.FieldClaimsEmail, field.TypeString, value) } - if value, ok := acuo.mutation.ClaimsEmailVerified(); ok { + if value, ok := _u.mutation.ClaimsEmailVerified(); ok { _spec.SetField(authcode.FieldClaimsEmailVerified, field.TypeBool, value) } - if value, ok := acuo.mutation.ClaimsGroups(); ok { + if value, ok := _u.mutation.ClaimsGroups(); ok { _spec.SetField(authcode.FieldClaimsGroups, field.TypeJSON, value) } - if value, ok := acuo.mutation.AppendedClaimsGroups(); ok { + if value, ok := _u.mutation.AppendedClaimsGroups(); ok { _spec.AddModifier(func(u *sql.UpdateBuilder) { sqljson.Append(u, authcode.FieldClaimsGroups, value) }) } - if acuo.mutation.ClaimsGroupsCleared() { + if _u.mutation.ClaimsGroupsCleared() { _spec.ClearField(authcode.FieldClaimsGroups, field.TypeJSON) } - if value, ok := acuo.mutation.ClaimsPreferredUsername(); ok { + if value, ok := _u.mutation.ClaimsPreferredUsername(); ok { _spec.SetField(authcode.FieldClaimsPreferredUsername, field.TypeString, value) } - if value, ok := acuo.mutation.ConnectorID(); ok { + if value, ok := _u.mutation.ConnectorID(); ok { _spec.SetField(authcode.FieldConnectorID, field.TypeString, value) } - if value, ok := acuo.mutation.ConnectorData(); ok { + if value, ok := _u.mutation.ConnectorData(); ok { _spec.SetField(authcode.FieldConnectorData, field.TypeBytes, value) } - if acuo.mutation.ConnectorDataCleared() { + if _u.mutation.ConnectorDataCleared() { _spec.ClearField(authcode.FieldConnectorData, field.TypeBytes) } - if value, ok := acuo.mutation.Expiry(); ok { + if value, ok := _u.mutation.Expiry(); ok { _spec.SetField(authcode.FieldExpiry, field.TypeTime, value) } - if value, ok := acuo.mutation.CodeChallenge(); ok { + if value, ok := _u.mutation.CodeChallenge(); ok { _spec.SetField(authcode.FieldCodeChallenge, field.TypeString, value) } - if value, ok := acuo.mutation.CodeChallengeMethod(); ok { + if value, ok := _u.mutation.CodeChallengeMethod(); ok { _spec.SetField(authcode.FieldCodeChallengeMethod, field.TypeString, value) } - _node = &AuthCode{config: acuo.config} + _node = &AuthCode{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, acuo.driver, _spec); err != nil { + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{authcode.Label} } else if sqlgraph.IsConstraintError(err) { @@ -818,6 +818,6 @@ func (acuo *AuthCodeUpdateOne) sqlSave(ctx context.Context) (_node *AuthCode, er } return nil, err } - acuo.mutation.done = true + _u.mutation.done = true return _node, nil } diff --git a/storage/ent/db/authrequest.go b/storage/ent/db/authrequest.go index b95592e58c..ac5b550ad9 100644 --- a/storage/ent/db/authrequest.go +++ b/storage/ent/db/authrequest.go @@ -83,7 +83,7 @@ func (*AuthRequest) scanValues(columns []string) ([]any, error) { // assignValues assigns the values that were returned from sql.Rows (after scanning) // to the AuthRequest fields. -func (ar *AuthRequest) assignValues(columns []string, values []any) error { +func (_m *AuthRequest) 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) } @@ -93,19 +93,19 @@ func (ar *AuthRequest) assignValues(columns []string, values []any) error { if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field id", values[i]) } else if value.Valid { - ar.ID = value.String + _m.ID = value.String } case authrequest.FieldClientID: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field client_id", values[i]) } else if value.Valid { - ar.ClientID = value.String + _m.ClientID = value.String } case authrequest.FieldScopes: if value, ok := values[i].(*[]byte); !ok { return fmt.Errorf("unexpected type %T for field scopes", values[i]) } else if value != nil && len(*value) > 0 { - if err := json.Unmarshal(*value, &ar.Scopes); err != nil { + if err := json.Unmarshal(*value, &_m.Scopes); err != nil { return fmt.Errorf("unmarshal field scopes: %w", err) } } @@ -113,7 +113,7 @@ func (ar *AuthRequest) assignValues(columns []string, values []any) error { if value, ok := values[i].(*[]byte); !ok { return fmt.Errorf("unexpected type %T for field response_types", values[i]) } else if value != nil && len(*value) > 0 { - if err := json.Unmarshal(*value, &ar.ResponseTypes); err != nil { + if err := json.Unmarshal(*value, &_m.ResponseTypes); err != nil { return fmt.Errorf("unmarshal field response_types: %w", err) } } @@ -121,61 +121,61 @@ func (ar *AuthRequest) assignValues(columns []string, values []any) error { if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field redirect_uri", values[i]) } else if value.Valid { - ar.RedirectURI = value.String + _m.RedirectURI = value.String } case authrequest.FieldNonce: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field nonce", values[i]) } else if value.Valid { - ar.Nonce = value.String + _m.Nonce = value.String } case authrequest.FieldState: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field state", values[i]) } else if value.Valid { - ar.State = value.String + _m.State = value.String } case authrequest.FieldForceApprovalPrompt: if value, ok := values[i].(*sql.NullBool); !ok { return fmt.Errorf("unexpected type %T for field force_approval_prompt", values[i]) } else if value.Valid { - ar.ForceApprovalPrompt = value.Bool + _m.ForceApprovalPrompt = value.Bool } case authrequest.FieldLoggedIn: if value, ok := values[i].(*sql.NullBool); !ok { return fmt.Errorf("unexpected type %T for field logged_in", values[i]) } else if value.Valid { - ar.LoggedIn = value.Bool + _m.LoggedIn = value.Bool } case authrequest.FieldClaimsUserID: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field claims_user_id", values[i]) } else if value.Valid { - ar.ClaimsUserID = value.String + _m.ClaimsUserID = value.String } case authrequest.FieldClaimsUsername: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field claims_username", values[i]) } else if value.Valid { - ar.ClaimsUsername = value.String + _m.ClaimsUsername = value.String } case authrequest.FieldClaimsEmail: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field claims_email", values[i]) } else if value.Valid { - ar.ClaimsEmail = value.String + _m.ClaimsEmail = value.String } case authrequest.FieldClaimsEmailVerified: if value, ok := values[i].(*sql.NullBool); !ok { return fmt.Errorf("unexpected type %T for field claims_email_verified", values[i]) } else if value.Valid { - ar.ClaimsEmailVerified = value.Bool + _m.ClaimsEmailVerified = value.Bool } case authrequest.FieldClaimsGroups: if value, ok := values[i].(*[]byte); !ok { return fmt.Errorf("unexpected type %T for field claims_groups", values[i]) } else if value != nil && len(*value) > 0 { - if err := json.Unmarshal(*value, &ar.ClaimsGroups); err != nil { + if err := json.Unmarshal(*value, &_m.ClaimsGroups); err != nil { return fmt.Errorf("unmarshal field claims_groups: %w", err) } } @@ -183,46 +183,46 @@ func (ar *AuthRequest) assignValues(columns []string, values []any) error { if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field claims_preferred_username", values[i]) } else if value.Valid { - ar.ClaimsPreferredUsername = value.String + _m.ClaimsPreferredUsername = value.String } case authrequest.FieldConnectorID: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field connector_id", values[i]) } else if value.Valid { - ar.ConnectorID = value.String + _m.ConnectorID = value.String } case authrequest.FieldConnectorData: if value, ok := values[i].(*[]byte); !ok { return fmt.Errorf("unexpected type %T for field connector_data", values[i]) } else if value != nil { - ar.ConnectorData = value + _m.ConnectorData = value } case authrequest.FieldExpiry: if value, ok := values[i].(*sql.NullTime); !ok { return fmt.Errorf("unexpected type %T for field expiry", values[i]) } else if value.Valid { - ar.Expiry = value.Time + _m.Expiry = value.Time } case authrequest.FieldCodeChallenge: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field code_challenge", values[i]) } else if value.Valid { - ar.CodeChallenge = value.String + _m.CodeChallenge = value.String } case authrequest.FieldCodeChallengeMethod: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field code_challenge_method", values[i]) } else if value.Valid { - ar.CodeChallengeMethod = value.String + _m.CodeChallengeMethod = value.String } case authrequest.FieldHmacKey: if value, ok := values[i].(*[]byte); !ok { return fmt.Errorf("unexpected type %T for field hmac_key", values[i]) } else if value != nil { - ar.HmacKey = *value + _m.HmacKey = *value } default: - ar.selectValues.Set(columns[i], values[i]) + _m.selectValues.Set(columns[i], values[i]) } } return nil @@ -230,94 +230,94 @@ func (ar *AuthRequest) assignValues(columns []string, values []any) error { // Value returns the ent.Value that was dynamically selected and assigned to the AuthRequest. // This includes values selected through modifiers, order, etc. -func (ar *AuthRequest) Value(name string) (ent.Value, error) { - return ar.selectValues.Get(name) +func (_m *AuthRequest) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) } // Update returns a builder for updating this AuthRequest. // Note that you need to call AuthRequest.Unwrap() before calling this method if this AuthRequest // was returned from a transaction, and the transaction was committed or rolled back. -func (ar *AuthRequest) Update() *AuthRequestUpdateOne { - return NewAuthRequestClient(ar.config).UpdateOne(ar) +func (_m *AuthRequest) Update() *AuthRequestUpdateOne { + return NewAuthRequestClient(_m.config).UpdateOne(_m) } // Unwrap unwraps the AuthRequest 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 (ar *AuthRequest) Unwrap() *AuthRequest { - _tx, ok := ar.config.driver.(*txDriver) +func (_m *AuthRequest) Unwrap() *AuthRequest { + _tx, ok := _m.config.driver.(*txDriver) if !ok { panic("db: AuthRequest is not a transactional entity") } - ar.config.driver = _tx.drv - return ar + _m.config.driver = _tx.drv + return _m } // String implements the fmt.Stringer. -func (ar *AuthRequest) String() string { +func (_m *AuthRequest) String() string { var builder strings.Builder builder.WriteString("AuthRequest(") - builder.WriteString(fmt.Sprintf("id=%v, ", ar.ID)) + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) builder.WriteString("client_id=") - builder.WriteString(ar.ClientID) + builder.WriteString(_m.ClientID) builder.WriteString(", ") builder.WriteString("scopes=") - builder.WriteString(fmt.Sprintf("%v", ar.Scopes)) + builder.WriteString(fmt.Sprintf("%v", _m.Scopes)) builder.WriteString(", ") builder.WriteString("response_types=") - builder.WriteString(fmt.Sprintf("%v", ar.ResponseTypes)) + builder.WriteString(fmt.Sprintf("%v", _m.ResponseTypes)) builder.WriteString(", ") builder.WriteString("redirect_uri=") - builder.WriteString(ar.RedirectURI) + builder.WriteString(_m.RedirectURI) builder.WriteString(", ") builder.WriteString("nonce=") - builder.WriteString(ar.Nonce) + builder.WriteString(_m.Nonce) builder.WriteString(", ") builder.WriteString("state=") - builder.WriteString(ar.State) + builder.WriteString(_m.State) builder.WriteString(", ") builder.WriteString("force_approval_prompt=") - builder.WriteString(fmt.Sprintf("%v", ar.ForceApprovalPrompt)) + builder.WriteString(fmt.Sprintf("%v", _m.ForceApprovalPrompt)) builder.WriteString(", ") builder.WriteString("logged_in=") - builder.WriteString(fmt.Sprintf("%v", ar.LoggedIn)) + builder.WriteString(fmt.Sprintf("%v", _m.LoggedIn)) builder.WriteString(", ") builder.WriteString("claims_user_id=") - builder.WriteString(ar.ClaimsUserID) + builder.WriteString(_m.ClaimsUserID) builder.WriteString(", ") builder.WriteString("claims_username=") - builder.WriteString(ar.ClaimsUsername) + builder.WriteString(_m.ClaimsUsername) builder.WriteString(", ") builder.WriteString("claims_email=") - builder.WriteString(ar.ClaimsEmail) + builder.WriteString(_m.ClaimsEmail) builder.WriteString(", ") builder.WriteString("claims_email_verified=") - builder.WriteString(fmt.Sprintf("%v", ar.ClaimsEmailVerified)) + builder.WriteString(fmt.Sprintf("%v", _m.ClaimsEmailVerified)) builder.WriteString(", ") builder.WriteString("claims_groups=") - builder.WriteString(fmt.Sprintf("%v", ar.ClaimsGroups)) + builder.WriteString(fmt.Sprintf("%v", _m.ClaimsGroups)) builder.WriteString(", ") builder.WriteString("claims_preferred_username=") - builder.WriteString(ar.ClaimsPreferredUsername) + builder.WriteString(_m.ClaimsPreferredUsername) builder.WriteString(", ") builder.WriteString("connector_id=") - builder.WriteString(ar.ConnectorID) + builder.WriteString(_m.ConnectorID) builder.WriteString(", ") - if v := ar.ConnectorData; v != nil { + if v := _m.ConnectorData; v != nil { builder.WriteString("connector_data=") builder.WriteString(fmt.Sprintf("%v", *v)) } builder.WriteString(", ") builder.WriteString("expiry=") - builder.WriteString(ar.Expiry.Format(time.ANSIC)) + builder.WriteString(_m.Expiry.Format(time.ANSIC)) builder.WriteString(", ") builder.WriteString("code_challenge=") - builder.WriteString(ar.CodeChallenge) + builder.WriteString(_m.CodeChallenge) builder.WriteString(", ") builder.WriteString("code_challenge_method=") - builder.WriteString(ar.CodeChallengeMethod) + builder.WriteString(_m.CodeChallengeMethod) builder.WriteString(", ") builder.WriteString("hmac_key=") - builder.WriteString(fmt.Sprintf("%v", ar.HmacKey)) + builder.WriteString(fmt.Sprintf("%v", _m.HmacKey)) builder.WriteByte(')') return builder.String() } diff --git a/storage/ent/db/authrequest_create.go b/storage/ent/db/authrequest_create.go index 3fe0c2b1f7..6224ef8eb0 100644 --- a/storage/ent/db/authrequest_create.go +++ b/storage/ent/db/authrequest_create.go @@ -21,169 +21,169 @@ type AuthRequestCreate struct { } // SetClientID sets the "client_id" field. -func (arc *AuthRequestCreate) SetClientID(s string) *AuthRequestCreate { - arc.mutation.SetClientID(s) - return arc +func (_c *AuthRequestCreate) SetClientID(v string) *AuthRequestCreate { + _c.mutation.SetClientID(v) + return _c } // SetScopes sets the "scopes" field. -func (arc *AuthRequestCreate) SetScopes(s []string) *AuthRequestCreate { - arc.mutation.SetScopes(s) - return arc +func (_c *AuthRequestCreate) SetScopes(v []string) *AuthRequestCreate { + _c.mutation.SetScopes(v) + return _c } // SetResponseTypes sets the "response_types" field. -func (arc *AuthRequestCreate) SetResponseTypes(s []string) *AuthRequestCreate { - arc.mutation.SetResponseTypes(s) - return arc +func (_c *AuthRequestCreate) SetResponseTypes(v []string) *AuthRequestCreate { + _c.mutation.SetResponseTypes(v) + return _c } // SetRedirectURI sets the "redirect_uri" field. -func (arc *AuthRequestCreate) SetRedirectURI(s string) *AuthRequestCreate { - arc.mutation.SetRedirectURI(s) - return arc +func (_c *AuthRequestCreate) SetRedirectURI(v string) *AuthRequestCreate { + _c.mutation.SetRedirectURI(v) + return _c } // SetNonce sets the "nonce" field. -func (arc *AuthRequestCreate) SetNonce(s string) *AuthRequestCreate { - arc.mutation.SetNonce(s) - return arc +func (_c *AuthRequestCreate) SetNonce(v string) *AuthRequestCreate { + _c.mutation.SetNonce(v) + return _c } // SetState sets the "state" field. -func (arc *AuthRequestCreate) SetState(s string) *AuthRequestCreate { - arc.mutation.SetState(s) - return arc +func (_c *AuthRequestCreate) SetState(v string) *AuthRequestCreate { + _c.mutation.SetState(v) + return _c } // SetForceApprovalPrompt sets the "force_approval_prompt" field. -func (arc *AuthRequestCreate) SetForceApprovalPrompt(b bool) *AuthRequestCreate { - arc.mutation.SetForceApprovalPrompt(b) - return arc +func (_c *AuthRequestCreate) SetForceApprovalPrompt(v bool) *AuthRequestCreate { + _c.mutation.SetForceApprovalPrompt(v) + return _c } // SetLoggedIn sets the "logged_in" field. -func (arc *AuthRequestCreate) SetLoggedIn(b bool) *AuthRequestCreate { - arc.mutation.SetLoggedIn(b) - return arc +func (_c *AuthRequestCreate) SetLoggedIn(v bool) *AuthRequestCreate { + _c.mutation.SetLoggedIn(v) + return _c } // SetClaimsUserID sets the "claims_user_id" field. -func (arc *AuthRequestCreate) SetClaimsUserID(s string) *AuthRequestCreate { - arc.mutation.SetClaimsUserID(s) - return arc +func (_c *AuthRequestCreate) SetClaimsUserID(v string) *AuthRequestCreate { + _c.mutation.SetClaimsUserID(v) + return _c } // SetClaimsUsername sets the "claims_username" field. -func (arc *AuthRequestCreate) SetClaimsUsername(s string) *AuthRequestCreate { - arc.mutation.SetClaimsUsername(s) - return arc +func (_c *AuthRequestCreate) SetClaimsUsername(v string) *AuthRequestCreate { + _c.mutation.SetClaimsUsername(v) + return _c } // SetClaimsEmail sets the "claims_email" field. -func (arc *AuthRequestCreate) SetClaimsEmail(s string) *AuthRequestCreate { - arc.mutation.SetClaimsEmail(s) - return arc +func (_c *AuthRequestCreate) SetClaimsEmail(v string) *AuthRequestCreate { + _c.mutation.SetClaimsEmail(v) + return _c } // SetClaimsEmailVerified sets the "claims_email_verified" field. -func (arc *AuthRequestCreate) SetClaimsEmailVerified(b bool) *AuthRequestCreate { - arc.mutation.SetClaimsEmailVerified(b) - return arc +func (_c *AuthRequestCreate) SetClaimsEmailVerified(v bool) *AuthRequestCreate { + _c.mutation.SetClaimsEmailVerified(v) + return _c } // SetClaimsGroups sets the "claims_groups" field. -func (arc *AuthRequestCreate) SetClaimsGroups(s []string) *AuthRequestCreate { - arc.mutation.SetClaimsGroups(s) - return arc +func (_c *AuthRequestCreate) SetClaimsGroups(v []string) *AuthRequestCreate { + _c.mutation.SetClaimsGroups(v) + return _c } // SetClaimsPreferredUsername sets the "claims_preferred_username" field. -func (arc *AuthRequestCreate) SetClaimsPreferredUsername(s string) *AuthRequestCreate { - arc.mutation.SetClaimsPreferredUsername(s) - return arc +func (_c *AuthRequestCreate) SetClaimsPreferredUsername(v string) *AuthRequestCreate { + _c.mutation.SetClaimsPreferredUsername(v) + return _c } // SetNillableClaimsPreferredUsername sets the "claims_preferred_username" field if the given value is not nil. -func (arc *AuthRequestCreate) SetNillableClaimsPreferredUsername(s *string) *AuthRequestCreate { - if s != nil { - arc.SetClaimsPreferredUsername(*s) +func (_c *AuthRequestCreate) SetNillableClaimsPreferredUsername(v *string) *AuthRequestCreate { + if v != nil { + _c.SetClaimsPreferredUsername(*v) } - return arc + return _c } // SetConnectorID sets the "connector_id" field. -func (arc *AuthRequestCreate) SetConnectorID(s string) *AuthRequestCreate { - arc.mutation.SetConnectorID(s) - return arc +func (_c *AuthRequestCreate) SetConnectorID(v string) *AuthRequestCreate { + _c.mutation.SetConnectorID(v) + return _c } // SetConnectorData sets the "connector_data" field. -func (arc *AuthRequestCreate) SetConnectorData(b []byte) *AuthRequestCreate { - arc.mutation.SetConnectorData(b) - return arc +func (_c *AuthRequestCreate) SetConnectorData(v []byte) *AuthRequestCreate { + _c.mutation.SetConnectorData(v) + return _c } // SetExpiry sets the "expiry" field. -func (arc *AuthRequestCreate) SetExpiry(t time.Time) *AuthRequestCreate { - arc.mutation.SetExpiry(t) - return arc +func (_c *AuthRequestCreate) SetExpiry(v time.Time) *AuthRequestCreate { + _c.mutation.SetExpiry(v) + return _c } // SetCodeChallenge sets the "code_challenge" field. -func (arc *AuthRequestCreate) SetCodeChallenge(s string) *AuthRequestCreate { - arc.mutation.SetCodeChallenge(s) - return arc +func (_c *AuthRequestCreate) SetCodeChallenge(v string) *AuthRequestCreate { + _c.mutation.SetCodeChallenge(v) + return _c } // SetNillableCodeChallenge sets the "code_challenge" field if the given value is not nil. -func (arc *AuthRequestCreate) SetNillableCodeChallenge(s *string) *AuthRequestCreate { - if s != nil { - arc.SetCodeChallenge(*s) +func (_c *AuthRequestCreate) SetNillableCodeChallenge(v *string) *AuthRequestCreate { + if v != nil { + _c.SetCodeChallenge(*v) } - return arc + return _c } // SetCodeChallengeMethod sets the "code_challenge_method" field. -func (arc *AuthRequestCreate) SetCodeChallengeMethod(s string) *AuthRequestCreate { - arc.mutation.SetCodeChallengeMethod(s) - return arc +func (_c *AuthRequestCreate) SetCodeChallengeMethod(v string) *AuthRequestCreate { + _c.mutation.SetCodeChallengeMethod(v) + return _c } // SetNillableCodeChallengeMethod sets the "code_challenge_method" field if the given value is not nil. -func (arc *AuthRequestCreate) SetNillableCodeChallengeMethod(s *string) *AuthRequestCreate { - if s != nil { - arc.SetCodeChallengeMethod(*s) +func (_c *AuthRequestCreate) SetNillableCodeChallengeMethod(v *string) *AuthRequestCreate { + if v != nil { + _c.SetCodeChallengeMethod(*v) } - return arc + return _c } // SetHmacKey sets the "hmac_key" field. -func (arc *AuthRequestCreate) SetHmacKey(b []byte) *AuthRequestCreate { - arc.mutation.SetHmacKey(b) - return arc +func (_c *AuthRequestCreate) SetHmacKey(v []byte) *AuthRequestCreate { + _c.mutation.SetHmacKey(v) + return _c } // SetID sets the "id" field. -func (arc *AuthRequestCreate) SetID(s string) *AuthRequestCreate { - arc.mutation.SetID(s) - return arc +func (_c *AuthRequestCreate) SetID(v string) *AuthRequestCreate { + _c.mutation.SetID(v) + return _c } // Mutation returns the AuthRequestMutation object of the builder. -func (arc *AuthRequestCreate) Mutation() *AuthRequestMutation { - return arc.mutation +func (_c *AuthRequestCreate) Mutation() *AuthRequestMutation { + return _c.mutation } // Save creates the AuthRequest in the database. -func (arc *AuthRequestCreate) Save(ctx context.Context) (*AuthRequest, error) { - arc.defaults() - return withHooks(ctx, arc.sqlSave, arc.mutation, arc.hooks) +func (_c *AuthRequestCreate) Save(ctx context.Context) (*AuthRequest, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) } // SaveX calls Save and panics if Save returns an error. -func (arc *AuthRequestCreate) SaveX(ctx context.Context) *AuthRequest { - v, err := arc.Save(ctx) +func (_c *AuthRequestCreate) SaveX(ctx context.Context) *AuthRequest { + v, err := _c.Save(ctx) if err != nil { panic(err) } @@ -191,85 +191,85 @@ func (arc *AuthRequestCreate) SaveX(ctx context.Context) *AuthRequest { } // Exec executes the query. -func (arc *AuthRequestCreate) Exec(ctx context.Context) error { - _, err := arc.Save(ctx) +func (_c *AuthRequestCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (arc *AuthRequestCreate) ExecX(ctx context.Context) { - if err := arc.Exec(ctx); err != nil { +func (_c *AuthRequestCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { panic(err) } } // defaults sets the default values of the builder before save. -func (arc *AuthRequestCreate) defaults() { - if _, ok := arc.mutation.ClaimsPreferredUsername(); !ok { +func (_c *AuthRequestCreate) defaults() { + if _, ok := _c.mutation.ClaimsPreferredUsername(); !ok { v := authrequest.DefaultClaimsPreferredUsername - arc.mutation.SetClaimsPreferredUsername(v) + _c.mutation.SetClaimsPreferredUsername(v) } - if _, ok := arc.mutation.CodeChallenge(); !ok { + if _, ok := _c.mutation.CodeChallenge(); !ok { v := authrequest.DefaultCodeChallenge - arc.mutation.SetCodeChallenge(v) + _c.mutation.SetCodeChallenge(v) } - if _, ok := arc.mutation.CodeChallengeMethod(); !ok { + if _, ok := _c.mutation.CodeChallengeMethod(); !ok { v := authrequest.DefaultCodeChallengeMethod - arc.mutation.SetCodeChallengeMethod(v) + _c.mutation.SetCodeChallengeMethod(v) } } // check runs all checks and user-defined validators on the builder. -func (arc *AuthRequestCreate) check() error { - if _, ok := arc.mutation.ClientID(); !ok { +func (_c *AuthRequestCreate) check() error { + if _, ok := _c.mutation.ClientID(); !ok { return &ValidationError{Name: "client_id", err: errors.New(`db: missing required field "AuthRequest.client_id"`)} } - if _, ok := arc.mutation.RedirectURI(); !ok { + if _, ok := _c.mutation.RedirectURI(); !ok { return &ValidationError{Name: "redirect_uri", err: errors.New(`db: missing required field "AuthRequest.redirect_uri"`)} } - if _, ok := arc.mutation.Nonce(); !ok { + if _, ok := _c.mutation.Nonce(); !ok { return &ValidationError{Name: "nonce", err: errors.New(`db: missing required field "AuthRequest.nonce"`)} } - if _, ok := arc.mutation.State(); !ok { + if _, ok := _c.mutation.State(); !ok { return &ValidationError{Name: "state", err: errors.New(`db: missing required field "AuthRequest.state"`)} } - if _, ok := arc.mutation.ForceApprovalPrompt(); !ok { + if _, ok := _c.mutation.ForceApprovalPrompt(); !ok { return &ValidationError{Name: "force_approval_prompt", err: errors.New(`db: missing required field "AuthRequest.force_approval_prompt"`)} } - if _, ok := arc.mutation.LoggedIn(); !ok { + if _, ok := _c.mutation.LoggedIn(); !ok { return &ValidationError{Name: "logged_in", err: errors.New(`db: missing required field "AuthRequest.logged_in"`)} } - if _, ok := arc.mutation.ClaimsUserID(); !ok { + if _, ok := _c.mutation.ClaimsUserID(); !ok { return &ValidationError{Name: "claims_user_id", err: errors.New(`db: missing required field "AuthRequest.claims_user_id"`)} } - if _, ok := arc.mutation.ClaimsUsername(); !ok { + if _, ok := _c.mutation.ClaimsUsername(); !ok { return &ValidationError{Name: "claims_username", err: errors.New(`db: missing required field "AuthRequest.claims_username"`)} } - if _, ok := arc.mutation.ClaimsEmail(); !ok { + if _, ok := _c.mutation.ClaimsEmail(); !ok { return &ValidationError{Name: "claims_email", err: errors.New(`db: missing required field "AuthRequest.claims_email"`)} } - if _, ok := arc.mutation.ClaimsEmailVerified(); !ok { + if _, ok := _c.mutation.ClaimsEmailVerified(); !ok { return &ValidationError{Name: "claims_email_verified", err: errors.New(`db: missing required field "AuthRequest.claims_email_verified"`)} } - if _, ok := arc.mutation.ClaimsPreferredUsername(); !ok { + if _, ok := _c.mutation.ClaimsPreferredUsername(); !ok { return &ValidationError{Name: "claims_preferred_username", err: errors.New(`db: missing required field "AuthRequest.claims_preferred_username"`)} } - if _, ok := arc.mutation.ConnectorID(); !ok { + if _, ok := _c.mutation.ConnectorID(); !ok { return &ValidationError{Name: "connector_id", err: errors.New(`db: missing required field "AuthRequest.connector_id"`)} } - if _, ok := arc.mutation.Expiry(); !ok { + if _, ok := _c.mutation.Expiry(); !ok { return &ValidationError{Name: "expiry", err: errors.New(`db: missing required field "AuthRequest.expiry"`)} } - if _, ok := arc.mutation.CodeChallenge(); !ok { + if _, ok := _c.mutation.CodeChallenge(); !ok { return &ValidationError{Name: "code_challenge", err: errors.New(`db: missing required field "AuthRequest.code_challenge"`)} } - if _, ok := arc.mutation.CodeChallengeMethod(); !ok { + if _, ok := _c.mutation.CodeChallengeMethod(); !ok { return &ValidationError{Name: "code_challenge_method", err: errors.New(`db: missing required field "AuthRequest.code_challenge_method"`)} } - if _, ok := arc.mutation.HmacKey(); !ok { + if _, ok := _c.mutation.HmacKey(); !ok { return &ValidationError{Name: "hmac_key", err: errors.New(`db: missing required field "AuthRequest.hmac_key"`)} } - if v, ok := arc.mutation.ID(); ok { + if v, ok := _c.mutation.ID(); ok { if err := authrequest.IDValidator(v); err != nil { return &ValidationError{Name: "id", err: fmt.Errorf(`db: validator failed for field "AuthRequest.id": %w`, err)} } @@ -277,12 +277,12 @@ func (arc *AuthRequestCreate) check() error { return nil } -func (arc *AuthRequestCreate) sqlSave(ctx context.Context) (*AuthRequest, error) { - if err := arc.check(); err != nil { +func (_c *AuthRequestCreate) sqlSave(ctx context.Context) (*AuthRequest, error) { + if err := _c.check(); err != nil { return nil, err } - _node, _spec := arc.createSpec() - if err := sqlgraph.CreateNode(ctx, arc.driver, _spec); err != nil { + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { if sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } @@ -295,97 +295,97 @@ func (arc *AuthRequestCreate) sqlSave(ctx context.Context) (*AuthRequest, error) return nil, fmt.Errorf("unexpected AuthRequest.ID type: %T", _spec.ID.Value) } } - arc.mutation.id = &_node.ID - arc.mutation.done = true + _c.mutation.id = &_node.ID + _c.mutation.done = true return _node, nil } -func (arc *AuthRequestCreate) createSpec() (*AuthRequest, *sqlgraph.CreateSpec) { +func (_c *AuthRequestCreate) createSpec() (*AuthRequest, *sqlgraph.CreateSpec) { var ( - _node = &AuthRequest{config: arc.config} + _node = &AuthRequest{config: _c.config} _spec = sqlgraph.NewCreateSpec(authrequest.Table, sqlgraph.NewFieldSpec(authrequest.FieldID, field.TypeString)) ) - if id, ok := arc.mutation.ID(); ok { + if id, ok := _c.mutation.ID(); ok { _node.ID = id _spec.ID.Value = id } - if value, ok := arc.mutation.ClientID(); ok { + if value, ok := _c.mutation.ClientID(); ok { _spec.SetField(authrequest.FieldClientID, field.TypeString, value) _node.ClientID = value } - if value, ok := arc.mutation.Scopes(); ok { + if value, ok := _c.mutation.Scopes(); ok { _spec.SetField(authrequest.FieldScopes, field.TypeJSON, value) _node.Scopes = value } - if value, ok := arc.mutation.ResponseTypes(); ok { + if value, ok := _c.mutation.ResponseTypes(); ok { _spec.SetField(authrequest.FieldResponseTypes, field.TypeJSON, value) _node.ResponseTypes = value } - if value, ok := arc.mutation.RedirectURI(); ok { + if value, ok := _c.mutation.RedirectURI(); ok { _spec.SetField(authrequest.FieldRedirectURI, field.TypeString, value) _node.RedirectURI = value } - if value, ok := arc.mutation.Nonce(); ok { + if value, ok := _c.mutation.Nonce(); ok { _spec.SetField(authrequest.FieldNonce, field.TypeString, value) _node.Nonce = value } - if value, ok := arc.mutation.State(); ok { + if value, ok := _c.mutation.State(); ok { _spec.SetField(authrequest.FieldState, field.TypeString, value) _node.State = value } - if value, ok := arc.mutation.ForceApprovalPrompt(); ok { + if value, ok := _c.mutation.ForceApprovalPrompt(); ok { _spec.SetField(authrequest.FieldForceApprovalPrompt, field.TypeBool, value) _node.ForceApprovalPrompt = value } - if value, ok := arc.mutation.LoggedIn(); ok { + if value, ok := _c.mutation.LoggedIn(); ok { _spec.SetField(authrequest.FieldLoggedIn, field.TypeBool, value) _node.LoggedIn = value } - if value, ok := arc.mutation.ClaimsUserID(); ok { + if value, ok := _c.mutation.ClaimsUserID(); ok { _spec.SetField(authrequest.FieldClaimsUserID, field.TypeString, value) _node.ClaimsUserID = value } - if value, ok := arc.mutation.ClaimsUsername(); ok { + if value, ok := _c.mutation.ClaimsUsername(); ok { _spec.SetField(authrequest.FieldClaimsUsername, field.TypeString, value) _node.ClaimsUsername = value } - if value, ok := arc.mutation.ClaimsEmail(); ok { + if value, ok := _c.mutation.ClaimsEmail(); ok { _spec.SetField(authrequest.FieldClaimsEmail, field.TypeString, value) _node.ClaimsEmail = value } - if value, ok := arc.mutation.ClaimsEmailVerified(); ok { + if value, ok := _c.mutation.ClaimsEmailVerified(); ok { _spec.SetField(authrequest.FieldClaimsEmailVerified, field.TypeBool, value) _node.ClaimsEmailVerified = value } - if value, ok := arc.mutation.ClaimsGroups(); ok { + if value, ok := _c.mutation.ClaimsGroups(); ok { _spec.SetField(authrequest.FieldClaimsGroups, field.TypeJSON, value) _node.ClaimsGroups = value } - if value, ok := arc.mutation.ClaimsPreferredUsername(); ok { + if value, ok := _c.mutation.ClaimsPreferredUsername(); ok { _spec.SetField(authrequest.FieldClaimsPreferredUsername, field.TypeString, value) _node.ClaimsPreferredUsername = value } - if value, ok := arc.mutation.ConnectorID(); ok { + if value, ok := _c.mutation.ConnectorID(); ok { _spec.SetField(authrequest.FieldConnectorID, field.TypeString, value) _node.ConnectorID = value } - if value, ok := arc.mutation.ConnectorData(); ok { + if value, ok := _c.mutation.ConnectorData(); ok { _spec.SetField(authrequest.FieldConnectorData, field.TypeBytes, value) _node.ConnectorData = &value } - if value, ok := arc.mutation.Expiry(); ok { + if value, ok := _c.mutation.Expiry(); ok { _spec.SetField(authrequest.FieldExpiry, field.TypeTime, value) _node.Expiry = value } - if value, ok := arc.mutation.CodeChallenge(); ok { + if value, ok := _c.mutation.CodeChallenge(); ok { _spec.SetField(authrequest.FieldCodeChallenge, field.TypeString, value) _node.CodeChallenge = value } - if value, ok := arc.mutation.CodeChallengeMethod(); ok { + if value, ok := _c.mutation.CodeChallengeMethod(); ok { _spec.SetField(authrequest.FieldCodeChallengeMethod, field.TypeString, value) _node.CodeChallengeMethod = value } - if value, ok := arc.mutation.HmacKey(); ok { + if value, ok := _c.mutation.HmacKey(); ok { _spec.SetField(authrequest.FieldHmacKey, field.TypeBytes, value) _node.HmacKey = value } @@ -400,16 +400,16 @@ type AuthRequestCreateBulk struct { } // Save creates the AuthRequest entities in the database. -func (arcb *AuthRequestCreateBulk) Save(ctx context.Context) ([]*AuthRequest, error) { - if arcb.err != nil { - return nil, arcb.err - } - specs := make([]*sqlgraph.CreateSpec, len(arcb.builders)) - nodes := make([]*AuthRequest, len(arcb.builders)) - mutators := make([]Mutator, len(arcb.builders)) - for i := range arcb.builders { +func (_c *AuthRequestCreateBulk) Save(ctx context.Context) ([]*AuthRequest, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*AuthRequest, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { func(i int, root context.Context) { - builder := arcb.builders[i] + builder := _c.builders[i] builder.defaults() var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { mutation, ok := m.(*AuthRequestMutation) @@ -423,11 +423,11 @@ func (arcb *AuthRequestCreateBulk) Save(ctx context.Context) ([]*AuthRequest, er var err error nodes[i], specs[i] = builder.createSpec() if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, arcb.builders[i+1].mutation) + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, arcb.driver, spec); err != nil { + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { if sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } @@ -447,7 +447,7 @@ func (arcb *AuthRequestCreateBulk) Save(ctx context.Context) ([]*AuthRequest, er }(i, ctx) } if len(mutators) > 0 { - if _, err := mutators[0].Mutate(ctx, arcb.builders[0].mutation); err != nil { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { return nil, err } } @@ -455,8 +455,8 @@ func (arcb *AuthRequestCreateBulk) Save(ctx context.Context) ([]*AuthRequest, er } // SaveX is like Save, but panics if an error occurs. -func (arcb *AuthRequestCreateBulk) SaveX(ctx context.Context) []*AuthRequest { - v, err := arcb.Save(ctx) +func (_c *AuthRequestCreateBulk) SaveX(ctx context.Context) []*AuthRequest { + v, err := _c.Save(ctx) if err != nil { panic(err) } @@ -464,14 +464,14 @@ func (arcb *AuthRequestCreateBulk) SaveX(ctx context.Context) []*AuthRequest { } // Exec executes the query. -func (arcb *AuthRequestCreateBulk) Exec(ctx context.Context) error { - _, err := arcb.Save(ctx) +func (_c *AuthRequestCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (arcb *AuthRequestCreateBulk) ExecX(ctx context.Context) { - if err := arcb.Exec(ctx); err != nil { +func (_c *AuthRequestCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { panic(err) } } diff --git a/storage/ent/db/authrequest_delete.go b/storage/ent/db/authrequest_delete.go index 0cef693afa..b9e2cd59a3 100644 --- a/storage/ent/db/authrequest_delete.go +++ b/storage/ent/db/authrequest_delete.go @@ -20,56 +20,56 @@ type AuthRequestDelete struct { } // Where appends a list predicates to the AuthRequestDelete builder. -func (ard *AuthRequestDelete) Where(ps ...predicate.AuthRequest) *AuthRequestDelete { - ard.mutation.Where(ps...) - return ard +func (_d *AuthRequestDelete) Where(ps ...predicate.AuthRequest) *AuthRequestDelete { + _d.mutation.Where(ps...) + return _d } // Exec executes the deletion query and returns how many vertices were deleted. -func (ard *AuthRequestDelete) Exec(ctx context.Context) (int, error) { - return withHooks(ctx, ard.sqlExec, ard.mutation, ard.hooks) +func (_d *AuthRequestDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) } // ExecX is like Exec, but panics if an error occurs. -func (ard *AuthRequestDelete) ExecX(ctx context.Context) int { - n, err := ard.Exec(ctx) +func (_d *AuthRequestDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) if err != nil { panic(err) } return n } -func (ard *AuthRequestDelete) sqlExec(ctx context.Context) (int, error) { +func (_d *AuthRequestDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(authrequest.Table, sqlgraph.NewFieldSpec(authrequest.FieldID, field.TypeString)) - if ps := ard.mutation.predicates; len(ps) > 0 { + if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - affected, err := sqlgraph.DeleteNodes(ctx, ard.driver, _spec) + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) if err != nil && sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } - ard.mutation.done = true + _d.mutation.done = true return affected, err } // AuthRequestDeleteOne is the builder for deleting a single AuthRequest entity. type AuthRequestDeleteOne struct { - ard *AuthRequestDelete + _d *AuthRequestDelete } // Where appends a list predicates to the AuthRequestDelete builder. -func (ardo *AuthRequestDeleteOne) Where(ps ...predicate.AuthRequest) *AuthRequestDeleteOne { - ardo.ard.mutation.Where(ps...) - return ardo +func (_d *AuthRequestDeleteOne) Where(ps ...predicate.AuthRequest) *AuthRequestDeleteOne { + _d._d.mutation.Where(ps...) + return _d } // Exec executes the deletion query. -func (ardo *AuthRequestDeleteOne) Exec(ctx context.Context) error { - n, err := ardo.ard.Exec(ctx) +func (_d *AuthRequestDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) switch { case err != nil: return err @@ -81,8 +81,8 @@ func (ardo *AuthRequestDeleteOne) Exec(ctx context.Context) error { } // ExecX is like Exec, but panics if an error occurs. -func (ardo *AuthRequestDeleteOne) ExecX(ctx context.Context) { - if err := ardo.Exec(ctx); err != nil { +func (_d *AuthRequestDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { panic(err) } } diff --git a/storage/ent/db/authrequest_query.go b/storage/ent/db/authrequest_query.go index 35ba24b0c2..22fd3fb1d2 100644 --- a/storage/ent/db/authrequest_query.go +++ b/storage/ent/db/authrequest_query.go @@ -28,40 +28,40 @@ type AuthRequestQuery struct { } // Where adds a new predicate for the AuthRequestQuery builder. -func (arq *AuthRequestQuery) Where(ps ...predicate.AuthRequest) *AuthRequestQuery { - arq.predicates = append(arq.predicates, ps...) - return arq +func (_q *AuthRequestQuery) Where(ps ...predicate.AuthRequest) *AuthRequestQuery { + _q.predicates = append(_q.predicates, ps...) + return _q } // Limit the number of records to be returned by this query. -func (arq *AuthRequestQuery) Limit(limit int) *AuthRequestQuery { - arq.ctx.Limit = &limit - return arq +func (_q *AuthRequestQuery) Limit(limit int) *AuthRequestQuery { + _q.ctx.Limit = &limit + return _q } // Offset to start from. -func (arq *AuthRequestQuery) Offset(offset int) *AuthRequestQuery { - arq.ctx.Offset = &offset - return arq +func (_q *AuthRequestQuery) Offset(offset int) *AuthRequestQuery { + _q.ctx.Offset = &offset + return _q } // Unique configures the query builder to filter duplicate records on query. // By default, unique is set to true, and can be disabled using this method. -func (arq *AuthRequestQuery) Unique(unique bool) *AuthRequestQuery { - arq.ctx.Unique = &unique - return arq +func (_q *AuthRequestQuery) Unique(unique bool) *AuthRequestQuery { + _q.ctx.Unique = &unique + return _q } // Order specifies how the records should be ordered. -func (arq *AuthRequestQuery) Order(o ...authrequest.OrderOption) *AuthRequestQuery { - arq.order = append(arq.order, o...) - return arq +func (_q *AuthRequestQuery) Order(o ...authrequest.OrderOption) *AuthRequestQuery { + _q.order = append(_q.order, o...) + return _q } // First returns the first AuthRequest entity from the query. // Returns a *NotFoundError when no AuthRequest was found. -func (arq *AuthRequestQuery) First(ctx context.Context) (*AuthRequest, error) { - nodes, err := arq.Limit(1).All(setContextOp(ctx, arq.ctx, ent.OpQueryFirst)) +func (_q *AuthRequestQuery) First(ctx context.Context) (*AuthRequest, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) if err != nil { return nil, err } @@ -72,8 +72,8 @@ func (arq *AuthRequestQuery) First(ctx context.Context) (*AuthRequest, error) { } // FirstX is like First, but panics if an error occurs. -func (arq *AuthRequestQuery) FirstX(ctx context.Context) *AuthRequest { - node, err := arq.First(ctx) +func (_q *AuthRequestQuery) FirstX(ctx context.Context) *AuthRequest { + node, err := _q.First(ctx) if err != nil && !IsNotFound(err) { panic(err) } @@ -82,9 +82,9 @@ func (arq *AuthRequestQuery) FirstX(ctx context.Context) *AuthRequest { // FirstID returns the first AuthRequest ID from the query. // Returns a *NotFoundError when no AuthRequest ID was found. -func (arq *AuthRequestQuery) FirstID(ctx context.Context) (id string, err error) { +func (_q *AuthRequestQuery) FirstID(ctx context.Context) (id string, err error) { var ids []string - if ids, err = arq.Limit(1).IDs(setContextOp(ctx, arq.ctx, ent.OpQueryFirstID)); err != nil { + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { return } if len(ids) == 0 { @@ -95,8 +95,8 @@ func (arq *AuthRequestQuery) FirstID(ctx context.Context) (id string, err error) } // FirstIDX is like FirstID, but panics if an error occurs. -func (arq *AuthRequestQuery) FirstIDX(ctx context.Context) string { - id, err := arq.FirstID(ctx) +func (_q *AuthRequestQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) if err != nil && !IsNotFound(err) { panic(err) } @@ -106,8 +106,8 @@ func (arq *AuthRequestQuery) FirstIDX(ctx context.Context) string { // Only returns a single AuthRequest entity found by the query, ensuring it only returns one. // Returns a *NotSingularError when more than one AuthRequest entity is found. // Returns a *NotFoundError when no AuthRequest entities are found. -func (arq *AuthRequestQuery) Only(ctx context.Context) (*AuthRequest, error) { - nodes, err := arq.Limit(2).All(setContextOp(ctx, arq.ctx, ent.OpQueryOnly)) +func (_q *AuthRequestQuery) Only(ctx context.Context) (*AuthRequest, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) if err != nil { return nil, err } @@ -122,8 +122,8 @@ func (arq *AuthRequestQuery) Only(ctx context.Context) (*AuthRequest, error) { } // OnlyX is like Only, but panics if an error occurs. -func (arq *AuthRequestQuery) OnlyX(ctx context.Context) *AuthRequest { - node, err := arq.Only(ctx) +func (_q *AuthRequestQuery) OnlyX(ctx context.Context) *AuthRequest { + node, err := _q.Only(ctx) if err != nil { panic(err) } @@ -133,9 +133,9 @@ func (arq *AuthRequestQuery) OnlyX(ctx context.Context) *AuthRequest { // OnlyID is like Only, but returns the only AuthRequest ID in the query. // Returns a *NotSingularError when more than one AuthRequest ID is found. // Returns a *NotFoundError when no entities are found. -func (arq *AuthRequestQuery) OnlyID(ctx context.Context) (id string, err error) { +func (_q *AuthRequestQuery) OnlyID(ctx context.Context) (id string, err error) { var ids []string - if ids, err = arq.Limit(2).IDs(setContextOp(ctx, arq.ctx, ent.OpQueryOnlyID)); err != nil { + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { return } switch len(ids) { @@ -150,8 +150,8 @@ func (arq *AuthRequestQuery) OnlyID(ctx context.Context) (id string, err error) } // OnlyIDX is like OnlyID, but panics if an error occurs. -func (arq *AuthRequestQuery) OnlyIDX(ctx context.Context) string { - id, err := arq.OnlyID(ctx) +func (_q *AuthRequestQuery) OnlyIDX(ctx context.Context) string { + id, err := _q.OnlyID(ctx) if err != nil { panic(err) } @@ -159,18 +159,18 @@ func (arq *AuthRequestQuery) OnlyIDX(ctx context.Context) string { } // All executes the query and returns a list of AuthRequests. -func (arq *AuthRequestQuery) All(ctx context.Context) ([]*AuthRequest, error) { - ctx = setContextOp(ctx, arq.ctx, ent.OpQueryAll) - if err := arq.prepareQuery(ctx); err != nil { +func (_q *AuthRequestQuery) All(ctx context.Context) ([]*AuthRequest, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { return nil, err } qr := querierAll[[]*AuthRequest, *AuthRequestQuery]() - return withInterceptors[[]*AuthRequest](ctx, arq, qr, arq.inters) + return withInterceptors[[]*AuthRequest](ctx, _q, qr, _q.inters) } // AllX is like All, but panics if an error occurs. -func (arq *AuthRequestQuery) AllX(ctx context.Context) []*AuthRequest { - nodes, err := arq.All(ctx) +func (_q *AuthRequestQuery) AllX(ctx context.Context) []*AuthRequest { + nodes, err := _q.All(ctx) if err != nil { panic(err) } @@ -178,20 +178,20 @@ func (arq *AuthRequestQuery) AllX(ctx context.Context) []*AuthRequest { } // IDs executes the query and returns a list of AuthRequest IDs. -func (arq *AuthRequestQuery) IDs(ctx context.Context) (ids []string, err error) { - if arq.ctx.Unique == nil && arq.path != nil { - arq.Unique(true) +func (_q *AuthRequestQuery) IDs(ctx context.Context) (ids []string, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) } - ctx = setContextOp(ctx, arq.ctx, ent.OpQueryIDs) - if err = arq.Select(authrequest.FieldID).Scan(ctx, &ids); err != nil { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(authrequest.FieldID).Scan(ctx, &ids); err != nil { return nil, err } return ids, nil } // IDsX is like IDs, but panics if an error occurs. -func (arq *AuthRequestQuery) IDsX(ctx context.Context) []string { - ids, err := arq.IDs(ctx) +func (_q *AuthRequestQuery) IDsX(ctx context.Context) []string { + ids, err := _q.IDs(ctx) if err != nil { panic(err) } @@ -199,17 +199,17 @@ func (arq *AuthRequestQuery) IDsX(ctx context.Context) []string { } // Count returns the count of the given query. -func (arq *AuthRequestQuery) Count(ctx context.Context) (int, error) { - ctx = setContextOp(ctx, arq.ctx, ent.OpQueryCount) - if err := arq.prepareQuery(ctx); err != nil { +func (_q *AuthRequestQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { return 0, err } - return withInterceptors[int](ctx, arq, querierCount[*AuthRequestQuery](), arq.inters) + return withInterceptors[int](ctx, _q, querierCount[*AuthRequestQuery](), _q.inters) } // CountX is like Count, but panics if an error occurs. -func (arq *AuthRequestQuery) CountX(ctx context.Context) int { - count, err := arq.Count(ctx) +func (_q *AuthRequestQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) if err != nil { panic(err) } @@ -217,9 +217,9 @@ func (arq *AuthRequestQuery) CountX(ctx context.Context) int { } // Exist returns true if the query has elements in the graph. -func (arq *AuthRequestQuery) Exist(ctx context.Context) (bool, error) { - ctx = setContextOp(ctx, arq.ctx, ent.OpQueryExist) - switch _, err := arq.FirstID(ctx); { +func (_q *AuthRequestQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { case IsNotFound(err): return false, nil case err != nil: @@ -230,8 +230,8 @@ func (arq *AuthRequestQuery) Exist(ctx context.Context) (bool, error) { } // ExistX is like Exist, but panics if an error occurs. -func (arq *AuthRequestQuery) ExistX(ctx context.Context) bool { - exist, err := arq.Exist(ctx) +func (_q *AuthRequestQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) if err != nil { panic(err) } @@ -240,19 +240,19 @@ func (arq *AuthRequestQuery) ExistX(ctx context.Context) bool { // Clone returns a duplicate of the AuthRequestQuery builder, including all associated steps. It can be // used to prepare common query builders and use them differently after the clone is made. -func (arq *AuthRequestQuery) Clone() *AuthRequestQuery { - if arq == nil { +func (_q *AuthRequestQuery) Clone() *AuthRequestQuery { + if _q == nil { return nil } return &AuthRequestQuery{ - config: arq.config, - ctx: arq.ctx.Clone(), - order: append([]authrequest.OrderOption{}, arq.order...), - inters: append([]Interceptor{}, arq.inters...), - predicates: append([]predicate.AuthRequest{}, arq.predicates...), + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]authrequest.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.AuthRequest{}, _q.predicates...), // clone intermediate query. - sql: arq.sql.Clone(), - path: arq.path, + sql: _q.sql.Clone(), + path: _q.path, } } @@ -270,10 +270,10 @@ func (arq *AuthRequestQuery) Clone() *AuthRequestQuery { // GroupBy(authrequest.FieldClientID). // Aggregate(db.Count()). // Scan(ctx, &v) -func (arq *AuthRequestQuery) GroupBy(field string, fields ...string) *AuthRequestGroupBy { - arq.ctx.Fields = append([]string{field}, fields...) - grbuild := &AuthRequestGroupBy{build: arq} - grbuild.flds = &arq.ctx.Fields +func (_q *AuthRequestQuery) GroupBy(field string, fields ...string) *AuthRequestGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &AuthRequestGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields grbuild.label = authrequest.Label grbuild.scan = grbuild.Scan return grbuild @@ -291,62 +291,62 @@ func (arq *AuthRequestQuery) GroupBy(field string, fields ...string) *AuthReques // client.AuthRequest.Query(). // Select(authrequest.FieldClientID). // Scan(ctx, &v) -func (arq *AuthRequestQuery) Select(fields ...string) *AuthRequestSelect { - arq.ctx.Fields = append(arq.ctx.Fields, fields...) - sbuild := &AuthRequestSelect{AuthRequestQuery: arq} +func (_q *AuthRequestQuery) Select(fields ...string) *AuthRequestSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &AuthRequestSelect{AuthRequestQuery: _q} sbuild.label = authrequest.Label - sbuild.flds, sbuild.scan = &arq.ctx.Fields, sbuild.Scan + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan return sbuild } // Aggregate returns a AuthRequestSelect configured with the given aggregations. -func (arq *AuthRequestQuery) Aggregate(fns ...AggregateFunc) *AuthRequestSelect { - return arq.Select().Aggregate(fns...) +func (_q *AuthRequestQuery) Aggregate(fns ...AggregateFunc) *AuthRequestSelect { + return _q.Select().Aggregate(fns...) } -func (arq *AuthRequestQuery) prepareQuery(ctx context.Context) error { - for _, inter := range arq.inters { +func (_q *AuthRequestQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { if inter == nil { return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)") } if trv, ok := inter.(Traverser); ok { - if err := trv.Traverse(ctx, arq); err != nil { + if err := trv.Traverse(ctx, _q); err != nil { return err } } } - for _, f := range arq.ctx.Fields { + for _, f := range _q.ctx.Fields { if !authrequest.ValidColumn(f) { return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} } } - if arq.path != nil { - prev, err := arq.path(ctx) + if _q.path != nil { + prev, err := _q.path(ctx) if err != nil { return err } - arq.sql = prev + _q.sql = prev } return nil } -func (arq *AuthRequestQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AuthRequest, error) { +func (_q *AuthRequestQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AuthRequest, error) { var ( nodes = []*AuthRequest{} - _spec = arq.querySpec() + _spec = _q.querySpec() ) _spec.ScanValues = func(columns []string) ([]any, error) { return (*AuthRequest).scanValues(nil, columns) } _spec.Assign = func(columns []string, values []any) error { - node := &AuthRequest{config: arq.config} + node := &AuthRequest{config: _q.config} nodes = append(nodes, node) return node.assignValues(columns, values) } for i := range hooks { hooks[i](ctx, _spec) } - if err := sqlgraph.QueryNodes(ctx, arq.driver, _spec); err != nil { + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { return nil, err } if len(nodes) == 0 { @@ -355,24 +355,24 @@ func (arq *AuthRequestQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([] return nodes, nil } -func (arq *AuthRequestQuery) sqlCount(ctx context.Context) (int, error) { - _spec := arq.querySpec() - _spec.Node.Columns = arq.ctx.Fields - if len(arq.ctx.Fields) > 0 { - _spec.Unique = arq.ctx.Unique != nil && *arq.ctx.Unique +func (_q *AuthRequestQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique } - return sqlgraph.CountNodes(ctx, arq.driver, _spec) + return sqlgraph.CountNodes(ctx, _q.driver, _spec) } -func (arq *AuthRequestQuery) querySpec() *sqlgraph.QuerySpec { +func (_q *AuthRequestQuery) querySpec() *sqlgraph.QuerySpec { _spec := sqlgraph.NewQuerySpec(authrequest.Table, authrequest.Columns, sqlgraph.NewFieldSpec(authrequest.FieldID, field.TypeString)) - _spec.From = arq.sql - if unique := arq.ctx.Unique; unique != nil { + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { _spec.Unique = *unique - } else if arq.path != nil { + } else if _q.path != nil { _spec.Unique = true } - if fields := arq.ctx.Fields; len(fields) > 0 { + if fields := _q.ctx.Fields; len(fields) > 0 { _spec.Node.Columns = make([]string, 0, len(fields)) _spec.Node.Columns = append(_spec.Node.Columns, authrequest.FieldID) for i := range fields { @@ -381,20 +381,20 @@ func (arq *AuthRequestQuery) querySpec() *sqlgraph.QuerySpec { } } } - if ps := arq.predicates; len(ps) > 0 { + if ps := _q.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if limit := arq.ctx.Limit; limit != nil { + if limit := _q.ctx.Limit; limit != nil { _spec.Limit = *limit } - if offset := arq.ctx.Offset; offset != nil { + if offset := _q.ctx.Offset; offset != nil { _spec.Offset = *offset } - if ps := arq.order; len(ps) > 0 { + if ps := _q.order; len(ps) > 0 { _spec.Order = func(selector *sql.Selector) { for i := range ps { ps[i](selector) @@ -404,33 +404,33 @@ func (arq *AuthRequestQuery) querySpec() *sqlgraph.QuerySpec { return _spec } -func (arq *AuthRequestQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(arq.driver.Dialect()) +func (_q *AuthRequestQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) t1 := builder.Table(authrequest.Table) - columns := arq.ctx.Fields + columns := _q.ctx.Fields if len(columns) == 0 { columns = authrequest.Columns } selector := builder.Select(t1.Columns(columns...)...).From(t1) - if arq.sql != nil { - selector = arq.sql + if _q.sql != nil { + selector = _q.sql selector.Select(selector.Columns(columns...)...) } - if arq.ctx.Unique != nil && *arq.ctx.Unique { + if _q.ctx.Unique != nil && *_q.ctx.Unique { selector.Distinct() } - for _, p := range arq.predicates { + for _, p := range _q.predicates { p(selector) } - for _, p := range arq.order { + for _, p := range _q.order { p(selector) } - if offset := arq.ctx.Offset; offset != nil { + if offset := _q.ctx.Offset; offset != nil { // limit is mandatory for offset clause. We start // with default value, and override it below if needed. selector.Offset(*offset).Limit(math.MaxInt32) } - if limit := arq.ctx.Limit; limit != nil { + if limit := _q.ctx.Limit; limit != nil { selector.Limit(*limit) } return selector @@ -443,41 +443,41 @@ type AuthRequestGroupBy struct { } // Aggregate adds the given aggregation functions to the group-by query. -func (argb *AuthRequestGroupBy) Aggregate(fns ...AggregateFunc) *AuthRequestGroupBy { - argb.fns = append(argb.fns, fns...) - return argb +func (_g *AuthRequestGroupBy) Aggregate(fns ...AggregateFunc) *AuthRequestGroupBy { + _g.fns = append(_g.fns, fns...) + return _g } // Scan applies the selector query and scans the result into the given value. -func (argb *AuthRequestGroupBy) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, argb.build.ctx, ent.OpQueryGroupBy) - if err := argb.build.prepareQuery(ctx); err != nil { +func (_g *AuthRequestGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { return err } - return scanWithInterceptors[*AuthRequestQuery, *AuthRequestGroupBy](ctx, argb.build, argb, argb.build.inters, v) + return scanWithInterceptors[*AuthRequestQuery, *AuthRequestGroupBy](ctx, _g.build, _g, _g.build.inters, v) } -func (argb *AuthRequestGroupBy) sqlScan(ctx context.Context, root *AuthRequestQuery, v any) error { +func (_g *AuthRequestGroupBy) sqlScan(ctx context.Context, root *AuthRequestQuery, v any) error { selector := root.sqlQuery(ctx).Select() - aggregation := make([]string, 0, len(argb.fns)) - for _, fn := range argb.fns { + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { aggregation = append(aggregation, fn(selector)) } if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(*argb.flds)+len(argb.fns)) - for _, f := range *argb.flds { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { columns = append(columns, selector.C(f)) } columns = append(columns, aggregation...) selector.Select(columns...) } - selector.GroupBy(selector.Columns(*argb.flds...)...) + selector.GroupBy(selector.Columns(*_g.flds...)...) if err := selector.Err(); err != nil { return err } rows := &sql.Rows{} query, args := selector.Query() - if err := argb.build.driver.Query(ctx, query, args, rows); err != nil { + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() @@ -491,27 +491,27 @@ type AuthRequestSelect struct { } // Aggregate adds the given aggregation functions to the selector query. -func (ars *AuthRequestSelect) Aggregate(fns ...AggregateFunc) *AuthRequestSelect { - ars.fns = append(ars.fns, fns...) - return ars +func (_s *AuthRequestSelect) Aggregate(fns ...AggregateFunc) *AuthRequestSelect { + _s.fns = append(_s.fns, fns...) + return _s } // Scan applies the selector query and scans the result into the given value. -func (ars *AuthRequestSelect) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, ars.ctx, ent.OpQuerySelect) - if err := ars.prepareQuery(ctx); err != nil { +func (_s *AuthRequestSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { return err } - return scanWithInterceptors[*AuthRequestQuery, *AuthRequestSelect](ctx, ars.AuthRequestQuery, ars, ars.inters, v) + return scanWithInterceptors[*AuthRequestQuery, *AuthRequestSelect](ctx, _s.AuthRequestQuery, _s, _s.inters, v) } -func (ars *AuthRequestSelect) sqlScan(ctx context.Context, root *AuthRequestQuery, v any) error { +func (_s *AuthRequestSelect) sqlScan(ctx context.Context, root *AuthRequestQuery, v any) error { selector := root.sqlQuery(ctx) - aggregation := make([]string, 0, len(ars.fns)) - for _, fn := range ars.fns { + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { aggregation = append(aggregation, fn(selector)) } - switch n := len(*ars.selector.flds); { + switch n := len(*_s.selector.flds); { case n == 0 && len(aggregation) > 0: selector.Select(aggregation...) case n != 0 && len(aggregation) > 0: @@ -519,7 +519,7 @@ func (ars *AuthRequestSelect) sqlScan(ctx context.Context, root *AuthRequestQuer } rows := &sql.Rows{} query, args := selector.Query() - if err := ars.driver.Query(ctx, query, args, rows); err != nil { + if err := _s.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() diff --git a/storage/ent/db/authrequest_update.go b/storage/ent/db/authrequest_update.go index 0f314a4f51..e1fa678a80 100644 --- a/storage/ent/db/authrequest_update.go +++ b/storage/ent/db/authrequest_update.go @@ -24,306 +24,306 @@ type AuthRequestUpdate struct { } // Where appends a list predicates to the AuthRequestUpdate builder. -func (aru *AuthRequestUpdate) Where(ps ...predicate.AuthRequest) *AuthRequestUpdate { - aru.mutation.Where(ps...) - return aru +func (_u *AuthRequestUpdate) Where(ps ...predicate.AuthRequest) *AuthRequestUpdate { + _u.mutation.Where(ps...) + return _u } // SetClientID sets the "client_id" field. -func (aru *AuthRequestUpdate) SetClientID(s string) *AuthRequestUpdate { - aru.mutation.SetClientID(s) - return aru +func (_u *AuthRequestUpdate) SetClientID(v string) *AuthRequestUpdate { + _u.mutation.SetClientID(v) + return _u } // SetNillableClientID sets the "client_id" field if the given value is not nil. -func (aru *AuthRequestUpdate) SetNillableClientID(s *string) *AuthRequestUpdate { - if s != nil { - aru.SetClientID(*s) +func (_u *AuthRequestUpdate) SetNillableClientID(v *string) *AuthRequestUpdate { + if v != nil { + _u.SetClientID(*v) } - return aru + return _u } // SetScopes sets the "scopes" field. -func (aru *AuthRequestUpdate) SetScopes(s []string) *AuthRequestUpdate { - aru.mutation.SetScopes(s) - return aru +func (_u *AuthRequestUpdate) SetScopes(v []string) *AuthRequestUpdate { + _u.mutation.SetScopes(v) + return _u } -// AppendScopes appends s to the "scopes" field. -func (aru *AuthRequestUpdate) AppendScopes(s []string) *AuthRequestUpdate { - aru.mutation.AppendScopes(s) - return aru +// AppendScopes appends value to the "scopes" field. +func (_u *AuthRequestUpdate) AppendScopes(v []string) *AuthRequestUpdate { + _u.mutation.AppendScopes(v) + return _u } // ClearScopes clears the value of the "scopes" field. -func (aru *AuthRequestUpdate) ClearScopes() *AuthRequestUpdate { - aru.mutation.ClearScopes() - return aru +func (_u *AuthRequestUpdate) ClearScopes() *AuthRequestUpdate { + _u.mutation.ClearScopes() + return _u } // SetResponseTypes sets the "response_types" field. -func (aru *AuthRequestUpdate) SetResponseTypes(s []string) *AuthRequestUpdate { - aru.mutation.SetResponseTypes(s) - return aru +func (_u *AuthRequestUpdate) SetResponseTypes(v []string) *AuthRequestUpdate { + _u.mutation.SetResponseTypes(v) + return _u } -// AppendResponseTypes appends s to the "response_types" field. -func (aru *AuthRequestUpdate) AppendResponseTypes(s []string) *AuthRequestUpdate { - aru.mutation.AppendResponseTypes(s) - return aru +// AppendResponseTypes appends value to the "response_types" field. +func (_u *AuthRequestUpdate) AppendResponseTypes(v []string) *AuthRequestUpdate { + _u.mutation.AppendResponseTypes(v) + return _u } // ClearResponseTypes clears the value of the "response_types" field. -func (aru *AuthRequestUpdate) ClearResponseTypes() *AuthRequestUpdate { - aru.mutation.ClearResponseTypes() - return aru +func (_u *AuthRequestUpdate) ClearResponseTypes() *AuthRequestUpdate { + _u.mutation.ClearResponseTypes() + return _u } // SetRedirectURI sets the "redirect_uri" field. -func (aru *AuthRequestUpdate) SetRedirectURI(s string) *AuthRequestUpdate { - aru.mutation.SetRedirectURI(s) - return aru +func (_u *AuthRequestUpdate) SetRedirectURI(v string) *AuthRequestUpdate { + _u.mutation.SetRedirectURI(v) + return _u } // SetNillableRedirectURI sets the "redirect_uri" field if the given value is not nil. -func (aru *AuthRequestUpdate) SetNillableRedirectURI(s *string) *AuthRequestUpdate { - if s != nil { - aru.SetRedirectURI(*s) +func (_u *AuthRequestUpdate) SetNillableRedirectURI(v *string) *AuthRequestUpdate { + if v != nil { + _u.SetRedirectURI(*v) } - return aru + return _u } // SetNonce sets the "nonce" field. -func (aru *AuthRequestUpdate) SetNonce(s string) *AuthRequestUpdate { - aru.mutation.SetNonce(s) - return aru +func (_u *AuthRequestUpdate) SetNonce(v string) *AuthRequestUpdate { + _u.mutation.SetNonce(v) + return _u } // SetNillableNonce sets the "nonce" field if the given value is not nil. -func (aru *AuthRequestUpdate) SetNillableNonce(s *string) *AuthRequestUpdate { - if s != nil { - aru.SetNonce(*s) +func (_u *AuthRequestUpdate) SetNillableNonce(v *string) *AuthRequestUpdate { + if v != nil { + _u.SetNonce(*v) } - return aru + return _u } // SetState sets the "state" field. -func (aru *AuthRequestUpdate) SetState(s string) *AuthRequestUpdate { - aru.mutation.SetState(s) - return aru +func (_u *AuthRequestUpdate) SetState(v string) *AuthRequestUpdate { + _u.mutation.SetState(v) + return _u } // SetNillableState sets the "state" field if the given value is not nil. -func (aru *AuthRequestUpdate) SetNillableState(s *string) *AuthRequestUpdate { - if s != nil { - aru.SetState(*s) +func (_u *AuthRequestUpdate) SetNillableState(v *string) *AuthRequestUpdate { + if v != nil { + _u.SetState(*v) } - return aru + return _u } // SetForceApprovalPrompt sets the "force_approval_prompt" field. -func (aru *AuthRequestUpdate) SetForceApprovalPrompt(b bool) *AuthRequestUpdate { - aru.mutation.SetForceApprovalPrompt(b) - return aru +func (_u *AuthRequestUpdate) SetForceApprovalPrompt(v bool) *AuthRequestUpdate { + _u.mutation.SetForceApprovalPrompt(v) + return _u } // SetNillableForceApprovalPrompt sets the "force_approval_prompt" field if the given value is not nil. -func (aru *AuthRequestUpdate) SetNillableForceApprovalPrompt(b *bool) *AuthRequestUpdate { - if b != nil { - aru.SetForceApprovalPrompt(*b) +func (_u *AuthRequestUpdate) SetNillableForceApprovalPrompt(v *bool) *AuthRequestUpdate { + if v != nil { + _u.SetForceApprovalPrompt(*v) } - return aru + return _u } // SetLoggedIn sets the "logged_in" field. -func (aru *AuthRequestUpdate) SetLoggedIn(b bool) *AuthRequestUpdate { - aru.mutation.SetLoggedIn(b) - return aru +func (_u *AuthRequestUpdate) SetLoggedIn(v bool) *AuthRequestUpdate { + _u.mutation.SetLoggedIn(v) + return _u } // SetNillableLoggedIn sets the "logged_in" field if the given value is not nil. -func (aru *AuthRequestUpdate) SetNillableLoggedIn(b *bool) *AuthRequestUpdate { - if b != nil { - aru.SetLoggedIn(*b) +func (_u *AuthRequestUpdate) SetNillableLoggedIn(v *bool) *AuthRequestUpdate { + if v != nil { + _u.SetLoggedIn(*v) } - return aru + return _u } // SetClaimsUserID sets the "claims_user_id" field. -func (aru *AuthRequestUpdate) SetClaimsUserID(s string) *AuthRequestUpdate { - aru.mutation.SetClaimsUserID(s) - return aru +func (_u *AuthRequestUpdate) SetClaimsUserID(v string) *AuthRequestUpdate { + _u.mutation.SetClaimsUserID(v) + return _u } // SetNillableClaimsUserID sets the "claims_user_id" field if the given value is not nil. -func (aru *AuthRequestUpdate) SetNillableClaimsUserID(s *string) *AuthRequestUpdate { - if s != nil { - aru.SetClaimsUserID(*s) +func (_u *AuthRequestUpdate) SetNillableClaimsUserID(v *string) *AuthRequestUpdate { + if v != nil { + _u.SetClaimsUserID(*v) } - return aru + return _u } // SetClaimsUsername sets the "claims_username" field. -func (aru *AuthRequestUpdate) SetClaimsUsername(s string) *AuthRequestUpdate { - aru.mutation.SetClaimsUsername(s) - return aru +func (_u *AuthRequestUpdate) SetClaimsUsername(v string) *AuthRequestUpdate { + _u.mutation.SetClaimsUsername(v) + return _u } // SetNillableClaimsUsername sets the "claims_username" field if the given value is not nil. -func (aru *AuthRequestUpdate) SetNillableClaimsUsername(s *string) *AuthRequestUpdate { - if s != nil { - aru.SetClaimsUsername(*s) +func (_u *AuthRequestUpdate) SetNillableClaimsUsername(v *string) *AuthRequestUpdate { + if v != nil { + _u.SetClaimsUsername(*v) } - return aru + return _u } // SetClaimsEmail sets the "claims_email" field. -func (aru *AuthRequestUpdate) SetClaimsEmail(s string) *AuthRequestUpdate { - aru.mutation.SetClaimsEmail(s) - return aru +func (_u *AuthRequestUpdate) SetClaimsEmail(v string) *AuthRequestUpdate { + _u.mutation.SetClaimsEmail(v) + return _u } // SetNillableClaimsEmail sets the "claims_email" field if the given value is not nil. -func (aru *AuthRequestUpdate) SetNillableClaimsEmail(s *string) *AuthRequestUpdate { - if s != nil { - aru.SetClaimsEmail(*s) +func (_u *AuthRequestUpdate) SetNillableClaimsEmail(v *string) *AuthRequestUpdate { + if v != nil { + _u.SetClaimsEmail(*v) } - return aru + return _u } // SetClaimsEmailVerified sets the "claims_email_verified" field. -func (aru *AuthRequestUpdate) SetClaimsEmailVerified(b bool) *AuthRequestUpdate { - aru.mutation.SetClaimsEmailVerified(b) - return aru +func (_u *AuthRequestUpdate) SetClaimsEmailVerified(v bool) *AuthRequestUpdate { + _u.mutation.SetClaimsEmailVerified(v) + return _u } // SetNillableClaimsEmailVerified sets the "claims_email_verified" field if the given value is not nil. -func (aru *AuthRequestUpdate) SetNillableClaimsEmailVerified(b *bool) *AuthRequestUpdate { - if b != nil { - aru.SetClaimsEmailVerified(*b) +func (_u *AuthRequestUpdate) SetNillableClaimsEmailVerified(v *bool) *AuthRequestUpdate { + if v != nil { + _u.SetClaimsEmailVerified(*v) } - return aru + return _u } // SetClaimsGroups sets the "claims_groups" field. -func (aru *AuthRequestUpdate) SetClaimsGroups(s []string) *AuthRequestUpdate { - aru.mutation.SetClaimsGroups(s) - return aru +func (_u *AuthRequestUpdate) SetClaimsGroups(v []string) *AuthRequestUpdate { + _u.mutation.SetClaimsGroups(v) + return _u } -// AppendClaimsGroups appends s to the "claims_groups" field. -func (aru *AuthRequestUpdate) AppendClaimsGroups(s []string) *AuthRequestUpdate { - aru.mutation.AppendClaimsGroups(s) - return aru +// AppendClaimsGroups appends value to the "claims_groups" field. +func (_u *AuthRequestUpdate) AppendClaimsGroups(v []string) *AuthRequestUpdate { + _u.mutation.AppendClaimsGroups(v) + return _u } // ClearClaimsGroups clears the value of the "claims_groups" field. -func (aru *AuthRequestUpdate) ClearClaimsGroups() *AuthRequestUpdate { - aru.mutation.ClearClaimsGroups() - return aru +func (_u *AuthRequestUpdate) ClearClaimsGroups() *AuthRequestUpdate { + _u.mutation.ClearClaimsGroups() + return _u } // SetClaimsPreferredUsername sets the "claims_preferred_username" field. -func (aru *AuthRequestUpdate) SetClaimsPreferredUsername(s string) *AuthRequestUpdate { - aru.mutation.SetClaimsPreferredUsername(s) - return aru +func (_u *AuthRequestUpdate) SetClaimsPreferredUsername(v string) *AuthRequestUpdate { + _u.mutation.SetClaimsPreferredUsername(v) + return _u } // SetNillableClaimsPreferredUsername sets the "claims_preferred_username" field if the given value is not nil. -func (aru *AuthRequestUpdate) SetNillableClaimsPreferredUsername(s *string) *AuthRequestUpdate { - if s != nil { - aru.SetClaimsPreferredUsername(*s) +func (_u *AuthRequestUpdate) SetNillableClaimsPreferredUsername(v *string) *AuthRequestUpdate { + if v != nil { + _u.SetClaimsPreferredUsername(*v) } - return aru + return _u } // SetConnectorID sets the "connector_id" field. -func (aru *AuthRequestUpdate) SetConnectorID(s string) *AuthRequestUpdate { - aru.mutation.SetConnectorID(s) - return aru +func (_u *AuthRequestUpdate) SetConnectorID(v string) *AuthRequestUpdate { + _u.mutation.SetConnectorID(v) + return _u } // SetNillableConnectorID sets the "connector_id" field if the given value is not nil. -func (aru *AuthRequestUpdate) SetNillableConnectorID(s *string) *AuthRequestUpdate { - if s != nil { - aru.SetConnectorID(*s) +func (_u *AuthRequestUpdate) SetNillableConnectorID(v *string) *AuthRequestUpdate { + if v != nil { + _u.SetConnectorID(*v) } - return aru + return _u } // SetConnectorData sets the "connector_data" field. -func (aru *AuthRequestUpdate) SetConnectorData(b []byte) *AuthRequestUpdate { - aru.mutation.SetConnectorData(b) - return aru +func (_u *AuthRequestUpdate) SetConnectorData(v []byte) *AuthRequestUpdate { + _u.mutation.SetConnectorData(v) + return _u } // ClearConnectorData clears the value of the "connector_data" field. -func (aru *AuthRequestUpdate) ClearConnectorData() *AuthRequestUpdate { - aru.mutation.ClearConnectorData() - return aru +func (_u *AuthRequestUpdate) ClearConnectorData() *AuthRequestUpdate { + _u.mutation.ClearConnectorData() + return _u } // SetExpiry sets the "expiry" field. -func (aru *AuthRequestUpdate) SetExpiry(t time.Time) *AuthRequestUpdate { - aru.mutation.SetExpiry(t) - return aru +func (_u *AuthRequestUpdate) SetExpiry(v time.Time) *AuthRequestUpdate { + _u.mutation.SetExpiry(v) + return _u } // SetNillableExpiry sets the "expiry" field if the given value is not nil. -func (aru *AuthRequestUpdate) SetNillableExpiry(t *time.Time) *AuthRequestUpdate { - if t != nil { - aru.SetExpiry(*t) +func (_u *AuthRequestUpdate) SetNillableExpiry(v *time.Time) *AuthRequestUpdate { + if v != nil { + _u.SetExpiry(*v) } - return aru + return _u } // SetCodeChallenge sets the "code_challenge" field. -func (aru *AuthRequestUpdate) SetCodeChallenge(s string) *AuthRequestUpdate { - aru.mutation.SetCodeChallenge(s) - return aru +func (_u *AuthRequestUpdate) SetCodeChallenge(v string) *AuthRequestUpdate { + _u.mutation.SetCodeChallenge(v) + return _u } // SetNillableCodeChallenge sets the "code_challenge" field if the given value is not nil. -func (aru *AuthRequestUpdate) SetNillableCodeChallenge(s *string) *AuthRequestUpdate { - if s != nil { - aru.SetCodeChallenge(*s) +func (_u *AuthRequestUpdate) SetNillableCodeChallenge(v *string) *AuthRequestUpdate { + if v != nil { + _u.SetCodeChallenge(*v) } - return aru + return _u } // SetCodeChallengeMethod sets the "code_challenge_method" field. -func (aru *AuthRequestUpdate) SetCodeChallengeMethod(s string) *AuthRequestUpdate { - aru.mutation.SetCodeChallengeMethod(s) - return aru +func (_u *AuthRequestUpdate) SetCodeChallengeMethod(v string) *AuthRequestUpdate { + _u.mutation.SetCodeChallengeMethod(v) + return _u } // SetNillableCodeChallengeMethod sets the "code_challenge_method" field if the given value is not nil. -func (aru *AuthRequestUpdate) SetNillableCodeChallengeMethod(s *string) *AuthRequestUpdate { - if s != nil { - aru.SetCodeChallengeMethod(*s) +func (_u *AuthRequestUpdate) SetNillableCodeChallengeMethod(v *string) *AuthRequestUpdate { + if v != nil { + _u.SetCodeChallengeMethod(*v) } - return aru + return _u } // SetHmacKey sets the "hmac_key" field. -func (aru *AuthRequestUpdate) SetHmacKey(b []byte) *AuthRequestUpdate { - aru.mutation.SetHmacKey(b) - return aru +func (_u *AuthRequestUpdate) SetHmacKey(v []byte) *AuthRequestUpdate { + _u.mutation.SetHmacKey(v) + return _u } // Mutation returns the AuthRequestMutation object of the builder. -func (aru *AuthRequestUpdate) Mutation() *AuthRequestMutation { - return aru.mutation +func (_u *AuthRequestUpdate) Mutation() *AuthRequestMutation { + return _u.mutation } // Save executes the query and returns the number of nodes affected by the update operation. -func (aru *AuthRequestUpdate) Save(ctx context.Context) (int, error) { - return withHooks(ctx, aru.sqlSave, aru.mutation, aru.hooks) +func (_u *AuthRequestUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) } // SaveX is like Save, but panics if an error occurs. -func (aru *AuthRequestUpdate) SaveX(ctx context.Context) int { - affected, err := aru.Save(ctx) +func (_u *AuthRequestUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) if err != nil { panic(err) } @@ -331,115 +331,115 @@ func (aru *AuthRequestUpdate) SaveX(ctx context.Context) int { } // Exec executes the query. -func (aru *AuthRequestUpdate) Exec(ctx context.Context) error { - _, err := aru.Save(ctx) +func (_u *AuthRequestUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (aru *AuthRequestUpdate) ExecX(ctx context.Context) { - if err := aru.Exec(ctx); err != nil { +func (_u *AuthRequestUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { panic(err) } } -func (aru *AuthRequestUpdate) sqlSave(ctx context.Context) (n int, err error) { +func (_u *AuthRequestUpdate) sqlSave(ctx context.Context) (_node int, err error) { _spec := sqlgraph.NewUpdateSpec(authrequest.Table, authrequest.Columns, sqlgraph.NewFieldSpec(authrequest.FieldID, field.TypeString)) - if ps := aru.mutation.predicates; len(ps) > 0 { + if ps := _u.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if value, ok := aru.mutation.ClientID(); ok { + if value, ok := _u.mutation.ClientID(); ok { _spec.SetField(authrequest.FieldClientID, field.TypeString, value) } - if value, ok := aru.mutation.Scopes(); ok { + if value, ok := _u.mutation.Scopes(); ok { _spec.SetField(authrequest.FieldScopes, field.TypeJSON, value) } - if value, ok := aru.mutation.AppendedScopes(); ok { + if value, ok := _u.mutation.AppendedScopes(); ok { _spec.AddModifier(func(u *sql.UpdateBuilder) { sqljson.Append(u, authrequest.FieldScopes, value) }) } - if aru.mutation.ScopesCleared() { + if _u.mutation.ScopesCleared() { _spec.ClearField(authrequest.FieldScopes, field.TypeJSON) } - if value, ok := aru.mutation.ResponseTypes(); ok { + if value, ok := _u.mutation.ResponseTypes(); ok { _spec.SetField(authrequest.FieldResponseTypes, field.TypeJSON, value) } - if value, ok := aru.mutation.AppendedResponseTypes(); ok { + if value, ok := _u.mutation.AppendedResponseTypes(); ok { _spec.AddModifier(func(u *sql.UpdateBuilder) { sqljson.Append(u, authrequest.FieldResponseTypes, value) }) } - if aru.mutation.ResponseTypesCleared() { + if _u.mutation.ResponseTypesCleared() { _spec.ClearField(authrequest.FieldResponseTypes, field.TypeJSON) } - if value, ok := aru.mutation.RedirectURI(); ok { + if value, ok := _u.mutation.RedirectURI(); ok { _spec.SetField(authrequest.FieldRedirectURI, field.TypeString, value) } - if value, ok := aru.mutation.Nonce(); ok { + if value, ok := _u.mutation.Nonce(); ok { _spec.SetField(authrequest.FieldNonce, field.TypeString, value) } - if value, ok := aru.mutation.State(); ok { + if value, ok := _u.mutation.State(); ok { _spec.SetField(authrequest.FieldState, field.TypeString, value) } - if value, ok := aru.mutation.ForceApprovalPrompt(); ok { + if value, ok := _u.mutation.ForceApprovalPrompt(); ok { _spec.SetField(authrequest.FieldForceApprovalPrompt, field.TypeBool, value) } - if value, ok := aru.mutation.LoggedIn(); ok { + if value, ok := _u.mutation.LoggedIn(); ok { _spec.SetField(authrequest.FieldLoggedIn, field.TypeBool, value) } - if value, ok := aru.mutation.ClaimsUserID(); ok { + if value, ok := _u.mutation.ClaimsUserID(); ok { _spec.SetField(authrequest.FieldClaimsUserID, field.TypeString, value) } - if value, ok := aru.mutation.ClaimsUsername(); ok { + if value, ok := _u.mutation.ClaimsUsername(); ok { _spec.SetField(authrequest.FieldClaimsUsername, field.TypeString, value) } - if value, ok := aru.mutation.ClaimsEmail(); ok { + if value, ok := _u.mutation.ClaimsEmail(); ok { _spec.SetField(authrequest.FieldClaimsEmail, field.TypeString, value) } - if value, ok := aru.mutation.ClaimsEmailVerified(); ok { + if value, ok := _u.mutation.ClaimsEmailVerified(); ok { _spec.SetField(authrequest.FieldClaimsEmailVerified, field.TypeBool, value) } - if value, ok := aru.mutation.ClaimsGroups(); ok { + if value, ok := _u.mutation.ClaimsGroups(); ok { _spec.SetField(authrequest.FieldClaimsGroups, field.TypeJSON, value) } - if value, ok := aru.mutation.AppendedClaimsGroups(); ok { + if value, ok := _u.mutation.AppendedClaimsGroups(); ok { _spec.AddModifier(func(u *sql.UpdateBuilder) { sqljson.Append(u, authrequest.FieldClaimsGroups, value) }) } - if aru.mutation.ClaimsGroupsCleared() { + if _u.mutation.ClaimsGroupsCleared() { _spec.ClearField(authrequest.FieldClaimsGroups, field.TypeJSON) } - if value, ok := aru.mutation.ClaimsPreferredUsername(); ok { + if value, ok := _u.mutation.ClaimsPreferredUsername(); ok { _spec.SetField(authrequest.FieldClaimsPreferredUsername, field.TypeString, value) } - if value, ok := aru.mutation.ConnectorID(); ok { + if value, ok := _u.mutation.ConnectorID(); ok { _spec.SetField(authrequest.FieldConnectorID, field.TypeString, value) } - if value, ok := aru.mutation.ConnectorData(); ok { + if value, ok := _u.mutation.ConnectorData(); ok { _spec.SetField(authrequest.FieldConnectorData, field.TypeBytes, value) } - if aru.mutation.ConnectorDataCleared() { + if _u.mutation.ConnectorDataCleared() { _spec.ClearField(authrequest.FieldConnectorData, field.TypeBytes) } - if value, ok := aru.mutation.Expiry(); ok { + if value, ok := _u.mutation.Expiry(); ok { _spec.SetField(authrequest.FieldExpiry, field.TypeTime, value) } - if value, ok := aru.mutation.CodeChallenge(); ok { + if value, ok := _u.mutation.CodeChallenge(); ok { _spec.SetField(authrequest.FieldCodeChallenge, field.TypeString, value) } - if value, ok := aru.mutation.CodeChallengeMethod(); ok { + if value, ok := _u.mutation.CodeChallengeMethod(); ok { _spec.SetField(authrequest.FieldCodeChallengeMethod, field.TypeString, value) } - if value, ok := aru.mutation.HmacKey(); ok { + if value, ok := _u.mutation.HmacKey(); ok { _spec.SetField(authrequest.FieldHmacKey, field.TypeBytes, value) } - if n, err = sqlgraph.UpdateNodes(ctx, aru.driver, _spec); err != nil { + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{authrequest.Label} } else if sqlgraph.IsConstraintError(err) { @@ -447,8 +447,8 @@ func (aru *AuthRequestUpdate) sqlSave(ctx context.Context) (n int, err error) { } return 0, err } - aru.mutation.done = true - return n, nil + _u.mutation.done = true + return _node, nil } // AuthRequestUpdateOne is the builder for updating a single AuthRequest entity. @@ -460,313 +460,313 @@ type AuthRequestUpdateOne struct { } // SetClientID sets the "client_id" field. -func (aruo *AuthRequestUpdateOne) SetClientID(s string) *AuthRequestUpdateOne { - aruo.mutation.SetClientID(s) - return aruo +func (_u *AuthRequestUpdateOne) SetClientID(v string) *AuthRequestUpdateOne { + _u.mutation.SetClientID(v) + return _u } // SetNillableClientID sets the "client_id" field if the given value is not nil. -func (aruo *AuthRequestUpdateOne) SetNillableClientID(s *string) *AuthRequestUpdateOne { - if s != nil { - aruo.SetClientID(*s) +func (_u *AuthRequestUpdateOne) SetNillableClientID(v *string) *AuthRequestUpdateOne { + if v != nil { + _u.SetClientID(*v) } - return aruo + return _u } // SetScopes sets the "scopes" field. -func (aruo *AuthRequestUpdateOne) SetScopes(s []string) *AuthRequestUpdateOne { - aruo.mutation.SetScopes(s) - return aruo +func (_u *AuthRequestUpdateOne) SetScopes(v []string) *AuthRequestUpdateOne { + _u.mutation.SetScopes(v) + return _u } -// AppendScopes appends s to the "scopes" field. -func (aruo *AuthRequestUpdateOne) AppendScopes(s []string) *AuthRequestUpdateOne { - aruo.mutation.AppendScopes(s) - return aruo +// AppendScopes appends value to the "scopes" field. +func (_u *AuthRequestUpdateOne) AppendScopes(v []string) *AuthRequestUpdateOne { + _u.mutation.AppendScopes(v) + return _u } // ClearScopes clears the value of the "scopes" field. -func (aruo *AuthRequestUpdateOne) ClearScopes() *AuthRequestUpdateOne { - aruo.mutation.ClearScopes() - return aruo +func (_u *AuthRequestUpdateOne) ClearScopes() *AuthRequestUpdateOne { + _u.mutation.ClearScopes() + return _u } // SetResponseTypes sets the "response_types" field. -func (aruo *AuthRequestUpdateOne) SetResponseTypes(s []string) *AuthRequestUpdateOne { - aruo.mutation.SetResponseTypes(s) - return aruo +func (_u *AuthRequestUpdateOne) SetResponseTypes(v []string) *AuthRequestUpdateOne { + _u.mutation.SetResponseTypes(v) + return _u } -// AppendResponseTypes appends s to the "response_types" field. -func (aruo *AuthRequestUpdateOne) AppendResponseTypes(s []string) *AuthRequestUpdateOne { - aruo.mutation.AppendResponseTypes(s) - return aruo +// AppendResponseTypes appends value to the "response_types" field. +func (_u *AuthRequestUpdateOne) AppendResponseTypes(v []string) *AuthRequestUpdateOne { + _u.mutation.AppendResponseTypes(v) + return _u } // ClearResponseTypes clears the value of the "response_types" field. -func (aruo *AuthRequestUpdateOne) ClearResponseTypes() *AuthRequestUpdateOne { - aruo.mutation.ClearResponseTypes() - return aruo +func (_u *AuthRequestUpdateOne) ClearResponseTypes() *AuthRequestUpdateOne { + _u.mutation.ClearResponseTypes() + return _u } // SetRedirectURI sets the "redirect_uri" field. -func (aruo *AuthRequestUpdateOne) SetRedirectURI(s string) *AuthRequestUpdateOne { - aruo.mutation.SetRedirectURI(s) - return aruo +func (_u *AuthRequestUpdateOne) SetRedirectURI(v string) *AuthRequestUpdateOne { + _u.mutation.SetRedirectURI(v) + return _u } // SetNillableRedirectURI sets the "redirect_uri" field if the given value is not nil. -func (aruo *AuthRequestUpdateOne) SetNillableRedirectURI(s *string) *AuthRequestUpdateOne { - if s != nil { - aruo.SetRedirectURI(*s) +func (_u *AuthRequestUpdateOne) SetNillableRedirectURI(v *string) *AuthRequestUpdateOne { + if v != nil { + _u.SetRedirectURI(*v) } - return aruo + return _u } // SetNonce sets the "nonce" field. -func (aruo *AuthRequestUpdateOne) SetNonce(s string) *AuthRequestUpdateOne { - aruo.mutation.SetNonce(s) - return aruo +func (_u *AuthRequestUpdateOne) SetNonce(v string) *AuthRequestUpdateOne { + _u.mutation.SetNonce(v) + return _u } // SetNillableNonce sets the "nonce" field if the given value is not nil. -func (aruo *AuthRequestUpdateOne) SetNillableNonce(s *string) *AuthRequestUpdateOne { - if s != nil { - aruo.SetNonce(*s) +func (_u *AuthRequestUpdateOne) SetNillableNonce(v *string) *AuthRequestUpdateOne { + if v != nil { + _u.SetNonce(*v) } - return aruo + return _u } // SetState sets the "state" field. -func (aruo *AuthRequestUpdateOne) SetState(s string) *AuthRequestUpdateOne { - aruo.mutation.SetState(s) - return aruo +func (_u *AuthRequestUpdateOne) SetState(v string) *AuthRequestUpdateOne { + _u.mutation.SetState(v) + return _u } // SetNillableState sets the "state" field if the given value is not nil. -func (aruo *AuthRequestUpdateOne) SetNillableState(s *string) *AuthRequestUpdateOne { - if s != nil { - aruo.SetState(*s) +func (_u *AuthRequestUpdateOne) SetNillableState(v *string) *AuthRequestUpdateOne { + if v != nil { + _u.SetState(*v) } - return aruo + return _u } // SetForceApprovalPrompt sets the "force_approval_prompt" field. -func (aruo *AuthRequestUpdateOne) SetForceApprovalPrompt(b bool) *AuthRequestUpdateOne { - aruo.mutation.SetForceApprovalPrompt(b) - return aruo +func (_u *AuthRequestUpdateOne) SetForceApprovalPrompt(v bool) *AuthRequestUpdateOne { + _u.mutation.SetForceApprovalPrompt(v) + return _u } // SetNillableForceApprovalPrompt sets the "force_approval_prompt" field if the given value is not nil. -func (aruo *AuthRequestUpdateOne) SetNillableForceApprovalPrompt(b *bool) *AuthRequestUpdateOne { - if b != nil { - aruo.SetForceApprovalPrompt(*b) +func (_u *AuthRequestUpdateOne) SetNillableForceApprovalPrompt(v *bool) *AuthRequestUpdateOne { + if v != nil { + _u.SetForceApprovalPrompt(*v) } - return aruo + return _u } // SetLoggedIn sets the "logged_in" field. -func (aruo *AuthRequestUpdateOne) SetLoggedIn(b bool) *AuthRequestUpdateOne { - aruo.mutation.SetLoggedIn(b) - return aruo +func (_u *AuthRequestUpdateOne) SetLoggedIn(v bool) *AuthRequestUpdateOne { + _u.mutation.SetLoggedIn(v) + return _u } // SetNillableLoggedIn sets the "logged_in" field if the given value is not nil. -func (aruo *AuthRequestUpdateOne) SetNillableLoggedIn(b *bool) *AuthRequestUpdateOne { - if b != nil { - aruo.SetLoggedIn(*b) +func (_u *AuthRequestUpdateOne) SetNillableLoggedIn(v *bool) *AuthRequestUpdateOne { + if v != nil { + _u.SetLoggedIn(*v) } - return aruo + return _u } // SetClaimsUserID sets the "claims_user_id" field. -func (aruo *AuthRequestUpdateOne) SetClaimsUserID(s string) *AuthRequestUpdateOne { - aruo.mutation.SetClaimsUserID(s) - return aruo +func (_u *AuthRequestUpdateOne) SetClaimsUserID(v string) *AuthRequestUpdateOne { + _u.mutation.SetClaimsUserID(v) + return _u } // SetNillableClaimsUserID sets the "claims_user_id" field if the given value is not nil. -func (aruo *AuthRequestUpdateOne) SetNillableClaimsUserID(s *string) *AuthRequestUpdateOne { - if s != nil { - aruo.SetClaimsUserID(*s) +func (_u *AuthRequestUpdateOne) SetNillableClaimsUserID(v *string) *AuthRequestUpdateOne { + if v != nil { + _u.SetClaimsUserID(*v) } - return aruo + return _u } // SetClaimsUsername sets the "claims_username" field. -func (aruo *AuthRequestUpdateOne) SetClaimsUsername(s string) *AuthRequestUpdateOne { - aruo.mutation.SetClaimsUsername(s) - return aruo +func (_u *AuthRequestUpdateOne) SetClaimsUsername(v string) *AuthRequestUpdateOne { + _u.mutation.SetClaimsUsername(v) + return _u } // SetNillableClaimsUsername sets the "claims_username" field if the given value is not nil. -func (aruo *AuthRequestUpdateOne) SetNillableClaimsUsername(s *string) *AuthRequestUpdateOne { - if s != nil { - aruo.SetClaimsUsername(*s) +func (_u *AuthRequestUpdateOne) SetNillableClaimsUsername(v *string) *AuthRequestUpdateOne { + if v != nil { + _u.SetClaimsUsername(*v) } - return aruo + return _u } // SetClaimsEmail sets the "claims_email" field. -func (aruo *AuthRequestUpdateOne) SetClaimsEmail(s string) *AuthRequestUpdateOne { - aruo.mutation.SetClaimsEmail(s) - return aruo +func (_u *AuthRequestUpdateOne) SetClaimsEmail(v string) *AuthRequestUpdateOne { + _u.mutation.SetClaimsEmail(v) + return _u } // SetNillableClaimsEmail sets the "claims_email" field if the given value is not nil. -func (aruo *AuthRequestUpdateOne) SetNillableClaimsEmail(s *string) *AuthRequestUpdateOne { - if s != nil { - aruo.SetClaimsEmail(*s) +func (_u *AuthRequestUpdateOne) SetNillableClaimsEmail(v *string) *AuthRequestUpdateOne { + if v != nil { + _u.SetClaimsEmail(*v) } - return aruo + return _u } // SetClaimsEmailVerified sets the "claims_email_verified" field. -func (aruo *AuthRequestUpdateOne) SetClaimsEmailVerified(b bool) *AuthRequestUpdateOne { - aruo.mutation.SetClaimsEmailVerified(b) - return aruo +func (_u *AuthRequestUpdateOne) SetClaimsEmailVerified(v bool) *AuthRequestUpdateOne { + _u.mutation.SetClaimsEmailVerified(v) + return _u } // SetNillableClaimsEmailVerified sets the "claims_email_verified" field if the given value is not nil. -func (aruo *AuthRequestUpdateOne) SetNillableClaimsEmailVerified(b *bool) *AuthRequestUpdateOne { - if b != nil { - aruo.SetClaimsEmailVerified(*b) +func (_u *AuthRequestUpdateOne) SetNillableClaimsEmailVerified(v *bool) *AuthRequestUpdateOne { + if v != nil { + _u.SetClaimsEmailVerified(*v) } - return aruo + return _u } // SetClaimsGroups sets the "claims_groups" field. -func (aruo *AuthRequestUpdateOne) SetClaimsGroups(s []string) *AuthRequestUpdateOne { - aruo.mutation.SetClaimsGroups(s) - return aruo +func (_u *AuthRequestUpdateOne) SetClaimsGroups(v []string) *AuthRequestUpdateOne { + _u.mutation.SetClaimsGroups(v) + return _u } -// AppendClaimsGroups appends s to the "claims_groups" field. -func (aruo *AuthRequestUpdateOne) AppendClaimsGroups(s []string) *AuthRequestUpdateOne { - aruo.mutation.AppendClaimsGroups(s) - return aruo +// AppendClaimsGroups appends value to the "claims_groups" field. +func (_u *AuthRequestUpdateOne) AppendClaimsGroups(v []string) *AuthRequestUpdateOne { + _u.mutation.AppendClaimsGroups(v) + return _u } // ClearClaimsGroups clears the value of the "claims_groups" field. -func (aruo *AuthRequestUpdateOne) ClearClaimsGroups() *AuthRequestUpdateOne { - aruo.mutation.ClearClaimsGroups() - return aruo +func (_u *AuthRequestUpdateOne) ClearClaimsGroups() *AuthRequestUpdateOne { + _u.mutation.ClearClaimsGroups() + return _u } // SetClaimsPreferredUsername sets the "claims_preferred_username" field. -func (aruo *AuthRequestUpdateOne) SetClaimsPreferredUsername(s string) *AuthRequestUpdateOne { - aruo.mutation.SetClaimsPreferredUsername(s) - return aruo +func (_u *AuthRequestUpdateOne) SetClaimsPreferredUsername(v string) *AuthRequestUpdateOne { + _u.mutation.SetClaimsPreferredUsername(v) + return _u } // SetNillableClaimsPreferredUsername sets the "claims_preferred_username" field if the given value is not nil. -func (aruo *AuthRequestUpdateOne) SetNillableClaimsPreferredUsername(s *string) *AuthRequestUpdateOne { - if s != nil { - aruo.SetClaimsPreferredUsername(*s) +func (_u *AuthRequestUpdateOne) SetNillableClaimsPreferredUsername(v *string) *AuthRequestUpdateOne { + if v != nil { + _u.SetClaimsPreferredUsername(*v) } - return aruo + return _u } // SetConnectorID sets the "connector_id" field. -func (aruo *AuthRequestUpdateOne) SetConnectorID(s string) *AuthRequestUpdateOne { - aruo.mutation.SetConnectorID(s) - return aruo +func (_u *AuthRequestUpdateOne) SetConnectorID(v string) *AuthRequestUpdateOne { + _u.mutation.SetConnectorID(v) + return _u } // SetNillableConnectorID sets the "connector_id" field if the given value is not nil. -func (aruo *AuthRequestUpdateOne) SetNillableConnectorID(s *string) *AuthRequestUpdateOne { - if s != nil { - aruo.SetConnectorID(*s) +func (_u *AuthRequestUpdateOne) SetNillableConnectorID(v *string) *AuthRequestUpdateOne { + if v != nil { + _u.SetConnectorID(*v) } - return aruo + return _u } // SetConnectorData sets the "connector_data" field. -func (aruo *AuthRequestUpdateOne) SetConnectorData(b []byte) *AuthRequestUpdateOne { - aruo.mutation.SetConnectorData(b) - return aruo +func (_u *AuthRequestUpdateOne) SetConnectorData(v []byte) *AuthRequestUpdateOne { + _u.mutation.SetConnectorData(v) + return _u } // ClearConnectorData clears the value of the "connector_data" field. -func (aruo *AuthRequestUpdateOne) ClearConnectorData() *AuthRequestUpdateOne { - aruo.mutation.ClearConnectorData() - return aruo +func (_u *AuthRequestUpdateOne) ClearConnectorData() *AuthRequestUpdateOne { + _u.mutation.ClearConnectorData() + return _u } // SetExpiry sets the "expiry" field. -func (aruo *AuthRequestUpdateOne) SetExpiry(t time.Time) *AuthRequestUpdateOne { - aruo.mutation.SetExpiry(t) - return aruo +func (_u *AuthRequestUpdateOne) SetExpiry(v time.Time) *AuthRequestUpdateOne { + _u.mutation.SetExpiry(v) + return _u } // SetNillableExpiry sets the "expiry" field if the given value is not nil. -func (aruo *AuthRequestUpdateOne) SetNillableExpiry(t *time.Time) *AuthRequestUpdateOne { - if t != nil { - aruo.SetExpiry(*t) +func (_u *AuthRequestUpdateOne) SetNillableExpiry(v *time.Time) *AuthRequestUpdateOne { + if v != nil { + _u.SetExpiry(*v) } - return aruo + return _u } // SetCodeChallenge sets the "code_challenge" field. -func (aruo *AuthRequestUpdateOne) SetCodeChallenge(s string) *AuthRequestUpdateOne { - aruo.mutation.SetCodeChallenge(s) - return aruo +func (_u *AuthRequestUpdateOne) SetCodeChallenge(v string) *AuthRequestUpdateOne { + _u.mutation.SetCodeChallenge(v) + return _u } // SetNillableCodeChallenge sets the "code_challenge" field if the given value is not nil. -func (aruo *AuthRequestUpdateOne) SetNillableCodeChallenge(s *string) *AuthRequestUpdateOne { - if s != nil { - aruo.SetCodeChallenge(*s) +func (_u *AuthRequestUpdateOne) SetNillableCodeChallenge(v *string) *AuthRequestUpdateOne { + if v != nil { + _u.SetCodeChallenge(*v) } - return aruo + return _u } // SetCodeChallengeMethod sets the "code_challenge_method" field. -func (aruo *AuthRequestUpdateOne) SetCodeChallengeMethod(s string) *AuthRequestUpdateOne { - aruo.mutation.SetCodeChallengeMethod(s) - return aruo +func (_u *AuthRequestUpdateOne) SetCodeChallengeMethod(v string) *AuthRequestUpdateOne { + _u.mutation.SetCodeChallengeMethod(v) + return _u } // SetNillableCodeChallengeMethod sets the "code_challenge_method" field if the given value is not nil. -func (aruo *AuthRequestUpdateOne) SetNillableCodeChallengeMethod(s *string) *AuthRequestUpdateOne { - if s != nil { - aruo.SetCodeChallengeMethod(*s) +func (_u *AuthRequestUpdateOne) SetNillableCodeChallengeMethod(v *string) *AuthRequestUpdateOne { + if v != nil { + _u.SetCodeChallengeMethod(*v) } - return aruo + return _u } // SetHmacKey sets the "hmac_key" field. -func (aruo *AuthRequestUpdateOne) SetHmacKey(b []byte) *AuthRequestUpdateOne { - aruo.mutation.SetHmacKey(b) - return aruo +func (_u *AuthRequestUpdateOne) SetHmacKey(v []byte) *AuthRequestUpdateOne { + _u.mutation.SetHmacKey(v) + return _u } // Mutation returns the AuthRequestMutation object of the builder. -func (aruo *AuthRequestUpdateOne) Mutation() *AuthRequestMutation { - return aruo.mutation +func (_u *AuthRequestUpdateOne) Mutation() *AuthRequestMutation { + return _u.mutation } // Where appends a list predicates to the AuthRequestUpdate builder. -func (aruo *AuthRequestUpdateOne) Where(ps ...predicate.AuthRequest) *AuthRequestUpdateOne { - aruo.mutation.Where(ps...) - return aruo +func (_u *AuthRequestUpdateOne) Where(ps ...predicate.AuthRequest) *AuthRequestUpdateOne { + _u.mutation.Where(ps...) + return _u } // Select allows selecting one or more fields (columns) of the returned entity. // The default is selecting all fields defined in the entity schema. -func (aruo *AuthRequestUpdateOne) Select(field string, fields ...string) *AuthRequestUpdateOne { - aruo.fields = append([]string{field}, fields...) - return aruo +func (_u *AuthRequestUpdateOne) Select(field string, fields ...string) *AuthRequestUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u } // Save executes the query and returns the updated AuthRequest entity. -func (aruo *AuthRequestUpdateOne) Save(ctx context.Context) (*AuthRequest, error) { - return withHooks(ctx, aruo.sqlSave, aruo.mutation, aruo.hooks) +func (_u *AuthRequestUpdateOne) Save(ctx context.Context) (*AuthRequest, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) } // SaveX is like Save, but panics if an error occurs. -func (aruo *AuthRequestUpdateOne) SaveX(ctx context.Context) *AuthRequest { - node, err := aruo.Save(ctx) +func (_u *AuthRequestUpdateOne) SaveX(ctx context.Context) *AuthRequest { + node, err := _u.Save(ctx) if err != nil { panic(err) } @@ -774,26 +774,26 @@ func (aruo *AuthRequestUpdateOne) SaveX(ctx context.Context) *AuthRequest { } // Exec executes the query on the entity. -func (aruo *AuthRequestUpdateOne) Exec(ctx context.Context) error { - _, err := aruo.Save(ctx) +func (_u *AuthRequestUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (aruo *AuthRequestUpdateOne) ExecX(ctx context.Context) { - if err := aruo.Exec(ctx); err != nil { +func (_u *AuthRequestUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { panic(err) } } -func (aruo *AuthRequestUpdateOne) sqlSave(ctx context.Context) (_node *AuthRequest, err error) { +func (_u *AuthRequestUpdateOne) sqlSave(ctx context.Context) (_node *AuthRequest, err error) { _spec := sqlgraph.NewUpdateSpec(authrequest.Table, authrequest.Columns, sqlgraph.NewFieldSpec(authrequest.FieldID, field.TypeString)) - id, ok := aruo.mutation.ID() + id, ok := _u.mutation.ID() if !ok { return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "AuthRequest.id" for update`)} } _spec.Node.ID.Value = id - if fields := aruo.fields; len(fields) > 0 { + if fields := _u.fields; len(fields) > 0 { _spec.Node.Columns = make([]string, 0, len(fields)) _spec.Node.Columns = append(_spec.Node.Columns, authrequest.FieldID) for _, f := range fields { @@ -805,104 +805,104 @@ func (aruo *AuthRequestUpdateOne) sqlSave(ctx context.Context) (_node *AuthReque } } } - if ps := aruo.mutation.predicates; len(ps) > 0 { + if ps := _u.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if value, ok := aruo.mutation.ClientID(); ok { + if value, ok := _u.mutation.ClientID(); ok { _spec.SetField(authrequest.FieldClientID, field.TypeString, value) } - if value, ok := aruo.mutation.Scopes(); ok { + if value, ok := _u.mutation.Scopes(); ok { _spec.SetField(authrequest.FieldScopes, field.TypeJSON, value) } - if value, ok := aruo.mutation.AppendedScopes(); ok { + if value, ok := _u.mutation.AppendedScopes(); ok { _spec.AddModifier(func(u *sql.UpdateBuilder) { sqljson.Append(u, authrequest.FieldScopes, value) }) } - if aruo.mutation.ScopesCleared() { + if _u.mutation.ScopesCleared() { _spec.ClearField(authrequest.FieldScopes, field.TypeJSON) } - if value, ok := aruo.mutation.ResponseTypes(); ok { + if value, ok := _u.mutation.ResponseTypes(); ok { _spec.SetField(authrequest.FieldResponseTypes, field.TypeJSON, value) } - if value, ok := aruo.mutation.AppendedResponseTypes(); ok { + if value, ok := _u.mutation.AppendedResponseTypes(); ok { _spec.AddModifier(func(u *sql.UpdateBuilder) { sqljson.Append(u, authrequest.FieldResponseTypes, value) }) } - if aruo.mutation.ResponseTypesCleared() { + if _u.mutation.ResponseTypesCleared() { _spec.ClearField(authrequest.FieldResponseTypes, field.TypeJSON) } - if value, ok := aruo.mutation.RedirectURI(); ok { + if value, ok := _u.mutation.RedirectURI(); ok { _spec.SetField(authrequest.FieldRedirectURI, field.TypeString, value) } - if value, ok := aruo.mutation.Nonce(); ok { + if value, ok := _u.mutation.Nonce(); ok { _spec.SetField(authrequest.FieldNonce, field.TypeString, value) } - if value, ok := aruo.mutation.State(); ok { + if value, ok := _u.mutation.State(); ok { _spec.SetField(authrequest.FieldState, field.TypeString, value) } - if value, ok := aruo.mutation.ForceApprovalPrompt(); ok { + if value, ok := _u.mutation.ForceApprovalPrompt(); ok { _spec.SetField(authrequest.FieldForceApprovalPrompt, field.TypeBool, value) } - if value, ok := aruo.mutation.LoggedIn(); ok { + if value, ok := _u.mutation.LoggedIn(); ok { _spec.SetField(authrequest.FieldLoggedIn, field.TypeBool, value) } - if value, ok := aruo.mutation.ClaimsUserID(); ok { + if value, ok := _u.mutation.ClaimsUserID(); ok { _spec.SetField(authrequest.FieldClaimsUserID, field.TypeString, value) } - if value, ok := aruo.mutation.ClaimsUsername(); ok { + if value, ok := _u.mutation.ClaimsUsername(); ok { _spec.SetField(authrequest.FieldClaimsUsername, field.TypeString, value) } - if value, ok := aruo.mutation.ClaimsEmail(); ok { + if value, ok := _u.mutation.ClaimsEmail(); ok { _spec.SetField(authrequest.FieldClaimsEmail, field.TypeString, value) } - if value, ok := aruo.mutation.ClaimsEmailVerified(); ok { + if value, ok := _u.mutation.ClaimsEmailVerified(); ok { _spec.SetField(authrequest.FieldClaimsEmailVerified, field.TypeBool, value) } - if value, ok := aruo.mutation.ClaimsGroups(); ok { + if value, ok := _u.mutation.ClaimsGroups(); ok { _spec.SetField(authrequest.FieldClaimsGroups, field.TypeJSON, value) } - if value, ok := aruo.mutation.AppendedClaimsGroups(); ok { + if value, ok := _u.mutation.AppendedClaimsGroups(); ok { _spec.AddModifier(func(u *sql.UpdateBuilder) { sqljson.Append(u, authrequest.FieldClaimsGroups, value) }) } - if aruo.mutation.ClaimsGroupsCleared() { + if _u.mutation.ClaimsGroupsCleared() { _spec.ClearField(authrequest.FieldClaimsGroups, field.TypeJSON) } - if value, ok := aruo.mutation.ClaimsPreferredUsername(); ok { + if value, ok := _u.mutation.ClaimsPreferredUsername(); ok { _spec.SetField(authrequest.FieldClaimsPreferredUsername, field.TypeString, value) } - if value, ok := aruo.mutation.ConnectorID(); ok { + if value, ok := _u.mutation.ConnectorID(); ok { _spec.SetField(authrequest.FieldConnectorID, field.TypeString, value) } - if value, ok := aruo.mutation.ConnectorData(); ok { + if value, ok := _u.mutation.ConnectorData(); ok { _spec.SetField(authrequest.FieldConnectorData, field.TypeBytes, value) } - if aruo.mutation.ConnectorDataCleared() { + if _u.mutation.ConnectorDataCleared() { _spec.ClearField(authrequest.FieldConnectorData, field.TypeBytes) } - if value, ok := aruo.mutation.Expiry(); ok { + if value, ok := _u.mutation.Expiry(); ok { _spec.SetField(authrequest.FieldExpiry, field.TypeTime, value) } - if value, ok := aruo.mutation.CodeChallenge(); ok { + if value, ok := _u.mutation.CodeChallenge(); ok { _spec.SetField(authrequest.FieldCodeChallenge, field.TypeString, value) } - if value, ok := aruo.mutation.CodeChallengeMethod(); ok { + if value, ok := _u.mutation.CodeChallengeMethod(); ok { _spec.SetField(authrequest.FieldCodeChallengeMethod, field.TypeString, value) } - if value, ok := aruo.mutation.HmacKey(); ok { + if value, ok := _u.mutation.HmacKey(); ok { _spec.SetField(authrequest.FieldHmacKey, field.TypeBytes, value) } - _node = &AuthRequest{config: aruo.config} + _node = &AuthRequest{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, aruo.driver, _spec); err != nil { + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{authrequest.Label} } else if sqlgraph.IsConstraintError(err) { @@ -910,6 +910,6 @@ func (aruo *AuthRequestUpdateOne) sqlSave(ctx context.Context) (_node *AuthReque } return nil, err } - aruo.mutation.done = true + _u.mutation.done = true return _node, nil } diff --git a/storage/ent/db/client.go b/storage/ent/db/client.go index 822fc3ed6b..4fb28cb3c5 100644 --- a/storage/ent/db/client.go +++ b/storage/ent/db/client.go @@ -333,8 +333,8 @@ func (c *AuthCodeClient) Update() *AuthCodeUpdate { } // UpdateOne returns an update builder for the given entity. -func (c *AuthCodeClient) UpdateOne(ac *AuthCode) *AuthCodeUpdateOne { - mutation := newAuthCodeMutation(c.config, OpUpdateOne, withAuthCode(ac)) +func (c *AuthCodeClient) UpdateOne(_m *AuthCode) *AuthCodeUpdateOne { + mutation := newAuthCodeMutation(c.config, OpUpdateOne, withAuthCode(_m)) return &AuthCodeUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} } @@ -351,8 +351,8 @@ func (c *AuthCodeClient) Delete() *AuthCodeDelete { } // DeleteOne returns a builder for deleting the given entity. -func (c *AuthCodeClient) DeleteOne(ac *AuthCode) *AuthCodeDeleteOne { - return c.DeleteOneID(ac.ID) +func (c *AuthCodeClient) DeleteOne(_m *AuthCode) *AuthCodeDeleteOne { + return c.DeleteOneID(_m.ID) } // DeleteOneID returns a builder for deleting the given entity by its id. @@ -466,8 +466,8 @@ func (c *AuthRequestClient) Update() *AuthRequestUpdate { } // UpdateOne returns an update builder for the given entity. -func (c *AuthRequestClient) UpdateOne(ar *AuthRequest) *AuthRequestUpdateOne { - mutation := newAuthRequestMutation(c.config, OpUpdateOne, withAuthRequest(ar)) +func (c *AuthRequestClient) UpdateOne(_m *AuthRequest) *AuthRequestUpdateOne { + mutation := newAuthRequestMutation(c.config, OpUpdateOne, withAuthRequest(_m)) return &AuthRequestUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} } @@ -484,8 +484,8 @@ func (c *AuthRequestClient) Delete() *AuthRequestDelete { } // DeleteOne returns a builder for deleting the given entity. -func (c *AuthRequestClient) DeleteOne(ar *AuthRequest) *AuthRequestDeleteOne { - return c.DeleteOneID(ar.ID) +func (c *AuthRequestClient) DeleteOne(_m *AuthRequest) *AuthRequestDeleteOne { + return c.DeleteOneID(_m.ID) } // DeleteOneID returns a builder for deleting the given entity by its id. @@ -599,8 +599,8 @@ func (c *ConnectorClient) Update() *ConnectorUpdate { } // UpdateOne returns an update builder for the given entity. -func (c *ConnectorClient) UpdateOne(co *Connector) *ConnectorUpdateOne { - mutation := newConnectorMutation(c.config, OpUpdateOne, withConnector(co)) +func (c *ConnectorClient) UpdateOne(_m *Connector) *ConnectorUpdateOne { + mutation := newConnectorMutation(c.config, OpUpdateOne, withConnector(_m)) return &ConnectorUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} } @@ -617,8 +617,8 @@ func (c *ConnectorClient) Delete() *ConnectorDelete { } // DeleteOne returns a builder for deleting the given entity. -func (c *ConnectorClient) DeleteOne(co *Connector) *ConnectorDeleteOne { - return c.DeleteOneID(co.ID) +func (c *ConnectorClient) DeleteOne(_m *Connector) *ConnectorDeleteOne { + return c.DeleteOneID(_m.ID) } // DeleteOneID returns a builder for deleting the given entity by its id. @@ -732,8 +732,8 @@ func (c *DeviceRequestClient) Update() *DeviceRequestUpdate { } // UpdateOne returns an update builder for the given entity. -func (c *DeviceRequestClient) UpdateOne(dr *DeviceRequest) *DeviceRequestUpdateOne { - mutation := newDeviceRequestMutation(c.config, OpUpdateOne, withDeviceRequest(dr)) +func (c *DeviceRequestClient) UpdateOne(_m *DeviceRequest) *DeviceRequestUpdateOne { + mutation := newDeviceRequestMutation(c.config, OpUpdateOne, withDeviceRequest(_m)) return &DeviceRequestUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} } @@ -750,8 +750,8 @@ func (c *DeviceRequestClient) Delete() *DeviceRequestDelete { } // DeleteOne returns a builder for deleting the given entity. -func (c *DeviceRequestClient) DeleteOne(dr *DeviceRequest) *DeviceRequestDeleteOne { - return c.DeleteOneID(dr.ID) +func (c *DeviceRequestClient) DeleteOne(_m *DeviceRequest) *DeviceRequestDeleteOne { + return c.DeleteOneID(_m.ID) } // DeleteOneID returns a builder for deleting the given entity by its id. @@ -865,8 +865,8 @@ func (c *DeviceTokenClient) Update() *DeviceTokenUpdate { } // UpdateOne returns an update builder for the given entity. -func (c *DeviceTokenClient) UpdateOne(dt *DeviceToken) *DeviceTokenUpdateOne { - mutation := newDeviceTokenMutation(c.config, OpUpdateOne, withDeviceToken(dt)) +func (c *DeviceTokenClient) UpdateOne(_m *DeviceToken) *DeviceTokenUpdateOne { + mutation := newDeviceTokenMutation(c.config, OpUpdateOne, withDeviceToken(_m)) return &DeviceTokenUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} } @@ -883,8 +883,8 @@ func (c *DeviceTokenClient) Delete() *DeviceTokenDelete { } // DeleteOne returns a builder for deleting the given entity. -func (c *DeviceTokenClient) DeleteOne(dt *DeviceToken) *DeviceTokenDeleteOne { - return c.DeleteOneID(dt.ID) +func (c *DeviceTokenClient) DeleteOne(_m *DeviceToken) *DeviceTokenDeleteOne { + return c.DeleteOneID(_m.ID) } // DeleteOneID returns a builder for deleting the given entity by its id. @@ -998,8 +998,8 @@ func (c *KeysClient) Update() *KeysUpdate { } // UpdateOne returns an update builder for the given entity. -func (c *KeysClient) UpdateOne(k *Keys) *KeysUpdateOne { - mutation := newKeysMutation(c.config, OpUpdateOne, withKeys(k)) +func (c *KeysClient) UpdateOne(_m *Keys) *KeysUpdateOne { + mutation := newKeysMutation(c.config, OpUpdateOne, withKeys(_m)) return &KeysUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} } @@ -1016,8 +1016,8 @@ func (c *KeysClient) Delete() *KeysDelete { } // DeleteOne returns a builder for deleting the given entity. -func (c *KeysClient) DeleteOne(k *Keys) *KeysDeleteOne { - return c.DeleteOneID(k.ID) +func (c *KeysClient) DeleteOne(_m *Keys) *KeysDeleteOne { + return c.DeleteOneID(_m.ID) } // DeleteOneID returns a builder for deleting the given entity by its id. @@ -1131,8 +1131,8 @@ func (c *OAuth2ClientClient) Update() *OAuth2ClientUpdate { } // UpdateOne returns an update builder for the given entity. -func (c *OAuth2ClientClient) UpdateOne(o *OAuth2Client) *OAuth2ClientUpdateOne { - mutation := newOAuth2ClientMutation(c.config, OpUpdateOne, withOAuth2Client(o)) +func (c *OAuth2ClientClient) UpdateOne(_m *OAuth2Client) *OAuth2ClientUpdateOne { + mutation := newOAuth2ClientMutation(c.config, OpUpdateOne, withOAuth2Client(_m)) return &OAuth2ClientUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} } @@ -1149,8 +1149,8 @@ func (c *OAuth2ClientClient) Delete() *OAuth2ClientDelete { } // DeleteOne returns a builder for deleting the given entity. -func (c *OAuth2ClientClient) DeleteOne(o *OAuth2Client) *OAuth2ClientDeleteOne { - return c.DeleteOneID(o.ID) +func (c *OAuth2ClientClient) DeleteOne(_m *OAuth2Client) *OAuth2ClientDeleteOne { + return c.DeleteOneID(_m.ID) } // DeleteOneID returns a builder for deleting the given entity by its id. @@ -1264,8 +1264,8 @@ func (c *OfflineSessionClient) Update() *OfflineSessionUpdate { } // UpdateOne returns an update builder for the given entity. -func (c *OfflineSessionClient) UpdateOne(os *OfflineSession) *OfflineSessionUpdateOne { - mutation := newOfflineSessionMutation(c.config, OpUpdateOne, withOfflineSession(os)) +func (c *OfflineSessionClient) UpdateOne(_m *OfflineSession) *OfflineSessionUpdateOne { + mutation := newOfflineSessionMutation(c.config, OpUpdateOne, withOfflineSession(_m)) return &OfflineSessionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} } @@ -1282,8 +1282,8 @@ func (c *OfflineSessionClient) Delete() *OfflineSessionDelete { } // DeleteOne returns a builder for deleting the given entity. -func (c *OfflineSessionClient) DeleteOne(os *OfflineSession) *OfflineSessionDeleteOne { - return c.DeleteOneID(os.ID) +func (c *OfflineSessionClient) DeleteOne(_m *OfflineSession) *OfflineSessionDeleteOne { + return c.DeleteOneID(_m.ID) } // DeleteOneID returns a builder for deleting the given entity by its id. @@ -1397,8 +1397,8 @@ func (c *PasswordClient) Update() *PasswordUpdate { } // UpdateOne returns an update builder for the given entity. -func (c *PasswordClient) UpdateOne(pa *Password) *PasswordUpdateOne { - mutation := newPasswordMutation(c.config, OpUpdateOne, withPassword(pa)) +func (c *PasswordClient) UpdateOne(_m *Password) *PasswordUpdateOne { + mutation := newPasswordMutation(c.config, OpUpdateOne, withPassword(_m)) return &PasswordUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} } @@ -1415,8 +1415,8 @@ func (c *PasswordClient) Delete() *PasswordDelete { } // DeleteOne returns a builder for deleting the given entity. -func (c *PasswordClient) DeleteOne(pa *Password) *PasswordDeleteOne { - return c.DeleteOneID(pa.ID) +func (c *PasswordClient) DeleteOne(_m *Password) *PasswordDeleteOne { + return c.DeleteOneID(_m.ID) } // DeleteOneID returns a builder for deleting the given entity by its id. @@ -1530,8 +1530,8 @@ func (c *RefreshTokenClient) Update() *RefreshTokenUpdate { } // UpdateOne returns an update builder for the given entity. -func (c *RefreshTokenClient) UpdateOne(rt *RefreshToken) *RefreshTokenUpdateOne { - mutation := newRefreshTokenMutation(c.config, OpUpdateOne, withRefreshToken(rt)) +func (c *RefreshTokenClient) UpdateOne(_m *RefreshToken) *RefreshTokenUpdateOne { + mutation := newRefreshTokenMutation(c.config, OpUpdateOne, withRefreshToken(_m)) return &RefreshTokenUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} } @@ -1548,8 +1548,8 @@ func (c *RefreshTokenClient) Delete() *RefreshTokenDelete { } // DeleteOne returns a builder for deleting the given entity. -func (c *RefreshTokenClient) DeleteOne(rt *RefreshToken) *RefreshTokenDeleteOne { - return c.DeleteOneID(rt.ID) +func (c *RefreshTokenClient) DeleteOne(_m *RefreshToken) *RefreshTokenDeleteOne { + return c.DeleteOneID(_m.ID) } // DeleteOneID returns a builder for deleting the given entity by its id. diff --git a/storage/ent/db/connector.go b/storage/ent/db/connector.go index 34c88e31e6..2071d14ebb 100644 --- a/storage/ent/db/connector.go +++ b/storage/ent/db/connector.go @@ -45,7 +45,7 @@ func (*Connector) scanValues(columns []string) ([]any, error) { // assignValues assigns the values that were returned from sql.Rows (after scanning) // to the Connector fields. -func (c *Connector) assignValues(columns []string, values []any) error { +func (_m *Connector) 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) } @@ -55,34 +55,34 @@ func (c *Connector) assignValues(columns []string, values []any) error { if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field id", values[i]) } else if value.Valid { - c.ID = value.String + _m.ID = value.String } case connector.FieldType: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field type", values[i]) } else if value.Valid { - c.Type = value.String + _m.Type = value.String } case connector.FieldName: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field name", values[i]) } else if value.Valid { - c.Name = value.String + _m.Name = value.String } case connector.FieldResourceVersion: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field resource_version", values[i]) } else if value.Valid { - c.ResourceVersion = value.String + _m.ResourceVersion = value.String } case connector.FieldConfig: if value, ok := values[i].(*[]byte); !ok { return fmt.Errorf("unexpected type %T for field config", values[i]) } else if value != nil { - c.Config = *value + _m.Config = *value } default: - c.selectValues.Set(columns[i], values[i]) + _m.selectValues.Set(columns[i], values[i]) } } return nil @@ -90,44 +90,44 @@ func (c *Connector) assignValues(columns []string, values []any) error { // Value returns the ent.Value that was dynamically selected and assigned to the Connector. // This includes values selected through modifiers, order, etc. -func (c *Connector) Value(name string) (ent.Value, error) { - return c.selectValues.Get(name) +func (_m *Connector) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) } // Update returns a builder for updating this Connector. // Note that you need to call Connector.Unwrap() before calling this method if this Connector // was returned from a transaction, and the transaction was committed or rolled back. -func (c *Connector) Update() *ConnectorUpdateOne { - return NewConnectorClient(c.config).UpdateOne(c) +func (_m *Connector) Update() *ConnectorUpdateOne { + return NewConnectorClient(_m.config).UpdateOne(_m) } // Unwrap unwraps the Connector 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 *Connector) Unwrap() *Connector { - _tx, ok := c.config.driver.(*txDriver) +func (_m *Connector) Unwrap() *Connector { + _tx, ok := _m.config.driver.(*txDriver) if !ok { panic("db: Connector is not a transactional entity") } - c.config.driver = _tx.drv - return c + _m.config.driver = _tx.drv + return _m } // String implements the fmt.Stringer. -func (c *Connector) String() string { +func (_m *Connector) String() string { var builder strings.Builder builder.WriteString("Connector(") - builder.WriteString(fmt.Sprintf("id=%v, ", c.ID)) + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) builder.WriteString("type=") - builder.WriteString(c.Type) + builder.WriteString(_m.Type) builder.WriteString(", ") builder.WriteString("name=") - builder.WriteString(c.Name) + builder.WriteString(_m.Name) builder.WriteString(", ") builder.WriteString("resource_version=") - builder.WriteString(c.ResourceVersion) + builder.WriteString(_m.ResourceVersion) builder.WriteString(", ") builder.WriteString("config=") - builder.WriteString(fmt.Sprintf("%v", c.Config)) + builder.WriteString(fmt.Sprintf("%v", _m.Config)) builder.WriteByte(')') return builder.String() } diff --git a/storage/ent/db/connector_create.go b/storage/ent/db/connector_create.go index 5bd4a19fc1..42da769e70 100644 --- a/storage/ent/db/connector_create.go +++ b/storage/ent/db/connector_create.go @@ -20,48 +20,48 @@ type ConnectorCreate struct { } // SetType sets the "type" field. -func (cc *ConnectorCreate) SetType(s string) *ConnectorCreate { - cc.mutation.SetType(s) - return cc +func (_c *ConnectorCreate) SetType(v string) *ConnectorCreate { + _c.mutation.SetType(v) + return _c } // SetName sets the "name" field. -func (cc *ConnectorCreate) SetName(s string) *ConnectorCreate { - cc.mutation.SetName(s) - return cc +func (_c *ConnectorCreate) SetName(v string) *ConnectorCreate { + _c.mutation.SetName(v) + return _c } // SetResourceVersion sets the "resource_version" field. -func (cc *ConnectorCreate) SetResourceVersion(s string) *ConnectorCreate { - cc.mutation.SetResourceVersion(s) - return cc +func (_c *ConnectorCreate) SetResourceVersion(v string) *ConnectorCreate { + _c.mutation.SetResourceVersion(v) + return _c } // SetConfig sets the "config" field. -func (cc *ConnectorCreate) SetConfig(b []byte) *ConnectorCreate { - cc.mutation.SetConfig(b) - return cc +func (_c *ConnectorCreate) SetConfig(v []byte) *ConnectorCreate { + _c.mutation.SetConfig(v) + return _c } // SetID sets the "id" field. -func (cc *ConnectorCreate) SetID(s string) *ConnectorCreate { - cc.mutation.SetID(s) - return cc +func (_c *ConnectorCreate) SetID(v string) *ConnectorCreate { + _c.mutation.SetID(v) + return _c } // Mutation returns the ConnectorMutation object of the builder. -func (cc *ConnectorCreate) Mutation() *ConnectorMutation { - return cc.mutation +func (_c *ConnectorCreate) Mutation() *ConnectorMutation { + return _c.mutation } // Save creates the Connector in the database. -func (cc *ConnectorCreate) Save(ctx context.Context) (*Connector, error) { - return withHooks(ctx, cc.sqlSave, cc.mutation, cc.hooks) +func (_c *ConnectorCreate) Save(ctx context.Context) (*Connector, error) { + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) } // SaveX calls Save and panics if Save returns an error. -func (cc *ConnectorCreate) SaveX(ctx context.Context) *Connector { - v, err := cc.Save(ctx) +func (_c *ConnectorCreate) SaveX(ctx context.Context) *Connector { + v, err := _c.Save(ctx) if err != nil { panic(err) } @@ -69,43 +69,43 @@ func (cc *ConnectorCreate) SaveX(ctx context.Context) *Connector { } // Exec executes the query. -func (cc *ConnectorCreate) Exec(ctx context.Context) error { - _, err := cc.Save(ctx) +func (_c *ConnectorCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (cc *ConnectorCreate) ExecX(ctx context.Context) { - if err := cc.Exec(ctx); err != nil { +func (_c *ConnectorCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { panic(err) } } // check runs all checks and user-defined validators on the builder. -func (cc *ConnectorCreate) check() error { - if _, ok := cc.mutation.GetType(); !ok { +func (_c *ConnectorCreate) check() error { + if _, ok := _c.mutation.GetType(); !ok { return &ValidationError{Name: "type", err: errors.New(`db: missing required field "Connector.type"`)} } - if v, ok := cc.mutation.GetType(); ok { + if v, ok := _c.mutation.GetType(); ok { if err := connector.TypeValidator(v); err != nil { return &ValidationError{Name: "type", err: fmt.Errorf(`db: validator failed for field "Connector.type": %w`, err)} } } - if _, ok := cc.mutation.Name(); !ok { + if _, ok := _c.mutation.Name(); !ok { return &ValidationError{Name: "name", err: errors.New(`db: missing required field "Connector.name"`)} } - if v, ok := cc.mutation.Name(); ok { + if v, ok := _c.mutation.Name(); ok { if err := connector.NameValidator(v); err != nil { return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "Connector.name": %w`, err)} } } - if _, ok := cc.mutation.ResourceVersion(); !ok { + if _, ok := _c.mutation.ResourceVersion(); !ok { return &ValidationError{Name: "resource_version", err: errors.New(`db: missing required field "Connector.resource_version"`)} } - if _, ok := cc.mutation.Config(); !ok { + if _, ok := _c.mutation.Config(); !ok { return &ValidationError{Name: "config", err: errors.New(`db: missing required field "Connector.config"`)} } - if v, ok := cc.mutation.ID(); ok { + if v, ok := _c.mutation.ID(); ok { if err := connector.IDValidator(v); err != nil { return &ValidationError{Name: "id", err: fmt.Errorf(`db: validator failed for field "Connector.id": %w`, err)} } @@ -113,12 +113,12 @@ func (cc *ConnectorCreate) check() error { return nil } -func (cc *ConnectorCreate) sqlSave(ctx context.Context) (*Connector, error) { - if err := cc.check(); err != nil { +func (_c *ConnectorCreate) sqlSave(ctx context.Context) (*Connector, error) { + if err := _c.check(); err != nil { return nil, err } - _node, _spec := cc.createSpec() - if err := sqlgraph.CreateNode(ctx, cc.driver, _spec); err != nil { + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { if sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } @@ -131,33 +131,33 @@ func (cc *ConnectorCreate) sqlSave(ctx context.Context) (*Connector, error) { return nil, fmt.Errorf("unexpected Connector.ID type: %T", _spec.ID.Value) } } - cc.mutation.id = &_node.ID - cc.mutation.done = true + _c.mutation.id = &_node.ID + _c.mutation.done = true return _node, nil } -func (cc *ConnectorCreate) createSpec() (*Connector, *sqlgraph.CreateSpec) { +func (_c *ConnectorCreate) createSpec() (*Connector, *sqlgraph.CreateSpec) { var ( - _node = &Connector{config: cc.config} + _node = &Connector{config: _c.config} _spec = sqlgraph.NewCreateSpec(connector.Table, sqlgraph.NewFieldSpec(connector.FieldID, field.TypeString)) ) - if id, ok := cc.mutation.ID(); ok { + if id, ok := _c.mutation.ID(); ok { _node.ID = id _spec.ID.Value = id } - if value, ok := cc.mutation.GetType(); ok { + if value, ok := _c.mutation.GetType(); ok { _spec.SetField(connector.FieldType, field.TypeString, value) _node.Type = value } - if value, ok := cc.mutation.Name(); ok { + if value, ok := _c.mutation.Name(); ok { _spec.SetField(connector.FieldName, field.TypeString, value) _node.Name = value } - if value, ok := cc.mutation.ResourceVersion(); ok { + if value, ok := _c.mutation.ResourceVersion(); ok { _spec.SetField(connector.FieldResourceVersion, field.TypeString, value) _node.ResourceVersion = value } - if value, ok := cc.mutation.Config(); ok { + if value, ok := _c.mutation.Config(); ok { _spec.SetField(connector.FieldConfig, field.TypeBytes, value) _node.Config = value } @@ -172,16 +172,16 @@ type ConnectorCreateBulk struct { } // Save creates the Connector entities in the database. -func (ccb *ConnectorCreateBulk) Save(ctx context.Context) ([]*Connector, error) { - if ccb.err != nil { - return nil, ccb.err - } - specs := make([]*sqlgraph.CreateSpec, len(ccb.builders)) - nodes := make([]*Connector, len(ccb.builders)) - mutators := make([]Mutator, len(ccb.builders)) - for i := range ccb.builders { +func (_c *ConnectorCreateBulk) Save(ctx context.Context) ([]*Connector, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Connector, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { func(i int, root context.Context) { - builder := ccb.builders[i] + builder := _c.builders[i] var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { mutation, ok := m.(*ConnectorMutation) if !ok { @@ -194,11 +194,11 @@ func (ccb *ConnectorCreateBulk) Save(ctx context.Context) ([]*Connector, error) 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) + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, ccb.driver, spec); err != nil { + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { if sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } @@ -218,7 +218,7 @@ func (ccb *ConnectorCreateBulk) Save(ctx context.Context) ([]*Connector, error) }(i, ctx) } if len(mutators) > 0 { - if _, err := mutators[0].Mutate(ctx, ccb.builders[0].mutation); err != nil { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { return nil, err } } @@ -226,8 +226,8 @@ func (ccb *ConnectorCreateBulk) Save(ctx context.Context) ([]*Connector, error) } // SaveX is like Save, but panics if an error occurs. -func (ccb *ConnectorCreateBulk) SaveX(ctx context.Context) []*Connector { - v, err := ccb.Save(ctx) +func (_c *ConnectorCreateBulk) SaveX(ctx context.Context) []*Connector { + v, err := _c.Save(ctx) if err != nil { panic(err) } @@ -235,14 +235,14 @@ func (ccb *ConnectorCreateBulk) SaveX(ctx context.Context) []*Connector { } // Exec executes the query. -func (ccb *ConnectorCreateBulk) Exec(ctx context.Context) error { - _, err := ccb.Save(ctx) +func (_c *ConnectorCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (ccb *ConnectorCreateBulk) ExecX(ctx context.Context) { - if err := ccb.Exec(ctx); err != nil { +func (_c *ConnectorCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { panic(err) } } diff --git a/storage/ent/db/connector_delete.go b/storage/ent/db/connector_delete.go index f7f3ed1e0f..4290b8db03 100644 --- a/storage/ent/db/connector_delete.go +++ b/storage/ent/db/connector_delete.go @@ -20,56 +20,56 @@ type ConnectorDelete struct { } // Where appends a list predicates to the ConnectorDelete builder. -func (cd *ConnectorDelete) Where(ps ...predicate.Connector) *ConnectorDelete { - cd.mutation.Where(ps...) - return cd +func (_d *ConnectorDelete) Where(ps ...predicate.Connector) *ConnectorDelete { + _d.mutation.Where(ps...) + return _d } // Exec executes the deletion query and returns how many vertices were deleted. -func (cd *ConnectorDelete) Exec(ctx context.Context) (int, error) { - return withHooks(ctx, cd.sqlExec, cd.mutation, cd.hooks) +func (_d *ConnectorDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) } // ExecX is like Exec, but panics if an error occurs. -func (cd *ConnectorDelete) ExecX(ctx context.Context) int { - n, err := cd.Exec(ctx) +func (_d *ConnectorDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) if err != nil { panic(err) } return n } -func (cd *ConnectorDelete) sqlExec(ctx context.Context) (int, error) { +func (_d *ConnectorDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(connector.Table, sqlgraph.NewFieldSpec(connector.FieldID, field.TypeString)) - if ps := cd.mutation.predicates; len(ps) > 0 { + if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - affected, err := sqlgraph.DeleteNodes(ctx, cd.driver, _spec) + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) if err != nil && sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } - cd.mutation.done = true + _d.mutation.done = true return affected, err } // ConnectorDeleteOne is the builder for deleting a single Connector entity. type ConnectorDeleteOne struct { - cd *ConnectorDelete + _d *ConnectorDelete } // Where appends a list predicates to the ConnectorDelete builder. -func (cdo *ConnectorDeleteOne) Where(ps ...predicate.Connector) *ConnectorDeleteOne { - cdo.cd.mutation.Where(ps...) - return cdo +func (_d *ConnectorDeleteOne) Where(ps ...predicate.Connector) *ConnectorDeleteOne { + _d._d.mutation.Where(ps...) + return _d } // Exec executes the deletion query. -func (cdo *ConnectorDeleteOne) Exec(ctx context.Context) error { - n, err := cdo.cd.Exec(ctx) +func (_d *ConnectorDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) switch { case err != nil: return err @@ -81,8 +81,8 @@ func (cdo *ConnectorDeleteOne) Exec(ctx context.Context) error { } // ExecX is like Exec, but panics if an error occurs. -func (cdo *ConnectorDeleteOne) ExecX(ctx context.Context) { - if err := cdo.Exec(ctx); err != nil { +func (_d *ConnectorDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { panic(err) } } diff --git a/storage/ent/db/connector_query.go b/storage/ent/db/connector_query.go index 35eae22a91..9f5e5dc2df 100644 --- a/storage/ent/db/connector_query.go +++ b/storage/ent/db/connector_query.go @@ -28,40 +28,40 @@ type ConnectorQuery struct { } // Where adds a new predicate for the ConnectorQuery builder. -func (cq *ConnectorQuery) Where(ps ...predicate.Connector) *ConnectorQuery { - cq.predicates = append(cq.predicates, ps...) - return cq +func (_q *ConnectorQuery) Where(ps ...predicate.Connector) *ConnectorQuery { + _q.predicates = append(_q.predicates, ps...) + return _q } // Limit the number of records to be returned by this query. -func (cq *ConnectorQuery) Limit(limit int) *ConnectorQuery { - cq.ctx.Limit = &limit - return cq +func (_q *ConnectorQuery) Limit(limit int) *ConnectorQuery { + _q.ctx.Limit = &limit + return _q } // Offset to start from. -func (cq *ConnectorQuery) Offset(offset int) *ConnectorQuery { - cq.ctx.Offset = &offset - return cq +func (_q *ConnectorQuery) Offset(offset int) *ConnectorQuery { + _q.ctx.Offset = &offset + return _q } // Unique configures the query builder to filter duplicate records on query. // By default, unique is set to true, and can be disabled using this method. -func (cq *ConnectorQuery) Unique(unique bool) *ConnectorQuery { - cq.ctx.Unique = &unique - return cq +func (_q *ConnectorQuery) Unique(unique bool) *ConnectorQuery { + _q.ctx.Unique = &unique + return _q } // Order specifies how the records should be ordered. -func (cq *ConnectorQuery) Order(o ...connector.OrderOption) *ConnectorQuery { - cq.order = append(cq.order, o...) - return cq +func (_q *ConnectorQuery) Order(o ...connector.OrderOption) *ConnectorQuery { + _q.order = append(_q.order, o...) + return _q } // First returns the first Connector entity from the query. // Returns a *NotFoundError when no Connector was found. -func (cq *ConnectorQuery) First(ctx context.Context) (*Connector, error) { - nodes, err := cq.Limit(1).All(setContextOp(ctx, cq.ctx, ent.OpQueryFirst)) +func (_q *ConnectorQuery) First(ctx context.Context) (*Connector, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) if err != nil { return nil, err } @@ -72,8 +72,8 @@ func (cq *ConnectorQuery) First(ctx context.Context) (*Connector, error) { } // FirstX is like First, but panics if an error occurs. -func (cq *ConnectorQuery) FirstX(ctx context.Context) *Connector { - node, err := cq.First(ctx) +func (_q *ConnectorQuery) FirstX(ctx context.Context) *Connector { + node, err := _q.First(ctx) if err != nil && !IsNotFound(err) { panic(err) } @@ -82,9 +82,9 @@ func (cq *ConnectorQuery) FirstX(ctx context.Context) *Connector { // FirstID returns the first Connector ID from the query. // Returns a *NotFoundError when no Connector ID was found. -func (cq *ConnectorQuery) FirstID(ctx context.Context) (id string, err error) { +func (_q *ConnectorQuery) FirstID(ctx context.Context) (id string, err error) { var ids []string - if ids, err = cq.Limit(1).IDs(setContextOp(ctx, cq.ctx, ent.OpQueryFirstID)); err != nil { + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { return } if len(ids) == 0 { @@ -95,8 +95,8 @@ func (cq *ConnectorQuery) FirstID(ctx context.Context) (id string, err error) { } // FirstIDX is like FirstID, but panics if an error occurs. -func (cq *ConnectorQuery) FirstIDX(ctx context.Context) string { - id, err := cq.FirstID(ctx) +func (_q *ConnectorQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) if err != nil && !IsNotFound(err) { panic(err) } @@ -106,8 +106,8 @@ func (cq *ConnectorQuery) FirstIDX(ctx context.Context) string { // Only returns a single Connector entity found by the query, ensuring it only returns one. // Returns a *NotSingularError when more than one Connector entity is found. // Returns a *NotFoundError when no Connector entities are found. -func (cq *ConnectorQuery) Only(ctx context.Context) (*Connector, error) { - nodes, err := cq.Limit(2).All(setContextOp(ctx, cq.ctx, ent.OpQueryOnly)) +func (_q *ConnectorQuery) Only(ctx context.Context) (*Connector, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) if err != nil { return nil, err } @@ -122,8 +122,8 @@ func (cq *ConnectorQuery) Only(ctx context.Context) (*Connector, error) { } // OnlyX is like Only, but panics if an error occurs. -func (cq *ConnectorQuery) OnlyX(ctx context.Context) *Connector { - node, err := cq.Only(ctx) +func (_q *ConnectorQuery) OnlyX(ctx context.Context) *Connector { + node, err := _q.Only(ctx) if err != nil { panic(err) } @@ -133,9 +133,9 @@ func (cq *ConnectorQuery) OnlyX(ctx context.Context) *Connector { // OnlyID is like Only, but returns the only Connector ID in the query. // Returns a *NotSingularError when more than one Connector ID is found. // Returns a *NotFoundError when no entities are found. -func (cq *ConnectorQuery) OnlyID(ctx context.Context) (id string, err error) { +func (_q *ConnectorQuery) OnlyID(ctx context.Context) (id string, err error) { var ids []string - if ids, err = cq.Limit(2).IDs(setContextOp(ctx, cq.ctx, ent.OpQueryOnlyID)); err != nil { + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { return } switch len(ids) { @@ -150,8 +150,8 @@ func (cq *ConnectorQuery) OnlyID(ctx context.Context) (id string, err error) { } // OnlyIDX is like OnlyID, but panics if an error occurs. -func (cq *ConnectorQuery) OnlyIDX(ctx context.Context) string { - id, err := cq.OnlyID(ctx) +func (_q *ConnectorQuery) OnlyIDX(ctx context.Context) string { + id, err := _q.OnlyID(ctx) if err != nil { panic(err) } @@ -159,18 +159,18 @@ func (cq *ConnectorQuery) OnlyIDX(ctx context.Context) string { } // All executes the query and returns a list of Connectors. -func (cq *ConnectorQuery) All(ctx context.Context) ([]*Connector, error) { - ctx = setContextOp(ctx, cq.ctx, ent.OpQueryAll) - if err := cq.prepareQuery(ctx); err != nil { +func (_q *ConnectorQuery) All(ctx context.Context) ([]*Connector, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { return nil, err } qr := querierAll[[]*Connector, *ConnectorQuery]() - return withInterceptors[[]*Connector](ctx, cq, qr, cq.inters) + return withInterceptors[[]*Connector](ctx, _q, qr, _q.inters) } // AllX is like All, but panics if an error occurs. -func (cq *ConnectorQuery) AllX(ctx context.Context) []*Connector { - nodes, err := cq.All(ctx) +func (_q *ConnectorQuery) AllX(ctx context.Context) []*Connector { + nodes, err := _q.All(ctx) if err != nil { panic(err) } @@ -178,20 +178,20 @@ func (cq *ConnectorQuery) AllX(ctx context.Context) []*Connector { } // IDs executes the query and returns a list of Connector IDs. -func (cq *ConnectorQuery) IDs(ctx context.Context) (ids []string, err error) { - if cq.ctx.Unique == nil && cq.path != nil { - cq.Unique(true) +func (_q *ConnectorQuery) IDs(ctx context.Context) (ids []string, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) } - ctx = setContextOp(ctx, cq.ctx, ent.OpQueryIDs) - if err = cq.Select(connector.FieldID).Scan(ctx, &ids); err != nil { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(connector.FieldID).Scan(ctx, &ids); err != nil { return nil, err } return ids, nil } // IDsX is like IDs, but panics if an error occurs. -func (cq *ConnectorQuery) IDsX(ctx context.Context) []string { - ids, err := cq.IDs(ctx) +func (_q *ConnectorQuery) IDsX(ctx context.Context) []string { + ids, err := _q.IDs(ctx) if err != nil { panic(err) } @@ -199,17 +199,17 @@ func (cq *ConnectorQuery) IDsX(ctx context.Context) []string { } // Count returns the count of the given query. -func (cq *ConnectorQuery) Count(ctx context.Context) (int, error) { - ctx = setContextOp(ctx, cq.ctx, ent.OpQueryCount) - if err := cq.prepareQuery(ctx); err != nil { +func (_q *ConnectorQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { return 0, err } - return withInterceptors[int](ctx, cq, querierCount[*ConnectorQuery](), cq.inters) + return withInterceptors[int](ctx, _q, querierCount[*ConnectorQuery](), _q.inters) } // CountX is like Count, but panics if an error occurs. -func (cq *ConnectorQuery) CountX(ctx context.Context) int { - count, err := cq.Count(ctx) +func (_q *ConnectorQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) if err != nil { panic(err) } @@ -217,9 +217,9 @@ func (cq *ConnectorQuery) CountX(ctx context.Context) int { } // Exist returns true if the query has elements in the graph. -func (cq *ConnectorQuery) Exist(ctx context.Context) (bool, error) { - ctx = setContextOp(ctx, cq.ctx, ent.OpQueryExist) - switch _, err := cq.FirstID(ctx); { +func (_q *ConnectorQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { case IsNotFound(err): return false, nil case err != nil: @@ -230,8 +230,8 @@ func (cq *ConnectorQuery) Exist(ctx context.Context) (bool, error) { } // ExistX is like Exist, but panics if an error occurs. -func (cq *ConnectorQuery) ExistX(ctx context.Context) bool { - exist, err := cq.Exist(ctx) +func (_q *ConnectorQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) if err != nil { panic(err) } @@ -240,19 +240,19 @@ func (cq *ConnectorQuery) ExistX(ctx context.Context) bool { // Clone returns a duplicate of the ConnectorQuery 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 *ConnectorQuery) Clone() *ConnectorQuery { - if cq == nil { +func (_q *ConnectorQuery) Clone() *ConnectorQuery { + if _q == nil { return nil } return &ConnectorQuery{ - config: cq.config, - ctx: cq.ctx.Clone(), - order: append([]connector.OrderOption{}, cq.order...), - inters: append([]Interceptor{}, cq.inters...), - predicates: append([]predicate.Connector{}, cq.predicates...), + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]connector.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Connector{}, _q.predicates...), // clone intermediate query. - sql: cq.sql.Clone(), - path: cq.path, + sql: _q.sql.Clone(), + path: _q.path, } } @@ -270,10 +270,10 @@ func (cq *ConnectorQuery) Clone() *ConnectorQuery { // GroupBy(connector.FieldType). // Aggregate(db.Count()). // Scan(ctx, &v) -func (cq *ConnectorQuery) GroupBy(field string, fields ...string) *ConnectorGroupBy { - cq.ctx.Fields = append([]string{field}, fields...) - grbuild := &ConnectorGroupBy{build: cq} - grbuild.flds = &cq.ctx.Fields +func (_q *ConnectorQuery) GroupBy(field string, fields ...string) *ConnectorGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &ConnectorGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields grbuild.label = connector.Label grbuild.scan = grbuild.Scan return grbuild @@ -291,62 +291,62 @@ func (cq *ConnectorQuery) GroupBy(field string, fields ...string) *ConnectorGrou // client.Connector.Query(). // Select(connector.FieldType). // Scan(ctx, &v) -func (cq *ConnectorQuery) Select(fields ...string) *ConnectorSelect { - cq.ctx.Fields = append(cq.ctx.Fields, fields...) - sbuild := &ConnectorSelect{ConnectorQuery: cq} +func (_q *ConnectorQuery) Select(fields ...string) *ConnectorSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &ConnectorSelect{ConnectorQuery: _q} sbuild.label = connector.Label - sbuild.flds, sbuild.scan = &cq.ctx.Fields, sbuild.Scan + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan return sbuild } // Aggregate returns a ConnectorSelect configured with the given aggregations. -func (cq *ConnectorQuery) Aggregate(fns ...AggregateFunc) *ConnectorSelect { - return cq.Select().Aggregate(fns...) +func (_q *ConnectorQuery) Aggregate(fns ...AggregateFunc) *ConnectorSelect { + return _q.Select().Aggregate(fns...) } -func (cq *ConnectorQuery) prepareQuery(ctx context.Context) error { - for _, inter := range cq.inters { +func (_q *ConnectorQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { if inter == nil { return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)") } if trv, ok := inter.(Traverser); ok { - if err := trv.Traverse(ctx, cq); err != nil { + if err := trv.Traverse(ctx, _q); err != nil { return err } } } - for _, f := range cq.ctx.Fields { + for _, f := range _q.ctx.Fields { if !connector.ValidColumn(f) { return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} } } - if cq.path != nil { - prev, err := cq.path(ctx) + if _q.path != nil { + prev, err := _q.path(ctx) if err != nil { return err } - cq.sql = prev + _q.sql = prev } return nil } -func (cq *ConnectorQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Connector, error) { +func (_q *ConnectorQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Connector, error) { var ( nodes = []*Connector{} - _spec = cq.querySpec() + _spec = _q.querySpec() ) _spec.ScanValues = func(columns []string) ([]any, error) { return (*Connector).scanValues(nil, columns) } _spec.Assign = func(columns []string, values []any) error { - node := &Connector{config: cq.config} + node := &Connector{config: _q.config} nodes = append(nodes, node) return node.assignValues(columns, values) } for i := range hooks { hooks[i](ctx, _spec) } - if err := sqlgraph.QueryNodes(ctx, cq.driver, _spec); err != nil { + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { return nil, err } if len(nodes) == 0 { @@ -355,24 +355,24 @@ func (cq *ConnectorQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Co return nodes, nil } -func (cq *ConnectorQuery) sqlCount(ctx context.Context) (int, error) { - _spec := cq.querySpec() - _spec.Node.Columns = cq.ctx.Fields - if len(cq.ctx.Fields) > 0 { - _spec.Unique = cq.ctx.Unique != nil && *cq.ctx.Unique +func (_q *ConnectorQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique } - return sqlgraph.CountNodes(ctx, cq.driver, _spec) + return sqlgraph.CountNodes(ctx, _q.driver, _spec) } -func (cq *ConnectorQuery) querySpec() *sqlgraph.QuerySpec { +func (_q *ConnectorQuery) querySpec() *sqlgraph.QuerySpec { _spec := sqlgraph.NewQuerySpec(connector.Table, connector.Columns, sqlgraph.NewFieldSpec(connector.FieldID, field.TypeString)) - _spec.From = cq.sql - if unique := cq.ctx.Unique; unique != nil { + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { _spec.Unique = *unique - } else if cq.path != nil { + } else if _q.path != nil { _spec.Unique = true } - if fields := cq.ctx.Fields; len(fields) > 0 { + if fields := _q.ctx.Fields; len(fields) > 0 { _spec.Node.Columns = make([]string, 0, len(fields)) _spec.Node.Columns = append(_spec.Node.Columns, connector.FieldID) for i := range fields { @@ -381,20 +381,20 @@ func (cq *ConnectorQuery) querySpec() *sqlgraph.QuerySpec { } } } - if ps := cq.predicates; len(ps) > 0 { + if ps := _q.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if limit := cq.ctx.Limit; limit != nil { + if limit := _q.ctx.Limit; limit != nil { _spec.Limit = *limit } - if offset := cq.ctx.Offset; offset != nil { + if offset := _q.ctx.Offset; offset != nil { _spec.Offset = *offset } - if ps := cq.order; len(ps) > 0 { + if ps := _q.order; len(ps) > 0 { _spec.Order = func(selector *sql.Selector) { for i := range ps { ps[i](selector) @@ -404,33 +404,33 @@ func (cq *ConnectorQuery) querySpec() *sqlgraph.QuerySpec { return _spec } -func (cq *ConnectorQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(cq.driver.Dialect()) +func (_q *ConnectorQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) t1 := builder.Table(connector.Table) - columns := cq.ctx.Fields + columns := _q.ctx.Fields if len(columns) == 0 { columns = connector.Columns } selector := builder.Select(t1.Columns(columns...)...).From(t1) - if cq.sql != nil { - selector = cq.sql + if _q.sql != nil { + selector = _q.sql selector.Select(selector.Columns(columns...)...) } - if cq.ctx.Unique != nil && *cq.ctx.Unique { + if _q.ctx.Unique != nil && *_q.ctx.Unique { selector.Distinct() } - for _, p := range cq.predicates { + for _, p := range _q.predicates { p(selector) } - for _, p := range cq.order { + for _, p := range _q.order { p(selector) } - if offset := cq.ctx.Offset; offset != nil { + if offset := _q.ctx.Offset; offset != nil { // limit is mandatory for offset clause. We start // with default value, and override it below if needed. selector.Offset(*offset).Limit(math.MaxInt32) } - if limit := cq.ctx.Limit; limit != nil { + if limit := _q.ctx.Limit; limit != nil { selector.Limit(*limit) } return selector @@ -443,41 +443,41 @@ type ConnectorGroupBy struct { } // Aggregate adds the given aggregation functions to the group-by query. -func (cgb *ConnectorGroupBy) Aggregate(fns ...AggregateFunc) *ConnectorGroupBy { - cgb.fns = append(cgb.fns, fns...) - return cgb +func (_g *ConnectorGroupBy) Aggregate(fns ...AggregateFunc) *ConnectorGroupBy { + _g.fns = append(_g.fns, fns...) + return _g } // Scan applies the selector query and scans the result into the given value. -func (cgb *ConnectorGroupBy) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, cgb.build.ctx, ent.OpQueryGroupBy) - if err := cgb.build.prepareQuery(ctx); err != nil { +func (_g *ConnectorGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { return err } - return scanWithInterceptors[*ConnectorQuery, *ConnectorGroupBy](ctx, cgb.build, cgb, cgb.build.inters, v) + return scanWithInterceptors[*ConnectorQuery, *ConnectorGroupBy](ctx, _g.build, _g, _g.build.inters, v) } -func (cgb *ConnectorGroupBy) sqlScan(ctx context.Context, root *ConnectorQuery, v any) error { +func (_g *ConnectorGroupBy) sqlScan(ctx context.Context, root *ConnectorQuery, v any) error { selector := root.sqlQuery(ctx).Select() - aggregation := make([]string, 0, len(cgb.fns)) - for _, fn := range cgb.fns { + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { aggregation = append(aggregation, fn(selector)) } if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(*cgb.flds)+len(cgb.fns)) - for _, f := range *cgb.flds { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { columns = append(columns, selector.C(f)) } columns = append(columns, aggregation...) selector.Select(columns...) } - selector.GroupBy(selector.Columns(*cgb.flds...)...) + selector.GroupBy(selector.Columns(*_g.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 { + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() @@ -491,27 +491,27 @@ type ConnectorSelect struct { } // Aggregate adds the given aggregation functions to the selector query. -func (cs *ConnectorSelect) Aggregate(fns ...AggregateFunc) *ConnectorSelect { - cs.fns = append(cs.fns, fns...) - return cs +func (_s *ConnectorSelect) Aggregate(fns ...AggregateFunc) *ConnectorSelect { + _s.fns = append(_s.fns, fns...) + return _s } // Scan applies the selector query and scans the result into the given value. -func (cs *ConnectorSelect) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, cs.ctx, ent.OpQuerySelect) - if err := cs.prepareQuery(ctx); err != nil { +func (_s *ConnectorSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { return err } - return scanWithInterceptors[*ConnectorQuery, *ConnectorSelect](ctx, cs.ConnectorQuery, cs, cs.inters, v) + return scanWithInterceptors[*ConnectorQuery, *ConnectorSelect](ctx, _s.ConnectorQuery, _s, _s.inters, v) } -func (cs *ConnectorSelect) sqlScan(ctx context.Context, root *ConnectorQuery, v any) error { +func (_s *ConnectorSelect) sqlScan(ctx context.Context, root *ConnectorQuery, v any) error { selector := root.sqlQuery(ctx) - aggregation := make([]string, 0, len(cs.fns)) - for _, fn := range cs.fns { + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { aggregation = append(aggregation, fn(selector)) } - switch n := len(*cs.selector.flds); { + switch n := len(*_s.selector.flds); { case n == 0 && len(aggregation) > 0: selector.Select(aggregation...) case n != 0 && len(aggregation) > 0: @@ -519,7 +519,7 @@ func (cs *ConnectorSelect) sqlScan(ctx context.Context, root *ConnectorQuery, v } rows := &sql.Rows{} query, args := selector.Query() - if err := cs.driver.Query(ctx, query, args, rows); err != nil { + if err := _s.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() diff --git a/storage/ent/db/connector_update.go b/storage/ent/db/connector_update.go index 71b5d25d71..bbcfd5654c 100644 --- a/storage/ent/db/connector_update.go +++ b/storage/ent/db/connector_update.go @@ -22,72 +22,72 @@ type ConnectorUpdate struct { } // Where appends a list predicates to the ConnectorUpdate builder. -func (cu *ConnectorUpdate) Where(ps ...predicate.Connector) *ConnectorUpdate { - cu.mutation.Where(ps...) - return cu +func (_u *ConnectorUpdate) Where(ps ...predicate.Connector) *ConnectorUpdate { + _u.mutation.Where(ps...) + return _u } // SetType sets the "type" field. -func (cu *ConnectorUpdate) SetType(s string) *ConnectorUpdate { - cu.mutation.SetType(s) - return cu +func (_u *ConnectorUpdate) SetType(v string) *ConnectorUpdate { + _u.mutation.SetType(v) + return _u } // SetNillableType sets the "type" field if the given value is not nil. -func (cu *ConnectorUpdate) SetNillableType(s *string) *ConnectorUpdate { - if s != nil { - cu.SetType(*s) +func (_u *ConnectorUpdate) SetNillableType(v *string) *ConnectorUpdate { + if v != nil { + _u.SetType(*v) } - return cu + return _u } // SetName sets the "name" field. -func (cu *ConnectorUpdate) SetName(s string) *ConnectorUpdate { - cu.mutation.SetName(s) - return cu +func (_u *ConnectorUpdate) SetName(v string) *ConnectorUpdate { + _u.mutation.SetName(v) + return _u } // SetNillableName sets the "name" field if the given value is not nil. -func (cu *ConnectorUpdate) SetNillableName(s *string) *ConnectorUpdate { - if s != nil { - cu.SetName(*s) +func (_u *ConnectorUpdate) SetNillableName(v *string) *ConnectorUpdate { + if v != nil { + _u.SetName(*v) } - return cu + return _u } // SetResourceVersion sets the "resource_version" field. -func (cu *ConnectorUpdate) SetResourceVersion(s string) *ConnectorUpdate { - cu.mutation.SetResourceVersion(s) - return cu +func (_u *ConnectorUpdate) SetResourceVersion(v string) *ConnectorUpdate { + _u.mutation.SetResourceVersion(v) + return _u } // SetNillableResourceVersion sets the "resource_version" field if the given value is not nil. -func (cu *ConnectorUpdate) SetNillableResourceVersion(s *string) *ConnectorUpdate { - if s != nil { - cu.SetResourceVersion(*s) +func (_u *ConnectorUpdate) SetNillableResourceVersion(v *string) *ConnectorUpdate { + if v != nil { + _u.SetResourceVersion(*v) } - return cu + return _u } // SetConfig sets the "config" field. -func (cu *ConnectorUpdate) SetConfig(b []byte) *ConnectorUpdate { - cu.mutation.SetConfig(b) - return cu +func (_u *ConnectorUpdate) SetConfig(v []byte) *ConnectorUpdate { + _u.mutation.SetConfig(v) + return _u } // Mutation returns the ConnectorMutation object of the builder. -func (cu *ConnectorUpdate) Mutation() *ConnectorMutation { - return cu.mutation +func (_u *ConnectorUpdate) Mutation() *ConnectorMutation { + return _u.mutation } // Save executes the query and returns the number of nodes affected by the update operation. -func (cu *ConnectorUpdate) Save(ctx context.Context) (int, error) { - return withHooks(ctx, cu.sqlSave, cu.mutation, cu.hooks) +func (_u *ConnectorUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) } // SaveX is like Save, but panics if an error occurs. -func (cu *ConnectorUpdate) SaveX(ctx context.Context) int { - affected, err := cu.Save(ctx) +func (_u *ConnectorUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) if err != nil { panic(err) } @@ -95,26 +95,26 @@ func (cu *ConnectorUpdate) SaveX(ctx context.Context) int { } // Exec executes the query. -func (cu *ConnectorUpdate) Exec(ctx context.Context) error { - _, err := cu.Save(ctx) +func (_u *ConnectorUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (cu *ConnectorUpdate) ExecX(ctx context.Context) { - if err := cu.Exec(ctx); err != nil { +func (_u *ConnectorUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { panic(err) } } // check runs all checks and user-defined validators on the builder. -func (cu *ConnectorUpdate) check() error { - if v, ok := cu.mutation.GetType(); ok { +func (_u *ConnectorUpdate) check() error { + if v, ok := _u.mutation.GetType(); ok { if err := connector.TypeValidator(v); err != nil { return &ValidationError{Name: "type", err: fmt.Errorf(`db: validator failed for field "Connector.type": %w`, err)} } } - if v, ok := cu.mutation.Name(); ok { + if v, ok := _u.mutation.Name(); ok { if err := connector.NameValidator(v); err != nil { return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "Connector.name": %w`, err)} } @@ -122,31 +122,31 @@ func (cu *ConnectorUpdate) check() error { return nil } -func (cu *ConnectorUpdate) sqlSave(ctx context.Context) (n int, err error) { - if err := cu.check(); err != nil { - return n, err +func (_u *ConnectorUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err } _spec := sqlgraph.NewUpdateSpec(connector.Table, connector.Columns, sqlgraph.NewFieldSpec(connector.FieldID, field.TypeString)) - if ps := cu.mutation.predicates; len(ps) > 0 { + if ps := _u.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if value, ok := cu.mutation.GetType(); ok { + if value, ok := _u.mutation.GetType(); ok { _spec.SetField(connector.FieldType, field.TypeString, value) } - if value, ok := cu.mutation.Name(); ok { + if value, ok := _u.mutation.Name(); ok { _spec.SetField(connector.FieldName, field.TypeString, value) } - if value, ok := cu.mutation.ResourceVersion(); ok { + if value, ok := _u.mutation.ResourceVersion(); ok { _spec.SetField(connector.FieldResourceVersion, field.TypeString, value) } - if value, ok := cu.mutation.Config(); ok { + if value, ok := _u.mutation.Config(); ok { _spec.SetField(connector.FieldConfig, field.TypeBytes, value) } - if n, err = sqlgraph.UpdateNodes(ctx, cu.driver, _spec); err != nil { + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{connector.Label} } else if sqlgraph.IsConstraintError(err) { @@ -154,8 +154,8 @@ func (cu *ConnectorUpdate) sqlSave(ctx context.Context) (n int, err error) { } return 0, err } - cu.mutation.done = true - return n, nil + _u.mutation.done = true + return _node, nil } // ConnectorUpdateOne is the builder for updating a single Connector entity. @@ -167,79 +167,79 @@ type ConnectorUpdateOne struct { } // SetType sets the "type" field. -func (cuo *ConnectorUpdateOne) SetType(s string) *ConnectorUpdateOne { - cuo.mutation.SetType(s) - return cuo +func (_u *ConnectorUpdateOne) SetType(v string) *ConnectorUpdateOne { + _u.mutation.SetType(v) + return _u } // SetNillableType sets the "type" field if the given value is not nil. -func (cuo *ConnectorUpdateOne) SetNillableType(s *string) *ConnectorUpdateOne { - if s != nil { - cuo.SetType(*s) +func (_u *ConnectorUpdateOne) SetNillableType(v *string) *ConnectorUpdateOne { + if v != nil { + _u.SetType(*v) } - return cuo + return _u } // SetName sets the "name" field. -func (cuo *ConnectorUpdateOne) SetName(s string) *ConnectorUpdateOne { - cuo.mutation.SetName(s) - return cuo +func (_u *ConnectorUpdateOne) SetName(v string) *ConnectorUpdateOne { + _u.mutation.SetName(v) + return _u } // SetNillableName sets the "name" field if the given value is not nil. -func (cuo *ConnectorUpdateOne) SetNillableName(s *string) *ConnectorUpdateOne { - if s != nil { - cuo.SetName(*s) +func (_u *ConnectorUpdateOne) SetNillableName(v *string) *ConnectorUpdateOne { + if v != nil { + _u.SetName(*v) } - return cuo + return _u } // SetResourceVersion sets the "resource_version" field. -func (cuo *ConnectorUpdateOne) SetResourceVersion(s string) *ConnectorUpdateOne { - cuo.mutation.SetResourceVersion(s) - return cuo +func (_u *ConnectorUpdateOne) SetResourceVersion(v string) *ConnectorUpdateOne { + _u.mutation.SetResourceVersion(v) + return _u } // SetNillableResourceVersion sets the "resource_version" field if the given value is not nil. -func (cuo *ConnectorUpdateOne) SetNillableResourceVersion(s *string) *ConnectorUpdateOne { - if s != nil { - cuo.SetResourceVersion(*s) +func (_u *ConnectorUpdateOne) SetNillableResourceVersion(v *string) *ConnectorUpdateOne { + if v != nil { + _u.SetResourceVersion(*v) } - return cuo + return _u } // SetConfig sets the "config" field. -func (cuo *ConnectorUpdateOne) SetConfig(b []byte) *ConnectorUpdateOne { - cuo.mutation.SetConfig(b) - return cuo +func (_u *ConnectorUpdateOne) SetConfig(v []byte) *ConnectorUpdateOne { + _u.mutation.SetConfig(v) + return _u } // Mutation returns the ConnectorMutation object of the builder. -func (cuo *ConnectorUpdateOne) Mutation() *ConnectorMutation { - return cuo.mutation +func (_u *ConnectorUpdateOne) Mutation() *ConnectorMutation { + return _u.mutation } // Where appends a list predicates to the ConnectorUpdate builder. -func (cuo *ConnectorUpdateOne) Where(ps ...predicate.Connector) *ConnectorUpdateOne { - cuo.mutation.Where(ps...) - return cuo +func (_u *ConnectorUpdateOne) Where(ps ...predicate.Connector) *ConnectorUpdateOne { + _u.mutation.Where(ps...) + return _u } // Select allows selecting one or more fields (columns) of the returned entity. // The default is selecting all fields defined in the entity schema. -func (cuo *ConnectorUpdateOne) Select(field string, fields ...string) *ConnectorUpdateOne { - cuo.fields = append([]string{field}, fields...) - return cuo +func (_u *ConnectorUpdateOne) Select(field string, fields ...string) *ConnectorUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u } // Save executes the query and returns the updated Connector entity. -func (cuo *ConnectorUpdateOne) Save(ctx context.Context) (*Connector, error) { - return withHooks(ctx, cuo.sqlSave, cuo.mutation, cuo.hooks) +func (_u *ConnectorUpdateOne) Save(ctx context.Context) (*Connector, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) } // SaveX is like Save, but panics if an error occurs. -func (cuo *ConnectorUpdateOne) SaveX(ctx context.Context) *Connector { - node, err := cuo.Save(ctx) +func (_u *ConnectorUpdateOne) SaveX(ctx context.Context) *Connector { + node, err := _u.Save(ctx) if err != nil { panic(err) } @@ -247,26 +247,26 @@ func (cuo *ConnectorUpdateOne) SaveX(ctx context.Context) *Connector { } // Exec executes the query on the entity. -func (cuo *ConnectorUpdateOne) Exec(ctx context.Context) error { - _, err := cuo.Save(ctx) +func (_u *ConnectorUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (cuo *ConnectorUpdateOne) ExecX(ctx context.Context) { - if err := cuo.Exec(ctx); err != nil { +func (_u *ConnectorUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { panic(err) } } // check runs all checks and user-defined validators on the builder. -func (cuo *ConnectorUpdateOne) check() error { - if v, ok := cuo.mutation.GetType(); ok { +func (_u *ConnectorUpdateOne) check() error { + if v, ok := _u.mutation.GetType(); ok { if err := connector.TypeValidator(v); err != nil { return &ValidationError{Name: "type", err: fmt.Errorf(`db: validator failed for field "Connector.type": %w`, err)} } } - if v, ok := cuo.mutation.Name(); ok { + if v, ok := _u.mutation.Name(); ok { if err := connector.NameValidator(v); err != nil { return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "Connector.name": %w`, err)} } @@ -274,17 +274,17 @@ func (cuo *ConnectorUpdateOne) check() error { return nil } -func (cuo *ConnectorUpdateOne) sqlSave(ctx context.Context) (_node *Connector, err error) { - if err := cuo.check(); err != nil { +func (_u *ConnectorUpdateOne) sqlSave(ctx context.Context) (_node *Connector, err error) { + if err := _u.check(); err != nil { return _node, err } _spec := sqlgraph.NewUpdateSpec(connector.Table, connector.Columns, sqlgraph.NewFieldSpec(connector.FieldID, field.TypeString)) - id, ok := cuo.mutation.ID() + id, ok := _u.mutation.ID() if !ok { return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "Connector.id" for update`)} } _spec.Node.ID.Value = id - if fields := cuo.fields; len(fields) > 0 { + if fields := _u.fields; len(fields) > 0 { _spec.Node.Columns = make([]string, 0, len(fields)) _spec.Node.Columns = append(_spec.Node.Columns, connector.FieldID) for _, f := range fields { @@ -296,29 +296,29 @@ func (cuo *ConnectorUpdateOne) sqlSave(ctx context.Context) (_node *Connector, e } } } - if ps := cuo.mutation.predicates; len(ps) > 0 { + if ps := _u.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if value, ok := cuo.mutation.GetType(); ok { + if value, ok := _u.mutation.GetType(); ok { _spec.SetField(connector.FieldType, field.TypeString, value) } - if value, ok := cuo.mutation.Name(); ok { + if value, ok := _u.mutation.Name(); ok { _spec.SetField(connector.FieldName, field.TypeString, value) } - if value, ok := cuo.mutation.ResourceVersion(); ok { + if value, ok := _u.mutation.ResourceVersion(); ok { _spec.SetField(connector.FieldResourceVersion, field.TypeString, value) } - if value, ok := cuo.mutation.Config(); ok { + if value, ok := _u.mutation.Config(); ok { _spec.SetField(connector.FieldConfig, field.TypeBytes, value) } - _node = &Connector{config: cuo.config} + _node = &Connector{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, cuo.driver, _spec); err != nil { + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{connector.Label} } else if sqlgraph.IsConstraintError(err) { @@ -326,6 +326,6 @@ func (cuo *ConnectorUpdateOne) sqlSave(ctx context.Context) (_node *Connector, e } return nil, err } - cuo.mutation.done = true + _u.mutation.done = true return _node, nil } diff --git a/storage/ent/db/devicerequest.go b/storage/ent/db/devicerequest.go index df0194bb45..ca502a2cd5 100644 --- a/storage/ent/db/devicerequest.go +++ b/storage/ent/db/devicerequest.go @@ -55,7 +55,7 @@ func (*DeviceRequest) scanValues(columns []string) ([]any, error) { // assignValues assigns the values that were returned from sql.Rows (after scanning) // to the DeviceRequest fields. -func (dr *DeviceRequest) assignValues(columns []string, values []any) error { +func (_m *DeviceRequest) 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) } @@ -66,36 +66,36 @@ func (dr *DeviceRequest) assignValues(columns []string, values []any) error { if !ok { return fmt.Errorf("unexpected type %T for field id", value) } - dr.ID = int(value.Int64) + _m.ID = int(value.Int64) case devicerequest.FieldUserCode: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field user_code", values[i]) } else if value.Valid { - dr.UserCode = value.String + _m.UserCode = value.String } case devicerequest.FieldDeviceCode: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field device_code", values[i]) } else if value.Valid { - dr.DeviceCode = value.String + _m.DeviceCode = value.String } case devicerequest.FieldClientID: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field client_id", values[i]) } else if value.Valid { - dr.ClientID = value.String + _m.ClientID = value.String } case devicerequest.FieldClientSecret: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field client_secret", values[i]) } else if value.Valid { - dr.ClientSecret = value.String + _m.ClientSecret = value.String } case devicerequest.FieldScopes: if value, ok := values[i].(*[]byte); !ok { return fmt.Errorf("unexpected type %T for field scopes", values[i]) } else if value != nil && len(*value) > 0 { - if err := json.Unmarshal(*value, &dr.Scopes); err != nil { + if err := json.Unmarshal(*value, &_m.Scopes); err != nil { return fmt.Errorf("unmarshal field scopes: %w", err) } } @@ -103,10 +103,10 @@ func (dr *DeviceRequest) assignValues(columns []string, values []any) error { if value, ok := values[i].(*sql.NullTime); !ok { return fmt.Errorf("unexpected type %T for field expiry", values[i]) } else if value.Valid { - dr.Expiry = value.Time + _m.Expiry = value.Time } default: - dr.selectValues.Set(columns[i], values[i]) + _m.selectValues.Set(columns[i], values[i]) } } return nil @@ -114,50 +114,50 @@ func (dr *DeviceRequest) assignValues(columns []string, values []any) error { // Value returns the ent.Value that was dynamically selected and assigned to the DeviceRequest. // This includes values selected through modifiers, order, etc. -func (dr *DeviceRequest) Value(name string) (ent.Value, error) { - return dr.selectValues.Get(name) +func (_m *DeviceRequest) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) } // Update returns a builder for updating this DeviceRequest. // Note that you need to call DeviceRequest.Unwrap() before calling this method if this DeviceRequest // was returned from a transaction, and the transaction was committed or rolled back. -func (dr *DeviceRequest) Update() *DeviceRequestUpdateOne { - return NewDeviceRequestClient(dr.config).UpdateOne(dr) +func (_m *DeviceRequest) Update() *DeviceRequestUpdateOne { + return NewDeviceRequestClient(_m.config).UpdateOne(_m) } // Unwrap unwraps the DeviceRequest 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 (dr *DeviceRequest) Unwrap() *DeviceRequest { - _tx, ok := dr.config.driver.(*txDriver) +func (_m *DeviceRequest) Unwrap() *DeviceRequest { + _tx, ok := _m.config.driver.(*txDriver) if !ok { panic("db: DeviceRequest is not a transactional entity") } - dr.config.driver = _tx.drv - return dr + _m.config.driver = _tx.drv + return _m } // String implements the fmt.Stringer. -func (dr *DeviceRequest) String() string { +func (_m *DeviceRequest) String() string { var builder strings.Builder builder.WriteString("DeviceRequest(") - builder.WriteString(fmt.Sprintf("id=%v, ", dr.ID)) + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) builder.WriteString("user_code=") - builder.WriteString(dr.UserCode) + builder.WriteString(_m.UserCode) builder.WriteString(", ") builder.WriteString("device_code=") - builder.WriteString(dr.DeviceCode) + builder.WriteString(_m.DeviceCode) builder.WriteString(", ") builder.WriteString("client_id=") - builder.WriteString(dr.ClientID) + builder.WriteString(_m.ClientID) builder.WriteString(", ") builder.WriteString("client_secret=") - builder.WriteString(dr.ClientSecret) + builder.WriteString(_m.ClientSecret) builder.WriteString(", ") builder.WriteString("scopes=") - builder.WriteString(fmt.Sprintf("%v", dr.Scopes)) + builder.WriteString(fmt.Sprintf("%v", _m.Scopes)) builder.WriteString(", ") builder.WriteString("expiry=") - builder.WriteString(dr.Expiry.Format(time.ANSIC)) + builder.WriteString(_m.Expiry.Format(time.ANSIC)) builder.WriteByte(')') return builder.String() } diff --git a/storage/ent/db/devicerequest_create.go b/storage/ent/db/devicerequest_create.go index 70c97875df..75a94c1781 100644 --- a/storage/ent/db/devicerequest_create.go +++ b/storage/ent/db/devicerequest_create.go @@ -21,54 +21,54 @@ type DeviceRequestCreate struct { } // SetUserCode sets the "user_code" field. -func (drc *DeviceRequestCreate) SetUserCode(s string) *DeviceRequestCreate { - drc.mutation.SetUserCode(s) - return drc +func (_c *DeviceRequestCreate) SetUserCode(v string) *DeviceRequestCreate { + _c.mutation.SetUserCode(v) + return _c } // SetDeviceCode sets the "device_code" field. -func (drc *DeviceRequestCreate) SetDeviceCode(s string) *DeviceRequestCreate { - drc.mutation.SetDeviceCode(s) - return drc +func (_c *DeviceRequestCreate) SetDeviceCode(v string) *DeviceRequestCreate { + _c.mutation.SetDeviceCode(v) + return _c } // SetClientID sets the "client_id" field. -func (drc *DeviceRequestCreate) SetClientID(s string) *DeviceRequestCreate { - drc.mutation.SetClientID(s) - return drc +func (_c *DeviceRequestCreate) SetClientID(v string) *DeviceRequestCreate { + _c.mutation.SetClientID(v) + return _c } // SetClientSecret sets the "client_secret" field. -func (drc *DeviceRequestCreate) SetClientSecret(s string) *DeviceRequestCreate { - drc.mutation.SetClientSecret(s) - return drc +func (_c *DeviceRequestCreate) SetClientSecret(v string) *DeviceRequestCreate { + _c.mutation.SetClientSecret(v) + return _c } // SetScopes sets the "scopes" field. -func (drc *DeviceRequestCreate) SetScopes(s []string) *DeviceRequestCreate { - drc.mutation.SetScopes(s) - return drc +func (_c *DeviceRequestCreate) SetScopes(v []string) *DeviceRequestCreate { + _c.mutation.SetScopes(v) + return _c } // SetExpiry sets the "expiry" field. -func (drc *DeviceRequestCreate) SetExpiry(t time.Time) *DeviceRequestCreate { - drc.mutation.SetExpiry(t) - return drc +func (_c *DeviceRequestCreate) SetExpiry(v time.Time) *DeviceRequestCreate { + _c.mutation.SetExpiry(v) + return _c } // Mutation returns the DeviceRequestMutation object of the builder. -func (drc *DeviceRequestCreate) Mutation() *DeviceRequestMutation { - return drc.mutation +func (_c *DeviceRequestCreate) Mutation() *DeviceRequestMutation { + return _c.mutation } // Save creates the DeviceRequest in the database. -func (drc *DeviceRequestCreate) Save(ctx context.Context) (*DeviceRequest, error) { - return withHooks(ctx, drc.sqlSave, drc.mutation, drc.hooks) +func (_c *DeviceRequestCreate) Save(ctx context.Context) (*DeviceRequest, error) { + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) } // SaveX calls Save and panics if Save returns an error. -func (drc *DeviceRequestCreate) SaveX(ctx context.Context) *DeviceRequest { - v, err := drc.Save(ctx) +func (_c *DeviceRequestCreate) SaveX(ctx context.Context) *DeviceRequest { + v, err := _c.Save(ctx) if err != nil { panic(err) } @@ -76,64 +76,64 @@ func (drc *DeviceRequestCreate) SaveX(ctx context.Context) *DeviceRequest { } // Exec executes the query. -func (drc *DeviceRequestCreate) Exec(ctx context.Context) error { - _, err := drc.Save(ctx) +func (_c *DeviceRequestCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (drc *DeviceRequestCreate) ExecX(ctx context.Context) { - if err := drc.Exec(ctx); err != nil { +func (_c *DeviceRequestCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { panic(err) } } // check runs all checks and user-defined validators on the builder. -func (drc *DeviceRequestCreate) check() error { - if _, ok := drc.mutation.UserCode(); !ok { +func (_c *DeviceRequestCreate) check() error { + if _, ok := _c.mutation.UserCode(); !ok { return &ValidationError{Name: "user_code", err: errors.New(`db: missing required field "DeviceRequest.user_code"`)} } - if v, ok := drc.mutation.UserCode(); ok { + if v, ok := _c.mutation.UserCode(); ok { if err := devicerequest.UserCodeValidator(v); err != nil { return &ValidationError{Name: "user_code", err: fmt.Errorf(`db: validator failed for field "DeviceRequest.user_code": %w`, err)} } } - if _, ok := drc.mutation.DeviceCode(); !ok { + if _, ok := _c.mutation.DeviceCode(); !ok { return &ValidationError{Name: "device_code", err: errors.New(`db: missing required field "DeviceRequest.device_code"`)} } - if v, ok := drc.mutation.DeviceCode(); ok { + if v, ok := _c.mutation.DeviceCode(); ok { if err := devicerequest.DeviceCodeValidator(v); err != nil { return &ValidationError{Name: "device_code", err: fmt.Errorf(`db: validator failed for field "DeviceRequest.device_code": %w`, err)} } } - if _, ok := drc.mutation.ClientID(); !ok { + if _, ok := _c.mutation.ClientID(); !ok { return &ValidationError{Name: "client_id", err: errors.New(`db: missing required field "DeviceRequest.client_id"`)} } - if v, ok := drc.mutation.ClientID(); ok { + if v, ok := _c.mutation.ClientID(); ok { if err := devicerequest.ClientIDValidator(v); err != nil { return &ValidationError{Name: "client_id", err: fmt.Errorf(`db: validator failed for field "DeviceRequest.client_id": %w`, err)} } } - if _, ok := drc.mutation.ClientSecret(); !ok { + if _, ok := _c.mutation.ClientSecret(); !ok { return &ValidationError{Name: "client_secret", err: errors.New(`db: missing required field "DeviceRequest.client_secret"`)} } - if v, ok := drc.mutation.ClientSecret(); ok { + if v, ok := _c.mutation.ClientSecret(); ok { if err := devicerequest.ClientSecretValidator(v); err != nil { return &ValidationError{Name: "client_secret", err: fmt.Errorf(`db: validator failed for field "DeviceRequest.client_secret": %w`, err)} } } - if _, ok := drc.mutation.Expiry(); !ok { + if _, ok := _c.mutation.Expiry(); !ok { return &ValidationError{Name: "expiry", err: errors.New(`db: missing required field "DeviceRequest.expiry"`)} } return nil } -func (drc *DeviceRequestCreate) sqlSave(ctx context.Context) (*DeviceRequest, error) { - if err := drc.check(); err != nil { +func (_c *DeviceRequestCreate) sqlSave(ctx context.Context) (*DeviceRequest, error) { + if err := _c.check(); err != nil { return nil, err } - _node, _spec := drc.createSpec() - if err := sqlgraph.CreateNode(ctx, drc.driver, _spec); err != nil { + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { if sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } @@ -141,37 +141,37 @@ func (drc *DeviceRequestCreate) sqlSave(ctx context.Context) (*DeviceRequest, er } id := _spec.ID.Value.(int64) _node.ID = int(id) - drc.mutation.id = &_node.ID - drc.mutation.done = true + _c.mutation.id = &_node.ID + _c.mutation.done = true return _node, nil } -func (drc *DeviceRequestCreate) createSpec() (*DeviceRequest, *sqlgraph.CreateSpec) { +func (_c *DeviceRequestCreate) createSpec() (*DeviceRequest, *sqlgraph.CreateSpec) { var ( - _node = &DeviceRequest{config: drc.config} + _node = &DeviceRequest{config: _c.config} _spec = sqlgraph.NewCreateSpec(devicerequest.Table, sqlgraph.NewFieldSpec(devicerequest.FieldID, field.TypeInt)) ) - if value, ok := drc.mutation.UserCode(); ok { + if value, ok := _c.mutation.UserCode(); ok { _spec.SetField(devicerequest.FieldUserCode, field.TypeString, value) _node.UserCode = value } - if value, ok := drc.mutation.DeviceCode(); ok { + if value, ok := _c.mutation.DeviceCode(); ok { _spec.SetField(devicerequest.FieldDeviceCode, field.TypeString, value) _node.DeviceCode = value } - if value, ok := drc.mutation.ClientID(); ok { + if value, ok := _c.mutation.ClientID(); ok { _spec.SetField(devicerequest.FieldClientID, field.TypeString, value) _node.ClientID = value } - if value, ok := drc.mutation.ClientSecret(); ok { + if value, ok := _c.mutation.ClientSecret(); ok { _spec.SetField(devicerequest.FieldClientSecret, field.TypeString, value) _node.ClientSecret = value } - if value, ok := drc.mutation.Scopes(); ok { + if value, ok := _c.mutation.Scopes(); ok { _spec.SetField(devicerequest.FieldScopes, field.TypeJSON, value) _node.Scopes = value } - if value, ok := drc.mutation.Expiry(); ok { + if value, ok := _c.mutation.Expiry(); ok { _spec.SetField(devicerequest.FieldExpiry, field.TypeTime, value) _node.Expiry = value } @@ -186,16 +186,16 @@ type DeviceRequestCreateBulk struct { } // Save creates the DeviceRequest entities in the database. -func (drcb *DeviceRequestCreateBulk) Save(ctx context.Context) ([]*DeviceRequest, error) { - if drcb.err != nil { - return nil, drcb.err +func (_c *DeviceRequestCreateBulk) Save(ctx context.Context) ([]*DeviceRequest, error) { + if _c.err != nil { + return nil, _c.err } - specs := make([]*sqlgraph.CreateSpec, len(drcb.builders)) - nodes := make([]*DeviceRequest, len(drcb.builders)) - mutators := make([]Mutator, len(drcb.builders)) - for i := range drcb.builders { + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*DeviceRequest, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { func(i int, root context.Context) { - builder := drcb.builders[i] + builder := _c.builders[i] var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { mutation, ok := m.(*DeviceRequestMutation) if !ok { @@ -208,11 +208,11 @@ func (drcb *DeviceRequestCreateBulk) Save(ctx context.Context) ([]*DeviceRequest var err error nodes[i], specs[i] = builder.createSpec() if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, drcb.builders[i+1].mutation) + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, drcb.driver, spec); err != nil { + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { if sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } @@ -236,7 +236,7 @@ func (drcb *DeviceRequestCreateBulk) Save(ctx context.Context) ([]*DeviceRequest }(i, ctx) } if len(mutators) > 0 { - if _, err := mutators[0].Mutate(ctx, drcb.builders[0].mutation); err != nil { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { return nil, err } } @@ -244,8 +244,8 @@ func (drcb *DeviceRequestCreateBulk) Save(ctx context.Context) ([]*DeviceRequest } // SaveX is like Save, but panics if an error occurs. -func (drcb *DeviceRequestCreateBulk) SaveX(ctx context.Context) []*DeviceRequest { - v, err := drcb.Save(ctx) +func (_c *DeviceRequestCreateBulk) SaveX(ctx context.Context) []*DeviceRequest { + v, err := _c.Save(ctx) if err != nil { panic(err) } @@ -253,14 +253,14 @@ func (drcb *DeviceRequestCreateBulk) SaveX(ctx context.Context) []*DeviceRequest } // Exec executes the query. -func (drcb *DeviceRequestCreateBulk) Exec(ctx context.Context) error { - _, err := drcb.Save(ctx) +func (_c *DeviceRequestCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (drcb *DeviceRequestCreateBulk) ExecX(ctx context.Context) { - if err := drcb.Exec(ctx); err != nil { +func (_c *DeviceRequestCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { panic(err) } } diff --git a/storage/ent/db/devicerequest_delete.go b/storage/ent/db/devicerequest_delete.go index b92f77984d..97ddacf72e 100644 --- a/storage/ent/db/devicerequest_delete.go +++ b/storage/ent/db/devicerequest_delete.go @@ -20,56 +20,56 @@ type DeviceRequestDelete struct { } // Where appends a list predicates to the DeviceRequestDelete builder. -func (drd *DeviceRequestDelete) Where(ps ...predicate.DeviceRequest) *DeviceRequestDelete { - drd.mutation.Where(ps...) - return drd +func (_d *DeviceRequestDelete) Where(ps ...predicate.DeviceRequest) *DeviceRequestDelete { + _d.mutation.Where(ps...) + return _d } // Exec executes the deletion query and returns how many vertices were deleted. -func (drd *DeviceRequestDelete) Exec(ctx context.Context) (int, error) { - return withHooks(ctx, drd.sqlExec, drd.mutation, drd.hooks) +func (_d *DeviceRequestDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) } // ExecX is like Exec, but panics if an error occurs. -func (drd *DeviceRequestDelete) ExecX(ctx context.Context) int { - n, err := drd.Exec(ctx) +func (_d *DeviceRequestDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) if err != nil { panic(err) } return n } -func (drd *DeviceRequestDelete) sqlExec(ctx context.Context) (int, error) { +func (_d *DeviceRequestDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(devicerequest.Table, sqlgraph.NewFieldSpec(devicerequest.FieldID, field.TypeInt)) - if ps := drd.mutation.predicates; len(ps) > 0 { + if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - affected, err := sqlgraph.DeleteNodes(ctx, drd.driver, _spec) + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) if err != nil && sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } - drd.mutation.done = true + _d.mutation.done = true return affected, err } // DeviceRequestDeleteOne is the builder for deleting a single DeviceRequest entity. type DeviceRequestDeleteOne struct { - drd *DeviceRequestDelete + _d *DeviceRequestDelete } // Where appends a list predicates to the DeviceRequestDelete builder. -func (drdo *DeviceRequestDeleteOne) Where(ps ...predicate.DeviceRequest) *DeviceRequestDeleteOne { - drdo.drd.mutation.Where(ps...) - return drdo +func (_d *DeviceRequestDeleteOne) Where(ps ...predicate.DeviceRequest) *DeviceRequestDeleteOne { + _d._d.mutation.Where(ps...) + return _d } // Exec executes the deletion query. -func (drdo *DeviceRequestDeleteOne) Exec(ctx context.Context) error { - n, err := drdo.drd.Exec(ctx) +func (_d *DeviceRequestDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) switch { case err != nil: return err @@ -81,8 +81,8 @@ func (drdo *DeviceRequestDeleteOne) Exec(ctx context.Context) error { } // ExecX is like Exec, but panics if an error occurs. -func (drdo *DeviceRequestDeleteOne) ExecX(ctx context.Context) { - if err := drdo.Exec(ctx); err != nil { +func (_d *DeviceRequestDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { panic(err) } } diff --git a/storage/ent/db/devicerequest_query.go b/storage/ent/db/devicerequest_query.go index 49ed0461ee..93093d2a1c 100644 --- a/storage/ent/db/devicerequest_query.go +++ b/storage/ent/db/devicerequest_query.go @@ -28,40 +28,40 @@ type DeviceRequestQuery struct { } // Where adds a new predicate for the DeviceRequestQuery builder. -func (drq *DeviceRequestQuery) Where(ps ...predicate.DeviceRequest) *DeviceRequestQuery { - drq.predicates = append(drq.predicates, ps...) - return drq +func (_q *DeviceRequestQuery) Where(ps ...predicate.DeviceRequest) *DeviceRequestQuery { + _q.predicates = append(_q.predicates, ps...) + return _q } // Limit the number of records to be returned by this query. -func (drq *DeviceRequestQuery) Limit(limit int) *DeviceRequestQuery { - drq.ctx.Limit = &limit - return drq +func (_q *DeviceRequestQuery) Limit(limit int) *DeviceRequestQuery { + _q.ctx.Limit = &limit + return _q } // Offset to start from. -func (drq *DeviceRequestQuery) Offset(offset int) *DeviceRequestQuery { - drq.ctx.Offset = &offset - return drq +func (_q *DeviceRequestQuery) Offset(offset int) *DeviceRequestQuery { + _q.ctx.Offset = &offset + return _q } // Unique configures the query builder to filter duplicate records on query. // By default, unique is set to true, and can be disabled using this method. -func (drq *DeviceRequestQuery) Unique(unique bool) *DeviceRequestQuery { - drq.ctx.Unique = &unique - return drq +func (_q *DeviceRequestQuery) Unique(unique bool) *DeviceRequestQuery { + _q.ctx.Unique = &unique + return _q } // Order specifies how the records should be ordered. -func (drq *DeviceRequestQuery) Order(o ...devicerequest.OrderOption) *DeviceRequestQuery { - drq.order = append(drq.order, o...) - return drq +func (_q *DeviceRequestQuery) Order(o ...devicerequest.OrderOption) *DeviceRequestQuery { + _q.order = append(_q.order, o...) + return _q } // First returns the first DeviceRequest entity from the query. // Returns a *NotFoundError when no DeviceRequest was found. -func (drq *DeviceRequestQuery) First(ctx context.Context) (*DeviceRequest, error) { - nodes, err := drq.Limit(1).All(setContextOp(ctx, drq.ctx, ent.OpQueryFirst)) +func (_q *DeviceRequestQuery) First(ctx context.Context) (*DeviceRequest, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) if err != nil { return nil, err } @@ -72,8 +72,8 @@ func (drq *DeviceRequestQuery) First(ctx context.Context) (*DeviceRequest, error } // FirstX is like First, but panics if an error occurs. -func (drq *DeviceRequestQuery) FirstX(ctx context.Context) *DeviceRequest { - node, err := drq.First(ctx) +func (_q *DeviceRequestQuery) FirstX(ctx context.Context) *DeviceRequest { + node, err := _q.First(ctx) if err != nil && !IsNotFound(err) { panic(err) } @@ -82,9 +82,9 @@ func (drq *DeviceRequestQuery) FirstX(ctx context.Context) *DeviceRequest { // FirstID returns the first DeviceRequest ID from the query. // Returns a *NotFoundError when no DeviceRequest ID was found. -func (drq *DeviceRequestQuery) FirstID(ctx context.Context) (id int, err error) { +func (_q *DeviceRequestQuery) FirstID(ctx context.Context) (id int, err error) { var ids []int - if ids, err = drq.Limit(1).IDs(setContextOp(ctx, drq.ctx, ent.OpQueryFirstID)); err != nil { + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { return } if len(ids) == 0 { @@ -95,8 +95,8 @@ func (drq *DeviceRequestQuery) FirstID(ctx context.Context) (id int, err error) } // FirstIDX is like FirstID, but panics if an error occurs. -func (drq *DeviceRequestQuery) FirstIDX(ctx context.Context) int { - id, err := drq.FirstID(ctx) +func (_q *DeviceRequestQuery) FirstIDX(ctx context.Context) int { + id, err := _q.FirstID(ctx) if err != nil && !IsNotFound(err) { panic(err) } @@ -106,8 +106,8 @@ func (drq *DeviceRequestQuery) FirstIDX(ctx context.Context) int { // Only returns a single DeviceRequest entity found by the query, ensuring it only returns one. // Returns a *NotSingularError when more than one DeviceRequest entity is found. // Returns a *NotFoundError when no DeviceRequest entities are found. -func (drq *DeviceRequestQuery) Only(ctx context.Context) (*DeviceRequest, error) { - nodes, err := drq.Limit(2).All(setContextOp(ctx, drq.ctx, ent.OpQueryOnly)) +func (_q *DeviceRequestQuery) Only(ctx context.Context) (*DeviceRequest, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) if err != nil { return nil, err } @@ -122,8 +122,8 @@ func (drq *DeviceRequestQuery) Only(ctx context.Context) (*DeviceRequest, error) } // OnlyX is like Only, but panics if an error occurs. -func (drq *DeviceRequestQuery) OnlyX(ctx context.Context) *DeviceRequest { - node, err := drq.Only(ctx) +func (_q *DeviceRequestQuery) OnlyX(ctx context.Context) *DeviceRequest { + node, err := _q.Only(ctx) if err != nil { panic(err) } @@ -133,9 +133,9 @@ func (drq *DeviceRequestQuery) OnlyX(ctx context.Context) *DeviceRequest { // OnlyID is like Only, but returns the only DeviceRequest ID in the query. // Returns a *NotSingularError when more than one DeviceRequest ID is found. // Returns a *NotFoundError when no entities are found. -func (drq *DeviceRequestQuery) OnlyID(ctx context.Context) (id int, err error) { +func (_q *DeviceRequestQuery) OnlyID(ctx context.Context) (id int, err error) { var ids []int - if ids, err = drq.Limit(2).IDs(setContextOp(ctx, drq.ctx, ent.OpQueryOnlyID)); err != nil { + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { return } switch len(ids) { @@ -150,8 +150,8 @@ func (drq *DeviceRequestQuery) OnlyID(ctx context.Context) (id int, err error) { } // OnlyIDX is like OnlyID, but panics if an error occurs. -func (drq *DeviceRequestQuery) OnlyIDX(ctx context.Context) int { - id, err := drq.OnlyID(ctx) +func (_q *DeviceRequestQuery) OnlyIDX(ctx context.Context) int { + id, err := _q.OnlyID(ctx) if err != nil { panic(err) } @@ -159,18 +159,18 @@ func (drq *DeviceRequestQuery) OnlyIDX(ctx context.Context) int { } // All executes the query and returns a list of DeviceRequests. -func (drq *DeviceRequestQuery) All(ctx context.Context) ([]*DeviceRequest, error) { - ctx = setContextOp(ctx, drq.ctx, ent.OpQueryAll) - if err := drq.prepareQuery(ctx); err != nil { +func (_q *DeviceRequestQuery) All(ctx context.Context) ([]*DeviceRequest, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { return nil, err } qr := querierAll[[]*DeviceRequest, *DeviceRequestQuery]() - return withInterceptors[[]*DeviceRequest](ctx, drq, qr, drq.inters) + return withInterceptors[[]*DeviceRequest](ctx, _q, qr, _q.inters) } // AllX is like All, but panics if an error occurs. -func (drq *DeviceRequestQuery) AllX(ctx context.Context) []*DeviceRequest { - nodes, err := drq.All(ctx) +func (_q *DeviceRequestQuery) AllX(ctx context.Context) []*DeviceRequest { + nodes, err := _q.All(ctx) if err != nil { panic(err) } @@ -178,20 +178,20 @@ func (drq *DeviceRequestQuery) AllX(ctx context.Context) []*DeviceRequest { } // IDs executes the query and returns a list of DeviceRequest IDs. -func (drq *DeviceRequestQuery) IDs(ctx context.Context) (ids []int, err error) { - if drq.ctx.Unique == nil && drq.path != nil { - drq.Unique(true) +func (_q *DeviceRequestQuery) IDs(ctx context.Context) (ids []int, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) } - ctx = setContextOp(ctx, drq.ctx, ent.OpQueryIDs) - if err = drq.Select(devicerequest.FieldID).Scan(ctx, &ids); err != nil { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(devicerequest.FieldID).Scan(ctx, &ids); err != nil { return nil, err } return ids, nil } // IDsX is like IDs, but panics if an error occurs. -func (drq *DeviceRequestQuery) IDsX(ctx context.Context) []int { - ids, err := drq.IDs(ctx) +func (_q *DeviceRequestQuery) IDsX(ctx context.Context) []int { + ids, err := _q.IDs(ctx) if err != nil { panic(err) } @@ -199,17 +199,17 @@ func (drq *DeviceRequestQuery) IDsX(ctx context.Context) []int { } // Count returns the count of the given query. -func (drq *DeviceRequestQuery) Count(ctx context.Context) (int, error) { - ctx = setContextOp(ctx, drq.ctx, ent.OpQueryCount) - if err := drq.prepareQuery(ctx); err != nil { +func (_q *DeviceRequestQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { return 0, err } - return withInterceptors[int](ctx, drq, querierCount[*DeviceRequestQuery](), drq.inters) + return withInterceptors[int](ctx, _q, querierCount[*DeviceRequestQuery](), _q.inters) } // CountX is like Count, but panics if an error occurs. -func (drq *DeviceRequestQuery) CountX(ctx context.Context) int { - count, err := drq.Count(ctx) +func (_q *DeviceRequestQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) if err != nil { panic(err) } @@ -217,9 +217,9 @@ func (drq *DeviceRequestQuery) CountX(ctx context.Context) int { } // Exist returns true if the query has elements in the graph. -func (drq *DeviceRequestQuery) Exist(ctx context.Context) (bool, error) { - ctx = setContextOp(ctx, drq.ctx, ent.OpQueryExist) - switch _, err := drq.FirstID(ctx); { +func (_q *DeviceRequestQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { case IsNotFound(err): return false, nil case err != nil: @@ -230,8 +230,8 @@ func (drq *DeviceRequestQuery) Exist(ctx context.Context) (bool, error) { } // ExistX is like Exist, but panics if an error occurs. -func (drq *DeviceRequestQuery) ExistX(ctx context.Context) bool { - exist, err := drq.Exist(ctx) +func (_q *DeviceRequestQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) if err != nil { panic(err) } @@ -240,19 +240,19 @@ func (drq *DeviceRequestQuery) ExistX(ctx context.Context) bool { // Clone returns a duplicate of the DeviceRequestQuery builder, including all associated steps. It can be // used to prepare common query builders and use them differently after the clone is made. -func (drq *DeviceRequestQuery) Clone() *DeviceRequestQuery { - if drq == nil { +func (_q *DeviceRequestQuery) Clone() *DeviceRequestQuery { + if _q == nil { return nil } return &DeviceRequestQuery{ - config: drq.config, - ctx: drq.ctx.Clone(), - order: append([]devicerequest.OrderOption{}, drq.order...), - inters: append([]Interceptor{}, drq.inters...), - predicates: append([]predicate.DeviceRequest{}, drq.predicates...), + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]devicerequest.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.DeviceRequest{}, _q.predicates...), // clone intermediate query. - sql: drq.sql.Clone(), - path: drq.path, + sql: _q.sql.Clone(), + path: _q.path, } } @@ -270,10 +270,10 @@ func (drq *DeviceRequestQuery) Clone() *DeviceRequestQuery { // GroupBy(devicerequest.FieldUserCode). // Aggregate(db.Count()). // Scan(ctx, &v) -func (drq *DeviceRequestQuery) GroupBy(field string, fields ...string) *DeviceRequestGroupBy { - drq.ctx.Fields = append([]string{field}, fields...) - grbuild := &DeviceRequestGroupBy{build: drq} - grbuild.flds = &drq.ctx.Fields +func (_q *DeviceRequestQuery) GroupBy(field string, fields ...string) *DeviceRequestGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &DeviceRequestGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields grbuild.label = devicerequest.Label grbuild.scan = grbuild.Scan return grbuild @@ -291,62 +291,62 @@ func (drq *DeviceRequestQuery) GroupBy(field string, fields ...string) *DeviceRe // client.DeviceRequest.Query(). // Select(devicerequest.FieldUserCode). // Scan(ctx, &v) -func (drq *DeviceRequestQuery) Select(fields ...string) *DeviceRequestSelect { - drq.ctx.Fields = append(drq.ctx.Fields, fields...) - sbuild := &DeviceRequestSelect{DeviceRequestQuery: drq} +func (_q *DeviceRequestQuery) Select(fields ...string) *DeviceRequestSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &DeviceRequestSelect{DeviceRequestQuery: _q} sbuild.label = devicerequest.Label - sbuild.flds, sbuild.scan = &drq.ctx.Fields, sbuild.Scan + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan return sbuild } // Aggregate returns a DeviceRequestSelect configured with the given aggregations. -func (drq *DeviceRequestQuery) Aggregate(fns ...AggregateFunc) *DeviceRequestSelect { - return drq.Select().Aggregate(fns...) +func (_q *DeviceRequestQuery) Aggregate(fns ...AggregateFunc) *DeviceRequestSelect { + return _q.Select().Aggregate(fns...) } -func (drq *DeviceRequestQuery) prepareQuery(ctx context.Context) error { - for _, inter := range drq.inters { +func (_q *DeviceRequestQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { if inter == nil { return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)") } if trv, ok := inter.(Traverser); ok { - if err := trv.Traverse(ctx, drq); err != nil { + if err := trv.Traverse(ctx, _q); err != nil { return err } } } - for _, f := range drq.ctx.Fields { + for _, f := range _q.ctx.Fields { if !devicerequest.ValidColumn(f) { return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} } } - if drq.path != nil { - prev, err := drq.path(ctx) + if _q.path != nil { + prev, err := _q.path(ctx) if err != nil { return err } - drq.sql = prev + _q.sql = prev } return nil } -func (drq *DeviceRequestQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*DeviceRequest, error) { +func (_q *DeviceRequestQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*DeviceRequest, error) { var ( nodes = []*DeviceRequest{} - _spec = drq.querySpec() + _spec = _q.querySpec() ) _spec.ScanValues = func(columns []string) ([]any, error) { return (*DeviceRequest).scanValues(nil, columns) } _spec.Assign = func(columns []string, values []any) error { - node := &DeviceRequest{config: drq.config} + node := &DeviceRequest{config: _q.config} nodes = append(nodes, node) return node.assignValues(columns, values) } for i := range hooks { hooks[i](ctx, _spec) } - if err := sqlgraph.QueryNodes(ctx, drq.driver, _spec); err != nil { + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { return nil, err } if len(nodes) == 0 { @@ -355,24 +355,24 @@ func (drq *DeviceRequestQuery) sqlAll(ctx context.Context, hooks ...queryHook) ( return nodes, nil } -func (drq *DeviceRequestQuery) sqlCount(ctx context.Context) (int, error) { - _spec := drq.querySpec() - _spec.Node.Columns = drq.ctx.Fields - if len(drq.ctx.Fields) > 0 { - _spec.Unique = drq.ctx.Unique != nil && *drq.ctx.Unique +func (_q *DeviceRequestQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique } - return sqlgraph.CountNodes(ctx, drq.driver, _spec) + return sqlgraph.CountNodes(ctx, _q.driver, _spec) } -func (drq *DeviceRequestQuery) querySpec() *sqlgraph.QuerySpec { +func (_q *DeviceRequestQuery) querySpec() *sqlgraph.QuerySpec { _spec := sqlgraph.NewQuerySpec(devicerequest.Table, devicerequest.Columns, sqlgraph.NewFieldSpec(devicerequest.FieldID, field.TypeInt)) - _spec.From = drq.sql - if unique := drq.ctx.Unique; unique != nil { + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { _spec.Unique = *unique - } else if drq.path != nil { + } else if _q.path != nil { _spec.Unique = true } - if fields := drq.ctx.Fields; len(fields) > 0 { + if fields := _q.ctx.Fields; len(fields) > 0 { _spec.Node.Columns = make([]string, 0, len(fields)) _spec.Node.Columns = append(_spec.Node.Columns, devicerequest.FieldID) for i := range fields { @@ -381,20 +381,20 @@ func (drq *DeviceRequestQuery) querySpec() *sqlgraph.QuerySpec { } } } - if ps := drq.predicates; len(ps) > 0 { + if ps := _q.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if limit := drq.ctx.Limit; limit != nil { + if limit := _q.ctx.Limit; limit != nil { _spec.Limit = *limit } - if offset := drq.ctx.Offset; offset != nil { + if offset := _q.ctx.Offset; offset != nil { _spec.Offset = *offset } - if ps := drq.order; len(ps) > 0 { + if ps := _q.order; len(ps) > 0 { _spec.Order = func(selector *sql.Selector) { for i := range ps { ps[i](selector) @@ -404,33 +404,33 @@ func (drq *DeviceRequestQuery) querySpec() *sqlgraph.QuerySpec { return _spec } -func (drq *DeviceRequestQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(drq.driver.Dialect()) +func (_q *DeviceRequestQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) t1 := builder.Table(devicerequest.Table) - columns := drq.ctx.Fields + columns := _q.ctx.Fields if len(columns) == 0 { columns = devicerequest.Columns } selector := builder.Select(t1.Columns(columns...)...).From(t1) - if drq.sql != nil { - selector = drq.sql + if _q.sql != nil { + selector = _q.sql selector.Select(selector.Columns(columns...)...) } - if drq.ctx.Unique != nil && *drq.ctx.Unique { + if _q.ctx.Unique != nil && *_q.ctx.Unique { selector.Distinct() } - for _, p := range drq.predicates { + for _, p := range _q.predicates { p(selector) } - for _, p := range drq.order { + for _, p := range _q.order { p(selector) } - if offset := drq.ctx.Offset; offset != nil { + if offset := _q.ctx.Offset; offset != nil { // limit is mandatory for offset clause. We start // with default value, and override it below if needed. selector.Offset(*offset).Limit(math.MaxInt32) } - if limit := drq.ctx.Limit; limit != nil { + if limit := _q.ctx.Limit; limit != nil { selector.Limit(*limit) } return selector @@ -443,41 +443,41 @@ type DeviceRequestGroupBy struct { } // Aggregate adds the given aggregation functions to the group-by query. -func (drgb *DeviceRequestGroupBy) Aggregate(fns ...AggregateFunc) *DeviceRequestGroupBy { - drgb.fns = append(drgb.fns, fns...) - return drgb +func (_g *DeviceRequestGroupBy) Aggregate(fns ...AggregateFunc) *DeviceRequestGroupBy { + _g.fns = append(_g.fns, fns...) + return _g } // Scan applies the selector query and scans the result into the given value. -func (drgb *DeviceRequestGroupBy) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, drgb.build.ctx, ent.OpQueryGroupBy) - if err := drgb.build.prepareQuery(ctx); err != nil { +func (_g *DeviceRequestGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { return err } - return scanWithInterceptors[*DeviceRequestQuery, *DeviceRequestGroupBy](ctx, drgb.build, drgb, drgb.build.inters, v) + return scanWithInterceptors[*DeviceRequestQuery, *DeviceRequestGroupBy](ctx, _g.build, _g, _g.build.inters, v) } -func (drgb *DeviceRequestGroupBy) sqlScan(ctx context.Context, root *DeviceRequestQuery, v any) error { +func (_g *DeviceRequestGroupBy) sqlScan(ctx context.Context, root *DeviceRequestQuery, v any) error { selector := root.sqlQuery(ctx).Select() - aggregation := make([]string, 0, len(drgb.fns)) - for _, fn := range drgb.fns { + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { aggregation = append(aggregation, fn(selector)) } if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(*drgb.flds)+len(drgb.fns)) - for _, f := range *drgb.flds { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { columns = append(columns, selector.C(f)) } columns = append(columns, aggregation...) selector.Select(columns...) } - selector.GroupBy(selector.Columns(*drgb.flds...)...) + selector.GroupBy(selector.Columns(*_g.flds...)...) if err := selector.Err(); err != nil { return err } rows := &sql.Rows{} query, args := selector.Query() - if err := drgb.build.driver.Query(ctx, query, args, rows); err != nil { + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() @@ -491,27 +491,27 @@ type DeviceRequestSelect struct { } // Aggregate adds the given aggregation functions to the selector query. -func (drs *DeviceRequestSelect) Aggregate(fns ...AggregateFunc) *DeviceRequestSelect { - drs.fns = append(drs.fns, fns...) - return drs +func (_s *DeviceRequestSelect) Aggregate(fns ...AggregateFunc) *DeviceRequestSelect { + _s.fns = append(_s.fns, fns...) + return _s } // Scan applies the selector query and scans the result into the given value. -func (drs *DeviceRequestSelect) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, drs.ctx, ent.OpQuerySelect) - if err := drs.prepareQuery(ctx); err != nil { +func (_s *DeviceRequestSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { return err } - return scanWithInterceptors[*DeviceRequestQuery, *DeviceRequestSelect](ctx, drs.DeviceRequestQuery, drs, drs.inters, v) + return scanWithInterceptors[*DeviceRequestQuery, *DeviceRequestSelect](ctx, _s.DeviceRequestQuery, _s, _s.inters, v) } -func (drs *DeviceRequestSelect) sqlScan(ctx context.Context, root *DeviceRequestQuery, v any) error { +func (_s *DeviceRequestSelect) sqlScan(ctx context.Context, root *DeviceRequestQuery, v any) error { selector := root.sqlQuery(ctx) - aggregation := make([]string, 0, len(drs.fns)) - for _, fn := range drs.fns { + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { aggregation = append(aggregation, fn(selector)) } - switch n := len(*drs.selector.flds); { + switch n := len(*_s.selector.flds); { case n == 0 && len(aggregation) > 0: selector.Select(aggregation...) case n != 0 && len(aggregation) > 0: @@ -519,7 +519,7 @@ func (drs *DeviceRequestSelect) sqlScan(ctx context.Context, root *DeviceRequest } rows := &sql.Rows{} query, args := selector.Query() - if err := drs.driver.Query(ctx, query, args, rows); err != nil { + if err := _s.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() diff --git a/storage/ent/db/devicerequest_update.go b/storage/ent/db/devicerequest_update.go index b71743c2c1..9447f4e532 100644 --- a/storage/ent/db/devicerequest_update.go +++ b/storage/ent/db/devicerequest_update.go @@ -24,112 +24,112 @@ type DeviceRequestUpdate struct { } // Where appends a list predicates to the DeviceRequestUpdate builder. -func (dru *DeviceRequestUpdate) Where(ps ...predicate.DeviceRequest) *DeviceRequestUpdate { - dru.mutation.Where(ps...) - return dru +func (_u *DeviceRequestUpdate) Where(ps ...predicate.DeviceRequest) *DeviceRequestUpdate { + _u.mutation.Where(ps...) + return _u } // SetUserCode sets the "user_code" field. -func (dru *DeviceRequestUpdate) SetUserCode(s string) *DeviceRequestUpdate { - dru.mutation.SetUserCode(s) - return dru +func (_u *DeviceRequestUpdate) SetUserCode(v string) *DeviceRequestUpdate { + _u.mutation.SetUserCode(v) + return _u } // SetNillableUserCode sets the "user_code" field if the given value is not nil. -func (dru *DeviceRequestUpdate) SetNillableUserCode(s *string) *DeviceRequestUpdate { - if s != nil { - dru.SetUserCode(*s) +func (_u *DeviceRequestUpdate) SetNillableUserCode(v *string) *DeviceRequestUpdate { + if v != nil { + _u.SetUserCode(*v) } - return dru + return _u } // SetDeviceCode sets the "device_code" field. -func (dru *DeviceRequestUpdate) SetDeviceCode(s string) *DeviceRequestUpdate { - dru.mutation.SetDeviceCode(s) - return dru +func (_u *DeviceRequestUpdate) SetDeviceCode(v string) *DeviceRequestUpdate { + _u.mutation.SetDeviceCode(v) + return _u } // SetNillableDeviceCode sets the "device_code" field if the given value is not nil. -func (dru *DeviceRequestUpdate) SetNillableDeviceCode(s *string) *DeviceRequestUpdate { - if s != nil { - dru.SetDeviceCode(*s) +func (_u *DeviceRequestUpdate) SetNillableDeviceCode(v *string) *DeviceRequestUpdate { + if v != nil { + _u.SetDeviceCode(*v) } - return dru + return _u } // SetClientID sets the "client_id" field. -func (dru *DeviceRequestUpdate) SetClientID(s string) *DeviceRequestUpdate { - dru.mutation.SetClientID(s) - return dru +func (_u *DeviceRequestUpdate) SetClientID(v string) *DeviceRequestUpdate { + _u.mutation.SetClientID(v) + return _u } // SetNillableClientID sets the "client_id" field if the given value is not nil. -func (dru *DeviceRequestUpdate) SetNillableClientID(s *string) *DeviceRequestUpdate { - if s != nil { - dru.SetClientID(*s) +func (_u *DeviceRequestUpdate) SetNillableClientID(v *string) *DeviceRequestUpdate { + if v != nil { + _u.SetClientID(*v) } - return dru + return _u } // SetClientSecret sets the "client_secret" field. -func (dru *DeviceRequestUpdate) SetClientSecret(s string) *DeviceRequestUpdate { - dru.mutation.SetClientSecret(s) - return dru +func (_u *DeviceRequestUpdate) SetClientSecret(v string) *DeviceRequestUpdate { + _u.mutation.SetClientSecret(v) + return _u } // SetNillableClientSecret sets the "client_secret" field if the given value is not nil. -func (dru *DeviceRequestUpdate) SetNillableClientSecret(s *string) *DeviceRequestUpdate { - if s != nil { - dru.SetClientSecret(*s) +func (_u *DeviceRequestUpdate) SetNillableClientSecret(v *string) *DeviceRequestUpdate { + if v != nil { + _u.SetClientSecret(*v) } - return dru + return _u } // SetScopes sets the "scopes" field. -func (dru *DeviceRequestUpdate) SetScopes(s []string) *DeviceRequestUpdate { - dru.mutation.SetScopes(s) - return dru +func (_u *DeviceRequestUpdate) SetScopes(v []string) *DeviceRequestUpdate { + _u.mutation.SetScopes(v) + return _u } -// AppendScopes appends s to the "scopes" field. -func (dru *DeviceRequestUpdate) AppendScopes(s []string) *DeviceRequestUpdate { - dru.mutation.AppendScopes(s) - return dru +// AppendScopes appends value to the "scopes" field. +func (_u *DeviceRequestUpdate) AppendScopes(v []string) *DeviceRequestUpdate { + _u.mutation.AppendScopes(v) + return _u } // ClearScopes clears the value of the "scopes" field. -func (dru *DeviceRequestUpdate) ClearScopes() *DeviceRequestUpdate { - dru.mutation.ClearScopes() - return dru +func (_u *DeviceRequestUpdate) ClearScopes() *DeviceRequestUpdate { + _u.mutation.ClearScopes() + return _u } // SetExpiry sets the "expiry" field. -func (dru *DeviceRequestUpdate) SetExpiry(t time.Time) *DeviceRequestUpdate { - dru.mutation.SetExpiry(t) - return dru +func (_u *DeviceRequestUpdate) SetExpiry(v time.Time) *DeviceRequestUpdate { + _u.mutation.SetExpiry(v) + return _u } // SetNillableExpiry sets the "expiry" field if the given value is not nil. -func (dru *DeviceRequestUpdate) SetNillableExpiry(t *time.Time) *DeviceRequestUpdate { - if t != nil { - dru.SetExpiry(*t) +func (_u *DeviceRequestUpdate) SetNillableExpiry(v *time.Time) *DeviceRequestUpdate { + if v != nil { + _u.SetExpiry(*v) } - return dru + return _u } // Mutation returns the DeviceRequestMutation object of the builder. -func (dru *DeviceRequestUpdate) Mutation() *DeviceRequestMutation { - return dru.mutation +func (_u *DeviceRequestUpdate) Mutation() *DeviceRequestMutation { + return _u.mutation } // Save executes the query and returns the number of nodes affected by the update operation. -func (dru *DeviceRequestUpdate) Save(ctx context.Context) (int, error) { - return withHooks(ctx, dru.sqlSave, dru.mutation, dru.hooks) +func (_u *DeviceRequestUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) } // SaveX is like Save, but panics if an error occurs. -func (dru *DeviceRequestUpdate) SaveX(ctx context.Context) int { - affected, err := dru.Save(ctx) +func (_u *DeviceRequestUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) if err != nil { panic(err) } @@ -137,36 +137,36 @@ func (dru *DeviceRequestUpdate) SaveX(ctx context.Context) int { } // Exec executes the query. -func (dru *DeviceRequestUpdate) Exec(ctx context.Context) error { - _, err := dru.Save(ctx) +func (_u *DeviceRequestUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (dru *DeviceRequestUpdate) ExecX(ctx context.Context) { - if err := dru.Exec(ctx); err != nil { +func (_u *DeviceRequestUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { panic(err) } } // check runs all checks and user-defined validators on the builder. -func (dru *DeviceRequestUpdate) check() error { - if v, ok := dru.mutation.UserCode(); ok { +func (_u *DeviceRequestUpdate) check() error { + if v, ok := _u.mutation.UserCode(); ok { if err := devicerequest.UserCodeValidator(v); err != nil { return &ValidationError{Name: "user_code", err: fmt.Errorf(`db: validator failed for field "DeviceRequest.user_code": %w`, err)} } } - if v, ok := dru.mutation.DeviceCode(); ok { + if v, ok := _u.mutation.DeviceCode(); ok { if err := devicerequest.DeviceCodeValidator(v); err != nil { return &ValidationError{Name: "device_code", err: fmt.Errorf(`db: validator failed for field "DeviceRequest.device_code": %w`, err)} } } - if v, ok := dru.mutation.ClientID(); ok { + if v, ok := _u.mutation.ClientID(); ok { if err := devicerequest.ClientIDValidator(v); err != nil { return &ValidationError{Name: "client_id", err: fmt.Errorf(`db: validator failed for field "DeviceRequest.client_id": %w`, err)} } } - if v, ok := dru.mutation.ClientSecret(); ok { + if v, ok := _u.mutation.ClientSecret(); ok { if err := devicerequest.ClientSecretValidator(v); err != nil { return &ValidationError{Name: "client_secret", err: fmt.Errorf(`db: validator failed for field "DeviceRequest.client_secret": %w`, err)} } @@ -174,45 +174,45 @@ func (dru *DeviceRequestUpdate) check() error { return nil } -func (dru *DeviceRequestUpdate) sqlSave(ctx context.Context) (n int, err error) { - if err := dru.check(); err != nil { - return n, err +func (_u *DeviceRequestUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err } _spec := sqlgraph.NewUpdateSpec(devicerequest.Table, devicerequest.Columns, sqlgraph.NewFieldSpec(devicerequest.FieldID, field.TypeInt)) - if ps := dru.mutation.predicates; len(ps) > 0 { + if ps := _u.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if value, ok := dru.mutation.UserCode(); ok { + if value, ok := _u.mutation.UserCode(); ok { _spec.SetField(devicerequest.FieldUserCode, field.TypeString, value) } - if value, ok := dru.mutation.DeviceCode(); ok { + if value, ok := _u.mutation.DeviceCode(); ok { _spec.SetField(devicerequest.FieldDeviceCode, field.TypeString, value) } - if value, ok := dru.mutation.ClientID(); ok { + if value, ok := _u.mutation.ClientID(); ok { _spec.SetField(devicerequest.FieldClientID, field.TypeString, value) } - if value, ok := dru.mutation.ClientSecret(); ok { + if value, ok := _u.mutation.ClientSecret(); ok { _spec.SetField(devicerequest.FieldClientSecret, field.TypeString, value) } - if value, ok := dru.mutation.Scopes(); ok { + if value, ok := _u.mutation.Scopes(); ok { _spec.SetField(devicerequest.FieldScopes, field.TypeJSON, value) } - if value, ok := dru.mutation.AppendedScopes(); ok { + if value, ok := _u.mutation.AppendedScopes(); ok { _spec.AddModifier(func(u *sql.UpdateBuilder) { sqljson.Append(u, devicerequest.FieldScopes, value) }) } - if dru.mutation.ScopesCleared() { + if _u.mutation.ScopesCleared() { _spec.ClearField(devicerequest.FieldScopes, field.TypeJSON) } - if value, ok := dru.mutation.Expiry(); ok { + if value, ok := _u.mutation.Expiry(); ok { _spec.SetField(devicerequest.FieldExpiry, field.TypeTime, value) } - if n, err = sqlgraph.UpdateNodes(ctx, dru.driver, _spec); err != nil { + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{devicerequest.Label} } else if sqlgraph.IsConstraintError(err) { @@ -220,8 +220,8 @@ func (dru *DeviceRequestUpdate) sqlSave(ctx context.Context) (n int, err error) } return 0, err } - dru.mutation.done = true - return n, nil + _u.mutation.done = true + return _node, nil } // DeviceRequestUpdateOne is the builder for updating a single DeviceRequest entity. @@ -233,119 +233,119 @@ type DeviceRequestUpdateOne struct { } // SetUserCode sets the "user_code" field. -func (druo *DeviceRequestUpdateOne) SetUserCode(s string) *DeviceRequestUpdateOne { - druo.mutation.SetUserCode(s) - return druo +func (_u *DeviceRequestUpdateOne) SetUserCode(v string) *DeviceRequestUpdateOne { + _u.mutation.SetUserCode(v) + return _u } // SetNillableUserCode sets the "user_code" field if the given value is not nil. -func (druo *DeviceRequestUpdateOne) SetNillableUserCode(s *string) *DeviceRequestUpdateOne { - if s != nil { - druo.SetUserCode(*s) +func (_u *DeviceRequestUpdateOne) SetNillableUserCode(v *string) *DeviceRequestUpdateOne { + if v != nil { + _u.SetUserCode(*v) } - return druo + return _u } // SetDeviceCode sets the "device_code" field. -func (druo *DeviceRequestUpdateOne) SetDeviceCode(s string) *DeviceRequestUpdateOne { - druo.mutation.SetDeviceCode(s) - return druo +func (_u *DeviceRequestUpdateOne) SetDeviceCode(v string) *DeviceRequestUpdateOne { + _u.mutation.SetDeviceCode(v) + return _u } // SetNillableDeviceCode sets the "device_code" field if the given value is not nil. -func (druo *DeviceRequestUpdateOne) SetNillableDeviceCode(s *string) *DeviceRequestUpdateOne { - if s != nil { - druo.SetDeviceCode(*s) +func (_u *DeviceRequestUpdateOne) SetNillableDeviceCode(v *string) *DeviceRequestUpdateOne { + if v != nil { + _u.SetDeviceCode(*v) } - return druo + return _u } // SetClientID sets the "client_id" field. -func (druo *DeviceRequestUpdateOne) SetClientID(s string) *DeviceRequestUpdateOne { - druo.mutation.SetClientID(s) - return druo +func (_u *DeviceRequestUpdateOne) SetClientID(v string) *DeviceRequestUpdateOne { + _u.mutation.SetClientID(v) + return _u } // SetNillableClientID sets the "client_id" field if the given value is not nil. -func (druo *DeviceRequestUpdateOne) SetNillableClientID(s *string) *DeviceRequestUpdateOne { - if s != nil { - druo.SetClientID(*s) +func (_u *DeviceRequestUpdateOne) SetNillableClientID(v *string) *DeviceRequestUpdateOne { + if v != nil { + _u.SetClientID(*v) } - return druo + return _u } // SetClientSecret sets the "client_secret" field. -func (druo *DeviceRequestUpdateOne) SetClientSecret(s string) *DeviceRequestUpdateOne { - druo.mutation.SetClientSecret(s) - return druo +func (_u *DeviceRequestUpdateOne) SetClientSecret(v string) *DeviceRequestUpdateOne { + _u.mutation.SetClientSecret(v) + return _u } // SetNillableClientSecret sets the "client_secret" field if the given value is not nil. -func (druo *DeviceRequestUpdateOne) SetNillableClientSecret(s *string) *DeviceRequestUpdateOne { - if s != nil { - druo.SetClientSecret(*s) +func (_u *DeviceRequestUpdateOne) SetNillableClientSecret(v *string) *DeviceRequestUpdateOne { + if v != nil { + _u.SetClientSecret(*v) } - return druo + return _u } // SetScopes sets the "scopes" field. -func (druo *DeviceRequestUpdateOne) SetScopes(s []string) *DeviceRequestUpdateOne { - druo.mutation.SetScopes(s) - return druo +func (_u *DeviceRequestUpdateOne) SetScopes(v []string) *DeviceRequestUpdateOne { + _u.mutation.SetScopes(v) + return _u } -// AppendScopes appends s to the "scopes" field. -func (druo *DeviceRequestUpdateOne) AppendScopes(s []string) *DeviceRequestUpdateOne { - druo.mutation.AppendScopes(s) - return druo +// AppendScopes appends value to the "scopes" field. +func (_u *DeviceRequestUpdateOne) AppendScopes(v []string) *DeviceRequestUpdateOne { + _u.mutation.AppendScopes(v) + return _u } // ClearScopes clears the value of the "scopes" field. -func (druo *DeviceRequestUpdateOne) ClearScopes() *DeviceRequestUpdateOne { - druo.mutation.ClearScopes() - return druo +func (_u *DeviceRequestUpdateOne) ClearScopes() *DeviceRequestUpdateOne { + _u.mutation.ClearScopes() + return _u } // SetExpiry sets the "expiry" field. -func (druo *DeviceRequestUpdateOne) SetExpiry(t time.Time) *DeviceRequestUpdateOne { - druo.mutation.SetExpiry(t) - return druo +func (_u *DeviceRequestUpdateOne) SetExpiry(v time.Time) *DeviceRequestUpdateOne { + _u.mutation.SetExpiry(v) + return _u } // SetNillableExpiry sets the "expiry" field if the given value is not nil. -func (druo *DeviceRequestUpdateOne) SetNillableExpiry(t *time.Time) *DeviceRequestUpdateOne { - if t != nil { - druo.SetExpiry(*t) +func (_u *DeviceRequestUpdateOne) SetNillableExpiry(v *time.Time) *DeviceRequestUpdateOne { + if v != nil { + _u.SetExpiry(*v) } - return druo + return _u } // Mutation returns the DeviceRequestMutation object of the builder. -func (druo *DeviceRequestUpdateOne) Mutation() *DeviceRequestMutation { - return druo.mutation +func (_u *DeviceRequestUpdateOne) Mutation() *DeviceRequestMutation { + return _u.mutation } // Where appends a list predicates to the DeviceRequestUpdate builder. -func (druo *DeviceRequestUpdateOne) Where(ps ...predicate.DeviceRequest) *DeviceRequestUpdateOne { - druo.mutation.Where(ps...) - return druo +func (_u *DeviceRequestUpdateOne) Where(ps ...predicate.DeviceRequest) *DeviceRequestUpdateOne { + _u.mutation.Where(ps...) + return _u } // Select allows selecting one or more fields (columns) of the returned entity. // The default is selecting all fields defined in the entity schema. -func (druo *DeviceRequestUpdateOne) Select(field string, fields ...string) *DeviceRequestUpdateOne { - druo.fields = append([]string{field}, fields...) - return druo +func (_u *DeviceRequestUpdateOne) Select(field string, fields ...string) *DeviceRequestUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u } // Save executes the query and returns the updated DeviceRequest entity. -func (druo *DeviceRequestUpdateOne) Save(ctx context.Context) (*DeviceRequest, error) { - return withHooks(ctx, druo.sqlSave, druo.mutation, druo.hooks) +func (_u *DeviceRequestUpdateOne) Save(ctx context.Context) (*DeviceRequest, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) } // SaveX is like Save, but panics if an error occurs. -func (druo *DeviceRequestUpdateOne) SaveX(ctx context.Context) *DeviceRequest { - node, err := druo.Save(ctx) +func (_u *DeviceRequestUpdateOne) SaveX(ctx context.Context) *DeviceRequest { + node, err := _u.Save(ctx) if err != nil { panic(err) } @@ -353,36 +353,36 @@ func (druo *DeviceRequestUpdateOne) SaveX(ctx context.Context) *DeviceRequest { } // Exec executes the query on the entity. -func (druo *DeviceRequestUpdateOne) Exec(ctx context.Context) error { - _, err := druo.Save(ctx) +func (_u *DeviceRequestUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (druo *DeviceRequestUpdateOne) ExecX(ctx context.Context) { - if err := druo.Exec(ctx); err != nil { +func (_u *DeviceRequestUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { panic(err) } } // check runs all checks and user-defined validators on the builder. -func (druo *DeviceRequestUpdateOne) check() error { - if v, ok := druo.mutation.UserCode(); ok { +func (_u *DeviceRequestUpdateOne) check() error { + if v, ok := _u.mutation.UserCode(); ok { if err := devicerequest.UserCodeValidator(v); err != nil { return &ValidationError{Name: "user_code", err: fmt.Errorf(`db: validator failed for field "DeviceRequest.user_code": %w`, err)} } } - if v, ok := druo.mutation.DeviceCode(); ok { + if v, ok := _u.mutation.DeviceCode(); ok { if err := devicerequest.DeviceCodeValidator(v); err != nil { return &ValidationError{Name: "device_code", err: fmt.Errorf(`db: validator failed for field "DeviceRequest.device_code": %w`, err)} } } - if v, ok := druo.mutation.ClientID(); ok { + if v, ok := _u.mutation.ClientID(); ok { if err := devicerequest.ClientIDValidator(v); err != nil { return &ValidationError{Name: "client_id", err: fmt.Errorf(`db: validator failed for field "DeviceRequest.client_id": %w`, err)} } } - if v, ok := druo.mutation.ClientSecret(); ok { + if v, ok := _u.mutation.ClientSecret(); ok { if err := devicerequest.ClientSecretValidator(v); err != nil { return &ValidationError{Name: "client_secret", err: fmt.Errorf(`db: validator failed for field "DeviceRequest.client_secret": %w`, err)} } @@ -390,17 +390,17 @@ func (druo *DeviceRequestUpdateOne) check() error { return nil } -func (druo *DeviceRequestUpdateOne) sqlSave(ctx context.Context) (_node *DeviceRequest, err error) { - if err := druo.check(); err != nil { +func (_u *DeviceRequestUpdateOne) sqlSave(ctx context.Context) (_node *DeviceRequest, err error) { + if err := _u.check(); err != nil { return _node, err } _spec := sqlgraph.NewUpdateSpec(devicerequest.Table, devicerequest.Columns, sqlgraph.NewFieldSpec(devicerequest.FieldID, field.TypeInt)) - id, ok := druo.mutation.ID() + id, ok := _u.mutation.ID() if !ok { return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "DeviceRequest.id" for update`)} } _spec.Node.ID.Value = id - if fields := druo.fields; len(fields) > 0 { + if fields := _u.fields; len(fields) > 0 { _spec.Node.Columns = make([]string, 0, len(fields)) _spec.Node.Columns = append(_spec.Node.Columns, devicerequest.FieldID) for _, f := range fields { @@ -412,43 +412,43 @@ func (druo *DeviceRequestUpdateOne) sqlSave(ctx context.Context) (_node *DeviceR } } } - if ps := druo.mutation.predicates; len(ps) > 0 { + if ps := _u.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if value, ok := druo.mutation.UserCode(); ok { + if value, ok := _u.mutation.UserCode(); ok { _spec.SetField(devicerequest.FieldUserCode, field.TypeString, value) } - if value, ok := druo.mutation.DeviceCode(); ok { + if value, ok := _u.mutation.DeviceCode(); ok { _spec.SetField(devicerequest.FieldDeviceCode, field.TypeString, value) } - if value, ok := druo.mutation.ClientID(); ok { + if value, ok := _u.mutation.ClientID(); ok { _spec.SetField(devicerequest.FieldClientID, field.TypeString, value) } - if value, ok := druo.mutation.ClientSecret(); ok { + if value, ok := _u.mutation.ClientSecret(); ok { _spec.SetField(devicerequest.FieldClientSecret, field.TypeString, value) } - if value, ok := druo.mutation.Scopes(); ok { + if value, ok := _u.mutation.Scopes(); ok { _spec.SetField(devicerequest.FieldScopes, field.TypeJSON, value) } - if value, ok := druo.mutation.AppendedScopes(); ok { + if value, ok := _u.mutation.AppendedScopes(); ok { _spec.AddModifier(func(u *sql.UpdateBuilder) { sqljson.Append(u, devicerequest.FieldScopes, value) }) } - if druo.mutation.ScopesCleared() { + if _u.mutation.ScopesCleared() { _spec.ClearField(devicerequest.FieldScopes, field.TypeJSON) } - if value, ok := druo.mutation.Expiry(); ok { + if value, ok := _u.mutation.Expiry(); ok { _spec.SetField(devicerequest.FieldExpiry, field.TypeTime, value) } - _node = &DeviceRequest{config: druo.config} + _node = &DeviceRequest{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, druo.driver, _spec); err != nil { + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{devicerequest.Label} } else if sqlgraph.IsConstraintError(err) { @@ -456,6 +456,6 @@ func (druo *DeviceRequestUpdateOne) sqlSave(ctx context.Context) (_node *DeviceR } return nil, err } - druo.mutation.done = true + _u.mutation.done = true return _node, nil } diff --git a/storage/ent/db/devicetoken.go b/storage/ent/db/devicetoken.go index 0eda024e05..30b69d0307 100644 --- a/storage/ent/db/devicetoken.go +++ b/storage/ent/db/devicetoken.go @@ -58,7 +58,7 @@ func (*DeviceToken) scanValues(columns []string) ([]any, error) { // assignValues assigns the values that were returned from sql.Rows (after scanning) // to the DeviceToken fields. -func (dt *DeviceToken) assignValues(columns []string, values []any) error { +func (_m *DeviceToken) 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) } @@ -69,57 +69,57 @@ func (dt *DeviceToken) assignValues(columns []string, values []any) error { if !ok { return fmt.Errorf("unexpected type %T for field id", value) } - dt.ID = int(value.Int64) + _m.ID = int(value.Int64) case devicetoken.FieldDeviceCode: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field device_code", values[i]) } else if value.Valid { - dt.DeviceCode = value.String + _m.DeviceCode = value.String } case devicetoken.FieldStatus: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field status", values[i]) } else if value.Valid { - dt.Status = value.String + _m.Status = value.String } case devicetoken.FieldToken: if value, ok := values[i].(*[]byte); !ok { return fmt.Errorf("unexpected type %T for field token", values[i]) } else if value != nil { - dt.Token = value + _m.Token = value } case devicetoken.FieldExpiry: if value, ok := values[i].(*sql.NullTime); !ok { return fmt.Errorf("unexpected type %T for field expiry", values[i]) } else if value.Valid { - dt.Expiry = value.Time + _m.Expiry = value.Time } case devicetoken.FieldLastRequest: if value, ok := values[i].(*sql.NullTime); !ok { return fmt.Errorf("unexpected type %T for field last_request", values[i]) } else if value.Valid { - dt.LastRequest = value.Time + _m.LastRequest = value.Time } case devicetoken.FieldPollInterval: if value, ok := values[i].(*sql.NullInt64); !ok { return fmt.Errorf("unexpected type %T for field poll_interval", values[i]) } else if value.Valid { - dt.PollInterval = int(value.Int64) + _m.PollInterval = int(value.Int64) } case devicetoken.FieldCodeChallenge: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field code_challenge", values[i]) } else if value.Valid { - dt.CodeChallenge = value.String + _m.CodeChallenge = value.String } case devicetoken.FieldCodeChallengeMethod: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field code_challenge_method", values[i]) } else if value.Valid { - dt.CodeChallengeMethod = value.String + _m.CodeChallengeMethod = value.String } default: - dt.selectValues.Set(columns[i], values[i]) + _m.selectValues.Set(columns[i], values[i]) } } return nil @@ -127,58 +127,58 @@ func (dt *DeviceToken) assignValues(columns []string, values []any) error { // Value returns the ent.Value that was dynamically selected and assigned to the DeviceToken. // This includes values selected through modifiers, order, etc. -func (dt *DeviceToken) Value(name string) (ent.Value, error) { - return dt.selectValues.Get(name) +func (_m *DeviceToken) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) } // Update returns a builder for updating this DeviceToken. // Note that you need to call DeviceToken.Unwrap() before calling this method if this DeviceToken // was returned from a transaction, and the transaction was committed or rolled back. -func (dt *DeviceToken) Update() *DeviceTokenUpdateOne { - return NewDeviceTokenClient(dt.config).UpdateOne(dt) +func (_m *DeviceToken) Update() *DeviceTokenUpdateOne { + return NewDeviceTokenClient(_m.config).UpdateOne(_m) } // Unwrap unwraps the DeviceToken entity that was returned from a transaction after it was closed, // so that all future queries will be executed through the driver which created the transaction. -func (dt *DeviceToken) Unwrap() *DeviceToken { - _tx, ok := dt.config.driver.(*txDriver) +func (_m *DeviceToken) Unwrap() *DeviceToken { + _tx, ok := _m.config.driver.(*txDriver) if !ok { panic("db: DeviceToken is not a transactional entity") } - dt.config.driver = _tx.drv - return dt + _m.config.driver = _tx.drv + return _m } // String implements the fmt.Stringer. -func (dt *DeviceToken) String() string { +func (_m *DeviceToken) String() string { var builder strings.Builder builder.WriteString("DeviceToken(") - builder.WriteString(fmt.Sprintf("id=%v, ", dt.ID)) + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) builder.WriteString("device_code=") - builder.WriteString(dt.DeviceCode) + builder.WriteString(_m.DeviceCode) builder.WriteString(", ") builder.WriteString("status=") - builder.WriteString(dt.Status) + builder.WriteString(_m.Status) builder.WriteString(", ") - if v := dt.Token; v != nil { + if v := _m.Token; v != nil { builder.WriteString("token=") builder.WriteString(fmt.Sprintf("%v", *v)) } builder.WriteString(", ") builder.WriteString("expiry=") - builder.WriteString(dt.Expiry.Format(time.ANSIC)) + builder.WriteString(_m.Expiry.Format(time.ANSIC)) builder.WriteString(", ") builder.WriteString("last_request=") - builder.WriteString(dt.LastRequest.Format(time.ANSIC)) + builder.WriteString(_m.LastRequest.Format(time.ANSIC)) builder.WriteString(", ") builder.WriteString("poll_interval=") - builder.WriteString(fmt.Sprintf("%v", dt.PollInterval)) + builder.WriteString(fmt.Sprintf("%v", _m.PollInterval)) builder.WriteString(", ") builder.WriteString("code_challenge=") - builder.WriteString(dt.CodeChallenge) + builder.WriteString(_m.CodeChallenge) builder.WriteString(", ") builder.WriteString("code_challenge_method=") - builder.WriteString(dt.CodeChallengeMethod) + builder.WriteString(_m.CodeChallengeMethod) builder.WriteByte(')') return builder.String() } diff --git a/storage/ent/db/devicetoken_create.go b/storage/ent/db/devicetoken_create.go index 966d208fae..577d475103 100644 --- a/storage/ent/db/devicetoken_create.go +++ b/storage/ent/db/devicetoken_create.go @@ -21,83 +21,83 @@ type DeviceTokenCreate struct { } // SetDeviceCode sets the "device_code" field. -func (dtc *DeviceTokenCreate) SetDeviceCode(s string) *DeviceTokenCreate { - dtc.mutation.SetDeviceCode(s) - return dtc +func (_c *DeviceTokenCreate) SetDeviceCode(v string) *DeviceTokenCreate { + _c.mutation.SetDeviceCode(v) + return _c } // SetStatus sets the "status" field. -func (dtc *DeviceTokenCreate) SetStatus(s string) *DeviceTokenCreate { - dtc.mutation.SetStatus(s) - return dtc +func (_c *DeviceTokenCreate) SetStatus(v string) *DeviceTokenCreate { + _c.mutation.SetStatus(v) + return _c } // SetToken sets the "token" field. -func (dtc *DeviceTokenCreate) SetToken(b []byte) *DeviceTokenCreate { - dtc.mutation.SetToken(b) - return dtc +func (_c *DeviceTokenCreate) SetToken(v []byte) *DeviceTokenCreate { + _c.mutation.SetToken(v) + return _c } // SetExpiry sets the "expiry" field. -func (dtc *DeviceTokenCreate) SetExpiry(t time.Time) *DeviceTokenCreate { - dtc.mutation.SetExpiry(t) - return dtc +func (_c *DeviceTokenCreate) SetExpiry(v time.Time) *DeviceTokenCreate { + _c.mutation.SetExpiry(v) + return _c } // SetLastRequest sets the "last_request" field. -func (dtc *DeviceTokenCreate) SetLastRequest(t time.Time) *DeviceTokenCreate { - dtc.mutation.SetLastRequest(t) - return dtc +func (_c *DeviceTokenCreate) SetLastRequest(v time.Time) *DeviceTokenCreate { + _c.mutation.SetLastRequest(v) + return _c } // SetPollInterval sets the "poll_interval" field. -func (dtc *DeviceTokenCreate) SetPollInterval(i int) *DeviceTokenCreate { - dtc.mutation.SetPollInterval(i) - return dtc +func (_c *DeviceTokenCreate) SetPollInterval(v int) *DeviceTokenCreate { + _c.mutation.SetPollInterval(v) + return _c } // SetCodeChallenge sets the "code_challenge" field. -func (dtc *DeviceTokenCreate) SetCodeChallenge(s string) *DeviceTokenCreate { - dtc.mutation.SetCodeChallenge(s) - return dtc +func (_c *DeviceTokenCreate) SetCodeChallenge(v string) *DeviceTokenCreate { + _c.mutation.SetCodeChallenge(v) + return _c } // SetNillableCodeChallenge sets the "code_challenge" field if the given value is not nil. -func (dtc *DeviceTokenCreate) SetNillableCodeChallenge(s *string) *DeviceTokenCreate { - if s != nil { - dtc.SetCodeChallenge(*s) +func (_c *DeviceTokenCreate) SetNillableCodeChallenge(v *string) *DeviceTokenCreate { + if v != nil { + _c.SetCodeChallenge(*v) } - return dtc + return _c } // SetCodeChallengeMethod sets the "code_challenge_method" field. -func (dtc *DeviceTokenCreate) SetCodeChallengeMethod(s string) *DeviceTokenCreate { - dtc.mutation.SetCodeChallengeMethod(s) - return dtc +func (_c *DeviceTokenCreate) SetCodeChallengeMethod(v string) *DeviceTokenCreate { + _c.mutation.SetCodeChallengeMethod(v) + return _c } // SetNillableCodeChallengeMethod sets the "code_challenge_method" field if the given value is not nil. -func (dtc *DeviceTokenCreate) SetNillableCodeChallengeMethod(s *string) *DeviceTokenCreate { - if s != nil { - dtc.SetCodeChallengeMethod(*s) +func (_c *DeviceTokenCreate) SetNillableCodeChallengeMethod(v *string) *DeviceTokenCreate { + if v != nil { + _c.SetCodeChallengeMethod(*v) } - return dtc + return _c } // Mutation returns the DeviceTokenMutation object of the builder. -func (dtc *DeviceTokenCreate) Mutation() *DeviceTokenMutation { - return dtc.mutation +func (_c *DeviceTokenCreate) Mutation() *DeviceTokenMutation { + return _c.mutation } // Save creates the DeviceToken in the database. -func (dtc *DeviceTokenCreate) Save(ctx context.Context) (*DeviceToken, error) { - dtc.defaults() - return withHooks(ctx, dtc.sqlSave, dtc.mutation, dtc.hooks) +func (_c *DeviceTokenCreate) Save(ctx context.Context) (*DeviceToken, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) } // SaveX calls Save and panics if Save returns an error. -func (dtc *DeviceTokenCreate) SaveX(ctx context.Context) *DeviceToken { - v, err := dtc.Save(ctx) +func (_c *DeviceTokenCreate) SaveX(ctx context.Context) *DeviceToken { + v, err := _c.Save(ctx) if err != nil { panic(err) } @@ -105,72 +105,72 @@ func (dtc *DeviceTokenCreate) SaveX(ctx context.Context) *DeviceToken { } // Exec executes the query. -func (dtc *DeviceTokenCreate) Exec(ctx context.Context) error { - _, err := dtc.Save(ctx) +func (_c *DeviceTokenCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (dtc *DeviceTokenCreate) ExecX(ctx context.Context) { - if err := dtc.Exec(ctx); err != nil { +func (_c *DeviceTokenCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { panic(err) } } // defaults sets the default values of the builder before save. -func (dtc *DeviceTokenCreate) defaults() { - if _, ok := dtc.mutation.CodeChallenge(); !ok { +func (_c *DeviceTokenCreate) defaults() { + if _, ok := _c.mutation.CodeChallenge(); !ok { v := devicetoken.DefaultCodeChallenge - dtc.mutation.SetCodeChallenge(v) + _c.mutation.SetCodeChallenge(v) } - if _, ok := dtc.mutation.CodeChallengeMethod(); !ok { + if _, ok := _c.mutation.CodeChallengeMethod(); !ok { v := devicetoken.DefaultCodeChallengeMethod - dtc.mutation.SetCodeChallengeMethod(v) + _c.mutation.SetCodeChallengeMethod(v) } } // check runs all checks and user-defined validators on the builder. -func (dtc *DeviceTokenCreate) check() error { - if _, ok := dtc.mutation.DeviceCode(); !ok { +func (_c *DeviceTokenCreate) check() error { + if _, ok := _c.mutation.DeviceCode(); !ok { return &ValidationError{Name: "device_code", err: errors.New(`db: missing required field "DeviceToken.device_code"`)} } - if v, ok := dtc.mutation.DeviceCode(); ok { + if v, ok := _c.mutation.DeviceCode(); ok { if err := devicetoken.DeviceCodeValidator(v); err != nil { return &ValidationError{Name: "device_code", err: fmt.Errorf(`db: validator failed for field "DeviceToken.device_code": %w`, err)} } } - if _, ok := dtc.mutation.Status(); !ok { + if _, ok := _c.mutation.Status(); !ok { return &ValidationError{Name: "status", err: errors.New(`db: missing required field "DeviceToken.status"`)} } - if v, ok := dtc.mutation.Status(); ok { + if v, ok := _c.mutation.Status(); ok { if err := devicetoken.StatusValidator(v); err != nil { return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "DeviceToken.status": %w`, err)} } } - if _, ok := dtc.mutation.Expiry(); !ok { + if _, ok := _c.mutation.Expiry(); !ok { return &ValidationError{Name: "expiry", err: errors.New(`db: missing required field "DeviceToken.expiry"`)} } - if _, ok := dtc.mutation.LastRequest(); !ok { + if _, ok := _c.mutation.LastRequest(); !ok { return &ValidationError{Name: "last_request", err: errors.New(`db: missing required field "DeviceToken.last_request"`)} } - if _, ok := dtc.mutation.PollInterval(); !ok { + if _, ok := _c.mutation.PollInterval(); !ok { return &ValidationError{Name: "poll_interval", err: errors.New(`db: missing required field "DeviceToken.poll_interval"`)} } - if _, ok := dtc.mutation.CodeChallenge(); !ok { + if _, ok := _c.mutation.CodeChallenge(); !ok { return &ValidationError{Name: "code_challenge", err: errors.New(`db: missing required field "DeviceToken.code_challenge"`)} } - if _, ok := dtc.mutation.CodeChallengeMethod(); !ok { + if _, ok := _c.mutation.CodeChallengeMethod(); !ok { return &ValidationError{Name: "code_challenge_method", err: errors.New(`db: missing required field "DeviceToken.code_challenge_method"`)} } return nil } -func (dtc *DeviceTokenCreate) sqlSave(ctx context.Context) (*DeviceToken, error) { - if err := dtc.check(); err != nil { +func (_c *DeviceTokenCreate) sqlSave(ctx context.Context) (*DeviceToken, error) { + if err := _c.check(); err != nil { return nil, err } - _node, _spec := dtc.createSpec() - if err := sqlgraph.CreateNode(ctx, dtc.driver, _spec); err != nil { + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { if sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } @@ -178,45 +178,45 @@ func (dtc *DeviceTokenCreate) sqlSave(ctx context.Context) (*DeviceToken, error) } id := _spec.ID.Value.(int64) _node.ID = int(id) - dtc.mutation.id = &_node.ID - dtc.mutation.done = true + _c.mutation.id = &_node.ID + _c.mutation.done = true return _node, nil } -func (dtc *DeviceTokenCreate) createSpec() (*DeviceToken, *sqlgraph.CreateSpec) { +func (_c *DeviceTokenCreate) createSpec() (*DeviceToken, *sqlgraph.CreateSpec) { var ( - _node = &DeviceToken{config: dtc.config} + _node = &DeviceToken{config: _c.config} _spec = sqlgraph.NewCreateSpec(devicetoken.Table, sqlgraph.NewFieldSpec(devicetoken.FieldID, field.TypeInt)) ) - if value, ok := dtc.mutation.DeviceCode(); ok { + if value, ok := _c.mutation.DeviceCode(); ok { _spec.SetField(devicetoken.FieldDeviceCode, field.TypeString, value) _node.DeviceCode = value } - if value, ok := dtc.mutation.Status(); ok { + if value, ok := _c.mutation.Status(); ok { _spec.SetField(devicetoken.FieldStatus, field.TypeString, value) _node.Status = value } - if value, ok := dtc.mutation.Token(); ok { + if value, ok := _c.mutation.Token(); ok { _spec.SetField(devicetoken.FieldToken, field.TypeBytes, value) _node.Token = &value } - if value, ok := dtc.mutation.Expiry(); ok { + if value, ok := _c.mutation.Expiry(); ok { _spec.SetField(devicetoken.FieldExpiry, field.TypeTime, value) _node.Expiry = value } - if value, ok := dtc.mutation.LastRequest(); ok { + if value, ok := _c.mutation.LastRequest(); ok { _spec.SetField(devicetoken.FieldLastRequest, field.TypeTime, value) _node.LastRequest = value } - if value, ok := dtc.mutation.PollInterval(); ok { + if value, ok := _c.mutation.PollInterval(); ok { _spec.SetField(devicetoken.FieldPollInterval, field.TypeInt, value) _node.PollInterval = value } - if value, ok := dtc.mutation.CodeChallenge(); ok { + if value, ok := _c.mutation.CodeChallenge(); ok { _spec.SetField(devicetoken.FieldCodeChallenge, field.TypeString, value) _node.CodeChallenge = value } - if value, ok := dtc.mutation.CodeChallengeMethod(); ok { + if value, ok := _c.mutation.CodeChallengeMethod(); ok { _spec.SetField(devicetoken.FieldCodeChallengeMethod, field.TypeString, value) _node.CodeChallengeMethod = value } @@ -231,16 +231,16 @@ type DeviceTokenCreateBulk struct { } // Save creates the DeviceToken entities in the database. -func (dtcb *DeviceTokenCreateBulk) Save(ctx context.Context) ([]*DeviceToken, error) { - if dtcb.err != nil { - return nil, dtcb.err +func (_c *DeviceTokenCreateBulk) Save(ctx context.Context) ([]*DeviceToken, error) { + if _c.err != nil { + return nil, _c.err } - specs := make([]*sqlgraph.CreateSpec, len(dtcb.builders)) - nodes := make([]*DeviceToken, len(dtcb.builders)) - mutators := make([]Mutator, len(dtcb.builders)) - for i := range dtcb.builders { + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*DeviceToken, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { func(i int, root context.Context) { - builder := dtcb.builders[i] + builder := _c.builders[i] builder.defaults() var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { mutation, ok := m.(*DeviceTokenMutation) @@ -254,11 +254,11 @@ func (dtcb *DeviceTokenCreateBulk) Save(ctx context.Context) ([]*DeviceToken, er var err error nodes[i], specs[i] = builder.createSpec() if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, dtcb.builders[i+1].mutation) + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, dtcb.driver, spec); err != nil { + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { if sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } @@ -282,7 +282,7 @@ func (dtcb *DeviceTokenCreateBulk) Save(ctx context.Context) ([]*DeviceToken, er }(i, ctx) } if len(mutators) > 0 { - if _, err := mutators[0].Mutate(ctx, dtcb.builders[0].mutation); err != nil { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { return nil, err } } @@ -290,8 +290,8 @@ func (dtcb *DeviceTokenCreateBulk) Save(ctx context.Context) ([]*DeviceToken, er } // SaveX is like Save, but panics if an error occurs. -func (dtcb *DeviceTokenCreateBulk) SaveX(ctx context.Context) []*DeviceToken { - v, err := dtcb.Save(ctx) +func (_c *DeviceTokenCreateBulk) SaveX(ctx context.Context) []*DeviceToken { + v, err := _c.Save(ctx) if err != nil { panic(err) } @@ -299,14 +299,14 @@ func (dtcb *DeviceTokenCreateBulk) SaveX(ctx context.Context) []*DeviceToken { } // Exec executes the query. -func (dtcb *DeviceTokenCreateBulk) Exec(ctx context.Context) error { - _, err := dtcb.Save(ctx) +func (_c *DeviceTokenCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (dtcb *DeviceTokenCreateBulk) ExecX(ctx context.Context) { - if err := dtcb.Exec(ctx); err != nil { +func (_c *DeviceTokenCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { panic(err) } } diff --git a/storage/ent/db/devicetoken_delete.go b/storage/ent/db/devicetoken_delete.go index 9632450b0b..02acd31454 100644 --- a/storage/ent/db/devicetoken_delete.go +++ b/storage/ent/db/devicetoken_delete.go @@ -20,56 +20,56 @@ type DeviceTokenDelete struct { } // Where appends a list predicates to the DeviceTokenDelete builder. -func (dtd *DeviceTokenDelete) Where(ps ...predicate.DeviceToken) *DeviceTokenDelete { - dtd.mutation.Where(ps...) - return dtd +func (_d *DeviceTokenDelete) Where(ps ...predicate.DeviceToken) *DeviceTokenDelete { + _d.mutation.Where(ps...) + return _d } // Exec executes the deletion query and returns how many vertices were deleted. -func (dtd *DeviceTokenDelete) Exec(ctx context.Context) (int, error) { - return withHooks(ctx, dtd.sqlExec, dtd.mutation, dtd.hooks) +func (_d *DeviceTokenDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) } // ExecX is like Exec, but panics if an error occurs. -func (dtd *DeviceTokenDelete) ExecX(ctx context.Context) int { - n, err := dtd.Exec(ctx) +func (_d *DeviceTokenDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) if err != nil { panic(err) } return n } -func (dtd *DeviceTokenDelete) sqlExec(ctx context.Context) (int, error) { +func (_d *DeviceTokenDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(devicetoken.Table, sqlgraph.NewFieldSpec(devicetoken.FieldID, field.TypeInt)) - if ps := dtd.mutation.predicates; len(ps) > 0 { + if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - affected, err := sqlgraph.DeleteNodes(ctx, dtd.driver, _spec) + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) if err != nil && sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } - dtd.mutation.done = true + _d.mutation.done = true return affected, err } // DeviceTokenDeleteOne is the builder for deleting a single DeviceToken entity. type DeviceTokenDeleteOne struct { - dtd *DeviceTokenDelete + _d *DeviceTokenDelete } // Where appends a list predicates to the DeviceTokenDelete builder. -func (dtdo *DeviceTokenDeleteOne) Where(ps ...predicate.DeviceToken) *DeviceTokenDeleteOne { - dtdo.dtd.mutation.Where(ps...) - return dtdo +func (_d *DeviceTokenDeleteOne) Where(ps ...predicate.DeviceToken) *DeviceTokenDeleteOne { + _d._d.mutation.Where(ps...) + return _d } // Exec executes the deletion query. -func (dtdo *DeviceTokenDeleteOne) Exec(ctx context.Context) error { - n, err := dtdo.dtd.Exec(ctx) +func (_d *DeviceTokenDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) switch { case err != nil: return err @@ -81,8 +81,8 @@ func (dtdo *DeviceTokenDeleteOne) Exec(ctx context.Context) error { } // ExecX is like Exec, but panics if an error occurs. -func (dtdo *DeviceTokenDeleteOne) ExecX(ctx context.Context) { - if err := dtdo.Exec(ctx); err != nil { +func (_d *DeviceTokenDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { panic(err) } } diff --git a/storage/ent/db/devicetoken_query.go b/storage/ent/db/devicetoken_query.go index cbdc9dac7d..af910afdc6 100644 --- a/storage/ent/db/devicetoken_query.go +++ b/storage/ent/db/devicetoken_query.go @@ -28,40 +28,40 @@ type DeviceTokenQuery struct { } // Where adds a new predicate for the DeviceTokenQuery builder. -func (dtq *DeviceTokenQuery) Where(ps ...predicate.DeviceToken) *DeviceTokenQuery { - dtq.predicates = append(dtq.predicates, ps...) - return dtq +func (_q *DeviceTokenQuery) Where(ps ...predicate.DeviceToken) *DeviceTokenQuery { + _q.predicates = append(_q.predicates, ps...) + return _q } // Limit the number of records to be returned by this query. -func (dtq *DeviceTokenQuery) Limit(limit int) *DeviceTokenQuery { - dtq.ctx.Limit = &limit - return dtq +func (_q *DeviceTokenQuery) Limit(limit int) *DeviceTokenQuery { + _q.ctx.Limit = &limit + return _q } // Offset to start from. -func (dtq *DeviceTokenQuery) Offset(offset int) *DeviceTokenQuery { - dtq.ctx.Offset = &offset - return dtq +func (_q *DeviceTokenQuery) Offset(offset int) *DeviceTokenQuery { + _q.ctx.Offset = &offset + return _q } // Unique configures the query builder to filter duplicate records on query. // By default, unique is set to true, and can be disabled using this method. -func (dtq *DeviceTokenQuery) Unique(unique bool) *DeviceTokenQuery { - dtq.ctx.Unique = &unique - return dtq +func (_q *DeviceTokenQuery) Unique(unique bool) *DeviceTokenQuery { + _q.ctx.Unique = &unique + return _q } // Order specifies how the records should be ordered. -func (dtq *DeviceTokenQuery) Order(o ...devicetoken.OrderOption) *DeviceTokenQuery { - dtq.order = append(dtq.order, o...) - return dtq +func (_q *DeviceTokenQuery) Order(o ...devicetoken.OrderOption) *DeviceTokenQuery { + _q.order = append(_q.order, o...) + return _q } // First returns the first DeviceToken entity from the query. // Returns a *NotFoundError when no DeviceToken was found. -func (dtq *DeviceTokenQuery) First(ctx context.Context) (*DeviceToken, error) { - nodes, err := dtq.Limit(1).All(setContextOp(ctx, dtq.ctx, ent.OpQueryFirst)) +func (_q *DeviceTokenQuery) First(ctx context.Context) (*DeviceToken, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) if err != nil { return nil, err } @@ -72,8 +72,8 @@ func (dtq *DeviceTokenQuery) First(ctx context.Context) (*DeviceToken, error) { } // FirstX is like First, but panics if an error occurs. -func (dtq *DeviceTokenQuery) FirstX(ctx context.Context) *DeviceToken { - node, err := dtq.First(ctx) +func (_q *DeviceTokenQuery) FirstX(ctx context.Context) *DeviceToken { + node, err := _q.First(ctx) if err != nil && !IsNotFound(err) { panic(err) } @@ -82,9 +82,9 @@ func (dtq *DeviceTokenQuery) FirstX(ctx context.Context) *DeviceToken { // FirstID returns the first DeviceToken ID from the query. // Returns a *NotFoundError when no DeviceToken ID was found. -func (dtq *DeviceTokenQuery) FirstID(ctx context.Context) (id int, err error) { +func (_q *DeviceTokenQuery) FirstID(ctx context.Context) (id int, err error) { var ids []int - if ids, err = dtq.Limit(1).IDs(setContextOp(ctx, dtq.ctx, ent.OpQueryFirstID)); err != nil { + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { return } if len(ids) == 0 { @@ -95,8 +95,8 @@ func (dtq *DeviceTokenQuery) FirstID(ctx context.Context) (id int, err error) { } // FirstIDX is like FirstID, but panics if an error occurs. -func (dtq *DeviceTokenQuery) FirstIDX(ctx context.Context) int { - id, err := dtq.FirstID(ctx) +func (_q *DeviceTokenQuery) FirstIDX(ctx context.Context) int { + id, err := _q.FirstID(ctx) if err != nil && !IsNotFound(err) { panic(err) } @@ -106,8 +106,8 @@ func (dtq *DeviceTokenQuery) FirstIDX(ctx context.Context) int { // Only returns a single DeviceToken entity found by the query, ensuring it only returns one. // Returns a *NotSingularError when more than one DeviceToken entity is found. // Returns a *NotFoundError when no DeviceToken entities are found. -func (dtq *DeviceTokenQuery) Only(ctx context.Context) (*DeviceToken, error) { - nodes, err := dtq.Limit(2).All(setContextOp(ctx, dtq.ctx, ent.OpQueryOnly)) +func (_q *DeviceTokenQuery) Only(ctx context.Context) (*DeviceToken, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) if err != nil { return nil, err } @@ -122,8 +122,8 @@ func (dtq *DeviceTokenQuery) Only(ctx context.Context) (*DeviceToken, error) { } // OnlyX is like Only, but panics if an error occurs. -func (dtq *DeviceTokenQuery) OnlyX(ctx context.Context) *DeviceToken { - node, err := dtq.Only(ctx) +func (_q *DeviceTokenQuery) OnlyX(ctx context.Context) *DeviceToken { + node, err := _q.Only(ctx) if err != nil { panic(err) } @@ -133,9 +133,9 @@ func (dtq *DeviceTokenQuery) OnlyX(ctx context.Context) *DeviceToken { // OnlyID is like Only, but returns the only DeviceToken ID in the query. // Returns a *NotSingularError when more than one DeviceToken ID is found. // Returns a *NotFoundError when no entities are found. -func (dtq *DeviceTokenQuery) OnlyID(ctx context.Context) (id int, err error) { +func (_q *DeviceTokenQuery) OnlyID(ctx context.Context) (id int, err error) { var ids []int - if ids, err = dtq.Limit(2).IDs(setContextOp(ctx, dtq.ctx, ent.OpQueryOnlyID)); err != nil { + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { return } switch len(ids) { @@ -150,8 +150,8 @@ func (dtq *DeviceTokenQuery) OnlyID(ctx context.Context) (id int, err error) { } // OnlyIDX is like OnlyID, but panics if an error occurs. -func (dtq *DeviceTokenQuery) OnlyIDX(ctx context.Context) int { - id, err := dtq.OnlyID(ctx) +func (_q *DeviceTokenQuery) OnlyIDX(ctx context.Context) int { + id, err := _q.OnlyID(ctx) if err != nil { panic(err) } @@ -159,18 +159,18 @@ func (dtq *DeviceTokenQuery) OnlyIDX(ctx context.Context) int { } // All executes the query and returns a list of DeviceTokens. -func (dtq *DeviceTokenQuery) All(ctx context.Context) ([]*DeviceToken, error) { - ctx = setContextOp(ctx, dtq.ctx, ent.OpQueryAll) - if err := dtq.prepareQuery(ctx); err != nil { +func (_q *DeviceTokenQuery) All(ctx context.Context) ([]*DeviceToken, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { return nil, err } qr := querierAll[[]*DeviceToken, *DeviceTokenQuery]() - return withInterceptors[[]*DeviceToken](ctx, dtq, qr, dtq.inters) + return withInterceptors[[]*DeviceToken](ctx, _q, qr, _q.inters) } // AllX is like All, but panics if an error occurs. -func (dtq *DeviceTokenQuery) AllX(ctx context.Context) []*DeviceToken { - nodes, err := dtq.All(ctx) +func (_q *DeviceTokenQuery) AllX(ctx context.Context) []*DeviceToken { + nodes, err := _q.All(ctx) if err != nil { panic(err) } @@ -178,20 +178,20 @@ func (dtq *DeviceTokenQuery) AllX(ctx context.Context) []*DeviceToken { } // IDs executes the query and returns a list of DeviceToken IDs. -func (dtq *DeviceTokenQuery) IDs(ctx context.Context) (ids []int, err error) { - if dtq.ctx.Unique == nil && dtq.path != nil { - dtq.Unique(true) +func (_q *DeviceTokenQuery) IDs(ctx context.Context) (ids []int, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) } - ctx = setContextOp(ctx, dtq.ctx, ent.OpQueryIDs) - if err = dtq.Select(devicetoken.FieldID).Scan(ctx, &ids); err != nil { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(devicetoken.FieldID).Scan(ctx, &ids); err != nil { return nil, err } return ids, nil } // IDsX is like IDs, but panics if an error occurs. -func (dtq *DeviceTokenQuery) IDsX(ctx context.Context) []int { - ids, err := dtq.IDs(ctx) +func (_q *DeviceTokenQuery) IDsX(ctx context.Context) []int { + ids, err := _q.IDs(ctx) if err != nil { panic(err) } @@ -199,17 +199,17 @@ func (dtq *DeviceTokenQuery) IDsX(ctx context.Context) []int { } // Count returns the count of the given query. -func (dtq *DeviceTokenQuery) Count(ctx context.Context) (int, error) { - ctx = setContextOp(ctx, dtq.ctx, ent.OpQueryCount) - if err := dtq.prepareQuery(ctx); err != nil { +func (_q *DeviceTokenQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { return 0, err } - return withInterceptors[int](ctx, dtq, querierCount[*DeviceTokenQuery](), dtq.inters) + return withInterceptors[int](ctx, _q, querierCount[*DeviceTokenQuery](), _q.inters) } // CountX is like Count, but panics if an error occurs. -func (dtq *DeviceTokenQuery) CountX(ctx context.Context) int { - count, err := dtq.Count(ctx) +func (_q *DeviceTokenQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) if err != nil { panic(err) } @@ -217,9 +217,9 @@ func (dtq *DeviceTokenQuery) CountX(ctx context.Context) int { } // Exist returns true if the query has elements in the graph. -func (dtq *DeviceTokenQuery) Exist(ctx context.Context) (bool, error) { - ctx = setContextOp(ctx, dtq.ctx, ent.OpQueryExist) - switch _, err := dtq.FirstID(ctx); { +func (_q *DeviceTokenQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { case IsNotFound(err): return false, nil case err != nil: @@ -230,8 +230,8 @@ func (dtq *DeviceTokenQuery) Exist(ctx context.Context) (bool, error) { } // ExistX is like Exist, but panics if an error occurs. -func (dtq *DeviceTokenQuery) ExistX(ctx context.Context) bool { - exist, err := dtq.Exist(ctx) +func (_q *DeviceTokenQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) if err != nil { panic(err) } @@ -240,19 +240,19 @@ func (dtq *DeviceTokenQuery) ExistX(ctx context.Context) bool { // Clone returns a duplicate of the DeviceTokenQuery builder, including all associated steps. It can be // used to prepare common query builders and use them differently after the clone is made. -func (dtq *DeviceTokenQuery) Clone() *DeviceTokenQuery { - if dtq == nil { +func (_q *DeviceTokenQuery) Clone() *DeviceTokenQuery { + if _q == nil { return nil } return &DeviceTokenQuery{ - config: dtq.config, - ctx: dtq.ctx.Clone(), - order: append([]devicetoken.OrderOption{}, dtq.order...), - inters: append([]Interceptor{}, dtq.inters...), - predicates: append([]predicate.DeviceToken{}, dtq.predicates...), + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]devicetoken.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.DeviceToken{}, _q.predicates...), // clone intermediate query. - sql: dtq.sql.Clone(), - path: dtq.path, + sql: _q.sql.Clone(), + path: _q.path, } } @@ -270,10 +270,10 @@ func (dtq *DeviceTokenQuery) Clone() *DeviceTokenQuery { // GroupBy(devicetoken.FieldDeviceCode). // Aggregate(db.Count()). // Scan(ctx, &v) -func (dtq *DeviceTokenQuery) GroupBy(field string, fields ...string) *DeviceTokenGroupBy { - dtq.ctx.Fields = append([]string{field}, fields...) - grbuild := &DeviceTokenGroupBy{build: dtq} - grbuild.flds = &dtq.ctx.Fields +func (_q *DeviceTokenQuery) GroupBy(field string, fields ...string) *DeviceTokenGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &DeviceTokenGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields grbuild.label = devicetoken.Label grbuild.scan = grbuild.Scan return grbuild @@ -291,62 +291,62 @@ func (dtq *DeviceTokenQuery) GroupBy(field string, fields ...string) *DeviceToke // client.DeviceToken.Query(). // Select(devicetoken.FieldDeviceCode). // Scan(ctx, &v) -func (dtq *DeviceTokenQuery) Select(fields ...string) *DeviceTokenSelect { - dtq.ctx.Fields = append(dtq.ctx.Fields, fields...) - sbuild := &DeviceTokenSelect{DeviceTokenQuery: dtq} +func (_q *DeviceTokenQuery) Select(fields ...string) *DeviceTokenSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &DeviceTokenSelect{DeviceTokenQuery: _q} sbuild.label = devicetoken.Label - sbuild.flds, sbuild.scan = &dtq.ctx.Fields, sbuild.Scan + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan return sbuild } // Aggregate returns a DeviceTokenSelect configured with the given aggregations. -func (dtq *DeviceTokenQuery) Aggregate(fns ...AggregateFunc) *DeviceTokenSelect { - return dtq.Select().Aggregate(fns...) +func (_q *DeviceTokenQuery) Aggregate(fns ...AggregateFunc) *DeviceTokenSelect { + return _q.Select().Aggregate(fns...) } -func (dtq *DeviceTokenQuery) prepareQuery(ctx context.Context) error { - for _, inter := range dtq.inters { +func (_q *DeviceTokenQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { if inter == nil { return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)") } if trv, ok := inter.(Traverser); ok { - if err := trv.Traverse(ctx, dtq); err != nil { + if err := trv.Traverse(ctx, _q); err != nil { return err } } } - for _, f := range dtq.ctx.Fields { + for _, f := range _q.ctx.Fields { if !devicetoken.ValidColumn(f) { return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} } } - if dtq.path != nil { - prev, err := dtq.path(ctx) + if _q.path != nil { + prev, err := _q.path(ctx) if err != nil { return err } - dtq.sql = prev + _q.sql = prev } return nil } -func (dtq *DeviceTokenQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*DeviceToken, error) { +func (_q *DeviceTokenQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*DeviceToken, error) { var ( nodes = []*DeviceToken{} - _spec = dtq.querySpec() + _spec = _q.querySpec() ) _spec.ScanValues = func(columns []string) ([]any, error) { return (*DeviceToken).scanValues(nil, columns) } _spec.Assign = func(columns []string, values []any) error { - node := &DeviceToken{config: dtq.config} + node := &DeviceToken{config: _q.config} nodes = append(nodes, node) return node.assignValues(columns, values) } for i := range hooks { hooks[i](ctx, _spec) } - if err := sqlgraph.QueryNodes(ctx, dtq.driver, _spec); err != nil { + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { return nil, err } if len(nodes) == 0 { @@ -355,24 +355,24 @@ func (dtq *DeviceTokenQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([] return nodes, nil } -func (dtq *DeviceTokenQuery) sqlCount(ctx context.Context) (int, error) { - _spec := dtq.querySpec() - _spec.Node.Columns = dtq.ctx.Fields - if len(dtq.ctx.Fields) > 0 { - _spec.Unique = dtq.ctx.Unique != nil && *dtq.ctx.Unique +func (_q *DeviceTokenQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique } - return sqlgraph.CountNodes(ctx, dtq.driver, _spec) + return sqlgraph.CountNodes(ctx, _q.driver, _spec) } -func (dtq *DeviceTokenQuery) querySpec() *sqlgraph.QuerySpec { +func (_q *DeviceTokenQuery) querySpec() *sqlgraph.QuerySpec { _spec := sqlgraph.NewQuerySpec(devicetoken.Table, devicetoken.Columns, sqlgraph.NewFieldSpec(devicetoken.FieldID, field.TypeInt)) - _spec.From = dtq.sql - if unique := dtq.ctx.Unique; unique != nil { + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { _spec.Unique = *unique - } else if dtq.path != nil { + } else if _q.path != nil { _spec.Unique = true } - if fields := dtq.ctx.Fields; len(fields) > 0 { + if fields := _q.ctx.Fields; len(fields) > 0 { _spec.Node.Columns = make([]string, 0, len(fields)) _spec.Node.Columns = append(_spec.Node.Columns, devicetoken.FieldID) for i := range fields { @@ -381,20 +381,20 @@ func (dtq *DeviceTokenQuery) querySpec() *sqlgraph.QuerySpec { } } } - if ps := dtq.predicates; len(ps) > 0 { + if ps := _q.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if limit := dtq.ctx.Limit; limit != nil { + if limit := _q.ctx.Limit; limit != nil { _spec.Limit = *limit } - if offset := dtq.ctx.Offset; offset != nil { + if offset := _q.ctx.Offset; offset != nil { _spec.Offset = *offset } - if ps := dtq.order; len(ps) > 0 { + if ps := _q.order; len(ps) > 0 { _spec.Order = func(selector *sql.Selector) { for i := range ps { ps[i](selector) @@ -404,33 +404,33 @@ func (dtq *DeviceTokenQuery) querySpec() *sqlgraph.QuerySpec { return _spec } -func (dtq *DeviceTokenQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(dtq.driver.Dialect()) +func (_q *DeviceTokenQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) t1 := builder.Table(devicetoken.Table) - columns := dtq.ctx.Fields + columns := _q.ctx.Fields if len(columns) == 0 { columns = devicetoken.Columns } selector := builder.Select(t1.Columns(columns...)...).From(t1) - if dtq.sql != nil { - selector = dtq.sql + if _q.sql != nil { + selector = _q.sql selector.Select(selector.Columns(columns...)...) } - if dtq.ctx.Unique != nil && *dtq.ctx.Unique { + if _q.ctx.Unique != nil && *_q.ctx.Unique { selector.Distinct() } - for _, p := range dtq.predicates { + for _, p := range _q.predicates { p(selector) } - for _, p := range dtq.order { + for _, p := range _q.order { p(selector) } - if offset := dtq.ctx.Offset; offset != nil { + if offset := _q.ctx.Offset; offset != nil { // limit is mandatory for offset clause. We start // with default value, and override it below if needed. selector.Offset(*offset).Limit(math.MaxInt32) } - if limit := dtq.ctx.Limit; limit != nil { + if limit := _q.ctx.Limit; limit != nil { selector.Limit(*limit) } return selector @@ -443,41 +443,41 @@ type DeviceTokenGroupBy struct { } // Aggregate adds the given aggregation functions to the group-by query. -func (dtgb *DeviceTokenGroupBy) Aggregate(fns ...AggregateFunc) *DeviceTokenGroupBy { - dtgb.fns = append(dtgb.fns, fns...) - return dtgb +func (_g *DeviceTokenGroupBy) Aggregate(fns ...AggregateFunc) *DeviceTokenGroupBy { + _g.fns = append(_g.fns, fns...) + return _g } // Scan applies the selector query and scans the result into the given value. -func (dtgb *DeviceTokenGroupBy) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, dtgb.build.ctx, ent.OpQueryGroupBy) - if err := dtgb.build.prepareQuery(ctx); err != nil { +func (_g *DeviceTokenGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { return err } - return scanWithInterceptors[*DeviceTokenQuery, *DeviceTokenGroupBy](ctx, dtgb.build, dtgb, dtgb.build.inters, v) + return scanWithInterceptors[*DeviceTokenQuery, *DeviceTokenGroupBy](ctx, _g.build, _g, _g.build.inters, v) } -func (dtgb *DeviceTokenGroupBy) sqlScan(ctx context.Context, root *DeviceTokenQuery, v any) error { +func (_g *DeviceTokenGroupBy) sqlScan(ctx context.Context, root *DeviceTokenQuery, v any) error { selector := root.sqlQuery(ctx).Select() - aggregation := make([]string, 0, len(dtgb.fns)) - for _, fn := range dtgb.fns { + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { aggregation = append(aggregation, fn(selector)) } if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(*dtgb.flds)+len(dtgb.fns)) - for _, f := range *dtgb.flds { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { columns = append(columns, selector.C(f)) } columns = append(columns, aggregation...) selector.Select(columns...) } - selector.GroupBy(selector.Columns(*dtgb.flds...)...) + selector.GroupBy(selector.Columns(*_g.flds...)...) if err := selector.Err(); err != nil { return err } rows := &sql.Rows{} query, args := selector.Query() - if err := dtgb.build.driver.Query(ctx, query, args, rows); err != nil { + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() @@ -491,27 +491,27 @@ type DeviceTokenSelect struct { } // Aggregate adds the given aggregation functions to the selector query. -func (dts *DeviceTokenSelect) Aggregate(fns ...AggregateFunc) *DeviceTokenSelect { - dts.fns = append(dts.fns, fns...) - return dts +func (_s *DeviceTokenSelect) Aggregate(fns ...AggregateFunc) *DeviceTokenSelect { + _s.fns = append(_s.fns, fns...) + return _s } // Scan applies the selector query and scans the result into the given value. -func (dts *DeviceTokenSelect) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, dts.ctx, ent.OpQuerySelect) - if err := dts.prepareQuery(ctx); err != nil { +func (_s *DeviceTokenSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { return err } - return scanWithInterceptors[*DeviceTokenQuery, *DeviceTokenSelect](ctx, dts.DeviceTokenQuery, dts, dts.inters, v) + return scanWithInterceptors[*DeviceTokenQuery, *DeviceTokenSelect](ctx, _s.DeviceTokenQuery, _s, _s.inters, v) } -func (dts *DeviceTokenSelect) sqlScan(ctx context.Context, root *DeviceTokenQuery, v any) error { +func (_s *DeviceTokenSelect) sqlScan(ctx context.Context, root *DeviceTokenQuery, v any) error { selector := root.sqlQuery(ctx) - aggregation := make([]string, 0, len(dts.fns)) - for _, fn := range dts.fns { + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { aggregation = append(aggregation, fn(selector)) } - switch n := len(*dts.selector.flds); { + switch n := len(*_s.selector.flds); { case n == 0 && len(aggregation) > 0: selector.Select(aggregation...) case n != 0 && len(aggregation) > 0: @@ -519,7 +519,7 @@ func (dts *DeviceTokenSelect) sqlScan(ctx context.Context, root *DeviceTokenQuer } rows := &sql.Rows{} query, args := selector.Query() - if err := dts.driver.Query(ctx, query, args, rows); err != nil { + if err := _s.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() diff --git a/storage/ent/db/devicetoken_update.go b/storage/ent/db/devicetoken_update.go index 3c6c841463..024beb35d1 100644 --- a/storage/ent/db/devicetoken_update.go +++ b/storage/ent/db/devicetoken_update.go @@ -23,141 +23,141 @@ type DeviceTokenUpdate struct { } // Where appends a list predicates to the DeviceTokenUpdate builder. -func (dtu *DeviceTokenUpdate) Where(ps ...predicate.DeviceToken) *DeviceTokenUpdate { - dtu.mutation.Where(ps...) - return dtu +func (_u *DeviceTokenUpdate) Where(ps ...predicate.DeviceToken) *DeviceTokenUpdate { + _u.mutation.Where(ps...) + return _u } // SetDeviceCode sets the "device_code" field. -func (dtu *DeviceTokenUpdate) SetDeviceCode(s string) *DeviceTokenUpdate { - dtu.mutation.SetDeviceCode(s) - return dtu +func (_u *DeviceTokenUpdate) SetDeviceCode(v string) *DeviceTokenUpdate { + _u.mutation.SetDeviceCode(v) + return _u } // SetNillableDeviceCode sets the "device_code" field if the given value is not nil. -func (dtu *DeviceTokenUpdate) SetNillableDeviceCode(s *string) *DeviceTokenUpdate { - if s != nil { - dtu.SetDeviceCode(*s) +func (_u *DeviceTokenUpdate) SetNillableDeviceCode(v *string) *DeviceTokenUpdate { + if v != nil { + _u.SetDeviceCode(*v) } - return dtu + return _u } // SetStatus sets the "status" field. -func (dtu *DeviceTokenUpdate) SetStatus(s string) *DeviceTokenUpdate { - dtu.mutation.SetStatus(s) - return dtu +func (_u *DeviceTokenUpdate) SetStatus(v string) *DeviceTokenUpdate { + _u.mutation.SetStatus(v) + return _u } // SetNillableStatus sets the "status" field if the given value is not nil. -func (dtu *DeviceTokenUpdate) SetNillableStatus(s *string) *DeviceTokenUpdate { - if s != nil { - dtu.SetStatus(*s) +func (_u *DeviceTokenUpdate) SetNillableStatus(v *string) *DeviceTokenUpdate { + if v != nil { + _u.SetStatus(*v) } - return dtu + return _u } // SetToken sets the "token" field. -func (dtu *DeviceTokenUpdate) SetToken(b []byte) *DeviceTokenUpdate { - dtu.mutation.SetToken(b) - return dtu +func (_u *DeviceTokenUpdate) SetToken(v []byte) *DeviceTokenUpdate { + _u.mutation.SetToken(v) + return _u } // ClearToken clears the value of the "token" field. -func (dtu *DeviceTokenUpdate) ClearToken() *DeviceTokenUpdate { - dtu.mutation.ClearToken() - return dtu +func (_u *DeviceTokenUpdate) ClearToken() *DeviceTokenUpdate { + _u.mutation.ClearToken() + return _u } // SetExpiry sets the "expiry" field. -func (dtu *DeviceTokenUpdate) SetExpiry(t time.Time) *DeviceTokenUpdate { - dtu.mutation.SetExpiry(t) - return dtu +func (_u *DeviceTokenUpdate) SetExpiry(v time.Time) *DeviceTokenUpdate { + _u.mutation.SetExpiry(v) + return _u } // SetNillableExpiry sets the "expiry" field if the given value is not nil. -func (dtu *DeviceTokenUpdate) SetNillableExpiry(t *time.Time) *DeviceTokenUpdate { - if t != nil { - dtu.SetExpiry(*t) +func (_u *DeviceTokenUpdate) SetNillableExpiry(v *time.Time) *DeviceTokenUpdate { + if v != nil { + _u.SetExpiry(*v) } - return dtu + return _u } // SetLastRequest sets the "last_request" field. -func (dtu *DeviceTokenUpdate) SetLastRequest(t time.Time) *DeviceTokenUpdate { - dtu.mutation.SetLastRequest(t) - return dtu +func (_u *DeviceTokenUpdate) SetLastRequest(v time.Time) *DeviceTokenUpdate { + _u.mutation.SetLastRequest(v) + return _u } // SetNillableLastRequest sets the "last_request" field if the given value is not nil. -func (dtu *DeviceTokenUpdate) SetNillableLastRequest(t *time.Time) *DeviceTokenUpdate { - if t != nil { - dtu.SetLastRequest(*t) +func (_u *DeviceTokenUpdate) SetNillableLastRequest(v *time.Time) *DeviceTokenUpdate { + if v != nil { + _u.SetLastRequest(*v) } - return dtu + return _u } // SetPollInterval sets the "poll_interval" field. -func (dtu *DeviceTokenUpdate) SetPollInterval(i int) *DeviceTokenUpdate { - dtu.mutation.ResetPollInterval() - dtu.mutation.SetPollInterval(i) - return dtu +func (_u *DeviceTokenUpdate) SetPollInterval(v int) *DeviceTokenUpdate { + _u.mutation.ResetPollInterval() + _u.mutation.SetPollInterval(v) + return _u } // SetNillablePollInterval sets the "poll_interval" field if the given value is not nil. -func (dtu *DeviceTokenUpdate) SetNillablePollInterval(i *int) *DeviceTokenUpdate { - if i != nil { - dtu.SetPollInterval(*i) +func (_u *DeviceTokenUpdate) SetNillablePollInterval(v *int) *DeviceTokenUpdate { + if v != nil { + _u.SetPollInterval(*v) } - return dtu + return _u } -// AddPollInterval adds i to the "poll_interval" field. -func (dtu *DeviceTokenUpdate) AddPollInterval(i int) *DeviceTokenUpdate { - dtu.mutation.AddPollInterval(i) - return dtu +// AddPollInterval adds value to the "poll_interval" field. +func (_u *DeviceTokenUpdate) AddPollInterval(v int) *DeviceTokenUpdate { + _u.mutation.AddPollInterval(v) + return _u } // SetCodeChallenge sets the "code_challenge" field. -func (dtu *DeviceTokenUpdate) SetCodeChallenge(s string) *DeviceTokenUpdate { - dtu.mutation.SetCodeChallenge(s) - return dtu +func (_u *DeviceTokenUpdate) SetCodeChallenge(v string) *DeviceTokenUpdate { + _u.mutation.SetCodeChallenge(v) + return _u } // SetNillableCodeChallenge sets the "code_challenge" field if the given value is not nil. -func (dtu *DeviceTokenUpdate) SetNillableCodeChallenge(s *string) *DeviceTokenUpdate { - if s != nil { - dtu.SetCodeChallenge(*s) +func (_u *DeviceTokenUpdate) SetNillableCodeChallenge(v *string) *DeviceTokenUpdate { + if v != nil { + _u.SetCodeChallenge(*v) } - return dtu + return _u } // SetCodeChallengeMethod sets the "code_challenge_method" field. -func (dtu *DeviceTokenUpdate) SetCodeChallengeMethod(s string) *DeviceTokenUpdate { - dtu.mutation.SetCodeChallengeMethod(s) - return dtu +func (_u *DeviceTokenUpdate) SetCodeChallengeMethod(v string) *DeviceTokenUpdate { + _u.mutation.SetCodeChallengeMethod(v) + return _u } // SetNillableCodeChallengeMethod sets the "code_challenge_method" field if the given value is not nil. -func (dtu *DeviceTokenUpdate) SetNillableCodeChallengeMethod(s *string) *DeviceTokenUpdate { - if s != nil { - dtu.SetCodeChallengeMethod(*s) +func (_u *DeviceTokenUpdate) SetNillableCodeChallengeMethod(v *string) *DeviceTokenUpdate { + if v != nil { + _u.SetCodeChallengeMethod(*v) } - return dtu + return _u } // Mutation returns the DeviceTokenMutation object of the builder. -func (dtu *DeviceTokenUpdate) Mutation() *DeviceTokenMutation { - return dtu.mutation +func (_u *DeviceTokenUpdate) Mutation() *DeviceTokenMutation { + return _u.mutation } // Save executes the query and returns the number of nodes affected by the update operation. -func (dtu *DeviceTokenUpdate) Save(ctx context.Context) (int, error) { - return withHooks(ctx, dtu.sqlSave, dtu.mutation, dtu.hooks) +func (_u *DeviceTokenUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) } // SaveX is like Save, but panics if an error occurs. -func (dtu *DeviceTokenUpdate) SaveX(ctx context.Context) int { - affected, err := dtu.Save(ctx) +func (_u *DeviceTokenUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) if err != nil { panic(err) } @@ -165,26 +165,26 @@ func (dtu *DeviceTokenUpdate) SaveX(ctx context.Context) int { } // Exec executes the query. -func (dtu *DeviceTokenUpdate) Exec(ctx context.Context) error { - _, err := dtu.Save(ctx) +func (_u *DeviceTokenUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (dtu *DeviceTokenUpdate) ExecX(ctx context.Context) { - if err := dtu.Exec(ctx); err != nil { +func (_u *DeviceTokenUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { panic(err) } } // check runs all checks and user-defined validators on the builder. -func (dtu *DeviceTokenUpdate) check() error { - if v, ok := dtu.mutation.DeviceCode(); ok { +func (_u *DeviceTokenUpdate) check() error { + if v, ok := _u.mutation.DeviceCode(); ok { if err := devicetoken.DeviceCodeValidator(v); err != nil { return &ValidationError{Name: "device_code", err: fmt.Errorf(`db: validator failed for field "DeviceToken.device_code": %w`, err)} } } - if v, ok := dtu.mutation.Status(); ok { + if v, ok := _u.mutation.Status(); ok { if err := devicetoken.StatusValidator(v); err != nil { return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "DeviceToken.status": %w`, err)} } @@ -192,49 +192,49 @@ func (dtu *DeviceTokenUpdate) check() error { return nil } -func (dtu *DeviceTokenUpdate) sqlSave(ctx context.Context) (n int, err error) { - if err := dtu.check(); err != nil { - return n, err +func (_u *DeviceTokenUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err } _spec := sqlgraph.NewUpdateSpec(devicetoken.Table, devicetoken.Columns, sqlgraph.NewFieldSpec(devicetoken.FieldID, field.TypeInt)) - if ps := dtu.mutation.predicates; len(ps) > 0 { + if ps := _u.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if value, ok := dtu.mutation.DeviceCode(); ok { + if value, ok := _u.mutation.DeviceCode(); ok { _spec.SetField(devicetoken.FieldDeviceCode, field.TypeString, value) } - if value, ok := dtu.mutation.Status(); ok { + if value, ok := _u.mutation.Status(); ok { _spec.SetField(devicetoken.FieldStatus, field.TypeString, value) } - if value, ok := dtu.mutation.Token(); ok { + if value, ok := _u.mutation.Token(); ok { _spec.SetField(devicetoken.FieldToken, field.TypeBytes, value) } - if dtu.mutation.TokenCleared() { + if _u.mutation.TokenCleared() { _spec.ClearField(devicetoken.FieldToken, field.TypeBytes) } - if value, ok := dtu.mutation.Expiry(); ok { + if value, ok := _u.mutation.Expiry(); ok { _spec.SetField(devicetoken.FieldExpiry, field.TypeTime, value) } - if value, ok := dtu.mutation.LastRequest(); ok { + if value, ok := _u.mutation.LastRequest(); ok { _spec.SetField(devicetoken.FieldLastRequest, field.TypeTime, value) } - if value, ok := dtu.mutation.PollInterval(); ok { + if value, ok := _u.mutation.PollInterval(); ok { _spec.SetField(devicetoken.FieldPollInterval, field.TypeInt, value) } - if value, ok := dtu.mutation.AddedPollInterval(); ok { + if value, ok := _u.mutation.AddedPollInterval(); ok { _spec.AddField(devicetoken.FieldPollInterval, field.TypeInt, value) } - if value, ok := dtu.mutation.CodeChallenge(); ok { + if value, ok := _u.mutation.CodeChallenge(); ok { _spec.SetField(devicetoken.FieldCodeChallenge, field.TypeString, value) } - if value, ok := dtu.mutation.CodeChallengeMethod(); ok { + if value, ok := _u.mutation.CodeChallengeMethod(); ok { _spec.SetField(devicetoken.FieldCodeChallengeMethod, field.TypeString, value) } - if n, err = sqlgraph.UpdateNodes(ctx, dtu.driver, _spec); err != nil { + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{devicetoken.Label} } else if sqlgraph.IsConstraintError(err) { @@ -242,8 +242,8 @@ func (dtu *DeviceTokenUpdate) sqlSave(ctx context.Context) (n int, err error) { } return 0, err } - dtu.mutation.done = true - return n, nil + _u.mutation.done = true + return _node, nil } // DeviceTokenUpdateOne is the builder for updating a single DeviceToken entity. @@ -255,148 +255,148 @@ type DeviceTokenUpdateOne struct { } // SetDeviceCode sets the "device_code" field. -func (dtuo *DeviceTokenUpdateOne) SetDeviceCode(s string) *DeviceTokenUpdateOne { - dtuo.mutation.SetDeviceCode(s) - return dtuo +func (_u *DeviceTokenUpdateOne) SetDeviceCode(v string) *DeviceTokenUpdateOne { + _u.mutation.SetDeviceCode(v) + return _u } // SetNillableDeviceCode sets the "device_code" field if the given value is not nil. -func (dtuo *DeviceTokenUpdateOne) SetNillableDeviceCode(s *string) *DeviceTokenUpdateOne { - if s != nil { - dtuo.SetDeviceCode(*s) +func (_u *DeviceTokenUpdateOne) SetNillableDeviceCode(v *string) *DeviceTokenUpdateOne { + if v != nil { + _u.SetDeviceCode(*v) } - return dtuo + return _u } // SetStatus sets the "status" field. -func (dtuo *DeviceTokenUpdateOne) SetStatus(s string) *DeviceTokenUpdateOne { - dtuo.mutation.SetStatus(s) - return dtuo +func (_u *DeviceTokenUpdateOne) SetStatus(v string) *DeviceTokenUpdateOne { + _u.mutation.SetStatus(v) + return _u } // SetNillableStatus sets the "status" field if the given value is not nil. -func (dtuo *DeviceTokenUpdateOne) SetNillableStatus(s *string) *DeviceTokenUpdateOne { - if s != nil { - dtuo.SetStatus(*s) +func (_u *DeviceTokenUpdateOne) SetNillableStatus(v *string) *DeviceTokenUpdateOne { + if v != nil { + _u.SetStatus(*v) } - return dtuo + return _u } // SetToken sets the "token" field. -func (dtuo *DeviceTokenUpdateOne) SetToken(b []byte) *DeviceTokenUpdateOne { - dtuo.mutation.SetToken(b) - return dtuo +func (_u *DeviceTokenUpdateOne) SetToken(v []byte) *DeviceTokenUpdateOne { + _u.mutation.SetToken(v) + return _u } // ClearToken clears the value of the "token" field. -func (dtuo *DeviceTokenUpdateOne) ClearToken() *DeviceTokenUpdateOne { - dtuo.mutation.ClearToken() - return dtuo +func (_u *DeviceTokenUpdateOne) ClearToken() *DeviceTokenUpdateOne { + _u.mutation.ClearToken() + return _u } // SetExpiry sets the "expiry" field. -func (dtuo *DeviceTokenUpdateOne) SetExpiry(t time.Time) *DeviceTokenUpdateOne { - dtuo.mutation.SetExpiry(t) - return dtuo +func (_u *DeviceTokenUpdateOne) SetExpiry(v time.Time) *DeviceTokenUpdateOne { + _u.mutation.SetExpiry(v) + return _u } // SetNillableExpiry sets the "expiry" field if the given value is not nil. -func (dtuo *DeviceTokenUpdateOne) SetNillableExpiry(t *time.Time) *DeviceTokenUpdateOne { - if t != nil { - dtuo.SetExpiry(*t) +func (_u *DeviceTokenUpdateOne) SetNillableExpiry(v *time.Time) *DeviceTokenUpdateOne { + if v != nil { + _u.SetExpiry(*v) } - return dtuo + return _u } // SetLastRequest sets the "last_request" field. -func (dtuo *DeviceTokenUpdateOne) SetLastRequest(t time.Time) *DeviceTokenUpdateOne { - dtuo.mutation.SetLastRequest(t) - return dtuo +func (_u *DeviceTokenUpdateOne) SetLastRequest(v time.Time) *DeviceTokenUpdateOne { + _u.mutation.SetLastRequest(v) + return _u } // SetNillableLastRequest sets the "last_request" field if the given value is not nil. -func (dtuo *DeviceTokenUpdateOne) SetNillableLastRequest(t *time.Time) *DeviceTokenUpdateOne { - if t != nil { - dtuo.SetLastRequest(*t) +func (_u *DeviceTokenUpdateOne) SetNillableLastRequest(v *time.Time) *DeviceTokenUpdateOne { + if v != nil { + _u.SetLastRequest(*v) } - return dtuo + return _u } // SetPollInterval sets the "poll_interval" field. -func (dtuo *DeviceTokenUpdateOne) SetPollInterval(i int) *DeviceTokenUpdateOne { - dtuo.mutation.ResetPollInterval() - dtuo.mutation.SetPollInterval(i) - return dtuo +func (_u *DeviceTokenUpdateOne) SetPollInterval(v int) *DeviceTokenUpdateOne { + _u.mutation.ResetPollInterval() + _u.mutation.SetPollInterval(v) + return _u } // SetNillablePollInterval sets the "poll_interval" field if the given value is not nil. -func (dtuo *DeviceTokenUpdateOne) SetNillablePollInterval(i *int) *DeviceTokenUpdateOne { - if i != nil { - dtuo.SetPollInterval(*i) +func (_u *DeviceTokenUpdateOne) SetNillablePollInterval(v *int) *DeviceTokenUpdateOne { + if v != nil { + _u.SetPollInterval(*v) } - return dtuo + return _u } -// AddPollInterval adds i to the "poll_interval" field. -func (dtuo *DeviceTokenUpdateOne) AddPollInterval(i int) *DeviceTokenUpdateOne { - dtuo.mutation.AddPollInterval(i) - return dtuo +// AddPollInterval adds value to the "poll_interval" field. +func (_u *DeviceTokenUpdateOne) AddPollInterval(v int) *DeviceTokenUpdateOne { + _u.mutation.AddPollInterval(v) + return _u } // SetCodeChallenge sets the "code_challenge" field. -func (dtuo *DeviceTokenUpdateOne) SetCodeChallenge(s string) *DeviceTokenUpdateOne { - dtuo.mutation.SetCodeChallenge(s) - return dtuo +func (_u *DeviceTokenUpdateOne) SetCodeChallenge(v string) *DeviceTokenUpdateOne { + _u.mutation.SetCodeChallenge(v) + return _u } // SetNillableCodeChallenge sets the "code_challenge" field if the given value is not nil. -func (dtuo *DeviceTokenUpdateOne) SetNillableCodeChallenge(s *string) *DeviceTokenUpdateOne { - if s != nil { - dtuo.SetCodeChallenge(*s) +func (_u *DeviceTokenUpdateOne) SetNillableCodeChallenge(v *string) *DeviceTokenUpdateOne { + if v != nil { + _u.SetCodeChallenge(*v) } - return dtuo + return _u } // SetCodeChallengeMethod sets the "code_challenge_method" field. -func (dtuo *DeviceTokenUpdateOne) SetCodeChallengeMethod(s string) *DeviceTokenUpdateOne { - dtuo.mutation.SetCodeChallengeMethod(s) - return dtuo +func (_u *DeviceTokenUpdateOne) SetCodeChallengeMethod(v string) *DeviceTokenUpdateOne { + _u.mutation.SetCodeChallengeMethod(v) + return _u } // SetNillableCodeChallengeMethod sets the "code_challenge_method" field if the given value is not nil. -func (dtuo *DeviceTokenUpdateOne) SetNillableCodeChallengeMethod(s *string) *DeviceTokenUpdateOne { - if s != nil { - dtuo.SetCodeChallengeMethod(*s) +func (_u *DeviceTokenUpdateOne) SetNillableCodeChallengeMethod(v *string) *DeviceTokenUpdateOne { + if v != nil { + _u.SetCodeChallengeMethod(*v) } - return dtuo + return _u } // Mutation returns the DeviceTokenMutation object of the builder. -func (dtuo *DeviceTokenUpdateOne) Mutation() *DeviceTokenMutation { - return dtuo.mutation +func (_u *DeviceTokenUpdateOne) Mutation() *DeviceTokenMutation { + return _u.mutation } // Where appends a list predicates to the DeviceTokenUpdate builder. -func (dtuo *DeviceTokenUpdateOne) Where(ps ...predicate.DeviceToken) *DeviceTokenUpdateOne { - dtuo.mutation.Where(ps...) - return dtuo +func (_u *DeviceTokenUpdateOne) Where(ps ...predicate.DeviceToken) *DeviceTokenUpdateOne { + _u.mutation.Where(ps...) + return _u } // Select allows selecting one or more fields (columns) of the returned entity. // The default is selecting all fields defined in the entity schema. -func (dtuo *DeviceTokenUpdateOne) Select(field string, fields ...string) *DeviceTokenUpdateOne { - dtuo.fields = append([]string{field}, fields...) - return dtuo +func (_u *DeviceTokenUpdateOne) Select(field string, fields ...string) *DeviceTokenUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u } // Save executes the query and returns the updated DeviceToken entity. -func (dtuo *DeviceTokenUpdateOne) Save(ctx context.Context) (*DeviceToken, error) { - return withHooks(ctx, dtuo.sqlSave, dtuo.mutation, dtuo.hooks) +func (_u *DeviceTokenUpdateOne) Save(ctx context.Context) (*DeviceToken, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) } // SaveX is like Save, but panics if an error occurs. -func (dtuo *DeviceTokenUpdateOne) SaveX(ctx context.Context) *DeviceToken { - node, err := dtuo.Save(ctx) +func (_u *DeviceTokenUpdateOne) SaveX(ctx context.Context) *DeviceToken { + node, err := _u.Save(ctx) if err != nil { panic(err) } @@ -404,26 +404,26 @@ func (dtuo *DeviceTokenUpdateOne) SaveX(ctx context.Context) *DeviceToken { } // Exec executes the query on the entity. -func (dtuo *DeviceTokenUpdateOne) Exec(ctx context.Context) error { - _, err := dtuo.Save(ctx) +func (_u *DeviceTokenUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (dtuo *DeviceTokenUpdateOne) ExecX(ctx context.Context) { - if err := dtuo.Exec(ctx); err != nil { +func (_u *DeviceTokenUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { panic(err) } } // check runs all checks and user-defined validators on the builder. -func (dtuo *DeviceTokenUpdateOne) check() error { - if v, ok := dtuo.mutation.DeviceCode(); ok { +func (_u *DeviceTokenUpdateOne) check() error { + if v, ok := _u.mutation.DeviceCode(); ok { if err := devicetoken.DeviceCodeValidator(v); err != nil { return &ValidationError{Name: "device_code", err: fmt.Errorf(`db: validator failed for field "DeviceToken.device_code": %w`, err)} } } - if v, ok := dtuo.mutation.Status(); ok { + if v, ok := _u.mutation.Status(); ok { if err := devicetoken.StatusValidator(v); err != nil { return &ValidationError{Name: "status", err: fmt.Errorf(`db: validator failed for field "DeviceToken.status": %w`, err)} } @@ -431,17 +431,17 @@ func (dtuo *DeviceTokenUpdateOne) check() error { return nil } -func (dtuo *DeviceTokenUpdateOne) sqlSave(ctx context.Context) (_node *DeviceToken, err error) { - if err := dtuo.check(); err != nil { +func (_u *DeviceTokenUpdateOne) sqlSave(ctx context.Context) (_node *DeviceToken, err error) { + if err := _u.check(); err != nil { return _node, err } _spec := sqlgraph.NewUpdateSpec(devicetoken.Table, devicetoken.Columns, sqlgraph.NewFieldSpec(devicetoken.FieldID, field.TypeInt)) - id, ok := dtuo.mutation.ID() + id, ok := _u.mutation.ID() if !ok { return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "DeviceToken.id" for update`)} } _spec.Node.ID.Value = id - if fields := dtuo.fields; len(fields) > 0 { + if fields := _u.fields; len(fields) > 0 { _spec.Node.Columns = make([]string, 0, len(fields)) _spec.Node.Columns = append(_spec.Node.Columns, devicetoken.FieldID) for _, f := range fields { @@ -453,47 +453,47 @@ func (dtuo *DeviceTokenUpdateOne) sqlSave(ctx context.Context) (_node *DeviceTok } } } - if ps := dtuo.mutation.predicates; len(ps) > 0 { + if ps := _u.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if value, ok := dtuo.mutation.DeviceCode(); ok { + if value, ok := _u.mutation.DeviceCode(); ok { _spec.SetField(devicetoken.FieldDeviceCode, field.TypeString, value) } - if value, ok := dtuo.mutation.Status(); ok { + if value, ok := _u.mutation.Status(); ok { _spec.SetField(devicetoken.FieldStatus, field.TypeString, value) } - if value, ok := dtuo.mutation.Token(); ok { + if value, ok := _u.mutation.Token(); ok { _spec.SetField(devicetoken.FieldToken, field.TypeBytes, value) } - if dtuo.mutation.TokenCleared() { + if _u.mutation.TokenCleared() { _spec.ClearField(devicetoken.FieldToken, field.TypeBytes) } - if value, ok := dtuo.mutation.Expiry(); ok { + if value, ok := _u.mutation.Expiry(); ok { _spec.SetField(devicetoken.FieldExpiry, field.TypeTime, value) } - if value, ok := dtuo.mutation.LastRequest(); ok { + if value, ok := _u.mutation.LastRequest(); ok { _spec.SetField(devicetoken.FieldLastRequest, field.TypeTime, value) } - if value, ok := dtuo.mutation.PollInterval(); ok { + if value, ok := _u.mutation.PollInterval(); ok { _spec.SetField(devicetoken.FieldPollInterval, field.TypeInt, value) } - if value, ok := dtuo.mutation.AddedPollInterval(); ok { + if value, ok := _u.mutation.AddedPollInterval(); ok { _spec.AddField(devicetoken.FieldPollInterval, field.TypeInt, value) } - if value, ok := dtuo.mutation.CodeChallenge(); ok { + if value, ok := _u.mutation.CodeChallenge(); ok { _spec.SetField(devicetoken.FieldCodeChallenge, field.TypeString, value) } - if value, ok := dtuo.mutation.CodeChallengeMethod(); ok { + if value, ok := _u.mutation.CodeChallengeMethod(); ok { _spec.SetField(devicetoken.FieldCodeChallengeMethod, field.TypeString, value) } - _node = &DeviceToken{config: dtuo.config} + _node = &DeviceToken{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, dtuo.driver, _spec); err != nil { + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{devicetoken.Label} } else if sqlgraph.IsConstraintError(err) { @@ -501,6 +501,6 @@ func (dtuo *DeviceTokenUpdateOne) sqlSave(ctx context.Context) (_node *DeviceTok } return nil, err } - dtuo.mutation.done = true + _u.mutation.done = true return _node, nil } diff --git a/storage/ent/db/ent.go b/storage/ent/db/ent.go index dec4be7860..06bee261c8 100644 --- a/storage/ent/db/ent.go +++ b/storage/ent/db/ent.go @@ -79,7 +79,7 @@ var ( ) // checkColumn checks if the column exists in the given table. -func checkColumn(table, column string) error { +func checkColumn(t, c string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ authcode.Table: authcode.ValidColumn, @@ -94,7 +94,7 @@ func checkColumn(table, column string) error { refreshtoken.Table: refreshtoken.ValidColumn, }) }) - return columnCheck(table, column) + return columnCheck(t, c) } // Asc applies the given fields in ASC order. diff --git a/storage/ent/db/keys.go b/storage/ent/db/keys.go index 616b1eaee2..bd3c02bcac 100644 --- a/storage/ent/db/keys.go +++ b/storage/ent/db/keys.go @@ -51,7 +51,7 @@ func (*Keys) scanValues(columns []string) ([]any, error) { // assignValues assigns the values that were returned from sql.Rows (after scanning) // to the Keys fields. -func (k *Keys) assignValues(columns []string, values []any) error { +func (_m *Keys) 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) } @@ -61,13 +61,13 @@ func (k *Keys) assignValues(columns []string, values []any) error { if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field id", values[i]) } else if value.Valid { - k.ID = value.String + _m.ID = value.String } case keys.FieldVerificationKeys: if value, ok := values[i].(*[]byte); !ok { return fmt.Errorf("unexpected type %T for field verification_keys", values[i]) } else if value != nil && len(*value) > 0 { - if err := json.Unmarshal(*value, &k.VerificationKeys); err != nil { + if err := json.Unmarshal(*value, &_m.VerificationKeys); err != nil { return fmt.Errorf("unmarshal field verification_keys: %w", err) } } @@ -75,7 +75,7 @@ func (k *Keys) assignValues(columns []string, values []any) error { if value, ok := values[i].(*[]byte); !ok { return fmt.Errorf("unexpected type %T for field signing_key", values[i]) } else if value != nil && len(*value) > 0 { - if err := json.Unmarshal(*value, &k.SigningKey); err != nil { + if err := json.Unmarshal(*value, &_m.SigningKey); err != nil { return fmt.Errorf("unmarshal field signing_key: %w", err) } } @@ -83,7 +83,7 @@ func (k *Keys) assignValues(columns []string, values []any) error { if value, ok := values[i].(*[]byte); !ok { return fmt.Errorf("unexpected type %T for field signing_key_pub", values[i]) } else if value != nil && len(*value) > 0 { - if err := json.Unmarshal(*value, &k.SigningKeyPub); err != nil { + if err := json.Unmarshal(*value, &_m.SigningKeyPub); err != nil { return fmt.Errorf("unmarshal field signing_key_pub: %w", err) } } @@ -91,10 +91,10 @@ func (k *Keys) assignValues(columns []string, values []any) error { if value, ok := values[i].(*sql.NullTime); !ok { return fmt.Errorf("unexpected type %T for field next_rotation", values[i]) } else if value.Valid { - k.NextRotation = value.Time + _m.NextRotation = value.Time } default: - k.selectValues.Set(columns[i], values[i]) + _m.selectValues.Set(columns[i], values[i]) } } return nil @@ -102,44 +102,44 @@ func (k *Keys) assignValues(columns []string, values []any) error { // Value returns the ent.Value that was dynamically selected and assigned to the Keys. // This includes values selected through modifiers, order, etc. -func (k *Keys) Value(name string) (ent.Value, error) { - return k.selectValues.Get(name) +func (_m *Keys) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) } // Update returns a builder for updating this Keys. // Note that you need to call Keys.Unwrap() before calling this method if this Keys // was returned from a transaction, and the transaction was committed or rolled back. -func (k *Keys) Update() *KeysUpdateOne { - return NewKeysClient(k.config).UpdateOne(k) +func (_m *Keys) Update() *KeysUpdateOne { + return NewKeysClient(_m.config).UpdateOne(_m) } // Unwrap unwraps the Keys 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 (k *Keys) Unwrap() *Keys { - _tx, ok := k.config.driver.(*txDriver) +func (_m *Keys) Unwrap() *Keys { + _tx, ok := _m.config.driver.(*txDriver) if !ok { panic("db: Keys is not a transactional entity") } - k.config.driver = _tx.drv - return k + _m.config.driver = _tx.drv + return _m } // String implements the fmt.Stringer. -func (k *Keys) String() string { +func (_m *Keys) String() string { var builder strings.Builder builder.WriteString("Keys(") - builder.WriteString(fmt.Sprintf("id=%v, ", k.ID)) + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) builder.WriteString("verification_keys=") - builder.WriteString(fmt.Sprintf("%v", k.VerificationKeys)) + builder.WriteString(fmt.Sprintf("%v", _m.VerificationKeys)) builder.WriteString(", ") builder.WriteString("signing_key=") - builder.WriteString(fmt.Sprintf("%v", k.SigningKey)) + builder.WriteString(fmt.Sprintf("%v", _m.SigningKey)) builder.WriteString(", ") builder.WriteString("signing_key_pub=") - builder.WriteString(fmt.Sprintf("%v", k.SigningKeyPub)) + builder.WriteString(fmt.Sprintf("%v", _m.SigningKeyPub)) builder.WriteString(", ") builder.WriteString("next_rotation=") - builder.WriteString(k.NextRotation.Format(time.ANSIC)) + builder.WriteString(_m.NextRotation.Format(time.ANSIC)) builder.WriteByte(')') return builder.String() } diff --git a/storage/ent/db/keys_create.go b/storage/ent/db/keys_create.go index d555448fe2..9cafd80a16 100644 --- a/storage/ent/db/keys_create.go +++ b/storage/ent/db/keys_create.go @@ -23,48 +23,48 @@ type KeysCreate struct { } // SetVerificationKeys sets the "verification_keys" field. -func (kc *KeysCreate) SetVerificationKeys(sk []storage.VerificationKey) *KeysCreate { - kc.mutation.SetVerificationKeys(sk) - return kc +func (_c *KeysCreate) SetVerificationKeys(v []storage.VerificationKey) *KeysCreate { + _c.mutation.SetVerificationKeys(v) + return _c } // SetSigningKey sets the "signing_key" field. -func (kc *KeysCreate) SetSigningKey(jwk jose.JSONWebKey) *KeysCreate { - kc.mutation.SetSigningKey(jwk) - return kc +func (_c *KeysCreate) SetSigningKey(v jose.JSONWebKey) *KeysCreate { + _c.mutation.SetSigningKey(v) + return _c } // SetSigningKeyPub sets the "signing_key_pub" field. -func (kc *KeysCreate) SetSigningKeyPub(jwk jose.JSONWebKey) *KeysCreate { - kc.mutation.SetSigningKeyPub(jwk) - return kc +func (_c *KeysCreate) SetSigningKeyPub(v jose.JSONWebKey) *KeysCreate { + _c.mutation.SetSigningKeyPub(v) + return _c } // SetNextRotation sets the "next_rotation" field. -func (kc *KeysCreate) SetNextRotation(t time.Time) *KeysCreate { - kc.mutation.SetNextRotation(t) - return kc +func (_c *KeysCreate) SetNextRotation(v time.Time) *KeysCreate { + _c.mutation.SetNextRotation(v) + return _c } // SetID sets the "id" field. -func (kc *KeysCreate) SetID(s string) *KeysCreate { - kc.mutation.SetID(s) - return kc +func (_c *KeysCreate) SetID(v string) *KeysCreate { + _c.mutation.SetID(v) + return _c } // Mutation returns the KeysMutation object of the builder. -func (kc *KeysCreate) Mutation() *KeysMutation { - return kc.mutation +func (_c *KeysCreate) Mutation() *KeysMutation { + return _c.mutation } // Save creates the Keys in the database. -func (kc *KeysCreate) Save(ctx context.Context) (*Keys, error) { - return withHooks(ctx, kc.sqlSave, kc.mutation, kc.hooks) +func (_c *KeysCreate) Save(ctx context.Context) (*Keys, error) { + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) } // SaveX calls Save and panics if Save returns an error. -func (kc *KeysCreate) SaveX(ctx context.Context) *Keys { - v, err := kc.Save(ctx) +func (_c *KeysCreate) SaveX(ctx context.Context) *Keys { + v, err := _c.Save(ctx) if err != nil { panic(err) } @@ -72,33 +72,33 @@ func (kc *KeysCreate) SaveX(ctx context.Context) *Keys { } // Exec executes the query. -func (kc *KeysCreate) Exec(ctx context.Context) error { - _, err := kc.Save(ctx) +func (_c *KeysCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (kc *KeysCreate) ExecX(ctx context.Context) { - if err := kc.Exec(ctx); err != nil { +func (_c *KeysCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { panic(err) } } // check runs all checks and user-defined validators on the builder. -func (kc *KeysCreate) check() error { - if _, ok := kc.mutation.VerificationKeys(); !ok { +func (_c *KeysCreate) check() error { + if _, ok := _c.mutation.VerificationKeys(); !ok { return &ValidationError{Name: "verification_keys", err: errors.New(`db: missing required field "Keys.verification_keys"`)} } - if _, ok := kc.mutation.SigningKey(); !ok { + if _, ok := _c.mutation.SigningKey(); !ok { return &ValidationError{Name: "signing_key", err: errors.New(`db: missing required field "Keys.signing_key"`)} } - if _, ok := kc.mutation.SigningKeyPub(); !ok { + if _, ok := _c.mutation.SigningKeyPub(); !ok { return &ValidationError{Name: "signing_key_pub", err: errors.New(`db: missing required field "Keys.signing_key_pub"`)} } - if _, ok := kc.mutation.NextRotation(); !ok { + if _, ok := _c.mutation.NextRotation(); !ok { return &ValidationError{Name: "next_rotation", err: errors.New(`db: missing required field "Keys.next_rotation"`)} } - if v, ok := kc.mutation.ID(); ok { + if v, ok := _c.mutation.ID(); ok { if err := keys.IDValidator(v); err != nil { return &ValidationError{Name: "id", err: fmt.Errorf(`db: validator failed for field "Keys.id": %w`, err)} } @@ -106,12 +106,12 @@ func (kc *KeysCreate) check() error { return nil } -func (kc *KeysCreate) sqlSave(ctx context.Context) (*Keys, error) { - if err := kc.check(); err != nil { +func (_c *KeysCreate) sqlSave(ctx context.Context) (*Keys, error) { + if err := _c.check(); err != nil { return nil, err } - _node, _spec := kc.createSpec() - if err := sqlgraph.CreateNode(ctx, kc.driver, _spec); err != nil { + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { if sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } @@ -124,33 +124,33 @@ func (kc *KeysCreate) sqlSave(ctx context.Context) (*Keys, error) { return nil, fmt.Errorf("unexpected Keys.ID type: %T", _spec.ID.Value) } } - kc.mutation.id = &_node.ID - kc.mutation.done = true + _c.mutation.id = &_node.ID + _c.mutation.done = true return _node, nil } -func (kc *KeysCreate) createSpec() (*Keys, *sqlgraph.CreateSpec) { +func (_c *KeysCreate) createSpec() (*Keys, *sqlgraph.CreateSpec) { var ( - _node = &Keys{config: kc.config} + _node = &Keys{config: _c.config} _spec = sqlgraph.NewCreateSpec(keys.Table, sqlgraph.NewFieldSpec(keys.FieldID, field.TypeString)) ) - if id, ok := kc.mutation.ID(); ok { + if id, ok := _c.mutation.ID(); ok { _node.ID = id _spec.ID.Value = id } - if value, ok := kc.mutation.VerificationKeys(); ok { + if value, ok := _c.mutation.VerificationKeys(); ok { _spec.SetField(keys.FieldVerificationKeys, field.TypeJSON, value) _node.VerificationKeys = value } - if value, ok := kc.mutation.SigningKey(); ok { + if value, ok := _c.mutation.SigningKey(); ok { _spec.SetField(keys.FieldSigningKey, field.TypeJSON, value) _node.SigningKey = value } - if value, ok := kc.mutation.SigningKeyPub(); ok { + if value, ok := _c.mutation.SigningKeyPub(); ok { _spec.SetField(keys.FieldSigningKeyPub, field.TypeJSON, value) _node.SigningKeyPub = value } - if value, ok := kc.mutation.NextRotation(); ok { + if value, ok := _c.mutation.NextRotation(); ok { _spec.SetField(keys.FieldNextRotation, field.TypeTime, value) _node.NextRotation = value } @@ -165,16 +165,16 @@ type KeysCreateBulk struct { } // Save creates the Keys entities in the database. -func (kcb *KeysCreateBulk) Save(ctx context.Context) ([]*Keys, error) { - if kcb.err != nil { - return nil, kcb.err - } - specs := make([]*sqlgraph.CreateSpec, len(kcb.builders)) - nodes := make([]*Keys, len(kcb.builders)) - mutators := make([]Mutator, len(kcb.builders)) - for i := range kcb.builders { +func (_c *KeysCreateBulk) Save(ctx context.Context) ([]*Keys, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Keys, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { func(i int, root context.Context) { - builder := kcb.builders[i] + builder := _c.builders[i] var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { mutation, ok := m.(*KeysMutation) if !ok { @@ -187,11 +187,11 @@ func (kcb *KeysCreateBulk) Save(ctx context.Context) ([]*Keys, error) { var err error nodes[i], specs[i] = builder.createSpec() if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, kcb.builders[i+1].mutation) + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, kcb.driver, spec); err != nil { + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { if sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } @@ -211,7 +211,7 @@ func (kcb *KeysCreateBulk) Save(ctx context.Context) ([]*Keys, error) { }(i, ctx) } if len(mutators) > 0 { - if _, err := mutators[0].Mutate(ctx, kcb.builders[0].mutation); err != nil { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { return nil, err } } @@ -219,8 +219,8 @@ func (kcb *KeysCreateBulk) Save(ctx context.Context) ([]*Keys, error) { } // SaveX is like Save, but panics if an error occurs. -func (kcb *KeysCreateBulk) SaveX(ctx context.Context) []*Keys { - v, err := kcb.Save(ctx) +func (_c *KeysCreateBulk) SaveX(ctx context.Context) []*Keys { + v, err := _c.Save(ctx) if err != nil { panic(err) } @@ -228,14 +228,14 @@ func (kcb *KeysCreateBulk) SaveX(ctx context.Context) []*Keys { } // Exec executes the query. -func (kcb *KeysCreateBulk) Exec(ctx context.Context) error { - _, err := kcb.Save(ctx) +func (_c *KeysCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (kcb *KeysCreateBulk) ExecX(ctx context.Context) { - if err := kcb.Exec(ctx); err != nil { +func (_c *KeysCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { panic(err) } } diff --git a/storage/ent/db/keys_delete.go b/storage/ent/db/keys_delete.go index 7f66119452..b4e838eb62 100644 --- a/storage/ent/db/keys_delete.go +++ b/storage/ent/db/keys_delete.go @@ -20,56 +20,56 @@ type KeysDelete struct { } // Where appends a list predicates to the KeysDelete builder. -func (kd *KeysDelete) Where(ps ...predicate.Keys) *KeysDelete { - kd.mutation.Where(ps...) - return kd +func (_d *KeysDelete) Where(ps ...predicate.Keys) *KeysDelete { + _d.mutation.Where(ps...) + return _d } // Exec executes the deletion query and returns how many vertices were deleted. -func (kd *KeysDelete) Exec(ctx context.Context) (int, error) { - return withHooks(ctx, kd.sqlExec, kd.mutation, kd.hooks) +func (_d *KeysDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) } // ExecX is like Exec, but panics if an error occurs. -func (kd *KeysDelete) ExecX(ctx context.Context) int { - n, err := kd.Exec(ctx) +func (_d *KeysDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) if err != nil { panic(err) } return n } -func (kd *KeysDelete) sqlExec(ctx context.Context) (int, error) { +func (_d *KeysDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(keys.Table, sqlgraph.NewFieldSpec(keys.FieldID, field.TypeString)) - if ps := kd.mutation.predicates; len(ps) > 0 { + if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - affected, err := sqlgraph.DeleteNodes(ctx, kd.driver, _spec) + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) if err != nil && sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } - kd.mutation.done = true + _d.mutation.done = true return affected, err } // KeysDeleteOne is the builder for deleting a single Keys entity. type KeysDeleteOne struct { - kd *KeysDelete + _d *KeysDelete } // Where appends a list predicates to the KeysDelete builder. -func (kdo *KeysDeleteOne) Where(ps ...predicate.Keys) *KeysDeleteOne { - kdo.kd.mutation.Where(ps...) - return kdo +func (_d *KeysDeleteOne) Where(ps ...predicate.Keys) *KeysDeleteOne { + _d._d.mutation.Where(ps...) + return _d } // Exec executes the deletion query. -func (kdo *KeysDeleteOne) Exec(ctx context.Context) error { - n, err := kdo.kd.Exec(ctx) +func (_d *KeysDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) switch { case err != nil: return err @@ -81,8 +81,8 @@ func (kdo *KeysDeleteOne) Exec(ctx context.Context) error { } // ExecX is like Exec, but panics if an error occurs. -func (kdo *KeysDeleteOne) ExecX(ctx context.Context) { - if err := kdo.Exec(ctx); err != nil { +func (_d *KeysDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { panic(err) } } diff --git a/storage/ent/db/keys_query.go b/storage/ent/db/keys_query.go index 2b59c67f0f..1c86b797a4 100644 --- a/storage/ent/db/keys_query.go +++ b/storage/ent/db/keys_query.go @@ -28,40 +28,40 @@ type KeysQuery struct { } // Where adds a new predicate for the KeysQuery builder. -func (kq *KeysQuery) Where(ps ...predicate.Keys) *KeysQuery { - kq.predicates = append(kq.predicates, ps...) - return kq +func (_q *KeysQuery) Where(ps ...predicate.Keys) *KeysQuery { + _q.predicates = append(_q.predicates, ps...) + return _q } // Limit the number of records to be returned by this query. -func (kq *KeysQuery) Limit(limit int) *KeysQuery { - kq.ctx.Limit = &limit - return kq +func (_q *KeysQuery) Limit(limit int) *KeysQuery { + _q.ctx.Limit = &limit + return _q } // Offset to start from. -func (kq *KeysQuery) Offset(offset int) *KeysQuery { - kq.ctx.Offset = &offset - return kq +func (_q *KeysQuery) Offset(offset int) *KeysQuery { + _q.ctx.Offset = &offset + return _q } // Unique configures the query builder to filter duplicate records on query. // By default, unique is set to true, and can be disabled using this method. -func (kq *KeysQuery) Unique(unique bool) *KeysQuery { - kq.ctx.Unique = &unique - return kq +func (_q *KeysQuery) Unique(unique bool) *KeysQuery { + _q.ctx.Unique = &unique + return _q } // Order specifies how the records should be ordered. -func (kq *KeysQuery) Order(o ...keys.OrderOption) *KeysQuery { - kq.order = append(kq.order, o...) - return kq +func (_q *KeysQuery) Order(o ...keys.OrderOption) *KeysQuery { + _q.order = append(_q.order, o...) + return _q } // First returns the first Keys entity from the query. // Returns a *NotFoundError when no Keys was found. -func (kq *KeysQuery) First(ctx context.Context) (*Keys, error) { - nodes, err := kq.Limit(1).All(setContextOp(ctx, kq.ctx, ent.OpQueryFirst)) +func (_q *KeysQuery) First(ctx context.Context) (*Keys, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) if err != nil { return nil, err } @@ -72,8 +72,8 @@ func (kq *KeysQuery) First(ctx context.Context) (*Keys, error) { } // FirstX is like First, but panics if an error occurs. -func (kq *KeysQuery) FirstX(ctx context.Context) *Keys { - node, err := kq.First(ctx) +func (_q *KeysQuery) FirstX(ctx context.Context) *Keys { + node, err := _q.First(ctx) if err != nil && !IsNotFound(err) { panic(err) } @@ -82,9 +82,9 @@ func (kq *KeysQuery) FirstX(ctx context.Context) *Keys { // FirstID returns the first Keys ID from the query. // Returns a *NotFoundError when no Keys ID was found. -func (kq *KeysQuery) FirstID(ctx context.Context) (id string, err error) { +func (_q *KeysQuery) FirstID(ctx context.Context) (id string, err error) { var ids []string - if ids, err = kq.Limit(1).IDs(setContextOp(ctx, kq.ctx, ent.OpQueryFirstID)); err != nil { + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { return } if len(ids) == 0 { @@ -95,8 +95,8 @@ func (kq *KeysQuery) FirstID(ctx context.Context) (id string, err error) { } // FirstIDX is like FirstID, but panics if an error occurs. -func (kq *KeysQuery) FirstIDX(ctx context.Context) string { - id, err := kq.FirstID(ctx) +func (_q *KeysQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) if err != nil && !IsNotFound(err) { panic(err) } @@ -106,8 +106,8 @@ func (kq *KeysQuery) FirstIDX(ctx context.Context) string { // Only returns a single Keys entity found by the query, ensuring it only returns one. // Returns a *NotSingularError when more than one Keys entity is found. // Returns a *NotFoundError when no Keys entities are found. -func (kq *KeysQuery) Only(ctx context.Context) (*Keys, error) { - nodes, err := kq.Limit(2).All(setContextOp(ctx, kq.ctx, ent.OpQueryOnly)) +func (_q *KeysQuery) Only(ctx context.Context) (*Keys, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) if err != nil { return nil, err } @@ -122,8 +122,8 @@ func (kq *KeysQuery) Only(ctx context.Context) (*Keys, error) { } // OnlyX is like Only, but panics if an error occurs. -func (kq *KeysQuery) OnlyX(ctx context.Context) *Keys { - node, err := kq.Only(ctx) +func (_q *KeysQuery) OnlyX(ctx context.Context) *Keys { + node, err := _q.Only(ctx) if err != nil { panic(err) } @@ -133,9 +133,9 @@ func (kq *KeysQuery) OnlyX(ctx context.Context) *Keys { // OnlyID is like Only, but returns the only Keys ID in the query. // Returns a *NotSingularError when more than one Keys ID is found. // Returns a *NotFoundError when no entities are found. -func (kq *KeysQuery) OnlyID(ctx context.Context) (id string, err error) { +func (_q *KeysQuery) OnlyID(ctx context.Context) (id string, err error) { var ids []string - if ids, err = kq.Limit(2).IDs(setContextOp(ctx, kq.ctx, ent.OpQueryOnlyID)); err != nil { + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { return } switch len(ids) { @@ -150,8 +150,8 @@ func (kq *KeysQuery) OnlyID(ctx context.Context) (id string, err error) { } // OnlyIDX is like OnlyID, but panics if an error occurs. -func (kq *KeysQuery) OnlyIDX(ctx context.Context) string { - id, err := kq.OnlyID(ctx) +func (_q *KeysQuery) OnlyIDX(ctx context.Context) string { + id, err := _q.OnlyID(ctx) if err != nil { panic(err) } @@ -159,18 +159,18 @@ func (kq *KeysQuery) OnlyIDX(ctx context.Context) string { } // All executes the query and returns a list of KeysSlice. -func (kq *KeysQuery) All(ctx context.Context) ([]*Keys, error) { - ctx = setContextOp(ctx, kq.ctx, ent.OpQueryAll) - if err := kq.prepareQuery(ctx); err != nil { +func (_q *KeysQuery) All(ctx context.Context) ([]*Keys, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { return nil, err } qr := querierAll[[]*Keys, *KeysQuery]() - return withInterceptors[[]*Keys](ctx, kq, qr, kq.inters) + return withInterceptors[[]*Keys](ctx, _q, qr, _q.inters) } // AllX is like All, but panics if an error occurs. -func (kq *KeysQuery) AllX(ctx context.Context) []*Keys { - nodes, err := kq.All(ctx) +func (_q *KeysQuery) AllX(ctx context.Context) []*Keys { + nodes, err := _q.All(ctx) if err != nil { panic(err) } @@ -178,20 +178,20 @@ func (kq *KeysQuery) AllX(ctx context.Context) []*Keys { } // IDs executes the query and returns a list of Keys IDs. -func (kq *KeysQuery) IDs(ctx context.Context) (ids []string, err error) { - if kq.ctx.Unique == nil && kq.path != nil { - kq.Unique(true) +func (_q *KeysQuery) IDs(ctx context.Context) (ids []string, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) } - ctx = setContextOp(ctx, kq.ctx, ent.OpQueryIDs) - if err = kq.Select(keys.FieldID).Scan(ctx, &ids); err != nil { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(keys.FieldID).Scan(ctx, &ids); err != nil { return nil, err } return ids, nil } // IDsX is like IDs, but panics if an error occurs. -func (kq *KeysQuery) IDsX(ctx context.Context) []string { - ids, err := kq.IDs(ctx) +func (_q *KeysQuery) IDsX(ctx context.Context) []string { + ids, err := _q.IDs(ctx) if err != nil { panic(err) } @@ -199,17 +199,17 @@ func (kq *KeysQuery) IDsX(ctx context.Context) []string { } // Count returns the count of the given query. -func (kq *KeysQuery) Count(ctx context.Context) (int, error) { - ctx = setContextOp(ctx, kq.ctx, ent.OpQueryCount) - if err := kq.prepareQuery(ctx); err != nil { +func (_q *KeysQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { return 0, err } - return withInterceptors[int](ctx, kq, querierCount[*KeysQuery](), kq.inters) + return withInterceptors[int](ctx, _q, querierCount[*KeysQuery](), _q.inters) } // CountX is like Count, but panics if an error occurs. -func (kq *KeysQuery) CountX(ctx context.Context) int { - count, err := kq.Count(ctx) +func (_q *KeysQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) if err != nil { panic(err) } @@ -217,9 +217,9 @@ func (kq *KeysQuery) CountX(ctx context.Context) int { } // Exist returns true if the query has elements in the graph. -func (kq *KeysQuery) Exist(ctx context.Context) (bool, error) { - ctx = setContextOp(ctx, kq.ctx, ent.OpQueryExist) - switch _, err := kq.FirstID(ctx); { +func (_q *KeysQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { case IsNotFound(err): return false, nil case err != nil: @@ -230,8 +230,8 @@ func (kq *KeysQuery) Exist(ctx context.Context) (bool, error) { } // ExistX is like Exist, but panics if an error occurs. -func (kq *KeysQuery) ExistX(ctx context.Context) bool { - exist, err := kq.Exist(ctx) +func (_q *KeysQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) if err != nil { panic(err) } @@ -240,19 +240,19 @@ func (kq *KeysQuery) ExistX(ctx context.Context) bool { // Clone returns a duplicate of the KeysQuery builder, including all associated steps. It can be // used to prepare common query builders and use them differently after the clone is made. -func (kq *KeysQuery) Clone() *KeysQuery { - if kq == nil { +func (_q *KeysQuery) Clone() *KeysQuery { + if _q == nil { return nil } return &KeysQuery{ - config: kq.config, - ctx: kq.ctx.Clone(), - order: append([]keys.OrderOption{}, kq.order...), - inters: append([]Interceptor{}, kq.inters...), - predicates: append([]predicate.Keys{}, kq.predicates...), + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]keys.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Keys{}, _q.predicates...), // clone intermediate query. - sql: kq.sql.Clone(), - path: kq.path, + sql: _q.sql.Clone(), + path: _q.path, } } @@ -270,10 +270,10 @@ func (kq *KeysQuery) Clone() *KeysQuery { // GroupBy(keys.FieldVerificationKeys). // Aggregate(db.Count()). // Scan(ctx, &v) -func (kq *KeysQuery) GroupBy(field string, fields ...string) *KeysGroupBy { - kq.ctx.Fields = append([]string{field}, fields...) - grbuild := &KeysGroupBy{build: kq} - grbuild.flds = &kq.ctx.Fields +func (_q *KeysQuery) GroupBy(field string, fields ...string) *KeysGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &KeysGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields grbuild.label = keys.Label grbuild.scan = grbuild.Scan return grbuild @@ -291,62 +291,62 @@ func (kq *KeysQuery) GroupBy(field string, fields ...string) *KeysGroupBy { // client.Keys.Query(). // Select(keys.FieldVerificationKeys). // Scan(ctx, &v) -func (kq *KeysQuery) Select(fields ...string) *KeysSelect { - kq.ctx.Fields = append(kq.ctx.Fields, fields...) - sbuild := &KeysSelect{KeysQuery: kq} +func (_q *KeysQuery) Select(fields ...string) *KeysSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &KeysSelect{KeysQuery: _q} sbuild.label = keys.Label - sbuild.flds, sbuild.scan = &kq.ctx.Fields, sbuild.Scan + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan return sbuild } // Aggregate returns a KeysSelect configured with the given aggregations. -func (kq *KeysQuery) Aggregate(fns ...AggregateFunc) *KeysSelect { - return kq.Select().Aggregate(fns...) +func (_q *KeysQuery) Aggregate(fns ...AggregateFunc) *KeysSelect { + return _q.Select().Aggregate(fns...) } -func (kq *KeysQuery) prepareQuery(ctx context.Context) error { - for _, inter := range kq.inters { +func (_q *KeysQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { if inter == nil { return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)") } if trv, ok := inter.(Traverser); ok { - if err := trv.Traverse(ctx, kq); err != nil { + if err := trv.Traverse(ctx, _q); err != nil { return err } } } - for _, f := range kq.ctx.Fields { + for _, f := range _q.ctx.Fields { if !keys.ValidColumn(f) { return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} } } - if kq.path != nil { - prev, err := kq.path(ctx) + if _q.path != nil { + prev, err := _q.path(ctx) if err != nil { return err } - kq.sql = prev + _q.sql = prev } return nil } -func (kq *KeysQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Keys, error) { +func (_q *KeysQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Keys, error) { var ( nodes = []*Keys{} - _spec = kq.querySpec() + _spec = _q.querySpec() ) _spec.ScanValues = func(columns []string) ([]any, error) { return (*Keys).scanValues(nil, columns) } _spec.Assign = func(columns []string, values []any) error { - node := &Keys{config: kq.config} + node := &Keys{config: _q.config} nodes = append(nodes, node) return node.assignValues(columns, values) } for i := range hooks { hooks[i](ctx, _spec) } - if err := sqlgraph.QueryNodes(ctx, kq.driver, _spec); err != nil { + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { return nil, err } if len(nodes) == 0 { @@ -355,24 +355,24 @@ func (kq *KeysQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Keys, e return nodes, nil } -func (kq *KeysQuery) sqlCount(ctx context.Context) (int, error) { - _spec := kq.querySpec() - _spec.Node.Columns = kq.ctx.Fields - if len(kq.ctx.Fields) > 0 { - _spec.Unique = kq.ctx.Unique != nil && *kq.ctx.Unique +func (_q *KeysQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique } - return sqlgraph.CountNodes(ctx, kq.driver, _spec) + return sqlgraph.CountNodes(ctx, _q.driver, _spec) } -func (kq *KeysQuery) querySpec() *sqlgraph.QuerySpec { +func (_q *KeysQuery) querySpec() *sqlgraph.QuerySpec { _spec := sqlgraph.NewQuerySpec(keys.Table, keys.Columns, sqlgraph.NewFieldSpec(keys.FieldID, field.TypeString)) - _spec.From = kq.sql - if unique := kq.ctx.Unique; unique != nil { + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { _spec.Unique = *unique - } else if kq.path != nil { + } else if _q.path != nil { _spec.Unique = true } - if fields := kq.ctx.Fields; len(fields) > 0 { + if fields := _q.ctx.Fields; len(fields) > 0 { _spec.Node.Columns = make([]string, 0, len(fields)) _spec.Node.Columns = append(_spec.Node.Columns, keys.FieldID) for i := range fields { @@ -381,20 +381,20 @@ func (kq *KeysQuery) querySpec() *sqlgraph.QuerySpec { } } } - if ps := kq.predicates; len(ps) > 0 { + if ps := _q.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if limit := kq.ctx.Limit; limit != nil { + if limit := _q.ctx.Limit; limit != nil { _spec.Limit = *limit } - if offset := kq.ctx.Offset; offset != nil { + if offset := _q.ctx.Offset; offset != nil { _spec.Offset = *offset } - if ps := kq.order; len(ps) > 0 { + if ps := _q.order; len(ps) > 0 { _spec.Order = func(selector *sql.Selector) { for i := range ps { ps[i](selector) @@ -404,33 +404,33 @@ func (kq *KeysQuery) querySpec() *sqlgraph.QuerySpec { return _spec } -func (kq *KeysQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(kq.driver.Dialect()) +func (_q *KeysQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) t1 := builder.Table(keys.Table) - columns := kq.ctx.Fields + columns := _q.ctx.Fields if len(columns) == 0 { columns = keys.Columns } selector := builder.Select(t1.Columns(columns...)...).From(t1) - if kq.sql != nil { - selector = kq.sql + if _q.sql != nil { + selector = _q.sql selector.Select(selector.Columns(columns...)...) } - if kq.ctx.Unique != nil && *kq.ctx.Unique { + if _q.ctx.Unique != nil && *_q.ctx.Unique { selector.Distinct() } - for _, p := range kq.predicates { + for _, p := range _q.predicates { p(selector) } - for _, p := range kq.order { + for _, p := range _q.order { p(selector) } - if offset := kq.ctx.Offset; offset != nil { + if offset := _q.ctx.Offset; offset != nil { // limit is mandatory for offset clause. We start // with default value, and override it below if needed. selector.Offset(*offset).Limit(math.MaxInt32) } - if limit := kq.ctx.Limit; limit != nil { + if limit := _q.ctx.Limit; limit != nil { selector.Limit(*limit) } return selector @@ -443,41 +443,41 @@ type KeysGroupBy struct { } // Aggregate adds the given aggregation functions to the group-by query. -func (kgb *KeysGroupBy) Aggregate(fns ...AggregateFunc) *KeysGroupBy { - kgb.fns = append(kgb.fns, fns...) - return kgb +func (_g *KeysGroupBy) Aggregate(fns ...AggregateFunc) *KeysGroupBy { + _g.fns = append(_g.fns, fns...) + return _g } // Scan applies the selector query and scans the result into the given value. -func (kgb *KeysGroupBy) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, kgb.build.ctx, ent.OpQueryGroupBy) - if err := kgb.build.prepareQuery(ctx); err != nil { +func (_g *KeysGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { return err } - return scanWithInterceptors[*KeysQuery, *KeysGroupBy](ctx, kgb.build, kgb, kgb.build.inters, v) + return scanWithInterceptors[*KeysQuery, *KeysGroupBy](ctx, _g.build, _g, _g.build.inters, v) } -func (kgb *KeysGroupBy) sqlScan(ctx context.Context, root *KeysQuery, v any) error { +func (_g *KeysGroupBy) sqlScan(ctx context.Context, root *KeysQuery, v any) error { selector := root.sqlQuery(ctx).Select() - aggregation := make([]string, 0, len(kgb.fns)) - for _, fn := range kgb.fns { + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { aggregation = append(aggregation, fn(selector)) } if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(*kgb.flds)+len(kgb.fns)) - for _, f := range *kgb.flds { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { columns = append(columns, selector.C(f)) } columns = append(columns, aggregation...) selector.Select(columns...) } - selector.GroupBy(selector.Columns(*kgb.flds...)...) + selector.GroupBy(selector.Columns(*_g.flds...)...) if err := selector.Err(); err != nil { return err } rows := &sql.Rows{} query, args := selector.Query() - if err := kgb.build.driver.Query(ctx, query, args, rows); err != nil { + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() @@ -491,27 +491,27 @@ type KeysSelect struct { } // Aggregate adds the given aggregation functions to the selector query. -func (ks *KeysSelect) Aggregate(fns ...AggregateFunc) *KeysSelect { - ks.fns = append(ks.fns, fns...) - return ks +func (_s *KeysSelect) Aggregate(fns ...AggregateFunc) *KeysSelect { + _s.fns = append(_s.fns, fns...) + return _s } // Scan applies the selector query and scans the result into the given value. -func (ks *KeysSelect) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, ks.ctx, ent.OpQuerySelect) - if err := ks.prepareQuery(ctx); err != nil { +func (_s *KeysSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { return err } - return scanWithInterceptors[*KeysQuery, *KeysSelect](ctx, ks.KeysQuery, ks, ks.inters, v) + return scanWithInterceptors[*KeysQuery, *KeysSelect](ctx, _s.KeysQuery, _s, _s.inters, v) } -func (ks *KeysSelect) sqlScan(ctx context.Context, root *KeysQuery, v any) error { +func (_s *KeysSelect) sqlScan(ctx context.Context, root *KeysQuery, v any) error { selector := root.sqlQuery(ctx) - aggregation := make([]string, 0, len(ks.fns)) - for _, fn := range ks.fns { + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { aggregation = append(aggregation, fn(selector)) } - switch n := len(*ks.selector.flds); { + switch n := len(*_s.selector.flds); { case n == 0 && len(aggregation) > 0: selector.Select(aggregation...) case n != 0 && len(aggregation) > 0: @@ -519,7 +519,7 @@ func (ks *KeysSelect) sqlScan(ctx context.Context, root *KeysQuery, v any) error } rows := &sql.Rows{} query, args := selector.Query() - if err := ks.driver.Query(ctx, query, args, rows); err != nil { + if err := _s.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() diff --git a/storage/ent/db/keys_update.go b/storage/ent/db/keys_update.go index ff9ff97fca..f45446f079 100644 --- a/storage/ent/db/keys_update.go +++ b/storage/ent/db/keys_update.go @@ -26,78 +26,78 @@ type KeysUpdate struct { } // Where appends a list predicates to the KeysUpdate builder. -func (ku *KeysUpdate) Where(ps ...predicate.Keys) *KeysUpdate { - ku.mutation.Where(ps...) - return ku +func (_u *KeysUpdate) Where(ps ...predicate.Keys) *KeysUpdate { + _u.mutation.Where(ps...) + return _u } // SetVerificationKeys sets the "verification_keys" field. -func (ku *KeysUpdate) SetVerificationKeys(sk []storage.VerificationKey) *KeysUpdate { - ku.mutation.SetVerificationKeys(sk) - return ku +func (_u *KeysUpdate) SetVerificationKeys(v []storage.VerificationKey) *KeysUpdate { + _u.mutation.SetVerificationKeys(v) + return _u } -// AppendVerificationKeys appends sk to the "verification_keys" field. -func (ku *KeysUpdate) AppendVerificationKeys(sk []storage.VerificationKey) *KeysUpdate { - ku.mutation.AppendVerificationKeys(sk) - return ku +// AppendVerificationKeys appends value to the "verification_keys" field. +func (_u *KeysUpdate) AppendVerificationKeys(v []storage.VerificationKey) *KeysUpdate { + _u.mutation.AppendVerificationKeys(v) + return _u } // SetSigningKey sets the "signing_key" field. -func (ku *KeysUpdate) SetSigningKey(jwk jose.JSONWebKey) *KeysUpdate { - ku.mutation.SetSigningKey(jwk) - return ku +func (_u *KeysUpdate) SetSigningKey(v jose.JSONWebKey) *KeysUpdate { + _u.mutation.SetSigningKey(v) + return _u } // SetNillableSigningKey sets the "signing_key" field if the given value is not nil. -func (ku *KeysUpdate) SetNillableSigningKey(jwk *jose.JSONWebKey) *KeysUpdate { - if jwk != nil { - ku.SetSigningKey(*jwk) +func (_u *KeysUpdate) SetNillableSigningKey(v *jose.JSONWebKey) *KeysUpdate { + if v != nil { + _u.SetSigningKey(*v) } - return ku + return _u } // SetSigningKeyPub sets the "signing_key_pub" field. -func (ku *KeysUpdate) SetSigningKeyPub(jwk jose.JSONWebKey) *KeysUpdate { - ku.mutation.SetSigningKeyPub(jwk) - return ku +func (_u *KeysUpdate) SetSigningKeyPub(v jose.JSONWebKey) *KeysUpdate { + _u.mutation.SetSigningKeyPub(v) + return _u } // SetNillableSigningKeyPub sets the "signing_key_pub" field if the given value is not nil. -func (ku *KeysUpdate) SetNillableSigningKeyPub(jwk *jose.JSONWebKey) *KeysUpdate { - if jwk != nil { - ku.SetSigningKeyPub(*jwk) +func (_u *KeysUpdate) SetNillableSigningKeyPub(v *jose.JSONWebKey) *KeysUpdate { + if v != nil { + _u.SetSigningKeyPub(*v) } - return ku + return _u } // SetNextRotation sets the "next_rotation" field. -func (ku *KeysUpdate) SetNextRotation(t time.Time) *KeysUpdate { - ku.mutation.SetNextRotation(t) - return ku +func (_u *KeysUpdate) SetNextRotation(v time.Time) *KeysUpdate { + _u.mutation.SetNextRotation(v) + return _u } // SetNillableNextRotation sets the "next_rotation" field if the given value is not nil. -func (ku *KeysUpdate) SetNillableNextRotation(t *time.Time) *KeysUpdate { - if t != nil { - ku.SetNextRotation(*t) +func (_u *KeysUpdate) SetNillableNextRotation(v *time.Time) *KeysUpdate { + if v != nil { + _u.SetNextRotation(*v) } - return ku + return _u } // Mutation returns the KeysMutation object of the builder. -func (ku *KeysUpdate) Mutation() *KeysMutation { - return ku.mutation +func (_u *KeysUpdate) Mutation() *KeysMutation { + return _u.mutation } // Save executes the query and returns the number of nodes affected by the update operation. -func (ku *KeysUpdate) Save(ctx context.Context) (int, error) { - return withHooks(ctx, ku.sqlSave, ku.mutation, ku.hooks) +func (_u *KeysUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) } // SaveX is like Save, but panics if an error occurs. -func (ku *KeysUpdate) SaveX(ctx context.Context) int { - affected, err := ku.Save(ctx) +func (_u *KeysUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) if err != nil { panic(err) } @@ -105,45 +105,45 @@ func (ku *KeysUpdate) SaveX(ctx context.Context) int { } // Exec executes the query. -func (ku *KeysUpdate) Exec(ctx context.Context) error { - _, err := ku.Save(ctx) +func (_u *KeysUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (ku *KeysUpdate) ExecX(ctx context.Context) { - if err := ku.Exec(ctx); err != nil { +func (_u *KeysUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { panic(err) } } -func (ku *KeysUpdate) sqlSave(ctx context.Context) (n int, err error) { +func (_u *KeysUpdate) sqlSave(ctx context.Context) (_node int, err error) { _spec := sqlgraph.NewUpdateSpec(keys.Table, keys.Columns, sqlgraph.NewFieldSpec(keys.FieldID, field.TypeString)) - if ps := ku.mutation.predicates; len(ps) > 0 { + if ps := _u.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if value, ok := ku.mutation.VerificationKeys(); ok { + if value, ok := _u.mutation.VerificationKeys(); ok { _spec.SetField(keys.FieldVerificationKeys, field.TypeJSON, value) } - if value, ok := ku.mutation.AppendedVerificationKeys(); ok { + if value, ok := _u.mutation.AppendedVerificationKeys(); ok { _spec.AddModifier(func(u *sql.UpdateBuilder) { sqljson.Append(u, keys.FieldVerificationKeys, value) }) } - if value, ok := ku.mutation.SigningKey(); ok { + if value, ok := _u.mutation.SigningKey(); ok { _spec.SetField(keys.FieldSigningKey, field.TypeJSON, value) } - if value, ok := ku.mutation.SigningKeyPub(); ok { + if value, ok := _u.mutation.SigningKeyPub(); ok { _spec.SetField(keys.FieldSigningKeyPub, field.TypeJSON, value) } - if value, ok := ku.mutation.NextRotation(); ok { + if value, ok := _u.mutation.NextRotation(); ok { _spec.SetField(keys.FieldNextRotation, field.TypeTime, value) } - if n, err = sqlgraph.UpdateNodes(ctx, ku.driver, _spec); err != nil { + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{keys.Label} } else if sqlgraph.IsConstraintError(err) { @@ -151,8 +151,8 @@ func (ku *KeysUpdate) sqlSave(ctx context.Context) (n int, err error) { } return 0, err } - ku.mutation.done = true - return n, nil + _u.mutation.done = true + return _node, nil } // KeysUpdateOne is the builder for updating a single Keys entity. @@ -164,85 +164,85 @@ type KeysUpdateOne struct { } // SetVerificationKeys sets the "verification_keys" field. -func (kuo *KeysUpdateOne) SetVerificationKeys(sk []storage.VerificationKey) *KeysUpdateOne { - kuo.mutation.SetVerificationKeys(sk) - return kuo +func (_u *KeysUpdateOne) SetVerificationKeys(v []storage.VerificationKey) *KeysUpdateOne { + _u.mutation.SetVerificationKeys(v) + return _u } -// AppendVerificationKeys appends sk to the "verification_keys" field. -func (kuo *KeysUpdateOne) AppendVerificationKeys(sk []storage.VerificationKey) *KeysUpdateOne { - kuo.mutation.AppendVerificationKeys(sk) - return kuo +// AppendVerificationKeys appends value to the "verification_keys" field. +func (_u *KeysUpdateOne) AppendVerificationKeys(v []storage.VerificationKey) *KeysUpdateOne { + _u.mutation.AppendVerificationKeys(v) + return _u } // SetSigningKey sets the "signing_key" field. -func (kuo *KeysUpdateOne) SetSigningKey(jwk jose.JSONWebKey) *KeysUpdateOne { - kuo.mutation.SetSigningKey(jwk) - return kuo +func (_u *KeysUpdateOne) SetSigningKey(v jose.JSONWebKey) *KeysUpdateOne { + _u.mutation.SetSigningKey(v) + return _u } // SetNillableSigningKey sets the "signing_key" field if the given value is not nil. -func (kuo *KeysUpdateOne) SetNillableSigningKey(jwk *jose.JSONWebKey) *KeysUpdateOne { - if jwk != nil { - kuo.SetSigningKey(*jwk) +func (_u *KeysUpdateOne) SetNillableSigningKey(v *jose.JSONWebKey) *KeysUpdateOne { + if v != nil { + _u.SetSigningKey(*v) } - return kuo + return _u } // SetSigningKeyPub sets the "signing_key_pub" field. -func (kuo *KeysUpdateOne) SetSigningKeyPub(jwk jose.JSONWebKey) *KeysUpdateOne { - kuo.mutation.SetSigningKeyPub(jwk) - return kuo +func (_u *KeysUpdateOne) SetSigningKeyPub(v jose.JSONWebKey) *KeysUpdateOne { + _u.mutation.SetSigningKeyPub(v) + return _u } // SetNillableSigningKeyPub sets the "signing_key_pub" field if the given value is not nil. -func (kuo *KeysUpdateOne) SetNillableSigningKeyPub(jwk *jose.JSONWebKey) *KeysUpdateOne { - if jwk != nil { - kuo.SetSigningKeyPub(*jwk) +func (_u *KeysUpdateOne) SetNillableSigningKeyPub(v *jose.JSONWebKey) *KeysUpdateOne { + if v != nil { + _u.SetSigningKeyPub(*v) } - return kuo + return _u } // SetNextRotation sets the "next_rotation" field. -func (kuo *KeysUpdateOne) SetNextRotation(t time.Time) *KeysUpdateOne { - kuo.mutation.SetNextRotation(t) - return kuo +func (_u *KeysUpdateOne) SetNextRotation(v time.Time) *KeysUpdateOne { + _u.mutation.SetNextRotation(v) + return _u } // SetNillableNextRotation sets the "next_rotation" field if the given value is not nil. -func (kuo *KeysUpdateOne) SetNillableNextRotation(t *time.Time) *KeysUpdateOne { - if t != nil { - kuo.SetNextRotation(*t) +func (_u *KeysUpdateOne) SetNillableNextRotation(v *time.Time) *KeysUpdateOne { + if v != nil { + _u.SetNextRotation(*v) } - return kuo + return _u } // Mutation returns the KeysMutation object of the builder. -func (kuo *KeysUpdateOne) Mutation() *KeysMutation { - return kuo.mutation +func (_u *KeysUpdateOne) Mutation() *KeysMutation { + return _u.mutation } // Where appends a list predicates to the KeysUpdate builder. -func (kuo *KeysUpdateOne) Where(ps ...predicate.Keys) *KeysUpdateOne { - kuo.mutation.Where(ps...) - return kuo +func (_u *KeysUpdateOne) Where(ps ...predicate.Keys) *KeysUpdateOne { + _u.mutation.Where(ps...) + return _u } // Select allows selecting one or more fields (columns) of the returned entity. // The default is selecting all fields defined in the entity schema. -func (kuo *KeysUpdateOne) Select(field string, fields ...string) *KeysUpdateOne { - kuo.fields = append([]string{field}, fields...) - return kuo +func (_u *KeysUpdateOne) Select(field string, fields ...string) *KeysUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u } // Save executes the query and returns the updated Keys entity. -func (kuo *KeysUpdateOne) Save(ctx context.Context) (*Keys, error) { - return withHooks(ctx, kuo.sqlSave, kuo.mutation, kuo.hooks) +func (_u *KeysUpdateOne) Save(ctx context.Context) (*Keys, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) } // SaveX is like Save, but panics if an error occurs. -func (kuo *KeysUpdateOne) SaveX(ctx context.Context) *Keys { - node, err := kuo.Save(ctx) +func (_u *KeysUpdateOne) SaveX(ctx context.Context) *Keys { + node, err := _u.Save(ctx) if err != nil { panic(err) } @@ -250,26 +250,26 @@ func (kuo *KeysUpdateOne) SaveX(ctx context.Context) *Keys { } // Exec executes the query on the entity. -func (kuo *KeysUpdateOne) Exec(ctx context.Context) error { - _, err := kuo.Save(ctx) +func (_u *KeysUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (kuo *KeysUpdateOne) ExecX(ctx context.Context) { - if err := kuo.Exec(ctx); err != nil { +func (_u *KeysUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { panic(err) } } -func (kuo *KeysUpdateOne) sqlSave(ctx context.Context) (_node *Keys, err error) { +func (_u *KeysUpdateOne) sqlSave(ctx context.Context) (_node *Keys, err error) { _spec := sqlgraph.NewUpdateSpec(keys.Table, keys.Columns, sqlgraph.NewFieldSpec(keys.FieldID, field.TypeString)) - id, ok := kuo.mutation.ID() + id, ok := _u.mutation.ID() if !ok { return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "Keys.id" for update`)} } _spec.Node.ID.Value = id - if fields := kuo.fields; len(fields) > 0 { + if fields := _u.fields; len(fields) > 0 { _spec.Node.Columns = make([]string, 0, len(fields)) _spec.Node.Columns = append(_spec.Node.Columns, keys.FieldID) for _, f := range fields { @@ -281,34 +281,34 @@ func (kuo *KeysUpdateOne) sqlSave(ctx context.Context) (_node *Keys, err error) } } } - if ps := kuo.mutation.predicates; len(ps) > 0 { + if ps := _u.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if value, ok := kuo.mutation.VerificationKeys(); ok { + if value, ok := _u.mutation.VerificationKeys(); ok { _spec.SetField(keys.FieldVerificationKeys, field.TypeJSON, value) } - if value, ok := kuo.mutation.AppendedVerificationKeys(); ok { + if value, ok := _u.mutation.AppendedVerificationKeys(); ok { _spec.AddModifier(func(u *sql.UpdateBuilder) { sqljson.Append(u, keys.FieldVerificationKeys, value) }) } - if value, ok := kuo.mutation.SigningKey(); ok { + if value, ok := _u.mutation.SigningKey(); ok { _spec.SetField(keys.FieldSigningKey, field.TypeJSON, value) } - if value, ok := kuo.mutation.SigningKeyPub(); ok { + if value, ok := _u.mutation.SigningKeyPub(); ok { _spec.SetField(keys.FieldSigningKeyPub, field.TypeJSON, value) } - if value, ok := kuo.mutation.NextRotation(); ok { + if value, ok := _u.mutation.NextRotation(); ok { _spec.SetField(keys.FieldNextRotation, field.TypeTime, value) } - _node = &Keys{config: kuo.config} + _node = &Keys{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, kuo.driver, _spec); err != nil { + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{keys.Label} } else if sqlgraph.IsConstraintError(err) { @@ -316,6 +316,6 @@ func (kuo *KeysUpdateOne) sqlSave(ctx context.Context) (_node *Keys, err error) } return nil, err } - kuo.mutation.done = true + _u.mutation.done = true return _node, nil } diff --git a/storage/ent/db/oauth2client.go b/storage/ent/db/oauth2client.go index 39a4cf82ab..f8491be21a 100644 --- a/storage/ent/db/oauth2client.go +++ b/storage/ent/db/oauth2client.go @@ -52,7 +52,7 @@ func (*OAuth2Client) scanValues(columns []string) ([]any, error) { // assignValues assigns the values that were returned from sql.Rows (after scanning) // to the OAuth2Client fields. -func (o *OAuth2Client) assignValues(columns []string, values []any) error { +func (_m *OAuth2Client) 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) } @@ -62,19 +62,19 @@ func (o *OAuth2Client) assignValues(columns []string, values []any) error { if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field id", values[i]) } else if value.Valid { - o.ID = value.String + _m.ID = value.String } case oauth2client.FieldSecret: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field secret", values[i]) } else if value.Valid { - o.Secret = value.String + _m.Secret = value.String } case oauth2client.FieldRedirectUris: if value, ok := values[i].(*[]byte); !ok { return fmt.Errorf("unexpected type %T for field redirect_uris", values[i]) } else if value != nil && len(*value) > 0 { - if err := json.Unmarshal(*value, &o.RedirectUris); err != nil { + if err := json.Unmarshal(*value, &_m.RedirectUris); err != nil { return fmt.Errorf("unmarshal field redirect_uris: %w", err) } } @@ -82,7 +82,7 @@ func (o *OAuth2Client) assignValues(columns []string, values []any) error { if value, ok := values[i].(*[]byte); !ok { return fmt.Errorf("unexpected type %T for field trusted_peers", values[i]) } else if value != nil && len(*value) > 0 { - if err := json.Unmarshal(*value, &o.TrustedPeers); err != nil { + if err := json.Unmarshal(*value, &_m.TrustedPeers); err != nil { return fmt.Errorf("unmarshal field trusted_peers: %w", err) } } @@ -90,22 +90,22 @@ func (o *OAuth2Client) assignValues(columns []string, values []any) error { if value, ok := values[i].(*sql.NullBool); !ok { return fmt.Errorf("unexpected type %T for field public", values[i]) } else if value.Valid { - o.Public = value.Bool + _m.Public = value.Bool } case oauth2client.FieldName: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field name", values[i]) } else if value.Valid { - o.Name = value.String + _m.Name = value.String } case oauth2client.FieldLogoURL: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field logo_url", values[i]) } else if value.Valid { - o.LogoURL = value.String + _m.LogoURL = value.String } default: - o.selectValues.Set(columns[i], values[i]) + _m.selectValues.Set(columns[i], values[i]) } } return nil @@ -113,50 +113,50 @@ func (o *OAuth2Client) assignValues(columns []string, values []any) error { // Value returns the ent.Value that was dynamically selected and assigned to the OAuth2Client. // This includes values selected through modifiers, order, etc. -func (o *OAuth2Client) Value(name string) (ent.Value, error) { - return o.selectValues.Get(name) +func (_m *OAuth2Client) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) } // Update returns a builder for updating this OAuth2Client. // Note that you need to call OAuth2Client.Unwrap() before calling this method if this OAuth2Client // was returned from a transaction, and the transaction was committed or rolled back. -func (o *OAuth2Client) Update() *OAuth2ClientUpdateOne { - return NewOAuth2ClientClient(o.config).UpdateOne(o) +func (_m *OAuth2Client) Update() *OAuth2ClientUpdateOne { + return NewOAuth2ClientClient(_m.config).UpdateOne(_m) } // Unwrap unwraps the OAuth2Client 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 (o *OAuth2Client) Unwrap() *OAuth2Client { - _tx, ok := o.config.driver.(*txDriver) +func (_m *OAuth2Client) Unwrap() *OAuth2Client { + _tx, ok := _m.config.driver.(*txDriver) if !ok { panic("db: OAuth2Client is not a transactional entity") } - o.config.driver = _tx.drv - return o + _m.config.driver = _tx.drv + return _m } // String implements the fmt.Stringer. -func (o *OAuth2Client) String() string { +func (_m *OAuth2Client) String() string { var builder strings.Builder builder.WriteString("OAuth2Client(") - builder.WriteString(fmt.Sprintf("id=%v, ", o.ID)) + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) builder.WriteString("secret=") - builder.WriteString(o.Secret) + builder.WriteString(_m.Secret) builder.WriteString(", ") builder.WriteString("redirect_uris=") - builder.WriteString(fmt.Sprintf("%v", o.RedirectUris)) + builder.WriteString(fmt.Sprintf("%v", _m.RedirectUris)) builder.WriteString(", ") builder.WriteString("trusted_peers=") - builder.WriteString(fmt.Sprintf("%v", o.TrustedPeers)) + builder.WriteString(fmt.Sprintf("%v", _m.TrustedPeers)) builder.WriteString(", ") builder.WriteString("public=") - builder.WriteString(fmt.Sprintf("%v", o.Public)) + builder.WriteString(fmt.Sprintf("%v", _m.Public)) builder.WriteString(", ") builder.WriteString("name=") - builder.WriteString(o.Name) + builder.WriteString(_m.Name) builder.WriteString(", ") builder.WriteString("logo_url=") - builder.WriteString(o.LogoURL) + builder.WriteString(_m.LogoURL) builder.WriteByte(')') return builder.String() } diff --git a/storage/ent/db/oauth2client_create.go b/storage/ent/db/oauth2client_create.go index 5b472cd36d..2bbf1f5033 100644 --- a/storage/ent/db/oauth2client_create.go +++ b/storage/ent/db/oauth2client_create.go @@ -20,60 +20,60 @@ type OAuth2ClientCreate struct { } // SetSecret sets the "secret" field. -func (oc *OAuth2ClientCreate) SetSecret(s string) *OAuth2ClientCreate { - oc.mutation.SetSecret(s) - return oc +func (_c *OAuth2ClientCreate) SetSecret(v string) *OAuth2ClientCreate { + _c.mutation.SetSecret(v) + return _c } // SetRedirectUris sets the "redirect_uris" field. -func (oc *OAuth2ClientCreate) SetRedirectUris(s []string) *OAuth2ClientCreate { - oc.mutation.SetRedirectUris(s) - return oc +func (_c *OAuth2ClientCreate) SetRedirectUris(v []string) *OAuth2ClientCreate { + _c.mutation.SetRedirectUris(v) + return _c } // SetTrustedPeers sets the "trusted_peers" field. -func (oc *OAuth2ClientCreate) SetTrustedPeers(s []string) *OAuth2ClientCreate { - oc.mutation.SetTrustedPeers(s) - return oc +func (_c *OAuth2ClientCreate) SetTrustedPeers(v []string) *OAuth2ClientCreate { + _c.mutation.SetTrustedPeers(v) + return _c } // SetPublic sets the "public" field. -func (oc *OAuth2ClientCreate) SetPublic(b bool) *OAuth2ClientCreate { - oc.mutation.SetPublic(b) - return oc +func (_c *OAuth2ClientCreate) SetPublic(v bool) *OAuth2ClientCreate { + _c.mutation.SetPublic(v) + return _c } // SetName sets the "name" field. -func (oc *OAuth2ClientCreate) SetName(s string) *OAuth2ClientCreate { - oc.mutation.SetName(s) - return oc +func (_c *OAuth2ClientCreate) SetName(v string) *OAuth2ClientCreate { + _c.mutation.SetName(v) + return _c } // SetLogoURL sets the "logo_url" field. -func (oc *OAuth2ClientCreate) SetLogoURL(s string) *OAuth2ClientCreate { - oc.mutation.SetLogoURL(s) - return oc +func (_c *OAuth2ClientCreate) SetLogoURL(v string) *OAuth2ClientCreate { + _c.mutation.SetLogoURL(v) + return _c } // SetID sets the "id" field. -func (oc *OAuth2ClientCreate) SetID(s string) *OAuth2ClientCreate { - oc.mutation.SetID(s) - return oc +func (_c *OAuth2ClientCreate) SetID(v string) *OAuth2ClientCreate { + _c.mutation.SetID(v) + return _c } // Mutation returns the OAuth2ClientMutation object of the builder. -func (oc *OAuth2ClientCreate) Mutation() *OAuth2ClientMutation { - return oc.mutation +func (_c *OAuth2ClientCreate) Mutation() *OAuth2ClientMutation { + return _c.mutation } // Save creates the OAuth2Client in the database. -func (oc *OAuth2ClientCreate) Save(ctx context.Context) (*OAuth2Client, error) { - return withHooks(ctx, oc.sqlSave, oc.mutation, oc.hooks) +func (_c *OAuth2ClientCreate) Save(ctx context.Context) (*OAuth2Client, error) { + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) } // SaveX calls Save and panics if Save returns an error. -func (oc *OAuth2ClientCreate) SaveX(ctx context.Context) *OAuth2Client { - v, err := oc.Save(ctx) +func (_c *OAuth2ClientCreate) SaveX(ctx context.Context) *OAuth2Client { + v, err := _c.Save(ctx) if err != nil { panic(err) } @@ -81,48 +81,48 @@ func (oc *OAuth2ClientCreate) SaveX(ctx context.Context) *OAuth2Client { } // Exec executes the query. -func (oc *OAuth2ClientCreate) Exec(ctx context.Context) error { - _, err := oc.Save(ctx) +func (_c *OAuth2ClientCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (oc *OAuth2ClientCreate) ExecX(ctx context.Context) { - if err := oc.Exec(ctx); err != nil { +func (_c *OAuth2ClientCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { panic(err) } } // check runs all checks and user-defined validators on the builder. -func (oc *OAuth2ClientCreate) check() error { - if _, ok := oc.mutation.Secret(); !ok { +func (_c *OAuth2ClientCreate) check() error { + if _, ok := _c.mutation.Secret(); !ok { return &ValidationError{Name: "secret", err: errors.New(`db: missing required field "OAuth2Client.secret"`)} } - if v, ok := oc.mutation.Secret(); ok { + if v, ok := _c.mutation.Secret(); ok { if err := oauth2client.SecretValidator(v); err != nil { return &ValidationError{Name: "secret", err: fmt.Errorf(`db: validator failed for field "OAuth2Client.secret": %w`, err)} } } - if _, ok := oc.mutation.Public(); !ok { + if _, ok := _c.mutation.Public(); !ok { return &ValidationError{Name: "public", err: errors.New(`db: missing required field "OAuth2Client.public"`)} } - if _, ok := oc.mutation.Name(); !ok { + if _, ok := _c.mutation.Name(); !ok { return &ValidationError{Name: "name", err: errors.New(`db: missing required field "OAuth2Client.name"`)} } - if v, ok := oc.mutation.Name(); ok { + if v, ok := _c.mutation.Name(); ok { if err := oauth2client.NameValidator(v); err != nil { return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "OAuth2Client.name": %w`, err)} } } - if _, ok := oc.mutation.LogoURL(); !ok { + if _, ok := _c.mutation.LogoURL(); !ok { return &ValidationError{Name: "logo_url", err: errors.New(`db: missing required field "OAuth2Client.logo_url"`)} } - if v, ok := oc.mutation.LogoURL(); ok { + if v, ok := _c.mutation.LogoURL(); ok { if err := oauth2client.LogoURLValidator(v); err != nil { return &ValidationError{Name: "logo_url", err: fmt.Errorf(`db: validator failed for field "OAuth2Client.logo_url": %w`, err)} } } - if v, ok := oc.mutation.ID(); ok { + if v, ok := _c.mutation.ID(); ok { if err := oauth2client.IDValidator(v); err != nil { return &ValidationError{Name: "id", err: fmt.Errorf(`db: validator failed for field "OAuth2Client.id": %w`, err)} } @@ -130,12 +130,12 @@ func (oc *OAuth2ClientCreate) check() error { return nil } -func (oc *OAuth2ClientCreate) sqlSave(ctx context.Context) (*OAuth2Client, error) { - if err := oc.check(); err != nil { +func (_c *OAuth2ClientCreate) sqlSave(ctx context.Context) (*OAuth2Client, error) { + if err := _c.check(); err != nil { return nil, err } - _node, _spec := oc.createSpec() - if err := sqlgraph.CreateNode(ctx, oc.driver, _spec); err != nil { + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { if sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } @@ -148,41 +148,41 @@ func (oc *OAuth2ClientCreate) sqlSave(ctx context.Context) (*OAuth2Client, error return nil, fmt.Errorf("unexpected OAuth2Client.ID type: %T", _spec.ID.Value) } } - oc.mutation.id = &_node.ID - oc.mutation.done = true + _c.mutation.id = &_node.ID + _c.mutation.done = true return _node, nil } -func (oc *OAuth2ClientCreate) createSpec() (*OAuth2Client, *sqlgraph.CreateSpec) { +func (_c *OAuth2ClientCreate) createSpec() (*OAuth2Client, *sqlgraph.CreateSpec) { var ( - _node = &OAuth2Client{config: oc.config} + _node = &OAuth2Client{config: _c.config} _spec = sqlgraph.NewCreateSpec(oauth2client.Table, sqlgraph.NewFieldSpec(oauth2client.FieldID, field.TypeString)) ) - if id, ok := oc.mutation.ID(); ok { + if id, ok := _c.mutation.ID(); ok { _node.ID = id _spec.ID.Value = id } - if value, ok := oc.mutation.Secret(); ok { + if value, ok := _c.mutation.Secret(); ok { _spec.SetField(oauth2client.FieldSecret, field.TypeString, value) _node.Secret = value } - if value, ok := oc.mutation.RedirectUris(); ok { + if value, ok := _c.mutation.RedirectUris(); ok { _spec.SetField(oauth2client.FieldRedirectUris, field.TypeJSON, value) _node.RedirectUris = value } - if value, ok := oc.mutation.TrustedPeers(); ok { + if value, ok := _c.mutation.TrustedPeers(); ok { _spec.SetField(oauth2client.FieldTrustedPeers, field.TypeJSON, value) _node.TrustedPeers = value } - if value, ok := oc.mutation.Public(); ok { + if value, ok := _c.mutation.Public(); ok { _spec.SetField(oauth2client.FieldPublic, field.TypeBool, value) _node.Public = value } - if value, ok := oc.mutation.Name(); ok { + if value, ok := _c.mutation.Name(); ok { _spec.SetField(oauth2client.FieldName, field.TypeString, value) _node.Name = value } - if value, ok := oc.mutation.LogoURL(); ok { + if value, ok := _c.mutation.LogoURL(); ok { _spec.SetField(oauth2client.FieldLogoURL, field.TypeString, value) _node.LogoURL = value } @@ -197,16 +197,16 @@ type OAuth2ClientCreateBulk struct { } // Save creates the OAuth2Client entities in the database. -func (ocb *OAuth2ClientCreateBulk) Save(ctx context.Context) ([]*OAuth2Client, error) { - if ocb.err != nil { - return nil, ocb.err +func (_c *OAuth2ClientCreateBulk) Save(ctx context.Context) ([]*OAuth2Client, error) { + if _c.err != nil { + return nil, _c.err } - specs := make([]*sqlgraph.CreateSpec, len(ocb.builders)) - nodes := make([]*OAuth2Client, len(ocb.builders)) - mutators := make([]Mutator, len(ocb.builders)) - for i := range ocb.builders { + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*OAuth2Client, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { func(i int, root context.Context) { - builder := ocb.builders[i] + builder := _c.builders[i] var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { mutation, ok := m.(*OAuth2ClientMutation) if !ok { @@ -219,11 +219,11 @@ func (ocb *OAuth2ClientCreateBulk) Save(ctx context.Context) ([]*OAuth2Client, e var err error nodes[i], specs[i] = builder.createSpec() if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, ocb.builders[i+1].mutation) + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, ocb.driver, spec); err != nil { + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { if sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } @@ -243,7 +243,7 @@ func (ocb *OAuth2ClientCreateBulk) Save(ctx context.Context) ([]*OAuth2Client, e }(i, ctx) } if len(mutators) > 0 { - if _, err := mutators[0].Mutate(ctx, ocb.builders[0].mutation); err != nil { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { return nil, err } } @@ -251,8 +251,8 @@ func (ocb *OAuth2ClientCreateBulk) Save(ctx context.Context) ([]*OAuth2Client, e } // SaveX is like Save, but panics if an error occurs. -func (ocb *OAuth2ClientCreateBulk) SaveX(ctx context.Context) []*OAuth2Client { - v, err := ocb.Save(ctx) +func (_c *OAuth2ClientCreateBulk) SaveX(ctx context.Context) []*OAuth2Client { + v, err := _c.Save(ctx) if err != nil { panic(err) } @@ -260,14 +260,14 @@ func (ocb *OAuth2ClientCreateBulk) SaveX(ctx context.Context) []*OAuth2Client { } // Exec executes the query. -func (ocb *OAuth2ClientCreateBulk) Exec(ctx context.Context) error { - _, err := ocb.Save(ctx) +func (_c *OAuth2ClientCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (ocb *OAuth2ClientCreateBulk) ExecX(ctx context.Context) { - if err := ocb.Exec(ctx); err != nil { +func (_c *OAuth2ClientCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { panic(err) } } diff --git a/storage/ent/db/oauth2client_delete.go b/storage/ent/db/oauth2client_delete.go index ee88e2800b..d8c340aedc 100644 --- a/storage/ent/db/oauth2client_delete.go +++ b/storage/ent/db/oauth2client_delete.go @@ -20,56 +20,56 @@ type OAuth2ClientDelete struct { } // Where appends a list predicates to the OAuth2ClientDelete builder. -func (od *OAuth2ClientDelete) Where(ps ...predicate.OAuth2Client) *OAuth2ClientDelete { - od.mutation.Where(ps...) - return od +func (_d *OAuth2ClientDelete) Where(ps ...predicate.OAuth2Client) *OAuth2ClientDelete { + _d.mutation.Where(ps...) + return _d } // Exec executes the deletion query and returns how many vertices were deleted. -func (od *OAuth2ClientDelete) Exec(ctx context.Context) (int, error) { - return withHooks(ctx, od.sqlExec, od.mutation, od.hooks) +func (_d *OAuth2ClientDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) } // ExecX is like Exec, but panics if an error occurs. -func (od *OAuth2ClientDelete) ExecX(ctx context.Context) int { - n, err := od.Exec(ctx) +func (_d *OAuth2ClientDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) if err != nil { panic(err) } return n } -func (od *OAuth2ClientDelete) sqlExec(ctx context.Context) (int, error) { +func (_d *OAuth2ClientDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(oauth2client.Table, sqlgraph.NewFieldSpec(oauth2client.FieldID, field.TypeString)) - if ps := od.mutation.predicates; len(ps) > 0 { + if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - affected, err := sqlgraph.DeleteNodes(ctx, od.driver, _spec) + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) if err != nil && sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } - od.mutation.done = true + _d.mutation.done = true return affected, err } // OAuth2ClientDeleteOne is the builder for deleting a single OAuth2Client entity. type OAuth2ClientDeleteOne struct { - od *OAuth2ClientDelete + _d *OAuth2ClientDelete } // Where appends a list predicates to the OAuth2ClientDelete builder. -func (odo *OAuth2ClientDeleteOne) Where(ps ...predicate.OAuth2Client) *OAuth2ClientDeleteOne { - odo.od.mutation.Where(ps...) - return odo +func (_d *OAuth2ClientDeleteOne) Where(ps ...predicate.OAuth2Client) *OAuth2ClientDeleteOne { + _d._d.mutation.Where(ps...) + return _d } // Exec executes the deletion query. -func (odo *OAuth2ClientDeleteOne) Exec(ctx context.Context) error { - n, err := odo.od.Exec(ctx) +func (_d *OAuth2ClientDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) switch { case err != nil: return err @@ -81,8 +81,8 @@ func (odo *OAuth2ClientDeleteOne) Exec(ctx context.Context) error { } // ExecX is like Exec, but panics if an error occurs. -func (odo *OAuth2ClientDeleteOne) ExecX(ctx context.Context) { - if err := odo.Exec(ctx); err != nil { +func (_d *OAuth2ClientDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { panic(err) } } diff --git a/storage/ent/db/oauth2client_query.go b/storage/ent/db/oauth2client_query.go index 27597112df..21e2b114dd 100644 --- a/storage/ent/db/oauth2client_query.go +++ b/storage/ent/db/oauth2client_query.go @@ -28,40 +28,40 @@ type OAuth2ClientQuery struct { } // Where adds a new predicate for the OAuth2ClientQuery builder. -func (oq *OAuth2ClientQuery) Where(ps ...predicate.OAuth2Client) *OAuth2ClientQuery { - oq.predicates = append(oq.predicates, ps...) - return oq +func (_q *OAuth2ClientQuery) Where(ps ...predicate.OAuth2Client) *OAuth2ClientQuery { + _q.predicates = append(_q.predicates, ps...) + return _q } // Limit the number of records to be returned by this query. -func (oq *OAuth2ClientQuery) Limit(limit int) *OAuth2ClientQuery { - oq.ctx.Limit = &limit - return oq +func (_q *OAuth2ClientQuery) Limit(limit int) *OAuth2ClientQuery { + _q.ctx.Limit = &limit + return _q } // Offset to start from. -func (oq *OAuth2ClientQuery) Offset(offset int) *OAuth2ClientQuery { - oq.ctx.Offset = &offset - return oq +func (_q *OAuth2ClientQuery) Offset(offset int) *OAuth2ClientQuery { + _q.ctx.Offset = &offset + return _q } // Unique configures the query builder to filter duplicate records on query. // By default, unique is set to true, and can be disabled using this method. -func (oq *OAuth2ClientQuery) Unique(unique bool) *OAuth2ClientQuery { - oq.ctx.Unique = &unique - return oq +func (_q *OAuth2ClientQuery) Unique(unique bool) *OAuth2ClientQuery { + _q.ctx.Unique = &unique + return _q } // Order specifies how the records should be ordered. -func (oq *OAuth2ClientQuery) Order(o ...oauth2client.OrderOption) *OAuth2ClientQuery { - oq.order = append(oq.order, o...) - return oq +func (_q *OAuth2ClientQuery) Order(o ...oauth2client.OrderOption) *OAuth2ClientQuery { + _q.order = append(_q.order, o...) + return _q } // First returns the first OAuth2Client entity from the query. // Returns a *NotFoundError when no OAuth2Client was found. -func (oq *OAuth2ClientQuery) First(ctx context.Context) (*OAuth2Client, error) { - nodes, err := oq.Limit(1).All(setContextOp(ctx, oq.ctx, ent.OpQueryFirst)) +func (_q *OAuth2ClientQuery) First(ctx context.Context) (*OAuth2Client, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) if err != nil { return nil, err } @@ -72,8 +72,8 @@ func (oq *OAuth2ClientQuery) First(ctx context.Context) (*OAuth2Client, error) { } // FirstX is like First, but panics if an error occurs. -func (oq *OAuth2ClientQuery) FirstX(ctx context.Context) *OAuth2Client { - node, err := oq.First(ctx) +func (_q *OAuth2ClientQuery) FirstX(ctx context.Context) *OAuth2Client { + node, err := _q.First(ctx) if err != nil && !IsNotFound(err) { panic(err) } @@ -82,9 +82,9 @@ func (oq *OAuth2ClientQuery) FirstX(ctx context.Context) *OAuth2Client { // FirstID returns the first OAuth2Client ID from the query. // Returns a *NotFoundError when no OAuth2Client ID was found. -func (oq *OAuth2ClientQuery) FirstID(ctx context.Context) (id string, err error) { +func (_q *OAuth2ClientQuery) FirstID(ctx context.Context) (id string, err error) { var ids []string - if ids, err = oq.Limit(1).IDs(setContextOp(ctx, oq.ctx, ent.OpQueryFirstID)); err != nil { + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { return } if len(ids) == 0 { @@ -95,8 +95,8 @@ func (oq *OAuth2ClientQuery) FirstID(ctx context.Context) (id string, err error) } // FirstIDX is like FirstID, but panics if an error occurs. -func (oq *OAuth2ClientQuery) FirstIDX(ctx context.Context) string { - id, err := oq.FirstID(ctx) +func (_q *OAuth2ClientQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) if err != nil && !IsNotFound(err) { panic(err) } @@ -106,8 +106,8 @@ func (oq *OAuth2ClientQuery) FirstIDX(ctx context.Context) string { // Only returns a single OAuth2Client entity found by the query, ensuring it only returns one. // Returns a *NotSingularError when more than one OAuth2Client entity is found. // Returns a *NotFoundError when no OAuth2Client entities are found. -func (oq *OAuth2ClientQuery) Only(ctx context.Context) (*OAuth2Client, error) { - nodes, err := oq.Limit(2).All(setContextOp(ctx, oq.ctx, ent.OpQueryOnly)) +func (_q *OAuth2ClientQuery) Only(ctx context.Context) (*OAuth2Client, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) if err != nil { return nil, err } @@ -122,8 +122,8 @@ func (oq *OAuth2ClientQuery) Only(ctx context.Context) (*OAuth2Client, error) { } // OnlyX is like Only, but panics if an error occurs. -func (oq *OAuth2ClientQuery) OnlyX(ctx context.Context) *OAuth2Client { - node, err := oq.Only(ctx) +func (_q *OAuth2ClientQuery) OnlyX(ctx context.Context) *OAuth2Client { + node, err := _q.Only(ctx) if err != nil { panic(err) } @@ -133,9 +133,9 @@ func (oq *OAuth2ClientQuery) OnlyX(ctx context.Context) *OAuth2Client { // OnlyID is like Only, but returns the only OAuth2Client ID in the query. // Returns a *NotSingularError when more than one OAuth2Client ID is found. // Returns a *NotFoundError when no entities are found. -func (oq *OAuth2ClientQuery) OnlyID(ctx context.Context) (id string, err error) { +func (_q *OAuth2ClientQuery) OnlyID(ctx context.Context) (id string, err error) { var ids []string - if ids, err = oq.Limit(2).IDs(setContextOp(ctx, oq.ctx, ent.OpQueryOnlyID)); err != nil { + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { return } switch len(ids) { @@ -150,8 +150,8 @@ func (oq *OAuth2ClientQuery) OnlyID(ctx context.Context) (id string, err error) } // OnlyIDX is like OnlyID, but panics if an error occurs. -func (oq *OAuth2ClientQuery) OnlyIDX(ctx context.Context) string { - id, err := oq.OnlyID(ctx) +func (_q *OAuth2ClientQuery) OnlyIDX(ctx context.Context) string { + id, err := _q.OnlyID(ctx) if err != nil { panic(err) } @@ -159,18 +159,18 @@ func (oq *OAuth2ClientQuery) OnlyIDX(ctx context.Context) string { } // All executes the query and returns a list of OAuth2Clients. -func (oq *OAuth2ClientQuery) All(ctx context.Context) ([]*OAuth2Client, error) { - ctx = setContextOp(ctx, oq.ctx, ent.OpQueryAll) - if err := oq.prepareQuery(ctx); err != nil { +func (_q *OAuth2ClientQuery) All(ctx context.Context) ([]*OAuth2Client, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { return nil, err } qr := querierAll[[]*OAuth2Client, *OAuth2ClientQuery]() - return withInterceptors[[]*OAuth2Client](ctx, oq, qr, oq.inters) + return withInterceptors[[]*OAuth2Client](ctx, _q, qr, _q.inters) } // AllX is like All, but panics if an error occurs. -func (oq *OAuth2ClientQuery) AllX(ctx context.Context) []*OAuth2Client { - nodes, err := oq.All(ctx) +func (_q *OAuth2ClientQuery) AllX(ctx context.Context) []*OAuth2Client { + nodes, err := _q.All(ctx) if err != nil { panic(err) } @@ -178,20 +178,20 @@ func (oq *OAuth2ClientQuery) AllX(ctx context.Context) []*OAuth2Client { } // IDs executes the query and returns a list of OAuth2Client IDs. -func (oq *OAuth2ClientQuery) IDs(ctx context.Context) (ids []string, err error) { - if oq.ctx.Unique == nil && oq.path != nil { - oq.Unique(true) +func (_q *OAuth2ClientQuery) IDs(ctx context.Context) (ids []string, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) } - ctx = setContextOp(ctx, oq.ctx, ent.OpQueryIDs) - if err = oq.Select(oauth2client.FieldID).Scan(ctx, &ids); err != nil { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(oauth2client.FieldID).Scan(ctx, &ids); err != nil { return nil, err } return ids, nil } // IDsX is like IDs, but panics if an error occurs. -func (oq *OAuth2ClientQuery) IDsX(ctx context.Context) []string { - ids, err := oq.IDs(ctx) +func (_q *OAuth2ClientQuery) IDsX(ctx context.Context) []string { + ids, err := _q.IDs(ctx) if err != nil { panic(err) } @@ -199,17 +199,17 @@ func (oq *OAuth2ClientQuery) IDsX(ctx context.Context) []string { } // Count returns the count of the given query. -func (oq *OAuth2ClientQuery) Count(ctx context.Context) (int, error) { - ctx = setContextOp(ctx, oq.ctx, ent.OpQueryCount) - if err := oq.prepareQuery(ctx); err != nil { +func (_q *OAuth2ClientQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { return 0, err } - return withInterceptors[int](ctx, oq, querierCount[*OAuth2ClientQuery](), oq.inters) + return withInterceptors[int](ctx, _q, querierCount[*OAuth2ClientQuery](), _q.inters) } // CountX is like Count, but panics if an error occurs. -func (oq *OAuth2ClientQuery) CountX(ctx context.Context) int { - count, err := oq.Count(ctx) +func (_q *OAuth2ClientQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) if err != nil { panic(err) } @@ -217,9 +217,9 @@ func (oq *OAuth2ClientQuery) CountX(ctx context.Context) int { } // Exist returns true if the query has elements in the graph. -func (oq *OAuth2ClientQuery) Exist(ctx context.Context) (bool, error) { - ctx = setContextOp(ctx, oq.ctx, ent.OpQueryExist) - switch _, err := oq.FirstID(ctx); { +func (_q *OAuth2ClientQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { case IsNotFound(err): return false, nil case err != nil: @@ -230,8 +230,8 @@ func (oq *OAuth2ClientQuery) Exist(ctx context.Context) (bool, error) { } // ExistX is like Exist, but panics if an error occurs. -func (oq *OAuth2ClientQuery) ExistX(ctx context.Context) bool { - exist, err := oq.Exist(ctx) +func (_q *OAuth2ClientQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) if err != nil { panic(err) } @@ -240,19 +240,19 @@ func (oq *OAuth2ClientQuery) ExistX(ctx context.Context) bool { // Clone returns a duplicate of the OAuth2ClientQuery builder, including all associated steps. It can be // used to prepare common query builders and use them differently after the clone is made. -func (oq *OAuth2ClientQuery) Clone() *OAuth2ClientQuery { - if oq == nil { +func (_q *OAuth2ClientQuery) Clone() *OAuth2ClientQuery { + if _q == nil { return nil } return &OAuth2ClientQuery{ - config: oq.config, - ctx: oq.ctx.Clone(), - order: append([]oauth2client.OrderOption{}, oq.order...), - inters: append([]Interceptor{}, oq.inters...), - predicates: append([]predicate.OAuth2Client{}, oq.predicates...), + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]oauth2client.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.OAuth2Client{}, _q.predicates...), // clone intermediate query. - sql: oq.sql.Clone(), - path: oq.path, + sql: _q.sql.Clone(), + path: _q.path, } } @@ -270,10 +270,10 @@ func (oq *OAuth2ClientQuery) Clone() *OAuth2ClientQuery { // GroupBy(oauth2client.FieldSecret). // Aggregate(db.Count()). // Scan(ctx, &v) -func (oq *OAuth2ClientQuery) GroupBy(field string, fields ...string) *OAuth2ClientGroupBy { - oq.ctx.Fields = append([]string{field}, fields...) - grbuild := &OAuth2ClientGroupBy{build: oq} - grbuild.flds = &oq.ctx.Fields +func (_q *OAuth2ClientQuery) GroupBy(field string, fields ...string) *OAuth2ClientGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &OAuth2ClientGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields grbuild.label = oauth2client.Label grbuild.scan = grbuild.Scan return grbuild @@ -291,62 +291,62 @@ func (oq *OAuth2ClientQuery) GroupBy(field string, fields ...string) *OAuth2Clie // client.OAuth2Client.Query(). // Select(oauth2client.FieldSecret). // Scan(ctx, &v) -func (oq *OAuth2ClientQuery) Select(fields ...string) *OAuth2ClientSelect { - oq.ctx.Fields = append(oq.ctx.Fields, fields...) - sbuild := &OAuth2ClientSelect{OAuth2ClientQuery: oq} +func (_q *OAuth2ClientQuery) Select(fields ...string) *OAuth2ClientSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &OAuth2ClientSelect{OAuth2ClientQuery: _q} sbuild.label = oauth2client.Label - sbuild.flds, sbuild.scan = &oq.ctx.Fields, sbuild.Scan + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan return sbuild } // Aggregate returns a OAuth2ClientSelect configured with the given aggregations. -func (oq *OAuth2ClientQuery) Aggregate(fns ...AggregateFunc) *OAuth2ClientSelect { - return oq.Select().Aggregate(fns...) +func (_q *OAuth2ClientQuery) Aggregate(fns ...AggregateFunc) *OAuth2ClientSelect { + return _q.Select().Aggregate(fns...) } -func (oq *OAuth2ClientQuery) prepareQuery(ctx context.Context) error { - for _, inter := range oq.inters { +func (_q *OAuth2ClientQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { if inter == nil { return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)") } if trv, ok := inter.(Traverser); ok { - if err := trv.Traverse(ctx, oq); err != nil { + if err := trv.Traverse(ctx, _q); err != nil { return err } } } - for _, f := range oq.ctx.Fields { + for _, f := range _q.ctx.Fields { if !oauth2client.ValidColumn(f) { return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} } } - if oq.path != nil { - prev, err := oq.path(ctx) + if _q.path != nil { + prev, err := _q.path(ctx) if err != nil { return err } - oq.sql = prev + _q.sql = prev } return nil } -func (oq *OAuth2ClientQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*OAuth2Client, error) { +func (_q *OAuth2ClientQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*OAuth2Client, error) { var ( nodes = []*OAuth2Client{} - _spec = oq.querySpec() + _spec = _q.querySpec() ) _spec.ScanValues = func(columns []string) ([]any, error) { return (*OAuth2Client).scanValues(nil, columns) } _spec.Assign = func(columns []string, values []any) error { - node := &OAuth2Client{config: oq.config} + node := &OAuth2Client{config: _q.config} nodes = append(nodes, node) return node.assignValues(columns, values) } for i := range hooks { hooks[i](ctx, _spec) } - if err := sqlgraph.QueryNodes(ctx, oq.driver, _spec); err != nil { + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { return nil, err } if len(nodes) == 0 { @@ -355,24 +355,24 @@ func (oq *OAuth2ClientQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([] return nodes, nil } -func (oq *OAuth2ClientQuery) sqlCount(ctx context.Context) (int, error) { - _spec := oq.querySpec() - _spec.Node.Columns = oq.ctx.Fields - if len(oq.ctx.Fields) > 0 { - _spec.Unique = oq.ctx.Unique != nil && *oq.ctx.Unique +func (_q *OAuth2ClientQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique } - return sqlgraph.CountNodes(ctx, oq.driver, _spec) + return sqlgraph.CountNodes(ctx, _q.driver, _spec) } -func (oq *OAuth2ClientQuery) querySpec() *sqlgraph.QuerySpec { +func (_q *OAuth2ClientQuery) querySpec() *sqlgraph.QuerySpec { _spec := sqlgraph.NewQuerySpec(oauth2client.Table, oauth2client.Columns, sqlgraph.NewFieldSpec(oauth2client.FieldID, field.TypeString)) - _spec.From = oq.sql - if unique := oq.ctx.Unique; unique != nil { + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { _spec.Unique = *unique - } else if oq.path != nil { + } else if _q.path != nil { _spec.Unique = true } - if fields := oq.ctx.Fields; len(fields) > 0 { + if fields := _q.ctx.Fields; len(fields) > 0 { _spec.Node.Columns = make([]string, 0, len(fields)) _spec.Node.Columns = append(_spec.Node.Columns, oauth2client.FieldID) for i := range fields { @@ -381,20 +381,20 @@ func (oq *OAuth2ClientQuery) querySpec() *sqlgraph.QuerySpec { } } } - if ps := oq.predicates; len(ps) > 0 { + if ps := _q.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if limit := oq.ctx.Limit; limit != nil { + if limit := _q.ctx.Limit; limit != nil { _spec.Limit = *limit } - if offset := oq.ctx.Offset; offset != nil { + if offset := _q.ctx.Offset; offset != nil { _spec.Offset = *offset } - if ps := oq.order; len(ps) > 0 { + if ps := _q.order; len(ps) > 0 { _spec.Order = func(selector *sql.Selector) { for i := range ps { ps[i](selector) @@ -404,33 +404,33 @@ func (oq *OAuth2ClientQuery) querySpec() *sqlgraph.QuerySpec { return _spec } -func (oq *OAuth2ClientQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(oq.driver.Dialect()) +func (_q *OAuth2ClientQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) t1 := builder.Table(oauth2client.Table) - columns := oq.ctx.Fields + columns := _q.ctx.Fields if len(columns) == 0 { columns = oauth2client.Columns } selector := builder.Select(t1.Columns(columns...)...).From(t1) - if oq.sql != nil { - selector = oq.sql + if _q.sql != nil { + selector = _q.sql selector.Select(selector.Columns(columns...)...) } - if oq.ctx.Unique != nil && *oq.ctx.Unique { + if _q.ctx.Unique != nil && *_q.ctx.Unique { selector.Distinct() } - for _, p := range oq.predicates { + for _, p := range _q.predicates { p(selector) } - for _, p := range oq.order { + for _, p := range _q.order { p(selector) } - if offset := oq.ctx.Offset; offset != nil { + if offset := _q.ctx.Offset; offset != nil { // limit is mandatory for offset clause. We start // with default value, and override it below if needed. selector.Offset(*offset).Limit(math.MaxInt32) } - if limit := oq.ctx.Limit; limit != nil { + if limit := _q.ctx.Limit; limit != nil { selector.Limit(*limit) } return selector @@ -443,41 +443,41 @@ type OAuth2ClientGroupBy struct { } // Aggregate adds the given aggregation functions to the group-by query. -func (ogb *OAuth2ClientGroupBy) Aggregate(fns ...AggregateFunc) *OAuth2ClientGroupBy { - ogb.fns = append(ogb.fns, fns...) - return ogb +func (_g *OAuth2ClientGroupBy) Aggregate(fns ...AggregateFunc) *OAuth2ClientGroupBy { + _g.fns = append(_g.fns, fns...) + return _g } // Scan applies the selector query and scans the result into the given value. -func (ogb *OAuth2ClientGroupBy) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, ogb.build.ctx, ent.OpQueryGroupBy) - if err := ogb.build.prepareQuery(ctx); err != nil { +func (_g *OAuth2ClientGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { return err } - return scanWithInterceptors[*OAuth2ClientQuery, *OAuth2ClientGroupBy](ctx, ogb.build, ogb, ogb.build.inters, v) + return scanWithInterceptors[*OAuth2ClientQuery, *OAuth2ClientGroupBy](ctx, _g.build, _g, _g.build.inters, v) } -func (ogb *OAuth2ClientGroupBy) sqlScan(ctx context.Context, root *OAuth2ClientQuery, v any) error { +func (_g *OAuth2ClientGroupBy) sqlScan(ctx context.Context, root *OAuth2ClientQuery, v any) error { selector := root.sqlQuery(ctx).Select() - aggregation := make([]string, 0, len(ogb.fns)) - for _, fn := range ogb.fns { + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { aggregation = append(aggregation, fn(selector)) } if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(*ogb.flds)+len(ogb.fns)) - for _, f := range *ogb.flds { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { columns = append(columns, selector.C(f)) } columns = append(columns, aggregation...) selector.Select(columns...) } - selector.GroupBy(selector.Columns(*ogb.flds...)...) + selector.GroupBy(selector.Columns(*_g.flds...)...) if err := selector.Err(); err != nil { return err } rows := &sql.Rows{} query, args := selector.Query() - if err := ogb.build.driver.Query(ctx, query, args, rows); err != nil { + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() @@ -491,27 +491,27 @@ type OAuth2ClientSelect struct { } // Aggregate adds the given aggregation functions to the selector query. -func (os *OAuth2ClientSelect) Aggregate(fns ...AggregateFunc) *OAuth2ClientSelect { - os.fns = append(os.fns, fns...) - return os +func (_s *OAuth2ClientSelect) Aggregate(fns ...AggregateFunc) *OAuth2ClientSelect { + _s.fns = append(_s.fns, fns...) + return _s } // Scan applies the selector query and scans the result into the given value. -func (os *OAuth2ClientSelect) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, os.ctx, ent.OpQuerySelect) - if err := os.prepareQuery(ctx); err != nil { +func (_s *OAuth2ClientSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { return err } - return scanWithInterceptors[*OAuth2ClientQuery, *OAuth2ClientSelect](ctx, os.OAuth2ClientQuery, os, os.inters, v) + return scanWithInterceptors[*OAuth2ClientQuery, *OAuth2ClientSelect](ctx, _s.OAuth2ClientQuery, _s, _s.inters, v) } -func (os *OAuth2ClientSelect) sqlScan(ctx context.Context, root *OAuth2ClientQuery, v any) error { +func (_s *OAuth2ClientSelect) sqlScan(ctx context.Context, root *OAuth2ClientQuery, v any) error { selector := root.sqlQuery(ctx) - aggregation := make([]string, 0, len(os.fns)) - for _, fn := range os.fns { + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { aggregation = append(aggregation, fn(selector)) } - switch n := len(*os.selector.flds); { + switch n := len(*_s.selector.flds); { case n == 0 && len(aggregation) > 0: selector.Select(aggregation...) case n != 0 && len(aggregation) > 0: @@ -519,7 +519,7 @@ func (os *OAuth2ClientSelect) sqlScan(ctx context.Context, root *OAuth2ClientQue } rows := &sql.Rows{} query, args := selector.Query() - if err := os.driver.Query(ctx, query, args, rows); err != nil { + if err := _s.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() diff --git a/storage/ent/db/oauth2client_update.go b/storage/ent/db/oauth2client_update.go index 9d84e0b854..69f2c0440e 100644 --- a/storage/ent/db/oauth2client_update.go +++ b/storage/ent/db/oauth2client_update.go @@ -23,116 +23,116 @@ type OAuth2ClientUpdate struct { } // Where appends a list predicates to the OAuth2ClientUpdate builder. -func (ou *OAuth2ClientUpdate) Where(ps ...predicate.OAuth2Client) *OAuth2ClientUpdate { - ou.mutation.Where(ps...) - return ou +func (_u *OAuth2ClientUpdate) Where(ps ...predicate.OAuth2Client) *OAuth2ClientUpdate { + _u.mutation.Where(ps...) + return _u } // SetSecret sets the "secret" field. -func (ou *OAuth2ClientUpdate) SetSecret(s string) *OAuth2ClientUpdate { - ou.mutation.SetSecret(s) - return ou +func (_u *OAuth2ClientUpdate) SetSecret(v string) *OAuth2ClientUpdate { + _u.mutation.SetSecret(v) + return _u } // SetNillableSecret sets the "secret" field if the given value is not nil. -func (ou *OAuth2ClientUpdate) SetNillableSecret(s *string) *OAuth2ClientUpdate { - if s != nil { - ou.SetSecret(*s) +func (_u *OAuth2ClientUpdate) SetNillableSecret(v *string) *OAuth2ClientUpdate { + if v != nil { + _u.SetSecret(*v) } - return ou + return _u } // SetRedirectUris sets the "redirect_uris" field. -func (ou *OAuth2ClientUpdate) SetRedirectUris(s []string) *OAuth2ClientUpdate { - ou.mutation.SetRedirectUris(s) - return ou +func (_u *OAuth2ClientUpdate) SetRedirectUris(v []string) *OAuth2ClientUpdate { + _u.mutation.SetRedirectUris(v) + return _u } -// AppendRedirectUris appends s to the "redirect_uris" field. -func (ou *OAuth2ClientUpdate) AppendRedirectUris(s []string) *OAuth2ClientUpdate { - ou.mutation.AppendRedirectUris(s) - return ou +// AppendRedirectUris appends value to the "redirect_uris" field. +func (_u *OAuth2ClientUpdate) AppendRedirectUris(v []string) *OAuth2ClientUpdate { + _u.mutation.AppendRedirectUris(v) + return _u } // ClearRedirectUris clears the value of the "redirect_uris" field. -func (ou *OAuth2ClientUpdate) ClearRedirectUris() *OAuth2ClientUpdate { - ou.mutation.ClearRedirectUris() - return ou +func (_u *OAuth2ClientUpdate) ClearRedirectUris() *OAuth2ClientUpdate { + _u.mutation.ClearRedirectUris() + return _u } // SetTrustedPeers sets the "trusted_peers" field. -func (ou *OAuth2ClientUpdate) SetTrustedPeers(s []string) *OAuth2ClientUpdate { - ou.mutation.SetTrustedPeers(s) - return ou +func (_u *OAuth2ClientUpdate) SetTrustedPeers(v []string) *OAuth2ClientUpdate { + _u.mutation.SetTrustedPeers(v) + return _u } -// AppendTrustedPeers appends s to the "trusted_peers" field. -func (ou *OAuth2ClientUpdate) AppendTrustedPeers(s []string) *OAuth2ClientUpdate { - ou.mutation.AppendTrustedPeers(s) - return ou +// AppendTrustedPeers appends value to the "trusted_peers" field. +func (_u *OAuth2ClientUpdate) AppendTrustedPeers(v []string) *OAuth2ClientUpdate { + _u.mutation.AppendTrustedPeers(v) + return _u } // ClearTrustedPeers clears the value of the "trusted_peers" field. -func (ou *OAuth2ClientUpdate) ClearTrustedPeers() *OAuth2ClientUpdate { - ou.mutation.ClearTrustedPeers() - return ou +func (_u *OAuth2ClientUpdate) ClearTrustedPeers() *OAuth2ClientUpdate { + _u.mutation.ClearTrustedPeers() + return _u } // SetPublic sets the "public" field. -func (ou *OAuth2ClientUpdate) SetPublic(b bool) *OAuth2ClientUpdate { - ou.mutation.SetPublic(b) - return ou +func (_u *OAuth2ClientUpdate) SetPublic(v bool) *OAuth2ClientUpdate { + _u.mutation.SetPublic(v) + return _u } // SetNillablePublic sets the "public" field if the given value is not nil. -func (ou *OAuth2ClientUpdate) SetNillablePublic(b *bool) *OAuth2ClientUpdate { - if b != nil { - ou.SetPublic(*b) +func (_u *OAuth2ClientUpdate) SetNillablePublic(v *bool) *OAuth2ClientUpdate { + if v != nil { + _u.SetPublic(*v) } - return ou + return _u } // SetName sets the "name" field. -func (ou *OAuth2ClientUpdate) SetName(s string) *OAuth2ClientUpdate { - ou.mutation.SetName(s) - return ou +func (_u *OAuth2ClientUpdate) SetName(v string) *OAuth2ClientUpdate { + _u.mutation.SetName(v) + return _u } // SetNillableName sets the "name" field if the given value is not nil. -func (ou *OAuth2ClientUpdate) SetNillableName(s *string) *OAuth2ClientUpdate { - if s != nil { - ou.SetName(*s) +func (_u *OAuth2ClientUpdate) SetNillableName(v *string) *OAuth2ClientUpdate { + if v != nil { + _u.SetName(*v) } - return ou + return _u } // SetLogoURL sets the "logo_url" field. -func (ou *OAuth2ClientUpdate) SetLogoURL(s string) *OAuth2ClientUpdate { - ou.mutation.SetLogoURL(s) - return ou +func (_u *OAuth2ClientUpdate) SetLogoURL(v string) *OAuth2ClientUpdate { + _u.mutation.SetLogoURL(v) + return _u } // SetNillableLogoURL sets the "logo_url" field if the given value is not nil. -func (ou *OAuth2ClientUpdate) SetNillableLogoURL(s *string) *OAuth2ClientUpdate { - if s != nil { - ou.SetLogoURL(*s) +func (_u *OAuth2ClientUpdate) SetNillableLogoURL(v *string) *OAuth2ClientUpdate { + if v != nil { + _u.SetLogoURL(*v) } - return ou + return _u } // Mutation returns the OAuth2ClientMutation object of the builder. -func (ou *OAuth2ClientUpdate) Mutation() *OAuth2ClientMutation { - return ou.mutation +func (_u *OAuth2ClientUpdate) Mutation() *OAuth2ClientMutation { + return _u.mutation } // Save executes the query and returns the number of nodes affected by the update operation. -func (ou *OAuth2ClientUpdate) Save(ctx context.Context) (int, error) { - return withHooks(ctx, ou.sqlSave, ou.mutation, ou.hooks) +func (_u *OAuth2ClientUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) } // SaveX is like Save, but panics if an error occurs. -func (ou *OAuth2ClientUpdate) SaveX(ctx context.Context) int { - affected, err := ou.Save(ctx) +func (_u *OAuth2ClientUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) if err != nil { panic(err) } @@ -140,31 +140,31 @@ func (ou *OAuth2ClientUpdate) SaveX(ctx context.Context) int { } // Exec executes the query. -func (ou *OAuth2ClientUpdate) Exec(ctx context.Context) error { - _, err := ou.Save(ctx) +func (_u *OAuth2ClientUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (ou *OAuth2ClientUpdate) ExecX(ctx context.Context) { - if err := ou.Exec(ctx); err != nil { +func (_u *OAuth2ClientUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { panic(err) } } // check runs all checks and user-defined validators on the builder. -func (ou *OAuth2ClientUpdate) check() error { - if v, ok := ou.mutation.Secret(); ok { +func (_u *OAuth2ClientUpdate) check() error { + if v, ok := _u.mutation.Secret(); ok { if err := oauth2client.SecretValidator(v); err != nil { return &ValidationError{Name: "secret", err: fmt.Errorf(`db: validator failed for field "OAuth2Client.secret": %w`, err)} } } - if v, ok := ou.mutation.Name(); ok { + if v, ok := _u.mutation.Name(); ok { if err := oauth2client.NameValidator(v); err != nil { return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "OAuth2Client.name": %w`, err)} } } - if v, ok := ou.mutation.LogoURL(); ok { + if v, ok := _u.mutation.LogoURL(); ok { if err := oauth2client.LogoURLValidator(v); err != nil { return &ValidationError{Name: "logo_url", err: fmt.Errorf(`db: validator failed for field "OAuth2Client.logo_url": %w`, err)} } @@ -172,53 +172,53 @@ func (ou *OAuth2ClientUpdate) check() error { return nil } -func (ou *OAuth2ClientUpdate) sqlSave(ctx context.Context) (n int, err error) { - if err := ou.check(); err != nil { - return n, err +func (_u *OAuth2ClientUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err } _spec := sqlgraph.NewUpdateSpec(oauth2client.Table, oauth2client.Columns, sqlgraph.NewFieldSpec(oauth2client.FieldID, field.TypeString)) - if ps := ou.mutation.predicates; len(ps) > 0 { + if ps := _u.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if value, ok := ou.mutation.Secret(); ok { + if value, ok := _u.mutation.Secret(); ok { _spec.SetField(oauth2client.FieldSecret, field.TypeString, value) } - if value, ok := ou.mutation.RedirectUris(); ok { + if value, ok := _u.mutation.RedirectUris(); ok { _spec.SetField(oauth2client.FieldRedirectUris, field.TypeJSON, value) } - if value, ok := ou.mutation.AppendedRedirectUris(); ok { + if value, ok := _u.mutation.AppendedRedirectUris(); ok { _spec.AddModifier(func(u *sql.UpdateBuilder) { sqljson.Append(u, oauth2client.FieldRedirectUris, value) }) } - if ou.mutation.RedirectUrisCleared() { + if _u.mutation.RedirectUrisCleared() { _spec.ClearField(oauth2client.FieldRedirectUris, field.TypeJSON) } - if value, ok := ou.mutation.TrustedPeers(); ok { + if value, ok := _u.mutation.TrustedPeers(); ok { _spec.SetField(oauth2client.FieldTrustedPeers, field.TypeJSON, value) } - if value, ok := ou.mutation.AppendedTrustedPeers(); ok { + if value, ok := _u.mutation.AppendedTrustedPeers(); ok { _spec.AddModifier(func(u *sql.UpdateBuilder) { sqljson.Append(u, oauth2client.FieldTrustedPeers, value) }) } - if ou.mutation.TrustedPeersCleared() { + if _u.mutation.TrustedPeersCleared() { _spec.ClearField(oauth2client.FieldTrustedPeers, field.TypeJSON) } - if value, ok := ou.mutation.Public(); ok { + if value, ok := _u.mutation.Public(); ok { _spec.SetField(oauth2client.FieldPublic, field.TypeBool, value) } - if value, ok := ou.mutation.Name(); ok { + if value, ok := _u.mutation.Name(); ok { _spec.SetField(oauth2client.FieldName, field.TypeString, value) } - if value, ok := ou.mutation.LogoURL(); ok { + if value, ok := _u.mutation.LogoURL(); ok { _spec.SetField(oauth2client.FieldLogoURL, field.TypeString, value) } - if n, err = sqlgraph.UpdateNodes(ctx, ou.driver, _spec); err != nil { + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{oauth2client.Label} } else if sqlgraph.IsConstraintError(err) { @@ -226,8 +226,8 @@ func (ou *OAuth2ClientUpdate) sqlSave(ctx context.Context) (n int, err error) { } return 0, err } - ou.mutation.done = true - return n, nil + _u.mutation.done = true + return _node, nil } // OAuth2ClientUpdateOne is the builder for updating a single OAuth2Client entity. @@ -239,123 +239,123 @@ type OAuth2ClientUpdateOne struct { } // SetSecret sets the "secret" field. -func (ouo *OAuth2ClientUpdateOne) SetSecret(s string) *OAuth2ClientUpdateOne { - ouo.mutation.SetSecret(s) - return ouo +func (_u *OAuth2ClientUpdateOne) SetSecret(v string) *OAuth2ClientUpdateOne { + _u.mutation.SetSecret(v) + return _u } // SetNillableSecret sets the "secret" field if the given value is not nil. -func (ouo *OAuth2ClientUpdateOne) SetNillableSecret(s *string) *OAuth2ClientUpdateOne { - if s != nil { - ouo.SetSecret(*s) +func (_u *OAuth2ClientUpdateOne) SetNillableSecret(v *string) *OAuth2ClientUpdateOne { + if v != nil { + _u.SetSecret(*v) } - return ouo + return _u } // SetRedirectUris sets the "redirect_uris" field. -func (ouo *OAuth2ClientUpdateOne) SetRedirectUris(s []string) *OAuth2ClientUpdateOne { - ouo.mutation.SetRedirectUris(s) - return ouo +func (_u *OAuth2ClientUpdateOne) SetRedirectUris(v []string) *OAuth2ClientUpdateOne { + _u.mutation.SetRedirectUris(v) + return _u } -// AppendRedirectUris appends s to the "redirect_uris" field. -func (ouo *OAuth2ClientUpdateOne) AppendRedirectUris(s []string) *OAuth2ClientUpdateOne { - ouo.mutation.AppendRedirectUris(s) - return ouo +// AppendRedirectUris appends value to the "redirect_uris" field. +func (_u *OAuth2ClientUpdateOne) AppendRedirectUris(v []string) *OAuth2ClientUpdateOne { + _u.mutation.AppendRedirectUris(v) + return _u } // ClearRedirectUris clears the value of the "redirect_uris" field. -func (ouo *OAuth2ClientUpdateOne) ClearRedirectUris() *OAuth2ClientUpdateOne { - ouo.mutation.ClearRedirectUris() - return ouo +func (_u *OAuth2ClientUpdateOne) ClearRedirectUris() *OAuth2ClientUpdateOne { + _u.mutation.ClearRedirectUris() + return _u } // SetTrustedPeers sets the "trusted_peers" field. -func (ouo *OAuth2ClientUpdateOne) SetTrustedPeers(s []string) *OAuth2ClientUpdateOne { - ouo.mutation.SetTrustedPeers(s) - return ouo +func (_u *OAuth2ClientUpdateOne) SetTrustedPeers(v []string) *OAuth2ClientUpdateOne { + _u.mutation.SetTrustedPeers(v) + return _u } -// AppendTrustedPeers appends s to the "trusted_peers" field. -func (ouo *OAuth2ClientUpdateOne) AppendTrustedPeers(s []string) *OAuth2ClientUpdateOne { - ouo.mutation.AppendTrustedPeers(s) - return ouo +// AppendTrustedPeers appends value to the "trusted_peers" field. +func (_u *OAuth2ClientUpdateOne) AppendTrustedPeers(v []string) *OAuth2ClientUpdateOne { + _u.mutation.AppendTrustedPeers(v) + return _u } // ClearTrustedPeers clears the value of the "trusted_peers" field. -func (ouo *OAuth2ClientUpdateOne) ClearTrustedPeers() *OAuth2ClientUpdateOne { - ouo.mutation.ClearTrustedPeers() - return ouo +func (_u *OAuth2ClientUpdateOne) ClearTrustedPeers() *OAuth2ClientUpdateOne { + _u.mutation.ClearTrustedPeers() + return _u } // SetPublic sets the "public" field. -func (ouo *OAuth2ClientUpdateOne) SetPublic(b bool) *OAuth2ClientUpdateOne { - ouo.mutation.SetPublic(b) - return ouo +func (_u *OAuth2ClientUpdateOne) SetPublic(v bool) *OAuth2ClientUpdateOne { + _u.mutation.SetPublic(v) + return _u } // SetNillablePublic sets the "public" field if the given value is not nil. -func (ouo *OAuth2ClientUpdateOne) SetNillablePublic(b *bool) *OAuth2ClientUpdateOne { - if b != nil { - ouo.SetPublic(*b) +func (_u *OAuth2ClientUpdateOne) SetNillablePublic(v *bool) *OAuth2ClientUpdateOne { + if v != nil { + _u.SetPublic(*v) } - return ouo + return _u } // SetName sets the "name" field. -func (ouo *OAuth2ClientUpdateOne) SetName(s string) *OAuth2ClientUpdateOne { - ouo.mutation.SetName(s) - return ouo +func (_u *OAuth2ClientUpdateOne) SetName(v string) *OAuth2ClientUpdateOne { + _u.mutation.SetName(v) + return _u } // SetNillableName sets the "name" field if the given value is not nil. -func (ouo *OAuth2ClientUpdateOne) SetNillableName(s *string) *OAuth2ClientUpdateOne { - if s != nil { - ouo.SetName(*s) +func (_u *OAuth2ClientUpdateOne) SetNillableName(v *string) *OAuth2ClientUpdateOne { + if v != nil { + _u.SetName(*v) } - return ouo + return _u } // SetLogoURL sets the "logo_url" field. -func (ouo *OAuth2ClientUpdateOne) SetLogoURL(s string) *OAuth2ClientUpdateOne { - ouo.mutation.SetLogoURL(s) - return ouo +func (_u *OAuth2ClientUpdateOne) SetLogoURL(v string) *OAuth2ClientUpdateOne { + _u.mutation.SetLogoURL(v) + return _u } // SetNillableLogoURL sets the "logo_url" field if the given value is not nil. -func (ouo *OAuth2ClientUpdateOne) SetNillableLogoURL(s *string) *OAuth2ClientUpdateOne { - if s != nil { - ouo.SetLogoURL(*s) +func (_u *OAuth2ClientUpdateOne) SetNillableLogoURL(v *string) *OAuth2ClientUpdateOne { + if v != nil { + _u.SetLogoURL(*v) } - return ouo + return _u } // Mutation returns the OAuth2ClientMutation object of the builder. -func (ouo *OAuth2ClientUpdateOne) Mutation() *OAuth2ClientMutation { - return ouo.mutation +func (_u *OAuth2ClientUpdateOne) Mutation() *OAuth2ClientMutation { + return _u.mutation } // Where appends a list predicates to the OAuth2ClientUpdate builder. -func (ouo *OAuth2ClientUpdateOne) Where(ps ...predicate.OAuth2Client) *OAuth2ClientUpdateOne { - ouo.mutation.Where(ps...) - return ouo +func (_u *OAuth2ClientUpdateOne) Where(ps ...predicate.OAuth2Client) *OAuth2ClientUpdateOne { + _u.mutation.Where(ps...) + return _u } // Select allows selecting one or more fields (columns) of the returned entity. // The default is selecting all fields defined in the entity schema. -func (ouo *OAuth2ClientUpdateOne) Select(field string, fields ...string) *OAuth2ClientUpdateOne { - ouo.fields = append([]string{field}, fields...) - return ouo +func (_u *OAuth2ClientUpdateOne) Select(field string, fields ...string) *OAuth2ClientUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u } // Save executes the query and returns the updated OAuth2Client entity. -func (ouo *OAuth2ClientUpdateOne) Save(ctx context.Context) (*OAuth2Client, error) { - return withHooks(ctx, ouo.sqlSave, ouo.mutation, ouo.hooks) +func (_u *OAuth2ClientUpdateOne) Save(ctx context.Context) (*OAuth2Client, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) } // SaveX is like Save, but panics if an error occurs. -func (ouo *OAuth2ClientUpdateOne) SaveX(ctx context.Context) *OAuth2Client { - node, err := ouo.Save(ctx) +func (_u *OAuth2ClientUpdateOne) SaveX(ctx context.Context) *OAuth2Client { + node, err := _u.Save(ctx) if err != nil { panic(err) } @@ -363,31 +363,31 @@ func (ouo *OAuth2ClientUpdateOne) SaveX(ctx context.Context) *OAuth2Client { } // Exec executes the query on the entity. -func (ouo *OAuth2ClientUpdateOne) Exec(ctx context.Context) error { - _, err := ouo.Save(ctx) +func (_u *OAuth2ClientUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (ouo *OAuth2ClientUpdateOne) ExecX(ctx context.Context) { - if err := ouo.Exec(ctx); err != nil { +func (_u *OAuth2ClientUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { panic(err) } } // check runs all checks and user-defined validators on the builder. -func (ouo *OAuth2ClientUpdateOne) check() error { - if v, ok := ouo.mutation.Secret(); ok { +func (_u *OAuth2ClientUpdateOne) check() error { + if v, ok := _u.mutation.Secret(); ok { if err := oauth2client.SecretValidator(v); err != nil { return &ValidationError{Name: "secret", err: fmt.Errorf(`db: validator failed for field "OAuth2Client.secret": %w`, err)} } } - if v, ok := ouo.mutation.Name(); ok { + if v, ok := _u.mutation.Name(); ok { if err := oauth2client.NameValidator(v); err != nil { return &ValidationError{Name: "name", err: fmt.Errorf(`db: validator failed for field "OAuth2Client.name": %w`, err)} } } - if v, ok := ouo.mutation.LogoURL(); ok { + if v, ok := _u.mutation.LogoURL(); ok { if err := oauth2client.LogoURLValidator(v); err != nil { return &ValidationError{Name: "logo_url", err: fmt.Errorf(`db: validator failed for field "OAuth2Client.logo_url": %w`, err)} } @@ -395,17 +395,17 @@ func (ouo *OAuth2ClientUpdateOne) check() error { return nil } -func (ouo *OAuth2ClientUpdateOne) sqlSave(ctx context.Context) (_node *OAuth2Client, err error) { - if err := ouo.check(); err != nil { +func (_u *OAuth2ClientUpdateOne) sqlSave(ctx context.Context) (_node *OAuth2Client, err error) { + if err := _u.check(); err != nil { return _node, err } _spec := sqlgraph.NewUpdateSpec(oauth2client.Table, oauth2client.Columns, sqlgraph.NewFieldSpec(oauth2client.FieldID, field.TypeString)) - id, ok := ouo.mutation.ID() + id, ok := _u.mutation.ID() if !ok { return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "OAuth2Client.id" for update`)} } _spec.Node.ID.Value = id - if fields := ouo.fields; len(fields) > 0 { + if fields := _u.fields; len(fields) > 0 { _spec.Node.Columns = make([]string, 0, len(fields)) _spec.Node.Columns = append(_spec.Node.Columns, oauth2client.FieldID) for _, f := range fields { @@ -417,51 +417,51 @@ func (ouo *OAuth2ClientUpdateOne) sqlSave(ctx context.Context) (_node *OAuth2Cli } } } - if ps := ouo.mutation.predicates; len(ps) > 0 { + if ps := _u.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if value, ok := ouo.mutation.Secret(); ok { + if value, ok := _u.mutation.Secret(); ok { _spec.SetField(oauth2client.FieldSecret, field.TypeString, value) } - if value, ok := ouo.mutation.RedirectUris(); ok { + if value, ok := _u.mutation.RedirectUris(); ok { _spec.SetField(oauth2client.FieldRedirectUris, field.TypeJSON, value) } - if value, ok := ouo.mutation.AppendedRedirectUris(); ok { + if value, ok := _u.mutation.AppendedRedirectUris(); ok { _spec.AddModifier(func(u *sql.UpdateBuilder) { sqljson.Append(u, oauth2client.FieldRedirectUris, value) }) } - if ouo.mutation.RedirectUrisCleared() { + if _u.mutation.RedirectUrisCleared() { _spec.ClearField(oauth2client.FieldRedirectUris, field.TypeJSON) } - if value, ok := ouo.mutation.TrustedPeers(); ok { + if value, ok := _u.mutation.TrustedPeers(); ok { _spec.SetField(oauth2client.FieldTrustedPeers, field.TypeJSON, value) } - if value, ok := ouo.mutation.AppendedTrustedPeers(); ok { + if value, ok := _u.mutation.AppendedTrustedPeers(); ok { _spec.AddModifier(func(u *sql.UpdateBuilder) { sqljson.Append(u, oauth2client.FieldTrustedPeers, value) }) } - if ouo.mutation.TrustedPeersCleared() { + if _u.mutation.TrustedPeersCleared() { _spec.ClearField(oauth2client.FieldTrustedPeers, field.TypeJSON) } - if value, ok := ouo.mutation.Public(); ok { + if value, ok := _u.mutation.Public(); ok { _spec.SetField(oauth2client.FieldPublic, field.TypeBool, value) } - if value, ok := ouo.mutation.Name(); ok { + if value, ok := _u.mutation.Name(); ok { _spec.SetField(oauth2client.FieldName, field.TypeString, value) } - if value, ok := ouo.mutation.LogoURL(); ok { + if value, ok := _u.mutation.LogoURL(); ok { _spec.SetField(oauth2client.FieldLogoURL, field.TypeString, value) } - _node = &OAuth2Client{config: ouo.config} + _node = &OAuth2Client{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, ouo.driver, _spec); err != nil { + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{oauth2client.Label} } else if sqlgraph.IsConstraintError(err) { @@ -469,6 +469,6 @@ func (ouo *OAuth2ClientUpdateOne) sqlSave(ctx context.Context) (_node *OAuth2Cli } return nil, err } - ouo.mutation.done = true + _u.mutation.done = true return _node, nil } diff --git a/storage/ent/db/offlinesession.go b/storage/ent/db/offlinesession.go index 7adc3afca3..b19fd9c6d2 100644 --- a/storage/ent/db/offlinesession.go +++ b/storage/ent/db/offlinesession.go @@ -45,7 +45,7 @@ func (*OfflineSession) scanValues(columns []string) ([]any, error) { // assignValues assigns the values that were returned from sql.Rows (after scanning) // to the OfflineSession fields. -func (os *OfflineSession) assignValues(columns []string, values []any) error { +func (_m *OfflineSession) 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) } @@ -55,34 +55,34 @@ func (os *OfflineSession) assignValues(columns []string, values []any) error { if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field id", values[i]) } else if value.Valid { - os.ID = value.String + _m.ID = value.String } case offlinesession.FieldUserID: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field user_id", values[i]) } else if value.Valid { - os.UserID = value.String + _m.UserID = value.String } case offlinesession.FieldConnID: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field conn_id", values[i]) } else if value.Valid { - os.ConnID = value.String + _m.ConnID = value.String } case offlinesession.FieldRefresh: if value, ok := values[i].(*[]byte); !ok { return fmt.Errorf("unexpected type %T for field refresh", values[i]) } else if value != nil { - os.Refresh = *value + _m.Refresh = *value } case offlinesession.FieldConnectorData: if value, ok := values[i].(*[]byte); !ok { return fmt.Errorf("unexpected type %T for field connector_data", values[i]) } else if value != nil { - os.ConnectorData = value + _m.ConnectorData = value } default: - os.selectValues.Set(columns[i], values[i]) + _m.selectValues.Set(columns[i], values[i]) } } return nil @@ -90,43 +90,43 @@ func (os *OfflineSession) assignValues(columns []string, values []any) error { // Value returns the ent.Value that was dynamically selected and assigned to the OfflineSession. // This includes values selected through modifiers, order, etc. -func (os *OfflineSession) Value(name string) (ent.Value, error) { - return os.selectValues.Get(name) +func (_m *OfflineSession) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) } // Update returns a builder for updating this OfflineSession. // Note that you need to call OfflineSession.Unwrap() before calling this method if this OfflineSession // was returned from a transaction, and the transaction was committed or rolled back. -func (os *OfflineSession) Update() *OfflineSessionUpdateOne { - return NewOfflineSessionClient(os.config).UpdateOne(os) +func (_m *OfflineSession) Update() *OfflineSessionUpdateOne { + return NewOfflineSessionClient(_m.config).UpdateOne(_m) } // Unwrap unwraps the OfflineSession 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 (os *OfflineSession) Unwrap() *OfflineSession { - _tx, ok := os.config.driver.(*txDriver) +func (_m *OfflineSession) Unwrap() *OfflineSession { + _tx, ok := _m.config.driver.(*txDriver) if !ok { panic("db: OfflineSession is not a transactional entity") } - os.config.driver = _tx.drv - return os + _m.config.driver = _tx.drv + return _m } // String implements the fmt.Stringer. -func (os *OfflineSession) String() string { +func (_m *OfflineSession) String() string { var builder strings.Builder builder.WriteString("OfflineSession(") - builder.WriteString(fmt.Sprintf("id=%v, ", os.ID)) + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) builder.WriteString("user_id=") - builder.WriteString(os.UserID) + builder.WriteString(_m.UserID) builder.WriteString(", ") builder.WriteString("conn_id=") - builder.WriteString(os.ConnID) + builder.WriteString(_m.ConnID) builder.WriteString(", ") builder.WriteString("refresh=") - builder.WriteString(fmt.Sprintf("%v", os.Refresh)) + builder.WriteString(fmt.Sprintf("%v", _m.Refresh)) builder.WriteString(", ") - if v := os.ConnectorData; v != nil { + if v := _m.ConnectorData; v != nil { builder.WriteString("connector_data=") builder.WriteString(fmt.Sprintf("%v", *v)) } diff --git a/storage/ent/db/offlinesession_create.go b/storage/ent/db/offlinesession_create.go index b8250aac8d..a3ccbbf390 100644 --- a/storage/ent/db/offlinesession_create.go +++ b/storage/ent/db/offlinesession_create.go @@ -20,48 +20,48 @@ type OfflineSessionCreate struct { } // SetUserID sets the "user_id" field. -func (osc *OfflineSessionCreate) SetUserID(s string) *OfflineSessionCreate { - osc.mutation.SetUserID(s) - return osc +func (_c *OfflineSessionCreate) SetUserID(v string) *OfflineSessionCreate { + _c.mutation.SetUserID(v) + return _c } // SetConnID sets the "conn_id" field. -func (osc *OfflineSessionCreate) SetConnID(s string) *OfflineSessionCreate { - osc.mutation.SetConnID(s) - return osc +func (_c *OfflineSessionCreate) SetConnID(v string) *OfflineSessionCreate { + _c.mutation.SetConnID(v) + return _c } // SetRefresh sets the "refresh" field. -func (osc *OfflineSessionCreate) SetRefresh(b []byte) *OfflineSessionCreate { - osc.mutation.SetRefresh(b) - return osc +func (_c *OfflineSessionCreate) SetRefresh(v []byte) *OfflineSessionCreate { + _c.mutation.SetRefresh(v) + return _c } // SetConnectorData sets the "connector_data" field. -func (osc *OfflineSessionCreate) SetConnectorData(b []byte) *OfflineSessionCreate { - osc.mutation.SetConnectorData(b) - return osc +func (_c *OfflineSessionCreate) SetConnectorData(v []byte) *OfflineSessionCreate { + _c.mutation.SetConnectorData(v) + return _c } // SetID sets the "id" field. -func (osc *OfflineSessionCreate) SetID(s string) *OfflineSessionCreate { - osc.mutation.SetID(s) - return osc +func (_c *OfflineSessionCreate) SetID(v string) *OfflineSessionCreate { + _c.mutation.SetID(v) + return _c } // Mutation returns the OfflineSessionMutation object of the builder. -func (osc *OfflineSessionCreate) Mutation() *OfflineSessionMutation { - return osc.mutation +func (_c *OfflineSessionCreate) Mutation() *OfflineSessionMutation { + return _c.mutation } // Save creates the OfflineSession in the database. -func (osc *OfflineSessionCreate) Save(ctx context.Context) (*OfflineSession, error) { - return withHooks(ctx, osc.sqlSave, osc.mutation, osc.hooks) +func (_c *OfflineSessionCreate) Save(ctx context.Context) (*OfflineSession, error) { + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) } // SaveX calls Save and panics if Save returns an error. -func (osc *OfflineSessionCreate) SaveX(ctx context.Context) *OfflineSession { - v, err := osc.Save(ctx) +func (_c *OfflineSessionCreate) SaveX(ctx context.Context) *OfflineSession { + v, err := _c.Save(ctx) if err != nil { panic(err) } @@ -69,40 +69,40 @@ func (osc *OfflineSessionCreate) SaveX(ctx context.Context) *OfflineSession { } // Exec executes the query. -func (osc *OfflineSessionCreate) Exec(ctx context.Context) error { - _, err := osc.Save(ctx) +func (_c *OfflineSessionCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (osc *OfflineSessionCreate) ExecX(ctx context.Context) { - if err := osc.Exec(ctx); err != nil { +func (_c *OfflineSessionCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { panic(err) } } // check runs all checks and user-defined validators on the builder. -func (osc *OfflineSessionCreate) check() error { - if _, ok := osc.mutation.UserID(); !ok { +func (_c *OfflineSessionCreate) check() error { + if _, ok := _c.mutation.UserID(); !ok { return &ValidationError{Name: "user_id", err: errors.New(`db: missing required field "OfflineSession.user_id"`)} } - if v, ok := osc.mutation.UserID(); ok { + if v, ok := _c.mutation.UserID(); ok { if err := offlinesession.UserIDValidator(v); err != nil { return &ValidationError{Name: "user_id", err: fmt.Errorf(`db: validator failed for field "OfflineSession.user_id": %w`, err)} } } - if _, ok := osc.mutation.ConnID(); !ok { + if _, ok := _c.mutation.ConnID(); !ok { return &ValidationError{Name: "conn_id", err: errors.New(`db: missing required field "OfflineSession.conn_id"`)} } - if v, ok := osc.mutation.ConnID(); ok { + if v, ok := _c.mutation.ConnID(); ok { if err := offlinesession.ConnIDValidator(v); err != nil { return &ValidationError{Name: "conn_id", err: fmt.Errorf(`db: validator failed for field "OfflineSession.conn_id": %w`, err)} } } - if _, ok := osc.mutation.Refresh(); !ok { + if _, ok := _c.mutation.Refresh(); !ok { return &ValidationError{Name: "refresh", err: errors.New(`db: missing required field "OfflineSession.refresh"`)} } - if v, ok := osc.mutation.ID(); ok { + if v, ok := _c.mutation.ID(); ok { if err := offlinesession.IDValidator(v); err != nil { return &ValidationError{Name: "id", err: fmt.Errorf(`db: validator failed for field "OfflineSession.id": %w`, err)} } @@ -110,12 +110,12 @@ func (osc *OfflineSessionCreate) check() error { return nil } -func (osc *OfflineSessionCreate) sqlSave(ctx context.Context) (*OfflineSession, error) { - if err := osc.check(); err != nil { +func (_c *OfflineSessionCreate) sqlSave(ctx context.Context) (*OfflineSession, error) { + if err := _c.check(); err != nil { return nil, err } - _node, _spec := osc.createSpec() - if err := sqlgraph.CreateNode(ctx, osc.driver, _spec); err != nil { + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { if sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } @@ -128,33 +128,33 @@ func (osc *OfflineSessionCreate) sqlSave(ctx context.Context) (*OfflineSession, return nil, fmt.Errorf("unexpected OfflineSession.ID type: %T", _spec.ID.Value) } } - osc.mutation.id = &_node.ID - osc.mutation.done = true + _c.mutation.id = &_node.ID + _c.mutation.done = true return _node, nil } -func (osc *OfflineSessionCreate) createSpec() (*OfflineSession, *sqlgraph.CreateSpec) { +func (_c *OfflineSessionCreate) createSpec() (*OfflineSession, *sqlgraph.CreateSpec) { var ( - _node = &OfflineSession{config: osc.config} + _node = &OfflineSession{config: _c.config} _spec = sqlgraph.NewCreateSpec(offlinesession.Table, sqlgraph.NewFieldSpec(offlinesession.FieldID, field.TypeString)) ) - if id, ok := osc.mutation.ID(); ok { + if id, ok := _c.mutation.ID(); ok { _node.ID = id _spec.ID.Value = id } - if value, ok := osc.mutation.UserID(); ok { + if value, ok := _c.mutation.UserID(); ok { _spec.SetField(offlinesession.FieldUserID, field.TypeString, value) _node.UserID = value } - if value, ok := osc.mutation.ConnID(); ok { + if value, ok := _c.mutation.ConnID(); ok { _spec.SetField(offlinesession.FieldConnID, field.TypeString, value) _node.ConnID = value } - if value, ok := osc.mutation.Refresh(); ok { + if value, ok := _c.mutation.Refresh(); ok { _spec.SetField(offlinesession.FieldRefresh, field.TypeBytes, value) _node.Refresh = value } - if value, ok := osc.mutation.ConnectorData(); ok { + if value, ok := _c.mutation.ConnectorData(); ok { _spec.SetField(offlinesession.FieldConnectorData, field.TypeBytes, value) _node.ConnectorData = &value } @@ -169,16 +169,16 @@ type OfflineSessionCreateBulk struct { } // Save creates the OfflineSession entities in the database. -func (oscb *OfflineSessionCreateBulk) Save(ctx context.Context) ([]*OfflineSession, error) { - if oscb.err != nil { - return nil, oscb.err - } - specs := make([]*sqlgraph.CreateSpec, len(oscb.builders)) - nodes := make([]*OfflineSession, len(oscb.builders)) - mutators := make([]Mutator, len(oscb.builders)) - for i := range oscb.builders { +func (_c *OfflineSessionCreateBulk) Save(ctx context.Context) ([]*OfflineSession, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*OfflineSession, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { func(i int, root context.Context) { - builder := oscb.builders[i] + builder := _c.builders[i] var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { mutation, ok := m.(*OfflineSessionMutation) if !ok { @@ -191,11 +191,11 @@ func (oscb *OfflineSessionCreateBulk) Save(ctx context.Context) ([]*OfflineSessi var err error nodes[i], specs[i] = builder.createSpec() if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, oscb.builders[i+1].mutation) + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, oscb.driver, spec); err != nil { + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { if sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } @@ -215,7 +215,7 @@ func (oscb *OfflineSessionCreateBulk) Save(ctx context.Context) ([]*OfflineSessi }(i, ctx) } if len(mutators) > 0 { - if _, err := mutators[0].Mutate(ctx, oscb.builders[0].mutation); err != nil { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { return nil, err } } @@ -223,8 +223,8 @@ func (oscb *OfflineSessionCreateBulk) Save(ctx context.Context) ([]*OfflineSessi } // SaveX is like Save, but panics if an error occurs. -func (oscb *OfflineSessionCreateBulk) SaveX(ctx context.Context) []*OfflineSession { - v, err := oscb.Save(ctx) +func (_c *OfflineSessionCreateBulk) SaveX(ctx context.Context) []*OfflineSession { + v, err := _c.Save(ctx) if err != nil { panic(err) } @@ -232,14 +232,14 @@ func (oscb *OfflineSessionCreateBulk) SaveX(ctx context.Context) []*OfflineSessi } // Exec executes the query. -func (oscb *OfflineSessionCreateBulk) Exec(ctx context.Context) error { - _, err := oscb.Save(ctx) +func (_c *OfflineSessionCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (oscb *OfflineSessionCreateBulk) ExecX(ctx context.Context) { - if err := oscb.Exec(ctx); err != nil { +func (_c *OfflineSessionCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { panic(err) } } diff --git a/storage/ent/db/offlinesession_delete.go b/storage/ent/db/offlinesession_delete.go index 354d0e9197..ea03cd507e 100644 --- a/storage/ent/db/offlinesession_delete.go +++ b/storage/ent/db/offlinesession_delete.go @@ -20,56 +20,56 @@ type OfflineSessionDelete struct { } // Where appends a list predicates to the OfflineSessionDelete builder. -func (osd *OfflineSessionDelete) Where(ps ...predicate.OfflineSession) *OfflineSessionDelete { - osd.mutation.Where(ps...) - return osd +func (_d *OfflineSessionDelete) Where(ps ...predicate.OfflineSession) *OfflineSessionDelete { + _d.mutation.Where(ps...) + return _d } // Exec executes the deletion query and returns how many vertices were deleted. -func (osd *OfflineSessionDelete) Exec(ctx context.Context) (int, error) { - return withHooks(ctx, osd.sqlExec, osd.mutation, osd.hooks) +func (_d *OfflineSessionDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) } // ExecX is like Exec, but panics if an error occurs. -func (osd *OfflineSessionDelete) ExecX(ctx context.Context) int { - n, err := osd.Exec(ctx) +func (_d *OfflineSessionDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) if err != nil { panic(err) } return n } -func (osd *OfflineSessionDelete) sqlExec(ctx context.Context) (int, error) { +func (_d *OfflineSessionDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(offlinesession.Table, sqlgraph.NewFieldSpec(offlinesession.FieldID, field.TypeString)) - if ps := osd.mutation.predicates; len(ps) > 0 { + if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - affected, err := sqlgraph.DeleteNodes(ctx, osd.driver, _spec) + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) if err != nil && sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } - osd.mutation.done = true + _d.mutation.done = true return affected, err } // OfflineSessionDeleteOne is the builder for deleting a single OfflineSession entity. type OfflineSessionDeleteOne struct { - osd *OfflineSessionDelete + _d *OfflineSessionDelete } // Where appends a list predicates to the OfflineSessionDelete builder. -func (osdo *OfflineSessionDeleteOne) Where(ps ...predicate.OfflineSession) *OfflineSessionDeleteOne { - osdo.osd.mutation.Where(ps...) - return osdo +func (_d *OfflineSessionDeleteOne) Where(ps ...predicate.OfflineSession) *OfflineSessionDeleteOne { + _d._d.mutation.Where(ps...) + return _d } // Exec executes the deletion query. -func (osdo *OfflineSessionDeleteOne) Exec(ctx context.Context) error { - n, err := osdo.osd.Exec(ctx) +func (_d *OfflineSessionDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) switch { case err != nil: return err @@ -81,8 +81,8 @@ func (osdo *OfflineSessionDeleteOne) Exec(ctx context.Context) error { } // ExecX is like Exec, but panics if an error occurs. -func (osdo *OfflineSessionDeleteOne) ExecX(ctx context.Context) { - if err := osdo.Exec(ctx); err != nil { +func (_d *OfflineSessionDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { panic(err) } } diff --git a/storage/ent/db/offlinesession_query.go b/storage/ent/db/offlinesession_query.go index 170bcad3ee..22723620d4 100644 --- a/storage/ent/db/offlinesession_query.go +++ b/storage/ent/db/offlinesession_query.go @@ -28,40 +28,40 @@ type OfflineSessionQuery struct { } // Where adds a new predicate for the OfflineSessionQuery builder. -func (osq *OfflineSessionQuery) Where(ps ...predicate.OfflineSession) *OfflineSessionQuery { - osq.predicates = append(osq.predicates, ps...) - return osq +func (_q *OfflineSessionQuery) Where(ps ...predicate.OfflineSession) *OfflineSessionQuery { + _q.predicates = append(_q.predicates, ps...) + return _q } // Limit the number of records to be returned by this query. -func (osq *OfflineSessionQuery) Limit(limit int) *OfflineSessionQuery { - osq.ctx.Limit = &limit - return osq +func (_q *OfflineSessionQuery) Limit(limit int) *OfflineSessionQuery { + _q.ctx.Limit = &limit + return _q } // Offset to start from. -func (osq *OfflineSessionQuery) Offset(offset int) *OfflineSessionQuery { - osq.ctx.Offset = &offset - return osq +func (_q *OfflineSessionQuery) Offset(offset int) *OfflineSessionQuery { + _q.ctx.Offset = &offset + return _q } // Unique configures the query builder to filter duplicate records on query. // By default, unique is set to true, and can be disabled using this method. -func (osq *OfflineSessionQuery) Unique(unique bool) *OfflineSessionQuery { - osq.ctx.Unique = &unique - return osq +func (_q *OfflineSessionQuery) Unique(unique bool) *OfflineSessionQuery { + _q.ctx.Unique = &unique + return _q } // Order specifies how the records should be ordered. -func (osq *OfflineSessionQuery) Order(o ...offlinesession.OrderOption) *OfflineSessionQuery { - osq.order = append(osq.order, o...) - return osq +func (_q *OfflineSessionQuery) Order(o ...offlinesession.OrderOption) *OfflineSessionQuery { + _q.order = append(_q.order, o...) + return _q } // First returns the first OfflineSession entity from the query. // Returns a *NotFoundError when no OfflineSession was found. -func (osq *OfflineSessionQuery) First(ctx context.Context) (*OfflineSession, error) { - nodes, err := osq.Limit(1).All(setContextOp(ctx, osq.ctx, ent.OpQueryFirst)) +func (_q *OfflineSessionQuery) First(ctx context.Context) (*OfflineSession, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) if err != nil { return nil, err } @@ -72,8 +72,8 @@ func (osq *OfflineSessionQuery) First(ctx context.Context) (*OfflineSession, err } // FirstX is like First, but panics if an error occurs. -func (osq *OfflineSessionQuery) FirstX(ctx context.Context) *OfflineSession { - node, err := osq.First(ctx) +func (_q *OfflineSessionQuery) FirstX(ctx context.Context) *OfflineSession { + node, err := _q.First(ctx) if err != nil && !IsNotFound(err) { panic(err) } @@ -82,9 +82,9 @@ func (osq *OfflineSessionQuery) FirstX(ctx context.Context) *OfflineSession { // FirstID returns the first OfflineSession ID from the query. // Returns a *NotFoundError when no OfflineSession ID was found. -func (osq *OfflineSessionQuery) FirstID(ctx context.Context) (id string, err error) { +func (_q *OfflineSessionQuery) FirstID(ctx context.Context) (id string, err error) { var ids []string - if ids, err = osq.Limit(1).IDs(setContextOp(ctx, osq.ctx, ent.OpQueryFirstID)); err != nil { + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { return } if len(ids) == 0 { @@ -95,8 +95,8 @@ func (osq *OfflineSessionQuery) FirstID(ctx context.Context) (id string, err err } // FirstIDX is like FirstID, but panics if an error occurs. -func (osq *OfflineSessionQuery) FirstIDX(ctx context.Context) string { - id, err := osq.FirstID(ctx) +func (_q *OfflineSessionQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) if err != nil && !IsNotFound(err) { panic(err) } @@ -106,8 +106,8 @@ func (osq *OfflineSessionQuery) FirstIDX(ctx context.Context) string { // Only returns a single OfflineSession entity found by the query, ensuring it only returns one. // Returns a *NotSingularError when more than one OfflineSession entity is found. // Returns a *NotFoundError when no OfflineSession entities are found. -func (osq *OfflineSessionQuery) Only(ctx context.Context) (*OfflineSession, error) { - nodes, err := osq.Limit(2).All(setContextOp(ctx, osq.ctx, ent.OpQueryOnly)) +func (_q *OfflineSessionQuery) Only(ctx context.Context) (*OfflineSession, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) if err != nil { return nil, err } @@ -122,8 +122,8 @@ func (osq *OfflineSessionQuery) Only(ctx context.Context) (*OfflineSession, erro } // OnlyX is like Only, but panics if an error occurs. -func (osq *OfflineSessionQuery) OnlyX(ctx context.Context) *OfflineSession { - node, err := osq.Only(ctx) +func (_q *OfflineSessionQuery) OnlyX(ctx context.Context) *OfflineSession { + node, err := _q.Only(ctx) if err != nil { panic(err) } @@ -133,9 +133,9 @@ func (osq *OfflineSessionQuery) OnlyX(ctx context.Context) *OfflineSession { // OnlyID is like Only, but returns the only OfflineSession ID in the query. // Returns a *NotSingularError when more than one OfflineSession ID is found. // Returns a *NotFoundError when no entities are found. -func (osq *OfflineSessionQuery) OnlyID(ctx context.Context) (id string, err error) { +func (_q *OfflineSessionQuery) OnlyID(ctx context.Context) (id string, err error) { var ids []string - if ids, err = osq.Limit(2).IDs(setContextOp(ctx, osq.ctx, ent.OpQueryOnlyID)); err != nil { + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { return } switch len(ids) { @@ -150,8 +150,8 @@ func (osq *OfflineSessionQuery) OnlyID(ctx context.Context) (id string, err erro } // OnlyIDX is like OnlyID, but panics if an error occurs. -func (osq *OfflineSessionQuery) OnlyIDX(ctx context.Context) string { - id, err := osq.OnlyID(ctx) +func (_q *OfflineSessionQuery) OnlyIDX(ctx context.Context) string { + id, err := _q.OnlyID(ctx) if err != nil { panic(err) } @@ -159,18 +159,18 @@ func (osq *OfflineSessionQuery) OnlyIDX(ctx context.Context) string { } // All executes the query and returns a list of OfflineSessions. -func (osq *OfflineSessionQuery) All(ctx context.Context) ([]*OfflineSession, error) { - ctx = setContextOp(ctx, osq.ctx, ent.OpQueryAll) - if err := osq.prepareQuery(ctx); err != nil { +func (_q *OfflineSessionQuery) All(ctx context.Context) ([]*OfflineSession, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { return nil, err } qr := querierAll[[]*OfflineSession, *OfflineSessionQuery]() - return withInterceptors[[]*OfflineSession](ctx, osq, qr, osq.inters) + return withInterceptors[[]*OfflineSession](ctx, _q, qr, _q.inters) } // AllX is like All, but panics if an error occurs. -func (osq *OfflineSessionQuery) AllX(ctx context.Context) []*OfflineSession { - nodes, err := osq.All(ctx) +func (_q *OfflineSessionQuery) AllX(ctx context.Context) []*OfflineSession { + nodes, err := _q.All(ctx) if err != nil { panic(err) } @@ -178,20 +178,20 @@ func (osq *OfflineSessionQuery) AllX(ctx context.Context) []*OfflineSession { } // IDs executes the query and returns a list of OfflineSession IDs. -func (osq *OfflineSessionQuery) IDs(ctx context.Context) (ids []string, err error) { - if osq.ctx.Unique == nil && osq.path != nil { - osq.Unique(true) +func (_q *OfflineSessionQuery) IDs(ctx context.Context) (ids []string, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) } - ctx = setContextOp(ctx, osq.ctx, ent.OpQueryIDs) - if err = osq.Select(offlinesession.FieldID).Scan(ctx, &ids); err != nil { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(offlinesession.FieldID).Scan(ctx, &ids); err != nil { return nil, err } return ids, nil } // IDsX is like IDs, but panics if an error occurs. -func (osq *OfflineSessionQuery) IDsX(ctx context.Context) []string { - ids, err := osq.IDs(ctx) +func (_q *OfflineSessionQuery) IDsX(ctx context.Context) []string { + ids, err := _q.IDs(ctx) if err != nil { panic(err) } @@ -199,17 +199,17 @@ func (osq *OfflineSessionQuery) IDsX(ctx context.Context) []string { } // Count returns the count of the given query. -func (osq *OfflineSessionQuery) Count(ctx context.Context) (int, error) { - ctx = setContextOp(ctx, osq.ctx, ent.OpQueryCount) - if err := osq.prepareQuery(ctx); err != nil { +func (_q *OfflineSessionQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { return 0, err } - return withInterceptors[int](ctx, osq, querierCount[*OfflineSessionQuery](), osq.inters) + return withInterceptors[int](ctx, _q, querierCount[*OfflineSessionQuery](), _q.inters) } // CountX is like Count, but panics if an error occurs. -func (osq *OfflineSessionQuery) CountX(ctx context.Context) int { - count, err := osq.Count(ctx) +func (_q *OfflineSessionQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) if err != nil { panic(err) } @@ -217,9 +217,9 @@ func (osq *OfflineSessionQuery) CountX(ctx context.Context) int { } // Exist returns true if the query has elements in the graph. -func (osq *OfflineSessionQuery) Exist(ctx context.Context) (bool, error) { - ctx = setContextOp(ctx, osq.ctx, ent.OpQueryExist) - switch _, err := osq.FirstID(ctx); { +func (_q *OfflineSessionQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { case IsNotFound(err): return false, nil case err != nil: @@ -230,8 +230,8 @@ func (osq *OfflineSessionQuery) Exist(ctx context.Context) (bool, error) { } // ExistX is like Exist, but panics if an error occurs. -func (osq *OfflineSessionQuery) ExistX(ctx context.Context) bool { - exist, err := osq.Exist(ctx) +func (_q *OfflineSessionQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) if err != nil { panic(err) } @@ -240,19 +240,19 @@ func (osq *OfflineSessionQuery) ExistX(ctx context.Context) bool { // Clone returns a duplicate of the OfflineSessionQuery builder, including all associated steps. It can be // used to prepare common query builders and use them differently after the clone is made. -func (osq *OfflineSessionQuery) Clone() *OfflineSessionQuery { - if osq == nil { +func (_q *OfflineSessionQuery) Clone() *OfflineSessionQuery { + if _q == nil { return nil } return &OfflineSessionQuery{ - config: osq.config, - ctx: osq.ctx.Clone(), - order: append([]offlinesession.OrderOption{}, osq.order...), - inters: append([]Interceptor{}, osq.inters...), - predicates: append([]predicate.OfflineSession{}, osq.predicates...), + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]offlinesession.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.OfflineSession{}, _q.predicates...), // clone intermediate query. - sql: osq.sql.Clone(), - path: osq.path, + sql: _q.sql.Clone(), + path: _q.path, } } @@ -270,10 +270,10 @@ func (osq *OfflineSessionQuery) Clone() *OfflineSessionQuery { // GroupBy(offlinesession.FieldUserID). // Aggregate(db.Count()). // Scan(ctx, &v) -func (osq *OfflineSessionQuery) GroupBy(field string, fields ...string) *OfflineSessionGroupBy { - osq.ctx.Fields = append([]string{field}, fields...) - grbuild := &OfflineSessionGroupBy{build: osq} - grbuild.flds = &osq.ctx.Fields +func (_q *OfflineSessionQuery) GroupBy(field string, fields ...string) *OfflineSessionGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &OfflineSessionGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields grbuild.label = offlinesession.Label grbuild.scan = grbuild.Scan return grbuild @@ -291,62 +291,62 @@ func (osq *OfflineSessionQuery) GroupBy(field string, fields ...string) *Offline // client.OfflineSession.Query(). // Select(offlinesession.FieldUserID). // Scan(ctx, &v) -func (osq *OfflineSessionQuery) Select(fields ...string) *OfflineSessionSelect { - osq.ctx.Fields = append(osq.ctx.Fields, fields...) - sbuild := &OfflineSessionSelect{OfflineSessionQuery: osq} +func (_q *OfflineSessionQuery) Select(fields ...string) *OfflineSessionSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &OfflineSessionSelect{OfflineSessionQuery: _q} sbuild.label = offlinesession.Label - sbuild.flds, sbuild.scan = &osq.ctx.Fields, sbuild.Scan + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan return sbuild } // Aggregate returns a OfflineSessionSelect configured with the given aggregations. -func (osq *OfflineSessionQuery) Aggregate(fns ...AggregateFunc) *OfflineSessionSelect { - return osq.Select().Aggregate(fns...) +func (_q *OfflineSessionQuery) Aggregate(fns ...AggregateFunc) *OfflineSessionSelect { + return _q.Select().Aggregate(fns...) } -func (osq *OfflineSessionQuery) prepareQuery(ctx context.Context) error { - for _, inter := range osq.inters { +func (_q *OfflineSessionQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { if inter == nil { return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)") } if trv, ok := inter.(Traverser); ok { - if err := trv.Traverse(ctx, osq); err != nil { + if err := trv.Traverse(ctx, _q); err != nil { return err } } } - for _, f := range osq.ctx.Fields { + for _, f := range _q.ctx.Fields { if !offlinesession.ValidColumn(f) { return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} } } - if osq.path != nil { - prev, err := osq.path(ctx) + if _q.path != nil { + prev, err := _q.path(ctx) if err != nil { return err } - osq.sql = prev + _q.sql = prev } return nil } -func (osq *OfflineSessionQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*OfflineSession, error) { +func (_q *OfflineSessionQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*OfflineSession, error) { var ( nodes = []*OfflineSession{} - _spec = osq.querySpec() + _spec = _q.querySpec() ) _spec.ScanValues = func(columns []string) ([]any, error) { return (*OfflineSession).scanValues(nil, columns) } _spec.Assign = func(columns []string, values []any) error { - node := &OfflineSession{config: osq.config} + node := &OfflineSession{config: _q.config} nodes = append(nodes, node) return node.assignValues(columns, values) } for i := range hooks { hooks[i](ctx, _spec) } - if err := sqlgraph.QueryNodes(ctx, osq.driver, _spec); err != nil { + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { return nil, err } if len(nodes) == 0 { @@ -355,24 +355,24 @@ func (osq *OfflineSessionQuery) sqlAll(ctx context.Context, hooks ...queryHook) return nodes, nil } -func (osq *OfflineSessionQuery) sqlCount(ctx context.Context) (int, error) { - _spec := osq.querySpec() - _spec.Node.Columns = osq.ctx.Fields - if len(osq.ctx.Fields) > 0 { - _spec.Unique = osq.ctx.Unique != nil && *osq.ctx.Unique +func (_q *OfflineSessionQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique } - return sqlgraph.CountNodes(ctx, osq.driver, _spec) + return sqlgraph.CountNodes(ctx, _q.driver, _spec) } -func (osq *OfflineSessionQuery) querySpec() *sqlgraph.QuerySpec { +func (_q *OfflineSessionQuery) querySpec() *sqlgraph.QuerySpec { _spec := sqlgraph.NewQuerySpec(offlinesession.Table, offlinesession.Columns, sqlgraph.NewFieldSpec(offlinesession.FieldID, field.TypeString)) - _spec.From = osq.sql - if unique := osq.ctx.Unique; unique != nil { + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { _spec.Unique = *unique - } else if osq.path != nil { + } else if _q.path != nil { _spec.Unique = true } - if fields := osq.ctx.Fields; len(fields) > 0 { + if fields := _q.ctx.Fields; len(fields) > 0 { _spec.Node.Columns = make([]string, 0, len(fields)) _spec.Node.Columns = append(_spec.Node.Columns, offlinesession.FieldID) for i := range fields { @@ -381,20 +381,20 @@ func (osq *OfflineSessionQuery) querySpec() *sqlgraph.QuerySpec { } } } - if ps := osq.predicates; len(ps) > 0 { + if ps := _q.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if limit := osq.ctx.Limit; limit != nil { + if limit := _q.ctx.Limit; limit != nil { _spec.Limit = *limit } - if offset := osq.ctx.Offset; offset != nil { + if offset := _q.ctx.Offset; offset != nil { _spec.Offset = *offset } - if ps := osq.order; len(ps) > 0 { + if ps := _q.order; len(ps) > 0 { _spec.Order = func(selector *sql.Selector) { for i := range ps { ps[i](selector) @@ -404,33 +404,33 @@ func (osq *OfflineSessionQuery) querySpec() *sqlgraph.QuerySpec { return _spec } -func (osq *OfflineSessionQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(osq.driver.Dialect()) +func (_q *OfflineSessionQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) t1 := builder.Table(offlinesession.Table) - columns := osq.ctx.Fields + columns := _q.ctx.Fields if len(columns) == 0 { columns = offlinesession.Columns } selector := builder.Select(t1.Columns(columns...)...).From(t1) - if osq.sql != nil { - selector = osq.sql + if _q.sql != nil { + selector = _q.sql selector.Select(selector.Columns(columns...)...) } - if osq.ctx.Unique != nil && *osq.ctx.Unique { + if _q.ctx.Unique != nil && *_q.ctx.Unique { selector.Distinct() } - for _, p := range osq.predicates { + for _, p := range _q.predicates { p(selector) } - for _, p := range osq.order { + for _, p := range _q.order { p(selector) } - if offset := osq.ctx.Offset; offset != nil { + if offset := _q.ctx.Offset; offset != nil { // limit is mandatory for offset clause. We start // with default value, and override it below if needed. selector.Offset(*offset).Limit(math.MaxInt32) } - if limit := osq.ctx.Limit; limit != nil { + if limit := _q.ctx.Limit; limit != nil { selector.Limit(*limit) } return selector @@ -443,41 +443,41 @@ type OfflineSessionGroupBy struct { } // Aggregate adds the given aggregation functions to the group-by query. -func (osgb *OfflineSessionGroupBy) Aggregate(fns ...AggregateFunc) *OfflineSessionGroupBy { - osgb.fns = append(osgb.fns, fns...) - return osgb +func (_g *OfflineSessionGroupBy) Aggregate(fns ...AggregateFunc) *OfflineSessionGroupBy { + _g.fns = append(_g.fns, fns...) + return _g } // Scan applies the selector query and scans the result into the given value. -func (osgb *OfflineSessionGroupBy) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, osgb.build.ctx, ent.OpQueryGroupBy) - if err := osgb.build.prepareQuery(ctx); err != nil { +func (_g *OfflineSessionGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { return err } - return scanWithInterceptors[*OfflineSessionQuery, *OfflineSessionGroupBy](ctx, osgb.build, osgb, osgb.build.inters, v) + return scanWithInterceptors[*OfflineSessionQuery, *OfflineSessionGroupBy](ctx, _g.build, _g, _g.build.inters, v) } -func (osgb *OfflineSessionGroupBy) sqlScan(ctx context.Context, root *OfflineSessionQuery, v any) error { +func (_g *OfflineSessionGroupBy) sqlScan(ctx context.Context, root *OfflineSessionQuery, v any) error { selector := root.sqlQuery(ctx).Select() - aggregation := make([]string, 0, len(osgb.fns)) - for _, fn := range osgb.fns { + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { aggregation = append(aggregation, fn(selector)) } if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(*osgb.flds)+len(osgb.fns)) - for _, f := range *osgb.flds { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { columns = append(columns, selector.C(f)) } columns = append(columns, aggregation...) selector.Select(columns...) } - selector.GroupBy(selector.Columns(*osgb.flds...)...) + selector.GroupBy(selector.Columns(*_g.flds...)...) if err := selector.Err(); err != nil { return err } rows := &sql.Rows{} query, args := selector.Query() - if err := osgb.build.driver.Query(ctx, query, args, rows); err != nil { + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() @@ -491,27 +491,27 @@ type OfflineSessionSelect struct { } // Aggregate adds the given aggregation functions to the selector query. -func (oss *OfflineSessionSelect) Aggregate(fns ...AggregateFunc) *OfflineSessionSelect { - oss.fns = append(oss.fns, fns...) - return oss +func (_s *OfflineSessionSelect) Aggregate(fns ...AggregateFunc) *OfflineSessionSelect { + _s.fns = append(_s.fns, fns...) + return _s } // Scan applies the selector query and scans the result into the given value. -func (oss *OfflineSessionSelect) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, oss.ctx, ent.OpQuerySelect) - if err := oss.prepareQuery(ctx); err != nil { +func (_s *OfflineSessionSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { return err } - return scanWithInterceptors[*OfflineSessionQuery, *OfflineSessionSelect](ctx, oss.OfflineSessionQuery, oss, oss.inters, v) + return scanWithInterceptors[*OfflineSessionQuery, *OfflineSessionSelect](ctx, _s.OfflineSessionQuery, _s, _s.inters, v) } -func (oss *OfflineSessionSelect) sqlScan(ctx context.Context, root *OfflineSessionQuery, v any) error { +func (_s *OfflineSessionSelect) sqlScan(ctx context.Context, root *OfflineSessionQuery, v any) error { selector := root.sqlQuery(ctx) - aggregation := make([]string, 0, len(oss.fns)) - for _, fn := range oss.fns { + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { aggregation = append(aggregation, fn(selector)) } - switch n := len(*oss.selector.flds); { + switch n := len(*_s.selector.flds); { case n == 0 && len(aggregation) > 0: selector.Select(aggregation...) case n != 0 && len(aggregation) > 0: @@ -519,7 +519,7 @@ func (oss *OfflineSessionSelect) sqlScan(ctx context.Context, root *OfflineSessi } rows := &sql.Rows{} query, args := selector.Query() - if err := oss.driver.Query(ctx, query, args, rows); err != nil { + if err := _s.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() diff --git a/storage/ent/db/offlinesession_update.go b/storage/ent/db/offlinesession_update.go index d912acf1a9..8eca1b76f0 100644 --- a/storage/ent/db/offlinesession_update.go +++ b/storage/ent/db/offlinesession_update.go @@ -22,70 +22,70 @@ type OfflineSessionUpdate struct { } // Where appends a list predicates to the OfflineSessionUpdate builder. -func (osu *OfflineSessionUpdate) Where(ps ...predicate.OfflineSession) *OfflineSessionUpdate { - osu.mutation.Where(ps...) - return osu +func (_u *OfflineSessionUpdate) Where(ps ...predicate.OfflineSession) *OfflineSessionUpdate { + _u.mutation.Where(ps...) + return _u } // SetUserID sets the "user_id" field. -func (osu *OfflineSessionUpdate) SetUserID(s string) *OfflineSessionUpdate { - osu.mutation.SetUserID(s) - return osu +func (_u *OfflineSessionUpdate) SetUserID(v string) *OfflineSessionUpdate { + _u.mutation.SetUserID(v) + return _u } // SetNillableUserID sets the "user_id" field if the given value is not nil. -func (osu *OfflineSessionUpdate) SetNillableUserID(s *string) *OfflineSessionUpdate { - if s != nil { - osu.SetUserID(*s) +func (_u *OfflineSessionUpdate) SetNillableUserID(v *string) *OfflineSessionUpdate { + if v != nil { + _u.SetUserID(*v) } - return osu + return _u } // SetConnID sets the "conn_id" field. -func (osu *OfflineSessionUpdate) SetConnID(s string) *OfflineSessionUpdate { - osu.mutation.SetConnID(s) - return osu +func (_u *OfflineSessionUpdate) SetConnID(v string) *OfflineSessionUpdate { + _u.mutation.SetConnID(v) + return _u } // SetNillableConnID sets the "conn_id" field if the given value is not nil. -func (osu *OfflineSessionUpdate) SetNillableConnID(s *string) *OfflineSessionUpdate { - if s != nil { - osu.SetConnID(*s) +func (_u *OfflineSessionUpdate) SetNillableConnID(v *string) *OfflineSessionUpdate { + if v != nil { + _u.SetConnID(*v) } - return osu + return _u } // SetRefresh sets the "refresh" field. -func (osu *OfflineSessionUpdate) SetRefresh(b []byte) *OfflineSessionUpdate { - osu.mutation.SetRefresh(b) - return osu +func (_u *OfflineSessionUpdate) SetRefresh(v []byte) *OfflineSessionUpdate { + _u.mutation.SetRefresh(v) + return _u } // SetConnectorData sets the "connector_data" field. -func (osu *OfflineSessionUpdate) SetConnectorData(b []byte) *OfflineSessionUpdate { - osu.mutation.SetConnectorData(b) - return osu +func (_u *OfflineSessionUpdate) SetConnectorData(v []byte) *OfflineSessionUpdate { + _u.mutation.SetConnectorData(v) + return _u } // ClearConnectorData clears the value of the "connector_data" field. -func (osu *OfflineSessionUpdate) ClearConnectorData() *OfflineSessionUpdate { - osu.mutation.ClearConnectorData() - return osu +func (_u *OfflineSessionUpdate) ClearConnectorData() *OfflineSessionUpdate { + _u.mutation.ClearConnectorData() + return _u } // Mutation returns the OfflineSessionMutation object of the builder. -func (osu *OfflineSessionUpdate) Mutation() *OfflineSessionMutation { - return osu.mutation +func (_u *OfflineSessionUpdate) Mutation() *OfflineSessionMutation { + return _u.mutation } // Save executes the query and returns the number of nodes affected by the update operation. -func (osu *OfflineSessionUpdate) Save(ctx context.Context) (int, error) { - return withHooks(ctx, osu.sqlSave, osu.mutation, osu.hooks) +func (_u *OfflineSessionUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) } // SaveX is like Save, but panics if an error occurs. -func (osu *OfflineSessionUpdate) SaveX(ctx context.Context) int { - affected, err := osu.Save(ctx) +func (_u *OfflineSessionUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) if err != nil { panic(err) } @@ -93,26 +93,26 @@ func (osu *OfflineSessionUpdate) SaveX(ctx context.Context) int { } // Exec executes the query. -func (osu *OfflineSessionUpdate) Exec(ctx context.Context) error { - _, err := osu.Save(ctx) +func (_u *OfflineSessionUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (osu *OfflineSessionUpdate) ExecX(ctx context.Context) { - if err := osu.Exec(ctx); err != nil { +func (_u *OfflineSessionUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { panic(err) } } // check runs all checks and user-defined validators on the builder. -func (osu *OfflineSessionUpdate) check() error { - if v, ok := osu.mutation.UserID(); ok { +func (_u *OfflineSessionUpdate) check() error { + if v, ok := _u.mutation.UserID(); ok { if err := offlinesession.UserIDValidator(v); err != nil { return &ValidationError{Name: "user_id", err: fmt.Errorf(`db: validator failed for field "OfflineSession.user_id": %w`, err)} } } - if v, ok := osu.mutation.ConnID(); ok { + if v, ok := _u.mutation.ConnID(); ok { if err := offlinesession.ConnIDValidator(v); err != nil { return &ValidationError{Name: "conn_id", err: fmt.Errorf(`db: validator failed for field "OfflineSession.conn_id": %w`, err)} } @@ -120,34 +120,34 @@ func (osu *OfflineSessionUpdate) check() error { return nil } -func (osu *OfflineSessionUpdate) sqlSave(ctx context.Context) (n int, err error) { - if err := osu.check(); err != nil { - return n, err +func (_u *OfflineSessionUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err } _spec := sqlgraph.NewUpdateSpec(offlinesession.Table, offlinesession.Columns, sqlgraph.NewFieldSpec(offlinesession.FieldID, field.TypeString)) - if ps := osu.mutation.predicates; len(ps) > 0 { + if ps := _u.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if value, ok := osu.mutation.UserID(); ok { + if value, ok := _u.mutation.UserID(); ok { _spec.SetField(offlinesession.FieldUserID, field.TypeString, value) } - if value, ok := osu.mutation.ConnID(); ok { + if value, ok := _u.mutation.ConnID(); ok { _spec.SetField(offlinesession.FieldConnID, field.TypeString, value) } - if value, ok := osu.mutation.Refresh(); ok { + if value, ok := _u.mutation.Refresh(); ok { _spec.SetField(offlinesession.FieldRefresh, field.TypeBytes, value) } - if value, ok := osu.mutation.ConnectorData(); ok { + if value, ok := _u.mutation.ConnectorData(); ok { _spec.SetField(offlinesession.FieldConnectorData, field.TypeBytes, value) } - if osu.mutation.ConnectorDataCleared() { + if _u.mutation.ConnectorDataCleared() { _spec.ClearField(offlinesession.FieldConnectorData, field.TypeBytes) } - if n, err = sqlgraph.UpdateNodes(ctx, osu.driver, _spec); err != nil { + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{offlinesession.Label} } else if sqlgraph.IsConstraintError(err) { @@ -155,8 +155,8 @@ func (osu *OfflineSessionUpdate) sqlSave(ctx context.Context) (n int, err error) } return 0, err } - osu.mutation.done = true - return n, nil + _u.mutation.done = true + return _node, nil } // OfflineSessionUpdateOne is the builder for updating a single OfflineSession entity. @@ -168,77 +168,77 @@ type OfflineSessionUpdateOne struct { } // SetUserID sets the "user_id" field. -func (osuo *OfflineSessionUpdateOne) SetUserID(s string) *OfflineSessionUpdateOne { - osuo.mutation.SetUserID(s) - return osuo +func (_u *OfflineSessionUpdateOne) SetUserID(v string) *OfflineSessionUpdateOne { + _u.mutation.SetUserID(v) + return _u } // SetNillableUserID sets the "user_id" field if the given value is not nil. -func (osuo *OfflineSessionUpdateOne) SetNillableUserID(s *string) *OfflineSessionUpdateOne { - if s != nil { - osuo.SetUserID(*s) +func (_u *OfflineSessionUpdateOne) SetNillableUserID(v *string) *OfflineSessionUpdateOne { + if v != nil { + _u.SetUserID(*v) } - return osuo + return _u } // SetConnID sets the "conn_id" field. -func (osuo *OfflineSessionUpdateOne) SetConnID(s string) *OfflineSessionUpdateOne { - osuo.mutation.SetConnID(s) - return osuo +func (_u *OfflineSessionUpdateOne) SetConnID(v string) *OfflineSessionUpdateOne { + _u.mutation.SetConnID(v) + return _u } // SetNillableConnID sets the "conn_id" field if the given value is not nil. -func (osuo *OfflineSessionUpdateOne) SetNillableConnID(s *string) *OfflineSessionUpdateOne { - if s != nil { - osuo.SetConnID(*s) +func (_u *OfflineSessionUpdateOne) SetNillableConnID(v *string) *OfflineSessionUpdateOne { + if v != nil { + _u.SetConnID(*v) } - return osuo + return _u } // SetRefresh sets the "refresh" field. -func (osuo *OfflineSessionUpdateOne) SetRefresh(b []byte) *OfflineSessionUpdateOne { - osuo.mutation.SetRefresh(b) - return osuo +func (_u *OfflineSessionUpdateOne) SetRefresh(v []byte) *OfflineSessionUpdateOne { + _u.mutation.SetRefresh(v) + return _u } // SetConnectorData sets the "connector_data" field. -func (osuo *OfflineSessionUpdateOne) SetConnectorData(b []byte) *OfflineSessionUpdateOne { - osuo.mutation.SetConnectorData(b) - return osuo +func (_u *OfflineSessionUpdateOne) SetConnectorData(v []byte) *OfflineSessionUpdateOne { + _u.mutation.SetConnectorData(v) + return _u } // ClearConnectorData clears the value of the "connector_data" field. -func (osuo *OfflineSessionUpdateOne) ClearConnectorData() *OfflineSessionUpdateOne { - osuo.mutation.ClearConnectorData() - return osuo +func (_u *OfflineSessionUpdateOne) ClearConnectorData() *OfflineSessionUpdateOne { + _u.mutation.ClearConnectorData() + return _u } // Mutation returns the OfflineSessionMutation object of the builder. -func (osuo *OfflineSessionUpdateOne) Mutation() *OfflineSessionMutation { - return osuo.mutation +func (_u *OfflineSessionUpdateOne) Mutation() *OfflineSessionMutation { + return _u.mutation } // Where appends a list predicates to the OfflineSessionUpdate builder. -func (osuo *OfflineSessionUpdateOne) Where(ps ...predicate.OfflineSession) *OfflineSessionUpdateOne { - osuo.mutation.Where(ps...) - return osuo +func (_u *OfflineSessionUpdateOne) Where(ps ...predicate.OfflineSession) *OfflineSessionUpdateOne { + _u.mutation.Where(ps...) + return _u } // Select allows selecting one or more fields (columns) of the returned entity. // The default is selecting all fields defined in the entity schema. -func (osuo *OfflineSessionUpdateOne) Select(field string, fields ...string) *OfflineSessionUpdateOne { - osuo.fields = append([]string{field}, fields...) - return osuo +func (_u *OfflineSessionUpdateOne) Select(field string, fields ...string) *OfflineSessionUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u } // Save executes the query and returns the updated OfflineSession entity. -func (osuo *OfflineSessionUpdateOne) Save(ctx context.Context) (*OfflineSession, error) { - return withHooks(ctx, osuo.sqlSave, osuo.mutation, osuo.hooks) +func (_u *OfflineSessionUpdateOne) Save(ctx context.Context) (*OfflineSession, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) } // SaveX is like Save, but panics if an error occurs. -func (osuo *OfflineSessionUpdateOne) SaveX(ctx context.Context) *OfflineSession { - node, err := osuo.Save(ctx) +func (_u *OfflineSessionUpdateOne) SaveX(ctx context.Context) *OfflineSession { + node, err := _u.Save(ctx) if err != nil { panic(err) } @@ -246,26 +246,26 @@ func (osuo *OfflineSessionUpdateOne) SaveX(ctx context.Context) *OfflineSession } // Exec executes the query on the entity. -func (osuo *OfflineSessionUpdateOne) Exec(ctx context.Context) error { - _, err := osuo.Save(ctx) +func (_u *OfflineSessionUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (osuo *OfflineSessionUpdateOne) ExecX(ctx context.Context) { - if err := osuo.Exec(ctx); err != nil { +func (_u *OfflineSessionUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { panic(err) } } // check runs all checks and user-defined validators on the builder. -func (osuo *OfflineSessionUpdateOne) check() error { - if v, ok := osuo.mutation.UserID(); ok { +func (_u *OfflineSessionUpdateOne) check() error { + if v, ok := _u.mutation.UserID(); ok { if err := offlinesession.UserIDValidator(v); err != nil { return &ValidationError{Name: "user_id", err: fmt.Errorf(`db: validator failed for field "OfflineSession.user_id": %w`, err)} } } - if v, ok := osuo.mutation.ConnID(); ok { + if v, ok := _u.mutation.ConnID(); ok { if err := offlinesession.ConnIDValidator(v); err != nil { return &ValidationError{Name: "conn_id", err: fmt.Errorf(`db: validator failed for field "OfflineSession.conn_id": %w`, err)} } @@ -273,17 +273,17 @@ func (osuo *OfflineSessionUpdateOne) check() error { return nil } -func (osuo *OfflineSessionUpdateOne) sqlSave(ctx context.Context) (_node *OfflineSession, err error) { - if err := osuo.check(); err != nil { +func (_u *OfflineSessionUpdateOne) sqlSave(ctx context.Context) (_node *OfflineSession, err error) { + if err := _u.check(); err != nil { return _node, err } _spec := sqlgraph.NewUpdateSpec(offlinesession.Table, offlinesession.Columns, sqlgraph.NewFieldSpec(offlinesession.FieldID, field.TypeString)) - id, ok := osuo.mutation.ID() + id, ok := _u.mutation.ID() if !ok { return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "OfflineSession.id" for update`)} } _spec.Node.ID.Value = id - if fields := osuo.fields; len(fields) > 0 { + if fields := _u.fields; len(fields) > 0 { _spec.Node.Columns = make([]string, 0, len(fields)) _spec.Node.Columns = append(_spec.Node.Columns, offlinesession.FieldID) for _, f := range fields { @@ -295,32 +295,32 @@ func (osuo *OfflineSessionUpdateOne) sqlSave(ctx context.Context) (_node *Offlin } } } - if ps := osuo.mutation.predicates; len(ps) > 0 { + if ps := _u.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if value, ok := osuo.mutation.UserID(); ok { + if value, ok := _u.mutation.UserID(); ok { _spec.SetField(offlinesession.FieldUserID, field.TypeString, value) } - if value, ok := osuo.mutation.ConnID(); ok { + if value, ok := _u.mutation.ConnID(); ok { _spec.SetField(offlinesession.FieldConnID, field.TypeString, value) } - if value, ok := osuo.mutation.Refresh(); ok { + if value, ok := _u.mutation.Refresh(); ok { _spec.SetField(offlinesession.FieldRefresh, field.TypeBytes, value) } - if value, ok := osuo.mutation.ConnectorData(); ok { + if value, ok := _u.mutation.ConnectorData(); ok { _spec.SetField(offlinesession.FieldConnectorData, field.TypeBytes, value) } - if osuo.mutation.ConnectorDataCleared() { + if _u.mutation.ConnectorDataCleared() { _spec.ClearField(offlinesession.FieldConnectorData, field.TypeBytes) } - _node = &OfflineSession{config: osuo.config} + _node = &OfflineSession{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, osuo.driver, _spec); err != nil { + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{offlinesession.Label} } else if sqlgraph.IsConstraintError(err) { @@ -328,6 +328,6 @@ func (osuo *OfflineSessionUpdateOne) sqlSave(ctx context.Context) (_node *Offlin } return nil, err } - osuo.mutation.done = true + _u.mutation.done = true return _node, nil } diff --git a/storage/ent/db/password.go b/storage/ent/db/password.go index 70f8ad2b1e..e2ceec8f22 100644 --- a/storage/ent/db/password.go +++ b/storage/ent/db/password.go @@ -47,7 +47,7 @@ func (*Password) scanValues(columns []string) ([]any, error) { // assignValues assigns the values that were returned from sql.Rows (after scanning) // to the Password fields. -func (pa *Password) assignValues(columns []string, values []any) error { +func (_m *Password) 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) } @@ -58,33 +58,33 @@ func (pa *Password) assignValues(columns []string, values []any) error { if !ok { return fmt.Errorf("unexpected type %T for field id", value) } - pa.ID = int(value.Int64) + _m.ID = int(value.Int64) case password.FieldEmail: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field email", values[i]) } else if value.Valid { - pa.Email = value.String + _m.Email = value.String } case password.FieldHash: if value, ok := values[i].(*[]byte); !ok { return fmt.Errorf("unexpected type %T for field hash", values[i]) } else if value != nil { - pa.Hash = *value + _m.Hash = *value } case password.FieldUsername: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field username", values[i]) } else if value.Valid { - pa.Username = value.String + _m.Username = value.String } case password.FieldUserID: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field user_id", values[i]) } else if value.Valid { - pa.UserID = value.String + _m.UserID = value.String } default: - pa.selectValues.Set(columns[i], values[i]) + _m.selectValues.Set(columns[i], values[i]) } } return nil @@ -92,44 +92,44 @@ func (pa *Password) assignValues(columns []string, values []any) error { // Value returns the ent.Value that was dynamically selected and assigned to the Password. // This includes values selected through modifiers, order, etc. -func (pa *Password) Value(name string) (ent.Value, error) { - return pa.selectValues.Get(name) +func (_m *Password) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) } // Update returns a builder for updating this Password. // Note that you need to call Password.Unwrap() before calling this method if this Password // was returned from a transaction, and the transaction was committed or rolled back. -func (pa *Password) Update() *PasswordUpdateOne { - return NewPasswordClient(pa.config).UpdateOne(pa) +func (_m *Password) Update() *PasswordUpdateOne { + return NewPasswordClient(_m.config).UpdateOne(_m) } // Unwrap unwraps the Password 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 (pa *Password) Unwrap() *Password { - _tx, ok := pa.config.driver.(*txDriver) +func (_m *Password) Unwrap() *Password { + _tx, ok := _m.config.driver.(*txDriver) if !ok { panic("db: Password is not a transactional entity") } - pa.config.driver = _tx.drv - return pa + _m.config.driver = _tx.drv + return _m } // String implements the fmt.Stringer. -func (pa *Password) String() string { +func (_m *Password) String() string { var builder strings.Builder builder.WriteString("Password(") - builder.WriteString(fmt.Sprintf("id=%v, ", pa.ID)) + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) builder.WriteString("email=") - builder.WriteString(pa.Email) + builder.WriteString(_m.Email) builder.WriteString(", ") builder.WriteString("hash=") - builder.WriteString(fmt.Sprintf("%v", pa.Hash)) + builder.WriteString(fmt.Sprintf("%v", _m.Hash)) builder.WriteString(", ") builder.WriteString("username=") - builder.WriteString(pa.Username) + builder.WriteString(_m.Username) builder.WriteString(", ") builder.WriteString("user_id=") - builder.WriteString(pa.UserID) + builder.WriteString(_m.UserID) builder.WriteByte(')') return builder.String() } diff --git a/storage/ent/db/password_create.go b/storage/ent/db/password_create.go index aba7ddd930..4d68de8f38 100644 --- a/storage/ent/db/password_create.go +++ b/storage/ent/db/password_create.go @@ -20,42 +20,42 @@ type PasswordCreate struct { } // SetEmail sets the "email" field. -func (pc *PasswordCreate) SetEmail(s string) *PasswordCreate { - pc.mutation.SetEmail(s) - return pc +func (_c *PasswordCreate) SetEmail(v string) *PasswordCreate { + _c.mutation.SetEmail(v) + return _c } // SetHash sets the "hash" field. -func (pc *PasswordCreate) SetHash(b []byte) *PasswordCreate { - pc.mutation.SetHash(b) - return pc +func (_c *PasswordCreate) SetHash(v []byte) *PasswordCreate { + _c.mutation.SetHash(v) + return _c } // SetUsername sets the "username" field. -func (pc *PasswordCreate) SetUsername(s string) *PasswordCreate { - pc.mutation.SetUsername(s) - return pc +func (_c *PasswordCreate) SetUsername(v string) *PasswordCreate { + _c.mutation.SetUsername(v) + return _c } // SetUserID sets the "user_id" field. -func (pc *PasswordCreate) SetUserID(s string) *PasswordCreate { - pc.mutation.SetUserID(s) - return pc +func (_c *PasswordCreate) SetUserID(v string) *PasswordCreate { + _c.mutation.SetUserID(v) + return _c } // Mutation returns the PasswordMutation object of the builder. -func (pc *PasswordCreate) Mutation() *PasswordMutation { - return pc.mutation +func (_c *PasswordCreate) Mutation() *PasswordMutation { + return _c.mutation } // Save creates the Password in the database. -func (pc *PasswordCreate) Save(ctx context.Context) (*Password, error) { - return withHooks(ctx, pc.sqlSave, pc.mutation, pc.hooks) +func (_c *PasswordCreate) Save(ctx context.Context) (*Password, error) { + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) } // SaveX calls Save and panics if Save returns an error. -func (pc *PasswordCreate) SaveX(ctx context.Context) *Password { - v, err := pc.Save(ctx) +func (_c *PasswordCreate) SaveX(ctx context.Context) *Password { + v, err := _c.Save(ctx) if err != nil { panic(err) } @@ -63,43 +63,43 @@ func (pc *PasswordCreate) SaveX(ctx context.Context) *Password { } // Exec executes the query. -func (pc *PasswordCreate) Exec(ctx context.Context) error { - _, err := pc.Save(ctx) +func (_c *PasswordCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (pc *PasswordCreate) ExecX(ctx context.Context) { - if err := pc.Exec(ctx); err != nil { +func (_c *PasswordCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { panic(err) } } // check runs all checks and user-defined validators on the builder. -func (pc *PasswordCreate) check() error { - if _, ok := pc.mutation.Email(); !ok { +func (_c *PasswordCreate) check() error { + if _, ok := _c.mutation.Email(); !ok { return &ValidationError{Name: "email", err: errors.New(`db: missing required field "Password.email"`)} } - if v, ok := pc.mutation.Email(); ok { + if v, ok := _c.mutation.Email(); ok { if err := password.EmailValidator(v); err != nil { return &ValidationError{Name: "email", err: fmt.Errorf(`db: validator failed for field "Password.email": %w`, err)} } } - if _, ok := pc.mutation.Hash(); !ok { + if _, ok := _c.mutation.Hash(); !ok { return &ValidationError{Name: "hash", err: errors.New(`db: missing required field "Password.hash"`)} } - if _, ok := pc.mutation.Username(); !ok { + if _, ok := _c.mutation.Username(); !ok { return &ValidationError{Name: "username", err: errors.New(`db: missing required field "Password.username"`)} } - if v, ok := pc.mutation.Username(); ok { + if v, ok := _c.mutation.Username(); ok { if err := password.UsernameValidator(v); err != nil { return &ValidationError{Name: "username", err: fmt.Errorf(`db: validator failed for field "Password.username": %w`, err)} } } - if _, ok := pc.mutation.UserID(); !ok { + if _, ok := _c.mutation.UserID(); !ok { return &ValidationError{Name: "user_id", err: errors.New(`db: missing required field "Password.user_id"`)} } - if v, ok := pc.mutation.UserID(); ok { + if v, ok := _c.mutation.UserID(); ok { if err := password.UserIDValidator(v); err != nil { return &ValidationError{Name: "user_id", err: fmt.Errorf(`db: validator failed for field "Password.user_id": %w`, err)} } @@ -107,12 +107,12 @@ func (pc *PasswordCreate) check() error { return nil } -func (pc *PasswordCreate) sqlSave(ctx context.Context) (*Password, error) { - if err := pc.check(); err != nil { +func (_c *PasswordCreate) sqlSave(ctx context.Context) (*Password, error) { + if err := _c.check(); err != nil { return nil, err } - _node, _spec := pc.createSpec() - if err := sqlgraph.CreateNode(ctx, pc.driver, _spec); err != nil { + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { if sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } @@ -120,29 +120,29 @@ func (pc *PasswordCreate) sqlSave(ctx context.Context) (*Password, error) { } id := _spec.ID.Value.(int64) _node.ID = int(id) - pc.mutation.id = &_node.ID - pc.mutation.done = true + _c.mutation.id = &_node.ID + _c.mutation.done = true return _node, nil } -func (pc *PasswordCreate) createSpec() (*Password, *sqlgraph.CreateSpec) { +func (_c *PasswordCreate) createSpec() (*Password, *sqlgraph.CreateSpec) { var ( - _node = &Password{config: pc.config} + _node = &Password{config: _c.config} _spec = sqlgraph.NewCreateSpec(password.Table, sqlgraph.NewFieldSpec(password.FieldID, field.TypeInt)) ) - if value, ok := pc.mutation.Email(); ok { + if value, ok := _c.mutation.Email(); ok { _spec.SetField(password.FieldEmail, field.TypeString, value) _node.Email = value } - if value, ok := pc.mutation.Hash(); ok { + if value, ok := _c.mutation.Hash(); ok { _spec.SetField(password.FieldHash, field.TypeBytes, value) _node.Hash = value } - if value, ok := pc.mutation.Username(); ok { + if value, ok := _c.mutation.Username(); ok { _spec.SetField(password.FieldUsername, field.TypeString, value) _node.Username = value } - if value, ok := pc.mutation.UserID(); ok { + if value, ok := _c.mutation.UserID(); ok { _spec.SetField(password.FieldUserID, field.TypeString, value) _node.UserID = value } @@ -157,16 +157,16 @@ type PasswordCreateBulk struct { } // Save creates the Password entities in the database. -func (pcb *PasswordCreateBulk) Save(ctx context.Context) ([]*Password, error) { - if pcb.err != nil { - return nil, pcb.err - } - specs := make([]*sqlgraph.CreateSpec, len(pcb.builders)) - nodes := make([]*Password, len(pcb.builders)) - mutators := make([]Mutator, len(pcb.builders)) - for i := range pcb.builders { +func (_c *PasswordCreateBulk) Save(ctx context.Context) ([]*Password, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*Password, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { func(i int, root context.Context) { - builder := pcb.builders[i] + builder := _c.builders[i] var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { mutation, ok := m.(*PasswordMutation) if !ok { @@ -179,11 +179,11 @@ func (pcb *PasswordCreateBulk) Save(ctx context.Context) ([]*Password, error) { 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) + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, pcb.driver, spec); err != nil { + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { if sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } @@ -207,7 +207,7 @@ func (pcb *PasswordCreateBulk) Save(ctx context.Context) ([]*Password, error) { }(i, ctx) } if len(mutators) > 0 { - if _, err := mutators[0].Mutate(ctx, pcb.builders[0].mutation); err != nil { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { return nil, err } } @@ -215,8 +215,8 @@ func (pcb *PasswordCreateBulk) Save(ctx context.Context) ([]*Password, error) { } // SaveX is like Save, but panics if an error occurs. -func (pcb *PasswordCreateBulk) SaveX(ctx context.Context) []*Password { - v, err := pcb.Save(ctx) +func (_c *PasswordCreateBulk) SaveX(ctx context.Context) []*Password { + v, err := _c.Save(ctx) if err != nil { panic(err) } @@ -224,14 +224,14 @@ func (pcb *PasswordCreateBulk) SaveX(ctx context.Context) []*Password { } // Exec executes the query. -func (pcb *PasswordCreateBulk) Exec(ctx context.Context) error { - _, err := pcb.Save(ctx) +func (_c *PasswordCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (pcb *PasswordCreateBulk) ExecX(ctx context.Context) { - if err := pcb.Exec(ctx); err != nil { +func (_c *PasswordCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { panic(err) } } diff --git a/storage/ent/db/password_delete.go b/storage/ent/db/password_delete.go index 784d545ee6..35ecfbc30d 100644 --- a/storage/ent/db/password_delete.go +++ b/storage/ent/db/password_delete.go @@ -20,56 +20,56 @@ type PasswordDelete struct { } // Where appends a list predicates to the PasswordDelete builder. -func (pd *PasswordDelete) Where(ps ...predicate.Password) *PasswordDelete { - pd.mutation.Where(ps...) - return pd +func (_d *PasswordDelete) Where(ps ...predicate.Password) *PasswordDelete { + _d.mutation.Where(ps...) + return _d } // Exec executes the deletion query and returns how many vertices were deleted. -func (pd *PasswordDelete) Exec(ctx context.Context) (int, error) { - return withHooks(ctx, pd.sqlExec, pd.mutation, pd.hooks) +func (_d *PasswordDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) } // ExecX is like Exec, but panics if an error occurs. -func (pd *PasswordDelete) ExecX(ctx context.Context) int { - n, err := pd.Exec(ctx) +func (_d *PasswordDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) if err != nil { panic(err) } return n } -func (pd *PasswordDelete) sqlExec(ctx context.Context) (int, error) { +func (_d *PasswordDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(password.Table, sqlgraph.NewFieldSpec(password.FieldID, field.TypeInt)) - if ps := pd.mutation.predicates; len(ps) > 0 { + if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - affected, err := sqlgraph.DeleteNodes(ctx, pd.driver, _spec) + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) if err != nil && sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } - pd.mutation.done = true + _d.mutation.done = true return affected, err } // PasswordDeleteOne is the builder for deleting a single Password entity. type PasswordDeleteOne struct { - pd *PasswordDelete + _d *PasswordDelete } // Where appends a list predicates to the PasswordDelete builder. -func (pdo *PasswordDeleteOne) Where(ps ...predicate.Password) *PasswordDeleteOne { - pdo.pd.mutation.Where(ps...) - return pdo +func (_d *PasswordDeleteOne) Where(ps ...predicate.Password) *PasswordDeleteOne { + _d._d.mutation.Where(ps...) + return _d } // Exec executes the deletion query. -func (pdo *PasswordDeleteOne) Exec(ctx context.Context) error { - n, err := pdo.pd.Exec(ctx) +func (_d *PasswordDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) switch { case err != nil: return err @@ -81,8 +81,8 @@ func (pdo *PasswordDeleteOne) Exec(ctx context.Context) error { } // ExecX is like Exec, but panics if an error occurs. -func (pdo *PasswordDeleteOne) ExecX(ctx context.Context) { - if err := pdo.Exec(ctx); err != nil { +func (_d *PasswordDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { panic(err) } } diff --git a/storage/ent/db/password_query.go b/storage/ent/db/password_query.go index b20422f763..eaeb28bba0 100644 --- a/storage/ent/db/password_query.go +++ b/storage/ent/db/password_query.go @@ -28,40 +28,40 @@ type PasswordQuery struct { } // Where adds a new predicate for the PasswordQuery builder. -func (pq *PasswordQuery) Where(ps ...predicate.Password) *PasswordQuery { - pq.predicates = append(pq.predicates, ps...) - return pq +func (_q *PasswordQuery) Where(ps ...predicate.Password) *PasswordQuery { + _q.predicates = append(_q.predicates, ps...) + return _q } // Limit the number of records to be returned by this query. -func (pq *PasswordQuery) Limit(limit int) *PasswordQuery { - pq.ctx.Limit = &limit - return pq +func (_q *PasswordQuery) Limit(limit int) *PasswordQuery { + _q.ctx.Limit = &limit + return _q } // Offset to start from. -func (pq *PasswordQuery) Offset(offset int) *PasswordQuery { - pq.ctx.Offset = &offset - return pq +func (_q *PasswordQuery) Offset(offset int) *PasswordQuery { + _q.ctx.Offset = &offset + return _q } // Unique configures the query builder to filter duplicate records on query. // By default, unique is set to true, and can be disabled using this method. -func (pq *PasswordQuery) Unique(unique bool) *PasswordQuery { - pq.ctx.Unique = &unique - return pq +func (_q *PasswordQuery) Unique(unique bool) *PasswordQuery { + _q.ctx.Unique = &unique + return _q } // Order specifies how the records should be ordered. -func (pq *PasswordQuery) Order(o ...password.OrderOption) *PasswordQuery { - pq.order = append(pq.order, o...) - return pq +func (_q *PasswordQuery) Order(o ...password.OrderOption) *PasswordQuery { + _q.order = append(_q.order, o...) + return _q } // First returns the first Password entity from the query. // Returns a *NotFoundError when no Password was found. -func (pq *PasswordQuery) First(ctx context.Context) (*Password, error) { - nodes, err := pq.Limit(1).All(setContextOp(ctx, pq.ctx, ent.OpQueryFirst)) +func (_q *PasswordQuery) First(ctx context.Context) (*Password, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) if err != nil { return nil, err } @@ -72,8 +72,8 @@ func (pq *PasswordQuery) First(ctx context.Context) (*Password, error) { } // FirstX is like First, but panics if an error occurs. -func (pq *PasswordQuery) FirstX(ctx context.Context) *Password { - node, err := pq.First(ctx) +func (_q *PasswordQuery) FirstX(ctx context.Context) *Password { + node, err := _q.First(ctx) if err != nil && !IsNotFound(err) { panic(err) } @@ -82,9 +82,9 @@ func (pq *PasswordQuery) FirstX(ctx context.Context) *Password { // FirstID returns the first Password ID from the query. // Returns a *NotFoundError when no Password ID was found. -func (pq *PasswordQuery) FirstID(ctx context.Context) (id int, err error) { +func (_q *PasswordQuery) 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 { + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { return } if len(ids) == 0 { @@ -95,8 +95,8 @@ func (pq *PasswordQuery) FirstID(ctx context.Context) (id int, err error) { } // FirstIDX is like FirstID, but panics if an error occurs. -func (pq *PasswordQuery) FirstIDX(ctx context.Context) int { - id, err := pq.FirstID(ctx) +func (_q *PasswordQuery) FirstIDX(ctx context.Context) int { + id, err := _q.FirstID(ctx) if err != nil && !IsNotFound(err) { panic(err) } @@ -106,8 +106,8 @@ func (pq *PasswordQuery) FirstIDX(ctx context.Context) int { // Only returns a single Password entity found by the query, ensuring it only returns one. // Returns a *NotSingularError when more than one Password entity is found. // Returns a *NotFoundError when no Password entities are found. -func (pq *PasswordQuery) Only(ctx context.Context) (*Password, error) { - nodes, err := pq.Limit(2).All(setContextOp(ctx, pq.ctx, ent.OpQueryOnly)) +func (_q *PasswordQuery) Only(ctx context.Context) (*Password, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) if err != nil { return nil, err } @@ -122,8 +122,8 @@ func (pq *PasswordQuery) Only(ctx context.Context) (*Password, error) { } // OnlyX is like Only, but panics if an error occurs. -func (pq *PasswordQuery) OnlyX(ctx context.Context) *Password { - node, err := pq.Only(ctx) +func (_q *PasswordQuery) OnlyX(ctx context.Context) *Password { + node, err := _q.Only(ctx) if err != nil { panic(err) } @@ -133,9 +133,9 @@ func (pq *PasswordQuery) OnlyX(ctx context.Context) *Password { // OnlyID is like Only, but returns the only Password ID in the query. // Returns a *NotSingularError when more than one Password ID is found. // Returns a *NotFoundError when no entities are found. -func (pq *PasswordQuery) OnlyID(ctx context.Context) (id int, err error) { +func (_q *PasswordQuery) 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 { + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { return } switch len(ids) { @@ -150,8 +150,8 @@ func (pq *PasswordQuery) OnlyID(ctx context.Context) (id int, err error) { } // OnlyIDX is like OnlyID, but panics if an error occurs. -func (pq *PasswordQuery) OnlyIDX(ctx context.Context) int { - id, err := pq.OnlyID(ctx) +func (_q *PasswordQuery) OnlyIDX(ctx context.Context) int { + id, err := _q.OnlyID(ctx) if err != nil { panic(err) } @@ -159,18 +159,18 @@ func (pq *PasswordQuery) OnlyIDX(ctx context.Context) int { } // All executes the query and returns a list of Passwords. -func (pq *PasswordQuery) All(ctx context.Context) ([]*Password, error) { - ctx = setContextOp(ctx, pq.ctx, ent.OpQueryAll) - if err := pq.prepareQuery(ctx); err != nil { +func (_q *PasswordQuery) All(ctx context.Context) ([]*Password, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { return nil, err } qr := querierAll[[]*Password, *PasswordQuery]() - return withInterceptors[[]*Password](ctx, pq, qr, pq.inters) + return withInterceptors[[]*Password](ctx, _q, qr, _q.inters) } // AllX is like All, but panics if an error occurs. -func (pq *PasswordQuery) AllX(ctx context.Context) []*Password { - nodes, err := pq.All(ctx) +func (_q *PasswordQuery) AllX(ctx context.Context) []*Password { + nodes, err := _q.All(ctx) if err != nil { panic(err) } @@ -178,20 +178,20 @@ func (pq *PasswordQuery) AllX(ctx context.Context) []*Password { } // IDs executes the query and returns a list of Password IDs. -func (pq *PasswordQuery) IDs(ctx context.Context) (ids []int, err error) { - if pq.ctx.Unique == nil && pq.path != nil { - pq.Unique(true) +func (_q *PasswordQuery) IDs(ctx context.Context) (ids []int, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) } - ctx = setContextOp(ctx, pq.ctx, ent.OpQueryIDs) - if err = pq.Select(password.FieldID).Scan(ctx, &ids); err != nil { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(password.FieldID).Scan(ctx, &ids); err != nil { return nil, err } return ids, nil } // IDsX is like IDs, but panics if an error occurs. -func (pq *PasswordQuery) IDsX(ctx context.Context) []int { - ids, err := pq.IDs(ctx) +func (_q *PasswordQuery) IDsX(ctx context.Context) []int { + ids, err := _q.IDs(ctx) if err != nil { panic(err) } @@ -199,17 +199,17 @@ func (pq *PasswordQuery) IDsX(ctx context.Context) []int { } // Count returns the count of the given query. -func (pq *PasswordQuery) Count(ctx context.Context) (int, error) { - ctx = setContextOp(ctx, pq.ctx, ent.OpQueryCount) - if err := pq.prepareQuery(ctx); err != nil { +func (_q *PasswordQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { return 0, err } - return withInterceptors[int](ctx, pq, querierCount[*PasswordQuery](), pq.inters) + return withInterceptors[int](ctx, _q, querierCount[*PasswordQuery](), _q.inters) } // CountX is like Count, but panics if an error occurs. -func (pq *PasswordQuery) CountX(ctx context.Context) int { - count, err := pq.Count(ctx) +func (_q *PasswordQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) if err != nil { panic(err) } @@ -217,9 +217,9 @@ func (pq *PasswordQuery) CountX(ctx context.Context) int { } // Exist returns true if the query has elements in the graph. -func (pq *PasswordQuery) Exist(ctx context.Context) (bool, error) { - ctx = setContextOp(ctx, pq.ctx, ent.OpQueryExist) - switch _, err := pq.FirstID(ctx); { +func (_q *PasswordQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { case IsNotFound(err): return false, nil case err != nil: @@ -230,8 +230,8 @@ func (pq *PasswordQuery) Exist(ctx context.Context) (bool, error) { } // ExistX is like Exist, but panics if an error occurs. -func (pq *PasswordQuery) ExistX(ctx context.Context) bool { - exist, err := pq.Exist(ctx) +func (_q *PasswordQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) if err != nil { panic(err) } @@ -240,19 +240,19 @@ func (pq *PasswordQuery) ExistX(ctx context.Context) bool { // Clone returns a duplicate of the PasswordQuery 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 *PasswordQuery) Clone() *PasswordQuery { - if pq == nil { +func (_q *PasswordQuery) Clone() *PasswordQuery { + if _q == nil { return nil } return &PasswordQuery{ - config: pq.config, - ctx: pq.ctx.Clone(), - order: append([]password.OrderOption{}, pq.order...), - inters: append([]Interceptor{}, pq.inters...), - predicates: append([]predicate.Password{}, pq.predicates...), + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]password.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.Password{}, _q.predicates...), // clone intermediate query. - sql: pq.sql.Clone(), - path: pq.path, + sql: _q.sql.Clone(), + path: _q.path, } } @@ -270,10 +270,10 @@ func (pq *PasswordQuery) Clone() *PasswordQuery { // GroupBy(password.FieldEmail). // Aggregate(db.Count()). // Scan(ctx, &v) -func (pq *PasswordQuery) GroupBy(field string, fields ...string) *PasswordGroupBy { - pq.ctx.Fields = append([]string{field}, fields...) - grbuild := &PasswordGroupBy{build: pq} - grbuild.flds = &pq.ctx.Fields +func (_q *PasswordQuery) GroupBy(field string, fields ...string) *PasswordGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &PasswordGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields grbuild.label = password.Label grbuild.scan = grbuild.Scan return grbuild @@ -291,62 +291,62 @@ func (pq *PasswordQuery) GroupBy(field string, fields ...string) *PasswordGroupB // client.Password.Query(). // Select(password.FieldEmail). // Scan(ctx, &v) -func (pq *PasswordQuery) Select(fields ...string) *PasswordSelect { - pq.ctx.Fields = append(pq.ctx.Fields, fields...) - sbuild := &PasswordSelect{PasswordQuery: pq} +func (_q *PasswordQuery) Select(fields ...string) *PasswordSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &PasswordSelect{PasswordQuery: _q} sbuild.label = password.Label - sbuild.flds, sbuild.scan = &pq.ctx.Fields, sbuild.Scan + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan return sbuild } // Aggregate returns a PasswordSelect configured with the given aggregations. -func (pq *PasswordQuery) Aggregate(fns ...AggregateFunc) *PasswordSelect { - return pq.Select().Aggregate(fns...) +func (_q *PasswordQuery) Aggregate(fns ...AggregateFunc) *PasswordSelect { + return _q.Select().Aggregate(fns...) } -func (pq *PasswordQuery) prepareQuery(ctx context.Context) error { - for _, inter := range pq.inters { +func (_q *PasswordQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { if inter == nil { return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)") } if trv, ok := inter.(Traverser); ok { - if err := trv.Traverse(ctx, pq); err != nil { + if err := trv.Traverse(ctx, _q); err != nil { return err } } } - for _, f := range pq.ctx.Fields { + for _, f := range _q.ctx.Fields { if !password.ValidColumn(f) { return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} } } - if pq.path != nil { - prev, err := pq.path(ctx) + if _q.path != nil { + prev, err := _q.path(ctx) if err != nil { return err } - pq.sql = prev + _q.sql = prev } return nil } -func (pq *PasswordQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Password, error) { +func (_q *PasswordQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Password, error) { var ( nodes = []*Password{} - _spec = pq.querySpec() + _spec = _q.querySpec() ) _spec.ScanValues = func(columns []string) ([]any, error) { return (*Password).scanValues(nil, columns) } _spec.Assign = func(columns []string, values []any) error { - node := &Password{config: pq.config} + node := &Password{config: _q.config} nodes = append(nodes, node) return node.assignValues(columns, values) } for i := range hooks { hooks[i](ctx, _spec) } - if err := sqlgraph.QueryNodes(ctx, pq.driver, _spec); err != nil { + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { return nil, err } if len(nodes) == 0 { @@ -355,24 +355,24 @@ func (pq *PasswordQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Pas return nodes, nil } -func (pq *PasswordQuery) sqlCount(ctx context.Context) (int, error) { - _spec := pq.querySpec() - _spec.Node.Columns = pq.ctx.Fields - if len(pq.ctx.Fields) > 0 { - _spec.Unique = pq.ctx.Unique != nil && *pq.ctx.Unique +func (_q *PasswordQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique } - return sqlgraph.CountNodes(ctx, pq.driver, _spec) + return sqlgraph.CountNodes(ctx, _q.driver, _spec) } -func (pq *PasswordQuery) querySpec() *sqlgraph.QuerySpec { +func (_q *PasswordQuery) querySpec() *sqlgraph.QuerySpec { _spec := sqlgraph.NewQuerySpec(password.Table, password.Columns, sqlgraph.NewFieldSpec(password.FieldID, field.TypeInt)) - _spec.From = pq.sql - if unique := pq.ctx.Unique; unique != nil { + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { _spec.Unique = *unique - } else if pq.path != nil { + } else if _q.path != nil { _spec.Unique = true } - if fields := pq.ctx.Fields; len(fields) > 0 { + if fields := _q.ctx.Fields; len(fields) > 0 { _spec.Node.Columns = make([]string, 0, len(fields)) _spec.Node.Columns = append(_spec.Node.Columns, password.FieldID) for i := range fields { @@ -381,20 +381,20 @@ func (pq *PasswordQuery) querySpec() *sqlgraph.QuerySpec { } } } - if ps := pq.predicates; len(ps) > 0 { + if ps := _q.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if limit := pq.ctx.Limit; limit != nil { + if limit := _q.ctx.Limit; limit != nil { _spec.Limit = *limit } - if offset := pq.ctx.Offset; offset != nil { + if offset := _q.ctx.Offset; offset != nil { _spec.Offset = *offset } - if ps := pq.order; len(ps) > 0 { + if ps := _q.order; len(ps) > 0 { _spec.Order = func(selector *sql.Selector) { for i := range ps { ps[i](selector) @@ -404,33 +404,33 @@ func (pq *PasswordQuery) querySpec() *sqlgraph.QuerySpec { return _spec } -func (pq *PasswordQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(pq.driver.Dialect()) +func (_q *PasswordQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) t1 := builder.Table(password.Table) - columns := pq.ctx.Fields + columns := _q.ctx.Fields if len(columns) == 0 { columns = password.Columns } selector := builder.Select(t1.Columns(columns...)...).From(t1) - if pq.sql != nil { - selector = pq.sql + if _q.sql != nil { + selector = _q.sql selector.Select(selector.Columns(columns...)...) } - if pq.ctx.Unique != nil && *pq.ctx.Unique { + if _q.ctx.Unique != nil && *_q.ctx.Unique { selector.Distinct() } - for _, p := range pq.predicates { + for _, p := range _q.predicates { p(selector) } - for _, p := range pq.order { + for _, p := range _q.order { p(selector) } - if offset := pq.ctx.Offset; offset != nil { + if offset := _q.ctx.Offset; offset != nil { // limit is mandatory for offset clause. We start // with default value, and override it below if needed. selector.Offset(*offset).Limit(math.MaxInt32) } - if limit := pq.ctx.Limit; limit != nil { + if limit := _q.ctx.Limit; limit != nil { selector.Limit(*limit) } return selector @@ -443,41 +443,41 @@ type PasswordGroupBy struct { } // Aggregate adds the given aggregation functions to the group-by query. -func (pgb *PasswordGroupBy) Aggregate(fns ...AggregateFunc) *PasswordGroupBy { - pgb.fns = append(pgb.fns, fns...) - return pgb +func (_g *PasswordGroupBy) Aggregate(fns ...AggregateFunc) *PasswordGroupBy { + _g.fns = append(_g.fns, fns...) + return _g } // Scan applies the selector query and scans the result into the given value. -func (pgb *PasswordGroupBy) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, pgb.build.ctx, ent.OpQueryGroupBy) - if err := pgb.build.prepareQuery(ctx); err != nil { +func (_g *PasswordGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { return err } - return scanWithInterceptors[*PasswordQuery, *PasswordGroupBy](ctx, pgb.build, pgb, pgb.build.inters, v) + return scanWithInterceptors[*PasswordQuery, *PasswordGroupBy](ctx, _g.build, _g, _g.build.inters, v) } -func (pgb *PasswordGroupBy) sqlScan(ctx context.Context, root *PasswordQuery, v any) error { +func (_g *PasswordGroupBy) sqlScan(ctx context.Context, root *PasswordQuery, v any) error { selector := root.sqlQuery(ctx).Select() - aggregation := make([]string, 0, len(pgb.fns)) - for _, fn := range pgb.fns { + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { aggregation = append(aggregation, fn(selector)) } if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(*pgb.flds)+len(pgb.fns)) - for _, f := range *pgb.flds { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { columns = append(columns, selector.C(f)) } columns = append(columns, aggregation...) selector.Select(columns...) } - selector.GroupBy(selector.Columns(*pgb.flds...)...) + selector.GroupBy(selector.Columns(*_g.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 { + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() @@ -491,27 +491,27 @@ type PasswordSelect struct { } // Aggregate adds the given aggregation functions to the selector query. -func (ps *PasswordSelect) Aggregate(fns ...AggregateFunc) *PasswordSelect { - ps.fns = append(ps.fns, fns...) - return ps +func (_s *PasswordSelect) Aggregate(fns ...AggregateFunc) *PasswordSelect { + _s.fns = append(_s.fns, fns...) + return _s } // Scan applies the selector query and scans the result into the given value. -func (ps *PasswordSelect) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, ps.ctx, ent.OpQuerySelect) - if err := ps.prepareQuery(ctx); err != nil { +func (_s *PasswordSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { return err } - return scanWithInterceptors[*PasswordQuery, *PasswordSelect](ctx, ps.PasswordQuery, ps, ps.inters, v) + return scanWithInterceptors[*PasswordQuery, *PasswordSelect](ctx, _s.PasswordQuery, _s, _s.inters, v) } -func (ps *PasswordSelect) sqlScan(ctx context.Context, root *PasswordQuery, v any) error { +func (_s *PasswordSelect) sqlScan(ctx context.Context, root *PasswordQuery, v any) error { selector := root.sqlQuery(ctx) - aggregation := make([]string, 0, len(ps.fns)) - for _, fn := range ps.fns { + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { aggregation = append(aggregation, fn(selector)) } - switch n := len(*ps.selector.flds); { + switch n := len(*_s.selector.flds); { case n == 0 && len(aggregation) > 0: selector.Select(aggregation...) case n != 0 && len(aggregation) > 0: @@ -519,7 +519,7 @@ func (ps *PasswordSelect) sqlScan(ctx context.Context, root *PasswordQuery, v an } rows := &sql.Rows{} query, args := selector.Query() - if err := ps.driver.Query(ctx, query, args, rows); err != nil { + if err := _s.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() diff --git a/storage/ent/db/password_update.go b/storage/ent/db/password_update.go index 977ad7b42d..75394a78a2 100644 --- a/storage/ent/db/password_update.go +++ b/storage/ent/db/password_update.go @@ -22,72 +22,72 @@ type PasswordUpdate struct { } // Where appends a list predicates to the PasswordUpdate builder. -func (pu *PasswordUpdate) Where(ps ...predicate.Password) *PasswordUpdate { - pu.mutation.Where(ps...) - return pu +func (_u *PasswordUpdate) Where(ps ...predicate.Password) *PasswordUpdate { + _u.mutation.Where(ps...) + return _u } // SetEmail sets the "email" field. -func (pu *PasswordUpdate) SetEmail(s string) *PasswordUpdate { - pu.mutation.SetEmail(s) - return pu +func (_u *PasswordUpdate) SetEmail(v string) *PasswordUpdate { + _u.mutation.SetEmail(v) + return _u } // SetNillableEmail sets the "email" field if the given value is not nil. -func (pu *PasswordUpdate) SetNillableEmail(s *string) *PasswordUpdate { - if s != nil { - pu.SetEmail(*s) +func (_u *PasswordUpdate) SetNillableEmail(v *string) *PasswordUpdate { + if v != nil { + _u.SetEmail(*v) } - return pu + return _u } // SetHash sets the "hash" field. -func (pu *PasswordUpdate) SetHash(b []byte) *PasswordUpdate { - pu.mutation.SetHash(b) - return pu +func (_u *PasswordUpdate) SetHash(v []byte) *PasswordUpdate { + _u.mutation.SetHash(v) + return _u } // SetUsername sets the "username" field. -func (pu *PasswordUpdate) SetUsername(s string) *PasswordUpdate { - pu.mutation.SetUsername(s) - return pu +func (_u *PasswordUpdate) SetUsername(v string) *PasswordUpdate { + _u.mutation.SetUsername(v) + return _u } // SetNillableUsername sets the "username" field if the given value is not nil. -func (pu *PasswordUpdate) SetNillableUsername(s *string) *PasswordUpdate { - if s != nil { - pu.SetUsername(*s) +func (_u *PasswordUpdate) SetNillableUsername(v *string) *PasswordUpdate { + if v != nil { + _u.SetUsername(*v) } - return pu + return _u } // SetUserID sets the "user_id" field. -func (pu *PasswordUpdate) SetUserID(s string) *PasswordUpdate { - pu.mutation.SetUserID(s) - return pu +func (_u *PasswordUpdate) SetUserID(v string) *PasswordUpdate { + _u.mutation.SetUserID(v) + return _u } // SetNillableUserID sets the "user_id" field if the given value is not nil. -func (pu *PasswordUpdate) SetNillableUserID(s *string) *PasswordUpdate { - if s != nil { - pu.SetUserID(*s) +func (_u *PasswordUpdate) SetNillableUserID(v *string) *PasswordUpdate { + if v != nil { + _u.SetUserID(*v) } - return pu + return _u } // Mutation returns the PasswordMutation object of the builder. -func (pu *PasswordUpdate) Mutation() *PasswordMutation { - return pu.mutation +func (_u *PasswordUpdate) Mutation() *PasswordMutation { + return _u.mutation } // Save executes the query and returns the number of nodes affected by the update operation. -func (pu *PasswordUpdate) Save(ctx context.Context) (int, error) { - return withHooks(ctx, pu.sqlSave, pu.mutation, pu.hooks) +func (_u *PasswordUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) } // SaveX is like Save, but panics if an error occurs. -func (pu *PasswordUpdate) SaveX(ctx context.Context) int { - affected, err := pu.Save(ctx) +func (_u *PasswordUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) if err != nil { panic(err) } @@ -95,31 +95,31 @@ func (pu *PasswordUpdate) SaveX(ctx context.Context) int { } // Exec executes the query. -func (pu *PasswordUpdate) Exec(ctx context.Context) error { - _, err := pu.Save(ctx) +func (_u *PasswordUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (pu *PasswordUpdate) ExecX(ctx context.Context) { - if err := pu.Exec(ctx); err != nil { +func (_u *PasswordUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { panic(err) } } // check runs all checks and user-defined validators on the builder. -func (pu *PasswordUpdate) check() error { - if v, ok := pu.mutation.Email(); ok { +func (_u *PasswordUpdate) check() error { + if v, ok := _u.mutation.Email(); ok { if err := password.EmailValidator(v); err != nil { return &ValidationError{Name: "email", err: fmt.Errorf(`db: validator failed for field "Password.email": %w`, err)} } } - if v, ok := pu.mutation.Username(); ok { + if v, ok := _u.mutation.Username(); ok { if err := password.UsernameValidator(v); err != nil { return &ValidationError{Name: "username", err: fmt.Errorf(`db: validator failed for field "Password.username": %w`, err)} } } - if v, ok := pu.mutation.UserID(); ok { + if v, ok := _u.mutation.UserID(); ok { if err := password.UserIDValidator(v); err != nil { return &ValidationError{Name: "user_id", err: fmt.Errorf(`db: validator failed for field "Password.user_id": %w`, err)} } @@ -127,31 +127,31 @@ func (pu *PasswordUpdate) check() error { return nil } -func (pu *PasswordUpdate) sqlSave(ctx context.Context) (n int, err error) { - if err := pu.check(); err != nil { - return n, err +func (_u *PasswordUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err } _spec := sqlgraph.NewUpdateSpec(password.Table, password.Columns, sqlgraph.NewFieldSpec(password.FieldID, field.TypeInt)) - if ps := pu.mutation.predicates; len(ps) > 0 { + if ps := _u.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if value, ok := pu.mutation.Email(); ok { + if value, ok := _u.mutation.Email(); ok { _spec.SetField(password.FieldEmail, field.TypeString, value) } - if value, ok := pu.mutation.Hash(); ok { + if value, ok := _u.mutation.Hash(); ok { _spec.SetField(password.FieldHash, field.TypeBytes, value) } - if value, ok := pu.mutation.Username(); ok { + if value, ok := _u.mutation.Username(); ok { _spec.SetField(password.FieldUsername, field.TypeString, value) } - if value, ok := pu.mutation.UserID(); ok { + if value, ok := _u.mutation.UserID(); ok { _spec.SetField(password.FieldUserID, field.TypeString, value) } - if n, err = sqlgraph.UpdateNodes(ctx, pu.driver, _spec); err != nil { + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{password.Label} } else if sqlgraph.IsConstraintError(err) { @@ -159,8 +159,8 @@ func (pu *PasswordUpdate) sqlSave(ctx context.Context) (n int, err error) { } return 0, err } - pu.mutation.done = true - return n, nil + _u.mutation.done = true + return _node, nil } // PasswordUpdateOne is the builder for updating a single Password entity. @@ -172,79 +172,79 @@ type PasswordUpdateOne struct { } // SetEmail sets the "email" field. -func (puo *PasswordUpdateOne) SetEmail(s string) *PasswordUpdateOne { - puo.mutation.SetEmail(s) - return puo +func (_u *PasswordUpdateOne) SetEmail(v string) *PasswordUpdateOne { + _u.mutation.SetEmail(v) + return _u } // SetNillableEmail sets the "email" field if the given value is not nil. -func (puo *PasswordUpdateOne) SetNillableEmail(s *string) *PasswordUpdateOne { - if s != nil { - puo.SetEmail(*s) +func (_u *PasswordUpdateOne) SetNillableEmail(v *string) *PasswordUpdateOne { + if v != nil { + _u.SetEmail(*v) } - return puo + return _u } // SetHash sets the "hash" field. -func (puo *PasswordUpdateOne) SetHash(b []byte) *PasswordUpdateOne { - puo.mutation.SetHash(b) - return puo +func (_u *PasswordUpdateOne) SetHash(v []byte) *PasswordUpdateOne { + _u.mutation.SetHash(v) + return _u } // SetUsername sets the "username" field. -func (puo *PasswordUpdateOne) SetUsername(s string) *PasswordUpdateOne { - puo.mutation.SetUsername(s) - return puo +func (_u *PasswordUpdateOne) SetUsername(v string) *PasswordUpdateOne { + _u.mutation.SetUsername(v) + return _u } // SetNillableUsername sets the "username" field if the given value is not nil. -func (puo *PasswordUpdateOne) SetNillableUsername(s *string) *PasswordUpdateOne { - if s != nil { - puo.SetUsername(*s) +func (_u *PasswordUpdateOne) SetNillableUsername(v *string) *PasswordUpdateOne { + if v != nil { + _u.SetUsername(*v) } - return puo + return _u } // SetUserID sets the "user_id" field. -func (puo *PasswordUpdateOne) SetUserID(s string) *PasswordUpdateOne { - puo.mutation.SetUserID(s) - return puo +func (_u *PasswordUpdateOne) SetUserID(v string) *PasswordUpdateOne { + _u.mutation.SetUserID(v) + return _u } // SetNillableUserID sets the "user_id" field if the given value is not nil. -func (puo *PasswordUpdateOne) SetNillableUserID(s *string) *PasswordUpdateOne { - if s != nil { - puo.SetUserID(*s) +func (_u *PasswordUpdateOne) SetNillableUserID(v *string) *PasswordUpdateOne { + if v != nil { + _u.SetUserID(*v) } - return puo + return _u } // Mutation returns the PasswordMutation object of the builder. -func (puo *PasswordUpdateOne) Mutation() *PasswordMutation { - return puo.mutation +func (_u *PasswordUpdateOne) Mutation() *PasswordMutation { + return _u.mutation } // Where appends a list predicates to the PasswordUpdate builder. -func (puo *PasswordUpdateOne) Where(ps ...predicate.Password) *PasswordUpdateOne { - puo.mutation.Where(ps...) - return puo +func (_u *PasswordUpdateOne) Where(ps ...predicate.Password) *PasswordUpdateOne { + _u.mutation.Where(ps...) + return _u } // Select allows selecting one or more fields (columns) of the returned entity. // The default is selecting all fields defined in the entity schema. -func (puo *PasswordUpdateOne) Select(field string, fields ...string) *PasswordUpdateOne { - puo.fields = append([]string{field}, fields...) - return puo +func (_u *PasswordUpdateOne) Select(field string, fields ...string) *PasswordUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u } // Save executes the query and returns the updated Password entity. -func (puo *PasswordUpdateOne) Save(ctx context.Context) (*Password, error) { - return withHooks(ctx, puo.sqlSave, puo.mutation, puo.hooks) +func (_u *PasswordUpdateOne) Save(ctx context.Context) (*Password, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) } // SaveX is like Save, but panics if an error occurs. -func (puo *PasswordUpdateOne) SaveX(ctx context.Context) *Password { - node, err := puo.Save(ctx) +func (_u *PasswordUpdateOne) SaveX(ctx context.Context) *Password { + node, err := _u.Save(ctx) if err != nil { panic(err) } @@ -252,31 +252,31 @@ func (puo *PasswordUpdateOne) SaveX(ctx context.Context) *Password { } // Exec executes the query on the entity. -func (puo *PasswordUpdateOne) Exec(ctx context.Context) error { - _, err := puo.Save(ctx) +func (_u *PasswordUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (puo *PasswordUpdateOne) ExecX(ctx context.Context) { - if err := puo.Exec(ctx); err != nil { +func (_u *PasswordUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { panic(err) } } // check runs all checks and user-defined validators on the builder. -func (puo *PasswordUpdateOne) check() error { - if v, ok := puo.mutation.Email(); ok { +func (_u *PasswordUpdateOne) check() error { + if v, ok := _u.mutation.Email(); ok { if err := password.EmailValidator(v); err != nil { return &ValidationError{Name: "email", err: fmt.Errorf(`db: validator failed for field "Password.email": %w`, err)} } } - if v, ok := puo.mutation.Username(); ok { + if v, ok := _u.mutation.Username(); ok { if err := password.UsernameValidator(v); err != nil { return &ValidationError{Name: "username", err: fmt.Errorf(`db: validator failed for field "Password.username": %w`, err)} } } - if v, ok := puo.mutation.UserID(); ok { + if v, ok := _u.mutation.UserID(); ok { if err := password.UserIDValidator(v); err != nil { return &ValidationError{Name: "user_id", err: fmt.Errorf(`db: validator failed for field "Password.user_id": %w`, err)} } @@ -284,17 +284,17 @@ func (puo *PasswordUpdateOne) check() error { return nil } -func (puo *PasswordUpdateOne) sqlSave(ctx context.Context) (_node *Password, err error) { - if err := puo.check(); err != nil { +func (_u *PasswordUpdateOne) sqlSave(ctx context.Context) (_node *Password, err error) { + if err := _u.check(); err != nil { return _node, err } _spec := sqlgraph.NewUpdateSpec(password.Table, password.Columns, sqlgraph.NewFieldSpec(password.FieldID, field.TypeInt)) - id, ok := puo.mutation.ID() + id, ok := _u.mutation.ID() if !ok { return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "Password.id" for update`)} } _spec.Node.ID.Value = id - if fields := puo.fields; len(fields) > 0 { + if fields := _u.fields; len(fields) > 0 { _spec.Node.Columns = make([]string, 0, len(fields)) _spec.Node.Columns = append(_spec.Node.Columns, password.FieldID) for _, f := range fields { @@ -306,29 +306,29 @@ func (puo *PasswordUpdateOne) sqlSave(ctx context.Context) (_node *Password, err } } } - if ps := puo.mutation.predicates; len(ps) > 0 { + if ps := _u.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if value, ok := puo.mutation.Email(); ok { + if value, ok := _u.mutation.Email(); ok { _spec.SetField(password.FieldEmail, field.TypeString, value) } - if value, ok := puo.mutation.Hash(); ok { + if value, ok := _u.mutation.Hash(); ok { _spec.SetField(password.FieldHash, field.TypeBytes, value) } - if value, ok := puo.mutation.Username(); ok { + if value, ok := _u.mutation.Username(); ok { _spec.SetField(password.FieldUsername, field.TypeString, value) } - if value, ok := puo.mutation.UserID(); ok { + if value, ok := _u.mutation.UserID(); ok { _spec.SetField(password.FieldUserID, field.TypeString, value) } - _node = &Password{config: puo.config} + _node = &Password{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, puo.driver, _spec); err != nil { + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{password.Label} } else if sqlgraph.IsConstraintError(err) { @@ -336,6 +336,6 @@ func (puo *PasswordUpdateOne) sqlSave(ctx context.Context) (_node *Password, err } return nil, err } - puo.mutation.done = true + _u.mutation.done = true return _node, nil } diff --git a/storage/ent/db/refreshtoken.go b/storage/ent/db/refreshtoken.go index f116d6846c..12f5910a7a 100644 --- a/storage/ent/db/refreshtoken.go +++ b/storage/ent/db/refreshtoken.go @@ -73,7 +73,7 @@ func (*RefreshToken) scanValues(columns []string) ([]any, error) { // assignValues assigns the values that were returned from sql.Rows (after scanning) // to the RefreshToken fields. -func (rt *RefreshToken) assignValues(columns []string, values []any) error { +func (_m *RefreshToken) 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) } @@ -83,19 +83,19 @@ func (rt *RefreshToken) assignValues(columns []string, values []any) error { if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field id", values[i]) } else if value.Valid { - rt.ID = value.String + _m.ID = value.String } case refreshtoken.FieldClientID: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field client_id", values[i]) } else if value.Valid { - rt.ClientID = value.String + _m.ClientID = value.String } case refreshtoken.FieldScopes: if value, ok := values[i].(*[]byte); !ok { return fmt.Errorf("unexpected type %T for field scopes", values[i]) } else if value != nil && len(*value) > 0 { - if err := json.Unmarshal(*value, &rt.Scopes); err != nil { + if err := json.Unmarshal(*value, &_m.Scopes); err != nil { return fmt.Errorf("unmarshal field scopes: %w", err) } } @@ -103,37 +103,37 @@ func (rt *RefreshToken) assignValues(columns []string, values []any) error { if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field nonce", values[i]) } else if value.Valid { - rt.Nonce = value.String + _m.Nonce = value.String } case refreshtoken.FieldClaimsUserID: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field claims_user_id", values[i]) } else if value.Valid { - rt.ClaimsUserID = value.String + _m.ClaimsUserID = value.String } case refreshtoken.FieldClaimsUsername: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field claims_username", values[i]) } else if value.Valid { - rt.ClaimsUsername = value.String + _m.ClaimsUsername = value.String } case refreshtoken.FieldClaimsEmail: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field claims_email", values[i]) } else if value.Valid { - rt.ClaimsEmail = value.String + _m.ClaimsEmail = value.String } case refreshtoken.FieldClaimsEmailVerified: if value, ok := values[i].(*sql.NullBool); !ok { return fmt.Errorf("unexpected type %T for field claims_email_verified", values[i]) } else if value.Valid { - rt.ClaimsEmailVerified = value.Bool + _m.ClaimsEmailVerified = value.Bool } case refreshtoken.FieldClaimsGroups: if value, ok := values[i].(*[]byte); !ok { return fmt.Errorf("unexpected type %T for field claims_groups", values[i]) } else if value != nil && len(*value) > 0 { - if err := json.Unmarshal(*value, &rt.ClaimsGroups); err != nil { + if err := json.Unmarshal(*value, &_m.ClaimsGroups); err != nil { return fmt.Errorf("unmarshal field claims_groups: %w", err) } } @@ -141,46 +141,46 @@ func (rt *RefreshToken) assignValues(columns []string, values []any) error { if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field claims_preferred_username", values[i]) } else if value.Valid { - rt.ClaimsPreferredUsername = value.String + _m.ClaimsPreferredUsername = value.String } case refreshtoken.FieldConnectorID: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field connector_id", values[i]) } else if value.Valid { - rt.ConnectorID = value.String + _m.ConnectorID = value.String } case refreshtoken.FieldConnectorData: if value, ok := values[i].(*[]byte); !ok { return fmt.Errorf("unexpected type %T for field connector_data", values[i]) } else if value != nil { - rt.ConnectorData = value + _m.ConnectorData = value } case refreshtoken.FieldToken: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field token", values[i]) } else if value.Valid { - rt.Token = value.String + _m.Token = value.String } case refreshtoken.FieldObsoleteToken: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field obsolete_token", values[i]) } else if value.Valid { - rt.ObsoleteToken = value.String + _m.ObsoleteToken = value.String } case refreshtoken.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 { - rt.CreatedAt = value.Time + _m.CreatedAt = value.Time } case refreshtoken.FieldLastUsed: if value, ok := values[i].(*sql.NullTime); !ok { return fmt.Errorf("unexpected type %T for field last_used", values[i]) } else if value.Valid { - rt.LastUsed = value.Time + _m.LastUsed = value.Time } default: - rt.selectValues.Set(columns[i], values[i]) + _m.selectValues.Set(columns[i], values[i]) } } return nil @@ -188,79 +188,79 @@ func (rt *RefreshToken) assignValues(columns []string, values []any) error { // Value returns the ent.Value that was dynamically selected and assigned to the RefreshToken. // This includes values selected through modifiers, order, etc. -func (rt *RefreshToken) Value(name string) (ent.Value, error) { - return rt.selectValues.Get(name) +func (_m *RefreshToken) Value(name string) (ent.Value, error) { + return _m.selectValues.Get(name) } // Update returns a builder for updating this RefreshToken. // Note that you need to call RefreshToken.Unwrap() before calling this method if this RefreshToken // was returned from a transaction, and the transaction was committed or rolled back. -func (rt *RefreshToken) Update() *RefreshTokenUpdateOne { - return NewRefreshTokenClient(rt.config).UpdateOne(rt) +func (_m *RefreshToken) Update() *RefreshTokenUpdateOne { + return NewRefreshTokenClient(_m.config).UpdateOne(_m) } // Unwrap unwraps the RefreshToken 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 (rt *RefreshToken) Unwrap() *RefreshToken { - _tx, ok := rt.config.driver.(*txDriver) +func (_m *RefreshToken) Unwrap() *RefreshToken { + _tx, ok := _m.config.driver.(*txDriver) if !ok { panic("db: RefreshToken is not a transactional entity") } - rt.config.driver = _tx.drv - return rt + _m.config.driver = _tx.drv + return _m } // String implements the fmt.Stringer. -func (rt *RefreshToken) String() string { +func (_m *RefreshToken) String() string { var builder strings.Builder builder.WriteString("RefreshToken(") - builder.WriteString(fmt.Sprintf("id=%v, ", rt.ID)) + builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) builder.WriteString("client_id=") - builder.WriteString(rt.ClientID) + builder.WriteString(_m.ClientID) builder.WriteString(", ") builder.WriteString("scopes=") - builder.WriteString(fmt.Sprintf("%v", rt.Scopes)) + builder.WriteString(fmt.Sprintf("%v", _m.Scopes)) builder.WriteString(", ") builder.WriteString("nonce=") - builder.WriteString(rt.Nonce) + builder.WriteString(_m.Nonce) builder.WriteString(", ") builder.WriteString("claims_user_id=") - builder.WriteString(rt.ClaimsUserID) + builder.WriteString(_m.ClaimsUserID) builder.WriteString(", ") builder.WriteString("claims_username=") - builder.WriteString(rt.ClaimsUsername) + builder.WriteString(_m.ClaimsUsername) builder.WriteString(", ") builder.WriteString("claims_email=") - builder.WriteString(rt.ClaimsEmail) + builder.WriteString(_m.ClaimsEmail) builder.WriteString(", ") builder.WriteString("claims_email_verified=") - builder.WriteString(fmt.Sprintf("%v", rt.ClaimsEmailVerified)) + builder.WriteString(fmt.Sprintf("%v", _m.ClaimsEmailVerified)) builder.WriteString(", ") builder.WriteString("claims_groups=") - builder.WriteString(fmt.Sprintf("%v", rt.ClaimsGroups)) + builder.WriteString(fmt.Sprintf("%v", _m.ClaimsGroups)) builder.WriteString(", ") builder.WriteString("claims_preferred_username=") - builder.WriteString(rt.ClaimsPreferredUsername) + builder.WriteString(_m.ClaimsPreferredUsername) builder.WriteString(", ") builder.WriteString("connector_id=") - builder.WriteString(rt.ConnectorID) + builder.WriteString(_m.ConnectorID) builder.WriteString(", ") - if v := rt.ConnectorData; v != nil { + if v := _m.ConnectorData; v != nil { builder.WriteString("connector_data=") builder.WriteString(fmt.Sprintf("%v", *v)) } builder.WriteString(", ") builder.WriteString("token=") - builder.WriteString(rt.Token) + builder.WriteString(_m.Token) builder.WriteString(", ") builder.WriteString("obsolete_token=") - builder.WriteString(rt.ObsoleteToken) + builder.WriteString(_m.ObsoleteToken) builder.WriteString(", ") builder.WriteString("created_at=") - builder.WriteString(rt.CreatedAt.Format(time.ANSIC)) + builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) builder.WriteString(", ") builder.WriteString("last_used=") - builder.WriteString(rt.LastUsed.Format(time.ANSIC)) + builder.WriteString(_m.LastUsed.Format(time.ANSIC)) builder.WriteByte(')') return builder.String() } diff --git a/storage/ent/db/refreshtoken_create.go b/storage/ent/db/refreshtoken_create.go index 9eb88abe08..2feb6f2c27 100644 --- a/storage/ent/db/refreshtoken_create.go +++ b/storage/ent/db/refreshtoken_create.go @@ -21,155 +21,155 @@ type RefreshTokenCreate struct { } // SetClientID sets the "client_id" field. -func (rtc *RefreshTokenCreate) SetClientID(s string) *RefreshTokenCreate { - rtc.mutation.SetClientID(s) - return rtc +func (_c *RefreshTokenCreate) SetClientID(v string) *RefreshTokenCreate { + _c.mutation.SetClientID(v) + return _c } // SetScopes sets the "scopes" field. -func (rtc *RefreshTokenCreate) SetScopes(s []string) *RefreshTokenCreate { - rtc.mutation.SetScopes(s) - return rtc +func (_c *RefreshTokenCreate) SetScopes(v []string) *RefreshTokenCreate { + _c.mutation.SetScopes(v) + return _c } // SetNonce sets the "nonce" field. -func (rtc *RefreshTokenCreate) SetNonce(s string) *RefreshTokenCreate { - rtc.mutation.SetNonce(s) - return rtc +func (_c *RefreshTokenCreate) SetNonce(v string) *RefreshTokenCreate { + _c.mutation.SetNonce(v) + return _c } // SetClaimsUserID sets the "claims_user_id" field. -func (rtc *RefreshTokenCreate) SetClaimsUserID(s string) *RefreshTokenCreate { - rtc.mutation.SetClaimsUserID(s) - return rtc +func (_c *RefreshTokenCreate) SetClaimsUserID(v string) *RefreshTokenCreate { + _c.mutation.SetClaimsUserID(v) + return _c } // SetClaimsUsername sets the "claims_username" field. -func (rtc *RefreshTokenCreate) SetClaimsUsername(s string) *RefreshTokenCreate { - rtc.mutation.SetClaimsUsername(s) - return rtc +func (_c *RefreshTokenCreate) SetClaimsUsername(v string) *RefreshTokenCreate { + _c.mutation.SetClaimsUsername(v) + return _c } // SetClaimsEmail sets the "claims_email" field. -func (rtc *RefreshTokenCreate) SetClaimsEmail(s string) *RefreshTokenCreate { - rtc.mutation.SetClaimsEmail(s) - return rtc +func (_c *RefreshTokenCreate) SetClaimsEmail(v string) *RefreshTokenCreate { + _c.mutation.SetClaimsEmail(v) + return _c } // SetClaimsEmailVerified sets the "claims_email_verified" field. -func (rtc *RefreshTokenCreate) SetClaimsEmailVerified(b bool) *RefreshTokenCreate { - rtc.mutation.SetClaimsEmailVerified(b) - return rtc +func (_c *RefreshTokenCreate) SetClaimsEmailVerified(v bool) *RefreshTokenCreate { + _c.mutation.SetClaimsEmailVerified(v) + return _c } // SetClaimsGroups sets the "claims_groups" field. -func (rtc *RefreshTokenCreate) SetClaimsGroups(s []string) *RefreshTokenCreate { - rtc.mutation.SetClaimsGroups(s) - return rtc +func (_c *RefreshTokenCreate) SetClaimsGroups(v []string) *RefreshTokenCreate { + _c.mutation.SetClaimsGroups(v) + return _c } // SetClaimsPreferredUsername sets the "claims_preferred_username" field. -func (rtc *RefreshTokenCreate) SetClaimsPreferredUsername(s string) *RefreshTokenCreate { - rtc.mutation.SetClaimsPreferredUsername(s) - return rtc +func (_c *RefreshTokenCreate) SetClaimsPreferredUsername(v string) *RefreshTokenCreate { + _c.mutation.SetClaimsPreferredUsername(v) + return _c } // SetNillableClaimsPreferredUsername sets the "claims_preferred_username" field if the given value is not nil. -func (rtc *RefreshTokenCreate) SetNillableClaimsPreferredUsername(s *string) *RefreshTokenCreate { - if s != nil { - rtc.SetClaimsPreferredUsername(*s) +func (_c *RefreshTokenCreate) SetNillableClaimsPreferredUsername(v *string) *RefreshTokenCreate { + if v != nil { + _c.SetClaimsPreferredUsername(*v) } - return rtc + return _c } // SetConnectorID sets the "connector_id" field. -func (rtc *RefreshTokenCreate) SetConnectorID(s string) *RefreshTokenCreate { - rtc.mutation.SetConnectorID(s) - return rtc +func (_c *RefreshTokenCreate) SetConnectorID(v string) *RefreshTokenCreate { + _c.mutation.SetConnectorID(v) + return _c } // SetConnectorData sets the "connector_data" field. -func (rtc *RefreshTokenCreate) SetConnectorData(b []byte) *RefreshTokenCreate { - rtc.mutation.SetConnectorData(b) - return rtc +func (_c *RefreshTokenCreate) SetConnectorData(v []byte) *RefreshTokenCreate { + _c.mutation.SetConnectorData(v) + return _c } // SetToken sets the "token" field. -func (rtc *RefreshTokenCreate) SetToken(s string) *RefreshTokenCreate { - rtc.mutation.SetToken(s) - return rtc +func (_c *RefreshTokenCreate) SetToken(v string) *RefreshTokenCreate { + _c.mutation.SetToken(v) + return _c } // SetNillableToken sets the "token" field if the given value is not nil. -func (rtc *RefreshTokenCreate) SetNillableToken(s *string) *RefreshTokenCreate { - if s != nil { - rtc.SetToken(*s) +func (_c *RefreshTokenCreate) SetNillableToken(v *string) *RefreshTokenCreate { + if v != nil { + _c.SetToken(*v) } - return rtc + return _c } // SetObsoleteToken sets the "obsolete_token" field. -func (rtc *RefreshTokenCreate) SetObsoleteToken(s string) *RefreshTokenCreate { - rtc.mutation.SetObsoleteToken(s) - return rtc +func (_c *RefreshTokenCreate) SetObsoleteToken(v string) *RefreshTokenCreate { + _c.mutation.SetObsoleteToken(v) + return _c } // SetNillableObsoleteToken sets the "obsolete_token" field if the given value is not nil. -func (rtc *RefreshTokenCreate) SetNillableObsoleteToken(s *string) *RefreshTokenCreate { - if s != nil { - rtc.SetObsoleteToken(*s) +func (_c *RefreshTokenCreate) SetNillableObsoleteToken(v *string) *RefreshTokenCreate { + if v != nil { + _c.SetObsoleteToken(*v) } - return rtc + return _c } // SetCreatedAt sets the "created_at" field. -func (rtc *RefreshTokenCreate) SetCreatedAt(t time.Time) *RefreshTokenCreate { - rtc.mutation.SetCreatedAt(t) - return rtc +func (_c *RefreshTokenCreate) SetCreatedAt(v time.Time) *RefreshTokenCreate { + _c.mutation.SetCreatedAt(v) + return _c } // SetNillableCreatedAt sets the "created_at" field if the given value is not nil. -func (rtc *RefreshTokenCreate) SetNillableCreatedAt(t *time.Time) *RefreshTokenCreate { - if t != nil { - rtc.SetCreatedAt(*t) +func (_c *RefreshTokenCreate) SetNillableCreatedAt(v *time.Time) *RefreshTokenCreate { + if v != nil { + _c.SetCreatedAt(*v) } - return rtc + return _c } // SetLastUsed sets the "last_used" field. -func (rtc *RefreshTokenCreate) SetLastUsed(t time.Time) *RefreshTokenCreate { - rtc.mutation.SetLastUsed(t) - return rtc +func (_c *RefreshTokenCreate) SetLastUsed(v time.Time) *RefreshTokenCreate { + _c.mutation.SetLastUsed(v) + return _c } // SetNillableLastUsed sets the "last_used" field if the given value is not nil. -func (rtc *RefreshTokenCreate) SetNillableLastUsed(t *time.Time) *RefreshTokenCreate { - if t != nil { - rtc.SetLastUsed(*t) +func (_c *RefreshTokenCreate) SetNillableLastUsed(v *time.Time) *RefreshTokenCreate { + if v != nil { + _c.SetLastUsed(*v) } - return rtc + return _c } // SetID sets the "id" field. -func (rtc *RefreshTokenCreate) SetID(s string) *RefreshTokenCreate { - rtc.mutation.SetID(s) - return rtc +func (_c *RefreshTokenCreate) SetID(v string) *RefreshTokenCreate { + _c.mutation.SetID(v) + return _c } // Mutation returns the RefreshTokenMutation object of the builder. -func (rtc *RefreshTokenCreate) Mutation() *RefreshTokenMutation { - return rtc.mutation +func (_c *RefreshTokenCreate) Mutation() *RefreshTokenMutation { + return _c.mutation } // Save creates the RefreshToken in the database. -func (rtc *RefreshTokenCreate) Save(ctx context.Context) (*RefreshToken, error) { - rtc.defaults() - return withHooks(ctx, rtc.sqlSave, rtc.mutation, rtc.hooks) +func (_c *RefreshTokenCreate) Save(ctx context.Context) (*RefreshToken, error) { + _c.defaults() + return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) } // SaveX calls Save and panics if Save returns an error. -func (rtc *RefreshTokenCreate) SaveX(ctx context.Context) *RefreshToken { - v, err := rtc.Save(ctx) +func (_c *RefreshTokenCreate) SaveX(ctx context.Context) *RefreshToken { + v, err := _c.Save(ctx) if err != nil { panic(err) } @@ -177,111 +177,111 @@ func (rtc *RefreshTokenCreate) SaveX(ctx context.Context) *RefreshToken { } // Exec executes the query. -func (rtc *RefreshTokenCreate) Exec(ctx context.Context) error { - _, err := rtc.Save(ctx) +func (_c *RefreshTokenCreate) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (rtc *RefreshTokenCreate) ExecX(ctx context.Context) { - if err := rtc.Exec(ctx); err != nil { +func (_c *RefreshTokenCreate) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { panic(err) } } // defaults sets the default values of the builder before save. -func (rtc *RefreshTokenCreate) defaults() { - if _, ok := rtc.mutation.ClaimsPreferredUsername(); !ok { +func (_c *RefreshTokenCreate) defaults() { + if _, ok := _c.mutation.ClaimsPreferredUsername(); !ok { v := refreshtoken.DefaultClaimsPreferredUsername - rtc.mutation.SetClaimsPreferredUsername(v) + _c.mutation.SetClaimsPreferredUsername(v) } - if _, ok := rtc.mutation.Token(); !ok { + if _, ok := _c.mutation.Token(); !ok { v := refreshtoken.DefaultToken - rtc.mutation.SetToken(v) + _c.mutation.SetToken(v) } - if _, ok := rtc.mutation.ObsoleteToken(); !ok { + if _, ok := _c.mutation.ObsoleteToken(); !ok { v := refreshtoken.DefaultObsoleteToken - rtc.mutation.SetObsoleteToken(v) + _c.mutation.SetObsoleteToken(v) } - if _, ok := rtc.mutation.CreatedAt(); !ok { + if _, ok := _c.mutation.CreatedAt(); !ok { v := refreshtoken.DefaultCreatedAt() - rtc.mutation.SetCreatedAt(v) + _c.mutation.SetCreatedAt(v) } - if _, ok := rtc.mutation.LastUsed(); !ok { + if _, ok := _c.mutation.LastUsed(); !ok { v := refreshtoken.DefaultLastUsed() - rtc.mutation.SetLastUsed(v) + _c.mutation.SetLastUsed(v) } } // check runs all checks and user-defined validators on the builder. -func (rtc *RefreshTokenCreate) check() error { - if _, ok := rtc.mutation.ClientID(); !ok { +func (_c *RefreshTokenCreate) check() error { + if _, ok := _c.mutation.ClientID(); !ok { return &ValidationError{Name: "client_id", err: errors.New(`db: missing required field "RefreshToken.client_id"`)} } - if v, ok := rtc.mutation.ClientID(); ok { + if v, ok := _c.mutation.ClientID(); ok { if err := refreshtoken.ClientIDValidator(v); err != nil { return &ValidationError{Name: "client_id", err: fmt.Errorf(`db: validator failed for field "RefreshToken.client_id": %w`, err)} } } - if _, ok := rtc.mutation.Nonce(); !ok { + if _, ok := _c.mutation.Nonce(); !ok { return &ValidationError{Name: "nonce", err: errors.New(`db: missing required field "RefreshToken.nonce"`)} } - if v, ok := rtc.mutation.Nonce(); ok { + if v, ok := _c.mutation.Nonce(); ok { if err := refreshtoken.NonceValidator(v); err != nil { return &ValidationError{Name: "nonce", err: fmt.Errorf(`db: validator failed for field "RefreshToken.nonce": %w`, err)} } } - if _, ok := rtc.mutation.ClaimsUserID(); !ok { + if _, ok := _c.mutation.ClaimsUserID(); !ok { return &ValidationError{Name: "claims_user_id", err: errors.New(`db: missing required field "RefreshToken.claims_user_id"`)} } - if v, ok := rtc.mutation.ClaimsUserID(); ok { + if v, ok := _c.mutation.ClaimsUserID(); ok { if err := refreshtoken.ClaimsUserIDValidator(v); err != nil { return &ValidationError{Name: "claims_user_id", err: fmt.Errorf(`db: validator failed for field "RefreshToken.claims_user_id": %w`, err)} } } - if _, ok := rtc.mutation.ClaimsUsername(); !ok { + if _, ok := _c.mutation.ClaimsUsername(); !ok { return &ValidationError{Name: "claims_username", err: errors.New(`db: missing required field "RefreshToken.claims_username"`)} } - if v, ok := rtc.mutation.ClaimsUsername(); ok { + if v, ok := _c.mutation.ClaimsUsername(); ok { if err := refreshtoken.ClaimsUsernameValidator(v); err != nil { return &ValidationError{Name: "claims_username", err: fmt.Errorf(`db: validator failed for field "RefreshToken.claims_username": %w`, err)} } } - if _, ok := rtc.mutation.ClaimsEmail(); !ok { + if _, ok := _c.mutation.ClaimsEmail(); !ok { return &ValidationError{Name: "claims_email", err: errors.New(`db: missing required field "RefreshToken.claims_email"`)} } - if v, ok := rtc.mutation.ClaimsEmail(); ok { + if v, ok := _c.mutation.ClaimsEmail(); ok { if err := refreshtoken.ClaimsEmailValidator(v); err != nil { return &ValidationError{Name: "claims_email", err: fmt.Errorf(`db: validator failed for field "RefreshToken.claims_email": %w`, err)} } } - if _, ok := rtc.mutation.ClaimsEmailVerified(); !ok { + if _, ok := _c.mutation.ClaimsEmailVerified(); !ok { return &ValidationError{Name: "claims_email_verified", err: errors.New(`db: missing required field "RefreshToken.claims_email_verified"`)} } - if _, ok := rtc.mutation.ClaimsPreferredUsername(); !ok { + if _, ok := _c.mutation.ClaimsPreferredUsername(); !ok { return &ValidationError{Name: "claims_preferred_username", err: errors.New(`db: missing required field "RefreshToken.claims_preferred_username"`)} } - if _, ok := rtc.mutation.ConnectorID(); !ok { + if _, ok := _c.mutation.ConnectorID(); !ok { return &ValidationError{Name: "connector_id", err: errors.New(`db: missing required field "RefreshToken.connector_id"`)} } - if v, ok := rtc.mutation.ConnectorID(); ok { + if v, ok := _c.mutation.ConnectorID(); ok { if err := refreshtoken.ConnectorIDValidator(v); err != nil { return &ValidationError{Name: "connector_id", err: fmt.Errorf(`db: validator failed for field "RefreshToken.connector_id": %w`, err)} } } - if _, ok := rtc.mutation.Token(); !ok { + if _, ok := _c.mutation.Token(); !ok { return &ValidationError{Name: "token", err: errors.New(`db: missing required field "RefreshToken.token"`)} } - if _, ok := rtc.mutation.ObsoleteToken(); !ok { + if _, ok := _c.mutation.ObsoleteToken(); !ok { return &ValidationError{Name: "obsolete_token", err: errors.New(`db: missing required field "RefreshToken.obsolete_token"`)} } - if _, ok := rtc.mutation.CreatedAt(); !ok { + if _, ok := _c.mutation.CreatedAt(); !ok { return &ValidationError{Name: "created_at", err: errors.New(`db: missing required field "RefreshToken.created_at"`)} } - if _, ok := rtc.mutation.LastUsed(); !ok { + if _, ok := _c.mutation.LastUsed(); !ok { return &ValidationError{Name: "last_used", err: errors.New(`db: missing required field "RefreshToken.last_used"`)} } - if v, ok := rtc.mutation.ID(); ok { + if v, ok := _c.mutation.ID(); ok { if err := refreshtoken.IDValidator(v); err != nil { return &ValidationError{Name: "id", err: fmt.Errorf(`db: validator failed for field "RefreshToken.id": %w`, err)} } @@ -289,12 +289,12 @@ func (rtc *RefreshTokenCreate) check() error { return nil } -func (rtc *RefreshTokenCreate) sqlSave(ctx context.Context) (*RefreshToken, error) { - if err := rtc.check(); err != nil { +func (_c *RefreshTokenCreate) sqlSave(ctx context.Context) (*RefreshToken, error) { + if err := _c.check(); err != nil { return nil, err } - _node, _spec := rtc.createSpec() - if err := sqlgraph.CreateNode(ctx, rtc.driver, _spec); err != nil { + _node, _spec := _c.createSpec() + if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { if sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } @@ -307,77 +307,77 @@ func (rtc *RefreshTokenCreate) sqlSave(ctx context.Context) (*RefreshToken, erro return nil, fmt.Errorf("unexpected RefreshToken.ID type: %T", _spec.ID.Value) } } - rtc.mutation.id = &_node.ID - rtc.mutation.done = true + _c.mutation.id = &_node.ID + _c.mutation.done = true return _node, nil } -func (rtc *RefreshTokenCreate) createSpec() (*RefreshToken, *sqlgraph.CreateSpec) { +func (_c *RefreshTokenCreate) createSpec() (*RefreshToken, *sqlgraph.CreateSpec) { var ( - _node = &RefreshToken{config: rtc.config} + _node = &RefreshToken{config: _c.config} _spec = sqlgraph.NewCreateSpec(refreshtoken.Table, sqlgraph.NewFieldSpec(refreshtoken.FieldID, field.TypeString)) ) - if id, ok := rtc.mutation.ID(); ok { + if id, ok := _c.mutation.ID(); ok { _node.ID = id _spec.ID.Value = id } - if value, ok := rtc.mutation.ClientID(); ok { + if value, ok := _c.mutation.ClientID(); ok { _spec.SetField(refreshtoken.FieldClientID, field.TypeString, value) _node.ClientID = value } - if value, ok := rtc.mutation.Scopes(); ok { + if value, ok := _c.mutation.Scopes(); ok { _spec.SetField(refreshtoken.FieldScopes, field.TypeJSON, value) _node.Scopes = value } - if value, ok := rtc.mutation.Nonce(); ok { + if value, ok := _c.mutation.Nonce(); ok { _spec.SetField(refreshtoken.FieldNonce, field.TypeString, value) _node.Nonce = value } - if value, ok := rtc.mutation.ClaimsUserID(); ok { + if value, ok := _c.mutation.ClaimsUserID(); ok { _spec.SetField(refreshtoken.FieldClaimsUserID, field.TypeString, value) _node.ClaimsUserID = value } - if value, ok := rtc.mutation.ClaimsUsername(); ok { + if value, ok := _c.mutation.ClaimsUsername(); ok { _spec.SetField(refreshtoken.FieldClaimsUsername, field.TypeString, value) _node.ClaimsUsername = value } - if value, ok := rtc.mutation.ClaimsEmail(); ok { + if value, ok := _c.mutation.ClaimsEmail(); ok { _spec.SetField(refreshtoken.FieldClaimsEmail, field.TypeString, value) _node.ClaimsEmail = value } - if value, ok := rtc.mutation.ClaimsEmailVerified(); ok { + if value, ok := _c.mutation.ClaimsEmailVerified(); ok { _spec.SetField(refreshtoken.FieldClaimsEmailVerified, field.TypeBool, value) _node.ClaimsEmailVerified = value } - if value, ok := rtc.mutation.ClaimsGroups(); ok { + if value, ok := _c.mutation.ClaimsGroups(); ok { _spec.SetField(refreshtoken.FieldClaimsGroups, field.TypeJSON, value) _node.ClaimsGroups = value } - if value, ok := rtc.mutation.ClaimsPreferredUsername(); ok { + if value, ok := _c.mutation.ClaimsPreferredUsername(); ok { _spec.SetField(refreshtoken.FieldClaimsPreferredUsername, field.TypeString, value) _node.ClaimsPreferredUsername = value } - if value, ok := rtc.mutation.ConnectorID(); ok { + if value, ok := _c.mutation.ConnectorID(); ok { _spec.SetField(refreshtoken.FieldConnectorID, field.TypeString, value) _node.ConnectorID = value } - if value, ok := rtc.mutation.ConnectorData(); ok { + if value, ok := _c.mutation.ConnectorData(); ok { _spec.SetField(refreshtoken.FieldConnectorData, field.TypeBytes, value) _node.ConnectorData = &value } - if value, ok := rtc.mutation.Token(); ok { + if value, ok := _c.mutation.Token(); ok { _spec.SetField(refreshtoken.FieldToken, field.TypeString, value) _node.Token = value } - if value, ok := rtc.mutation.ObsoleteToken(); ok { + if value, ok := _c.mutation.ObsoleteToken(); ok { _spec.SetField(refreshtoken.FieldObsoleteToken, field.TypeString, value) _node.ObsoleteToken = value } - if value, ok := rtc.mutation.CreatedAt(); ok { + if value, ok := _c.mutation.CreatedAt(); ok { _spec.SetField(refreshtoken.FieldCreatedAt, field.TypeTime, value) _node.CreatedAt = value } - if value, ok := rtc.mutation.LastUsed(); ok { + if value, ok := _c.mutation.LastUsed(); ok { _spec.SetField(refreshtoken.FieldLastUsed, field.TypeTime, value) _node.LastUsed = value } @@ -392,16 +392,16 @@ type RefreshTokenCreateBulk struct { } // Save creates the RefreshToken entities in the database. -func (rtcb *RefreshTokenCreateBulk) Save(ctx context.Context) ([]*RefreshToken, error) { - if rtcb.err != nil { - return nil, rtcb.err - } - specs := make([]*sqlgraph.CreateSpec, len(rtcb.builders)) - nodes := make([]*RefreshToken, len(rtcb.builders)) - mutators := make([]Mutator, len(rtcb.builders)) - for i := range rtcb.builders { +func (_c *RefreshTokenCreateBulk) Save(ctx context.Context) ([]*RefreshToken, error) { + if _c.err != nil { + return nil, _c.err + } + specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) + nodes := make([]*RefreshToken, len(_c.builders)) + mutators := make([]Mutator, len(_c.builders)) + for i := range _c.builders { func(i int, root context.Context) { - builder := rtcb.builders[i] + builder := _c.builders[i] builder.defaults() var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { mutation, ok := m.(*RefreshTokenMutation) @@ -415,11 +415,11 @@ func (rtcb *RefreshTokenCreateBulk) Save(ctx context.Context) ([]*RefreshToken, var err error nodes[i], specs[i] = builder.createSpec() if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, rtcb.builders[i+1].mutation) + _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, rtcb.driver, spec); err != nil { + if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { if sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } @@ -439,7 +439,7 @@ func (rtcb *RefreshTokenCreateBulk) Save(ctx context.Context) ([]*RefreshToken, }(i, ctx) } if len(mutators) > 0 { - if _, err := mutators[0].Mutate(ctx, rtcb.builders[0].mutation); err != nil { + if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { return nil, err } } @@ -447,8 +447,8 @@ func (rtcb *RefreshTokenCreateBulk) Save(ctx context.Context) ([]*RefreshToken, } // SaveX is like Save, but panics if an error occurs. -func (rtcb *RefreshTokenCreateBulk) SaveX(ctx context.Context) []*RefreshToken { - v, err := rtcb.Save(ctx) +func (_c *RefreshTokenCreateBulk) SaveX(ctx context.Context) []*RefreshToken { + v, err := _c.Save(ctx) if err != nil { panic(err) } @@ -456,14 +456,14 @@ func (rtcb *RefreshTokenCreateBulk) SaveX(ctx context.Context) []*RefreshToken { } // Exec executes the query. -func (rtcb *RefreshTokenCreateBulk) Exec(ctx context.Context) error { - _, err := rtcb.Save(ctx) +func (_c *RefreshTokenCreateBulk) Exec(ctx context.Context) error { + _, err := _c.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (rtcb *RefreshTokenCreateBulk) ExecX(ctx context.Context) { - if err := rtcb.Exec(ctx); err != nil { +func (_c *RefreshTokenCreateBulk) ExecX(ctx context.Context) { + if err := _c.Exec(ctx); err != nil { panic(err) } } diff --git a/storage/ent/db/refreshtoken_delete.go b/storage/ent/db/refreshtoken_delete.go index 78c8cbc6de..3e85fd5bd6 100644 --- a/storage/ent/db/refreshtoken_delete.go +++ b/storage/ent/db/refreshtoken_delete.go @@ -20,56 +20,56 @@ type RefreshTokenDelete struct { } // Where appends a list predicates to the RefreshTokenDelete builder. -func (rtd *RefreshTokenDelete) Where(ps ...predicate.RefreshToken) *RefreshTokenDelete { - rtd.mutation.Where(ps...) - return rtd +func (_d *RefreshTokenDelete) Where(ps ...predicate.RefreshToken) *RefreshTokenDelete { + _d.mutation.Where(ps...) + return _d } // Exec executes the deletion query and returns how many vertices were deleted. -func (rtd *RefreshTokenDelete) Exec(ctx context.Context) (int, error) { - return withHooks(ctx, rtd.sqlExec, rtd.mutation, rtd.hooks) +func (_d *RefreshTokenDelete) Exec(ctx context.Context) (int, error) { + return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) } // ExecX is like Exec, but panics if an error occurs. -func (rtd *RefreshTokenDelete) ExecX(ctx context.Context) int { - n, err := rtd.Exec(ctx) +func (_d *RefreshTokenDelete) ExecX(ctx context.Context) int { + n, err := _d.Exec(ctx) if err != nil { panic(err) } return n } -func (rtd *RefreshTokenDelete) sqlExec(ctx context.Context) (int, error) { +func (_d *RefreshTokenDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(refreshtoken.Table, sqlgraph.NewFieldSpec(refreshtoken.FieldID, field.TypeString)) - if ps := rtd.mutation.predicates; len(ps) > 0 { + if ps := _d.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - affected, err := sqlgraph.DeleteNodes(ctx, rtd.driver, _spec) + affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) if err != nil && sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } - rtd.mutation.done = true + _d.mutation.done = true return affected, err } // RefreshTokenDeleteOne is the builder for deleting a single RefreshToken entity. type RefreshTokenDeleteOne struct { - rtd *RefreshTokenDelete + _d *RefreshTokenDelete } // Where appends a list predicates to the RefreshTokenDelete builder. -func (rtdo *RefreshTokenDeleteOne) Where(ps ...predicate.RefreshToken) *RefreshTokenDeleteOne { - rtdo.rtd.mutation.Where(ps...) - return rtdo +func (_d *RefreshTokenDeleteOne) Where(ps ...predicate.RefreshToken) *RefreshTokenDeleteOne { + _d._d.mutation.Where(ps...) + return _d } // Exec executes the deletion query. -func (rtdo *RefreshTokenDeleteOne) Exec(ctx context.Context) error { - n, err := rtdo.rtd.Exec(ctx) +func (_d *RefreshTokenDeleteOne) Exec(ctx context.Context) error { + n, err := _d._d.Exec(ctx) switch { case err != nil: return err @@ -81,8 +81,8 @@ func (rtdo *RefreshTokenDeleteOne) Exec(ctx context.Context) error { } // ExecX is like Exec, but panics if an error occurs. -func (rtdo *RefreshTokenDeleteOne) ExecX(ctx context.Context) { - if err := rtdo.Exec(ctx); err != nil { +func (_d *RefreshTokenDeleteOne) ExecX(ctx context.Context) { + if err := _d.Exec(ctx); err != nil { panic(err) } } diff --git a/storage/ent/db/refreshtoken_query.go b/storage/ent/db/refreshtoken_query.go index 29713182b7..e6f399b0e1 100644 --- a/storage/ent/db/refreshtoken_query.go +++ b/storage/ent/db/refreshtoken_query.go @@ -28,40 +28,40 @@ type RefreshTokenQuery struct { } // Where adds a new predicate for the RefreshTokenQuery builder. -func (rtq *RefreshTokenQuery) Where(ps ...predicate.RefreshToken) *RefreshTokenQuery { - rtq.predicates = append(rtq.predicates, ps...) - return rtq +func (_q *RefreshTokenQuery) Where(ps ...predicate.RefreshToken) *RefreshTokenQuery { + _q.predicates = append(_q.predicates, ps...) + return _q } // Limit the number of records to be returned by this query. -func (rtq *RefreshTokenQuery) Limit(limit int) *RefreshTokenQuery { - rtq.ctx.Limit = &limit - return rtq +func (_q *RefreshTokenQuery) Limit(limit int) *RefreshTokenQuery { + _q.ctx.Limit = &limit + return _q } // Offset to start from. -func (rtq *RefreshTokenQuery) Offset(offset int) *RefreshTokenQuery { - rtq.ctx.Offset = &offset - return rtq +func (_q *RefreshTokenQuery) Offset(offset int) *RefreshTokenQuery { + _q.ctx.Offset = &offset + return _q } // Unique configures the query builder to filter duplicate records on query. // By default, unique is set to true, and can be disabled using this method. -func (rtq *RefreshTokenQuery) Unique(unique bool) *RefreshTokenQuery { - rtq.ctx.Unique = &unique - return rtq +func (_q *RefreshTokenQuery) Unique(unique bool) *RefreshTokenQuery { + _q.ctx.Unique = &unique + return _q } // Order specifies how the records should be ordered. -func (rtq *RefreshTokenQuery) Order(o ...refreshtoken.OrderOption) *RefreshTokenQuery { - rtq.order = append(rtq.order, o...) - return rtq +func (_q *RefreshTokenQuery) Order(o ...refreshtoken.OrderOption) *RefreshTokenQuery { + _q.order = append(_q.order, o...) + return _q } // First returns the first RefreshToken entity from the query. // Returns a *NotFoundError when no RefreshToken was found. -func (rtq *RefreshTokenQuery) First(ctx context.Context) (*RefreshToken, error) { - nodes, err := rtq.Limit(1).All(setContextOp(ctx, rtq.ctx, ent.OpQueryFirst)) +func (_q *RefreshTokenQuery) First(ctx context.Context) (*RefreshToken, error) { + nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) if err != nil { return nil, err } @@ -72,8 +72,8 @@ func (rtq *RefreshTokenQuery) First(ctx context.Context) (*RefreshToken, error) } // FirstX is like First, but panics if an error occurs. -func (rtq *RefreshTokenQuery) FirstX(ctx context.Context) *RefreshToken { - node, err := rtq.First(ctx) +func (_q *RefreshTokenQuery) FirstX(ctx context.Context) *RefreshToken { + node, err := _q.First(ctx) if err != nil && !IsNotFound(err) { panic(err) } @@ -82,9 +82,9 @@ func (rtq *RefreshTokenQuery) FirstX(ctx context.Context) *RefreshToken { // FirstID returns the first RefreshToken ID from the query. // Returns a *NotFoundError when no RefreshToken ID was found. -func (rtq *RefreshTokenQuery) FirstID(ctx context.Context) (id string, err error) { +func (_q *RefreshTokenQuery) FirstID(ctx context.Context) (id string, err error) { var ids []string - if ids, err = rtq.Limit(1).IDs(setContextOp(ctx, rtq.ctx, ent.OpQueryFirstID)); err != nil { + if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { return } if len(ids) == 0 { @@ -95,8 +95,8 @@ func (rtq *RefreshTokenQuery) FirstID(ctx context.Context) (id string, err error } // FirstIDX is like FirstID, but panics if an error occurs. -func (rtq *RefreshTokenQuery) FirstIDX(ctx context.Context) string { - id, err := rtq.FirstID(ctx) +func (_q *RefreshTokenQuery) FirstIDX(ctx context.Context) string { + id, err := _q.FirstID(ctx) if err != nil && !IsNotFound(err) { panic(err) } @@ -106,8 +106,8 @@ func (rtq *RefreshTokenQuery) FirstIDX(ctx context.Context) string { // Only returns a single RefreshToken entity found by the query, ensuring it only returns one. // Returns a *NotSingularError when more than one RefreshToken entity is found. // Returns a *NotFoundError when no RefreshToken entities are found. -func (rtq *RefreshTokenQuery) Only(ctx context.Context) (*RefreshToken, error) { - nodes, err := rtq.Limit(2).All(setContextOp(ctx, rtq.ctx, ent.OpQueryOnly)) +func (_q *RefreshTokenQuery) Only(ctx context.Context) (*RefreshToken, error) { + nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) if err != nil { return nil, err } @@ -122,8 +122,8 @@ func (rtq *RefreshTokenQuery) Only(ctx context.Context) (*RefreshToken, error) { } // OnlyX is like Only, but panics if an error occurs. -func (rtq *RefreshTokenQuery) OnlyX(ctx context.Context) *RefreshToken { - node, err := rtq.Only(ctx) +func (_q *RefreshTokenQuery) OnlyX(ctx context.Context) *RefreshToken { + node, err := _q.Only(ctx) if err != nil { panic(err) } @@ -133,9 +133,9 @@ func (rtq *RefreshTokenQuery) OnlyX(ctx context.Context) *RefreshToken { // OnlyID is like Only, but returns the only RefreshToken ID in the query. // Returns a *NotSingularError when more than one RefreshToken ID is found. // Returns a *NotFoundError when no entities are found. -func (rtq *RefreshTokenQuery) OnlyID(ctx context.Context) (id string, err error) { +func (_q *RefreshTokenQuery) OnlyID(ctx context.Context) (id string, err error) { var ids []string - if ids, err = rtq.Limit(2).IDs(setContextOp(ctx, rtq.ctx, ent.OpQueryOnlyID)); err != nil { + if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { return } switch len(ids) { @@ -150,8 +150,8 @@ func (rtq *RefreshTokenQuery) OnlyID(ctx context.Context) (id string, err error) } // OnlyIDX is like OnlyID, but panics if an error occurs. -func (rtq *RefreshTokenQuery) OnlyIDX(ctx context.Context) string { - id, err := rtq.OnlyID(ctx) +func (_q *RefreshTokenQuery) OnlyIDX(ctx context.Context) string { + id, err := _q.OnlyID(ctx) if err != nil { panic(err) } @@ -159,18 +159,18 @@ func (rtq *RefreshTokenQuery) OnlyIDX(ctx context.Context) string { } // All executes the query and returns a list of RefreshTokens. -func (rtq *RefreshTokenQuery) All(ctx context.Context) ([]*RefreshToken, error) { - ctx = setContextOp(ctx, rtq.ctx, ent.OpQueryAll) - if err := rtq.prepareQuery(ctx); err != nil { +func (_q *RefreshTokenQuery) All(ctx context.Context) ([]*RefreshToken, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) + if err := _q.prepareQuery(ctx); err != nil { return nil, err } qr := querierAll[[]*RefreshToken, *RefreshTokenQuery]() - return withInterceptors[[]*RefreshToken](ctx, rtq, qr, rtq.inters) + return withInterceptors[[]*RefreshToken](ctx, _q, qr, _q.inters) } // AllX is like All, but panics if an error occurs. -func (rtq *RefreshTokenQuery) AllX(ctx context.Context) []*RefreshToken { - nodes, err := rtq.All(ctx) +func (_q *RefreshTokenQuery) AllX(ctx context.Context) []*RefreshToken { + nodes, err := _q.All(ctx) if err != nil { panic(err) } @@ -178,20 +178,20 @@ func (rtq *RefreshTokenQuery) AllX(ctx context.Context) []*RefreshToken { } // IDs executes the query and returns a list of RefreshToken IDs. -func (rtq *RefreshTokenQuery) IDs(ctx context.Context) (ids []string, err error) { - if rtq.ctx.Unique == nil && rtq.path != nil { - rtq.Unique(true) +func (_q *RefreshTokenQuery) IDs(ctx context.Context) (ids []string, err error) { + if _q.ctx.Unique == nil && _q.path != nil { + _q.Unique(true) } - ctx = setContextOp(ctx, rtq.ctx, ent.OpQueryIDs) - if err = rtq.Select(refreshtoken.FieldID).Scan(ctx, &ids); err != nil { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) + if err = _q.Select(refreshtoken.FieldID).Scan(ctx, &ids); err != nil { return nil, err } return ids, nil } // IDsX is like IDs, but panics if an error occurs. -func (rtq *RefreshTokenQuery) IDsX(ctx context.Context) []string { - ids, err := rtq.IDs(ctx) +func (_q *RefreshTokenQuery) IDsX(ctx context.Context) []string { + ids, err := _q.IDs(ctx) if err != nil { panic(err) } @@ -199,17 +199,17 @@ func (rtq *RefreshTokenQuery) IDsX(ctx context.Context) []string { } // Count returns the count of the given query. -func (rtq *RefreshTokenQuery) Count(ctx context.Context) (int, error) { - ctx = setContextOp(ctx, rtq.ctx, ent.OpQueryCount) - if err := rtq.prepareQuery(ctx); err != nil { +func (_q *RefreshTokenQuery) Count(ctx context.Context) (int, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) + if err := _q.prepareQuery(ctx); err != nil { return 0, err } - return withInterceptors[int](ctx, rtq, querierCount[*RefreshTokenQuery](), rtq.inters) + return withInterceptors[int](ctx, _q, querierCount[*RefreshTokenQuery](), _q.inters) } // CountX is like Count, but panics if an error occurs. -func (rtq *RefreshTokenQuery) CountX(ctx context.Context) int { - count, err := rtq.Count(ctx) +func (_q *RefreshTokenQuery) CountX(ctx context.Context) int { + count, err := _q.Count(ctx) if err != nil { panic(err) } @@ -217,9 +217,9 @@ func (rtq *RefreshTokenQuery) CountX(ctx context.Context) int { } // Exist returns true if the query has elements in the graph. -func (rtq *RefreshTokenQuery) Exist(ctx context.Context) (bool, error) { - ctx = setContextOp(ctx, rtq.ctx, ent.OpQueryExist) - switch _, err := rtq.FirstID(ctx); { +func (_q *RefreshTokenQuery) Exist(ctx context.Context) (bool, error) { + ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) + switch _, err := _q.FirstID(ctx); { case IsNotFound(err): return false, nil case err != nil: @@ -230,8 +230,8 @@ func (rtq *RefreshTokenQuery) Exist(ctx context.Context) (bool, error) { } // ExistX is like Exist, but panics if an error occurs. -func (rtq *RefreshTokenQuery) ExistX(ctx context.Context) bool { - exist, err := rtq.Exist(ctx) +func (_q *RefreshTokenQuery) ExistX(ctx context.Context) bool { + exist, err := _q.Exist(ctx) if err != nil { panic(err) } @@ -240,19 +240,19 @@ func (rtq *RefreshTokenQuery) ExistX(ctx context.Context) bool { // Clone returns a duplicate of the RefreshTokenQuery builder, including all associated steps. It can be // used to prepare common query builders and use them differently after the clone is made. -func (rtq *RefreshTokenQuery) Clone() *RefreshTokenQuery { - if rtq == nil { +func (_q *RefreshTokenQuery) Clone() *RefreshTokenQuery { + if _q == nil { return nil } return &RefreshTokenQuery{ - config: rtq.config, - ctx: rtq.ctx.Clone(), - order: append([]refreshtoken.OrderOption{}, rtq.order...), - inters: append([]Interceptor{}, rtq.inters...), - predicates: append([]predicate.RefreshToken{}, rtq.predicates...), + config: _q.config, + ctx: _q.ctx.Clone(), + order: append([]refreshtoken.OrderOption{}, _q.order...), + inters: append([]Interceptor{}, _q.inters...), + predicates: append([]predicate.RefreshToken{}, _q.predicates...), // clone intermediate query. - sql: rtq.sql.Clone(), - path: rtq.path, + sql: _q.sql.Clone(), + path: _q.path, } } @@ -270,10 +270,10 @@ func (rtq *RefreshTokenQuery) Clone() *RefreshTokenQuery { // GroupBy(refreshtoken.FieldClientID). // Aggregate(db.Count()). // Scan(ctx, &v) -func (rtq *RefreshTokenQuery) GroupBy(field string, fields ...string) *RefreshTokenGroupBy { - rtq.ctx.Fields = append([]string{field}, fields...) - grbuild := &RefreshTokenGroupBy{build: rtq} - grbuild.flds = &rtq.ctx.Fields +func (_q *RefreshTokenQuery) GroupBy(field string, fields ...string) *RefreshTokenGroupBy { + _q.ctx.Fields = append([]string{field}, fields...) + grbuild := &RefreshTokenGroupBy{build: _q} + grbuild.flds = &_q.ctx.Fields grbuild.label = refreshtoken.Label grbuild.scan = grbuild.Scan return grbuild @@ -291,62 +291,62 @@ func (rtq *RefreshTokenQuery) GroupBy(field string, fields ...string) *RefreshTo // client.RefreshToken.Query(). // Select(refreshtoken.FieldClientID). // Scan(ctx, &v) -func (rtq *RefreshTokenQuery) Select(fields ...string) *RefreshTokenSelect { - rtq.ctx.Fields = append(rtq.ctx.Fields, fields...) - sbuild := &RefreshTokenSelect{RefreshTokenQuery: rtq} +func (_q *RefreshTokenQuery) Select(fields ...string) *RefreshTokenSelect { + _q.ctx.Fields = append(_q.ctx.Fields, fields...) + sbuild := &RefreshTokenSelect{RefreshTokenQuery: _q} sbuild.label = refreshtoken.Label - sbuild.flds, sbuild.scan = &rtq.ctx.Fields, sbuild.Scan + sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan return sbuild } // Aggregate returns a RefreshTokenSelect configured with the given aggregations. -func (rtq *RefreshTokenQuery) Aggregate(fns ...AggregateFunc) *RefreshTokenSelect { - return rtq.Select().Aggregate(fns...) +func (_q *RefreshTokenQuery) Aggregate(fns ...AggregateFunc) *RefreshTokenSelect { + return _q.Select().Aggregate(fns...) } -func (rtq *RefreshTokenQuery) prepareQuery(ctx context.Context) error { - for _, inter := range rtq.inters { +func (_q *RefreshTokenQuery) prepareQuery(ctx context.Context) error { + for _, inter := range _q.inters { if inter == nil { return fmt.Errorf("db: uninitialized interceptor (forgotten import db/runtime?)") } if trv, ok := inter.(Traverser); ok { - if err := trv.Traverse(ctx, rtq); err != nil { + if err := trv.Traverse(ctx, _q); err != nil { return err } } } - for _, f := range rtq.ctx.Fields { + for _, f := range _q.ctx.Fields { if !refreshtoken.ValidColumn(f) { return &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)} } } - if rtq.path != nil { - prev, err := rtq.path(ctx) + if _q.path != nil { + prev, err := _q.path(ctx) if err != nil { return err } - rtq.sql = prev + _q.sql = prev } return nil } -func (rtq *RefreshTokenQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*RefreshToken, error) { +func (_q *RefreshTokenQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*RefreshToken, error) { var ( nodes = []*RefreshToken{} - _spec = rtq.querySpec() + _spec = _q.querySpec() ) _spec.ScanValues = func(columns []string) ([]any, error) { return (*RefreshToken).scanValues(nil, columns) } _spec.Assign = func(columns []string, values []any) error { - node := &RefreshToken{config: rtq.config} + node := &RefreshToken{config: _q.config} nodes = append(nodes, node) return node.assignValues(columns, values) } for i := range hooks { hooks[i](ctx, _spec) } - if err := sqlgraph.QueryNodes(ctx, rtq.driver, _spec); err != nil { + if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { return nil, err } if len(nodes) == 0 { @@ -355,24 +355,24 @@ func (rtq *RefreshTokenQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([ return nodes, nil } -func (rtq *RefreshTokenQuery) sqlCount(ctx context.Context) (int, error) { - _spec := rtq.querySpec() - _spec.Node.Columns = rtq.ctx.Fields - if len(rtq.ctx.Fields) > 0 { - _spec.Unique = rtq.ctx.Unique != nil && *rtq.ctx.Unique +func (_q *RefreshTokenQuery) sqlCount(ctx context.Context) (int, error) { + _spec := _q.querySpec() + _spec.Node.Columns = _q.ctx.Fields + if len(_q.ctx.Fields) > 0 { + _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique } - return sqlgraph.CountNodes(ctx, rtq.driver, _spec) + return sqlgraph.CountNodes(ctx, _q.driver, _spec) } -func (rtq *RefreshTokenQuery) querySpec() *sqlgraph.QuerySpec { +func (_q *RefreshTokenQuery) querySpec() *sqlgraph.QuerySpec { _spec := sqlgraph.NewQuerySpec(refreshtoken.Table, refreshtoken.Columns, sqlgraph.NewFieldSpec(refreshtoken.FieldID, field.TypeString)) - _spec.From = rtq.sql - if unique := rtq.ctx.Unique; unique != nil { + _spec.From = _q.sql + if unique := _q.ctx.Unique; unique != nil { _spec.Unique = *unique - } else if rtq.path != nil { + } else if _q.path != nil { _spec.Unique = true } - if fields := rtq.ctx.Fields; len(fields) > 0 { + if fields := _q.ctx.Fields; len(fields) > 0 { _spec.Node.Columns = make([]string, 0, len(fields)) _spec.Node.Columns = append(_spec.Node.Columns, refreshtoken.FieldID) for i := range fields { @@ -381,20 +381,20 @@ func (rtq *RefreshTokenQuery) querySpec() *sqlgraph.QuerySpec { } } } - if ps := rtq.predicates; len(ps) > 0 { + if ps := _q.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if limit := rtq.ctx.Limit; limit != nil { + if limit := _q.ctx.Limit; limit != nil { _spec.Limit = *limit } - if offset := rtq.ctx.Offset; offset != nil { + if offset := _q.ctx.Offset; offset != nil { _spec.Offset = *offset } - if ps := rtq.order; len(ps) > 0 { + if ps := _q.order; len(ps) > 0 { _spec.Order = func(selector *sql.Selector) { for i := range ps { ps[i](selector) @@ -404,33 +404,33 @@ func (rtq *RefreshTokenQuery) querySpec() *sqlgraph.QuerySpec { return _spec } -func (rtq *RefreshTokenQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(rtq.driver.Dialect()) +func (_q *RefreshTokenQuery) sqlQuery(ctx context.Context) *sql.Selector { + builder := sql.Dialect(_q.driver.Dialect()) t1 := builder.Table(refreshtoken.Table) - columns := rtq.ctx.Fields + columns := _q.ctx.Fields if len(columns) == 0 { columns = refreshtoken.Columns } selector := builder.Select(t1.Columns(columns...)...).From(t1) - if rtq.sql != nil { - selector = rtq.sql + if _q.sql != nil { + selector = _q.sql selector.Select(selector.Columns(columns...)...) } - if rtq.ctx.Unique != nil && *rtq.ctx.Unique { + if _q.ctx.Unique != nil && *_q.ctx.Unique { selector.Distinct() } - for _, p := range rtq.predicates { + for _, p := range _q.predicates { p(selector) } - for _, p := range rtq.order { + for _, p := range _q.order { p(selector) } - if offset := rtq.ctx.Offset; offset != nil { + if offset := _q.ctx.Offset; offset != nil { // limit is mandatory for offset clause. We start // with default value, and override it below if needed. selector.Offset(*offset).Limit(math.MaxInt32) } - if limit := rtq.ctx.Limit; limit != nil { + if limit := _q.ctx.Limit; limit != nil { selector.Limit(*limit) } return selector @@ -443,41 +443,41 @@ type RefreshTokenGroupBy struct { } // Aggregate adds the given aggregation functions to the group-by query. -func (rtgb *RefreshTokenGroupBy) Aggregate(fns ...AggregateFunc) *RefreshTokenGroupBy { - rtgb.fns = append(rtgb.fns, fns...) - return rtgb +func (_g *RefreshTokenGroupBy) Aggregate(fns ...AggregateFunc) *RefreshTokenGroupBy { + _g.fns = append(_g.fns, fns...) + return _g } // Scan applies the selector query and scans the result into the given value. -func (rtgb *RefreshTokenGroupBy) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, rtgb.build.ctx, ent.OpQueryGroupBy) - if err := rtgb.build.prepareQuery(ctx); err != nil { +func (_g *RefreshTokenGroupBy) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) + if err := _g.build.prepareQuery(ctx); err != nil { return err } - return scanWithInterceptors[*RefreshTokenQuery, *RefreshTokenGroupBy](ctx, rtgb.build, rtgb, rtgb.build.inters, v) + return scanWithInterceptors[*RefreshTokenQuery, *RefreshTokenGroupBy](ctx, _g.build, _g, _g.build.inters, v) } -func (rtgb *RefreshTokenGroupBy) sqlScan(ctx context.Context, root *RefreshTokenQuery, v any) error { +func (_g *RefreshTokenGroupBy) sqlScan(ctx context.Context, root *RefreshTokenQuery, v any) error { selector := root.sqlQuery(ctx).Select() - aggregation := make([]string, 0, len(rtgb.fns)) - for _, fn := range rtgb.fns { + aggregation := make([]string, 0, len(_g.fns)) + for _, fn := range _g.fns { aggregation = append(aggregation, fn(selector)) } if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(*rtgb.flds)+len(rtgb.fns)) - for _, f := range *rtgb.flds { + columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) + for _, f := range *_g.flds { columns = append(columns, selector.C(f)) } columns = append(columns, aggregation...) selector.Select(columns...) } - selector.GroupBy(selector.Columns(*rtgb.flds...)...) + selector.GroupBy(selector.Columns(*_g.flds...)...) if err := selector.Err(); err != nil { return err } rows := &sql.Rows{} query, args := selector.Query() - if err := rtgb.build.driver.Query(ctx, query, args, rows); err != nil { + if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() @@ -491,27 +491,27 @@ type RefreshTokenSelect struct { } // Aggregate adds the given aggregation functions to the selector query. -func (rts *RefreshTokenSelect) Aggregate(fns ...AggregateFunc) *RefreshTokenSelect { - rts.fns = append(rts.fns, fns...) - return rts +func (_s *RefreshTokenSelect) Aggregate(fns ...AggregateFunc) *RefreshTokenSelect { + _s.fns = append(_s.fns, fns...) + return _s } // Scan applies the selector query and scans the result into the given value. -func (rts *RefreshTokenSelect) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, rts.ctx, ent.OpQuerySelect) - if err := rts.prepareQuery(ctx); err != nil { +func (_s *RefreshTokenSelect) Scan(ctx context.Context, v any) error { + ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) + if err := _s.prepareQuery(ctx); err != nil { return err } - return scanWithInterceptors[*RefreshTokenQuery, *RefreshTokenSelect](ctx, rts.RefreshTokenQuery, rts, rts.inters, v) + return scanWithInterceptors[*RefreshTokenQuery, *RefreshTokenSelect](ctx, _s.RefreshTokenQuery, _s, _s.inters, v) } -func (rts *RefreshTokenSelect) sqlScan(ctx context.Context, root *RefreshTokenQuery, v any) error { +func (_s *RefreshTokenSelect) sqlScan(ctx context.Context, root *RefreshTokenQuery, v any) error { selector := root.sqlQuery(ctx) - aggregation := make([]string, 0, len(rts.fns)) - for _, fn := range rts.fns { + aggregation := make([]string, 0, len(_s.fns)) + for _, fn := range _s.fns { aggregation = append(aggregation, fn(selector)) } - switch n := len(*rts.selector.flds); { + switch n := len(*_s.selector.flds); { case n == 0 && len(aggregation) > 0: selector.Select(aggregation...) case n != 0 && len(aggregation) > 0: @@ -519,7 +519,7 @@ func (rts *RefreshTokenSelect) sqlScan(ctx context.Context, root *RefreshTokenQu } rows := &sql.Rows{} query, args := selector.Query() - if err := rts.driver.Query(ctx, query, args, rows); err != nil { + if err := _s.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() diff --git a/storage/ent/db/refreshtoken_update.go b/storage/ent/db/refreshtoken_update.go index 4019868b60..cdf8cee86e 100644 --- a/storage/ent/db/refreshtoken_update.go +++ b/storage/ent/db/refreshtoken_update.go @@ -24,240 +24,240 @@ type RefreshTokenUpdate struct { } // Where appends a list predicates to the RefreshTokenUpdate builder. -func (rtu *RefreshTokenUpdate) Where(ps ...predicate.RefreshToken) *RefreshTokenUpdate { - rtu.mutation.Where(ps...) - return rtu +func (_u *RefreshTokenUpdate) Where(ps ...predicate.RefreshToken) *RefreshTokenUpdate { + _u.mutation.Where(ps...) + return _u } // SetClientID sets the "client_id" field. -func (rtu *RefreshTokenUpdate) SetClientID(s string) *RefreshTokenUpdate { - rtu.mutation.SetClientID(s) - return rtu +func (_u *RefreshTokenUpdate) SetClientID(v string) *RefreshTokenUpdate { + _u.mutation.SetClientID(v) + return _u } // SetNillableClientID sets the "client_id" field if the given value is not nil. -func (rtu *RefreshTokenUpdate) SetNillableClientID(s *string) *RefreshTokenUpdate { - if s != nil { - rtu.SetClientID(*s) +func (_u *RefreshTokenUpdate) SetNillableClientID(v *string) *RefreshTokenUpdate { + if v != nil { + _u.SetClientID(*v) } - return rtu + return _u } // SetScopes sets the "scopes" field. -func (rtu *RefreshTokenUpdate) SetScopes(s []string) *RefreshTokenUpdate { - rtu.mutation.SetScopes(s) - return rtu +func (_u *RefreshTokenUpdate) SetScopes(v []string) *RefreshTokenUpdate { + _u.mutation.SetScopes(v) + return _u } -// AppendScopes appends s to the "scopes" field. -func (rtu *RefreshTokenUpdate) AppendScopes(s []string) *RefreshTokenUpdate { - rtu.mutation.AppendScopes(s) - return rtu +// AppendScopes appends value to the "scopes" field. +func (_u *RefreshTokenUpdate) AppendScopes(v []string) *RefreshTokenUpdate { + _u.mutation.AppendScopes(v) + return _u } // ClearScopes clears the value of the "scopes" field. -func (rtu *RefreshTokenUpdate) ClearScopes() *RefreshTokenUpdate { - rtu.mutation.ClearScopes() - return rtu +func (_u *RefreshTokenUpdate) ClearScopes() *RefreshTokenUpdate { + _u.mutation.ClearScopes() + return _u } // SetNonce sets the "nonce" field. -func (rtu *RefreshTokenUpdate) SetNonce(s string) *RefreshTokenUpdate { - rtu.mutation.SetNonce(s) - return rtu +func (_u *RefreshTokenUpdate) SetNonce(v string) *RefreshTokenUpdate { + _u.mutation.SetNonce(v) + return _u } // SetNillableNonce sets the "nonce" field if the given value is not nil. -func (rtu *RefreshTokenUpdate) SetNillableNonce(s *string) *RefreshTokenUpdate { - if s != nil { - rtu.SetNonce(*s) +func (_u *RefreshTokenUpdate) SetNillableNonce(v *string) *RefreshTokenUpdate { + if v != nil { + _u.SetNonce(*v) } - return rtu + return _u } // SetClaimsUserID sets the "claims_user_id" field. -func (rtu *RefreshTokenUpdate) SetClaimsUserID(s string) *RefreshTokenUpdate { - rtu.mutation.SetClaimsUserID(s) - return rtu +func (_u *RefreshTokenUpdate) SetClaimsUserID(v string) *RefreshTokenUpdate { + _u.mutation.SetClaimsUserID(v) + return _u } // SetNillableClaimsUserID sets the "claims_user_id" field if the given value is not nil. -func (rtu *RefreshTokenUpdate) SetNillableClaimsUserID(s *string) *RefreshTokenUpdate { - if s != nil { - rtu.SetClaimsUserID(*s) +func (_u *RefreshTokenUpdate) SetNillableClaimsUserID(v *string) *RefreshTokenUpdate { + if v != nil { + _u.SetClaimsUserID(*v) } - return rtu + return _u } // SetClaimsUsername sets the "claims_username" field. -func (rtu *RefreshTokenUpdate) SetClaimsUsername(s string) *RefreshTokenUpdate { - rtu.mutation.SetClaimsUsername(s) - return rtu +func (_u *RefreshTokenUpdate) SetClaimsUsername(v string) *RefreshTokenUpdate { + _u.mutation.SetClaimsUsername(v) + return _u } // SetNillableClaimsUsername sets the "claims_username" field if the given value is not nil. -func (rtu *RefreshTokenUpdate) SetNillableClaimsUsername(s *string) *RefreshTokenUpdate { - if s != nil { - rtu.SetClaimsUsername(*s) +func (_u *RefreshTokenUpdate) SetNillableClaimsUsername(v *string) *RefreshTokenUpdate { + if v != nil { + _u.SetClaimsUsername(*v) } - return rtu + return _u } // SetClaimsEmail sets the "claims_email" field. -func (rtu *RefreshTokenUpdate) SetClaimsEmail(s string) *RefreshTokenUpdate { - rtu.mutation.SetClaimsEmail(s) - return rtu +func (_u *RefreshTokenUpdate) SetClaimsEmail(v string) *RefreshTokenUpdate { + _u.mutation.SetClaimsEmail(v) + return _u } // SetNillableClaimsEmail sets the "claims_email" field if the given value is not nil. -func (rtu *RefreshTokenUpdate) SetNillableClaimsEmail(s *string) *RefreshTokenUpdate { - if s != nil { - rtu.SetClaimsEmail(*s) +func (_u *RefreshTokenUpdate) SetNillableClaimsEmail(v *string) *RefreshTokenUpdate { + if v != nil { + _u.SetClaimsEmail(*v) } - return rtu + return _u } // SetClaimsEmailVerified sets the "claims_email_verified" field. -func (rtu *RefreshTokenUpdate) SetClaimsEmailVerified(b bool) *RefreshTokenUpdate { - rtu.mutation.SetClaimsEmailVerified(b) - return rtu +func (_u *RefreshTokenUpdate) SetClaimsEmailVerified(v bool) *RefreshTokenUpdate { + _u.mutation.SetClaimsEmailVerified(v) + return _u } // SetNillableClaimsEmailVerified sets the "claims_email_verified" field if the given value is not nil. -func (rtu *RefreshTokenUpdate) SetNillableClaimsEmailVerified(b *bool) *RefreshTokenUpdate { - if b != nil { - rtu.SetClaimsEmailVerified(*b) +func (_u *RefreshTokenUpdate) SetNillableClaimsEmailVerified(v *bool) *RefreshTokenUpdate { + if v != nil { + _u.SetClaimsEmailVerified(*v) } - return rtu + return _u } // SetClaimsGroups sets the "claims_groups" field. -func (rtu *RefreshTokenUpdate) SetClaimsGroups(s []string) *RefreshTokenUpdate { - rtu.mutation.SetClaimsGroups(s) - return rtu +func (_u *RefreshTokenUpdate) SetClaimsGroups(v []string) *RefreshTokenUpdate { + _u.mutation.SetClaimsGroups(v) + return _u } -// AppendClaimsGroups appends s to the "claims_groups" field. -func (rtu *RefreshTokenUpdate) AppendClaimsGroups(s []string) *RefreshTokenUpdate { - rtu.mutation.AppendClaimsGroups(s) - return rtu +// AppendClaimsGroups appends value to the "claims_groups" field. +func (_u *RefreshTokenUpdate) AppendClaimsGroups(v []string) *RefreshTokenUpdate { + _u.mutation.AppendClaimsGroups(v) + return _u } // ClearClaimsGroups clears the value of the "claims_groups" field. -func (rtu *RefreshTokenUpdate) ClearClaimsGroups() *RefreshTokenUpdate { - rtu.mutation.ClearClaimsGroups() - return rtu +func (_u *RefreshTokenUpdate) ClearClaimsGroups() *RefreshTokenUpdate { + _u.mutation.ClearClaimsGroups() + return _u } // SetClaimsPreferredUsername sets the "claims_preferred_username" field. -func (rtu *RefreshTokenUpdate) SetClaimsPreferredUsername(s string) *RefreshTokenUpdate { - rtu.mutation.SetClaimsPreferredUsername(s) - return rtu +func (_u *RefreshTokenUpdate) SetClaimsPreferredUsername(v string) *RefreshTokenUpdate { + _u.mutation.SetClaimsPreferredUsername(v) + return _u } // SetNillableClaimsPreferredUsername sets the "claims_preferred_username" field if the given value is not nil. -func (rtu *RefreshTokenUpdate) SetNillableClaimsPreferredUsername(s *string) *RefreshTokenUpdate { - if s != nil { - rtu.SetClaimsPreferredUsername(*s) +func (_u *RefreshTokenUpdate) SetNillableClaimsPreferredUsername(v *string) *RefreshTokenUpdate { + if v != nil { + _u.SetClaimsPreferredUsername(*v) } - return rtu + return _u } // SetConnectorID sets the "connector_id" field. -func (rtu *RefreshTokenUpdate) SetConnectorID(s string) *RefreshTokenUpdate { - rtu.mutation.SetConnectorID(s) - return rtu +func (_u *RefreshTokenUpdate) SetConnectorID(v string) *RefreshTokenUpdate { + _u.mutation.SetConnectorID(v) + return _u } // SetNillableConnectorID sets the "connector_id" field if the given value is not nil. -func (rtu *RefreshTokenUpdate) SetNillableConnectorID(s *string) *RefreshTokenUpdate { - if s != nil { - rtu.SetConnectorID(*s) +func (_u *RefreshTokenUpdate) SetNillableConnectorID(v *string) *RefreshTokenUpdate { + if v != nil { + _u.SetConnectorID(*v) } - return rtu + return _u } // SetConnectorData sets the "connector_data" field. -func (rtu *RefreshTokenUpdate) SetConnectorData(b []byte) *RefreshTokenUpdate { - rtu.mutation.SetConnectorData(b) - return rtu +func (_u *RefreshTokenUpdate) SetConnectorData(v []byte) *RefreshTokenUpdate { + _u.mutation.SetConnectorData(v) + return _u } // ClearConnectorData clears the value of the "connector_data" field. -func (rtu *RefreshTokenUpdate) ClearConnectorData() *RefreshTokenUpdate { - rtu.mutation.ClearConnectorData() - return rtu +func (_u *RefreshTokenUpdate) ClearConnectorData() *RefreshTokenUpdate { + _u.mutation.ClearConnectorData() + return _u } // SetToken sets the "token" field. -func (rtu *RefreshTokenUpdate) SetToken(s string) *RefreshTokenUpdate { - rtu.mutation.SetToken(s) - return rtu +func (_u *RefreshTokenUpdate) SetToken(v string) *RefreshTokenUpdate { + _u.mutation.SetToken(v) + return _u } // SetNillableToken sets the "token" field if the given value is not nil. -func (rtu *RefreshTokenUpdate) SetNillableToken(s *string) *RefreshTokenUpdate { - if s != nil { - rtu.SetToken(*s) +func (_u *RefreshTokenUpdate) SetNillableToken(v *string) *RefreshTokenUpdate { + if v != nil { + _u.SetToken(*v) } - return rtu + return _u } // SetObsoleteToken sets the "obsolete_token" field. -func (rtu *RefreshTokenUpdate) SetObsoleteToken(s string) *RefreshTokenUpdate { - rtu.mutation.SetObsoleteToken(s) - return rtu +func (_u *RefreshTokenUpdate) SetObsoleteToken(v string) *RefreshTokenUpdate { + _u.mutation.SetObsoleteToken(v) + return _u } // SetNillableObsoleteToken sets the "obsolete_token" field if the given value is not nil. -func (rtu *RefreshTokenUpdate) SetNillableObsoleteToken(s *string) *RefreshTokenUpdate { - if s != nil { - rtu.SetObsoleteToken(*s) +func (_u *RefreshTokenUpdate) SetNillableObsoleteToken(v *string) *RefreshTokenUpdate { + if v != nil { + _u.SetObsoleteToken(*v) } - return rtu + return _u } // SetCreatedAt sets the "created_at" field. -func (rtu *RefreshTokenUpdate) SetCreatedAt(t time.Time) *RefreshTokenUpdate { - rtu.mutation.SetCreatedAt(t) - return rtu +func (_u *RefreshTokenUpdate) SetCreatedAt(v time.Time) *RefreshTokenUpdate { + _u.mutation.SetCreatedAt(v) + return _u } // SetNillableCreatedAt sets the "created_at" field if the given value is not nil. -func (rtu *RefreshTokenUpdate) SetNillableCreatedAt(t *time.Time) *RefreshTokenUpdate { - if t != nil { - rtu.SetCreatedAt(*t) +func (_u *RefreshTokenUpdate) SetNillableCreatedAt(v *time.Time) *RefreshTokenUpdate { + if v != nil { + _u.SetCreatedAt(*v) } - return rtu + return _u } // SetLastUsed sets the "last_used" field. -func (rtu *RefreshTokenUpdate) SetLastUsed(t time.Time) *RefreshTokenUpdate { - rtu.mutation.SetLastUsed(t) - return rtu +func (_u *RefreshTokenUpdate) SetLastUsed(v time.Time) *RefreshTokenUpdate { + _u.mutation.SetLastUsed(v) + return _u } // SetNillableLastUsed sets the "last_used" field if the given value is not nil. -func (rtu *RefreshTokenUpdate) SetNillableLastUsed(t *time.Time) *RefreshTokenUpdate { - if t != nil { - rtu.SetLastUsed(*t) +func (_u *RefreshTokenUpdate) SetNillableLastUsed(v *time.Time) *RefreshTokenUpdate { + if v != nil { + _u.SetLastUsed(*v) } - return rtu + return _u } // Mutation returns the RefreshTokenMutation object of the builder. -func (rtu *RefreshTokenUpdate) Mutation() *RefreshTokenMutation { - return rtu.mutation +func (_u *RefreshTokenUpdate) Mutation() *RefreshTokenMutation { + return _u.mutation } // Save executes the query and returns the number of nodes affected by the update operation. -func (rtu *RefreshTokenUpdate) Save(ctx context.Context) (int, error) { - return withHooks(ctx, rtu.sqlSave, rtu.mutation, rtu.hooks) +func (_u *RefreshTokenUpdate) Save(ctx context.Context) (int, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) } // SaveX is like Save, but panics if an error occurs. -func (rtu *RefreshTokenUpdate) SaveX(ctx context.Context) int { - affected, err := rtu.Save(ctx) +func (_u *RefreshTokenUpdate) SaveX(ctx context.Context) int { + affected, err := _u.Save(ctx) if err != nil { panic(err) } @@ -265,46 +265,46 @@ func (rtu *RefreshTokenUpdate) SaveX(ctx context.Context) int { } // Exec executes the query. -func (rtu *RefreshTokenUpdate) Exec(ctx context.Context) error { - _, err := rtu.Save(ctx) +func (_u *RefreshTokenUpdate) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (rtu *RefreshTokenUpdate) ExecX(ctx context.Context) { - if err := rtu.Exec(ctx); err != nil { +func (_u *RefreshTokenUpdate) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { panic(err) } } // check runs all checks and user-defined validators on the builder. -func (rtu *RefreshTokenUpdate) check() error { - if v, ok := rtu.mutation.ClientID(); ok { +func (_u *RefreshTokenUpdate) check() error { + if v, ok := _u.mutation.ClientID(); ok { if err := refreshtoken.ClientIDValidator(v); err != nil { return &ValidationError{Name: "client_id", err: fmt.Errorf(`db: validator failed for field "RefreshToken.client_id": %w`, err)} } } - if v, ok := rtu.mutation.Nonce(); ok { + if v, ok := _u.mutation.Nonce(); ok { if err := refreshtoken.NonceValidator(v); err != nil { return &ValidationError{Name: "nonce", err: fmt.Errorf(`db: validator failed for field "RefreshToken.nonce": %w`, err)} } } - if v, ok := rtu.mutation.ClaimsUserID(); ok { + if v, ok := _u.mutation.ClaimsUserID(); ok { if err := refreshtoken.ClaimsUserIDValidator(v); err != nil { return &ValidationError{Name: "claims_user_id", err: fmt.Errorf(`db: validator failed for field "RefreshToken.claims_user_id": %w`, err)} } } - if v, ok := rtu.mutation.ClaimsUsername(); ok { + if v, ok := _u.mutation.ClaimsUsername(); ok { if err := refreshtoken.ClaimsUsernameValidator(v); err != nil { return &ValidationError{Name: "claims_username", err: fmt.Errorf(`db: validator failed for field "RefreshToken.claims_username": %w`, err)} } } - if v, ok := rtu.mutation.ClaimsEmail(); ok { + if v, ok := _u.mutation.ClaimsEmail(); ok { if err := refreshtoken.ClaimsEmailValidator(v); err != nil { return &ValidationError{Name: "claims_email", err: fmt.Errorf(`db: validator failed for field "RefreshToken.claims_email": %w`, err)} } } - if v, ok := rtu.mutation.ConnectorID(); ok { + if v, ok := _u.mutation.ConnectorID(); ok { if err := refreshtoken.ConnectorIDValidator(v); err != nil { return &ValidationError{Name: "connector_id", err: fmt.Errorf(`db: validator failed for field "RefreshToken.connector_id": %w`, err)} } @@ -312,83 +312,83 @@ func (rtu *RefreshTokenUpdate) check() error { return nil } -func (rtu *RefreshTokenUpdate) sqlSave(ctx context.Context) (n int, err error) { - if err := rtu.check(); err != nil { - return n, err +func (_u *RefreshTokenUpdate) sqlSave(ctx context.Context) (_node int, err error) { + if err := _u.check(); err != nil { + return _node, err } _spec := sqlgraph.NewUpdateSpec(refreshtoken.Table, refreshtoken.Columns, sqlgraph.NewFieldSpec(refreshtoken.FieldID, field.TypeString)) - if ps := rtu.mutation.predicates; len(ps) > 0 { + if ps := _u.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if value, ok := rtu.mutation.ClientID(); ok { + if value, ok := _u.mutation.ClientID(); ok { _spec.SetField(refreshtoken.FieldClientID, field.TypeString, value) } - if value, ok := rtu.mutation.Scopes(); ok { + if value, ok := _u.mutation.Scopes(); ok { _spec.SetField(refreshtoken.FieldScopes, field.TypeJSON, value) } - if value, ok := rtu.mutation.AppendedScopes(); ok { + if value, ok := _u.mutation.AppendedScopes(); ok { _spec.AddModifier(func(u *sql.UpdateBuilder) { sqljson.Append(u, refreshtoken.FieldScopes, value) }) } - if rtu.mutation.ScopesCleared() { + if _u.mutation.ScopesCleared() { _spec.ClearField(refreshtoken.FieldScopes, field.TypeJSON) } - if value, ok := rtu.mutation.Nonce(); ok { + if value, ok := _u.mutation.Nonce(); ok { _spec.SetField(refreshtoken.FieldNonce, field.TypeString, value) } - if value, ok := rtu.mutation.ClaimsUserID(); ok { + if value, ok := _u.mutation.ClaimsUserID(); ok { _spec.SetField(refreshtoken.FieldClaimsUserID, field.TypeString, value) } - if value, ok := rtu.mutation.ClaimsUsername(); ok { + if value, ok := _u.mutation.ClaimsUsername(); ok { _spec.SetField(refreshtoken.FieldClaimsUsername, field.TypeString, value) } - if value, ok := rtu.mutation.ClaimsEmail(); ok { + if value, ok := _u.mutation.ClaimsEmail(); ok { _spec.SetField(refreshtoken.FieldClaimsEmail, field.TypeString, value) } - if value, ok := rtu.mutation.ClaimsEmailVerified(); ok { + if value, ok := _u.mutation.ClaimsEmailVerified(); ok { _spec.SetField(refreshtoken.FieldClaimsEmailVerified, field.TypeBool, value) } - if value, ok := rtu.mutation.ClaimsGroups(); ok { + if value, ok := _u.mutation.ClaimsGroups(); ok { _spec.SetField(refreshtoken.FieldClaimsGroups, field.TypeJSON, value) } - if value, ok := rtu.mutation.AppendedClaimsGroups(); ok { + if value, ok := _u.mutation.AppendedClaimsGroups(); ok { _spec.AddModifier(func(u *sql.UpdateBuilder) { sqljson.Append(u, refreshtoken.FieldClaimsGroups, value) }) } - if rtu.mutation.ClaimsGroupsCleared() { + if _u.mutation.ClaimsGroupsCleared() { _spec.ClearField(refreshtoken.FieldClaimsGroups, field.TypeJSON) } - if value, ok := rtu.mutation.ClaimsPreferredUsername(); ok { + if value, ok := _u.mutation.ClaimsPreferredUsername(); ok { _spec.SetField(refreshtoken.FieldClaimsPreferredUsername, field.TypeString, value) } - if value, ok := rtu.mutation.ConnectorID(); ok { + if value, ok := _u.mutation.ConnectorID(); ok { _spec.SetField(refreshtoken.FieldConnectorID, field.TypeString, value) } - if value, ok := rtu.mutation.ConnectorData(); ok { + if value, ok := _u.mutation.ConnectorData(); ok { _spec.SetField(refreshtoken.FieldConnectorData, field.TypeBytes, value) } - if rtu.mutation.ConnectorDataCleared() { + if _u.mutation.ConnectorDataCleared() { _spec.ClearField(refreshtoken.FieldConnectorData, field.TypeBytes) } - if value, ok := rtu.mutation.Token(); ok { + if value, ok := _u.mutation.Token(); ok { _spec.SetField(refreshtoken.FieldToken, field.TypeString, value) } - if value, ok := rtu.mutation.ObsoleteToken(); ok { + if value, ok := _u.mutation.ObsoleteToken(); ok { _spec.SetField(refreshtoken.FieldObsoleteToken, field.TypeString, value) } - if value, ok := rtu.mutation.CreatedAt(); ok { + if value, ok := _u.mutation.CreatedAt(); ok { _spec.SetField(refreshtoken.FieldCreatedAt, field.TypeTime, value) } - if value, ok := rtu.mutation.LastUsed(); ok { + if value, ok := _u.mutation.LastUsed(); ok { _spec.SetField(refreshtoken.FieldLastUsed, field.TypeTime, value) } - if n, err = sqlgraph.UpdateNodes(ctx, rtu.driver, _spec); err != nil { + if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{refreshtoken.Label} } else if sqlgraph.IsConstraintError(err) { @@ -396,8 +396,8 @@ func (rtu *RefreshTokenUpdate) sqlSave(ctx context.Context) (n int, err error) { } return 0, err } - rtu.mutation.done = true - return n, nil + _u.mutation.done = true + return _node, nil } // RefreshTokenUpdateOne is the builder for updating a single RefreshToken entity. @@ -409,247 +409,247 @@ type RefreshTokenUpdateOne struct { } // SetClientID sets the "client_id" field. -func (rtuo *RefreshTokenUpdateOne) SetClientID(s string) *RefreshTokenUpdateOne { - rtuo.mutation.SetClientID(s) - return rtuo +func (_u *RefreshTokenUpdateOne) SetClientID(v string) *RefreshTokenUpdateOne { + _u.mutation.SetClientID(v) + return _u } // SetNillableClientID sets the "client_id" field if the given value is not nil. -func (rtuo *RefreshTokenUpdateOne) SetNillableClientID(s *string) *RefreshTokenUpdateOne { - if s != nil { - rtuo.SetClientID(*s) +func (_u *RefreshTokenUpdateOne) SetNillableClientID(v *string) *RefreshTokenUpdateOne { + if v != nil { + _u.SetClientID(*v) } - return rtuo + return _u } // SetScopes sets the "scopes" field. -func (rtuo *RefreshTokenUpdateOne) SetScopes(s []string) *RefreshTokenUpdateOne { - rtuo.mutation.SetScopes(s) - return rtuo +func (_u *RefreshTokenUpdateOne) SetScopes(v []string) *RefreshTokenUpdateOne { + _u.mutation.SetScopes(v) + return _u } -// AppendScopes appends s to the "scopes" field. -func (rtuo *RefreshTokenUpdateOne) AppendScopes(s []string) *RefreshTokenUpdateOne { - rtuo.mutation.AppendScopes(s) - return rtuo +// AppendScopes appends value to the "scopes" field. +func (_u *RefreshTokenUpdateOne) AppendScopes(v []string) *RefreshTokenUpdateOne { + _u.mutation.AppendScopes(v) + return _u } // ClearScopes clears the value of the "scopes" field. -func (rtuo *RefreshTokenUpdateOne) ClearScopes() *RefreshTokenUpdateOne { - rtuo.mutation.ClearScopes() - return rtuo +func (_u *RefreshTokenUpdateOne) ClearScopes() *RefreshTokenUpdateOne { + _u.mutation.ClearScopes() + return _u } // SetNonce sets the "nonce" field. -func (rtuo *RefreshTokenUpdateOne) SetNonce(s string) *RefreshTokenUpdateOne { - rtuo.mutation.SetNonce(s) - return rtuo +func (_u *RefreshTokenUpdateOne) SetNonce(v string) *RefreshTokenUpdateOne { + _u.mutation.SetNonce(v) + return _u } // SetNillableNonce sets the "nonce" field if the given value is not nil. -func (rtuo *RefreshTokenUpdateOne) SetNillableNonce(s *string) *RefreshTokenUpdateOne { - if s != nil { - rtuo.SetNonce(*s) +func (_u *RefreshTokenUpdateOne) SetNillableNonce(v *string) *RefreshTokenUpdateOne { + if v != nil { + _u.SetNonce(*v) } - return rtuo + return _u } // SetClaimsUserID sets the "claims_user_id" field. -func (rtuo *RefreshTokenUpdateOne) SetClaimsUserID(s string) *RefreshTokenUpdateOne { - rtuo.mutation.SetClaimsUserID(s) - return rtuo +func (_u *RefreshTokenUpdateOne) SetClaimsUserID(v string) *RefreshTokenUpdateOne { + _u.mutation.SetClaimsUserID(v) + return _u } // SetNillableClaimsUserID sets the "claims_user_id" field if the given value is not nil. -func (rtuo *RefreshTokenUpdateOne) SetNillableClaimsUserID(s *string) *RefreshTokenUpdateOne { - if s != nil { - rtuo.SetClaimsUserID(*s) +func (_u *RefreshTokenUpdateOne) SetNillableClaimsUserID(v *string) *RefreshTokenUpdateOne { + if v != nil { + _u.SetClaimsUserID(*v) } - return rtuo + return _u } // SetClaimsUsername sets the "claims_username" field. -func (rtuo *RefreshTokenUpdateOne) SetClaimsUsername(s string) *RefreshTokenUpdateOne { - rtuo.mutation.SetClaimsUsername(s) - return rtuo +func (_u *RefreshTokenUpdateOne) SetClaimsUsername(v string) *RefreshTokenUpdateOne { + _u.mutation.SetClaimsUsername(v) + return _u } // SetNillableClaimsUsername sets the "claims_username" field if the given value is not nil. -func (rtuo *RefreshTokenUpdateOne) SetNillableClaimsUsername(s *string) *RefreshTokenUpdateOne { - if s != nil { - rtuo.SetClaimsUsername(*s) +func (_u *RefreshTokenUpdateOne) SetNillableClaimsUsername(v *string) *RefreshTokenUpdateOne { + if v != nil { + _u.SetClaimsUsername(*v) } - return rtuo + return _u } // SetClaimsEmail sets the "claims_email" field. -func (rtuo *RefreshTokenUpdateOne) SetClaimsEmail(s string) *RefreshTokenUpdateOne { - rtuo.mutation.SetClaimsEmail(s) - return rtuo +func (_u *RefreshTokenUpdateOne) SetClaimsEmail(v string) *RefreshTokenUpdateOne { + _u.mutation.SetClaimsEmail(v) + return _u } // SetNillableClaimsEmail sets the "claims_email" field if the given value is not nil. -func (rtuo *RefreshTokenUpdateOne) SetNillableClaimsEmail(s *string) *RefreshTokenUpdateOne { - if s != nil { - rtuo.SetClaimsEmail(*s) +func (_u *RefreshTokenUpdateOne) SetNillableClaimsEmail(v *string) *RefreshTokenUpdateOne { + if v != nil { + _u.SetClaimsEmail(*v) } - return rtuo + return _u } // SetClaimsEmailVerified sets the "claims_email_verified" field. -func (rtuo *RefreshTokenUpdateOne) SetClaimsEmailVerified(b bool) *RefreshTokenUpdateOne { - rtuo.mutation.SetClaimsEmailVerified(b) - return rtuo +func (_u *RefreshTokenUpdateOne) SetClaimsEmailVerified(v bool) *RefreshTokenUpdateOne { + _u.mutation.SetClaimsEmailVerified(v) + return _u } // SetNillableClaimsEmailVerified sets the "claims_email_verified" field if the given value is not nil. -func (rtuo *RefreshTokenUpdateOne) SetNillableClaimsEmailVerified(b *bool) *RefreshTokenUpdateOne { - if b != nil { - rtuo.SetClaimsEmailVerified(*b) +func (_u *RefreshTokenUpdateOne) SetNillableClaimsEmailVerified(v *bool) *RefreshTokenUpdateOne { + if v != nil { + _u.SetClaimsEmailVerified(*v) } - return rtuo + return _u } // SetClaimsGroups sets the "claims_groups" field. -func (rtuo *RefreshTokenUpdateOne) SetClaimsGroups(s []string) *RefreshTokenUpdateOne { - rtuo.mutation.SetClaimsGroups(s) - return rtuo +func (_u *RefreshTokenUpdateOne) SetClaimsGroups(v []string) *RefreshTokenUpdateOne { + _u.mutation.SetClaimsGroups(v) + return _u } -// AppendClaimsGroups appends s to the "claims_groups" field. -func (rtuo *RefreshTokenUpdateOne) AppendClaimsGroups(s []string) *RefreshTokenUpdateOne { - rtuo.mutation.AppendClaimsGroups(s) - return rtuo +// AppendClaimsGroups appends value to the "claims_groups" field. +func (_u *RefreshTokenUpdateOne) AppendClaimsGroups(v []string) *RefreshTokenUpdateOne { + _u.mutation.AppendClaimsGroups(v) + return _u } // ClearClaimsGroups clears the value of the "claims_groups" field. -func (rtuo *RefreshTokenUpdateOne) ClearClaimsGroups() *RefreshTokenUpdateOne { - rtuo.mutation.ClearClaimsGroups() - return rtuo +func (_u *RefreshTokenUpdateOne) ClearClaimsGroups() *RefreshTokenUpdateOne { + _u.mutation.ClearClaimsGroups() + return _u } // SetClaimsPreferredUsername sets the "claims_preferred_username" field. -func (rtuo *RefreshTokenUpdateOne) SetClaimsPreferredUsername(s string) *RefreshTokenUpdateOne { - rtuo.mutation.SetClaimsPreferredUsername(s) - return rtuo +func (_u *RefreshTokenUpdateOne) SetClaimsPreferredUsername(v string) *RefreshTokenUpdateOne { + _u.mutation.SetClaimsPreferredUsername(v) + return _u } // SetNillableClaimsPreferredUsername sets the "claims_preferred_username" field if the given value is not nil. -func (rtuo *RefreshTokenUpdateOne) SetNillableClaimsPreferredUsername(s *string) *RefreshTokenUpdateOne { - if s != nil { - rtuo.SetClaimsPreferredUsername(*s) +func (_u *RefreshTokenUpdateOne) SetNillableClaimsPreferredUsername(v *string) *RefreshTokenUpdateOne { + if v != nil { + _u.SetClaimsPreferredUsername(*v) } - return rtuo + return _u } // SetConnectorID sets the "connector_id" field. -func (rtuo *RefreshTokenUpdateOne) SetConnectorID(s string) *RefreshTokenUpdateOne { - rtuo.mutation.SetConnectorID(s) - return rtuo +func (_u *RefreshTokenUpdateOne) SetConnectorID(v string) *RefreshTokenUpdateOne { + _u.mutation.SetConnectorID(v) + return _u } // SetNillableConnectorID sets the "connector_id" field if the given value is not nil. -func (rtuo *RefreshTokenUpdateOne) SetNillableConnectorID(s *string) *RefreshTokenUpdateOne { - if s != nil { - rtuo.SetConnectorID(*s) +func (_u *RefreshTokenUpdateOne) SetNillableConnectorID(v *string) *RefreshTokenUpdateOne { + if v != nil { + _u.SetConnectorID(*v) } - return rtuo + return _u } // SetConnectorData sets the "connector_data" field. -func (rtuo *RefreshTokenUpdateOne) SetConnectorData(b []byte) *RefreshTokenUpdateOne { - rtuo.mutation.SetConnectorData(b) - return rtuo +func (_u *RefreshTokenUpdateOne) SetConnectorData(v []byte) *RefreshTokenUpdateOne { + _u.mutation.SetConnectorData(v) + return _u } // ClearConnectorData clears the value of the "connector_data" field. -func (rtuo *RefreshTokenUpdateOne) ClearConnectorData() *RefreshTokenUpdateOne { - rtuo.mutation.ClearConnectorData() - return rtuo +func (_u *RefreshTokenUpdateOne) ClearConnectorData() *RefreshTokenUpdateOne { + _u.mutation.ClearConnectorData() + return _u } // SetToken sets the "token" field. -func (rtuo *RefreshTokenUpdateOne) SetToken(s string) *RefreshTokenUpdateOne { - rtuo.mutation.SetToken(s) - return rtuo +func (_u *RefreshTokenUpdateOne) SetToken(v string) *RefreshTokenUpdateOne { + _u.mutation.SetToken(v) + return _u } // SetNillableToken sets the "token" field if the given value is not nil. -func (rtuo *RefreshTokenUpdateOne) SetNillableToken(s *string) *RefreshTokenUpdateOne { - if s != nil { - rtuo.SetToken(*s) +func (_u *RefreshTokenUpdateOne) SetNillableToken(v *string) *RefreshTokenUpdateOne { + if v != nil { + _u.SetToken(*v) } - return rtuo + return _u } // SetObsoleteToken sets the "obsolete_token" field. -func (rtuo *RefreshTokenUpdateOne) SetObsoleteToken(s string) *RefreshTokenUpdateOne { - rtuo.mutation.SetObsoleteToken(s) - return rtuo +func (_u *RefreshTokenUpdateOne) SetObsoleteToken(v string) *RefreshTokenUpdateOne { + _u.mutation.SetObsoleteToken(v) + return _u } // SetNillableObsoleteToken sets the "obsolete_token" field if the given value is not nil. -func (rtuo *RefreshTokenUpdateOne) SetNillableObsoleteToken(s *string) *RefreshTokenUpdateOne { - if s != nil { - rtuo.SetObsoleteToken(*s) +func (_u *RefreshTokenUpdateOne) SetNillableObsoleteToken(v *string) *RefreshTokenUpdateOne { + if v != nil { + _u.SetObsoleteToken(*v) } - return rtuo + return _u } // SetCreatedAt sets the "created_at" field. -func (rtuo *RefreshTokenUpdateOne) SetCreatedAt(t time.Time) *RefreshTokenUpdateOne { - rtuo.mutation.SetCreatedAt(t) - return rtuo +func (_u *RefreshTokenUpdateOne) SetCreatedAt(v time.Time) *RefreshTokenUpdateOne { + _u.mutation.SetCreatedAt(v) + return _u } // SetNillableCreatedAt sets the "created_at" field if the given value is not nil. -func (rtuo *RefreshTokenUpdateOne) SetNillableCreatedAt(t *time.Time) *RefreshTokenUpdateOne { - if t != nil { - rtuo.SetCreatedAt(*t) +func (_u *RefreshTokenUpdateOne) SetNillableCreatedAt(v *time.Time) *RefreshTokenUpdateOne { + if v != nil { + _u.SetCreatedAt(*v) } - return rtuo + return _u } // SetLastUsed sets the "last_used" field. -func (rtuo *RefreshTokenUpdateOne) SetLastUsed(t time.Time) *RefreshTokenUpdateOne { - rtuo.mutation.SetLastUsed(t) - return rtuo +func (_u *RefreshTokenUpdateOne) SetLastUsed(v time.Time) *RefreshTokenUpdateOne { + _u.mutation.SetLastUsed(v) + return _u } // SetNillableLastUsed sets the "last_used" field if the given value is not nil. -func (rtuo *RefreshTokenUpdateOne) SetNillableLastUsed(t *time.Time) *RefreshTokenUpdateOne { - if t != nil { - rtuo.SetLastUsed(*t) +func (_u *RefreshTokenUpdateOne) SetNillableLastUsed(v *time.Time) *RefreshTokenUpdateOne { + if v != nil { + _u.SetLastUsed(*v) } - return rtuo + return _u } // Mutation returns the RefreshTokenMutation object of the builder. -func (rtuo *RefreshTokenUpdateOne) Mutation() *RefreshTokenMutation { - return rtuo.mutation +func (_u *RefreshTokenUpdateOne) Mutation() *RefreshTokenMutation { + return _u.mutation } // Where appends a list predicates to the RefreshTokenUpdate builder. -func (rtuo *RefreshTokenUpdateOne) Where(ps ...predicate.RefreshToken) *RefreshTokenUpdateOne { - rtuo.mutation.Where(ps...) - return rtuo +func (_u *RefreshTokenUpdateOne) Where(ps ...predicate.RefreshToken) *RefreshTokenUpdateOne { + _u.mutation.Where(ps...) + return _u } // Select allows selecting one or more fields (columns) of the returned entity. // The default is selecting all fields defined in the entity schema. -func (rtuo *RefreshTokenUpdateOne) Select(field string, fields ...string) *RefreshTokenUpdateOne { - rtuo.fields = append([]string{field}, fields...) - return rtuo +func (_u *RefreshTokenUpdateOne) Select(field string, fields ...string) *RefreshTokenUpdateOne { + _u.fields = append([]string{field}, fields...) + return _u } // Save executes the query and returns the updated RefreshToken entity. -func (rtuo *RefreshTokenUpdateOne) Save(ctx context.Context) (*RefreshToken, error) { - return withHooks(ctx, rtuo.sqlSave, rtuo.mutation, rtuo.hooks) +func (_u *RefreshTokenUpdateOne) Save(ctx context.Context) (*RefreshToken, error) { + return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) } // SaveX is like Save, but panics if an error occurs. -func (rtuo *RefreshTokenUpdateOne) SaveX(ctx context.Context) *RefreshToken { - node, err := rtuo.Save(ctx) +func (_u *RefreshTokenUpdateOne) SaveX(ctx context.Context) *RefreshToken { + node, err := _u.Save(ctx) if err != nil { panic(err) } @@ -657,46 +657,46 @@ func (rtuo *RefreshTokenUpdateOne) SaveX(ctx context.Context) *RefreshToken { } // Exec executes the query on the entity. -func (rtuo *RefreshTokenUpdateOne) Exec(ctx context.Context) error { - _, err := rtuo.Save(ctx) +func (_u *RefreshTokenUpdateOne) Exec(ctx context.Context) error { + _, err := _u.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. -func (rtuo *RefreshTokenUpdateOne) ExecX(ctx context.Context) { - if err := rtuo.Exec(ctx); err != nil { +func (_u *RefreshTokenUpdateOne) ExecX(ctx context.Context) { + if err := _u.Exec(ctx); err != nil { panic(err) } } // check runs all checks and user-defined validators on the builder. -func (rtuo *RefreshTokenUpdateOne) check() error { - if v, ok := rtuo.mutation.ClientID(); ok { +func (_u *RefreshTokenUpdateOne) check() error { + if v, ok := _u.mutation.ClientID(); ok { if err := refreshtoken.ClientIDValidator(v); err != nil { return &ValidationError{Name: "client_id", err: fmt.Errorf(`db: validator failed for field "RefreshToken.client_id": %w`, err)} } } - if v, ok := rtuo.mutation.Nonce(); ok { + if v, ok := _u.mutation.Nonce(); ok { if err := refreshtoken.NonceValidator(v); err != nil { return &ValidationError{Name: "nonce", err: fmt.Errorf(`db: validator failed for field "RefreshToken.nonce": %w`, err)} } } - if v, ok := rtuo.mutation.ClaimsUserID(); ok { + if v, ok := _u.mutation.ClaimsUserID(); ok { if err := refreshtoken.ClaimsUserIDValidator(v); err != nil { return &ValidationError{Name: "claims_user_id", err: fmt.Errorf(`db: validator failed for field "RefreshToken.claims_user_id": %w`, err)} } } - if v, ok := rtuo.mutation.ClaimsUsername(); ok { + if v, ok := _u.mutation.ClaimsUsername(); ok { if err := refreshtoken.ClaimsUsernameValidator(v); err != nil { return &ValidationError{Name: "claims_username", err: fmt.Errorf(`db: validator failed for field "RefreshToken.claims_username": %w`, err)} } } - if v, ok := rtuo.mutation.ClaimsEmail(); ok { + if v, ok := _u.mutation.ClaimsEmail(); ok { if err := refreshtoken.ClaimsEmailValidator(v); err != nil { return &ValidationError{Name: "claims_email", err: fmt.Errorf(`db: validator failed for field "RefreshToken.claims_email": %w`, err)} } } - if v, ok := rtuo.mutation.ConnectorID(); ok { + if v, ok := _u.mutation.ConnectorID(); ok { if err := refreshtoken.ConnectorIDValidator(v); err != nil { return &ValidationError{Name: "connector_id", err: fmt.Errorf(`db: validator failed for field "RefreshToken.connector_id": %w`, err)} } @@ -704,17 +704,17 @@ func (rtuo *RefreshTokenUpdateOne) check() error { return nil } -func (rtuo *RefreshTokenUpdateOne) sqlSave(ctx context.Context) (_node *RefreshToken, err error) { - if err := rtuo.check(); err != nil { +func (_u *RefreshTokenUpdateOne) sqlSave(ctx context.Context) (_node *RefreshToken, err error) { + if err := _u.check(); err != nil { return _node, err } _spec := sqlgraph.NewUpdateSpec(refreshtoken.Table, refreshtoken.Columns, sqlgraph.NewFieldSpec(refreshtoken.FieldID, field.TypeString)) - id, ok := rtuo.mutation.ID() + id, ok := _u.mutation.ID() if !ok { return nil, &ValidationError{Name: "id", err: errors.New(`db: missing "RefreshToken.id" for update`)} } _spec.Node.ID.Value = id - if fields := rtuo.fields; len(fields) > 0 { + if fields := _u.fields; len(fields) > 0 { _spec.Node.Columns = make([]string, 0, len(fields)) _spec.Node.Columns = append(_spec.Node.Columns, refreshtoken.FieldID) for _, f := range fields { @@ -726,81 +726,81 @@ func (rtuo *RefreshTokenUpdateOne) sqlSave(ctx context.Context) (_node *RefreshT } } } - if ps := rtuo.mutation.predicates; len(ps) > 0 { + if ps := _u.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } - if value, ok := rtuo.mutation.ClientID(); ok { + if value, ok := _u.mutation.ClientID(); ok { _spec.SetField(refreshtoken.FieldClientID, field.TypeString, value) } - if value, ok := rtuo.mutation.Scopes(); ok { + if value, ok := _u.mutation.Scopes(); ok { _spec.SetField(refreshtoken.FieldScopes, field.TypeJSON, value) } - if value, ok := rtuo.mutation.AppendedScopes(); ok { + if value, ok := _u.mutation.AppendedScopes(); ok { _spec.AddModifier(func(u *sql.UpdateBuilder) { sqljson.Append(u, refreshtoken.FieldScopes, value) }) } - if rtuo.mutation.ScopesCleared() { + if _u.mutation.ScopesCleared() { _spec.ClearField(refreshtoken.FieldScopes, field.TypeJSON) } - if value, ok := rtuo.mutation.Nonce(); ok { + if value, ok := _u.mutation.Nonce(); ok { _spec.SetField(refreshtoken.FieldNonce, field.TypeString, value) } - if value, ok := rtuo.mutation.ClaimsUserID(); ok { + if value, ok := _u.mutation.ClaimsUserID(); ok { _spec.SetField(refreshtoken.FieldClaimsUserID, field.TypeString, value) } - if value, ok := rtuo.mutation.ClaimsUsername(); ok { + if value, ok := _u.mutation.ClaimsUsername(); ok { _spec.SetField(refreshtoken.FieldClaimsUsername, field.TypeString, value) } - if value, ok := rtuo.mutation.ClaimsEmail(); ok { + if value, ok := _u.mutation.ClaimsEmail(); ok { _spec.SetField(refreshtoken.FieldClaimsEmail, field.TypeString, value) } - if value, ok := rtuo.mutation.ClaimsEmailVerified(); ok { + if value, ok := _u.mutation.ClaimsEmailVerified(); ok { _spec.SetField(refreshtoken.FieldClaimsEmailVerified, field.TypeBool, value) } - if value, ok := rtuo.mutation.ClaimsGroups(); ok { + if value, ok := _u.mutation.ClaimsGroups(); ok { _spec.SetField(refreshtoken.FieldClaimsGroups, field.TypeJSON, value) } - if value, ok := rtuo.mutation.AppendedClaimsGroups(); ok { + if value, ok := _u.mutation.AppendedClaimsGroups(); ok { _spec.AddModifier(func(u *sql.UpdateBuilder) { sqljson.Append(u, refreshtoken.FieldClaimsGroups, value) }) } - if rtuo.mutation.ClaimsGroupsCleared() { + if _u.mutation.ClaimsGroupsCleared() { _spec.ClearField(refreshtoken.FieldClaimsGroups, field.TypeJSON) } - if value, ok := rtuo.mutation.ClaimsPreferredUsername(); ok { + if value, ok := _u.mutation.ClaimsPreferredUsername(); ok { _spec.SetField(refreshtoken.FieldClaimsPreferredUsername, field.TypeString, value) } - if value, ok := rtuo.mutation.ConnectorID(); ok { + if value, ok := _u.mutation.ConnectorID(); ok { _spec.SetField(refreshtoken.FieldConnectorID, field.TypeString, value) } - if value, ok := rtuo.mutation.ConnectorData(); ok { + if value, ok := _u.mutation.ConnectorData(); ok { _spec.SetField(refreshtoken.FieldConnectorData, field.TypeBytes, value) } - if rtuo.mutation.ConnectorDataCleared() { + if _u.mutation.ConnectorDataCleared() { _spec.ClearField(refreshtoken.FieldConnectorData, field.TypeBytes) } - if value, ok := rtuo.mutation.Token(); ok { + if value, ok := _u.mutation.Token(); ok { _spec.SetField(refreshtoken.FieldToken, field.TypeString, value) } - if value, ok := rtuo.mutation.ObsoleteToken(); ok { + if value, ok := _u.mutation.ObsoleteToken(); ok { _spec.SetField(refreshtoken.FieldObsoleteToken, field.TypeString, value) } - if value, ok := rtuo.mutation.CreatedAt(); ok { + if value, ok := _u.mutation.CreatedAt(); ok { _spec.SetField(refreshtoken.FieldCreatedAt, field.TypeTime, value) } - if value, ok := rtuo.mutation.LastUsed(); ok { + if value, ok := _u.mutation.LastUsed(); ok { _spec.SetField(refreshtoken.FieldLastUsed, field.TypeTime, value) } - _node = &RefreshToken{config: rtuo.config} + _node = &RefreshToken{config: _u.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, rtuo.driver, _spec); err != nil { + if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{refreshtoken.Label} } else if sqlgraph.IsConstraintError(err) { @@ -808,6 +808,6 @@ func (rtuo *RefreshTokenUpdateOne) sqlSave(ctx context.Context) (_node *RefreshT } return nil, err } - rtuo.mutation.done = true + _u.mutation.done = true return _node, nil } diff --git a/storage/ent/db/runtime/runtime.go b/storage/ent/db/runtime/runtime.go index 81286891b1..33f2aeb764 100644 --- a/storage/ent/db/runtime/runtime.go +++ b/storage/ent/db/runtime/runtime.go @@ -5,6 +5,5 @@ package runtime // The schema-stitching logic is generated in github.com/dexidp/dex/storage/ent/db/runtime.go const ( - Version = "v0.14.4" // Version of ent codegen. - Sum = "h1:/DhDraSLXIkBhyiVoJeSshr4ZYi7femzhj6/TckzZuI=" // Sum of ent codegen. + Version = "v0.14.4" // Version of ent codegen. ) diff --git a/storage/ent/mysql.go b/storage/ent/mysql.go index 008f7bad33..5b2618364f 100644 --- a/storage/ent/mysql.go +++ b/storage/ent/mysql.go @@ -14,7 +14,9 @@ import ( "time" entSQL "entgo.io/ent/dialect/sql" + "github.com/XSAM/otelsql" "github.com/go-sql-driver/mysql" // Register mysql driver. + semconv "go.opentelemetry.io/otel/semconv/v1.28.0" "github.com/dexidp/dex/storage" "github.com/dexidp/dex/storage/ent/client" @@ -74,11 +76,19 @@ func (m *MySQL) driver() (*entSQL.Driver, error) { default: tlsConfig = m.SSL.Mode } - - drv, err := entSQL.Open("mysql", m.dsn(tlsConfig)) + db, err := otelsql.Open("mysql", m.dsn(tlsConfig), otelsql.WithAttributes( + semconv.DBSystemMySQL, + )) + if err != nil { + return nil, err + } + err = otelsql.RegisterDBStatsMetrics(db, otelsql.WithAttributes( + semconv.DBSystemMySQL, + )) if err != nil { return nil, err } + drv := entSQL.OpenDB("mysql", db) if m.MaxIdleConns == 0 { /* Override default behaviour to fix https://github.com/dexidp/dex/issues/1608 */ diff --git a/storage/ent/postgres.go b/storage/ent/postgres.go index dad81df445..da8d96fc07 100644 --- a/storage/ent/postgres.go +++ b/storage/ent/postgres.go @@ -13,7 +13,9 @@ import ( "time" entSQL "entgo.io/ent/dialect/sql" + "github.com/XSAM/otelsql" _ "github.com/lib/pq" // Register postgres driver. + semconv "go.opentelemetry.io/otel/semconv/v1.28.0" "github.com/dexidp/dex/storage" "github.com/dexidp/dex/storage/ent/client" @@ -61,10 +63,19 @@ func (p *Postgres) Open(logger *slog.Logger) (storage.Storage, error) { } func (p *Postgres) driver() (*entSQL.Driver, error) { - drv, err := entSQL.Open("postgres", p.dsn()) + db, err := otelsql.Open("postgres", p.dsn(), otelsql.WithAttributes( + semconv.DBSystemPostgreSQL, + )) if err != nil { return nil, err } + err = otelsql.RegisterDBStatsMetrics(db, otelsql.WithAttributes( + semconv.DBSystemPostgreSQL, + )) + if err != nil { + return nil, err + } + drv := entSQL.OpenDB("postgres", db) // set database/sql tunables if configured if p.ConnMaxLifetime != 0 { diff --git a/storage/ent/sqlite.go b/storage/ent/sqlite.go index 8c5287ef50..ece3944eaa 100644 --- a/storage/ent/sqlite.go +++ b/storage/ent/sqlite.go @@ -7,7 +7,9 @@ import ( "strings" "entgo.io/ent/dialect/sql" + "github.com/XSAM/otelsql" _ "github.com/mattn/go-sqlite3" // Register sqlite driver. + semconv "go.opentelemetry.io/otel/semconv/v1.28.0" "github.com/dexidp/dex/storage" "github.com/dexidp/dex/storage/ent/client" @@ -25,11 +27,13 @@ func (s *SQLite3) Open(logger *slog.Logger) (storage.Storage, error) { // Implicitly set foreign_keys pragma to "on" because it is required by ent s.File = addFK(s.File) - - drv, err := sql.Open("sqlite3", s.File) + open, err := otelsql.Open("sqlite3", s.File, otelsql.WithAttributes( + semconv.DBSystemSqlite, + )) if err != nil { return nil, err } + drv := sql.OpenDB("sqlite3", open) // always allow only one connection to sqlite3, any other thread/go-routine // attempting concurrent access will have to wait diff --git a/storage/health_test.go b/storage/health_test.go new file mode 100644 index 0000000000..f3ab649da6 --- /dev/null +++ b/storage/health_test.go @@ -0,0 +1,93 @@ +package storage + +import ( + "context" + "errors" + "fmt" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func (m *mockStorage) GetAuthRequest(ctx context.Context, id string) (AuthRequest, error) { + if m.getErr != nil { + return AuthRequest{}, m.getErr + } + return AuthRequest{}, ErrNotFound +} + +func (m *mockStorage) CreateAuthRequest(ctx context.Context, a AuthRequest) error { + if m.createErr != nil { + return m.createErr + } + return nil +} + +func (m *mockStorage) DeleteAuthRequest(ctx context.Context, id string) error { + if m.deleteErr != nil { + return m.deleteErr + } + return nil +} + +func TestNewCustomHealthCheckFunc(t *testing.T) { + ctx := context.Background() + + fixedTime := time.Now() + now := func() time.Time { return fixedTime } + + tests := []struct { + name string + createErr error + deleteErr error + expectedErr error + expectedDetails interface{} + }{ + { + name: "Success", + createErr: nil, + deleteErr: nil, + expectedErr: nil, + expectedDetails: nil, + }, + { + name: "Create auth request fails", + createErr: errors.New("create failed"), + deleteErr: nil, + expectedErr: fmt.Errorf("create auth request: %w", errors.New("create failed")), + expectedDetails: nil, + }, + { + name: "Delete auth request fails", + createErr: nil, + deleteErr: errors.New("delete failed"), + expectedErr: fmt.Errorf("delete auth request: %w", errors.New("delete failed")), + expectedDetails: nil, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + // Set up mock storage + mock := newMockStorage() + mock.createErr = tc.createErr + mock.deleteErr = tc.deleteErr + + // Create health check function + healthCheck := NewCustomHealthCheckFunc(mock, now) + + // Run health check + details, err := healthCheck(ctx) + + // Verify results + if tc.expectedErr != nil { + require.Error(t, err) + require.EqualError(t, err, tc.expectedErr.Error()) + } else { + require.NoError(t, err) + } + require.Equal(t, tc.expectedDetails, details) + }) + } +} diff --git a/storage/sql/config.go b/storage/sql/config.go index 5379aeb6b2..f46baa1e13 100644 --- a/storage/sql/config.go +++ b/storage/sql/config.go @@ -1,9 +1,10 @@ package sql import ( + "context" "crypto/tls" "crypto/x509" - "database/sql" + "database/sql/driver" "fmt" "log/slog" "net" @@ -13,8 +14,11 @@ import ( "strings" "time" + "github.com/XSAM/otelsql" "github.com/go-sql-driver/mysql" "github.com/lib/pq" + "go.opentelemetry.io/otel/attribute" + semconv "go.opentelemetry.io/otel/semconv/v1.34.0" "github.com/dexidp/dex/storage" ) @@ -162,10 +166,96 @@ func (p *Postgres) createDataSourceName() string { return strings.Join(parameters, " ") } +// Add this helper function to extract the operation name +func extractOperationName(query string) string { + upperQuery := strings.ToUpper(query) + // Regex to match the operation keyword at the start of the query (after optional whitespace) + // Captures common SQL operations; extend the list as needed for your use case + re := regexp.MustCompile(`^\s*(SELECT|INSERT|UPDATE|DELETE|REPLACE|UPSERT|MERGE|CALL|EXPLAIN|CREATE|ALTER|DROP|TRUNCATE|RENAME|SET|USE|GRANT|REVOKE)\b`) + matches := re.FindStringSubmatch(upperQuery) + if len(matches) == 2 { + // Find indices to extract from original query (preserves case) + idx := re.FindStringSubmatchIndex(upperQuery) + if len(idx) >= 4 { + start := idx[2] + end := idx[3] + return query[start:end] + } + } + return "" +} + +// Existing helper function to extract the table name (unchanged, but included for completeness) +func extractTableName(query string) string { + upperQuery := strings.ToUpper(query) + // Regex to match the table after common SQL keywords (uppercase for case-insensitive matching via ToUpper) + // Captures quoted or unquoted table names, possibly with schema (e.g., public.users) + re := regexp.MustCompile(`\b(FROM|INTO|UPDATE|DELETE\s+FROM)\s+(["]?[\w.]+\b["]?)\b`) + matches := re.FindStringSubmatch(upperQuery) + if len(matches) == 3 { + // Find indices to extract from original query (preserves case) + idx := re.FindStringSubmatchIndex(upperQuery) + if len(idx) >= 6 { + start := idx[4] + end := idx[5] + table := query[start:end] + // Remove any surrounding quotes + table = strings.Trim(table, "\"`") + return table + } + } + return "" +} + func (p *Postgres) open(logger *slog.Logger) (*conn, error) { dataSourceName := p.createDataSourceName() - - db, err := sql.Open("postgres", dataSourceName) + db, err := otelsql.Open("postgres", dataSourceName, otelsql.WithAttributes( + semconv.DBSystemNamePostgreSQL, + semconv.DBNamespace(p.Database), + semconv.NetworkPeerPort(int(p.Port)), + ), + otelsql.WithAttributesGetter(func(ctx context.Context, method otelsql.Method, query string, args []driver.NamedValue) []attribute.KeyValue { + attrs := []attribute.KeyValue{} + operation := extractOperationName(query) + if operation != "" { + attrs = append(attrs, semconv.DBOperationName(operation)) + } + table := extractTableName(query) + if table != "" { + attrs = append(attrs, semconv.DBCollectionName(table)) + } + if len(attrs) > 0 { + return attrs + } + // If nothing extracted, return empty (or fallback to other attributes if needed) + return nil + }), + ) + if err != nil { + return nil, err + } + err = otelsql.RegisterDBStatsMetrics(db, otelsql.WithAttributes( + semconv.DBSystemNamePostgreSQL, + semconv.DBNamespace(p.Database), + semconv.NetworkPeerPort(int(p.Port)), + ), + otelsql.WithAttributesGetter(func(ctx context.Context, method otelsql.Method, query string, args []driver.NamedValue) []attribute.KeyValue { + attrs := []attribute.KeyValue{} + operation := extractOperationName(query) + if operation != "" { + attrs = append(attrs, semconv.DBOperationName(operation)) + } + table := extractTableName(query) + if table != "" { + attrs = append(attrs, semconv.DBCollectionName(table)) + } + if len(attrs) > 0 { + return attrs + } + // If nothing extracted, return empty (or fallback to other attributes if needed) + return nil + }), + ) if err != nil { return nil, err } @@ -265,8 +355,15 @@ func (s *MySQL) open(logger *slog.Logger) (*conn, error) { for k, v := range s.params { cfg.Params[k] = v } - - db, err := sql.Open("mysql", cfg.FormatDSN()) + db, err := otelsql.Open("mysql", cfg.FormatDSN(), otelsql.WithAttributes( + semconv.DBSystemNameMySQL, + )) + if err != nil { + return nil, err + } + err = otelsql.RegisterDBStatsMetrics(db, otelsql.WithAttributes( + semconv.DBSystemNameMySQL, + )) if err != nil { return nil, err } @@ -289,7 +386,15 @@ func (s *MySQL) open(logger *slog.Logger) (*conn, error) { delete(cfg.Params, "transaction_isolation") cfg.Params["tx_isolation"] = "'SERIALIZABLE'" - db, err = sql.Open("mysql", cfg.FormatDSN()) + db, err = otelsql.Open("mysql", cfg.FormatDSN(), otelsql.WithAttributes( + semconv.DBSystemNameMySQL, + )) + if err != nil { + return nil, err + } + err = otelsql.RegisterDBStatsMetrics(db, otelsql.WithAttributes( + semconv.DBSystemNameMySQL, + )) if err != nil { return nil, err } diff --git a/storage/sql/crud.go b/storage/sql/crud.go index a9ca38167d..8b93d4f284 100644 --- a/storage/sql/crud.go +++ b/storage/sql/crud.go @@ -77,6 +77,7 @@ func (j jsonDecoder) Scan(dest interface{}) error { // Abstract conn vs trans. type querier interface { QueryRow(query string, args ...interface{}) *sql.Row + QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row } // Abstract row vs rows. @@ -86,10 +87,10 @@ type scanner interface { var _ storage.Storage = (*conn)(nil) -func (c *conn) GarbageCollect(ctc context.Context, now time.Time) (storage.GCResult, error) { +func (c *conn) GarbageCollect(ctx context.Context, now time.Time) (storage.GCResult, error) { result := storage.GCResult{} - r, err := c.Exec(`delete from auth_request where expiry < $1`, now) + r, err := c.ExecContext(ctx, `delete from auth_request where expiry < $1`, now) if err != nil { return result, fmt.Errorf("gc auth_request: %v", err) } @@ -97,7 +98,7 @@ func (c *conn) GarbageCollect(ctc context.Context, now time.Time) (storage.GCRes result.AuthRequests = n } - r, err = c.Exec(`delete from auth_code where expiry < $1`, now) + r, err = c.ExecContext(ctx, `delete from auth_code where expiry < $1`, now) if err != nil { return result, fmt.Errorf("gc auth_code: %v", err) } @@ -105,7 +106,7 @@ func (c *conn) GarbageCollect(ctc context.Context, now time.Time) (storage.GCRes result.AuthCodes = n } - r, err = c.Exec(`delete from device_request where expiry < $1`, now) + r, err = c.ExecContext(ctx, `delete from device_request where expiry < $1`, now) if err != nil { return result, fmt.Errorf("gc device_request: %v", err) } @@ -113,7 +114,7 @@ func (c *conn) GarbageCollect(ctc context.Context, now time.Time) (storage.GCRes result.DeviceRequests = n } - r, err = c.Exec(`delete from device_token where expiry < $1`, now) + r, err = c.ExecContext(ctx, `delete from device_token where expiry < $1`, now) if err != nil { return result, fmt.Errorf("gc device_token: %v", err) } @@ -125,7 +126,7 @@ func (c *conn) GarbageCollect(ctc context.Context, now time.Time) (storage.GCRes } func (c *conn) CreateAuthRequest(ctx context.Context, a storage.AuthRequest) error { - _, err := c.Exec(` + _, err := c.ExecContext(ctx, ` insert into auth_request ( id, client_id, response_types, scopes, redirect_uri, nonce, state, force_approval_prompt, logged_in, @@ -159,7 +160,7 @@ func (c *conn) CreateAuthRequest(ctx context.Context, a storage.AuthRequest) err } func (c *conn) UpdateAuthRequest(ctx context.Context, id string, updater func(a storage.AuthRequest) (storage.AuthRequest, error)) error { - return c.ExecTx(func(tx *trans) error { + return c.ExecTxContext(ctx, func(tx *trans) error { r, err := getAuthRequest(ctx, tx, id) if err != nil { return err @@ -169,7 +170,7 @@ func (c *conn) UpdateAuthRequest(ctx context.Context, id string, updater func(a if err != nil { return err } - _, err = tx.Exec(` + _, err = tx.ExecContext(ctx, ` update auth_request set client_id = $1, response_types = $2, scopes = $3, redirect_uri = $4, @@ -205,7 +206,7 @@ func (c *conn) GetAuthRequest(ctx context.Context, id string) (storage.AuthReque } func getAuthRequest(ctx context.Context, q querier, id string) (a storage.AuthRequest, err error) { - err = q.QueryRow(` + err = q.QueryRowContext(ctx, ` select id, client_id, response_types, scopes, redirect_uri, nonce, state, force_approval_prompt, logged_in, @@ -233,7 +234,7 @@ func getAuthRequest(ctx context.Context, q querier, id string) (a storage.AuthRe } func (c *conn) CreateAuthCode(ctx context.Context, a storage.AuthCode) error { - _, err := c.Exec(` + _, err := c.ExecContext(ctx, ` insert into auth_code ( id, client_id, scopes, nonce, redirect_uri, claims_user_id, claims_username, claims_preferred_username, @@ -259,7 +260,7 @@ func (c *conn) CreateAuthCode(ctx context.Context, a storage.AuthCode) error { } func (c *conn) GetAuthCode(ctx context.Context, id string) (a storage.AuthCode, err error) { - err = c.QueryRow(` + err = c.QueryRowContext(ctx, ` select id, client_id, scopes, nonce, redirect_uri, claims_user_id, claims_username, claims_preferred_username, @@ -284,7 +285,7 @@ func (c *conn) GetAuthCode(ctx context.Context, id string) (a storage.AuthCode, } func (c *conn) CreateRefresh(ctx context.Context, r storage.RefreshToken) error { - _, err := c.Exec(` + _, err := c.ExecContext(ctx, ` insert into refresh_token ( id, client_id, scopes, nonce, claims_user_id, claims_username, claims_preferred_username, @@ -311,7 +312,7 @@ func (c *conn) CreateRefresh(ctx context.Context, r storage.RefreshToken) error } func (c *conn) UpdateRefreshToken(ctx context.Context, id string, updater func(old storage.RefreshToken) (storage.RefreshToken, error)) error { - return c.ExecTx(func(tx *trans) error { + return c.ExecTxContext(ctx, func(tx *trans) error { r, err := getRefresh(ctx, tx, id) if err != nil { return err @@ -319,7 +320,7 @@ func (c *conn) UpdateRefreshToken(ctx context.Context, id string, updater func(o if r, err = updater(r); err != nil { return err } - _, err = tx.Exec(` + _, err = tx.ExecContext(ctx, ` update refresh_token set client_id = $1, @@ -359,7 +360,7 @@ func (c *conn) GetRefresh(ctx context.Context, id string) (storage.RefreshToken, } func getRefresh(ctx context.Context, q querier, id string) (storage.RefreshToken, error) { - return scanRefresh(q.QueryRow(` + return scanRefresh(q.QueryRowContext(ctx, ` select id, client_id, scopes, nonce, claims_user_id, claims_username, claims_preferred_username, @@ -372,7 +373,7 @@ func getRefresh(ctx context.Context, q querier, id string) (storage.RefreshToken } func (c *conn) ListRefreshTokens(ctx context.Context) ([]storage.RefreshToken, error) { - rows, err := c.Query(` + rows, err := c.QueryContext(ctx, ` select id, client_id, scopes, nonce, claims_user_id, claims_username, claims_preferred_username, @@ -419,7 +420,7 @@ func scanRefresh(s scanner) (r storage.RefreshToken, err error) { } func (c *conn) UpdateKeys(ctx context.Context, updater func(old storage.Keys) (storage.Keys, error)) error { - return c.ExecTx(func(tx *trans) error { + return c.ExecTxContext(ctx, func(tx *trans) error { firstUpdate := false // TODO(ericchiang): errors may cause a transaction be rolled back by the SQL // server. Test this, and consider adding a COUNT() command beforehand. @@ -438,7 +439,7 @@ func (c *conn) UpdateKeys(ctx context.Context, updater func(old storage.Keys) (s } if firstUpdate { - _, err = tx.Exec(` + _, err = tx.ExecContext(ctx, ` insert into keys ( id, verification_keys, signing_key, signing_key_pub, next_rotation ) @@ -451,7 +452,7 @@ func (c *conn) UpdateKeys(ctx context.Context, updater func(old storage.Keys) (s return fmt.Errorf("insert: %v", err) } } else { - _, err = tx.Exec(` + _, err = tx.ExecContext(ctx, ` update keys set verification_keys = $1, @@ -476,7 +477,7 @@ func (c *conn) GetKeys(ctx context.Context) (keys storage.Keys, err error) { } func getKeys(ctx context.Context, q querier) (keys storage.Keys, err error) { - err = q.QueryRow(` + err = q.QueryRowContext(ctx, ` select verification_keys, signing_key, signing_key_pub, next_rotation from keys @@ -495,7 +496,7 @@ func getKeys(ctx context.Context, q querier) (keys storage.Keys, err error) { } func (c *conn) UpdateClient(ctx context.Context, id string, updater func(old storage.Client) (storage.Client, error)) error { - return c.ExecTx(func(tx *trans) error { + return c.ExecTxContext(ctx, func(tx *trans) error { cli, err := getClient(ctx, tx, id) if err != nil { return err @@ -505,7 +506,7 @@ func (c *conn) UpdateClient(ctx context.Context, id string, updater func(old sto return err } - _, err = tx.Exec(` + _, err = tx.ExecContext(ctx, ` update client set secret = $1, @@ -525,7 +526,7 @@ func (c *conn) UpdateClient(ctx context.Context, id string, updater func(old sto } func (c *conn) CreateClient(ctx context.Context, cli storage.Client) error { - _, err := c.Exec(` + _, err := c.ExecContext(ctx, ` insert into client ( id, secret, redirect_uris, trusted_peers, public, name, logo_url ) @@ -544,7 +545,7 @@ func (c *conn) CreateClient(ctx context.Context, cli storage.Client) error { } func getClient(ctx context.Context, q querier, id string) (storage.Client, error) { - return scanClient(q.QueryRow(` + return scanClient(q.QueryRowContext(ctx, ` select id, secret, redirect_uris, trusted_peers, public, name, logo_url from client where id = $1; @@ -556,7 +557,7 @@ func (c *conn) GetClient(ctx context.Context, id string) (storage.Client, error) } func (c *conn) ListClients(ctx context.Context) ([]storage.Client, error) { - rows, err := c.Query(` + rows, err := c.QueryContext(ctx, ` select id, secret, redirect_uris, trusted_peers, public, name, logo_url from client; @@ -596,7 +597,7 @@ func scanClient(s scanner) (cli storage.Client, err error) { func (c *conn) CreatePassword(ctx context.Context, p storage.Password) error { p.Email = strings.ToLower(p.Email) - _, err := c.Exec(` + _, err := c.ExecContext(ctx, ` insert into password ( email, hash, username, user_id ) @@ -616,7 +617,7 @@ func (c *conn) CreatePassword(ctx context.Context, p storage.Password) error { } func (c *conn) UpdatePassword(ctx context.Context, email string, updater func(p storage.Password) (storage.Password, error)) error { - return c.ExecTx(func(tx *trans) error { + return c.ExecTxContext(ctx, func(tx *trans) error { p, err := getPassword(ctx, tx, email) if err != nil { return err @@ -626,7 +627,7 @@ func (c *conn) UpdatePassword(ctx context.Context, email string, updater func(p if err != nil { return err } - _, err = tx.Exec(` + _, err = tx.ExecContext(ctx, ` update password set hash = $1, username = $2, user_id = $3 @@ -646,7 +647,7 @@ func (c *conn) GetPassword(ctx context.Context, email string) (storage.Password, } func getPassword(ctx context.Context, q querier, email string) (p storage.Password, err error) { - return scanPassword(q.QueryRow(` + return scanPassword(q.QueryRowContext(ctx, ` select email, hash, username, user_id from password where email = $1; @@ -654,7 +655,7 @@ func getPassword(ctx context.Context, q querier, email string) (p storage.Passwo } func (c *conn) ListPasswords(ctx context.Context) ([]storage.Password, error) { - rows, err := c.Query(` + rows, err := c.QueryContext(ctx, ` select email, hash, username, user_id from password; @@ -692,7 +693,7 @@ func scanPassword(s scanner) (p storage.Password, err error) { } func (c *conn) CreateOfflineSessions(ctx context.Context, s storage.OfflineSessions) error { - _, err := c.Exec(` + _, err := c.ExecContext(ctx, ` insert into offline_session ( user_id, conn_id, refresh, connector_data ) @@ -712,7 +713,7 @@ func (c *conn) CreateOfflineSessions(ctx context.Context, s storage.OfflineSessi } func (c *conn) UpdateOfflineSessions(ctx context.Context, userID string, connID string, updater func(s storage.OfflineSessions) (storage.OfflineSessions, error)) error { - return c.ExecTx(func(tx *trans) error { + return c.ExecTxContext(ctx, func(tx *trans) error { s, err := getOfflineSessions(ctx, tx, userID, connID) if err != nil { return err @@ -722,7 +723,7 @@ func (c *conn) UpdateOfflineSessions(ctx context.Context, userID string, connID if err != nil { return err } - _, err = tx.Exec(` + _, err = tx.ExecContext(ctx, ` update offline_session set refresh = $1, @@ -743,7 +744,7 @@ func (c *conn) GetOfflineSessions(ctx context.Context, userID string, connID str } func getOfflineSessions(ctx context.Context, q querier, userID string, connID string) (storage.OfflineSessions, error) { - return scanOfflineSessions(q.QueryRow(` + return scanOfflineSessions(q.QueryRowContext(ctx, ` select user_id, conn_id, refresh, connector_data from offline_session @@ -765,7 +766,7 @@ func scanOfflineSessions(s scanner) (o storage.OfflineSessions, err error) { } func (c *conn) CreateConnector(ctx context.Context, connector storage.Connector) error { - _, err := c.Exec(` + _, err := c.ExecContext(ctx, ` insert into connector ( id, type, name, resource_version, config ) @@ -785,7 +786,7 @@ func (c *conn) CreateConnector(ctx context.Context, connector storage.Connector) } func (c *conn) UpdateConnector(ctx context.Context, id string, updater func(s storage.Connector) (storage.Connector, error)) error { - return c.ExecTx(func(tx *trans) error { + return c.ExecTxContext(ctx, func(tx *trans) error { connector, err := getConnector(ctx, tx, id) if err != nil { return err @@ -795,7 +796,7 @@ func (c *conn) UpdateConnector(ctx context.Context, id string, updater func(s st if err != nil { return err } - _, err = tx.Exec(` + _, err = tx.ExecContext(ctx, ` update connector set type = $1, @@ -818,7 +819,7 @@ func (c *conn) GetConnector(ctx context.Context, id string) (storage.Connector, } func getConnector(ctx context.Context, q querier, id string) (storage.Connector, error) { - return scanConnector(q.QueryRow(` + return scanConnector(q.QueryRowContext(ctx, ` select id, type, name, resource_version, config from connector @@ -840,7 +841,7 @@ func scanConnector(s scanner) (c storage.Connector, err error) { } func (c *conn) ListConnectors(ctx context.Context) ([]storage.Connector, error) { - rows, err := c.Query(` + rows, err := c.QueryContext(ctx, ` select id, type, name, resource_version, config from connector; @@ -865,31 +866,31 @@ func (c *conn) ListConnectors(ctx context.Context) ([]storage.Connector, error) } func (c *conn) DeleteAuthRequest(ctx context.Context, id string) error { - return c.delete("auth_request", "id", id) + return c.deleteContext(ctx, "auth_request", "id", id) } func (c *conn) DeleteAuthCode(ctx context.Context, id string) error { - return c.delete("auth_code", "id", id) + return c.deleteContext(ctx, "auth_code", "id", id) } func (c *conn) DeleteClient(ctx context.Context, id string) error { - return c.delete("client", "id", id) + return c.deleteContext(ctx, "client", "id", id) } func (c *conn) DeleteRefresh(ctx context.Context, id string) error { - return c.delete("refresh_token", "id", id) + return c.deleteContext(ctx, "refresh_token", "id", id) } func (c *conn) DeletePassword(ctx context.Context, email string) error { - return c.delete("password", "email", strings.ToLower(email)) + return c.deleteContext(ctx, "password", "email", strings.ToLower(email)) } func (c *conn) DeleteConnector(ctx context.Context, id string) error { - return c.delete("connector", "id", id) + return c.deleteContext(ctx, "connector", "id", id) } func (c *conn) DeleteOfflineSessions(ctx context.Context, userID string, connID string) error { - result, err := c.Exec(`delete from offline_session where user_id = $1 AND conn_id = $2`, userID, connID) + result, err := c.ExecContext(ctx, `delete from offline_session where user_id = $1 AND conn_id = $2`, userID, connID) if err != nil { return fmt.Errorf("delete offline_session: user_id = %s, conn_id = %s", userID, connID) } @@ -906,9 +907,8 @@ func (c *conn) DeleteOfflineSessions(ctx context.Context, userID string, connID return nil } -// Do NOT call directly. Does not escape table. -func (c *conn) delete(table, field, id string) error { - result, err := c.Exec(`delete from `+table+` where `+field+` = $1`, id) +func (c *conn) deleteContext(ctx context.Context, table, field, id string) error { + result, err := c.ExecContext(ctx, `delete from `+table+` where `+field+` = $1`, id) if err != nil { return fmt.Errorf("delete %s: %v", table, id) } @@ -926,7 +926,7 @@ func (c *conn) delete(table, field, id string) error { } func (c *conn) CreateDeviceRequest(ctx context.Context, d storage.DeviceRequest) error { - _, err := c.Exec(` + _, err := c.ExecContext(ctx, ` insert into device_request ( user_code, device_code, client_id, client_secret, scopes, expiry ) @@ -945,7 +945,7 @@ func (c *conn) CreateDeviceRequest(ctx context.Context, d storage.DeviceRequest) } func (c *conn) CreateDeviceToken(ctx context.Context, t storage.DeviceToken) error { - _, err := c.Exec(` + _, err := c.ExecContext(ctx, ` insert into device_token ( device_code, status, token, expiry, last_request, poll_interval, code_challenge, code_challenge_method ) @@ -968,7 +968,7 @@ func (c *conn) GetDeviceRequest(ctx context.Context, userCode string) (storage.D } func getDeviceRequest(ctx context.Context, q querier, userCode string) (d storage.DeviceRequest, err error) { - err = q.QueryRow(` + err = q.QueryRowContext(ctx, ` select device_code, client_id, client_secret, scopes, expiry from device_request where user_code = $1; @@ -982,6 +982,7 @@ func getDeviceRequest(ctx context.Context, q querier, userCode string) (d storag return d, fmt.Errorf("select device token: %v", err) } d.UserCode = userCode + d.Expiry = d.Expiry.UTC() return d, nil } @@ -990,7 +991,7 @@ func (c *conn) GetDeviceToken(ctx context.Context, deviceCode string) (storage.D } func getDeviceToken(ctx context.Context, q querier, deviceCode string) (a storage.DeviceToken, err error) { - err = q.QueryRow(` + err = q.QueryRowContext(ctx, ` select status, token, expiry, last_request, poll_interval, code_challenge, code_challenge_method from device_token where device_code = $1; @@ -1008,7 +1009,7 @@ func getDeviceToken(ctx context.Context, q querier, deviceCode string) (a storag } func (c *conn) UpdateDeviceToken(ctx context.Context, deviceCode string, updater func(old storage.DeviceToken) (storage.DeviceToken, error)) error { - return c.ExecTx(func(tx *trans) error { + return c.ExecTxContext(ctx, func(tx *trans) error { r, err := getDeviceToken(ctx, tx, deviceCode) if err != nil { return err diff --git a/storage/sql/crud_test.go b/storage/sql/crud_test.go index 7cca1d6fcd..d744e97594 100644 --- a/storage/sql/crud_test.go +++ b/storage/sql/crud_test.go @@ -4,9 +4,17 @@ package sql import ( + "context" "database/sql" + "log/slog" "reflect" + "sort" "testing" + + "github.com/go-jose/go-jose/v4/json" + "github.com/stretchr/testify/require" + + "github.com/dexidp/dex/storage" ) func TestDecoder(t *testing.T) { @@ -56,3 +64,187 @@ func TestEncoder(t *testing.T) { t.Errorf("wanted %q got %q", want, got) } } + +func Test_conn_ListClients(t *testing.T) { + type fields struct { + db *sql.DB + flavor *flavor + logger *slog.Logger + alreadyExistsCheck func(err error) bool + } + type args struct { + ctx context.Context + } + tests := []struct { + name string + fields fields + args args + setup func(db *sql.DB) + want []storage.Client + wantErr bool + }{ + { + name: "empty database", + fields: fields{ + flavor: &flavorSQLite3, + logger: slog.Default(), + alreadyExistsCheck: func(err error) bool { return false }, + }, + args: args{ + ctx: context.Background(), + }, + setup: func(db *sql.DB) { + // Create table with BLOB for JSON fields + _, err := db.Exec(` + CREATE TABLE client ( + id TEXT PRIMARY KEY, + secret TEXT, + redirect_uris BLOB, + trusted_peers BLOB, + public INTEGER, + name TEXT, + logo_url TEXT + ); + `) + require.NoError(t, err) + }, + want: nil, + }, + { + name: "multiple clients", + fields: fields{ + flavor: &flavorSQLite3, + logger: slog.Default(), + alreadyExistsCheck: func(err error) bool { return false }, + }, + args: args{ + ctx: context.Background(), + }, + setup: func(db *sql.DB) { + // Create table with BLOB for JSON fields + _, err := db.Exec(` + CREATE TABLE client ( + id TEXT PRIMARY KEY, + secret TEXT, + redirect_uris BLOB, + trusted_peers BLOB, + public INTEGER, + name TEXT, + logo_url TEXT + ); + `) + require.NoError(t, err) + + // Insert data with []byte JSON + redirect1, _ := json.Marshal([]string{"uri1"}) + trusted1, _ := json.Marshal([]string{"peer1"}) + _, err = db.Exec(` + INSERT INTO client (id, secret, redirect_uris, trusted_peers, public, name, logo_url) + VALUES ('client1', 'secret1', ?, ?, 1, 'name1', 'logo1'); + `, redirect1, trusted1) + require.NoError(t, err) + + redirect2, _ := json.Marshal([]string{"uri2"}) + trusted2, _ := json.Marshal([]string{"peer2"}) + _, err = db.Exec(` + INSERT INTO client (id, secret, redirect_uris, trusted_peers, public, name, logo_url) + VALUES ('client2', 'secret2', ?, ?, 0, 'name2', 'logo2'); + `, redirect2, trusted2) + require.NoError(t, err) + }, + want: []storage.Client{ + {ID: "client1", Secret: "secret1", RedirectURIs: []string{"uri1"}, TrustedPeers: []string{"peer1"}, Public: true, Name: "name1", LogoURL: "logo1"}, + {ID: "client2", Secret: "secret2", RedirectURIs: []string{"uri2"}, TrustedPeers: []string{"peer2"}, Public: false, Name: "name2", LogoURL: "logo2"}, + }, + }, + { + name: "multiple broken clients", + fields: fields{ + flavor: &flavorSQLite3, + logger: slog.Default(), + alreadyExistsCheck: func(err error) bool { return false }, + }, + args: args{ + ctx: context.Background(), + }, + setup: func(db *sql.DB) { + // Create table with BLOB for JSON fields + _, err := db.Exec(` + CREATE TABLE client ( + id TEXT PRIMARY KEY, + secret TEXT, + redirect_uris BLOB, + trusted_peers BLOB, + public INTEGER, + name TEXT, + logo_url TEXT + ); + `) + require.NoError(t, err) + + // Insert data with []byte JSON + redirect1, _ := json.Marshal([]string{"uri1"}) + trusted1, _ := json.Marshal([]string{"peer1"}) + _, err = db.Exec(` + INSERT INTO client (id, secret, redirect_uris, trusted_peers, public, name, logo_url) + VALUES ('client1', 'secret1', ?, ?, 1, 'name1', 'logo1'); + `, string(redirect1), string(trusted1)) + require.NoError(t, err) + + redirect2, _ := json.Marshal([]string{"uri2"}) + trusted2, _ := json.Marshal([]string{"peer2"}) + _, err = db.Exec(` + INSERT INTO client (id, secret, redirect_uris, trusted_peers, public, name, logo_url) + VALUES ('client2', 'secret2', ?, ?, 0, 'name2', 'logo2'); + `, string(redirect2), string(trusted2)) + require.NoError(t, err) + }, + want: nil, + wantErr: true, // Expect error due to broken JSON + }, + { + name: "query error", + fields: fields{ + flavor: &flavorSQLite3, + logger: slog.Default(), + alreadyExistsCheck: func(err error) bool { return false }, + }, + args: args{ + ctx: context.Background(), + }, + setup: func(db *sql.DB) { + db.Close() // Cause query to fail + }, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + db, err := sql.Open("sqlite3", ":memory:") + require.NoError(t, err) + defer db.Close() + + tt.fields.db = db + if tt.setup != nil { + tt.setup(db) + } + + c := &conn{ + db: tt.fields.db, + flavor: tt.fields.flavor, + logger: tt.fields.logger, + alreadyExistsCheck: tt.fields.alreadyExistsCheck, + } + got, err := c.ListClients(tt.args.ctx) + if tt.wantErr { + require.Error(t, err) + return + } + require.NoError(t, err) + // Sort for consistent order + sort.Slice(got, func(i, j int) bool { return got[i].ID < got[j].ID }) + sort.Slice(tt.want, func(i, j int) bool { return tt.want[i].ID < tt.want[j].ID }) + require.Equal(t, tt.want, got) + }) + } +} diff --git a/storage/sql/sql.go b/storage/sql/sql.go index d671021fca..e9490c54e7 100644 --- a/storage/sql/sql.go +++ b/storage/sql/sql.go @@ -2,6 +2,7 @@ package sql import ( + "context" "database/sql" "log/slog" "regexp" @@ -10,6 +11,8 @@ import ( // import third party drivers _ "github.com/lib/pq" _ "github.com/mattn/go-sqlite3" + + "github.com/dexidp/dex/pkg/otel/traces" ) // flavor represents a specific SQL implementation, and is used to translate query strings @@ -145,11 +148,45 @@ func (c *conn) Exec(query string, args ...interface{}) (sql.Result, error) { return c.db.Exec(query, c.translateArgs(args)...) } +func (c *conn) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.db_exec") + defer span.End() + query = c.flavor.translate(query) + // Translate args to the flavor. + args = c.translateArgs(args) + // Use the context-aware Exec method. + result, err := c.db.ExecContext(ctx, query, args...) + if err != nil { + return nil, err + } + return result, nil +} + func (c *conn) Query(query string, args ...interface{}) (*sql.Rows, error) { query = c.flavor.translate(query) return c.db.Query(query, c.translateArgs(args)...) } +func (c *conn) QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.db_query") + defer span.End() + query = c.flavor.translate(query) + // Translate args to the flavor. + args = c.translateArgs(args) + // Use the context-aware Query method. + return c.db.QueryContext(ctx, query, args...) +} + +func (c *conn) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row { + ctx, span := traces.InstrumentationTracer(ctx, "dex.query_row") + defer span.End() + query = c.flavor.translate(query) + // Translate args to the flavor. + args = c.translateArgs(args) + // Use the context-aware QueryRow method. + return c.db.QueryRowContext(ctx, query, args...) +} + func (c *conn) QueryRow(query string, args ...interface{}) *sql.Row { query = c.flavor.translate(query) return c.db.QueryRow(query, c.translateArgs(args)...) @@ -174,6 +211,27 @@ func (c *conn) ExecTx(fn func(tx *trans) error) error { return sqlTx.Commit() } +func (c *conn) ExecTxContext(ctx context.Context, fn func(tx *trans) error) error { + ctx, span := traces.InstrumentationTracer(ctx, "dex.db_exec_tx") + defer span.End() + + if c.flavor.executeTx != nil { + return c.flavor.executeTx(c.db, func(sqlTx *sql.Tx) error { + return fn(&trans{sqlTx, c}) + }) + } + + sqlTx, err := c.db.BeginTx(ctx, nil) + if err != nil { + return err + } + if err := fn(&trans{sqlTx, c}); err != nil { + sqlTx.Rollback() + return err + } + return sqlTx.Commit() +} + type trans struct { tx *sql.Tx c *conn @@ -195,3 +253,27 @@ func (t *trans) QueryRow(query string, args ...interface{}) *sql.Row { query = t.c.flavor.translate(query) return t.tx.QueryRow(query, t.c.translateArgs(args)...) } + +func (t *trans) ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.db_exec") + defer span.End() + query = t.c.flavor.translate(query) + // Translate args to the flavor. + args = t.c.translateArgs(args) + // Translate args to the flavor. + result, err := t.tx.ExecContext(ctx, query, args...) + if err != nil { + return nil, err + } + return result, nil +} + +func (t *trans) QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row { + ctx, span := traces.InstrumentationTracer(ctx, "dex.db_query_row") + defer span.End() + query = t.c.flavor.translate(query) + // Translate args to the flavor. + args = t.c.translateArgs(args) + // Use the context-aware QueryRow method. + return t.tx.QueryRowContext(ctx, query, args...) +} diff --git a/storage/static.go b/storage/static.go index 386b2b2883..fa7b070ecb 100644 --- a/storage/static.go +++ b/storage/static.go @@ -5,6 +5,10 @@ import ( "errors" "log/slog" "strings" + + "go.opentelemetry.io/otel/attribute" + + "github.com/dexidp/dex/pkg/otel/traces" ) // Tests for this code are in the "memory" package, since this package doesn't @@ -186,6 +190,9 @@ func (s staticConnectorsStorage) isStatic(id string) bool { } func (s staticConnectorsStorage) GetConnector(ctx context.Context, id string) (Connector, error) { + ctx, span := traces.InstrumentationTracer(ctx, "dex.storage.staticConnectorsStorage.GetConnector") + defer span.End() + span.SetAttributes(attribute.String("dex.connector.id", id)) if connector, ok := s.connectorsByID[id]; ok { return connector, nil } diff --git a/storage/static_test.go b/storage/static_test.go new file mode 100644 index 0000000000..8957211975 --- /dev/null +++ b/storage/static_test.go @@ -0,0 +1,1892 @@ +package storage + +import ( + "context" + "errors" + "log/slog" + "sort" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +type mockStorage struct { + Storage + + clients map[string]Client + connectors map[string]Connector + passwords map[string]Password + updateErr error + listErr error + getErr error + createErr error + deleteErr error +} + +func newMockStorage() *mockStorage { + return &mockStorage{ + clients: make(map[string]Client), + connectors: make(map[string]Connector), + passwords: make(map[string]Password), + } +} + +func (m *mockStorage) GetClient(ctx context.Context, id string) (Client, error) { + if m.getErr != nil { + return Client{}, m.getErr + } + c, ok := m.clients[id] + if !ok { + return Client{}, ErrNotFound + } + return c, nil +} + +func (m *mockStorage) ListClients(ctx context.Context) ([]Client, error) { + if m.listErr != nil { + return nil, m.listErr + } + cs := make([]Client, 0, len(m.clients)) + for _, c := range m.clients { + cs = append(cs, c) + } + sort.Slice(cs, func(i, j int) bool { return cs[i].ID < cs[j].ID }) + return cs, nil +} + +func (m *mockStorage) CreateClient(ctx context.Context, c Client) error { + if m.createErr != nil { + return m.createErr + } + m.clients[c.ID] = c + return nil +} + +func (m *mockStorage) DeleteClient(ctx context.Context, id string) error { + if m.deleteErr != nil { + return m.deleteErr + } + delete(m.clients, id) + return nil +} + +func (m *mockStorage) UpdateClient(ctx context.Context, id string, updater func(old Client) (Client, error)) error { + if m.updateErr != nil { + return m.updateErr + } + old, ok := m.clients[id] + if !ok { + return ErrNotFound + } + newC, err := updater(old) + if err != nil { + return err + } + m.clients[id] = newC + return nil +} + +func (m *mockStorage) GetConnector(ctx context.Context, id string) (Connector, error) { + if m.getErr != nil { + return Connector{}, m.getErr + } + c, ok := m.connectors[id] + if !ok { + return Connector{}, ErrNotFound + } + return c, nil +} + +func (m *mockStorage) ListConnectors(ctx context.Context) ([]Connector, error) { + if m.listErr != nil { + return nil, m.listErr + } + cs := make([]Connector, 0, len(m.connectors)) + for _, c := range m.connectors { + cs = append(cs, c) + } + sort.Slice(cs, func(i, j int) bool { return cs[i].ID < cs[j].ID }) + return cs, nil +} + +func (m *mockStorage) CreateConnector(ctx context.Context, c Connector) error { + if m.createErr != nil { + return m.createErr + } + m.connectors[c.ID] = c + return nil +} + +func (m *mockStorage) DeleteConnector(ctx context.Context, id string) error { + if m.deleteErr != nil { + return m.deleteErr + } + delete(m.connectors, id) + return nil +} + +func (m *mockStorage) UpdateConnector(ctx context.Context, id string, updater func(old Connector) (Connector, error)) error { + if m.updateErr != nil { + return m.updateErr + } + old, ok := m.connectors[id] + if !ok { + return ErrNotFound + } + newC, err := updater(old) + if err != nil { + return err + } + m.connectors[id] = newC + return nil +} + +func (m *mockStorage) GetPassword(ctx context.Context, email string) (Password, error) { + if m.getErr != nil { + return Password{}, m.getErr + } + p, ok := m.passwords[strings.ToLower(email)] + if !ok { + return Password{}, ErrNotFound + } + return p, nil +} + +func (m *mockStorage) ListPasswords(ctx context.Context) ([]Password, error) { + if m.listErr != nil { + return nil, m.listErr + } + ps := make([]Password, 0, len(m.passwords)) + for _, p := range m.passwords { + ps = append(ps, p) + } + sort.Slice(ps, func(i, j int) bool { return strings.ToLower(ps[i].Email) < strings.ToLower(ps[j].Email) }) + return ps, nil +} + +func (m *mockStorage) CreatePassword(ctx context.Context, p Password) error { + if m.createErr != nil { + return m.createErr + } + m.passwords[strings.ToLower(p.Email)] = p + return nil +} + +func (m *mockStorage) DeletePassword(ctx context.Context, email string) error { + if m.deleteErr != nil { + return m.deleteErr + } + delete(m.passwords, strings.ToLower(email)) + return nil +} + +func (m *mockStorage) UpdatePassword(ctx context.Context, email string, updater func(old Password) (Password, error)) error { + if m.updateErr != nil { + return m.updateErr + } + old, ok := m.passwords[strings.ToLower(email)] + if !ok { + return ErrNotFound + } + newP, err := updater(old) + if err != nil { + return err + } + m.passwords[strings.ToLower(email)] = newP + return nil +} + +func TestWithStaticClients(t *testing.T) { + type args struct { + s Storage + staticClients []Client + } + tests := []struct { + name string + args args + want Storage + }{ + { + name: "basic", + args: args{ + s: newMockStorage(), + staticClients: []Client{{ID: "static1"}, {ID: "static2"}}, + }, + want: staticClientsStorage{ + Storage: newMockStorage(), + clients: []Client{{ID: "static1"}, {ID: "static2"}}, + clientsByID: map[string]Client{"static1": {ID: "static1"}, "static2": {ID: "static2"}}, + }, + }, + { + name: "empty static", + args: args{ + s: newMockStorage(), + staticClients: []Client{}, + }, + want: staticClientsStorage{ + Storage: newMockStorage(), + clients: []Client{}, + clientsByID: map[string]Client{}, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := WithStaticClients(tt.args.s, tt.args.staticClients) + require.Equal(t, tt.want, got) + }) + } +} + +func TestWithStaticConnectors(t *testing.T) { + type args struct { + s Storage + staticConnectors []Connector + } + tests := []struct { + name string + args args + want Storage + }{ + { + name: "basic", + args: args{ + s: newMockStorage(), + staticConnectors: []Connector{{ID: "static1"}, {ID: "static2"}}, + }, + want: staticConnectorsStorage{ + Storage: newMockStorage(), + connectors: []Connector{{ID: "static1"}, {ID: "static2"}}, + connectorsByID: map[string]Connector{"static1": {ID: "static1"}, "static2": {ID: "static2"}}, + }, + }, + { + name: "empty static", + args: args{ + s: newMockStorage(), + staticConnectors: []Connector{}, + }, + want: staticConnectorsStorage{ + Storage: newMockStorage(), + connectors: []Connector{}, + connectorsByID: map[string]Connector{}, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := WithStaticConnectors(tt.args.s, tt.args.staticConnectors) + require.Equal(t, tt.want, got) + }) + } +} + +func TestWithStaticPasswords(t *testing.T) { + logger := slog.Default() + type args struct { + s Storage + staticPasswords []Password + logger *slog.Logger + } + tests := []struct { + name string + args args + want Storage + }{ + { + name: "basic", + args: args{ + s: newMockStorage(), + staticPasswords: []Password{{Email: "static1@example.com"}, {Email: "Static2@Example.com"}}, + logger: logger, + }, + want: staticPasswordsStorage{ + Storage: newMockStorage(), + passwords: []Password{{Email: "static1@example.com"}, {Email: "Static2@Example.com"}}, + passwordsByEmail: map[string]Password{"static1@example.com": {Email: "static1@example.com"}, "static2@example.com": {Email: "Static2@Example.com"}}, + logger: logger, + }, + }, + { + name: "empty static", + args: args{ + s: newMockStorage(), + staticPasswords: []Password{}, + logger: logger, + }, + want: staticPasswordsStorage{ + Storage: newMockStorage(), + passwords: []Password{}, + passwordsByEmail: map[string]Password{}, + logger: logger, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := WithStaticPasswords(tt.args.s, tt.args.staticPasswords, tt.args.logger) + require.Equal(t, tt.want, got) + }) + } +} + +func Test_staticClientsStorage_CreateClient(t *testing.T) { + ctx := context.Background() + type fields struct { + Storage Storage + clients []Client + clientsByID map[string]Client + } + type args struct { + ctx context.Context + c Client + } + tests := []struct { + name string + fields fields + args args + wantErr bool + }{ + { + name: "create dynamic", + fields: fields{ + Storage: newMockStorage(), + }, + args: args{ + ctx: ctx, + c: Client{ID: "dynamic"}, + }, + wantErr: false, + }, + { + name: "create static", + fields: fields{ + Storage: newMockStorage(), + clientsByID: map[string]Client{"static": {ID: "static"}}, + }, + args: args{ + ctx: ctx, + c: Client{ID: "static"}, + }, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := staticClientsStorage{ + Storage: tt.fields.Storage, + clients: tt.fields.clients, + clientsByID: tt.fields.clientsByID, + } + err := s.CreateClient(tt.args.ctx, tt.args.c) + if tt.wantErr { + require.Error(t, err) + require.Contains(t, err.Error(), "read-only cannot create client") + return + } + require.NoError(t, err) + got, err := tt.fields.Storage.GetClient(ctx, tt.args.c.ID) + require.NoError(t, err) + require.Equal(t, tt.args.c, got) + }) + } +} + +func Test_staticClientsStorage_DeleteClient(t *testing.T) { + ctx := context.Background() + type fields struct { + Storage Storage + clients []Client + clientsByID map[string]Client + } + type args struct { + ctx context.Context + id string + } + tests := []struct { + name string + fields fields + args args + setup func(s Storage) + wantErr bool + }{ + { + name: "delete dynamic", + fields: fields{ + Storage: newMockStorage(), + }, + args: args{ + ctx: ctx, + id: "dynamic", + }, + setup: func(s Storage) { + s.CreateClient(ctx, Client{ID: "dynamic"}) + }, + wantErr: false, + }, + { + name: "delete static", + fields: fields{ + Storage: newMockStorage(), + clientsByID: map[string]Client{"static": {ID: "static"}}, + }, + args: args{ + ctx: ctx, + id: "static", + }, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := staticClientsStorage{ + Storage: tt.fields.Storage, + clients: tt.fields.clients, + clientsByID: tt.fields.clientsByID, + } + if tt.setup != nil { + tt.setup(s.Storage) + } + err := s.DeleteClient(tt.args.ctx, tt.args.id) + if tt.wantErr { + require.Error(t, err) + if tt.args.id != "missing" { + require.Contains(t, err.Error(), "read-only cannot delete client") + } + return + } + require.NoError(t, err) + _, err = s.Storage.GetClient(ctx, tt.args.id) + require.Error(t, err) + }) + } +} + +func Test_staticClientsStorage_GetClient(t *testing.T) { + ctx := context.Background() + type fields struct { + Storage Storage + clients []Client + clientsByID map[string]Client + } + type args struct { + ctx context.Context + id string + } + tests := []struct { + name string + fields fields + args args + setup func(s Storage) + want Client + wantErr bool + }{ + { + name: "get static", + fields: fields{ + Storage: newMockStorage(), + clientsByID: map[string]Client{"static": {ID: "static", Name: "static client"}}, + }, + args: args{ + ctx: ctx, + id: "static", + }, + want: Client{ID: "static", Name: "static client"}, + }, + { + name: "get dynamic", + fields: fields{ + Storage: newMockStorage(), + }, + args: args{ + ctx: ctx, + id: "dynamic", + }, + setup: func(s Storage) { + s.CreateClient(ctx, Client{ID: "dynamic", Name: "dynamic client"}) + }, + want: Client{ID: "dynamic", Name: "dynamic client"}, + }, + { + name: "missing", + fields: fields{ + Storage: newMockStorage(), + }, + args: args{ + ctx: ctx, + id: "missing", + }, + wantErr: true, + }, + { + name: "prefer static over dynamic", + fields: fields{ + Storage: newMockStorage(), + clientsByID: map[string]Client{"overlap": {ID: "overlap", Name: "static overlap"}}, + }, + args: args{ + ctx: ctx, + id: "overlap", + }, + setup: func(s Storage) { + s.CreateClient(ctx, Client{ID: "overlap", Name: "dynamic overlap"}) + }, + want: Client{ID: "overlap", Name: "static overlap"}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := staticClientsStorage{ + Storage: tt.fields.Storage, + clients: tt.fields.clients, + clientsByID: tt.fields.clientsByID, + } + if tt.setup != nil { + tt.setup(s.Storage) + } + got, err := s.GetClient(tt.args.ctx, tt.args.id) + if tt.wantErr { + require.Error(t, err) + return + } + require.NoError(t, err) + require.Equal(t, tt.want, got) + }) + } +} + +func Test_staticClientsStorage_ListClients(t *testing.T) { + ctx := context.Background() + type fields struct { + Storage Storage + clients []Client + clientsByID map[string]Client + } + type args struct { + ctx context.Context + } + tests := []struct { + name string + fields fields + args args + setup func(s Storage) + want []Client + wantErr bool + }{ + { + name: "static only", + fields: fields{ + Storage: newMockStorage(), + clients: []Client{{ID: "static1"}, {ID: "static2"}}, + clientsByID: map[string]Client{"static1": {ID: "static1"}, "static2": {ID: "static2"}}, + }, + args: args{ + ctx: ctx, + }, + want: []Client{{ID: "static1"}, {ID: "static2"}}, + }, + { + name: "dynamic only", + fields: fields{ + Storage: newMockStorage(), + }, + args: args{ + ctx: ctx, + }, + setup: func(s Storage) { + s.CreateClient(ctx, Client{ID: "dynamic1"}) + s.CreateClient(ctx, Client{ID: "dynamic2"}) + }, + want: []Client{{ID: "dynamic1"}, {ID: "dynamic2"}}, + }, + { + name: "mixed", + fields: fields{ + Storage: newMockStorage(), + clients: []Client{{ID: "static"}}, + clientsByID: map[string]Client{"static": {ID: "static"}}, + }, + args: args{ + ctx: ctx, + }, + setup: func(s Storage) { + s.CreateClient(ctx, Client{ID: "dynamic"}) + }, + want: []Client{{ID: "dynamic"}, {ID: "static"}}, + }, + { + name: "overlap prefers static", + fields: fields{ + Storage: newMockStorage(), + clients: []Client{{ID: "overlap", Name: "static"}}, + clientsByID: map[string]Client{"overlap": {ID: "overlap", Name: "static"}}, + }, + args: args{ + ctx: ctx, + }, + setup: func(s Storage) { + s.CreateClient(ctx, Client{ID: "overlap", Name: "dynamic"}) + }, + want: []Client{{ID: "overlap", Name: "static"}}, + }, + { + name: "base list error", + fields: fields{ + Storage: newMockStorage(), + }, + args: args{ + ctx: ctx, + }, + setup: func(s Storage) { + s.(*mockStorage).listErr = errors.New("list error") + }, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := staticClientsStorage{ + Storage: tt.fields.Storage, + clients: tt.fields.clients, + clientsByID: tt.fields.clientsByID, + } + if tt.setup != nil { + tt.setup(s.Storage) + } + got, err := s.ListClients(tt.args.ctx) + if tt.wantErr { + require.Error(t, err) + return + } + require.NoError(t, err) + sort.Slice(got, func(i, j int) bool { return got[i].ID < got[j].ID }) + sort.Slice(tt.want, func(i, j int) bool { return tt.want[i].ID < tt.want[j].ID }) + require.Equal(t, tt.want, got) + }) + } +} + +func Test_staticClientsStorage_UpdateClient(t *testing.T) { + ctx := context.Background() + type fields struct { + Storage Storage + clients []Client + clientsByID map[string]Client + } + type args struct { + ctx context.Context + id string + updater func(old Client) (Client, error) + } + tests := []struct { + name string + fields fields + args args + setup func(s Storage) + wantErr bool + }{ + { + name: "update dynamic", + fields: fields{ + Storage: newMockStorage(), + }, + args: args{ + ctx: ctx, + id: "dynamic", + updater: func(old Client) (Client, error) { + old.Name = "new" + return old, nil + }, + }, + setup: func(s Storage) { + s.CreateClient(ctx, Client{ID: "dynamic", Name: "old"}) + }, + wantErr: false, + }, + { + name: "update static", + fields: fields{ + Storage: newMockStorage(), + clientsByID: map[string]Client{"static": {ID: "static"}}, + }, + args: args{ + ctx: ctx, + id: "static", + updater: func(old Client) (Client, error) { + old.Name = "new" + return old, nil + }, + }, + wantErr: true, + }, + { + name: "update missing", + fields: fields{ + Storage: newMockStorage(), + }, + args: args{ + ctx: ctx, + id: "missing", + updater: func(old Client) (Client, error) { + return old, nil + }, + }, + wantErr: true, + }, + { + name: "base update error", + fields: fields{ + Storage: newMockStorage(), + }, + args: args{ + ctx: ctx, + id: "dynamic", + updater: func(old Client) (Client, error) { + return old, nil + }, + }, + setup: func(s Storage) { + s.(*mockStorage).updateErr = errors.New("update error") + s.CreateClient(ctx, Client{ID: "dynamic"}) + }, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := staticClientsStorage{ + Storage: tt.fields.Storage, + clients: tt.fields.clients, + clientsByID: tt.fields.clientsByID, + } + if tt.setup != nil { + tt.setup(s.Storage) + } + err := s.UpdateClient(tt.args.ctx, tt.args.id, tt.args.updater) + if tt.wantErr { + require.Error(t, err) + return + } + require.NoError(t, err) + got, err := s.Storage.GetClient(ctx, tt.args.id) + require.NoError(t, err) + require.Equal(t, "new", got.Name) + }) + } +} + +func Test_staticClientsStorage_isStatic(t *testing.T) { + type fields struct { + Storage Storage + clients []Client + clientsByID map[string]Client + } + type args struct { + id string + } + tests := []struct { + name string + fields fields + args args + want bool + }{ + { + name: "static", + fields: fields{ + clientsByID: map[string]Client{"static": {}}, + }, + args: args{ + id: "static", + }, + want: true, + }, + { + name: "dynamic", + fields: fields{ + clientsByID: map[string]Client{}, + }, + args: args{ + id: "dynamic", + }, + want: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := staticClientsStorage{ + Storage: tt.fields.Storage, + clients: tt.fields.clients, + clientsByID: tt.fields.clientsByID, + } + got := s.isStatic(tt.args.id) + require.Equal(t, tt.want, got) + }) + } +} + +func Test_staticConnectorsStorage_CreateConnector(t *testing.T) { + ctx := context.Background() + type fields struct { + Storage Storage + connectors []Connector + connectorsByID map[string]Connector + } + type args struct { + ctx context.Context + c Connector + } + tests := []struct { + name string + fields fields + args args + wantErr bool + }{ + { + name: "create dynamic", + fields: fields{ + Storage: newMockStorage(), + }, + args: args{ + ctx: ctx, + c: Connector{ID: "dynamic"}, + }, + wantErr: false, + }, + { + name: "create static", + fields: fields{ + Storage: newMockStorage(), + connectorsByID: map[string]Connector{"static": {ID: "static"}}, + }, + args: args{ + ctx: ctx, + c: Connector{ID: "static"}, + }, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := staticConnectorsStorage{ + Storage: tt.fields.Storage, + connectors: tt.fields.connectors, + connectorsByID: tt.fields.connectorsByID, + } + err := s.CreateConnector(tt.args.ctx, tt.args.c) + if tt.wantErr { + require.Error(t, err) + require.Contains(t, err.Error(), "read-only cannot create connector") + return + } + require.NoError(t, err) + got, err := tt.fields.Storage.GetConnector(ctx, tt.args.c.ID) + require.NoError(t, err) + require.Equal(t, tt.args.c, got) + }) + } +} + +func Test_staticConnectorsStorage_DeleteConnector(t *testing.T) { + ctx := context.Background() + type fields struct { + Storage Storage + connectors []Connector + connectorsByID map[string]Connector + } + type args struct { + ctx context.Context + id string + } + tests := []struct { + name string + fields fields + args args + setup func(s Storage) + wantErr bool + }{ + { + name: "delete dynamic", + fields: fields{ + Storage: newMockStorage(), + }, + args: args{ + ctx: ctx, + id: "dynamic", + }, + setup: func(s Storage) { + s.CreateConnector(ctx, Connector{ID: "dynamic"}) + }, + wantErr: false, + }, + { + name: "delete static", + fields: fields{ + Storage: newMockStorage(), + connectorsByID: map[string]Connector{"static": {ID: "static"}}, + }, + args: args{ + ctx: ctx, + id: "static", + }, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := staticConnectorsStorage{ + Storage: tt.fields.Storage, + connectors: tt.fields.connectors, + connectorsByID: tt.fields.connectorsByID, + } + if tt.setup != nil { + tt.setup(s.Storage) + } + err := s.DeleteConnector(tt.args.ctx, tt.args.id) + if tt.wantErr { + require.Error(t, err) + if tt.args.id != "missing" { + require.Contains(t, err.Error(), "read-only cannot delete connector") + } + return + } + require.NoError(t, err) + _, err = s.Storage.GetConnector(ctx, tt.args.id) + require.Error(t, err) + }) + } +} + +func Test_staticConnectorsStorage_GetConnector(t *testing.T) { + ctx := context.Background() + type fields struct { + Storage Storage + connectors []Connector + connectorsByID map[string]Connector + } + type args struct { + ctx context.Context + id string + } + tests := []struct { + name string + fields fields + args args + setup func(s Storage) + want Connector + wantErr bool + }{ + { + name: "get static", + fields: fields{ + Storage: newMockStorage(), + connectorsByID: map[string]Connector{"static": {ID: "static", Name: "static connector"}}, + }, + args: args{ + ctx: ctx, + id: "static", + }, + want: Connector{ID: "static", Name: "static connector"}, + }, + { + name: "get dynamic", + fields: fields{ + Storage: newMockStorage(), + }, + args: args{ + ctx: ctx, + id: "dynamic", + }, + setup: func(s Storage) { + s.CreateConnector(ctx, Connector{ID: "dynamic", Name: "dynamic connector"}) + }, + want: Connector{ID: "dynamic", Name: "dynamic connector"}, + }, + { + name: "missing", + fields: fields{ + Storage: newMockStorage(), + }, + args: args{ + ctx: ctx, + id: "missing", + }, + wantErr: true, + }, + { + name: "prefer static over dynamic", + fields: fields{ + Storage: newMockStorage(), + connectorsByID: map[string]Connector{"overlap": {ID: "overlap", Name: "static overlap"}}, + }, + args: args{ + ctx: ctx, + id: "overlap", + }, + setup: func(s Storage) { + s.CreateConnector(ctx, Connector{ID: "overlap", Name: "dynamic overlap"}) + }, + want: Connector{ID: "overlap", Name: "static overlap"}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := staticConnectorsStorage{ + Storage: tt.fields.Storage, + connectors: tt.fields.connectors, + connectorsByID: tt.fields.connectorsByID, + } + if tt.setup != nil { + tt.setup(s.Storage) + } + got, err := s.GetConnector(tt.args.ctx, tt.args.id) + if tt.wantErr { + require.Error(t, err) + return + } + require.NoError(t, err) + require.Equal(t, tt.want, got) + }) + } +} + +func Test_staticConnectorsStorage_ListConnectors(t *testing.T) { + ctx := context.Background() + type fields struct { + Storage Storage + connectors []Connector + connectorsByID map[string]Connector + } + type args struct { + ctx context.Context + } + tests := []struct { + name string + fields fields + args args + setup func(s Storage) + want []Connector + wantErr bool + }{ + { + name: "static only", + fields: fields{ + Storage: newMockStorage(), + connectors: []Connector{{ID: "static1"}, {ID: "static2"}}, + connectorsByID: map[string]Connector{"static1": {ID: "static1"}, "static2": {ID: "static2"}}, + }, + args: args{ + ctx: ctx, + }, + want: []Connector{{ID: "static1"}, {ID: "static2"}}, + }, + { + name: "dynamic only", + fields: fields{ + Storage: newMockStorage(), + }, + args: args{ + ctx: ctx, + }, + setup: func(s Storage) { + s.CreateConnector(ctx, Connector{ID: "dynamic1"}) + s.CreateConnector(ctx, Connector{ID: "dynamic2"}) + }, + want: []Connector{{ID: "dynamic1"}, {ID: "dynamic2"}}, + }, + { + name: "mixed", + fields: fields{ + Storage: newMockStorage(), + connectors: []Connector{{ID: "static"}}, + connectorsByID: map[string]Connector{"static": {ID: "static"}}, + }, + args: args{ + ctx: ctx, + }, + setup: func(s Storage) { + s.CreateConnector(ctx, Connector{ID: "dynamic"}) + }, + want: []Connector{{ID: "dynamic"}, {ID: "static"}}, + }, + { + name: "overlap prefers static", + fields: fields{ + Storage: newMockStorage(), + connectors: []Connector{{ID: "overlap", Name: "static"}}, + connectorsByID: map[string]Connector{"overlap": {ID: "overlap", Name: "static"}}, + }, + args: args{ + ctx: ctx, + }, + setup: func(s Storage) { + s.CreateConnector(ctx, Connector{ID: "overlap", Name: "dynamic"}) + }, + want: []Connector{{ID: "overlap", Name: "static"}}, + }, + { + name: "base list error", + fields: fields{ + Storage: newMockStorage(), + }, + args: args{ + ctx: ctx, + }, + setup: func(s Storage) { + s.(*mockStorage).listErr = errors.New("list error") + }, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := staticConnectorsStorage{ + Storage: tt.fields.Storage, + connectors: tt.fields.connectors, + connectorsByID: tt.fields.connectorsByID, + } + if tt.setup != nil { + tt.setup(s.Storage) + } + got, err := s.ListConnectors(tt.args.ctx) + if tt.wantErr { + require.Error(t, err) + return + } + require.NoError(t, err) + sort.Slice(got, func(i, j int) bool { return got[i].ID < got[j].ID }) + sort.Slice(tt.want, func(i, j int) bool { return tt.want[i].ID < tt.want[j].ID }) + require.Equal(t, tt.want, got) + }) + } +} + +func Test_staticConnectorsStorage_UpdateConnector(t *testing.T) { + ctx := context.Background() + type fields struct { + Storage Storage + connectors []Connector + connectorsByID map[string]Connector + } + type args struct { + ctx context.Context + id string + updater func(old Connector) (Connector, error) + } + tests := []struct { + name string + fields fields + args args + setup func(s Storage) + wantErr bool + }{ + { + name: "update dynamic", + fields: fields{ + Storage: newMockStorage(), + }, + args: args{ + ctx: ctx, + id: "dynamic", + updater: func(old Connector) (Connector, error) { + old.Name = "new" + return old, nil + }, + }, + setup: func(s Storage) { + s.CreateConnector(ctx, Connector{ID: "dynamic", Name: "old"}) + }, + wantErr: false, + }, + { + name: "update static", + fields: fields{ + Storage: newMockStorage(), + connectorsByID: map[string]Connector{"static": {ID: "static"}}, + }, + args: args{ + ctx: ctx, + id: "static", + updater: func(old Connector) (Connector, error) { + old.Name = "new" + return old, nil + }, + }, + wantErr: true, + }, + { + name: "update missing", + fields: fields{ + Storage: newMockStorage(), + }, + args: args{ + ctx: ctx, + id: "missing", + updater: func(old Connector) (Connector, error) { + return old, nil + }, + }, + wantErr: true, + }, + { + name: "base update error", + fields: fields{ + Storage: newMockStorage(), + }, + args: args{ + ctx: ctx, + id: "dynamic", + updater: func(old Connector) (Connector, error) { + return old, nil + }, + }, + setup: func(s Storage) { + s.(*mockStorage).updateErr = errors.New("update error") + s.CreateConnector(ctx, Connector{ID: "dynamic"}) + }, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := staticConnectorsStorage{ + Storage: tt.fields.Storage, + connectors: tt.fields.connectors, + connectorsByID: tt.fields.connectorsByID, + } + if tt.setup != nil { + tt.setup(s.Storage) + } + err := s.UpdateConnector(tt.args.ctx, tt.args.id, tt.args.updater) + if tt.wantErr { + require.Error(t, err) + return + } + require.NoError(t, err) + got, err := s.Storage.GetConnector(ctx, tt.args.id) + require.NoError(t, err) + require.Equal(t, "new", got.Name) + }) + } +} + +func Test_staticConnectorsStorage_isStatic(t *testing.T) { + type fields struct { + Storage Storage + connectors []Connector + connectorsByID map[string]Connector + } + type args struct { + id string + } + tests := []struct { + name string + fields fields + args args + want bool + }{ + { + name: "static", + fields: fields{ + connectorsByID: map[string]Connector{"static": {}}, + }, + args: args{ + id: "static", + }, + want: true, + }, + { + name: "dynamic", + fields: fields{ + connectorsByID: map[string]Connector{}, + }, + args: args{ + id: "dynamic", + }, + want: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := staticConnectorsStorage{ + Storage: tt.fields.Storage, + connectors: tt.fields.connectors, + connectorsByID: tt.fields.connectorsByID, + } + got := s.isStatic(tt.args.id) + require.Equal(t, tt.want, got) + }) + } +} + +func Test_staticPasswordsStorage_CreatePassword(t *testing.T) { + ctx := context.Background() + logger := slog.Default() + type fields struct { + Storage Storage + passwords []Password + passwordsByEmail map[string]Password + logger *slog.Logger + } + type args struct { + ctx context.Context + p Password + } + tests := []struct { + name string + fields fields + args args + wantErr bool + }{ + { + name: "create dynamic", + fields: fields{ + Storage: newMockStorage(), + logger: logger, + }, + args: args{ + ctx: ctx, + p: Password{Email: "dynamic@example.com"}, + }, + wantErr: false, + }, + { + name: "create static", + fields: fields{ + Storage: newMockStorage(), + passwordsByEmail: map[string]Password{"static@example.com": {Email: "static@example.com"}}, + logger: logger, + }, + args: args{ + ctx: ctx, + p: Password{Email: "static@example.com"}, + }, + wantErr: true, + }, + { + name: "create static case insensitive", + fields: fields{ + Storage: newMockStorage(), + passwordsByEmail: map[string]Password{"static@example.com": {Email: "Static@Example.com"}}, + logger: logger, + }, + args: args{ + ctx: ctx, + p: Password{Email: "static@example.com"}, + }, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := staticPasswordsStorage{ + Storage: tt.fields.Storage, + passwords: tt.fields.passwords, + passwordsByEmail: tt.fields.passwordsByEmail, + logger: tt.fields.logger, + } + err := s.CreatePassword(tt.args.ctx, tt.args.p) + if tt.wantErr { + require.Error(t, err) + require.Contains(t, err.Error(), "read-only cannot create password") + return + } + require.NoError(t, err) + got, err := tt.fields.Storage.GetPassword(ctx, tt.args.p.Email) + require.NoError(t, err) + require.Equal(t, tt.args.p, got) + }) + } +} + +func Test_staticPasswordsStorage_DeletePassword(t *testing.T) { + ctx := context.Background() + logger := slog.Default() + type fields struct { + Storage Storage + passwords []Password + passwordsByEmail map[string]Password + logger *slog.Logger + } + type args struct { + ctx context.Context + email string + } + tests := []struct { + name string + fields fields + args args + setup func(s Storage) + wantErr bool + }{ + { + name: "delete dynamic", + fields: fields{ + Storage: newMockStorage(), + logger: logger, + }, + args: args{ + ctx: ctx, + email: "dynamic@example.com", + }, + setup: func(s Storage) { + s.CreatePassword(ctx, Password{Email: "dynamic@example.com"}) + }, + wantErr: false, + }, + { + name: "delete static", + fields: fields{ + Storage: newMockStorage(), + passwordsByEmail: map[string]Password{"static@example.com": {Email: "static@example.com"}}, + logger: logger, + }, + args: args{ + ctx: ctx, + email: "static@example.com", + }, + wantErr: true, + }, + { + name: "delete static case insensitive", + fields: fields{ + Storage: newMockStorage(), + passwordsByEmail: map[string]Password{"static@example.com": {Email: "Static@Example.com"}}, + logger: logger, + }, + args: args{ + ctx: ctx, + email: "static@example.com", + }, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := staticPasswordsStorage{ + Storage: tt.fields.Storage, + passwords: tt.fields.passwords, + passwordsByEmail: tt.fields.passwordsByEmail, + logger: tt.fields.logger, + } + if tt.setup != nil { + tt.setup(s.Storage) + } + err := s.DeletePassword(tt.args.ctx, tt.args.email) + if tt.wantErr { + require.Error(t, err) + if tt.args.email != "missing@example.com" { + require.Contains(t, err.Error(), "read-only cannot delete password") + } + return + } + require.NoError(t, err) + _, err = s.Storage.GetPassword(ctx, tt.args.email) + require.Error(t, err) + }) + } +} + +func Test_staticPasswordsStorage_GetPassword(t *testing.T) { + ctx := context.Background() + logger := slog.Default() + type fields struct { + Storage Storage + passwords []Password + passwordsByEmail map[string]Password + logger *slog.Logger + } + type args struct { + ctx context.Context + email string + } + tests := []struct { + name string + fields fields + args args + setup func(s Storage) + want Password + wantErr bool + }{ + { + name: "get static case insensitive", + fields: fields{ + Storage: newMockStorage(), + passwordsByEmail: map[string]Password{"static@example.com": {Email: "Static@Example.com", Username: "static"}}, + logger: logger, + }, + args: args{ + ctx: ctx, + email: "static@example.com", + }, + want: Password{Email: "Static@Example.com", Username: "static"}, + }, + { + name: "get dynamic", + fields: fields{ + Storage: newMockStorage(), + logger: logger, + }, + args: args{ + ctx: ctx, + email: "dynamic@example.com", + }, + setup: func(s Storage) { + s.CreatePassword(ctx, Password{Email: "dynamic@example.com", Username: "dynamic"}) + }, + want: Password{Email: "dynamic@example.com", Username: "dynamic"}, + }, + { + name: "missing", + fields: fields{ + Storage: newMockStorage(), + logger: logger, + }, + args: args{ + ctx: ctx, + email: "missing@example.com", + }, + wantErr: true, + }, + { + name: "prefer static over dynamic", + fields: fields{ + Storage: newMockStorage(), + passwordsByEmail: map[string]Password{"overlap@example.com": {Email: "overlap@example.com", Username: "static"}}, + logger: logger, + }, + args: args{ + ctx: ctx, + email: "overlap@example.com", + }, + setup: func(s Storage) { + s.CreatePassword(ctx, Password{Email: "overlap@example.com", Username: "dynamic"}) + }, + want: Password{Email: "overlap@example.com", Username: "static"}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := staticPasswordsStorage{ + Storage: tt.fields.Storage, + passwords: tt.fields.passwords, + passwordsByEmail: tt.fields.passwordsByEmail, + logger: tt.fields.logger, + } + if tt.setup != nil { + tt.setup(s.Storage) + } + got, err := s.GetPassword(tt.args.ctx, tt.args.email) + if tt.wantErr { + require.Error(t, err) + return + } + require.NoError(t, err) + require.Equal(t, tt.want, got) + }) + } +} + +func Test_staticPasswordsStorage_ListPasswords(t *testing.T) { + ctx := context.Background() + logger := slog.Default() + type fields struct { + Storage Storage + passwords []Password + passwordsByEmail map[string]Password + logger *slog.Logger + } + type args struct { + ctx context.Context + } + tests := []struct { + name string + fields fields + args args + setup func(s Storage) + want []Password + wantErr bool + }{ + { + name: "static only", + fields: fields{ + Storage: newMockStorage(), + passwords: []Password{{Email: "static1@example.com"}, {Email: "static2@example.com"}}, + passwordsByEmail: map[string]Password{"static1@example.com": {Email: "static1@example.com"}, "static2@example.com": {Email: "static2@example.com"}}, + logger: logger, + }, + args: args{ + ctx: ctx, + }, + want: []Password{{Email: "static1@example.com"}, {Email: "static2@example.com"}}, + }, + { + name: "dynamic only", + fields: fields{ + Storage: newMockStorage(), + logger: logger, + }, + args: args{ + ctx: ctx, + }, + setup: func(s Storage) { + s.CreatePassword(ctx, Password{Email: "dynamic1@example.com"}) + s.CreatePassword(ctx, Password{Email: "dynamic2@example.com"}) + }, + want: []Password{{Email: "dynamic1@example.com"}, {Email: "dynamic2@example.com"}}, + }, + { + name: "mixed", + fields: fields{ + Storage: newMockStorage(), + passwords: []Password{{Email: "static@example.com"}}, + passwordsByEmail: map[string]Password{"static@example.com": {Email: "static@example.com"}}, + logger: logger, + }, + args: args{ + ctx: ctx, + }, + setup: func(s Storage) { + s.CreatePassword(ctx, Password{Email: "dynamic@example.com"}) + }, + want: []Password{{Email: "dynamic@example.com"}, {Email: "static@example.com"}}, + }, + { + name: "overlap prefers static case insensitive", + fields: fields{ + Storage: newMockStorage(), + passwords: []Password{{Email: "Overlap@Example.com", Username: "static"}}, + passwordsByEmail: map[string]Password{"overlap@example.com": {Email: "Overlap@Example.com", Username: "static"}}, + logger: logger, + }, + args: args{ + ctx: ctx, + }, + setup: func(s Storage) { + s.CreatePassword(ctx, Password{Email: "overlap@example.com", Username: "dynamic"}) + }, + want: []Password{{Email: "Overlap@Example.com", Username: "static"}}, + }, + { + name: "base list error", + fields: fields{ + Storage: newMockStorage(), + logger: logger, + }, + args: args{ + ctx: ctx, + }, + setup: func(s Storage) { + s.(*mockStorage).listErr = errors.New("list error") + }, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := staticPasswordsStorage{ + Storage: tt.fields.Storage, + passwords: tt.fields.passwords, + passwordsByEmail: tt.fields.passwordsByEmail, + logger: tt.fields.logger, + } + if tt.setup != nil { + tt.setup(s.Storage) + } + got, err := s.ListPasswords(tt.args.ctx) + if tt.wantErr { + require.Error(t, err) + return + } + require.NoError(t, err) + sort.Slice(got, func(i, j int) bool { return strings.ToLower(got[i].Email) < strings.ToLower(got[j].Email) }) + sort.Slice(tt.want, func(i, j int) bool { return strings.ToLower(tt.want[i].Email) < strings.ToLower(tt.want[j].Email) }) + require.Equal(t, tt.want, got) + }) + } +} + +func Test_staticPasswordsStorage_UpdatePassword(t *testing.T) { + ctx := context.Background() + logger := slog.Default() + type fields struct { + Storage Storage + passwords []Password + passwordsByEmail map[string]Password + logger *slog.Logger + } + type args struct { + ctx context.Context + email string + updater func(old Password) (Password, error) + } + tests := []struct { + name string + fields fields + args args + setup func(s Storage) + wantErr bool + }{ + { + name: "update dynamic", + fields: fields{ + Storage: newMockStorage(), + logger: logger, + }, + args: args{ + ctx: ctx, + email: "dynamic@example.com", + updater: func(old Password) (Password, error) { + old.Username = "new" + return old, nil + }, + }, + setup: func(s Storage) { + s.CreatePassword(ctx, Password{Email: "dynamic@example.com", Username: "old"}) + }, + wantErr: false, + }, + { + name: "update static", + fields: fields{ + Storage: newMockStorage(), + passwordsByEmail: map[string]Password{"static@example.com": {Email: "static@example.com"}}, + logger: logger, + }, + args: args{ + ctx: ctx, + email: "static@example.com", + updater: func(old Password) (Password, error) { + old.Username = "new" + return old, nil + }, + }, + wantErr: true, + }, + { + name: "update static case insensitive", + fields: fields{ + Storage: newMockStorage(), + passwordsByEmail: map[string]Password{"static@example.com": {Email: "Static@Example.com"}}, + logger: logger, + }, + args: args{ + ctx: ctx, + email: "static@example.com", + updater: func(old Password) (Password, error) { + old.Username = "new" + return old, nil + }, + }, + wantErr: true, + }, + { + name: "update missing", + fields: fields{ + Storage: newMockStorage(), + logger: logger, + }, + args: args{ + ctx: ctx, + email: "missing@example.com", + updater: func(old Password) (Password, error) { + return old, nil + }, + }, + wantErr: true, + }, + { + name: "base update error", + fields: fields{ + Storage: newMockStorage(), + logger: logger, + }, + args: args{ + ctx: ctx, + email: "dynamic@example.com", + updater: func(old Password) (Password, error) { + return old, nil + }, + }, + setup: func(s Storage) { + s.(*mockStorage).updateErr = errors.New("update error") + s.CreatePassword(ctx, Password{Email: "dynamic@example.com"}) + }, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := staticPasswordsStorage{ + Storage: tt.fields.Storage, + passwords: tt.fields.passwords, + passwordsByEmail: tt.fields.passwordsByEmail, + logger: tt.fields.logger, + } + if tt.setup != nil { + tt.setup(s.Storage) + } + err := s.UpdatePassword(tt.args.ctx, tt.args.email, tt.args.updater) + if tt.wantErr { + require.Error(t, err) + return + } + require.NoError(t, err) + got, err := s.Storage.GetPassword(ctx, tt.args.email) + require.NoError(t, err) + require.Equal(t, "new", got.Username) + }) + } +} + +func Test_staticPasswordsStorage_isStatic(t *testing.T) { + type fields struct { + Storage Storage + passwords []Password + passwordsByEmail map[string]Password + logger *slog.Logger + } + type args struct { + email string + } + tests := []struct { + name string + fields fields + args args + want bool + }{ + { + name: "static", + fields: fields{ + passwordsByEmail: map[string]Password{"static@example.com": {}}, + }, + args: args{ + email: "Static@Example.com", + }, + want: true, + }, + { + name: "dynamic", + fields: fields{ + passwordsByEmail: map[string]Password{}, + }, + args: args{ + email: "dynamic@example.com", + }, + want: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + s := staticPasswordsStorage{ + Storage: tt.fields.Storage, + passwords: tt.fields.passwords, + passwordsByEmail: tt.fields.passwordsByEmail, + logger: tt.fields.logger, + } + got := s.isStatic(tt.args.email) + require.Equal(t, tt.want, got) + }) + } +} diff --git a/storage/storage_test.go b/storage/storage_test.go new file mode 100644 index 0000000000..4749a8cf0b --- /dev/null +++ b/storage/storage_test.go @@ -0,0 +1,82 @@ +package storage + +import ( + "crypto" + "testing" +) + +func TestGCResult_IsEmpty(t *testing.T) { + tests := []struct { + name string + result GCResult + want bool + }{ + {"empty result", GCResult{}, true}, + {"non-empty AuthRequests", GCResult{AuthRequests: 1}, false}, + {"non-empty AuthCodes", GCResult{AuthCodes: 1}, false}, + {"non-empty DeviceRequests", GCResult{DeviceRequests: 1}, false}, + {"non-empty DeviceTokens", GCResult{DeviceTokens: 1}, false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := tt.result.IsEmpty(); got != tt.want { + t.Errorf("IsEmpty() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestNewSecureID(t *testing.T) { + tests := []struct { + name string + len int + want int + }{ + {"length 16", 16, 25}, + {"length 32", 32, 51}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + id := newSecureID(tt.len) + if len(id) != tt.want { + t.Errorf("newSecureID() got length %d, want %d", len(id), tt.want) + } + }) + } +} + +func TestNewHMACKey(t *testing.T) { + tests := []struct { + name string + hash crypto.Hash + wantLen int + }{ + {"SHA256", crypto.SHA256, 51}, + {"SHA512", crypto.SHA512, 102}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + key := NewHMACKey(tt.hash) + if len(key) != tt.wantLen { + t.Errorf("NewHMACKey() got length %d, want %d", len(key), tt.wantLen) + } + }) + } +} + +func TestNewDeviceCode(t *testing.T) { + code := NewDeviceCode() + if len(code) == 0 { + t.Error("NewDeviceCode() returned empty code") + } +} + +func TestNewUserCode(t *testing.T) { + code := NewUserCode() + if len(code) != 9 || code[4] != '-' { + t.Errorf("NewUserCode() got %s, want format xxxx-xxxx", code) + } +}