Merge pull request #1906 from flant/ent-sqlite

feat: Add ent-based sqlite3 storage
This commit is contained in:
Maksim Nabokikh 2021-05-05 18:19:25 +04:00 committed by GitHub
commit 81c4dc7994
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
114 changed files with 41894 additions and 3 deletions

View file

@ -26,7 +26,10 @@ PROTOC_VERSION = 3.15.6
PROTOC_GEN_GO_VERSION = 1.26.0 PROTOC_GEN_GO_VERSION = 1.26.0
PROTOC_GEN_GO_GRPC_VERSION = 1.1.0 PROTOC_GEN_GO_GRPC_VERSION = 1.1.0
build: bin/dex generate:
@go generate $(REPO_PATH)/storage/ent/
build: generate bin/dex
bin/dex: bin/dex:
@mkdir -p bin/ @mkdir -p bin/
@ -42,7 +45,7 @@ bin/example-app:
@mkdir -p bin/ @mkdir -p bin/
@cd examples/ && go install -v -ldflags $(LD_FLAGS) $(REPO_PATH)/examples/example-app @cd examples/ && go install -v -ldflags $(LD_FLAGS) $(REPO_PATH)/examples/example-app
.PHONY: release-binary .PHONY: generate release-binary
release-binary: release-binary:
@go build -o /go/bin/dex -v -ldflags $(LD_FLAGS) $(REPO_PATH)/cmd/dex @go build -o /go/bin/dex -v -ldflags $(LD_FLAGS) $(REPO_PATH)/cmd/dex

View file

@ -13,6 +13,7 @@ import (
"github.com/dexidp/dex/pkg/log" "github.com/dexidp/dex/pkg/log"
"github.com/dexidp/dex/server" "github.com/dexidp/dex/server"
"github.com/dexidp/dex/storage" "github.com/dexidp/dex/storage"
"github.com/dexidp/dex/storage/ent"
"github.com/dexidp/dex/storage/etcd" "github.com/dexidp/dex/storage/etcd"
"github.com/dexidp/dex/storage/kubernetes" "github.com/dexidp/dex/storage/kubernetes"
"github.com/dexidp/dex/storage/memory" "github.com/dexidp/dex/storage/memory"
@ -173,13 +174,32 @@ type StorageConfig interface {
Open(logger log.Logger) (storage.Storage, error) Open(logger log.Logger) (storage.Storage, error)
} }
var (
_ StorageConfig = (*etcd.Etcd)(nil)
_ StorageConfig = (*kubernetes.Config)(nil)
_ StorageConfig = (*memory.Config)(nil)
_ StorageConfig = (*sql.SQLite3)(nil)
_ StorageConfig = (*sql.Postgres)(nil)
_ StorageConfig = (*sql.MySQL)(nil)
_ StorageConfig = (*ent.SQLite3)(nil)
)
func getORMBasedSQLiteStorage() StorageConfig {
switch os.Getenv("DEX_ENT_ENABLED") {
case "true", "yes":
return new(ent.SQLite3)
default:
return new(sql.SQLite3)
}
}
var storages = map[string]func() StorageConfig{ var storages = map[string]func() StorageConfig{
"etcd": func() StorageConfig { return new(etcd.Etcd) }, "etcd": func() StorageConfig { return new(etcd.Etcd) },
"kubernetes": func() StorageConfig { return new(kubernetes.Config) }, "kubernetes": func() StorageConfig { return new(kubernetes.Config) },
"memory": func() StorageConfig { return new(memory.Config) }, "memory": func() StorageConfig { return new(memory.Config) },
"sqlite3": func() StorageConfig { return new(sql.SQLite3) },
"postgres": func() StorageConfig { return new(sql.Postgres) }, "postgres": func() StorageConfig { return new(sql.Postgres) },
"mysql": func() StorageConfig { return new(sql.MySQL) }, "mysql": func() StorageConfig { return new(sql.MySQL) },
"sqlite3": getORMBasedSQLiteStorage,
} }
// isExpandEnvEnabled returns if os.ExpandEnv should be used for each storage and connector config. // isExpandEnvEnabled returns if os.ExpandEnv should be used for each storage and connector config.

1
go.mod
View file

@ -3,6 +3,7 @@ module github.com/dexidp/dex
go 1.16 go 1.16
require ( require (
entgo.io/ent v0.8.0
github.com/AppsFlyer/go-sundheit v0.3.1 github.com/AppsFlyer/go-sundheit v0.3.1
github.com/beevik/etree v1.1.0 github.com/beevik/etree v1.1.0
github.com/coreos/go-oidc/v3 v3.0.0 github.com/coreos/go-oidc/v3 v3.0.0

15
go.sum
View file

@ -38,6 +38,8 @@ cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohl
cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs=
cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0=
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
entgo.io/ent v0.8.0 h1:xirrW//1oda7pp0bz+XssSOv4/C3nmgYQOxjIfljFt8=
entgo.io/ent v0.8.0/go.mod h1:KNjsukat/NJi6zJh1utwRadsbGOZsBbAZNDxkW7tMCc=
github.com/AppsFlyer/go-sundheit v0.3.1 h1:Zqnr3wV3WQmXonc234k9XZAoV2KHUHw3osR5k2iHQZE= github.com/AppsFlyer/go-sundheit v0.3.1 h1:Zqnr3wV3WQmXonc234k9XZAoV2KHUHw3osR5k2iHQZE=
github.com/AppsFlyer/go-sundheit v0.3.1/go.mod h1:iZ8zWMS7idcvmqewf5mEymWWgoOiG/0WD4+aeh+heX4= github.com/AppsFlyer/go-sundheit v0.3.1/go.mod h1:iZ8zWMS7idcvmqewf5mEymWWgoOiG/0WD4+aeh+heX4=
github.com/Azure/go-ntlmssp v0.0.0-20200615164410-66371956d46c h1:/IBSNwUN8+eKzUzbJPqhK839ygXJ82sde8x3ogr6R28= github.com/Azure/go-ntlmssp v0.0.0-20200615164410-66371956d46c h1:/IBSNwUN8+eKzUzbJPqhK839ygXJ82sde8x3ogr6R28=
@ -45,6 +47,8 @@ github.com/Azure/go-ntlmssp v0.0.0-20200615164410-66371956d46c/go.mod h1:chxPXzS
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/DATA-DOG/go-sqlmock v1.5.0 h1:Shsta01QNfFxHCfpW6YH2STWB0MudeXXEWMr20OEh60=
github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM=
github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0=
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo= github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo=
@ -141,6 +145,7 @@ github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/go-asn1-ber/asn1-ber v1.5.1 h1:pDbRAunXzIUXfx4CB2QJFv5IuPiuoW+sWvr/Us009o8= github.com/go-asn1-ber/asn1-ber v1.5.1 h1:pDbRAunXzIUXfx4CB2QJFv5IuPiuoW+sWvr/Us009o8=
github.com/go-asn1-ber/asn1-ber v1.5.1/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0= github.com/go-asn1-ber/asn1-ber v1.5.1/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
github.com/go-bindata/go-bindata v1.0.1-0.20190711162640-ee3c2418e368/go.mod h1:7xCgX1lzlrXPHkfvn3EhumqHkmSlzt8at9q7v0ax19c=
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
@ -152,7 +157,9 @@ github.com/go-ldap/ldap/v3 v3.3.0/go.mod h1:iYS1MdmrmceOJ1QOTnRXrIs7i3kloqtmGQjR
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A=
github.com/go-openapi/inflect v0.19.0/go.mod h1:lHpZVlpIQqLyKwJ4N+YSc9hchQy/i12fJykb83CRBH4=
github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w= github.com/go-sql-driver/mysql v1.4.0/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
github.com/go-sql-driver/mysql v1.5.1-0.20200311113236-681ffa848bae/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE= github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE=
github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
@ -230,6 +237,8 @@ github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5/go.mod h1:kpwsk12EmLe
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.2.0 h1:qJYtXnJRWmpe7m/3XlyhrsLrEURqHRM2kxzoxXqyUDs=
github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
github.com/googleapis/gax-go/v2 v2.0.5 h1:sjZBwGj9Jlw33ImPtvFviGYvseOtDM7hkSKB7+Tv3SM= github.com/googleapis/gax-go/v2 v2.0.5 h1:sjZBwGj9Jlw33ImPtvFviGYvseOtDM7hkSKB7+Tv3SM=
github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk=
@ -281,6 +290,7 @@ github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo=
github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c2EWnYs/m4=
github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k=
github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
github.com/jonboulle/clockwork v0.2.0 h1:J2SLSdy7HgElq8ekSl2Mxh6vrRNFxqbXGenYH2I02Vs= github.com/jonboulle/clockwork v0.2.0 h1:J2SLSdy7HgElq8ekSl2Mxh6vrRNFxqbXGenYH2I02Vs=
@ -309,6 +319,7 @@ github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/lib/pq v1.10.0/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/lib/pq v1.10.1 h1:6VXZrLU0jHBYyAqrSPa+MgPfnSvTPuMgK+k0o5kVFWo= github.com/lib/pq v1.10.1 h1:6VXZrLU0jHBYyAqrSPa+MgPfnSvTPuMgK+k0o5kVFWo=
github.com/lib/pq v1.10.1/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/lib/pq v1.10.1/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM= github.com/lightstep/lightstep-tracer-common/golang/gogo v0.0.0-20190605223551-bc2310a04743/go.mod h1:qklhhLq1aX+mtWk9cPHPzaBjWImj5ULL6C7HFJtXQMM=
@ -321,6 +332,8 @@ github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaO
github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
github.com/mattn/go-sqlite3 v1.14.7 h1:fxWBnXkxfM6sRiuH3bqJ4CfzZojMOLVc0UTsTglEghA= github.com/mattn/go-sqlite3 v1.14.7 h1:fxWBnXkxfM6sRiuH3bqJ4CfzZojMOLVc0UTsTglEghA=
github.com/mattn/go-sqlite3 v1.14.7/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= github.com/mattn/go-sqlite3 v1.14.7/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU=
@ -334,6 +347,7 @@ github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS4
github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY= github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY=
github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
@ -353,6 +367,7 @@ github.com/oklog/run v1.1.0 h1:GEenZ1cK0+q0+wsJew9qUg/DyD8k3JzYsZAi5gYi2mA=
github.com/oklog/run v1.1.0/go.mod h1:sVPdnTZT1zYwAJeCMu2Th4T21pA3FPOQRfWjQlk7DVU= github.com/oklog/run v1.1.0/go.mod h1:sVPdnTZT1zYwAJeCMu2Th4T21pA3FPOQRfWjQlk7DVU=
github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U= github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo=
github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
github.com/onsi/ginkgo v1.4.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.4.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.7.0 h1:WSHQ+IS43OoUrWtD1/bbclrwK8TTH5hzp+umCiuxHgs= github.com/onsi/ginkgo v1.7.0 h1:WSHQ+IS43OoUrWtD1/bbclrwK8TTH5hzp+umCiuxHgs=

View file

@ -0,0 +1,52 @@
package client
import (
"context"
"github.com/dexidp/dex/storage"
)
// CreateAuthCode saves provided auth code into the database.
func (d *Database) CreateAuthCode(code storage.AuthCode) error {
_, err := d.client.AuthCode.Create().
SetID(code.ID).
SetClientID(code.ClientID).
SetScopes(code.Scopes).
SetRedirectURI(code.RedirectURI).
SetNonce(code.Nonce).
SetClaimsUserID(code.Claims.UserID).
SetClaimsEmail(code.Claims.Email).
SetClaimsEmailVerified(code.Claims.EmailVerified).
SetClaimsUsername(code.Claims.Username).
SetClaimsPreferredUsername(code.Claims.PreferredUsername).
SetClaimsGroups(code.Claims.Groups).
SetCodeChallenge(code.PKCE.CodeChallenge).
SetCodeChallengeMethod(code.PKCE.CodeChallengeMethod).
// Save utc time into database because ent doesn't support comparing dates with different timezones
SetExpiry(code.Expiry.UTC()).
SetConnectorID(code.ConnectorID).
SetConnectorData(code.ConnectorData).
Save(context.TODO())
if err != nil {
return convertDBError("create auth code: %w", err)
}
return nil
}
// GetAuthCode extracts an auth code from the database by id.
func (d *Database) GetAuthCode(id string) (storage.AuthCode, error) {
authCode, err := d.client.AuthCode.Get(context.TODO(), id)
if err != nil {
return storage.AuthCode{}, convertDBError("get auth code: %w", err)
}
return toStorageAuthCode(authCode), nil
}
// DeleteAuthCode deletes an auth code from the database by id.
func (d *Database) DeleteAuthCode(id string) error {
err := d.client.AuthCode.DeleteOneID(id).Exec(context.TODO())
if err != nil {
return convertDBError("delete auth code: %w", err)
}
return nil
}

View file

@ -0,0 +1,107 @@
package client
import (
"context"
"fmt"
"github.com/dexidp/dex/storage"
)
// CreateAuthRequest saves provided auth request into the database.
func (d *Database) CreateAuthRequest(authRequest storage.AuthRequest) error {
_, err := d.client.AuthRequest.Create().
SetID(authRequest.ID).
SetClientID(authRequest.ClientID).
SetScopes(authRequest.Scopes).
SetResponseTypes(authRequest.ResponseTypes).
SetRedirectURI(authRequest.RedirectURI).
SetState(authRequest.State).
SetNonce(authRequest.Nonce).
SetForceApprovalPrompt(authRequest.ForceApprovalPrompt).
SetLoggedIn(authRequest.LoggedIn).
SetClaimsUserID(authRequest.Claims.UserID).
SetClaimsEmail(authRequest.Claims.Email).
SetClaimsEmailVerified(authRequest.Claims.EmailVerified).
SetClaimsUsername(authRequest.Claims.Username).
SetClaimsPreferredUsername(authRequest.Claims.PreferredUsername).
SetClaimsGroups(authRequest.Claims.Groups).
SetCodeChallenge(authRequest.PKCE.CodeChallenge).
SetCodeChallengeMethod(authRequest.PKCE.CodeChallengeMethod).
// Save utc time into database because ent doesn't support comparing dates with different timezones
SetExpiry(authRequest.Expiry.UTC()).
SetConnectorID(authRequest.ConnectorID).
SetConnectorData(authRequest.ConnectorData).
Save(context.TODO())
if err != nil {
return convertDBError("create auth request: %w", err)
}
return nil
}
// GetAuthRequest extracts an auth request from the database by id.
func (d *Database) GetAuthRequest(id string) (storage.AuthRequest, error) {
authRequest, err := d.client.AuthRequest.Get(context.TODO(), id)
if err != nil {
return storage.AuthRequest{}, convertDBError("get auth request: %w", err)
}
return toStorageAuthRequest(authRequest), nil
}
// DeleteAuthRequest deletes an auth request from the database by id.
func (d *Database) DeleteAuthRequest(id string) error {
err := d.client.AuthRequest.DeleteOneID(id).Exec(context.TODO())
if err != nil {
return convertDBError("delete auth request: %w", err)
}
return nil
}
// UpdateAuthRequest changes an auth request by id using an updater function and saves it to the database.
func (d *Database) UpdateAuthRequest(id string, updater func(old storage.AuthRequest) (storage.AuthRequest, error)) error {
tx, err := d.client.Tx(context.TODO())
if err != nil {
return fmt.Errorf("update auth request tx: %w", err)
}
authRequest, err := tx.AuthRequest.Get(context.TODO(), id)
if err != nil {
return rollback(tx, "update auth request database: %w", err)
}
newAuthRequest, err := updater(toStorageAuthRequest(authRequest))
if err != nil {
return rollback(tx, "update auth request updating: %w", err)
}
_, err = tx.AuthRequest.UpdateOneID(newAuthRequest.ID).
SetClientID(newAuthRequest.ClientID).
SetScopes(newAuthRequest.Scopes).
SetResponseTypes(newAuthRequest.ResponseTypes).
SetRedirectURI(newAuthRequest.RedirectURI).
SetState(newAuthRequest.State).
SetNonce(newAuthRequest.Nonce).
SetForceApprovalPrompt(newAuthRequest.ForceApprovalPrompt).
SetLoggedIn(newAuthRequest.LoggedIn).
SetClaimsUserID(newAuthRequest.Claims.UserID).
SetClaimsEmail(newAuthRequest.Claims.Email).
SetClaimsEmailVerified(newAuthRequest.Claims.EmailVerified).
SetClaimsUsername(newAuthRequest.Claims.Username).
SetClaimsPreferredUsername(newAuthRequest.Claims.PreferredUsername).
SetClaimsGroups(newAuthRequest.Claims.Groups).
SetCodeChallenge(newAuthRequest.PKCE.CodeChallenge).
SetCodeChallengeMethod(newAuthRequest.PKCE.CodeChallengeMethod).
// Save utc time into database because ent doesn't support comparing dates with different timezones
SetExpiry(newAuthRequest.Expiry.UTC()).
SetConnectorID(newAuthRequest.ConnectorID).
SetConnectorData(newAuthRequest.ConnectorData).
Save(context.TODO())
if err != nil {
return rollback(tx, "update auth request uploading: %w", err)
}
if err = tx.Commit(); err != nil {
return rollback(tx, "update auth request commit: %w", err)
}
return nil
}

View file

@ -0,0 +1,92 @@
package client
import (
"context"
"github.com/dexidp/dex/storage"
)
// CreateClient saves provided oauth2 client settings into the database.
func (d *Database) CreateClient(client storage.Client) error {
_, err := d.client.OAuth2Client.Create().
SetID(client.ID).
SetName(client.Name).
SetSecret(client.Secret).
SetPublic(client.Public).
SetLogoURL(client.LogoURL).
SetRedirectUris(client.RedirectURIs).
SetTrustedPeers(client.TrustedPeers).
Save(context.TODO())
if err != nil {
return convertDBError("create oauth2 client: %w", err)
}
return nil
}
// ListClients extracts an array of oauth2 clients from the database.
func (d *Database) ListClients() ([]storage.Client, error) {
clients, err := d.client.OAuth2Client.Query().All(context.TODO())
if err != nil {
return nil, convertDBError("list clients: %w", err)
}
storageClients := make([]storage.Client, 0, len(clients))
for _, c := range clients {
storageClients = append(storageClients, toStorageClient(c))
}
return storageClients, nil
}
// GetClient extracts an oauth2 client from the database by id.
func (d *Database) GetClient(id string) (storage.Client, error) {
client, err := d.client.OAuth2Client.Get(context.TODO(), id)
if err != nil {
return storage.Client{}, convertDBError("get client: %w", err)
}
return toStorageClient(client), nil
}
// DeleteClient deletes an oauth2 client from the database by id.
func (d *Database) DeleteClient(id string) error {
err := d.client.OAuth2Client.DeleteOneID(id).Exec(context.TODO())
if err != nil {
return convertDBError("delete client: %w", err)
}
return nil
}
// UpdateClient changes an oauth2 client by id using an updater function and saves it to the database.
func (d *Database) UpdateClient(id string, updater func(old storage.Client) (storage.Client, error)) error {
tx, err := d.client.Tx(context.TODO())
if err != nil {
return convertDBError("update client tx: %w", err)
}
client, err := tx.OAuth2Client.Get(context.TODO(), id)
if err != nil {
return rollback(tx, "update client database: %w", err)
}
newClient, err := updater(toStorageClient(client))
if err != nil {
return rollback(tx, "update client updating: %w", err)
}
_, err = tx.OAuth2Client.UpdateOneID(newClient.ID).
SetName(newClient.Name).
SetSecret(newClient.Secret).
SetPublic(newClient.Public).
SetLogoURL(newClient.LogoURL).
SetRedirectUris(newClient.RedirectURIs).
SetTrustedPeers(newClient.TrustedPeers).
Save(context.TODO())
if err != nil {
return rollback(tx, "update client uploading: %w", err)
}
if err = tx.Commit(); err != nil {
return rollback(tx, "update auth request commit: %w", err)
}
return nil
}

View file

@ -0,0 +1,88 @@
package client
import (
"context"
"github.com/dexidp/dex/storage"
)
// CreateConnector saves a connector into the database.
func (d *Database) CreateConnector(connector storage.Connector) error {
_, err := d.client.Connector.Create().
SetID(connector.ID).
SetName(connector.Name).
SetType(connector.Type).
SetResourceVersion(connector.ResourceVersion).
SetConfig(connector.Config).
Save(context.TODO())
if err != nil {
return convertDBError("create connector: %w", err)
}
return nil
}
// ListConnectors extracts an array of connectors from the database.
func (d *Database) ListConnectors() ([]storage.Connector, error) {
connectors, err := d.client.Connector.Query().All(context.TODO())
if err != nil {
return nil, convertDBError("list connectors: %w", err)
}
storageConnectors := make([]storage.Connector, 0, len(connectors))
for _, c := range connectors {
storageConnectors = append(storageConnectors, toStorageConnector(c))
}
return storageConnectors, nil
}
// GetConnector extracts a connector from the database by id.
func (d *Database) GetConnector(id string) (storage.Connector, error) {
connector, err := d.client.Connector.Get(context.TODO(), id)
if err != nil {
return storage.Connector{}, convertDBError("get connector: %w", err)
}
return toStorageConnector(connector), nil
}
// DeleteConnector deletes a connector from the database by id.
func (d *Database) DeleteConnector(id string) error {
err := d.client.Connector.DeleteOneID(id).Exec(context.TODO())
if err != nil {
return convertDBError("delete connector: %w", err)
}
return nil
}
// UpdateConnector changes a connector by id using an updater function and saves it to the database.
func (d *Database) UpdateConnector(id string, updater func(old storage.Connector) (storage.Connector, error)) error {
tx, err := d.client.Tx(context.TODO())
if err != nil {
return convertDBError("update connector tx: %w", err)
}
connector, err := tx.Connector.Get(context.TODO(), id)
if err != nil {
return rollback(tx, "update connector database: %w", err)
}
newConnector, err := updater(toStorageConnector(connector))
if err != nil {
return rollback(tx, "update connector updating: %w", err)
}
_, err = tx.Connector.UpdateOneID(newConnector.ID).
SetName(newConnector.Name).
SetType(newConnector.Type).
SetResourceVersion(newConnector.ResourceVersion).
SetConfig(newConnector.Config).
Save(context.TODO())
if err != nil {
return rollback(tx, "update connector uploading: %w", err)
}
if err = tx.Commit(); err != nil {
return rollback(tx, "update connector commit: %w", err)
}
return nil
}

View file

@ -0,0 +1,36 @@
package client
import (
"context"
"github.com/dexidp/dex/storage"
"github.com/dexidp/dex/storage/ent/db/devicerequest"
)
// CreateDeviceRequest saves provided device request into the database.
func (d *Database) CreateDeviceRequest(request storage.DeviceRequest) error {
_, err := d.client.DeviceRequest.Create().
SetClientID(request.ClientID).
SetClientSecret(request.ClientSecret).
SetScopes(request.Scopes).
SetUserCode(request.UserCode).
SetDeviceCode(request.DeviceCode).
// Save utc time into database because ent doesn't support comparing dates with different timezones
SetExpiry(request.Expiry.UTC()).
Save(context.TODO())
if err != nil {
return convertDBError("create device request: %w", err)
}
return nil
}
// GetDeviceRequest extracts a device request from the database by user code.
func (d *Database) GetDeviceRequest(userCode string) (storage.DeviceRequest, error) {
deviceRequest, err := d.client.DeviceRequest.Query().
Where(devicerequest.UserCode(userCode)).
Only(context.TODO())
if err != nil {
return storage.DeviceRequest{}, convertDBError("get device request: %w", err)
}
return toStorageDeviceRequest(deviceRequest), nil
}

View file

@ -0,0 +1,76 @@
package client
import (
"context"
"github.com/dexidp/dex/storage"
"github.com/dexidp/dex/storage/ent/db/devicetoken"
)
// CreateDeviceToken saves provided token into the database.
func (d *Database) CreateDeviceToken(token storage.DeviceToken) error {
_, err := d.client.DeviceToken.Create().
SetDeviceCode(token.DeviceCode).
SetToken([]byte(token.Token)).
SetPollInterval(token.PollIntervalSeconds).
// Save utc time into database because ent doesn't support comparing dates with different timezones
SetExpiry(token.Expiry.UTC()).
SetLastRequest(token.LastRequestTime.UTC()).
SetStatus(token.Status).
Save(context.TODO())
if err != nil {
return convertDBError("create device token: %w", err)
}
return nil
}
// GetDeviceToken extracts a token from the database by device code.
func (d *Database) GetDeviceToken(deviceCode string) (storage.DeviceToken, error) {
deviceToken, err := d.client.DeviceToken.Query().
Where(devicetoken.DeviceCode(deviceCode)).
Only(context.TODO())
if err != nil {
return storage.DeviceToken{}, convertDBError("get device token: %w", err)
}
return toStorageDeviceToken(deviceToken), nil
}
// UpdateDeviceToken changes a token by device code using an updater function and saves it to the database.
func (d *Database) UpdateDeviceToken(deviceCode string, updater func(old storage.DeviceToken) (storage.DeviceToken, error)) error {
tx, err := d.client.Tx(context.TODO())
if err != nil {
return convertDBError("update device token tx: %w", err)
}
token, err := tx.DeviceToken.Query().
Where(devicetoken.DeviceCode(deviceCode)).
Only(context.TODO())
if err != nil {
return rollback(tx, "update device token database: %w", err)
}
newToken, err := updater(toStorageDeviceToken(token))
if err != nil {
return rollback(tx, "update device token updating: %w", err)
}
_, err = tx.DeviceToken.Update().
Where(devicetoken.DeviceCode(newToken.DeviceCode)).
SetDeviceCode(newToken.DeviceCode).
SetToken([]byte(newToken.Token)).
SetPollInterval(newToken.PollIntervalSeconds).
// Save utc time into database because ent doesn't support comparing dates with different timezones
SetExpiry(newToken.Expiry.UTC()).
SetLastRequest(newToken.LastRequestTime.UTC()).
SetStatus(newToken.Status).
Save(context.TODO())
if err != nil {
return rollback(tx, "update device token uploading: %w", err)
}
if err = tx.Commit(); err != nil {
return rollback(tx, "update device token commit: %w", err)
}
return nil
}

View file

@ -0,0 +1,81 @@
package client
import (
"context"
"errors"
"github.com/dexidp/dex/storage"
"github.com/dexidp/dex/storage/ent/db"
)
func getKeys(client *db.KeysClient) (storage.Keys, error) {
rawKeys, err := client.Get(context.TODO(), keysRowID)
if err != nil {
return storage.Keys{}, convertDBError("get keys: %w", err)
}
return toStorageKeys(rawKeys), nil
}
// GetKeys returns signing keys, public keys and verification keys from the database.
func (d *Database) GetKeys() (storage.Keys, error) {
return getKeys(d.client.Keys)
}
// UpdateKeys rotates keys using updater function.
func (d *Database) UpdateKeys(updater func(old storage.Keys) (storage.Keys, error)) error {
firstUpdate := false
tx, err := d.client.Tx(context.TODO())
if err != nil {
return convertDBError("update keys tx: %w", err)
}
storageKeys, err := getKeys(tx.Keys)
if err != nil {
if !errors.Is(err, storage.ErrNotFound) {
return rollback(tx, "update keys get: %w", err)
}
firstUpdate = true
}
newKeys, err := updater(storageKeys)
if err != nil {
return rollback(tx, "update keys updating: %w", err)
}
// ent doesn't have an upsert support yet
// https://github.com/facebook/ent/issues/139
if firstUpdate {
_, err = tx.Keys.Create().
SetID(keysRowID).
SetNextRotation(newKeys.NextRotation).
SetSigningKey(*newKeys.SigningKey).
SetSigningKeyPub(*newKeys.SigningKeyPub).
SetVerificationKeys(newKeys.VerificationKeys).
Save(context.TODO())
if err != nil {
return rollback(tx, "create keys: %w", err)
}
if err = tx.Commit(); err != nil {
return rollback(tx, "update keys commit: %w", err)
}
return nil
}
err = tx.Keys.UpdateOneID(keysRowID).
SetNextRotation(newKeys.NextRotation.UTC()).
SetSigningKey(*newKeys.SigningKey).
SetSigningKeyPub(*newKeys.SigningKeyPub).
SetVerificationKeys(newKeys.VerificationKeys).
Exec(context.TODO())
if err != nil {
return rollback(tx, "update keys uploading: %w", err)
}
if err = tx.Commit(); err != nil {
return rollback(tx, "update keys commit: %w", err)
}
return nil
}

View file

@ -0,0 +1,95 @@
package client
import (
"context"
"hash"
"time"
"github.com/dexidp/dex/storage"
"github.com/dexidp/dex/storage/ent/db"
"github.com/dexidp/dex/storage/ent/db/authcode"
"github.com/dexidp/dex/storage/ent/db/authrequest"
"github.com/dexidp/dex/storage/ent/db/devicerequest"
"github.com/dexidp/dex/storage/ent/db/devicetoken"
"github.com/dexidp/dex/storage/ent/db/migrate"
)
var _ storage.Storage = (*Database)(nil)
type Database struct {
client *db.Client
hasher func() hash.Hash
}
// NewDatabase returns new database client with set options.
func NewDatabase(opts ...func(*Database)) *Database {
database := &Database{}
for _, f := range opts {
f(database)
}
return database
}
// WithClient sets client option of a Database object.
func WithClient(c *db.Client) func(*Database) {
return func(s *Database) {
s.client = c
}
}
// WithHasher sets client option of a Database object.
func WithHasher(h func() hash.Hash) func(*Database) {
return func(s *Database) {
s.hasher = h
}
}
// Schema exposes migration schema to perform migrations.
func (d *Database) Schema() *migrate.Schema {
return d.client.Schema
}
// Close calls the corresponding method of the ent database client.
func (d *Database) Close() error {
return d.client.Close()
}
// GarbageCollect removes expired entities from the database.
func (d *Database) GarbageCollect(now time.Time) (storage.GCResult, error) {
result := storage.GCResult{}
utcNow := now.UTC()
q, err := d.client.AuthRequest.Delete().
Where(authrequest.ExpiryLT(utcNow)).
Exec(context.TODO())
if err != nil {
return result, convertDBError("gc auth request: %w", err)
}
result.AuthRequests = int64(q)
q, err = d.client.AuthCode.Delete().
Where(authcode.ExpiryLT(utcNow)).
Exec(context.TODO())
if err != nil {
return result, convertDBError("gc auth code: %w", err)
}
result.AuthCodes = int64(q)
q, err = d.client.DeviceRequest.Delete().
Where(devicerequest.ExpiryLT(utcNow)).
Exec(context.TODO())
if err != nil {
return result, convertDBError("gc device request: %w", err)
}
result.DeviceRequests = int64(q)
q, err = d.client.DeviceToken.Delete().
Where(devicetoken.ExpiryLT(utcNow)).
Exec(context.TODO())
if err != nil {
return result, convertDBError("gc device token: %w", err)
}
result.DeviceTokens = int64(q)
return result, err
}

View file

@ -0,0 +1,93 @@
package client
import (
"context"
"encoding/json"
"fmt"
"github.com/dexidp/dex/storage"
)
// CreateOfflineSessions saves provided offline session into the database.
func (d *Database) CreateOfflineSessions(session storage.OfflineSessions) error {
encodedRefresh, err := json.Marshal(session.Refresh)
if err != nil {
return fmt.Errorf("encode refresh offline session: %w", err)
}
id := offlineSessionID(session.UserID, session.ConnID, d.hasher)
_, err = d.client.OfflineSession.Create().
SetID(id).
SetUserID(session.UserID).
SetConnID(session.ConnID).
SetConnectorData(session.ConnectorData).
SetRefresh(encodedRefresh).
Save(context.TODO())
if err != nil {
return convertDBError("create offline session: %w", err)
}
return nil
}
// GetOfflineSessions extracts an offline session from the database by user id and connector id.
func (d *Database) GetOfflineSessions(userID, connID string) (storage.OfflineSessions, error) {
id := offlineSessionID(userID, connID, d.hasher)
offlineSession, err := d.client.OfflineSession.Get(context.TODO(), id)
if err != nil {
return storage.OfflineSessions{}, convertDBError("get offline session: %w", err)
}
return toStorageOfflineSession(offlineSession), nil
}
// DeleteOfflineSessions deletes an offline session from the database by user id and connector id.
func (d *Database) DeleteOfflineSessions(userID, connID string) error {
id := offlineSessionID(userID, connID, d.hasher)
err := d.client.OfflineSession.DeleteOneID(id).Exec(context.TODO())
if err != nil {
return convertDBError("delete offline session: %w", err)
}
return nil
}
// UpdatePassword changes an offline session by user id and connector id using an updater function.
func (d *Database) UpdateOfflineSessions(userID string, connID string, updater func(s storage.OfflineSessions) (storage.OfflineSessions, error)) error {
id := offlineSessionID(userID, connID, d.hasher)
tx, err := d.client.Tx(context.TODO())
if err != nil {
return convertDBError("update offline session tx: %w", err)
}
offlineSession, err := tx.OfflineSession.Get(context.TODO(), id)
if err != nil {
return rollback(tx, "update offline session database: %w", err)
}
newOfflineSession, err := updater(toStorageOfflineSession(offlineSession))
if err != nil {
return rollback(tx, "update offline session updating: %w", err)
}
encodedRefresh, err := json.Marshal(newOfflineSession.Refresh)
if err != nil {
return rollback(tx, "encode refresh offline session: %w", err)
}
_, err = tx.OfflineSession.UpdateOneID(id).
SetUserID(newOfflineSession.UserID).
SetConnID(newOfflineSession.ConnID).
SetConnectorData(newOfflineSession.ConnectorData).
SetRefresh(encodedRefresh).
Save(context.TODO())
if err != nil {
return rollback(tx, "update offline session uploading: %w", err)
}
if err = tx.Commit(); err != nil {
return rollback(tx, "update password commit: %w", err)
}
return nil
}

View file

@ -0,0 +1,100 @@
package client
import (
"context"
"strings"
"github.com/dexidp/dex/storage"
"github.com/dexidp/dex/storage/ent/db/password"
)
// CreatePassword saves provided password into the database.
func (d *Database) CreatePassword(password storage.Password) error {
_, err := d.client.Password.Create().
SetEmail(password.Email).
SetHash(password.Hash).
SetUsername(password.Username).
SetUserID(password.UserID).
Save(context.TODO())
if err != nil {
return convertDBError("create password: %w", err)
}
return nil
}
// ListPasswords extracts an array of passwords from the database.
func (d *Database) ListPasswords() ([]storage.Password, error) {
passwords, err := d.client.Password.Query().All(context.TODO())
if err != nil {
return nil, convertDBError("list passwords: %w", err)
}
storagePasswords := make([]storage.Password, 0, len(passwords))
for _, p := range passwords {
storagePasswords = append(storagePasswords, toStoragePassword(p))
}
return storagePasswords, nil
}
// GetPassword extracts a password from the database by email.
func (d *Database) GetPassword(email string) (storage.Password, error) {
email = strings.ToLower(email)
passwordFromStorage, err := d.client.Password.Query().
Where(password.Email(email)).
Only(context.TODO())
if err != nil {
return storage.Password{}, convertDBError("get password: %w", err)
}
return toStoragePassword(passwordFromStorage), nil
}
// DeletePassword deletes a password from the database by email.
func (d *Database) DeletePassword(email string) error {
email = strings.ToLower(email)
_, err := d.client.Password.Delete().
Where(password.Email(email)).
Exec(context.TODO())
if err != nil {
return convertDBError("delete password: %w", err)
}
return nil
}
// UpdatePassword changes a password by email using an updater function and saves it to the database.
func (d *Database) UpdatePassword(email string, updater func(old storage.Password) (storage.Password, error)) error {
email = strings.ToLower(email)
tx, err := d.client.Tx(context.TODO())
if err != nil {
return convertDBError("update connector tx: %w", err)
}
passwordToUpdate, err := tx.Password.Query().
Where(password.Email(email)).
Only(context.TODO())
if err != nil {
return rollback(tx, "update password database: %w", err)
}
newPassword, err := updater(toStoragePassword(passwordToUpdate))
if err != nil {
return rollback(tx, "update password updating: %w", err)
}
_, err = tx.Password.Update().
Where(password.Email(newPassword.Email)).
SetEmail(newPassword.Email).
SetHash(newPassword.Hash).
SetUsername(newPassword.Username).
SetUserID(newPassword.UserID).
Save(context.TODO())
if err != nil {
return rollback(tx, "update password uploading: %w", err)
}
if err = tx.Commit(); err != nil {
return rollback(tx, "update password commit: %w", err)
}
return nil
}

View file

@ -0,0 +1,111 @@
package client
import (
"context"
"github.com/dexidp/dex/storage"
)
// CreateRefresh saves provided refresh token into the database.
func (d *Database) CreateRefresh(refresh storage.RefreshToken) error {
_, err := d.client.RefreshToken.Create().
SetID(refresh.ID).
SetClientID(refresh.ClientID).
SetScopes(refresh.Scopes).
SetNonce(refresh.Nonce).
SetClaimsUserID(refresh.Claims.UserID).
SetClaimsEmail(refresh.Claims.Email).
SetClaimsEmailVerified(refresh.Claims.EmailVerified).
SetClaimsUsername(refresh.Claims.Username).
SetClaimsPreferredUsername(refresh.Claims.PreferredUsername).
SetClaimsGroups(refresh.Claims.Groups).
SetConnectorID(refresh.ConnectorID).
SetConnectorData(refresh.ConnectorData).
SetToken(refresh.Token).
SetObsoleteToken(refresh.ObsoleteToken).
// Save utc time into database because ent doesn't support comparing dates with different timezones
SetLastUsed(refresh.LastUsed.UTC()).
SetCreatedAt(refresh.CreatedAt.UTC()).
Save(context.TODO())
if err != nil {
return convertDBError("create refresh token: %w", err)
}
return nil
}
// ListRefreshTokens extracts an array of refresh tokens from the database.
func (d *Database) ListRefreshTokens() ([]storage.RefreshToken, error) {
refreshTokens, err := d.client.RefreshToken.Query().All(context.TODO())
if err != nil {
return nil, convertDBError("list refresh tokens: %w", err)
}
storageRefreshTokens := make([]storage.RefreshToken, 0, len(refreshTokens))
for _, r := range refreshTokens {
storageRefreshTokens = append(storageRefreshTokens, toStorageRefreshToken(r))
}
return storageRefreshTokens, nil
}
// GetRefresh extracts a refresh token from the database by id.
func (d *Database) GetRefresh(id string) (storage.RefreshToken, error) {
refreshToken, err := d.client.RefreshToken.Get(context.TODO(), id)
if err != nil {
return storage.RefreshToken{}, convertDBError("get refresh token: %w", err)
}
return toStorageRefreshToken(refreshToken), nil
}
// DeleteRefresh deletes a refresh token from the database by id.
func (d *Database) DeleteRefresh(id string) error {
err := d.client.RefreshToken.DeleteOneID(id).Exec(context.TODO())
if err != nil {
return convertDBError("delete refresh token: %w", err)
}
return nil
}
// UpdateRefreshToken changes a refresh token by id using an updater function and saves it to the database.
func (d *Database) UpdateRefreshToken(id string, updater func(old storage.RefreshToken) (storage.RefreshToken, error)) error {
tx, err := d.client.Tx(context.TODO())
if err != nil {
return convertDBError("update refresh token tx: %w", err)
}
token, err := tx.RefreshToken.Get(context.TODO(), id)
if err != nil {
return rollback(tx, "update refresh token database: %w", err)
}
newtToken, err := updater(toStorageRefreshToken(token))
if err != nil {
return rollback(tx, "update refresh token updating: %w", err)
}
_, err = tx.RefreshToken.UpdateOneID(newtToken.ID).
SetClientID(newtToken.ClientID).
SetScopes(newtToken.Scopes).
SetNonce(newtToken.Nonce).
SetClaimsUserID(newtToken.Claims.UserID).
SetClaimsEmail(newtToken.Claims.Email).
SetClaimsEmailVerified(newtToken.Claims.EmailVerified).
SetClaimsUsername(newtToken.Claims.Username).
SetClaimsPreferredUsername(newtToken.Claims.PreferredUsername).
SetClaimsGroups(newtToken.Claims.Groups).
SetConnectorID(newtToken.ConnectorID).
SetConnectorData(newtToken.ConnectorData).
SetToken(newtToken.Token).
SetObsoleteToken(newtToken.ObsoleteToken).
// Save utc time into database because ent doesn't support comparing dates with different timezones
SetLastUsed(newtToken.LastUsed.UTC()).
SetCreatedAt(newtToken.CreatedAt.UTC()).
Save(context.TODO())
if err != nil {
return rollback(tx, "update refresh token uploading: %w", err)
}
if err = tx.Commit(); err != nil {
return rollback(tx, "update refresh token commit: %w", err)
}
return nil
}

168
storage/ent/client/types.go Normal file
View file

@ -0,0 +1,168 @@
package client
import (
"encoding/json"
"strings"
"github.com/dexidp/dex/storage"
"github.com/dexidp/dex/storage/ent/db"
)
const keysRowID = "keys"
func toStorageKeys(keys *db.Keys) storage.Keys {
return storage.Keys{
SigningKey: &keys.SigningKey,
SigningKeyPub: &keys.SigningKeyPub,
VerificationKeys: keys.VerificationKeys,
NextRotation: keys.NextRotation,
}
}
func toStorageAuthRequest(a *db.AuthRequest) storage.AuthRequest {
return storage.AuthRequest{
ID: a.ID,
ClientID: a.ClientID,
ResponseTypes: a.ResponseTypes,
Scopes: a.Scopes,
RedirectURI: a.RedirectURI,
Nonce: a.Nonce,
State: a.State,
ForceApprovalPrompt: a.ForceApprovalPrompt,
LoggedIn: a.LoggedIn,
ConnectorID: a.ConnectorID,
ConnectorData: *a.ConnectorData,
Expiry: a.Expiry,
Claims: storage.Claims{
UserID: a.ClaimsUserID,
Username: a.ClaimsUsername,
PreferredUsername: a.ClaimsPreferredUsername,
Email: a.ClaimsEmail,
EmailVerified: a.ClaimsEmailVerified,
Groups: a.ClaimsGroups,
},
PKCE: storage.PKCE{
CodeChallenge: a.CodeChallenge,
CodeChallengeMethod: a.CodeChallengeMethod,
},
}
}
func toStorageAuthCode(a *db.AuthCode) storage.AuthCode {
return storage.AuthCode{
ID: a.ID,
ClientID: a.ClientID,
Scopes: a.Scopes,
RedirectURI: a.RedirectURI,
Nonce: a.Nonce,
ConnectorID: a.ConnectorID,
ConnectorData: *a.ConnectorData,
Expiry: a.Expiry,
Claims: storage.Claims{
UserID: a.ClaimsUserID,
Username: a.ClaimsUsername,
PreferredUsername: a.ClaimsPreferredUsername,
Email: a.ClaimsEmail,
EmailVerified: a.ClaimsEmailVerified,
Groups: a.ClaimsGroups,
},
PKCE: storage.PKCE{
CodeChallenge: a.CodeChallenge,
CodeChallengeMethod: a.CodeChallengeMethod,
},
}
}
func toStorageClient(c *db.OAuth2Client) storage.Client {
return storage.Client{
ID: c.ID,
Secret: c.Secret,
RedirectURIs: c.RedirectUris,
TrustedPeers: c.TrustedPeers,
Public: c.Public,
Name: c.Name,
LogoURL: c.LogoURL,
}
}
func toStorageConnector(c *db.Connector) storage.Connector {
return storage.Connector{
ID: c.ID,
Type: c.Type,
Name: c.Name,
Config: c.Config,
}
}
func toStorageOfflineSession(o *db.OfflineSession) storage.OfflineSessions {
s := storage.OfflineSessions{
UserID: o.UserID,
ConnID: o.ConnID,
ConnectorData: *o.ConnectorData,
}
if o.Refresh != nil {
if err := json.Unmarshal(o.Refresh, &s.Refresh); err != nil {
// Correctness of json structure if guaranteed on uploading
panic(err)
}
} else {
// Server code assumes this will be non-nil.
s.Refresh = make(map[string]*storage.RefreshTokenRef)
}
return s
}
func toStorageRefreshToken(r *db.RefreshToken) storage.RefreshToken {
return storage.RefreshToken{
ID: r.ID,
Token: r.Token,
ObsoleteToken: r.ObsoleteToken,
CreatedAt: r.CreatedAt,
LastUsed: r.LastUsed,
ClientID: r.ClientID,
ConnectorID: r.ConnectorID,
ConnectorData: *r.ConnectorData,
Scopes: r.Scopes,
Nonce: r.Nonce,
Claims: storage.Claims{
UserID: r.ClaimsUserID,
Username: r.ClaimsUsername,
PreferredUsername: r.ClaimsPreferredUsername,
Email: r.ClaimsEmail,
EmailVerified: r.ClaimsEmailVerified,
Groups: r.ClaimsGroups,
},
}
}
func toStoragePassword(p *db.Password) storage.Password {
return storage.Password{
Email: p.Email,
Hash: p.Hash,
Username: p.Username,
UserID: p.UserID,
}
}
func toStorageDeviceRequest(r *db.DeviceRequest) storage.DeviceRequest {
return storage.DeviceRequest{
UserCode: strings.ToUpper(r.UserCode),
DeviceCode: r.DeviceCode,
ClientID: r.ClientID,
ClientSecret: r.ClientSecret,
Scopes: r.Scopes,
Expiry: r.Expiry,
}
}
func toStorageDeviceToken(t *db.DeviceToken) storage.DeviceToken {
return storage.DeviceToken{
DeviceCode: t.DeviceCode,
Status: t.Status,
Token: string(*t.Token),
Expiry: t.Expiry,
LastRequestTime: t.LastRequest,
PollIntervalSeconds: t.PollInterval,
}
}

View file

@ -0,0 +1,44 @@
package client
import (
"fmt"
"hash"
"github.com/pkg/errors"
"github.com/dexidp/dex/storage"
"github.com/dexidp/dex/storage/ent/db"
)
func rollback(tx *db.Tx, t string, err error) error {
rerr := tx.Rollback()
err = convertDBError(t, err)
if rerr == nil {
return err
}
return errors.Wrapf(err, "rolling back transaction: %v", rerr)
}
func convertDBError(t string, err error) error {
if db.IsNotFound(err) {
return storage.ErrNotFound
}
if db.IsConstraintError(err) {
return storage.ErrAlreadyExists
}
return fmt.Errorf(t, err)
}
// compose hashed id from user and connection id to use it as primary key
// ent doesn't support multi-key primary yet
// https://github.com/facebook/ent/issues/400
func offlineSessionID(userID string, connID string, hasher func() hash.Hash) string {
h := hasher()
h.Write([]byte(userID))
h.Write([]byte(connID))
return fmt.Sprintf("%x", h.Sum(nil))
}

253
storage/ent/db/authcode.go Normal file
View file

@ -0,0 +1,253 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"encoding/json"
"fmt"
"strings"
"time"
"entgo.io/ent/dialect/sql"
"github.com/dexidp/dex/storage/ent/db/authcode"
)
// AuthCode is the model entity for the AuthCode schema.
type AuthCode struct {
config `json:"-"`
// ID of the ent.
ID string `json:"id,omitempty"`
// ClientID holds the value of the "client_id" field.
ClientID string `json:"client_id,omitempty"`
// Scopes holds the value of the "scopes" field.
Scopes []string `json:"scopes,omitempty"`
// Nonce holds the value of the "nonce" field.
Nonce string `json:"nonce,omitempty"`
// RedirectURI holds the value of the "redirect_uri" field.
RedirectURI string `json:"redirect_uri,omitempty"`
// ClaimsUserID holds the value of the "claims_user_id" field.
ClaimsUserID string `json:"claims_user_id,omitempty"`
// ClaimsUsername holds the value of the "claims_username" field.
ClaimsUsername string `json:"claims_username,omitempty"`
// ClaimsEmail holds the value of the "claims_email" field.
ClaimsEmail string `json:"claims_email,omitempty"`
// ClaimsEmailVerified holds the value of the "claims_email_verified" field.
ClaimsEmailVerified bool `json:"claims_email_verified,omitempty"`
// ClaimsGroups holds the value of the "claims_groups" field.
ClaimsGroups []string `json:"claims_groups,omitempty"`
// ClaimsPreferredUsername holds the value of the "claims_preferred_username" field.
ClaimsPreferredUsername string `json:"claims_preferred_username,omitempty"`
// ConnectorID holds the value of the "connector_id" field.
ConnectorID string `json:"connector_id,omitempty"`
// ConnectorData holds the value of the "connector_data" field.
ConnectorData *[]byte `json:"connector_data,omitempty"`
// Expiry holds the value of the "expiry" field.
Expiry time.Time `json:"expiry,omitempty"`
// CodeChallenge holds the value of the "code_challenge" field.
CodeChallenge string `json:"code_challenge,omitempty"`
// CodeChallengeMethod holds the value of the "code_challenge_method" field.
CodeChallengeMethod string `json:"code_challenge_method,omitempty"`
}
// scanValues returns the types for scanning values from sql.Rows.
func (*AuthCode) scanValues(columns []string) ([]interface{}, error) {
values := make([]interface{}, len(columns))
for i := range columns {
switch columns[i] {
case authcode.FieldScopes, authcode.FieldClaimsGroups, authcode.FieldConnectorData:
values[i] = new([]byte)
case authcode.FieldClaimsEmailVerified:
values[i] = new(sql.NullBool)
case authcode.FieldID, authcode.FieldClientID, authcode.FieldNonce, authcode.FieldRedirectURI, authcode.FieldClaimsUserID, authcode.FieldClaimsUsername, authcode.FieldClaimsEmail, authcode.FieldClaimsPreferredUsername, authcode.FieldConnectorID, authcode.FieldCodeChallenge, authcode.FieldCodeChallengeMethod:
values[i] = new(sql.NullString)
case authcode.FieldExpiry:
values[i] = new(sql.NullTime)
default:
return nil, fmt.Errorf("unexpected column %q for type AuthCode", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the AuthCode fields.
func (ac *AuthCode) assignValues(columns []string, values []interface{}) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case authcode.FieldID:
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
}
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
}
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 {
return fmt.Errorf("unmarshal field scopes: %w", err)
}
}
case authcode.FieldNonce:
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
}
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
}
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
}
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
}
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
}
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
}
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 {
return fmt.Errorf("unmarshal field claims_groups: %w", err)
}
}
case authcode.FieldClaimsPreferredUsername:
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
}
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
}
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
}
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
}
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
}
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
}
}
}
return nil
}
// 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 (&AuthCodeClient{config: ac.config}).UpdateOne(ac)
}
// 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)
if !ok {
panic("db: AuthCode is not a transactional entity")
}
ac.config.driver = tx.drv
return ac
}
// String implements the fmt.Stringer.
func (ac *AuthCode) String() string {
var builder strings.Builder
builder.WriteString("AuthCode(")
builder.WriteString(fmt.Sprintf("id=%v", ac.ID))
builder.WriteString(", client_id=")
builder.WriteString(ac.ClientID)
builder.WriteString(", scopes=")
builder.WriteString(fmt.Sprintf("%v", ac.Scopes))
builder.WriteString(", nonce=")
builder.WriteString(ac.Nonce)
builder.WriteString(", redirect_uri=")
builder.WriteString(ac.RedirectURI)
builder.WriteString(", claims_user_id=")
builder.WriteString(ac.ClaimsUserID)
builder.WriteString(", claims_username=")
builder.WriteString(ac.ClaimsUsername)
builder.WriteString(", claims_email=")
builder.WriteString(ac.ClaimsEmail)
builder.WriteString(", claims_email_verified=")
builder.WriteString(fmt.Sprintf("%v", ac.ClaimsEmailVerified))
builder.WriteString(", claims_groups=")
builder.WriteString(fmt.Sprintf("%v", ac.ClaimsGroups))
builder.WriteString(", claims_preferred_username=")
builder.WriteString(ac.ClaimsPreferredUsername)
builder.WriteString(", connector_id=")
builder.WriteString(ac.ConnectorID)
if v := ac.ConnectorData; v != nil {
builder.WriteString(", connector_data=")
builder.WriteString(fmt.Sprintf("%v", *v))
}
builder.WriteString(", expiry=")
builder.WriteString(ac.Expiry.Format(time.ANSIC))
builder.WriteString(", code_challenge=")
builder.WriteString(ac.CodeChallenge)
builder.WriteString(", code_challenge_method=")
builder.WriteString(ac.CodeChallengeMethod)
builder.WriteByte(')')
return builder.String()
}
// AuthCodes is a parsable slice of AuthCode.
type AuthCodes []*AuthCode
func (ac AuthCodes) config(cfg config) {
for _i := range ac {
ac[_i].config = cfg
}
}

View file

@ -0,0 +1,97 @@
// Code generated by entc, DO NOT EDIT.
package authcode
const (
// Label holds the string label denoting the authcode type in the database.
Label = "auth_code"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldClientID holds the string denoting the client_id field in the database.
FieldClientID = "client_id"
// FieldScopes holds the string denoting the scopes field in the database.
FieldScopes = "scopes"
// FieldNonce holds the string denoting the nonce field in the database.
FieldNonce = "nonce"
// FieldRedirectURI holds the string denoting the redirect_uri field in the database.
FieldRedirectURI = "redirect_uri"
// FieldClaimsUserID holds the string denoting the claims_user_id field in the database.
FieldClaimsUserID = "claims_user_id"
// FieldClaimsUsername holds the string denoting the claims_username field in the database.
FieldClaimsUsername = "claims_username"
// FieldClaimsEmail holds the string denoting the claims_email field in the database.
FieldClaimsEmail = "claims_email"
// FieldClaimsEmailVerified holds the string denoting the claims_email_verified field in the database.
FieldClaimsEmailVerified = "claims_email_verified"
// FieldClaimsGroups holds the string denoting the claims_groups field in the database.
FieldClaimsGroups = "claims_groups"
// FieldClaimsPreferredUsername holds the string denoting the claims_preferred_username field in the database.
FieldClaimsPreferredUsername = "claims_preferred_username"
// FieldConnectorID holds the string denoting the connector_id field in the database.
FieldConnectorID = "connector_id"
// FieldConnectorData holds the string denoting the connector_data field in the database.
FieldConnectorData = "connector_data"
// FieldExpiry holds the string denoting the expiry field in the database.
FieldExpiry = "expiry"
// FieldCodeChallenge holds the string denoting the code_challenge field in the database.
FieldCodeChallenge = "code_challenge"
// FieldCodeChallengeMethod holds the string denoting the code_challenge_method field in the database.
FieldCodeChallengeMethod = "code_challenge_method"
// Table holds the table name of the authcode in the database.
Table = "auth_codes"
)
// Columns holds all SQL columns for authcode fields.
var Columns = []string{
FieldID,
FieldClientID,
FieldScopes,
FieldNonce,
FieldRedirectURI,
FieldClaimsUserID,
FieldClaimsUsername,
FieldClaimsEmail,
FieldClaimsEmailVerified,
FieldClaimsGroups,
FieldClaimsPreferredUsername,
FieldConnectorID,
FieldConnectorData,
FieldExpiry,
FieldCodeChallenge,
FieldCodeChallengeMethod,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// ClientIDValidator is a validator for the "client_id" field. It is called by the builders before save.
ClientIDValidator func(string) error
// NonceValidator is a validator for the "nonce" field. It is called by the builders before save.
NonceValidator func(string) error
// RedirectURIValidator is a validator for the "redirect_uri" field. It is called by the builders before save.
RedirectURIValidator func(string) error
// ClaimsUserIDValidator is a validator for the "claims_user_id" field. It is called by the builders before save.
ClaimsUserIDValidator func(string) error
// ClaimsUsernameValidator is a validator for the "claims_username" field. It is called by the builders before save.
ClaimsUsernameValidator func(string) error
// ClaimsEmailValidator is a validator for the "claims_email" field. It is called by the builders before save.
ClaimsEmailValidator func(string) error
// DefaultClaimsPreferredUsername holds the default value on creation for the "claims_preferred_username" field.
DefaultClaimsPreferredUsername string
// ConnectorIDValidator is a validator for the "connector_id" field. It is called by the builders before save.
ConnectorIDValidator func(string) error
// DefaultCodeChallenge holds the default value on creation for the "code_challenge" field.
DefaultCodeChallenge string
// DefaultCodeChallengeMethod holds the default value on creation for the "code_challenge_method" field.
DefaultCodeChallengeMethod string
// IDValidator is a validator for the "id" field. It is called by the builders before save.
IDValidator func(string) error
)

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,502 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/authcode"
)
// AuthCodeCreate is the builder for creating a AuthCode entity.
type AuthCodeCreate struct {
config
mutation *AuthCodeMutation
hooks []Hook
}
// SetClientID sets the "client_id" field.
func (acc *AuthCodeCreate) SetClientID(s string) *AuthCodeCreate {
acc.mutation.SetClientID(s)
return acc
}
// SetScopes sets the "scopes" field.
func (acc *AuthCodeCreate) SetScopes(s []string) *AuthCodeCreate {
acc.mutation.SetScopes(s)
return acc
}
// SetNonce sets the "nonce" field.
func (acc *AuthCodeCreate) SetNonce(s string) *AuthCodeCreate {
acc.mutation.SetNonce(s)
return acc
}
// SetRedirectURI sets the "redirect_uri" field.
func (acc *AuthCodeCreate) SetRedirectURI(s string) *AuthCodeCreate {
acc.mutation.SetRedirectURI(s)
return acc
}
// SetClaimsUserID sets the "claims_user_id" field.
func (acc *AuthCodeCreate) SetClaimsUserID(s string) *AuthCodeCreate {
acc.mutation.SetClaimsUserID(s)
return acc
}
// SetClaimsUsername sets the "claims_username" field.
func (acc *AuthCodeCreate) SetClaimsUsername(s string) *AuthCodeCreate {
acc.mutation.SetClaimsUsername(s)
return acc
}
// SetClaimsEmail sets the "claims_email" field.
func (acc *AuthCodeCreate) SetClaimsEmail(s string) *AuthCodeCreate {
acc.mutation.SetClaimsEmail(s)
return acc
}
// SetClaimsEmailVerified sets the "claims_email_verified" field.
func (acc *AuthCodeCreate) SetClaimsEmailVerified(b bool) *AuthCodeCreate {
acc.mutation.SetClaimsEmailVerified(b)
return acc
}
// SetClaimsGroups sets the "claims_groups" field.
func (acc *AuthCodeCreate) SetClaimsGroups(s []string) *AuthCodeCreate {
acc.mutation.SetClaimsGroups(s)
return acc
}
// SetClaimsPreferredUsername sets the "claims_preferred_username" field.
func (acc *AuthCodeCreate) SetClaimsPreferredUsername(s string) *AuthCodeCreate {
acc.mutation.SetClaimsPreferredUsername(s)
return acc
}
// 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)
}
return acc
}
// SetConnectorID sets the "connector_id" field.
func (acc *AuthCodeCreate) SetConnectorID(s string) *AuthCodeCreate {
acc.mutation.SetConnectorID(s)
return acc
}
// SetConnectorData sets the "connector_data" field.
func (acc *AuthCodeCreate) SetConnectorData(b []byte) *AuthCodeCreate {
acc.mutation.SetConnectorData(b)
return acc
}
// SetExpiry sets the "expiry" field.
func (acc *AuthCodeCreate) SetExpiry(t time.Time) *AuthCodeCreate {
acc.mutation.SetExpiry(t)
return acc
}
// SetCodeChallenge sets the "code_challenge" field.
func (acc *AuthCodeCreate) SetCodeChallenge(s string) *AuthCodeCreate {
acc.mutation.SetCodeChallenge(s)
return acc
}
// 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)
}
return acc
}
// SetCodeChallengeMethod sets the "code_challenge_method" field.
func (acc *AuthCodeCreate) SetCodeChallengeMethod(s string) *AuthCodeCreate {
acc.mutation.SetCodeChallengeMethod(s)
return acc
}
// 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)
}
return acc
}
// SetID sets the "id" field.
func (acc *AuthCodeCreate) SetID(s string) *AuthCodeCreate {
acc.mutation.SetID(s)
return acc
}
// Mutation returns the AuthCodeMutation object of the builder.
func (acc *AuthCodeCreate) Mutation() *AuthCodeMutation {
return acc.mutation
}
// Save creates the AuthCode in the database.
func (acc *AuthCodeCreate) Save(ctx context.Context) (*AuthCode, error) {
var (
err error
node *AuthCode
)
acc.defaults()
if len(acc.hooks) == 0 {
if err = acc.check(); err != nil {
return nil, err
}
node, err = acc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*AuthCodeMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = acc.check(); err != nil {
return nil, err
}
acc.mutation = mutation
node, err = acc.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(acc.hooks) - 1; i >= 0; i-- {
mut = acc.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, acc.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (acc *AuthCodeCreate) SaveX(ctx context.Context) *AuthCode {
v, err := acc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// defaults sets the default values of the builder before save.
func (acc *AuthCodeCreate) defaults() {
if _, ok := acc.mutation.ClaimsPreferredUsername(); !ok {
v := authcode.DefaultClaimsPreferredUsername
acc.mutation.SetClaimsPreferredUsername(v)
}
if _, ok := acc.mutation.CodeChallenge(); !ok {
v := authcode.DefaultCodeChallenge
acc.mutation.SetCodeChallenge(v)
}
if _, ok := acc.mutation.CodeChallengeMethod(); !ok {
v := authcode.DefaultCodeChallengeMethod
acc.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 {
return &ValidationError{Name: "client_id", err: errors.New("db: missing required field \"client_id\"")}
}
if v, ok := acc.mutation.ClientID(); ok {
if err := authcode.ClientIDValidator(v); err != nil {
return &ValidationError{Name: "client_id", err: fmt.Errorf("db: validator failed for field \"client_id\": %w", err)}
}
}
if _, ok := acc.mutation.Nonce(); !ok {
return &ValidationError{Name: "nonce", err: errors.New("db: missing required field \"nonce\"")}
}
if v, ok := acc.mutation.Nonce(); ok {
if err := authcode.NonceValidator(v); err != nil {
return &ValidationError{Name: "nonce", err: fmt.Errorf("db: validator failed for field \"nonce\": %w", err)}
}
}
if _, ok := acc.mutation.RedirectURI(); !ok {
return &ValidationError{Name: "redirect_uri", err: errors.New("db: missing required field \"redirect_uri\"")}
}
if v, ok := acc.mutation.RedirectURI(); ok {
if err := authcode.RedirectURIValidator(v); err != nil {
return &ValidationError{Name: "redirect_uri", err: fmt.Errorf("db: validator failed for field \"redirect_uri\": %w", err)}
}
}
if _, ok := acc.mutation.ClaimsUserID(); !ok {
return &ValidationError{Name: "claims_user_id", err: errors.New("db: missing required field \"claims_user_id\"")}
}
if v, ok := acc.mutation.ClaimsUserID(); ok {
if err := authcode.ClaimsUserIDValidator(v); err != nil {
return &ValidationError{Name: "claims_user_id", err: fmt.Errorf("db: validator failed for field \"claims_user_id\": %w", err)}
}
}
if _, ok := acc.mutation.ClaimsUsername(); !ok {
return &ValidationError{Name: "claims_username", err: errors.New("db: missing required field \"claims_username\"")}
}
if v, ok := acc.mutation.ClaimsUsername(); ok {
if err := authcode.ClaimsUsernameValidator(v); err != nil {
return &ValidationError{Name: "claims_username", err: fmt.Errorf("db: validator failed for field \"claims_username\": %w", err)}
}
}
if _, ok := acc.mutation.ClaimsEmail(); !ok {
return &ValidationError{Name: "claims_email", err: errors.New("db: missing required field \"claims_email\"")}
}
if v, ok := acc.mutation.ClaimsEmail(); ok {
if err := authcode.ClaimsEmailValidator(v); err != nil {
return &ValidationError{Name: "claims_email", err: fmt.Errorf("db: validator failed for field \"claims_email\": %w", err)}
}
}
if _, ok := acc.mutation.ClaimsEmailVerified(); !ok {
return &ValidationError{Name: "claims_email_verified", err: errors.New("db: missing required field \"claims_email_verified\"")}
}
if _, ok := acc.mutation.ClaimsPreferredUsername(); !ok {
return &ValidationError{Name: "claims_preferred_username", err: errors.New("db: missing required field \"claims_preferred_username\"")}
}
if _, ok := acc.mutation.ConnectorID(); !ok {
return &ValidationError{Name: "connector_id", err: errors.New("db: missing required field \"connector_id\"")}
}
if v, ok := acc.mutation.ConnectorID(); ok {
if err := authcode.ConnectorIDValidator(v); err != nil {
return &ValidationError{Name: "connector_id", err: fmt.Errorf("db: validator failed for field \"connector_id\": %w", err)}
}
}
if _, ok := acc.mutation.Expiry(); !ok {
return &ValidationError{Name: "expiry", err: errors.New("db: missing required field \"expiry\"")}
}
if _, ok := acc.mutation.CodeChallenge(); !ok {
return &ValidationError{Name: "code_challenge", err: errors.New("db: missing required field \"code_challenge\"")}
}
if _, ok := acc.mutation.CodeChallengeMethod(); !ok {
return &ValidationError{Name: "code_challenge_method", err: errors.New("db: missing required field \"code_challenge_method\"")}
}
if v, ok := acc.mutation.ID(); ok {
if err := authcode.IDValidator(v); err != nil {
return &ValidationError{Name: "id", err: fmt.Errorf("db: validator failed for field \"id\": %w", err)}
}
}
return nil
}
func (acc *AuthCodeCreate) sqlSave(ctx context.Context) (*AuthCode, error) {
_node, _spec := acc.createSpec()
if err := sqlgraph.CreateNode(ctx, acc.driver, _spec); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return nil, err
}
return _node, nil
}
func (acc *AuthCodeCreate) createSpec() (*AuthCode, *sqlgraph.CreateSpec) {
var (
_node = &AuthCode{config: acc.config}
_spec = &sqlgraph.CreateSpec{
Table: authcode.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: authcode.FieldID,
},
}
)
if id, ok := acc.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = id
}
if value, ok := acc.mutation.ClientID(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldClientID,
})
_node.ClientID = value
}
if value, ok := acc.mutation.Scopes(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: authcode.FieldScopes,
})
_node.Scopes = value
}
if value, ok := acc.mutation.Nonce(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldNonce,
})
_node.Nonce = value
}
if value, ok := acc.mutation.RedirectURI(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldRedirectURI,
})
_node.RedirectURI = value
}
if value, ok := acc.mutation.ClaimsUserID(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldClaimsUserID,
})
_node.ClaimsUserID = value
}
if value, ok := acc.mutation.ClaimsUsername(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldClaimsUsername,
})
_node.ClaimsUsername = value
}
if value, ok := acc.mutation.ClaimsEmail(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldClaimsEmail,
})
_node.ClaimsEmail = value
}
if value, ok := acc.mutation.ClaimsEmailVerified(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: authcode.FieldClaimsEmailVerified,
})
_node.ClaimsEmailVerified = value
}
if value, ok := acc.mutation.ClaimsGroups(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: authcode.FieldClaimsGroups,
})
_node.ClaimsGroups = value
}
if value, ok := acc.mutation.ClaimsPreferredUsername(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldClaimsPreferredUsername,
})
_node.ClaimsPreferredUsername = value
}
if value, ok := acc.mutation.ConnectorID(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldConnectorID,
})
_node.ConnectorID = value
}
if value, ok := acc.mutation.ConnectorData(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: authcode.FieldConnectorData,
})
_node.ConnectorData = &value
}
if value, ok := acc.mutation.Expiry(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: authcode.FieldExpiry,
})
_node.Expiry = value
}
if value, ok := acc.mutation.CodeChallenge(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldCodeChallenge,
})
_node.CodeChallenge = value
}
if value, ok := acc.mutation.CodeChallengeMethod(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldCodeChallengeMethod,
})
_node.CodeChallengeMethod = value
}
return _node, _spec
}
// AuthCodeCreateBulk is the builder for creating many AuthCode entities in bulk.
type AuthCodeCreateBulk struct {
config
builders []*AuthCodeCreate
}
// Save creates the AuthCode entities in the database.
func (accb *AuthCodeCreateBulk) Save(ctx context.Context) ([]*AuthCode, error) {
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(i int, root context.Context) {
builder := accb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*AuthCodeMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
nodes[i], specs[i] = builder.createSpec()
var err error
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, accb.builders[i+1].mutation)
} else {
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, accb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
}
}
mutation.done = true
if err != nil {
return nil, err
}
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, accb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (accb *AuthCodeCreateBulk) SaveX(ctx context.Context) []*AuthCode {
v, err := accb.Save(ctx)
if err != nil {
panic(err)
}
return v
}

View file

@ -0,0 +1,108 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/authcode"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// AuthCodeDelete is the builder for deleting a AuthCode entity.
type AuthCodeDelete struct {
config
hooks []Hook
mutation *AuthCodeMutation
}
// Where adds a new predicate to the AuthCodeDelete builder.
func (acd *AuthCodeDelete) Where(ps ...predicate.AuthCode) *AuthCodeDelete {
acd.mutation.predicates = append(acd.mutation.predicates, ps...)
return acd
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (acd *AuthCodeDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(acd.hooks) == 0 {
affected, err = acd.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*AuthCodeMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
acd.mutation = mutation
affected, err = acd.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(acd.hooks) - 1; i >= 0; i-- {
mut = acd.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, acd.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (acd *AuthCodeDelete) ExecX(ctx context.Context) int {
n, err := acd.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (acd *AuthCodeDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: authcode.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: authcode.FieldID,
},
},
}
if ps := acd.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return sqlgraph.DeleteNodes(ctx, acd.driver, _spec)
}
// AuthCodeDeleteOne is the builder for deleting a single AuthCode entity.
type AuthCodeDeleteOne struct {
acd *AuthCodeDelete
}
// Exec executes the deletion query.
func (acdo *AuthCodeDeleteOne) Exec(ctx context.Context) error {
n, err := acdo.acd.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{authcode.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (acdo *AuthCodeDeleteOne) ExecX(ctx context.Context) {
acdo.acd.ExecX(ctx)
}

View file

@ -0,0 +1,906 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"errors"
"fmt"
"math"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/authcode"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// AuthCodeQuery is the builder for querying AuthCode entities.
type AuthCodeQuery struct {
config
limit *int
offset *int
unique *bool
order []OrderFunc
fields []string
predicates []predicate.AuthCode
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// 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
}
// Limit adds a limit step to the query.
func (acq *AuthCodeQuery) Limit(limit int) *AuthCodeQuery {
acq.limit = &limit
return acq
}
// Offset adds an offset step to the query.
func (acq *AuthCodeQuery) Offset(offset int) *AuthCodeQuery {
acq.offset = &offset
return acq
}
// 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.unique = &unique
return acq
}
// Order adds an order step to the query.
func (acq *AuthCodeQuery) Order(o ...OrderFunc) *AuthCodeQuery {
acq.order = append(acq.order, o...)
return acq
}
// 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(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{authcode.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (acq *AuthCodeQuery) FirstX(ctx context.Context) *AuthCode {
node, err := acq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// 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) {
var ids []string
if ids, err = acq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{authcode.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (acq *AuthCodeQuery) FirstIDX(ctx context.Context) string {
id, err := acq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single AuthCode entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when exactly one AuthCode entity is not 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(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{authcode.Label}
default:
return nil, &NotSingularError{authcode.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (acq *AuthCodeQuery) OnlyX(ctx context.Context) *AuthCode {
node, err := acq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only AuthCode ID in the query.
// Returns a *NotSingularError when exactly one AuthCode ID is not found.
// Returns a *NotFoundError when no entities are found.
func (acq *AuthCodeQuery) OnlyID(ctx context.Context) (id string, err error) {
var ids []string
if ids, err = acq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{authcode.Label}
default:
err = &NotSingularError{authcode.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (acq *AuthCodeQuery) OnlyIDX(ctx context.Context) string {
id, err := acq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of AuthCodes.
func (acq *AuthCodeQuery) All(ctx context.Context) ([]*AuthCode, error) {
if err := acq.prepareQuery(ctx); err != nil {
return nil, err
}
return acq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (acq *AuthCodeQuery) AllX(ctx context.Context) []*AuthCode {
nodes, err := acq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of AuthCode IDs.
func (acq *AuthCodeQuery) IDs(ctx context.Context) ([]string, error) {
var ids []string
if err := acq.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)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (acq *AuthCodeQuery) Count(ctx context.Context) (int, error) {
if err := acq.prepareQuery(ctx); err != nil {
return 0, err
}
return acq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (acq *AuthCodeQuery) CountX(ctx context.Context) int {
count, err := acq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (acq *AuthCodeQuery) Exist(ctx context.Context) (bool, error) {
if err := acq.prepareQuery(ctx); err != nil {
return false, err
}
return acq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (acq *AuthCodeQuery) ExistX(ctx context.Context) bool {
exist, err := acq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// 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 {
return nil
}
return &AuthCodeQuery{
config: acq.config,
limit: acq.limit,
offset: acq.offset,
order: append([]OrderFunc{}, acq.order...),
predicates: append([]predicate.AuthCode{}, acq.predicates...),
// clone intermediate query.
sql: acq.sql.Clone(),
path: acq.path,
}
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// ClientID string `json:"client_id,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.AuthCode.Query().
// GroupBy(authcode.FieldClientID).
// Aggregate(db.Count()).
// Scan(ctx, &v)
//
func (acq *AuthCodeQuery) GroupBy(field string, fields ...string) *AuthCodeGroupBy {
group := &AuthCodeGroupBy{config: acq.config}
group.fields = append([]string{field}, fields...)
group.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := acq.prepareQuery(ctx); err != nil {
return nil, err
}
return acq.sqlQuery(ctx), nil
}
return group
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// ClientID string `json:"client_id,omitempty"`
// }
//
// client.AuthCode.Query().
// Select(authcode.FieldClientID).
// Scan(ctx, &v)
//
func (acq *AuthCodeQuery) Select(field string, fields ...string) *AuthCodeSelect {
acq.fields = append([]string{field}, fields...)
return &AuthCodeSelect{AuthCodeQuery: acq}
}
func (acq *AuthCodeQuery) prepareQuery(ctx context.Context) error {
for _, f := range acq.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 err != nil {
return err
}
acq.sql = prev
}
return nil
}
func (acq *AuthCodeQuery) sqlAll(ctx context.Context) ([]*AuthCode, error) {
var (
nodes = []*AuthCode{}
_spec = acq.querySpec()
)
_spec.ScanValues = func(columns []string) ([]interface{}, error) {
node := &AuthCode{config: acq.config}
nodes = append(nodes, node)
return node.scanValues(columns)
}
_spec.Assign = func(columns []string, values []interface{}) error {
if len(nodes) == 0 {
return fmt.Errorf("db: Assign called without calling ScanValues")
}
node := nodes[len(nodes)-1]
return node.assignValues(columns, values)
}
if err := sqlgraph.QueryNodes(ctx, acq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (acq *AuthCodeQuery) sqlCount(ctx context.Context) (int, error) {
_spec := acq.querySpec()
return sqlgraph.CountNodes(ctx, acq.driver, _spec)
}
func (acq *AuthCodeQuery) sqlExist(ctx context.Context) (bool, error) {
n, err := acq.sqlCount(ctx)
if err != nil {
return false, fmt.Errorf("db: check existence: %w", err)
}
return n > 0, nil
}
func (acq *AuthCodeQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: authcode.Table,
Columns: authcode.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: authcode.FieldID,
},
},
From: acq.sql,
Unique: true,
}
if unique := acq.unique; unique != nil {
_spec.Unique = *unique
}
if fields := acq.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 {
if fields[i] != authcode.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := acq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := acq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := acq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := acq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (acq *AuthCodeQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(acq.driver.Dialect())
t1 := builder.Table(authcode.Table)
selector := builder.Select(t1.Columns(authcode.Columns...)...).From(t1)
if acq.sql != nil {
selector = acq.sql
selector.Select(selector.Columns(authcode.Columns...)...)
}
for _, p := range acq.predicates {
p(selector)
}
for _, p := range acq.order {
p(selector)
}
if offset := acq.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.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// AuthCodeGroupBy is the group-by builder for AuthCode entities.
type AuthCodeGroupBy struct {
config
fields []string
fns []AggregateFunc
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Aggregate adds the given aggregation functions to the group-by query.
func (acgb *AuthCodeGroupBy) Aggregate(fns ...AggregateFunc) *AuthCodeGroupBy {
acgb.fns = append(acgb.fns, fns...)
return acgb
}
// Scan applies the group-by query and scans the result into the given value.
func (acgb *AuthCodeGroupBy) Scan(ctx context.Context, v interface{}) error {
query, err := acgb.path(ctx)
if err != nil {
return err
}
acgb.sql = query
return acgb.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (acgb *AuthCodeGroupBy) ScanX(ctx context.Context, v interface{}) {
if err := acgb.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from group-by.
// It is only allowed when executing a group-by query with one field.
func (acgb *AuthCodeGroupBy) Strings(ctx context.Context) ([]string, error) {
if len(acgb.fields) > 1 {
return nil, errors.New("db: AuthCodeGroupBy.Strings is not achievable when grouping more than 1 field")
}
var v []string
if err := acgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (acgb *AuthCodeGroupBy) StringsX(ctx context.Context) []string {
v, err := acgb.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (acgb *AuthCodeGroupBy) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = acgb.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{authcode.Label}
default:
err = fmt.Errorf("db: AuthCodeGroupBy.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (acgb *AuthCodeGroupBy) StringX(ctx context.Context) string {
v, err := acgb.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from group-by.
// It is only allowed when executing a group-by query with one field.
func (acgb *AuthCodeGroupBy) Ints(ctx context.Context) ([]int, error) {
if len(acgb.fields) > 1 {
return nil, errors.New("db: AuthCodeGroupBy.Ints is not achievable when grouping more than 1 field")
}
var v []int
if err := acgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (acgb *AuthCodeGroupBy) IntsX(ctx context.Context) []int {
v, err := acgb.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (acgb *AuthCodeGroupBy) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = acgb.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{authcode.Label}
default:
err = fmt.Errorf("db: AuthCodeGroupBy.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (acgb *AuthCodeGroupBy) IntX(ctx context.Context) int {
v, err := acgb.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from group-by.
// It is only allowed when executing a group-by query with one field.
func (acgb *AuthCodeGroupBy) Float64s(ctx context.Context) ([]float64, error) {
if len(acgb.fields) > 1 {
return nil, errors.New("db: AuthCodeGroupBy.Float64s is not achievable when grouping more than 1 field")
}
var v []float64
if err := acgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (acgb *AuthCodeGroupBy) Float64sX(ctx context.Context) []float64 {
v, err := acgb.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (acgb *AuthCodeGroupBy) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = acgb.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{authcode.Label}
default:
err = fmt.Errorf("db: AuthCodeGroupBy.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (acgb *AuthCodeGroupBy) Float64X(ctx context.Context) float64 {
v, err := acgb.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from group-by.
// It is only allowed when executing a group-by query with one field.
func (acgb *AuthCodeGroupBy) Bools(ctx context.Context) ([]bool, error) {
if len(acgb.fields) > 1 {
return nil, errors.New("db: AuthCodeGroupBy.Bools is not achievable when grouping more than 1 field")
}
var v []bool
if err := acgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (acgb *AuthCodeGroupBy) BoolsX(ctx context.Context) []bool {
v, err := acgb.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (acgb *AuthCodeGroupBy) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = acgb.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{authcode.Label}
default:
err = fmt.Errorf("db: AuthCodeGroupBy.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (acgb *AuthCodeGroupBy) BoolX(ctx context.Context) bool {
v, err := acgb.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
func (acgb *AuthCodeGroupBy) sqlScan(ctx context.Context, v interface{}) error {
for _, f := range acgb.fields {
if !authcode.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := acgb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := acgb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (acgb *AuthCodeGroupBy) sqlQuery() *sql.Selector {
selector := acgb.sql
columns := make([]string, 0, len(acgb.fields)+len(acgb.fns))
columns = append(columns, acgb.fields...)
for _, fn := range acgb.fns {
columns = append(columns, fn(selector))
}
return selector.Select(columns...).GroupBy(acgb.fields...)
}
// AuthCodeSelect is the builder for selecting fields of AuthCode entities.
type AuthCodeSelect struct {
*AuthCodeQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
}
// Scan applies the selector query and scans the result into the given value.
func (acs *AuthCodeSelect) Scan(ctx context.Context, v interface{}) error {
if err := acs.prepareQuery(ctx); err != nil {
return err
}
acs.sql = acs.AuthCodeQuery.sqlQuery(ctx)
return acs.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (acs *AuthCodeSelect) ScanX(ctx context.Context, v interface{}) {
if err := acs.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from a selector. It is only allowed when selecting one field.
func (acs *AuthCodeSelect) Strings(ctx context.Context) ([]string, error) {
if len(acs.fields) > 1 {
return nil, errors.New("db: AuthCodeSelect.Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := acs.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (acs *AuthCodeSelect) StringsX(ctx context.Context) []string {
v, err := acs.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a selector. It is only allowed when selecting one field.
func (acs *AuthCodeSelect) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = acs.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{authcode.Label}
default:
err = fmt.Errorf("db: AuthCodeSelect.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (acs *AuthCodeSelect) StringX(ctx context.Context) string {
v, err := acs.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from a selector. It is only allowed when selecting one field.
func (acs *AuthCodeSelect) Ints(ctx context.Context) ([]int, error) {
if len(acs.fields) > 1 {
return nil, errors.New("db: AuthCodeSelect.Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := acs.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (acs *AuthCodeSelect) IntsX(ctx context.Context) []int {
v, err := acs.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a selector. It is only allowed when selecting one field.
func (acs *AuthCodeSelect) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = acs.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{authcode.Label}
default:
err = fmt.Errorf("db: AuthCodeSelect.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (acs *AuthCodeSelect) IntX(ctx context.Context) int {
v, err := acs.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
func (acs *AuthCodeSelect) Float64s(ctx context.Context) ([]float64, error) {
if len(acs.fields) > 1 {
return nil, errors.New("db: AuthCodeSelect.Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := acs.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (acs *AuthCodeSelect) Float64sX(ctx context.Context) []float64 {
v, err := acs.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
func (acs *AuthCodeSelect) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = acs.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{authcode.Label}
default:
err = fmt.Errorf("db: AuthCodeSelect.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (acs *AuthCodeSelect) Float64X(ctx context.Context) float64 {
v, err := acs.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from a selector. It is only allowed when selecting one field.
func (acs *AuthCodeSelect) Bools(ctx context.Context) ([]bool, error) {
if len(acs.fields) > 1 {
return nil, errors.New("db: AuthCodeSelect.Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := acs.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (acs *AuthCodeSelect) BoolsX(ctx context.Context) []bool {
v, err := acs.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a selector. It is only allowed when selecting one field.
func (acs *AuthCodeSelect) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = acs.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{authcode.Label}
default:
err = fmt.Errorf("db: AuthCodeSelect.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (acs *AuthCodeSelect) BoolX(ctx context.Context) bool {
v, err := acs.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
func (acs *AuthCodeSelect) sqlScan(ctx context.Context, v interface{}) error {
rows := &sql.Rows{}
query, args := acs.sqlQuery().Query()
if err := acs.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (acs *AuthCodeSelect) sqlQuery() sql.Querier {
selector := acs.sql
selector.Select(selector.Columns(acs.fields...)...)
return selector
}

View file

@ -0,0 +1,835 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"fmt"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/authcode"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// AuthCodeUpdate is the builder for updating AuthCode entities.
type AuthCodeUpdate struct {
config
hooks []Hook
mutation *AuthCodeMutation
}
// Where adds a new predicate for the AuthCodeUpdate builder.
func (acu *AuthCodeUpdate) Where(ps ...predicate.AuthCode) *AuthCodeUpdate {
acu.mutation.predicates = append(acu.mutation.predicates, ps...)
return acu
}
// SetClientID sets the "client_id" field.
func (acu *AuthCodeUpdate) SetClientID(s string) *AuthCodeUpdate {
acu.mutation.SetClientID(s)
return acu
}
// SetScopes sets the "scopes" field.
func (acu *AuthCodeUpdate) SetScopes(s []string) *AuthCodeUpdate {
acu.mutation.SetScopes(s)
return acu
}
// ClearScopes clears the value of the "scopes" field.
func (acu *AuthCodeUpdate) ClearScopes() *AuthCodeUpdate {
acu.mutation.ClearScopes()
return acu
}
// SetNonce sets the "nonce" field.
func (acu *AuthCodeUpdate) SetNonce(s string) *AuthCodeUpdate {
acu.mutation.SetNonce(s)
return acu
}
// SetRedirectURI sets the "redirect_uri" field.
func (acu *AuthCodeUpdate) SetRedirectURI(s string) *AuthCodeUpdate {
acu.mutation.SetRedirectURI(s)
return acu
}
// SetClaimsUserID sets the "claims_user_id" field.
func (acu *AuthCodeUpdate) SetClaimsUserID(s string) *AuthCodeUpdate {
acu.mutation.SetClaimsUserID(s)
return acu
}
// SetClaimsUsername sets the "claims_username" field.
func (acu *AuthCodeUpdate) SetClaimsUsername(s string) *AuthCodeUpdate {
acu.mutation.SetClaimsUsername(s)
return acu
}
// SetClaimsEmail sets the "claims_email" field.
func (acu *AuthCodeUpdate) SetClaimsEmail(s string) *AuthCodeUpdate {
acu.mutation.SetClaimsEmail(s)
return acu
}
// SetClaimsEmailVerified sets the "claims_email_verified" field.
func (acu *AuthCodeUpdate) SetClaimsEmailVerified(b bool) *AuthCodeUpdate {
acu.mutation.SetClaimsEmailVerified(b)
return acu
}
// SetClaimsGroups sets the "claims_groups" field.
func (acu *AuthCodeUpdate) SetClaimsGroups(s []string) *AuthCodeUpdate {
acu.mutation.SetClaimsGroups(s)
return acu
}
// ClearClaimsGroups clears the value of the "claims_groups" field.
func (acu *AuthCodeUpdate) ClearClaimsGroups() *AuthCodeUpdate {
acu.mutation.ClearClaimsGroups()
return acu
}
// SetClaimsPreferredUsername sets the "claims_preferred_username" field.
func (acu *AuthCodeUpdate) SetClaimsPreferredUsername(s string) *AuthCodeUpdate {
acu.mutation.SetClaimsPreferredUsername(s)
return acu
}
// 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)
}
return acu
}
// SetConnectorID sets the "connector_id" field.
func (acu *AuthCodeUpdate) SetConnectorID(s string) *AuthCodeUpdate {
acu.mutation.SetConnectorID(s)
return acu
}
// SetConnectorData sets the "connector_data" field.
func (acu *AuthCodeUpdate) SetConnectorData(b []byte) *AuthCodeUpdate {
acu.mutation.SetConnectorData(b)
return acu
}
// ClearConnectorData clears the value of the "connector_data" field.
func (acu *AuthCodeUpdate) ClearConnectorData() *AuthCodeUpdate {
acu.mutation.ClearConnectorData()
return acu
}
// SetExpiry sets the "expiry" field.
func (acu *AuthCodeUpdate) SetExpiry(t time.Time) *AuthCodeUpdate {
acu.mutation.SetExpiry(t)
return acu
}
// SetCodeChallenge sets the "code_challenge" field.
func (acu *AuthCodeUpdate) SetCodeChallenge(s string) *AuthCodeUpdate {
acu.mutation.SetCodeChallenge(s)
return acu
}
// 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)
}
return acu
}
// SetCodeChallengeMethod sets the "code_challenge_method" field.
func (acu *AuthCodeUpdate) SetCodeChallengeMethod(s string) *AuthCodeUpdate {
acu.mutation.SetCodeChallengeMethod(s)
return acu
}
// 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)
}
return acu
}
// Mutation returns the AuthCodeMutation object of the builder.
func (acu *AuthCodeUpdate) Mutation() *AuthCodeMutation {
return acu.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) {
var (
err error
affected int
)
if len(acu.hooks) == 0 {
if err = acu.check(); err != nil {
return 0, err
}
affected, err = acu.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*AuthCodeMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = acu.check(); err != nil {
return 0, err
}
acu.mutation = mutation
affected, err = acu.sqlSave(ctx)
mutation.done = true
return affected, err
})
for i := len(acu.hooks) - 1; i >= 0; i-- {
mut = acu.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, acu.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// SaveX is like Save, but panics if an error occurs.
func (acu *AuthCodeUpdate) SaveX(ctx context.Context) int {
affected, err := acu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (acu *AuthCodeUpdate) Exec(ctx context.Context) error {
_, err := acu.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 {
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 {
if err := authcode.ClientIDValidator(v); err != nil {
return &ValidationError{Name: "client_id", err: fmt.Errorf("db: validator failed for field \"client_id\": %w", err)}
}
}
if v, ok := acu.mutation.Nonce(); ok {
if err := authcode.NonceValidator(v); err != nil {
return &ValidationError{Name: "nonce", err: fmt.Errorf("db: validator failed for field \"nonce\": %w", err)}
}
}
if v, ok := acu.mutation.RedirectURI(); ok {
if err := authcode.RedirectURIValidator(v); err != nil {
return &ValidationError{Name: "redirect_uri", err: fmt.Errorf("db: validator failed for field \"redirect_uri\": %w", err)}
}
}
if v, ok := acu.mutation.ClaimsUserID(); ok {
if err := authcode.ClaimsUserIDValidator(v); err != nil {
return &ValidationError{Name: "claims_user_id", err: fmt.Errorf("db: validator failed for field \"claims_user_id\": %w", err)}
}
}
if v, ok := acu.mutation.ClaimsUsername(); ok {
if err := authcode.ClaimsUsernameValidator(v); err != nil {
return &ValidationError{Name: "claims_username", err: fmt.Errorf("db: validator failed for field \"claims_username\": %w", err)}
}
}
if v, ok := acu.mutation.ClaimsEmail(); ok {
if err := authcode.ClaimsEmailValidator(v); err != nil {
return &ValidationError{Name: "claims_email", err: fmt.Errorf("db: validator failed for field \"claims_email\": %w", err)}
}
}
if v, ok := acu.mutation.ConnectorID(); ok {
if err := authcode.ConnectorIDValidator(v); err != nil {
return &ValidationError{Name: "connector_id", err: fmt.Errorf("db: validator failed for field \"connector_id\": %w", err)}
}
}
return nil
}
func (acu *AuthCodeUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: authcode.Table,
Columns: authcode.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: authcode.FieldID,
},
},
}
if ps := acu.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 {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldClientID,
})
}
if value, ok := acu.mutation.Scopes(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: authcode.FieldScopes,
})
}
if acu.mutation.ScopesCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Column: authcode.FieldScopes,
})
}
if value, ok := acu.mutation.Nonce(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldNonce,
})
}
if value, ok := acu.mutation.RedirectURI(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldRedirectURI,
})
}
if value, ok := acu.mutation.ClaimsUserID(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldClaimsUserID,
})
}
if value, ok := acu.mutation.ClaimsUsername(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldClaimsUsername,
})
}
if value, ok := acu.mutation.ClaimsEmail(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldClaimsEmail,
})
}
if value, ok := acu.mutation.ClaimsEmailVerified(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: authcode.FieldClaimsEmailVerified,
})
}
if value, ok := acu.mutation.ClaimsGroups(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: authcode.FieldClaimsGroups,
})
}
if acu.mutation.ClaimsGroupsCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Column: authcode.FieldClaimsGroups,
})
}
if value, ok := acu.mutation.ClaimsPreferredUsername(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldClaimsPreferredUsername,
})
}
if value, ok := acu.mutation.ConnectorID(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldConnectorID,
})
}
if value, ok := acu.mutation.ConnectorData(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: authcode.FieldConnectorData,
})
}
if acu.mutation.ConnectorDataCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Column: authcode.FieldConnectorData,
})
}
if value, ok := acu.mutation.Expiry(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: authcode.FieldExpiry,
})
}
if value, ok := acu.mutation.CodeChallenge(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldCodeChallenge,
})
}
if value, ok := acu.mutation.CodeChallengeMethod(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldCodeChallengeMethod,
})
}
if n, err = sqlgraph.UpdateNodes(ctx, acu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{authcode.Label}
} else if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return 0, err
}
return n, nil
}
// AuthCodeUpdateOne is the builder for updating a single AuthCode entity.
type AuthCodeUpdateOne struct {
config
fields []string
hooks []Hook
mutation *AuthCodeMutation
}
// SetClientID sets the "client_id" field.
func (acuo *AuthCodeUpdateOne) SetClientID(s string) *AuthCodeUpdateOne {
acuo.mutation.SetClientID(s)
return acuo
}
// SetScopes sets the "scopes" field.
func (acuo *AuthCodeUpdateOne) SetScopes(s []string) *AuthCodeUpdateOne {
acuo.mutation.SetScopes(s)
return acuo
}
// ClearScopes clears the value of the "scopes" field.
func (acuo *AuthCodeUpdateOne) ClearScopes() *AuthCodeUpdateOne {
acuo.mutation.ClearScopes()
return acuo
}
// SetNonce sets the "nonce" field.
func (acuo *AuthCodeUpdateOne) SetNonce(s string) *AuthCodeUpdateOne {
acuo.mutation.SetNonce(s)
return acuo
}
// SetRedirectURI sets the "redirect_uri" field.
func (acuo *AuthCodeUpdateOne) SetRedirectURI(s string) *AuthCodeUpdateOne {
acuo.mutation.SetRedirectURI(s)
return acuo
}
// SetClaimsUserID sets the "claims_user_id" field.
func (acuo *AuthCodeUpdateOne) SetClaimsUserID(s string) *AuthCodeUpdateOne {
acuo.mutation.SetClaimsUserID(s)
return acuo
}
// SetClaimsUsername sets the "claims_username" field.
func (acuo *AuthCodeUpdateOne) SetClaimsUsername(s string) *AuthCodeUpdateOne {
acuo.mutation.SetClaimsUsername(s)
return acuo
}
// SetClaimsEmail sets the "claims_email" field.
func (acuo *AuthCodeUpdateOne) SetClaimsEmail(s string) *AuthCodeUpdateOne {
acuo.mutation.SetClaimsEmail(s)
return acuo
}
// SetClaimsEmailVerified sets the "claims_email_verified" field.
func (acuo *AuthCodeUpdateOne) SetClaimsEmailVerified(b bool) *AuthCodeUpdateOne {
acuo.mutation.SetClaimsEmailVerified(b)
return acuo
}
// SetClaimsGroups sets the "claims_groups" field.
func (acuo *AuthCodeUpdateOne) SetClaimsGroups(s []string) *AuthCodeUpdateOne {
acuo.mutation.SetClaimsGroups(s)
return acuo
}
// ClearClaimsGroups clears the value of the "claims_groups" field.
func (acuo *AuthCodeUpdateOne) ClearClaimsGroups() *AuthCodeUpdateOne {
acuo.mutation.ClearClaimsGroups()
return acuo
}
// SetClaimsPreferredUsername sets the "claims_preferred_username" field.
func (acuo *AuthCodeUpdateOne) SetClaimsPreferredUsername(s string) *AuthCodeUpdateOne {
acuo.mutation.SetClaimsPreferredUsername(s)
return acuo
}
// 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)
}
return acuo
}
// SetConnectorID sets the "connector_id" field.
func (acuo *AuthCodeUpdateOne) SetConnectorID(s string) *AuthCodeUpdateOne {
acuo.mutation.SetConnectorID(s)
return acuo
}
// SetConnectorData sets the "connector_data" field.
func (acuo *AuthCodeUpdateOne) SetConnectorData(b []byte) *AuthCodeUpdateOne {
acuo.mutation.SetConnectorData(b)
return acuo
}
// ClearConnectorData clears the value of the "connector_data" field.
func (acuo *AuthCodeUpdateOne) ClearConnectorData() *AuthCodeUpdateOne {
acuo.mutation.ClearConnectorData()
return acuo
}
// SetExpiry sets the "expiry" field.
func (acuo *AuthCodeUpdateOne) SetExpiry(t time.Time) *AuthCodeUpdateOne {
acuo.mutation.SetExpiry(t)
return acuo
}
// SetCodeChallenge sets the "code_challenge" field.
func (acuo *AuthCodeUpdateOne) SetCodeChallenge(s string) *AuthCodeUpdateOne {
acuo.mutation.SetCodeChallenge(s)
return acuo
}
// 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)
}
return acuo
}
// SetCodeChallengeMethod sets the "code_challenge_method" field.
func (acuo *AuthCodeUpdateOne) SetCodeChallengeMethod(s string) *AuthCodeUpdateOne {
acuo.mutation.SetCodeChallengeMethod(s)
return acuo
}
// 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)
}
return acuo
}
// Mutation returns the AuthCodeMutation object of the builder.
func (acuo *AuthCodeUpdateOne) Mutation() *AuthCodeMutation {
return acuo.mutation
}
// 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
}
// Save executes the query and returns the updated AuthCode entity.
func (acuo *AuthCodeUpdateOne) Save(ctx context.Context) (*AuthCode, error) {
var (
err error
node *AuthCode
)
if len(acuo.hooks) == 0 {
if err = acuo.check(); err != nil {
return nil, err
}
node, err = acuo.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*AuthCodeMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = acuo.check(); err != nil {
return nil, err
}
acuo.mutation = mutation
node, err = acuo.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(acuo.hooks) - 1; i >= 0; i-- {
mut = acuo.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, acuo.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX is like Save, but panics if an error occurs.
func (acuo *AuthCodeUpdateOne) SaveX(ctx context.Context) *AuthCode {
node, err := acuo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (acuo *AuthCodeUpdateOne) Exec(ctx context.Context) error {
_, err := acuo.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 {
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 {
if err := authcode.ClientIDValidator(v); err != nil {
return &ValidationError{Name: "client_id", err: fmt.Errorf("db: validator failed for field \"client_id\": %w", err)}
}
}
if v, ok := acuo.mutation.Nonce(); ok {
if err := authcode.NonceValidator(v); err != nil {
return &ValidationError{Name: "nonce", err: fmt.Errorf("db: validator failed for field \"nonce\": %w", err)}
}
}
if v, ok := acuo.mutation.RedirectURI(); ok {
if err := authcode.RedirectURIValidator(v); err != nil {
return &ValidationError{Name: "redirect_uri", err: fmt.Errorf("db: validator failed for field \"redirect_uri\": %w", err)}
}
}
if v, ok := acuo.mutation.ClaimsUserID(); ok {
if err := authcode.ClaimsUserIDValidator(v); err != nil {
return &ValidationError{Name: "claims_user_id", err: fmt.Errorf("db: validator failed for field \"claims_user_id\": %w", err)}
}
}
if v, ok := acuo.mutation.ClaimsUsername(); ok {
if err := authcode.ClaimsUsernameValidator(v); err != nil {
return &ValidationError{Name: "claims_username", err: fmt.Errorf("db: validator failed for field \"claims_username\": %w", err)}
}
}
if v, ok := acuo.mutation.ClaimsEmail(); ok {
if err := authcode.ClaimsEmailValidator(v); err != nil {
return &ValidationError{Name: "claims_email", err: fmt.Errorf("db: validator failed for field \"claims_email\": %w", err)}
}
}
if v, ok := acuo.mutation.ConnectorID(); ok {
if err := authcode.ConnectorIDValidator(v); err != nil {
return &ValidationError{Name: "connector_id", err: fmt.Errorf("db: validator failed for field \"connector_id\": %w", err)}
}
}
return nil
}
func (acuo *AuthCodeUpdateOne) sqlSave(ctx context.Context) (_node *AuthCode, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: authcode.Table,
Columns: authcode.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: authcode.FieldID,
},
},
}
id, ok := acuo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing AuthCode.ID for update")}
}
_spec.Node.ID.Value = id
if fields := acuo.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 {
if !authcode.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
}
if f != authcode.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := acuo.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 {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldClientID,
})
}
if value, ok := acuo.mutation.Scopes(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: authcode.FieldScopes,
})
}
if acuo.mutation.ScopesCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Column: authcode.FieldScopes,
})
}
if value, ok := acuo.mutation.Nonce(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldNonce,
})
}
if value, ok := acuo.mutation.RedirectURI(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldRedirectURI,
})
}
if value, ok := acuo.mutation.ClaimsUserID(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldClaimsUserID,
})
}
if value, ok := acuo.mutation.ClaimsUsername(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldClaimsUsername,
})
}
if value, ok := acuo.mutation.ClaimsEmail(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldClaimsEmail,
})
}
if value, ok := acuo.mutation.ClaimsEmailVerified(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: authcode.FieldClaimsEmailVerified,
})
}
if value, ok := acuo.mutation.ClaimsGroups(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: authcode.FieldClaimsGroups,
})
}
if acuo.mutation.ClaimsGroupsCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Column: authcode.FieldClaimsGroups,
})
}
if value, ok := acuo.mutation.ClaimsPreferredUsername(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldClaimsPreferredUsername,
})
}
if value, ok := acuo.mutation.ConnectorID(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldConnectorID,
})
}
if value, ok := acuo.mutation.ConnectorData(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: authcode.FieldConnectorData,
})
}
if acuo.mutation.ConnectorDataCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Column: authcode.FieldConnectorData,
})
}
if value, ok := acuo.mutation.Expiry(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: authcode.FieldExpiry,
})
}
if value, ok := acuo.mutation.CodeChallenge(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldCodeChallenge,
})
}
if value, ok := acuo.mutation.CodeChallengeMethod(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authcode.FieldCodeChallengeMethod,
})
}
_node = &AuthCode{config: acuo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, acuo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{authcode.Label}
} else if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return nil, err
}
return _node, nil
}

View file

@ -0,0 +1,296 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"encoding/json"
"fmt"
"strings"
"time"
"entgo.io/ent/dialect/sql"
"github.com/dexidp/dex/storage/ent/db/authrequest"
)
// AuthRequest is the model entity for the AuthRequest schema.
type AuthRequest struct {
config `json:"-"`
// ID of the ent.
ID string `json:"id,omitempty"`
// ClientID holds the value of the "client_id" field.
ClientID string `json:"client_id,omitempty"`
// Scopes holds the value of the "scopes" field.
Scopes []string `json:"scopes,omitempty"`
// ResponseTypes holds the value of the "response_types" field.
ResponseTypes []string `json:"response_types,omitempty"`
// RedirectURI holds the value of the "redirect_uri" field.
RedirectURI string `json:"redirect_uri,omitempty"`
// Nonce holds the value of the "nonce" field.
Nonce string `json:"nonce,omitempty"`
// State holds the value of the "state" field.
State string `json:"state,omitempty"`
// ForceApprovalPrompt holds the value of the "force_approval_prompt" field.
ForceApprovalPrompt bool `json:"force_approval_prompt,omitempty"`
// LoggedIn holds the value of the "logged_in" field.
LoggedIn bool `json:"logged_in,omitempty"`
// ClaimsUserID holds the value of the "claims_user_id" field.
ClaimsUserID string `json:"claims_user_id,omitempty"`
// ClaimsUsername holds the value of the "claims_username" field.
ClaimsUsername string `json:"claims_username,omitempty"`
// ClaimsEmail holds the value of the "claims_email" field.
ClaimsEmail string `json:"claims_email,omitempty"`
// ClaimsEmailVerified holds the value of the "claims_email_verified" field.
ClaimsEmailVerified bool `json:"claims_email_verified,omitempty"`
// ClaimsGroups holds the value of the "claims_groups" field.
ClaimsGroups []string `json:"claims_groups,omitempty"`
// ClaimsPreferredUsername holds the value of the "claims_preferred_username" field.
ClaimsPreferredUsername string `json:"claims_preferred_username,omitempty"`
// ConnectorID holds the value of the "connector_id" field.
ConnectorID string `json:"connector_id,omitempty"`
// ConnectorData holds the value of the "connector_data" field.
ConnectorData *[]byte `json:"connector_data,omitempty"`
// Expiry holds the value of the "expiry" field.
Expiry time.Time `json:"expiry,omitempty"`
// CodeChallenge holds the value of the "code_challenge" field.
CodeChallenge string `json:"code_challenge,omitempty"`
// CodeChallengeMethod holds the value of the "code_challenge_method" field.
CodeChallengeMethod string `json:"code_challenge_method,omitempty"`
}
// scanValues returns the types for scanning values from sql.Rows.
func (*AuthRequest) scanValues(columns []string) ([]interface{}, error) {
values := make([]interface{}, len(columns))
for i := range columns {
switch columns[i] {
case authrequest.FieldScopes, authrequest.FieldResponseTypes, authrequest.FieldClaimsGroups, authrequest.FieldConnectorData:
values[i] = new([]byte)
case authrequest.FieldForceApprovalPrompt, authrequest.FieldLoggedIn, authrequest.FieldClaimsEmailVerified:
values[i] = new(sql.NullBool)
case authrequest.FieldID, authrequest.FieldClientID, authrequest.FieldRedirectURI, authrequest.FieldNonce, authrequest.FieldState, authrequest.FieldClaimsUserID, authrequest.FieldClaimsUsername, authrequest.FieldClaimsEmail, authrequest.FieldClaimsPreferredUsername, authrequest.FieldConnectorID, authrequest.FieldCodeChallenge, authrequest.FieldCodeChallengeMethod:
values[i] = new(sql.NullString)
case authrequest.FieldExpiry:
values[i] = new(sql.NullTime)
default:
return nil, fmt.Errorf("unexpected column %q for type AuthRequest", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the AuthRequest fields.
func (ar *AuthRequest) assignValues(columns []string, values []interface{}) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case authrequest.FieldID:
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
}
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
}
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 {
return fmt.Errorf("unmarshal field scopes: %w", err)
}
}
case authrequest.FieldResponseTypes:
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 {
return fmt.Errorf("unmarshal field response_types: %w", err)
}
}
case authrequest.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 {
ar.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
}
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
}
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
}
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
}
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
}
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
}
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
}
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
}
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 {
return fmt.Errorf("unmarshal field claims_groups: %w", err)
}
}
case authrequest.FieldClaimsPreferredUsername:
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
}
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
}
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
}
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
}
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
}
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
}
}
}
return nil
}
// 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 (&AuthRequestClient{config: ar.config}).UpdateOne(ar)
}
// 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)
if !ok {
panic("db: AuthRequest is not a transactional entity")
}
ar.config.driver = tx.drv
return ar
}
// String implements the fmt.Stringer.
func (ar *AuthRequest) String() string {
var builder strings.Builder
builder.WriteString("AuthRequest(")
builder.WriteString(fmt.Sprintf("id=%v", ar.ID))
builder.WriteString(", client_id=")
builder.WriteString(ar.ClientID)
builder.WriteString(", scopes=")
builder.WriteString(fmt.Sprintf("%v", ar.Scopes))
builder.WriteString(", response_types=")
builder.WriteString(fmt.Sprintf("%v", ar.ResponseTypes))
builder.WriteString(", redirect_uri=")
builder.WriteString(ar.RedirectURI)
builder.WriteString(", nonce=")
builder.WriteString(ar.Nonce)
builder.WriteString(", state=")
builder.WriteString(ar.State)
builder.WriteString(", force_approval_prompt=")
builder.WriteString(fmt.Sprintf("%v", ar.ForceApprovalPrompt))
builder.WriteString(", logged_in=")
builder.WriteString(fmt.Sprintf("%v", ar.LoggedIn))
builder.WriteString(", claims_user_id=")
builder.WriteString(ar.ClaimsUserID)
builder.WriteString(", claims_username=")
builder.WriteString(ar.ClaimsUsername)
builder.WriteString(", claims_email=")
builder.WriteString(ar.ClaimsEmail)
builder.WriteString(", claims_email_verified=")
builder.WriteString(fmt.Sprintf("%v", ar.ClaimsEmailVerified))
builder.WriteString(", claims_groups=")
builder.WriteString(fmt.Sprintf("%v", ar.ClaimsGroups))
builder.WriteString(", claims_preferred_username=")
builder.WriteString(ar.ClaimsPreferredUsername)
builder.WriteString(", connector_id=")
builder.WriteString(ar.ConnectorID)
if v := ar.ConnectorData; v != nil {
builder.WriteString(", connector_data=")
builder.WriteString(fmt.Sprintf("%v", *v))
}
builder.WriteString(", expiry=")
builder.WriteString(ar.Expiry.Format(time.ANSIC))
builder.WriteString(", code_challenge=")
builder.WriteString(ar.CodeChallenge)
builder.WriteString(", code_challenge_method=")
builder.WriteString(ar.CodeChallengeMethod)
builder.WriteByte(')')
return builder.String()
}
// AuthRequests is a parsable slice of AuthRequest.
type AuthRequests []*AuthRequest
func (ar AuthRequests) config(cfg config) {
for _i := range ar {
ar[_i].config = cfg
}
}

View file

@ -0,0 +1,95 @@
// Code generated by entc, DO NOT EDIT.
package authrequest
const (
// Label holds the string label denoting the authrequest type in the database.
Label = "auth_request"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldClientID holds the string denoting the client_id field in the database.
FieldClientID = "client_id"
// FieldScopes holds the string denoting the scopes field in the database.
FieldScopes = "scopes"
// FieldResponseTypes holds the string denoting the response_types field in the database.
FieldResponseTypes = "response_types"
// FieldRedirectURI holds the string denoting the redirect_uri field in the database.
FieldRedirectURI = "redirect_uri"
// FieldNonce holds the string denoting the nonce field in the database.
FieldNonce = "nonce"
// FieldState holds the string denoting the state field in the database.
FieldState = "state"
// FieldForceApprovalPrompt holds the string denoting the force_approval_prompt field in the database.
FieldForceApprovalPrompt = "force_approval_prompt"
// FieldLoggedIn holds the string denoting the logged_in field in the database.
FieldLoggedIn = "logged_in"
// FieldClaimsUserID holds the string denoting the claims_user_id field in the database.
FieldClaimsUserID = "claims_user_id"
// FieldClaimsUsername holds the string denoting the claims_username field in the database.
FieldClaimsUsername = "claims_username"
// FieldClaimsEmail holds the string denoting the claims_email field in the database.
FieldClaimsEmail = "claims_email"
// FieldClaimsEmailVerified holds the string denoting the claims_email_verified field in the database.
FieldClaimsEmailVerified = "claims_email_verified"
// FieldClaimsGroups holds the string denoting the claims_groups field in the database.
FieldClaimsGroups = "claims_groups"
// FieldClaimsPreferredUsername holds the string denoting the claims_preferred_username field in the database.
FieldClaimsPreferredUsername = "claims_preferred_username"
// FieldConnectorID holds the string denoting the connector_id field in the database.
FieldConnectorID = "connector_id"
// FieldConnectorData holds the string denoting the connector_data field in the database.
FieldConnectorData = "connector_data"
// FieldExpiry holds the string denoting the expiry field in the database.
FieldExpiry = "expiry"
// FieldCodeChallenge holds the string denoting the code_challenge field in the database.
FieldCodeChallenge = "code_challenge"
// FieldCodeChallengeMethod holds the string denoting the code_challenge_method field in the database.
FieldCodeChallengeMethod = "code_challenge_method"
// Table holds the table name of the authrequest in the database.
Table = "auth_requests"
)
// Columns holds all SQL columns for authrequest fields.
var Columns = []string{
FieldID,
FieldClientID,
FieldScopes,
FieldResponseTypes,
FieldRedirectURI,
FieldNonce,
FieldState,
FieldForceApprovalPrompt,
FieldLoggedIn,
FieldClaimsUserID,
FieldClaimsUsername,
FieldClaimsEmail,
FieldClaimsEmailVerified,
FieldClaimsGroups,
FieldClaimsPreferredUsername,
FieldConnectorID,
FieldConnectorData,
FieldExpiry,
FieldCodeChallenge,
FieldCodeChallengeMethod,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// DefaultClaimsPreferredUsername holds the default value on creation for the "claims_preferred_username" field.
DefaultClaimsPreferredUsername string
// DefaultCodeChallenge holds the default value on creation for the "code_challenge" field.
DefaultCodeChallenge string
// DefaultCodeChallengeMethod holds the default value on creation for the "code_challenge_method" field.
DefaultCodeChallengeMethod string
// IDValidator is a validator for the "id" field. It is called by the builders before save.
IDValidator func(string) error
)

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,532 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/authrequest"
)
// AuthRequestCreate is the builder for creating a AuthRequest entity.
type AuthRequestCreate struct {
config
mutation *AuthRequestMutation
hooks []Hook
}
// SetClientID sets the "client_id" field.
func (arc *AuthRequestCreate) SetClientID(s string) *AuthRequestCreate {
arc.mutation.SetClientID(s)
return arc
}
// SetScopes sets the "scopes" field.
func (arc *AuthRequestCreate) SetScopes(s []string) *AuthRequestCreate {
arc.mutation.SetScopes(s)
return arc
}
// SetResponseTypes sets the "response_types" field.
func (arc *AuthRequestCreate) SetResponseTypes(s []string) *AuthRequestCreate {
arc.mutation.SetResponseTypes(s)
return arc
}
// SetRedirectURI sets the "redirect_uri" field.
func (arc *AuthRequestCreate) SetRedirectURI(s string) *AuthRequestCreate {
arc.mutation.SetRedirectURI(s)
return arc
}
// SetNonce sets the "nonce" field.
func (arc *AuthRequestCreate) SetNonce(s string) *AuthRequestCreate {
arc.mutation.SetNonce(s)
return arc
}
// SetState sets the "state" field.
func (arc *AuthRequestCreate) SetState(s string) *AuthRequestCreate {
arc.mutation.SetState(s)
return arc
}
// SetForceApprovalPrompt sets the "force_approval_prompt" field.
func (arc *AuthRequestCreate) SetForceApprovalPrompt(b bool) *AuthRequestCreate {
arc.mutation.SetForceApprovalPrompt(b)
return arc
}
// SetLoggedIn sets the "logged_in" field.
func (arc *AuthRequestCreate) SetLoggedIn(b bool) *AuthRequestCreate {
arc.mutation.SetLoggedIn(b)
return arc
}
// SetClaimsUserID sets the "claims_user_id" field.
func (arc *AuthRequestCreate) SetClaimsUserID(s string) *AuthRequestCreate {
arc.mutation.SetClaimsUserID(s)
return arc
}
// SetClaimsUsername sets the "claims_username" field.
func (arc *AuthRequestCreate) SetClaimsUsername(s string) *AuthRequestCreate {
arc.mutation.SetClaimsUsername(s)
return arc
}
// SetClaimsEmail sets the "claims_email" field.
func (arc *AuthRequestCreate) SetClaimsEmail(s string) *AuthRequestCreate {
arc.mutation.SetClaimsEmail(s)
return arc
}
// SetClaimsEmailVerified sets the "claims_email_verified" field.
func (arc *AuthRequestCreate) SetClaimsEmailVerified(b bool) *AuthRequestCreate {
arc.mutation.SetClaimsEmailVerified(b)
return arc
}
// SetClaimsGroups sets the "claims_groups" field.
func (arc *AuthRequestCreate) SetClaimsGroups(s []string) *AuthRequestCreate {
arc.mutation.SetClaimsGroups(s)
return arc
}
// SetClaimsPreferredUsername sets the "claims_preferred_username" field.
func (arc *AuthRequestCreate) SetClaimsPreferredUsername(s string) *AuthRequestCreate {
arc.mutation.SetClaimsPreferredUsername(s)
return arc
}
// 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)
}
return arc
}
// SetConnectorID sets the "connector_id" field.
func (arc *AuthRequestCreate) SetConnectorID(s string) *AuthRequestCreate {
arc.mutation.SetConnectorID(s)
return arc
}
// SetConnectorData sets the "connector_data" field.
func (arc *AuthRequestCreate) SetConnectorData(b []byte) *AuthRequestCreate {
arc.mutation.SetConnectorData(b)
return arc
}
// SetExpiry sets the "expiry" field.
func (arc *AuthRequestCreate) SetExpiry(t time.Time) *AuthRequestCreate {
arc.mutation.SetExpiry(t)
return arc
}
// SetCodeChallenge sets the "code_challenge" field.
func (arc *AuthRequestCreate) SetCodeChallenge(s string) *AuthRequestCreate {
arc.mutation.SetCodeChallenge(s)
return arc
}
// 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)
}
return arc
}
// SetCodeChallengeMethod sets the "code_challenge_method" field.
func (arc *AuthRequestCreate) SetCodeChallengeMethod(s string) *AuthRequestCreate {
arc.mutation.SetCodeChallengeMethod(s)
return arc
}
// 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)
}
return arc
}
// SetID sets the "id" field.
func (arc *AuthRequestCreate) SetID(s string) *AuthRequestCreate {
arc.mutation.SetID(s)
return arc
}
// Mutation returns the AuthRequestMutation object of the builder.
func (arc *AuthRequestCreate) Mutation() *AuthRequestMutation {
return arc.mutation
}
// Save creates the AuthRequest in the database.
func (arc *AuthRequestCreate) Save(ctx context.Context) (*AuthRequest, error) {
var (
err error
node *AuthRequest
)
arc.defaults()
if len(arc.hooks) == 0 {
if err = arc.check(); err != nil {
return nil, err
}
node, err = arc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*AuthRequestMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = arc.check(); err != nil {
return nil, err
}
arc.mutation = mutation
node, err = arc.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(arc.hooks) - 1; i >= 0; i-- {
mut = arc.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, arc.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (arc *AuthRequestCreate) SaveX(ctx context.Context) *AuthRequest {
v, err := arc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// defaults sets the default values of the builder before save.
func (arc *AuthRequestCreate) defaults() {
if _, ok := arc.mutation.ClaimsPreferredUsername(); !ok {
v := authrequest.DefaultClaimsPreferredUsername
arc.mutation.SetClaimsPreferredUsername(v)
}
if _, ok := arc.mutation.CodeChallenge(); !ok {
v := authrequest.DefaultCodeChallenge
arc.mutation.SetCodeChallenge(v)
}
if _, ok := arc.mutation.CodeChallengeMethod(); !ok {
v := authrequest.DefaultCodeChallengeMethod
arc.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 {
return &ValidationError{Name: "client_id", err: errors.New("db: missing required field \"client_id\"")}
}
if _, ok := arc.mutation.RedirectURI(); !ok {
return &ValidationError{Name: "redirect_uri", err: errors.New("db: missing required field \"redirect_uri\"")}
}
if _, ok := arc.mutation.Nonce(); !ok {
return &ValidationError{Name: "nonce", err: errors.New("db: missing required field \"nonce\"")}
}
if _, ok := arc.mutation.State(); !ok {
return &ValidationError{Name: "state", err: errors.New("db: missing required field \"state\"")}
}
if _, ok := arc.mutation.ForceApprovalPrompt(); !ok {
return &ValidationError{Name: "force_approval_prompt", err: errors.New("db: missing required field \"force_approval_prompt\"")}
}
if _, ok := arc.mutation.LoggedIn(); !ok {
return &ValidationError{Name: "logged_in", err: errors.New("db: missing required field \"logged_in\"")}
}
if _, ok := arc.mutation.ClaimsUserID(); !ok {
return &ValidationError{Name: "claims_user_id", err: errors.New("db: missing required field \"claims_user_id\"")}
}
if _, ok := arc.mutation.ClaimsUsername(); !ok {
return &ValidationError{Name: "claims_username", err: errors.New("db: missing required field \"claims_username\"")}
}
if _, ok := arc.mutation.ClaimsEmail(); !ok {
return &ValidationError{Name: "claims_email", err: errors.New("db: missing required field \"claims_email\"")}
}
if _, ok := arc.mutation.ClaimsEmailVerified(); !ok {
return &ValidationError{Name: "claims_email_verified", err: errors.New("db: missing required field \"claims_email_verified\"")}
}
if _, ok := arc.mutation.ClaimsPreferredUsername(); !ok {
return &ValidationError{Name: "claims_preferred_username", err: errors.New("db: missing required field \"claims_preferred_username\"")}
}
if _, ok := arc.mutation.ConnectorID(); !ok {
return &ValidationError{Name: "connector_id", err: errors.New("db: missing required field \"connector_id\"")}
}
if _, ok := arc.mutation.Expiry(); !ok {
return &ValidationError{Name: "expiry", err: errors.New("db: missing required field \"expiry\"")}
}
if _, ok := arc.mutation.CodeChallenge(); !ok {
return &ValidationError{Name: "code_challenge", err: errors.New("db: missing required field \"code_challenge\"")}
}
if _, ok := arc.mutation.CodeChallengeMethod(); !ok {
return &ValidationError{Name: "code_challenge_method", err: errors.New("db: missing required field \"code_challenge_method\"")}
}
if v, ok := arc.mutation.ID(); ok {
if err := authrequest.IDValidator(v); err != nil {
return &ValidationError{Name: "id", err: fmt.Errorf("db: validator failed for field \"id\": %w", err)}
}
}
return nil
}
func (arc *AuthRequestCreate) sqlSave(ctx context.Context) (*AuthRequest, error) {
_node, _spec := arc.createSpec()
if err := sqlgraph.CreateNode(ctx, arc.driver, _spec); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return nil, err
}
return _node, nil
}
func (arc *AuthRequestCreate) createSpec() (*AuthRequest, *sqlgraph.CreateSpec) {
var (
_node = &AuthRequest{config: arc.config}
_spec = &sqlgraph.CreateSpec{
Table: authrequest.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: authrequest.FieldID,
},
}
)
if id, ok := arc.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = id
}
if value, ok := arc.mutation.ClientID(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldClientID,
})
_node.ClientID = value
}
if value, ok := arc.mutation.Scopes(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: authrequest.FieldScopes,
})
_node.Scopes = value
}
if value, ok := arc.mutation.ResponseTypes(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: authrequest.FieldResponseTypes,
})
_node.ResponseTypes = value
}
if value, ok := arc.mutation.RedirectURI(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldRedirectURI,
})
_node.RedirectURI = value
}
if value, ok := arc.mutation.Nonce(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldNonce,
})
_node.Nonce = value
}
if value, ok := arc.mutation.State(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldState,
})
_node.State = value
}
if value, ok := arc.mutation.ForceApprovalPrompt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: authrequest.FieldForceApprovalPrompt,
})
_node.ForceApprovalPrompt = value
}
if value, ok := arc.mutation.LoggedIn(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: authrequest.FieldLoggedIn,
})
_node.LoggedIn = value
}
if value, ok := arc.mutation.ClaimsUserID(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldClaimsUserID,
})
_node.ClaimsUserID = value
}
if value, ok := arc.mutation.ClaimsUsername(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldClaimsUsername,
})
_node.ClaimsUsername = value
}
if value, ok := arc.mutation.ClaimsEmail(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldClaimsEmail,
})
_node.ClaimsEmail = value
}
if value, ok := arc.mutation.ClaimsEmailVerified(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: authrequest.FieldClaimsEmailVerified,
})
_node.ClaimsEmailVerified = value
}
if value, ok := arc.mutation.ClaimsGroups(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: authrequest.FieldClaimsGroups,
})
_node.ClaimsGroups = value
}
if value, ok := arc.mutation.ClaimsPreferredUsername(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldClaimsPreferredUsername,
})
_node.ClaimsPreferredUsername = value
}
if value, ok := arc.mutation.ConnectorID(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldConnectorID,
})
_node.ConnectorID = value
}
if value, ok := arc.mutation.ConnectorData(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: authrequest.FieldConnectorData,
})
_node.ConnectorData = &value
}
if value, ok := arc.mutation.Expiry(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: authrequest.FieldExpiry,
})
_node.Expiry = value
}
if value, ok := arc.mutation.CodeChallenge(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldCodeChallenge,
})
_node.CodeChallenge = value
}
if value, ok := arc.mutation.CodeChallengeMethod(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldCodeChallengeMethod,
})
_node.CodeChallengeMethod = value
}
return _node, _spec
}
// AuthRequestCreateBulk is the builder for creating many AuthRequest entities in bulk.
type AuthRequestCreateBulk struct {
config
builders []*AuthRequestCreate
}
// Save creates the AuthRequest entities in the database.
func (arcb *AuthRequestCreateBulk) Save(ctx context.Context) ([]*AuthRequest, error) {
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(i int, root context.Context) {
builder := arcb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*AuthRequestMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
nodes[i], specs[i] = builder.createSpec()
var err error
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, arcb.builders[i+1].mutation)
} else {
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, arcb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
}
}
mutation.done = true
if err != nil {
return nil, err
}
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, arcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (arcb *AuthRequestCreateBulk) SaveX(ctx context.Context) []*AuthRequest {
v, err := arcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}

View file

@ -0,0 +1,108 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/authrequest"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// AuthRequestDelete is the builder for deleting a AuthRequest entity.
type AuthRequestDelete struct {
config
hooks []Hook
mutation *AuthRequestMutation
}
// Where adds a new predicate to the AuthRequestDelete builder.
func (ard *AuthRequestDelete) Where(ps ...predicate.AuthRequest) *AuthRequestDelete {
ard.mutation.predicates = append(ard.mutation.predicates, ps...)
return ard
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (ard *AuthRequestDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(ard.hooks) == 0 {
affected, err = ard.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*AuthRequestMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
ard.mutation = mutation
affected, err = ard.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(ard.hooks) - 1; i >= 0; i-- {
mut = ard.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, ard.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (ard *AuthRequestDelete) ExecX(ctx context.Context) int {
n, err := ard.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (ard *AuthRequestDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: authrequest.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: authrequest.FieldID,
},
},
}
if ps := ard.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return sqlgraph.DeleteNodes(ctx, ard.driver, _spec)
}
// AuthRequestDeleteOne is the builder for deleting a single AuthRequest entity.
type AuthRequestDeleteOne struct {
ard *AuthRequestDelete
}
// Exec executes the deletion query.
func (ardo *AuthRequestDeleteOne) Exec(ctx context.Context) error {
n, err := ardo.ard.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{authrequest.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (ardo *AuthRequestDeleteOne) ExecX(ctx context.Context) {
ardo.ard.ExecX(ctx)
}

View file

@ -0,0 +1,906 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"errors"
"fmt"
"math"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/authrequest"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// AuthRequestQuery is the builder for querying AuthRequest entities.
type AuthRequestQuery struct {
config
limit *int
offset *int
unique *bool
order []OrderFunc
fields []string
predicates []predicate.AuthRequest
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// 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
}
// Limit adds a limit step to the query.
func (arq *AuthRequestQuery) Limit(limit int) *AuthRequestQuery {
arq.limit = &limit
return arq
}
// Offset adds an offset step to the query.
func (arq *AuthRequestQuery) Offset(offset int) *AuthRequestQuery {
arq.offset = &offset
return arq
}
// 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.unique = &unique
return arq
}
// Order adds an order step to the query.
func (arq *AuthRequestQuery) Order(o ...OrderFunc) *AuthRequestQuery {
arq.order = append(arq.order, o...)
return arq
}
// 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(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{authrequest.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (arq *AuthRequestQuery) FirstX(ctx context.Context) *AuthRequest {
node, err := arq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// 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) {
var ids []string
if ids, err = arq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{authrequest.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (arq *AuthRequestQuery) FirstIDX(ctx context.Context) string {
id, err := arq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single AuthRequest entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when exactly one AuthRequest entity is not 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(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{authrequest.Label}
default:
return nil, &NotSingularError{authrequest.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (arq *AuthRequestQuery) OnlyX(ctx context.Context) *AuthRequest {
node, err := arq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only AuthRequest ID in the query.
// Returns a *NotSingularError when exactly one AuthRequest ID is not found.
// Returns a *NotFoundError when no entities are found.
func (arq *AuthRequestQuery) OnlyID(ctx context.Context) (id string, err error) {
var ids []string
if ids, err = arq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{authrequest.Label}
default:
err = &NotSingularError{authrequest.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (arq *AuthRequestQuery) OnlyIDX(ctx context.Context) string {
id, err := arq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of AuthRequests.
func (arq *AuthRequestQuery) All(ctx context.Context) ([]*AuthRequest, error) {
if err := arq.prepareQuery(ctx); err != nil {
return nil, err
}
return arq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (arq *AuthRequestQuery) AllX(ctx context.Context) []*AuthRequest {
nodes, err := arq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of AuthRequest IDs.
func (arq *AuthRequestQuery) IDs(ctx context.Context) ([]string, error) {
var ids []string
if err := arq.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)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (arq *AuthRequestQuery) Count(ctx context.Context) (int, error) {
if err := arq.prepareQuery(ctx); err != nil {
return 0, err
}
return arq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (arq *AuthRequestQuery) CountX(ctx context.Context) int {
count, err := arq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (arq *AuthRequestQuery) Exist(ctx context.Context) (bool, error) {
if err := arq.prepareQuery(ctx); err != nil {
return false, err
}
return arq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (arq *AuthRequestQuery) ExistX(ctx context.Context) bool {
exist, err := arq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// 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 {
return nil
}
return &AuthRequestQuery{
config: arq.config,
limit: arq.limit,
offset: arq.offset,
order: append([]OrderFunc{}, arq.order...),
predicates: append([]predicate.AuthRequest{}, arq.predicates...),
// clone intermediate query.
sql: arq.sql.Clone(),
path: arq.path,
}
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// ClientID string `json:"client_id,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.AuthRequest.Query().
// GroupBy(authrequest.FieldClientID).
// Aggregate(db.Count()).
// Scan(ctx, &v)
//
func (arq *AuthRequestQuery) GroupBy(field string, fields ...string) *AuthRequestGroupBy {
group := &AuthRequestGroupBy{config: arq.config}
group.fields = append([]string{field}, fields...)
group.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := arq.prepareQuery(ctx); err != nil {
return nil, err
}
return arq.sqlQuery(ctx), nil
}
return group
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// ClientID string `json:"client_id,omitempty"`
// }
//
// client.AuthRequest.Query().
// Select(authrequest.FieldClientID).
// Scan(ctx, &v)
//
func (arq *AuthRequestQuery) Select(field string, fields ...string) *AuthRequestSelect {
arq.fields = append([]string{field}, fields...)
return &AuthRequestSelect{AuthRequestQuery: arq}
}
func (arq *AuthRequestQuery) prepareQuery(ctx context.Context) error {
for _, f := range arq.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 err != nil {
return err
}
arq.sql = prev
}
return nil
}
func (arq *AuthRequestQuery) sqlAll(ctx context.Context) ([]*AuthRequest, error) {
var (
nodes = []*AuthRequest{}
_spec = arq.querySpec()
)
_spec.ScanValues = func(columns []string) ([]interface{}, error) {
node := &AuthRequest{config: arq.config}
nodes = append(nodes, node)
return node.scanValues(columns)
}
_spec.Assign = func(columns []string, values []interface{}) error {
if len(nodes) == 0 {
return fmt.Errorf("db: Assign called without calling ScanValues")
}
node := nodes[len(nodes)-1]
return node.assignValues(columns, values)
}
if err := sqlgraph.QueryNodes(ctx, arq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (arq *AuthRequestQuery) sqlCount(ctx context.Context) (int, error) {
_spec := arq.querySpec()
return sqlgraph.CountNodes(ctx, arq.driver, _spec)
}
func (arq *AuthRequestQuery) sqlExist(ctx context.Context) (bool, error) {
n, err := arq.sqlCount(ctx)
if err != nil {
return false, fmt.Errorf("db: check existence: %w", err)
}
return n > 0, nil
}
func (arq *AuthRequestQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: authrequest.Table,
Columns: authrequest.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: authrequest.FieldID,
},
},
From: arq.sql,
Unique: true,
}
if unique := arq.unique; unique != nil {
_spec.Unique = *unique
}
if fields := arq.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 {
if fields[i] != authrequest.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := arq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := arq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := arq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := arq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (arq *AuthRequestQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(arq.driver.Dialect())
t1 := builder.Table(authrequest.Table)
selector := builder.Select(t1.Columns(authrequest.Columns...)...).From(t1)
if arq.sql != nil {
selector = arq.sql
selector.Select(selector.Columns(authrequest.Columns...)...)
}
for _, p := range arq.predicates {
p(selector)
}
for _, p := range arq.order {
p(selector)
}
if offset := arq.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.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// AuthRequestGroupBy is the group-by builder for AuthRequest entities.
type AuthRequestGroupBy struct {
config
fields []string
fns []AggregateFunc
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Aggregate adds the given aggregation functions to the group-by query.
func (argb *AuthRequestGroupBy) Aggregate(fns ...AggregateFunc) *AuthRequestGroupBy {
argb.fns = append(argb.fns, fns...)
return argb
}
// Scan applies the group-by query and scans the result into the given value.
func (argb *AuthRequestGroupBy) Scan(ctx context.Context, v interface{}) error {
query, err := argb.path(ctx)
if err != nil {
return err
}
argb.sql = query
return argb.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (argb *AuthRequestGroupBy) ScanX(ctx context.Context, v interface{}) {
if err := argb.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from group-by.
// It is only allowed when executing a group-by query with one field.
func (argb *AuthRequestGroupBy) Strings(ctx context.Context) ([]string, error) {
if len(argb.fields) > 1 {
return nil, errors.New("db: AuthRequestGroupBy.Strings is not achievable when grouping more than 1 field")
}
var v []string
if err := argb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (argb *AuthRequestGroupBy) StringsX(ctx context.Context) []string {
v, err := argb.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (argb *AuthRequestGroupBy) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = argb.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{authrequest.Label}
default:
err = fmt.Errorf("db: AuthRequestGroupBy.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (argb *AuthRequestGroupBy) StringX(ctx context.Context) string {
v, err := argb.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from group-by.
// It is only allowed when executing a group-by query with one field.
func (argb *AuthRequestGroupBy) Ints(ctx context.Context) ([]int, error) {
if len(argb.fields) > 1 {
return nil, errors.New("db: AuthRequestGroupBy.Ints is not achievable when grouping more than 1 field")
}
var v []int
if err := argb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (argb *AuthRequestGroupBy) IntsX(ctx context.Context) []int {
v, err := argb.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (argb *AuthRequestGroupBy) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = argb.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{authrequest.Label}
default:
err = fmt.Errorf("db: AuthRequestGroupBy.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (argb *AuthRequestGroupBy) IntX(ctx context.Context) int {
v, err := argb.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from group-by.
// It is only allowed when executing a group-by query with one field.
func (argb *AuthRequestGroupBy) Float64s(ctx context.Context) ([]float64, error) {
if len(argb.fields) > 1 {
return nil, errors.New("db: AuthRequestGroupBy.Float64s is not achievable when grouping more than 1 field")
}
var v []float64
if err := argb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (argb *AuthRequestGroupBy) Float64sX(ctx context.Context) []float64 {
v, err := argb.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (argb *AuthRequestGroupBy) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = argb.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{authrequest.Label}
default:
err = fmt.Errorf("db: AuthRequestGroupBy.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (argb *AuthRequestGroupBy) Float64X(ctx context.Context) float64 {
v, err := argb.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from group-by.
// It is only allowed when executing a group-by query with one field.
func (argb *AuthRequestGroupBy) Bools(ctx context.Context) ([]bool, error) {
if len(argb.fields) > 1 {
return nil, errors.New("db: AuthRequestGroupBy.Bools is not achievable when grouping more than 1 field")
}
var v []bool
if err := argb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (argb *AuthRequestGroupBy) BoolsX(ctx context.Context) []bool {
v, err := argb.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (argb *AuthRequestGroupBy) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = argb.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{authrequest.Label}
default:
err = fmt.Errorf("db: AuthRequestGroupBy.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (argb *AuthRequestGroupBy) BoolX(ctx context.Context) bool {
v, err := argb.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
func (argb *AuthRequestGroupBy) sqlScan(ctx context.Context, v interface{}) error {
for _, f := range argb.fields {
if !authrequest.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := argb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := argb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (argb *AuthRequestGroupBy) sqlQuery() *sql.Selector {
selector := argb.sql
columns := make([]string, 0, len(argb.fields)+len(argb.fns))
columns = append(columns, argb.fields...)
for _, fn := range argb.fns {
columns = append(columns, fn(selector))
}
return selector.Select(columns...).GroupBy(argb.fields...)
}
// AuthRequestSelect is the builder for selecting fields of AuthRequest entities.
type AuthRequestSelect struct {
*AuthRequestQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
}
// Scan applies the selector query and scans the result into the given value.
func (ars *AuthRequestSelect) Scan(ctx context.Context, v interface{}) error {
if err := ars.prepareQuery(ctx); err != nil {
return err
}
ars.sql = ars.AuthRequestQuery.sqlQuery(ctx)
return ars.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (ars *AuthRequestSelect) ScanX(ctx context.Context, v interface{}) {
if err := ars.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from a selector. It is only allowed when selecting one field.
func (ars *AuthRequestSelect) Strings(ctx context.Context) ([]string, error) {
if len(ars.fields) > 1 {
return nil, errors.New("db: AuthRequestSelect.Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := ars.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (ars *AuthRequestSelect) StringsX(ctx context.Context) []string {
v, err := ars.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a selector. It is only allowed when selecting one field.
func (ars *AuthRequestSelect) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = ars.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{authrequest.Label}
default:
err = fmt.Errorf("db: AuthRequestSelect.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (ars *AuthRequestSelect) StringX(ctx context.Context) string {
v, err := ars.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from a selector. It is only allowed when selecting one field.
func (ars *AuthRequestSelect) Ints(ctx context.Context) ([]int, error) {
if len(ars.fields) > 1 {
return nil, errors.New("db: AuthRequestSelect.Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := ars.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (ars *AuthRequestSelect) IntsX(ctx context.Context) []int {
v, err := ars.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a selector. It is only allowed when selecting one field.
func (ars *AuthRequestSelect) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = ars.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{authrequest.Label}
default:
err = fmt.Errorf("db: AuthRequestSelect.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (ars *AuthRequestSelect) IntX(ctx context.Context) int {
v, err := ars.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
func (ars *AuthRequestSelect) Float64s(ctx context.Context) ([]float64, error) {
if len(ars.fields) > 1 {
return nil, errors.New("db: AuthRequestSelect.Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := ars.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (ars *AuthRequestSelect) Float64sX(ctx context.Context) []float64 {
v, err := ars.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
func (ars *AuthRequestSelect) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = ars.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{authrequest.Label}
default:
err = fmt.Errorf("db: AuthRequestSelect.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (ars *AuthRequestSelect) Float64X(ctx context.Context) float64 {
v, err := ars.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from a selector. It is only allowed when selecting one field.
func (ars *AuthRequestSelect) Bools(ctx context.Context) ([]bool, error) {
if len(ars.fields) > 1 {
return nil, errors.New("db: AuthRequestSelect.Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := ars.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (ars *AuthRequestSelect) BoolsX(ctx context.Context) []bool {
v, err := ars.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a selector. It is only allowed when selecting one field.
func (ars *AuthRequestSelect) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = ars.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{authrequest.Label}
default:
err = fmt.Errorf("db: AuthRequestSelect.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (ars *AuthRequestSelect) BoolX(ctx context.Context) bool {
v, err := ars.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
func (ars *AuthRequestSelect) sqlScan(ctx context.Context, v interface{}) error {
rows := &sql.Rows{}
query, args := ars.sqlQuery().Query()
if err := ars.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (ars *AuthRequestSelect) sqlQuery() sql.Querier {
selector := ars.sql
selector.Select(selector.Columns(ars.fields...)...)
return selector
}

View file

@ -0,0 +1,871 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"fmt"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/authrequest"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// AuthRequestUpdate is the builder for updating AuthRequest entities.
type AuthRequestUpdate struct {
config
hooks []Hook
mutation *AuthRequestMutation
}
// Where adds a new predicate for the AuthRequestUpdate builder.
func (aru *AuthRequestUpdate) Where(ps ...predicate.AuthRequest) *AuthRequestUpdate {
aru.mutation.predicates = append(aru.mutation.predicates, ps...)
return aru
}
// SetClientID sets the "client_id" field.
func (aru *AuthRequestUpdate) SetClientID(s string) *AuthRequestUpdate {
aru.mutation.SetClientID(s)
return aru
}
// SetScopes sets the "scopes" field.
func (aru *AuthRequestUpdate) SetScopes(s []string) *AuthRequestUpdate {
aru.mutation.SetScopes(s)
return aru
}
// ClearScopes clears the value of the "scopes" field.
func (aru *AuthRequestUpdate) ClearScopes() *AuthRequestUpdate {
aru.mutation.ClearScopes()
return aru
}
// SetResponseTypes sets the "response_types" field.
func (aru *AuthRequestUpdate) SetResponseTypes(s []string) *AuthRequestUpdate {
aru.mutation.SetResponseTypes(s)
return aru
}
// ClearResponseTypes clears the value of the "response_types" field.
func (aru *AuthRequestUpdate) ClearResponseTypes() *AuthRequestUpdate {
aru.mutation.ClearResponseTypes()
return aru
}
// SetRedirectURI sets the "redirect_uri" field.
func (aru *AuthRequestUpdate) SetRedirectURI(s string) *AuthRequestUpdate {
aru.mutation.SetRedirectURI(s)
return aru
}
// SetNonce sets the "nonce" field.
func (aru *AuthRequestUpdate) SetNonce(s string) *AuthRequestUpdate {
aru.mutation.SetNonce(s)
return aru
}
// SetState sets the "state" field.
func (aru *AuthRequestUpdate) SetState(s string) *AuthRequestUpdate {
aru.mutation.SetState(s)
return aru
}
// SetForceApprovalPrompt sets the "force_approval_prompt" field.
func (aru *AuthRequestUpdate) SetForceApprovalPrompt(b bool) *AuthRequestUpdate {
aru.mutation.SetForceApprovalPrompt(b)
return aru
}
// SetLoggedIn sets the "logged_in" field.
func (aru *AuthRequestUpdate) SetLoggedIn(b bool) *AuthRequestUpdate {
aru.mutation.SetLoggedIn(b)
return aru
}
// SetClaimsUserID sets the "claims_user_id" field.
func (aru *AuthRequestUpdate) SetClaimsUserID(s string) *AuthRequestUpdate {
aru.mutation.SetClaimsUserID(s)
return aru
}
// SetClaimsUsername sets the "claims_username" field.
func (aru *AuthRequestUpdate) SetClaimsUsername(s string) *AuthRequestUpdate {
aru.mutation.SetClaimsUsername(s)
return aru
}
// SetClaimsEmail sets the "claims_email" field.
func (aru *AuthRequestUpdate) SetClaimsEmail(s string) *AuthRequestUpdate {
aru.mutation.SetClaimsEmail(s)
return aru
}
// SetClaimsEmailVerified sets the "claims_email_verified" field.
func (aru *AuthRequestUpdate) SetClaimsEmailVerified(b bool) *AuthRequestUpdate {
aru.mutation.SetClaimsEmailVerified(b)
return aru
}
// SetClaimsGroups sets the "claims_groups" field.
func (aru *AuthRequestUpdate) SetClaimsGroups(s []string) *AuthRequestUpdate {
aru.mutation.SetClaimsGroups(s)
return aru
}
// ClearClaimsGroups clears the value of the "claims_groups" field.
func (aru *AuthRequestUpdate) ClearClaimsGroups() *AuthRequestUpdate {
aru.mutation.ClearClaimsGroups()
return aru
}
// SetClaimsPreferredUsername sets the "claims_preferred_username" field.
func (aru *AuthRequestUpdate) SetClaimsPreferredUsername(s string) *AuthRequestUpdate {
aru.mutation.SetClaimsPreferredUsername(s)
return aru
}
// 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)
}
return aru
}
// SetConnectorID sets the "connector_id" field.
func (aru *AuthRequestUpdate) SetConnectorID(s string) *AuthRequestUpdate {
aru.mutation.SetConnectorID(s)
return aru
}
// SetConnectorData sets the "connector_data" field.
func (aru *AuthRequestUpdate) SetConnectorData(b []byte) *AuthRequestUpdate {
aru.mutation.SetConnectorData(b)
return aru
}
// ClearConnectorData clears the value of the "connector_data" field.
func (aru *AuthRequestUpdate) ClearConnectorData() *AuthRequestUpdate {
aru.mutation.ClearConnectorData()
return aru
}
// SetExpiry sets the "expiry" field.
func (aru *AuthRequestUpdate) SetExpiry(t time.Time) *AuthRequestUpdate {
aru.mutation.SetExpiry(t)
return aru
}
// SetCodeChallenge sets the "code_challenge" field.
func (aru *AuthRequestUpdate) SetCodeChallenge(s string) *AuthRequestUpdate {
aru.mutation.SetCodeChallenge(s)
return aru
}
// 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)
}
return aru
}
// SetCodeChallengeMethod sets the "code_challenge_method" field.
func (aru *AuthRequestUpdate) SetCodeChallengeMethod(s string) *AuthRequestUpdate {
aru.mutation.SetCodeChallengeMethod(s)
return aru
}
// 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)
}
return aru
}
// Mutation returns the AuthRequestMutation object of the builder.
func (aru *AuthRequestUpdate) Mutation() *AuthRequestMutation {
return aru.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) {
var (
err error
affected int
)
if len(aru.hooks) == 0 {
affected, err = aru.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*AuthRequestMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
aru.mutation = mutation
affected, err = aru.sqlSave(ctx)
mutation.done = true
return affected, err
})
for i := len(aru.hooks) - 1; i >= 0; i-- {
mut = aru.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, aru.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// SaveX is like Save, but panics if an error occurs.
func (aru *AuthRequestUpdate) SaveX(ctx context.Context) int {
affected, err := aru.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (aru *AuthRequestUpdate) Exec(ctx context.Context) error {
_, err := aru.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 {
panic(err)
}
}
func (aru *AuthRequestUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: authrequest.Table,
Columns: authrequest.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: authrequest.FieldID,
},
},
}
if ps := aru.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 {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldClientID,
})
}
if value, ok := aru.mutation.Scopes(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: authrequest.FieldScopes,
})
}
if aru.mutation.ScopesCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Column: authrequest.FieldScopes,
})
}
if value, ok := aru.mutation.ResponseTypes(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: authrequest.FieldResponseTypes,
})
}
if aru.mutation.ResponseTypesCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Column: authrequest.FieldResponseTypes,
})
}
if value, ok := aru.mutation.RedirectURI(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldRedirectURI,
})
}
if value, ok := aru.mutation.Nonce(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldNonce,
})
}
if value, ok := aru.mutation.State(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldState,
})
}
if value, ok := aru.mutation.ForceApprovalPrompt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: authrequest.FieldForceApprovalPrompt,
})
}
if value, ok := aru.mutation.LoggedIn(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: authrequest.FieldLoggedIn,
})
}
if value, ok := aru.mutation.ClaimsUserID(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldClaimsUserID,
})
}
if value, ok := aru.mutation.ClaimsUsername(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldClaimsUsername,
})
}
if value, ok := aru.mutation.ClaimsEmail(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldClaimsEmail,
})
}
if value, ok := aru.mutation.ClaimsEmailVerified(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: authrequest.FieldClaimsEmailVerified,
})
}
if value, ok := aru.mutation.ClaimsGroups(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: authrequest.FieldClaimsGroups,
})
}
if aru.mutation.ClaimsGroupsCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Column: authrequest.FieldClaimsGroups,
})
}
if value, ok := aru.mutation.ClaimsPreferredUsername(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldClaimsPreferredUsername,
})
}
if value, ok := aru.mutation.ConnectorID(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldConnectorID,
})
}
if value, ok := aru.mutation.ConnectorData(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: authrequest.FieldConnectorData,
})
}
if aru.mutation.ConnectorDataCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Column: authrequest.FieldConnectorData,
})
}
if value, ok := aru.mutation.Expiry(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: authrequest.FieldExpiry,
})
}
if value, ok := aru.mutation.CodeChallenge(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldCodeChallenge,
})
}
if value, ok := aru.mutation.CodeChallengeMethod(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldCodeChallengeMethod,
})
}
if n, err = sqlgraph.UpdateNodes(ctx, aru.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{authrequest.Label}
} else if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return 0, err
}
return n, nil
}
// AuthRequestUpdateOne is the builder for updating a single AuthRequest entity.
type AuthRequestUpdateOne struct {
config
fields []string
hooks []Hook
mutation *AuthRequestMutation
}
// SetClientID sets the "client_id" field.
func (aruo *AuthRequestUpdateOne) SetClientID(s string) *AuthRequestUpdateOne {
aruo.mutation.SetClientID(s)
return aruo
}
// SetScopes sets the "scopes" field.
func (aruo *AuthRequestUpdateOne) SetScopes(s []string) *AuthRequestUpdateOne {
aruo.mutation.SetScopes(s)
return aruo
}
// ClearScopes clears the value of the "scopes" field.
func (aruo *AuthRequestUpdateOne) ClearScopes() *AuthRequestUpdateOne {
aruo.mutation.ClearScopes()
return aruo
}
// SetResponseTypes sets the "response_types" field.
func (aruo *AuthRequestUpdateOne) SetResponseTypes(s []string) *AuthRequestUpdateOne {
aruo.mutation.SetResponseTypes(s)
return aruo
}
// ClearResponseTypes clears the value of the "response_types" field.
func (aruo *AuthRequestUpdateOne) ClearResponseTypes() *AuthRequestUpdateOne {
aruo.mutation.ClearResponseTypes()
return aruo
}
// SetRedirectURI sets the "redirect_uri" field.
func (aruo *AuthRequestUpdateOne) SetRedirectURI(s string) *AuthRequestUpdateOne {
aruo.mutation.SetRedirectURI(s)
return aruo
}
// SetNonce sets the "nonce" field.
func (aruo *AuthRequestUpdateOne) SetNonce(s string) *AuthRequestUpdateOne {
aruo.mutation.SetNonce(s)
return aruo
}
// SetState sets the "state" field.
func (aruo *AuthRequestUpdateOne) SetState(s string) *AuthRequestUpdateOne {
aruo.mutation.SetState(s)
return aruo
}
// SetForceApprovalPrompt sets the "force_approval_prompt" field.
func (aruo *AuthRequestUpdateOne) SetForceApprovalPrompt(b bool) *AuthRequestUpdateOne {
aruo.mutation.SetForceApprovalPrompt(b)
return aruo
}
// SetLoggedIn sets the "logged_in" field.
func (aruo *AuthRequestUpdateOne) SetLoggedIn(b bool) *AuthRequestUpdateOne {
aruo.mutation.SetLoggedIn(b)
return aruo
}
// SetClaimsUserID sets the "claims_user_id" field.
func (aruo *AuthRequestUpdateOne) SetClaimsUserID(s string) *AuthRequestUpdateOne {
aruo.mutation.SetClaimsUserID(s)
return aruo
}
// SetClaimsUsername sets the "claims_username" field.
func (aruo *AuthRequestUpdateOne) SetClaimsUsername(s string) *AuthRequestUpdateOne {
aruo.mutation.SetClaimsUsername(s)
return aruo
}
// SetClaimsEmail sets the "claims_email" field.
func (aruo *AuthRequestUpdateOne) SetClaimsEmail(s string) *AuthRequestUpdateOne {
aruo.mutation.SetClaimsEmail(s)
return aruo
}
// SetClaimsEmailVerified sets the "claims_email_verified" field.
func (aruo *AuthRequestUpdateOne) SetClaimsEmailVerified(b bool) *AuthRequestUpdateOne {
aruo.mutation.SetClaimsEmailVerified(b)
return aruo
}
// SetClaimsGroups sets the "claims_groups" field.
func (aruo *AuthRequestUpdateOne) SetClaimsGroups(s []string) *AuthRequestUpdateOne {
aruo.mutation.SetClaimsGroups(s)
return aruo
}
// ClearClaimsGroups clears the value of the "claims_groups" field.
func (aruo *AuthRequestUpdateOne) ClearClaimsGroups() *AuthRequestUpdateOne {
aruo.mutation.ClearClaimsGroups()
return aruo
}
// SetClaimsPreferredUsername sets the "claims_preferred_username" field.
func (aruo *AuthRequestUpdateOne) SetClaimsPreferredUsername(s string) *AuthRequestUpdateOne {
aruo.mutation.SetClaimsPreferredUsername(s)
return aruo
}
// 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)
}
return aruo
}
// SetConnectorID sets the "connector_id" field.
func (aruo *AuthRequestUpdateOne) SetConnectorID(s string) *AuthRequestUpdateOne {
aruo.mutation.SetConnectorID(s)
return aruo
}
// SetConnectorData sets the "connector_data" field.
func (aruo *AuthRequestUpdateOne) SetConnectorData(b []byte) *AuthRequestUpdateOne {
aruo.mutation.SetConnectorData(b)
return aruo
}
// ClearConnectorData clears the value of the "connector_data" field.
func (aruo *AuthRequestUpdateOne) ClearConnectorData() *AuthRequestUpdateOne {
aruo.mutation.ClearConnectorData()
return aruo
}
// SetExpiry sets the "expiry" field.
func (aruo *AuthRequestUpdateOne) SetExpiry(t time.Time) *AuthRequestUpdateOne {
aruo.mutation.SetExpiry(t)
return aruo
}
// SetCodeChallenge sets the "code_challenge" field.
func (aruo *AuthRequestUpdateOne) SetCodeChallenge(s string) *AuthRequestUpdateOne {
aruo.mutation.SetCodeChallenge(s)
return aruo
}
// 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)
}
return aruo
}
// SetCodeChallengeMethod sets the "code_challenge_method" field.
func (aruo *AuthRequestUpdateOne) SetCodeChallengeMethod(s string) *AuthRequestUpdateOne {
aruo.mutation.SetCodeChallengeMethod(s)
return aruo
}
// 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)
}
return aruo
}
// Mutation returns the AuthRequestMutation object of the builder.
func (aruo *AuthRequestUpdateOne) Mutation() *AuthRequestMutation {
return aruo.mutation
}
// 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
}
// Save executes the query and returns the updated AuthRequest entity.
func (aruo *AuthRequestUpdateOne) Save(ctx context.Context) (*AuthRequest, error) {
var (
err error
node *AuthRequest
)
if len(aruo.hooks) == 0 {
node, err = aruo.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*AuthRequestMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
aruo.mutation = mutation
node, err = aruo.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(aruo.hooks) - 1; i >= 0; i-- {
mut = aruo.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, aruo.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX is like Save, but panics if an error occurs.
func (aruo *AuthRequestUpdateOne) SaveX(ctx context.Context) *AuthRequest {
node, err := aruo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (aruo *AuthRequestUpdateOne) Exec(ctx context.Context) error {
_, err := aruo.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 {
panic(err)
}
}
func (aruo *AuthRequestUpdateOne) sqlSave(ctx context.Context) (_node *AuthRequest, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: authrequest.Table,
Columns: authrequest.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: authrequest.FieldID,
},
},
}
id, ok := aruo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing AuthRequest.ID for update")}
}
_spec.Node.ID.Value = id
if fields := aruo.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 {
if !authrequest.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
}
if f != authrequest.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := aruo.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 {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldClientID,
})
}
if value, ok := aruo.mutation.Scopes(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: authrequest.FieldScopes,
})
}
if aruo.mutation.ScopesCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Column: authrequest.FieldScopes,
})
}
if value, ok := aruo.mutation.ResponseTypes(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: authrequest.FieldResponseTypes,
})
}
if aruo.mutation.ResponseTypesCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Column: authrequest.FieldResponseTypes,
})
}
if value, ok := aruo.mutation.RedirectURI(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldRedirectURI,
})
}
if value, ok := aruo.mutation.Nonce(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldNonce,
})
}
if value, ok := aruo.mutation.State(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldState,
})
}
if value, ok := aruo.mutation.ForceApprovalPrompt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: authrequest.FieldForceApprovalPrompt,
})
}
if value, ok := aruo.mutation.LoggedIn(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: authrequest.FieldLoggedIn,
})
}
if value, ok := aruo.mutation.ClaimsUserID(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldClaimsUserID,
})
}
if value, ok := aruo.mutation.ClaimsUsername(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldClaimsUsername,
})
}
if value, ok := aruo.mutation.ClaimsEmail(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldClaimsEmail,
})
}
if value, ok := aruo.mutation.ClaimsEmailVerified(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: authrequest.FieldClaimsEmailVerified,
})
}
if value, ok := aruo.mutation.ClaimsGroups(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: authrequest.FieldClaimsGroups,
})
}
if aruo.mutation.ClaimsGroupsCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Column: authrequest.FieldClaimsGroups,
})
}
if value, ok := aruo.mutation.ClaimsPreferredUsername(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldClaimsPreferredUsername,
})
}
if value, ok := aruo.mutation.ConnectorID(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldConnectorID,
})
}
if value, ok := aruo.mutation.ConnectorData(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: authrequest.FieldConnectorData,
})
}
if aruo.mutation.ConnectorDataCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Column: authrequest.FieldConnectorData,
})
}
if value, ok := aruo.mutation.Expiry(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: authrequest.FieldExpiry,
})
}
if value, ok := aruo.mutation.CodeChallenge(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldCodeChallenge,
})
}
if value, ok := aruo.mutation.CodeChallengeMethod(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: authrequest.FieldCodeChallengeMethod,
})
}
_node = &AuthRequest{config: aruo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, aruo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{authrequest.Label}
} else if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return nil, err
}
return _node, nil
}

1085
storage/ent/db/client.go Normal file

File diff suppressed because it is too large Load diff

68
storage/ent/db/config.go Normal file
View file

@ -0,0 +1,68 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"entgo.io/ent"
"entgo.io/ent/dialect"
)
// Option function to configure the client.
type Option func(*config)
// Config is the configuration for the client and its builder.
type config struct {
// driver used for executing database requests.
driver dialect.Driver
// debug enable a debug logging.
debug bool
// log used for logging on debug mode.
log func(...interface{})
// hooks to execute on mutations.
hooks *hooks
}
// hooks per client, for fast access.
type hooks struct {
AuthCode []ent.Hook
AuthRequest []ent.Hook
Connector []ent.Hook
DeviceRequest []ent.Hook
DeviceToken []ent.Hook
Keys []ent.Hook
OAuth2Client []ent.Hook
OfflineSession []ent.Hook
Password []ent.Hook
RefreshToken []ent.Hook
}
// Options applies the options on the config object.
func (c *config) options(opts ...Option) {
for _, opt := range opts {
opt(c)
}
if c.debug {
c.driver = dialect.Debug(c.driver, c.log)
}
}
// Debug enables debug logging on the ent.Driver.
func Debug() Option {
return func(c *config) {
c.debug = true
}
}
// Log sets the logging function for debug mode.
func Log(fn func(...interface{})) Option {
return func(c *config) {
c.log = fn
}
}
// Driver configures the client driver.
func Driver(driver dialect.Driver) Option {
return func(c *config) {
c.driver = driver
}
}

129
storage/ent/db/connector.go Normal file
View file

@ -0,0 +1,129 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"fmt"
"strings"
"entgo.io/ent/dialect/sql"
"github.com/dexidp/dex/storage/ent/db/connector"
)
// Connector is the model entity for the Connector schema.
type Connector struct {
config `json:"-"`
// ID of the ent.
ID string `json:"id,omitempty"`
// Type holds the value of the "type" field.
Type string `json:"type,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// ResourceVersion holds the value of the "resource_version" field.
ResourceVersion string `json:"resource_version,omitempty"`
// Config holds the value of the "config" field.
Config []byte `json:"config,omitempty"`
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Connector) scanValues(columns []string) ([]interface{}, error) {
values := make([]interface{}, len(columns))
for i := range columns {
switch columns[i] {
case connector.FieldConfig:
values[i] = new([]byte)
case connector.FieldID, connector.FieldType, connector.FieldName, connector.FieldResourceVersion:
values[i] = new(sql.NullString)
default:
return nil, fmt.Errorf("unexpected column %q for type Connector", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Connector fields.
func (c *Connector) assignValues(columns []string, values []interface{}) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case connector.FieldID:
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
}
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
}
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
}
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
}
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
}
}
}
return nil
}
// 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 (&ConnectorClient{config: c.config}).UpdateOne(c)
}
// 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)
if !ok {
panic("db: Connector is not a transactional entity")
}
c.config.driver = tx.drv
return c
}
// String implements the fmt.Stringer.
func (c *Connector) String() string {
var builder strings.Builder
builder.WriteString("Connector(")
builder.WriteString(fmt.Sprintf("id=%v", c.ID))
builder.WriteString(", type=")
builder.WriteString(c.Type)
builder.WriteString(", name=")
builder.WriteString(c.Name)
builder.WriteString(", resource_version=")
builder.WriteString(c.ResourceVersion)
builder.WriteString(", config=")
builder.WriteString(fmt.Sprintf("%v", c.Config))
builder.WriteByte(')')
return builder.String()
}
// Connectors is a parsable slice of Connector.
type Connectors []*Connector
func (c Connectors) config(cfg config) {
for _i := range c {
c[_i].config = cfg
}
}

View file

@ -0,0 +1,48 @@
// Code generated by entc, DO NOT EDIT.
package connector
const (
// Label holds the string label denoting the connector type in the database.
Label = "connector"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldType holds the string denoting the type field in the database.
FieldType = "type"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// FieldResourceVersion holds the string denoting the resource_version field in the database.
FieldResourceVersion = "resource_version"
// FieldConfig holds the string denoting the config field in the database.
FieldConfig = "config"
// Table holds the table name of the connector in the database.
Table = "connectors"
)
// Columns holds all SQL columns for connector fields.
var Columns = []string{
FieldID,
FieldType,
FieldName,
FieldResourceVersion,
FieldConfig,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// TypeValidator is a validator for the "type" field. It is called by the builders before save.
TypeValidator func(string) error
// NameValidator is a validator for the "name" field. It is called by the builders before save.
NameValidator func(string) error
// IDValidator is a validator for the "id" field. It is called by the builders before save.
IDValidator func(string) error
)

View file

@ -0,0 +1,560 @@
// Code generated by entc, DO NOT EDIT.
package connector
import (
"entgo.io/ent/dialect/sql"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// ID filters vertices based on their ID field.
func ID(id string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldID), id))
})
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.In(s.C(FieldID), v...))
})
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.NotIn(s.C(FieldID), v...))
})
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldID), id))
})
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldID), id))
})
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldID), id))
})
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldID), id))
})
}
// Type applies equality check predicate on the "type" field. It's identical to TypeEQ.
func Type(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldType), v))
})
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldName), v))
})
}
// ResourceVersion applies equality check predicate on the "resource_version" field. It's identical to ResourceVersionEQ.
func ResourceVersion(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldResourceVersion), v))
})
}
// Config applies equality check predicate on the "config" field. It's identical to ConfigEQ.
func Config(v []byte) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldConfig), v))
})
}
// TypeEQ applies the EQ predicate on the "type" field.
func TypeEQ(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldType), v))
})
}
// TypeNEQ applies the NEQ predicate on the "type" field.
func TypeNEQ(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldType), v))
})
}
// TypeIn applies the In predicate on the "type" field.
func TypeIn(vs ...string) predicate.Connector {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Connector(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldType), v...))
})
}
// TypeNotIn applies the NotIn predicate on the "type" field.
func TypeNotIn(vs ...string) predicate.Connector {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Connector(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldType), v...))
})
}
// TypeGT applies the GT predicate on the "type" field.
func TypeGT(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldType), v))
})
}
// TypeGTE applies the GTE predicate on the "type" field.
func TypeGTE(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldType), v))
})
}
// TypeLT applies the LT predicate on the "type" field.
func TypeLT(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldType), v))
})
}
// TypeLTE applies the LTE predicate on the "type" field.
func TypeLTE(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldType), v))
})
}
// TypeContains applies the Contains predicate on the "type" field.
func TypeContains(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldType), v))
})
}
// TypeHasPrefix applies the HasPrefix predicate on the "type" field.
func TypeHasPrefix(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldType), v))
})
}
// TypeHasSuffix applies the HasSuffix predicate on the "type" field.
func TypeHasSuffix(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldType), v))
})
}
// TypeEqualFold applies the EqualFold predicate on the "type" field.
func TypeEqualFold(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldType), v))
})
}
// TypeContainsFold applies the ContainsFold predicate on the "type" field.
func TypeContainsFold(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldType), v))
})
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldName), v))
})
}
// NameNEQ applies the NEQ predicate on the "name" field.
func NameNEQ(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldName), v))
})
}
// NameIn applies the In predicate on the "name" field.
func NameIn(vs ...string) predicate.Connector {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Connector(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldName), v...))
})
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.Connector {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Connector(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldName), v...))
})
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldName), v))
})
}
// NameGTE applies the GTE predicate on the "name" field.
func NameGTE(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldName), v))
})
}
// NameLT applies the LT predicate on the "name" field.
func NameLT(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldName), v))
})
}
// NameLTE applies the LTE predicate on the "name" field.
func NameLTE(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldName), v))
})
}
// NameContains applies the Contains predicate on the "name" field.
func NameContains(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldName), v))
})
}
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
func NameHasPrefix(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldName), v))
})
}
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
func NameHasSuffix(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldName), v))
})
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldName), v))
})
}
// NameContainsFold applies the ContainsFold predicate on the "name" field.
func NameContainsFold(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldName), v))
})
}
// ResourceVersionEQ applies the EQ predicate on the "resource_version" field.
func ResourceVersionEQ(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldResourceVersion), v))
})
}
// ResourceVersionNEQ applies the NEQ predicate on the "resource_version" field.
func ResourceVersionNEQ(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldResourceVersion), v))
})
}
// ResourceVersionIn applies the In predicate on the "resource_version" field.
func ResourceVersionIn(vs ...string) predicate.Connector {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Connector(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldResourceVersion), v...))
})
}
// ResourceVersionNotIn applies the NotIn predicate on the "resource_version" field.
func ResourceVersionNotIn(vs ...string) predicate.Connector {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Connector(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldResourceVersion), v...))
})
}
// ResourceVersionGT applies the GT predicate on the "resource_version" field.
func ResourceVersionGT(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldResourceVersion), v))
})
}
// ResourceVersionGTE applies the GTE predicate on the "resource_version" field.
func ResourceVersionGTE(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldResourceVersion), v))
})
}
// ResourceVersionLT applies the LT predicate on the "resource_version" field.
func ResourceVersionLT(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldResourceVersion), v))
})
}
// ResourceVersionLTE applies the LTE predicate on the "resource_version" field.
func ResourceVersionLTE(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldResourceVersion), v))
})
}
// ResourceVersionContains applies the Contains predicate on the "resource_version" field.
func ResourceVersionContains(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldResourceVersion), v))
})
}
// ResourceVersionHasPrefix applies the HasPrefix predicate on the "resource_version" field.
func ResourceVersionHasPrefix(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldResourceVersion), v))
})
}
// ResourceVersionHasSuffix applies the HasSuffix predicate on the "resource_version" field.
func ResourceVersionHasSuffix(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldResourceVersion), v))
})
}
// ResourceVersionEqualFold applies the EqualFold predicate on the "resource_version" field.
func ResourceVersionEqualFold(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldResourceVersion), v))
})
}
// ResourceVersionContainsFold applies the ContainsFold predicate on the "resource_version" field.
func ResourceVersionContainsFold(v string) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldResourceVersion), v))
})
}
// ConfigEQ applies the EQ predicate on the "config" field.
func ConfigEQ(v []byte) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldConfig), v))
})
}
// ConfigNEQ applies the NEQ predicate on the "config" field.
func ConfigNEQ(v []byte) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldConfig), v))
})
}
// ConfigIn applies the In predicate on the "config" field.
func ConfigIn(vs ...[]byte) predicate.Connector {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Connector(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldConfig), v...))
})
}
// ConfigNotIn applies the NotIn predicate on the "config" field.
func ConfigNotIn(vs ...[]byte) predicate.Connector {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Connector(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldConfig), v...))
})
}
// ConfigGT applies the GT predicate on the "config" field.
func ConfigGT(v []byte) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldConfig), v))
})
}
// ConfigGTE applies the GTE predicate on the "config" field.
func ConfigGTE(v []byte) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldConfig), v))
})
}
// ConfigLT applies the LT predicate on the "config" field.
func ConfigLT(v []byte) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldConfig), v))
})
}
// ConfigLTE applies the LTE predicate on the "config" field.
func ConfigLTE(v []byte) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldConfig), v))
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Connector) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for _, p := range predicates {
p(s1)
}
s.Where(s1.P())
})
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Connector) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for i, p := range predicates {
if i > 0 {
s1.Or()
}
p(s1)
}
s.Where(s1.P())
})
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Connector) predicate.Connector {
return predicate.Connector(func(s *sql.Selector) {
p(s.Not())
})
}

View file

@ -0,0 +1,256 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/connector"
)
// ConnectorCreate is the builder for creating a Connector entity.
type ConnectorCreate struct {
config
mutation *ConnectorMutation
hooks []Hook
}
// SetType sets the "type" field.
func (cc *ConnectorCreate) SetType(s string) *ConnectorCreate {
cc.mutation.SetType(s)
return cc
}
// SetName sets the "name" field.
func (cc *ConnectorCreate) SetName(s string) *ConnectorCreate {
cc.mutation.SetName(s)
return cc
}
// SetResourceVersion sets the "resource_version" field.
func (cc *ConnectorCreate) SetResourceVersion(s string) *ConnectorCreate {
cc.mutation.SetResourceVersion(s)
return cc
}
// SetConfig sets the "config" field.
func (cc *ConnectorCreate) SetConfig(b []byte) *ConnectorCreate {
cc.mutation.SetConfig(b)
return cc
}
// SetID sets the "id" field.
func (cc *ConnectorCreate) SetID(s string) *ConnectorCreate {
cc.mutation.SetID(s)
return cc
}
// Mutation returns the ConnectorMutation object of the builder.
func (cc *ConnectorCreate) Mutation() *ConnectorMutation {
return cc.mutation
}
// Save creates the Connector in the database.
func (cc *ConnectorCreate) Save(ctx context.Context) (*Connector, error) {
var (
err error
node *Connector
)
if len(cc.hooks) == 0 {
if err = cc.check(); err != nil {
return nil, err
}
node, err = cc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*ConnectorMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = cc.check(); err != nil {
return nil, err
}
cc.mutation = mutation
node, err = cc.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(cc.hooks) - 1; i >= 0; i-- {
mut = cc.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, cc.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (cc *ConnectorCreate) SaveX(ctx context.Context) *Connector {
v, err := cc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// check runs all checks and user-defined validators on the builder.
func (cc *ConnectorCreate) check() error {
if _, ok := cc.mutation.GetType(); !ok {
return &ValidationError{Name: "type", err: errors.New("db: missing required field \"type\"")}
}
if v, ok := cc.mutation.GetType(); ok {
if err := connector.TypeValidator(v); err != nil {
return &ValidationError{Name: "type", err: fmt.Errorf("db: validator failed for field \"type\": %w", err)}
}
}
if _, ok := cc.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New("db: missing required field \"name\"")}
}
if v, ok := cc.mutation.Name(); ok {
if err := connector.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf("db: validator failed for field \"name\": %w", err)}
}
}
if _, ok := cc.mutation.ResourceVersion(); !ok {
return &ValidationError{Name: "resource_version", err: errors.New("db: missing required field \"resource_version\"")}
}
if _, ok := cc.mutation.Config(); !ok {
return &ValidationError{Name: "config", err: errors.New("db: missing required field \"config\"")}
}
if v, ok := cc.mutation.ID(); ok {
if err := connector.IDValidator(v); err != nil {
return &ValidationError{Name: "id", err: fmt.Errorf("db: validator failed for field \"id\": %w", err)}
}
}
return nil
}
func (cc *ConnectorCreate) sqlSave(ctx context.Context) (*Connector, error) {
_node, _spec := cc.createSpec()
if err := sqlgraph.CreateNode(ctx, cc.driver, _spec); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return nil, err
}
return _node, nil
}
func (cc *ConnectorCreate) createSpec() (*Connector, *sqlgraph.CreateSpec) {
var (
_node = &Connector{config: cc.config}
_spec = &sqlgraph.CreateSpec{
Table: connector.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: connector.FieldID,
},
}
)
if id, ok := cc.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = id
}
if value, ok := cc.mutation.GetType(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: connector.FieldType,
})
_node.Type = value
}
if value, ok := cc.mutation.Name(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: connector.FieldName,
})
_node.Name = value
}
if value, ok := cc.mutation.ResourceVersion(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: connector.FieldResourceVersion,
})
_node.ResourceVersion = value
}
if value, ok := cc.mutation.Config(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: connector.FieldConfig,
})
_node.Config = value
}
return _node, _spec
}
// ConnectorCreateBulk is the builder for creating many Connector entities in bulk.
type ConnectorCreateBulk struct {
config
builders []*ConnectorCreate
}
// Save creates the Connector entities in the database.
func (ccb *ConnectorCreateBulk) Save(ctx context.Context) ([]*Connector, error) {
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(i int, root context.Context) {
builder := ccb.builders[i]
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*ConnectorMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
nodes[i], specs[i] = builder.createSpec()
var err error
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, ccb.builders[i+1].mutation)
} else {
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, ccb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
}
}
mutation.done = true
if err != nil {
return nil, err
}
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, ccb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (ccb *ConnectorCreateBulk) SaveX(ctx context.Context) []*Connector {
v, err := ccb.Save(ctx)
if err != nil {
panic(err)
}
return v
}

View file

@ -0,0 +1,108 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/connector"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// ConnectorDelete is the builder for deleting a Connector entity.
type ConnectorDelete struct {
config
hooks []Hook
mutation *ConnectorMutation
}
// Where adds a new predicate to the ConnectorDelete builder.
func (cd *ConnectorDelete) Where(ps ...predicate.Connector) *ConnectorDelete {
cd.mutation.predicates = append(cd.mutation.predicates, ps...)
return cd
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (cd *ConnectorDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(cd.hooks) == 0 {
affected, err = cd.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*ConnectorMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
cd.mutation = mutation
affected, err = cd.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(cd.hooks) - 1; i >= 0; i-- {
mut = cd.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, cd.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (cd *ConnectorDelete) ExecX(ctx context.Context) int {
n, err := cd.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (cd *ConnectorDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: connector.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: connector.FieldID,
},
},
}
if ps := cd.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return sqlgraph.DeleteNodes(ctx, cd.driver, _spec)
}
// ConnectorDeleteOne is the builder for deleting a single Connector entity.
type ConnectorDeleteOne struct {
cd *ConnectorDelete
}
// Exec executes the deletion query.
func (cdo *ConnectorDeleteOne) Exec(ctx context.Context) error {
n, err := cdo.cd.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{connector.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (cdo *ConnectorDeleteOne) ExecX(ctx context.Context) {
cdo.cd.ExecX(ctx)
}

View file

@ -0,0 +1,906 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"errors"
"fmt"
"math"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/connector"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// ConnectorQuery is the builder for querying Connector entities.
type ConnectorQuery struct {
config
limit *int
offset *int
unique *bool
order []OrderFunc
fields []string
predicates []predicate.Connector
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// 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
}
// Limit adds a limit step to the query.
func (cq *ConnectorQuery) Limit(limit int) *ConnectorQuery {
cq.limit = &limit
return cq
}
// Offset adds an offset step to the query.
func (cq *ConnectorQuery) Offset(offset int) *ConnectorQuery {
cq.offset = &offset
return cq
}
// Unique configures the query builder to filter duplicate records on query.
// By default, unique is set to true, and can be disabled using this method.
func (cq *ConnectorQuery) Unique(unique bool) *ConnectorQuery {
cq.unique = &unique
return cq
}
// Order adds an order step to the query.
func (cq *ConnectorQuery) Order(o ...OrderFunc) *ConnectorQuery {
cq.order = append(cq.order, o...)
return cq
}
// 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(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{connector.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (cq *ConnectorQuery) FirstX(ctx context.Context) *Connector {
node, err := cq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// 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) {
var ids []string
if ids, err = cq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{connector.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (cq *ConnectorQuery) FirstIDX(ctx context.Context) string {
id, err := cq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Connector entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when exactly one Connector entity is not 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(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{connector.Label}
default:
return nil, &NotSingularError{connector.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (cq *ConnectorQuery) OnlyX(ctx context.Context) *Connector {
node, err := cq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Connector ID in the query.
// Returns a *NotSingularError when exactly one Connector ID is not found.
// Returns a *NotFoundError when no entities are found.
func (cq *ConnectorQuery) OnlyID(ctx context.Context) (id string, err error) {
var ids []string
if ids, err = cq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{connector.Label}
default:
err = &NotSingularError{connector.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (cq *ConnectorQuery) OnlyIDX(ctx context.Context) string {
id, err := cq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Connectors.
func (cq *ConnectorQuery) All(ctx context.Context) ([]*Connector, error) {
if err := cq.prepareQuery(ctx); err != nil {
return nil, err
}
return cq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (cq *ConnectorQuery) AllX(ctx context.Context) []*Connector {
nodes, err := cq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Connector IDs.
func (cq *ConnectorQuery) IDs(ctx context.Context) ([]string, error) {
var ids []string
if err := cq.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)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (cq *ConnectorQuery) Count(ctx context.Context) (int, error) {
if err := cq.prepareQuery(ctx); err != nil {
return 0, err
}
return cq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (cq *ConnectorQuery) CountX(ctx context.Context) int {
count, err := cq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (cq *ConnectorQuery) Exist(ctx context.Context) (bool, error) {
if err := cq.prepareQuery(ctx); err != nil {
return false, err
}
return cq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (cq *ConnectorQuery) ExistX(ctx context.Context) bool {
exist, err := cq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// 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 {
return nil
}
return &ConnectorQuery{
config: cq.config,
limit: cq.limit,
offset: cq.offset,
order: append([]OrderFunc{}, cq.order...),
predicates: append([]predicate.Connector{}, cq.predicates...),
// clone intermediate query.
sql: cq.sql.Clone(),
path: cq.path,
}
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// Type string `json:"type,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Connector.Query().
// GroupBy(connector.FieldType).
// Aggregate(db.Count()).
// Scan(ctx, &v)
//
func (cq *ConnectorQuery) GroupBy(field string, fields ...string) *ConnectorGroupBy {
group := &ConnectorGroupBy{config: cq.config}
group.fields = append([]string{field}, fields...)
group.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := cq.prepareQuery(ctx); err != nil {
return nil, err
}
return cq.sqlQuery(ctx), nil
}
return group
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// Type string `json:"type,omitempty"`
// }
//
// client.Connector.Query().
// Select(connector.FieldType).
// Scan(ctx, &v)
//
func (cq *ConnectorQuery) Select(field string, fields ...string) *ConnectorSelect {
cq.fields = append([]string{field}, fields...)
return &ConnectorSelect{ConnectorQuery: cq}
}
func (cq *ConnectorQuery) prepareQuery(ctx context.Context) error {
for _, f := range cq.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 err != nil {
return err
}
cq.sql = prev
}
return nil
}
func (cq *ConnectorQuery) sqlAll(ctx context.Context) ([]*Connector, error) {
var (
nodes = []*Connector{}
_spec = cq.querySpec()
)
_spec.ScanValues = func(columns []string) ([]interface{}, error) {
node := &Connector{config: cq.config}
nodes = append(nodes, node)
return node.scanValues(columns)
}
_spec.Assign = func(columns []string, values []interface{}) error {
if len(nodes) == 0 {
return fmt.Errorf("db: Assign called without calling ScanValues")
}
node := nodes[len(nodes)-1]
return node.assignValues(columns, values)
}
if err := sqlgraph.QueryNodes(ctx, cq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (cq *ConnectorQuery) sqlCount(ctx context.Context) (int, error) {
_spec := cq.querySpec()
return sqlgraph.CountNodes(ctx, cq.driver, _spec)
}
func (cq *ConnectorQuery) sqlExist(ctx context.Context) (bool, error) {
n, err := cq.sqlCount(ctx)
if err != nil {
return false, fmt.Errorf("db: check existence: %w", err)
}
return n > 0, nil
}
func (cq *ConnectorQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: connector.Table,
Columns: connector.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: connector.FieldID,
},
},
From: cq.sql,
Unique: true,
}
if unique := cq.unique; unique != nil {
_spec.Unique = *unique
}
if fields := cq.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 {
if fields[i] != connector.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := cq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := cq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := cq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := cq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (cq *ConnectorQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(cq.driver.Dialect())
t1 := builder.Table(connector.Table)
selector := builder.Select(t1.Columns(connector.Columns...)...).From(t1)
if cq.sql != nil {
selector = cq.sql
selector.Select(selector.Columns(connector.Columns...)...)
}
for _, p := range cq.predicates {
p(selector)
}
for _, p := range cq.order {
p(selector)
}
if offset := cq.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.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// ConnectorGroupBy is the group-by builder for Connector entities.
type ConnectorGroupBy struct {
config
fields []string
fns []AggregateFunc
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Aggregate adds the given aggregation functions to the group-by query.
func (cgb *ConnectorGroupBy) Aggregate(fns ...AggregateFunc) *ConnectorGroupBy {
cgb.fns = append(cgb.fns, fns...)
return cgb
}
// Scan applies the group-by query and scans the result into the given value.
func (cgb *ConnectorGroupBy) Scan(ctx context.Context, v interface{}) error {
query, err := cgb.path(ctx)
if err != nil {
return err
}
cgb.sql = query
return cgb.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (cgb *ConnectorGroupBy) ScanX(ctx context.Context, v interface{}) {
if err := cgb.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from group-by.
// It is only allowed when executing a group-by query with one field.
func (cgb *ConnectorGroupBy) Strings(ctx context.Context) ([]string, error) {
if len(cgb.fields) > 1 {
return nil, errors.New("db: ConnectorGroupBy.Strings is not achievable when grouping more than 1 field")
}
var v []string
if err := cgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (cgb *ConnectorGroupBy) StringsX(ctx context.Context) []string {
v, err := cgb.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (cgb *ConnectorGroupBy) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = cgb.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{connector.Label}
default:
err = fmt.Errorf("db: ConnectorGroupBy.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (cgb *ConnectorGroupBy) StringX(ctx context.Context) string {
v, err := cgb.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from group-by.
// It is only allowed when executing a group-by query with one field.
func (cgb *ConnectorGroupBy) Ints(ctx context.Context) ([]int, error) {
if len(cgb.fields) > 1 {
return nil, errors.New("db: ConnectorGroupBy.Ints is not achievable when grouping more than 1 field")
}
var v []int
if err := cgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (cgb *ConnectorGroupBy) IntsX(ctx context.Context) []int {
v, err := cgb.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (cgb *ConnectorGroupBy) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = cgb.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{connector.Label}
default:
err = fmt.Errorf("db: ConnectorGroupBy.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (cgb *ConnectorGroupBy) IntX(ctx context.Context) int {
v, err := cgb.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from group-by.
// It is only allowed when executing a group-by query with one field.
func (cgb *ConnectorGroupBy) Float64s(ctx context.Context) ([]float64, error) {
if len(cgb.fields) > 1 {
return nil, errors.New("db: ConnectorGroupBy.Float64s is not achievable when grouping more than 1 field")
}
var v []float64
if err := cgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (cgb *ConnectorGroupBy) Float64sX(ctx context.Context) []float64 {
v, err := cgb.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (cgb *ConnectorGroupBy) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = cgb.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{connector.Label}
default:
err = fmt.Errorf("db: ConnectorGroupBy.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (cgb *ConnectorGroupBy) Float64X(ctx context.Context) float64 {
v, err := cgb.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from group-by.
// It is only allowed when executing a group-by query with one field.
func (cgb *ConnectorGroupBy) Bools(ctx context.Context) ([]bool, error) {
if len(cgb.fields) > 1 {
return nil, errors.New("db: ConnectorGroupBy.Bools is not achievable when grouping more than 1 field")
}
var v []bool
if err := cgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (cgb *ConnectorGroupBy) BoolsX(ctx context.Context) []bool {
v, err := cgb.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (cgb *ConnectorGroupBy) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = cgb.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{connector.Label}
default:
err = fmt.Errorf("db: ConnectorGroupBy.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (cgb *ConnectorGroupBy) BoolX(ctx context.Context) bool {
v, err := cgb.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
func (cgb *ConnectorGroupBy) sqlScan(ctx context.Context, v interface{}) error {
for _, f := range cgb.fields {
if !connector.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := cgb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := cgb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (cgb *ConnectorGroupBy) sqlQuery() *sql.Selector {
selector := cgb.sql
columns := make([]string, 0, len(cgb.fields)+len(cgb.fns))
columns = append(columns, cgb.fields...)
for _, fn := range cgb.fns {
columns = append(columns, fn(selector))
}
return selector.Select(columns...).GroupBy(cgb.fields...)
}
// ConnectorSelect is the builder for selecting fields of Connector entities.
type ConnectorSelect struct {
*ConnectorQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
}
// Scan applies the selector query and scans the result into the given value.
func (cs *ConnectorSelect) Scan(ctx context.Context, v interface{}) error {
if err := cs.prepareQuery(ctx); err != nil {
return err
}
cs.sql = cs.ConnectorQuery.sqlQuery(ctx)
return cs.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (cs *ConnectorSelect) ScanX(ctx context.Context, v interface{}) {
if err := cs.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from a selector. It is only allowed when selecting one field.
func (cs *ConnectorSelect) Strings(ctx context.Context) ([]string, error) {
if len(cs.fields) > 1 {
return nil, errors.New("db: ConnectorSelect.Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := cs.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (cs *ConnectorSelect) StringsX(ctx context.Context) []string {
v, err := cs.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a selector. It is only allowed when selecting one field.
func (cs *ConnectorSelect) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = cs.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{connector.Label}
default:
err = fmt.Errorf("db: ConnectorSelect.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (cs *ConnectorSelect) StringX(ctx context.Context) string {
v, err := cs.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from a selector. It is only allowed when selecting one field.
func (cs *ConnectorSelect) Ints(ctx context.Context) ([]int, error) {
if len(cs.fields) > 1 {
return nil, errors.New("db: ConnectorSelect.Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := cs.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (cs *ConnectorSelect) IntsX(ctx context.Context) []int {
v, err := cs.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a selector. It is only allowed when selecting one field.
func (cs *ConnectorSelect) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = cs.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{connector.Label}
default:
err = fmt.Errorf("db: ConnectorSelect.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (cs *ConnectorSelect) IntX(ctx context.Context) int {
v, err := cs.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
func (cs *ConnectorSelect) Float64s(ctx context.Context) ([]float64, error) {
if len(cs.fields) > 1 {
return nil, errors.New("db: ConnectorSelect.Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := cs.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (cs *ConnectorSelect) Float64sX(ctx context.Context) []float64 {
v, err := cs.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
func (cs *ConnectorSelect) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = cs.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{connector.Label}
default:
err = fmt.Errorf("db: ConnectorSelect.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (cs *ConnectorSelect) Float64X(ctx context.Context) float64 {
v, err := cs.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from a selector. It is only allowed when selecting one field.
func (cs *ConnectorSelect) Bools(ctx context.Context) ([]bool, error) {
if len(cs.fields) > 1 {
return nil, errors.New("db: ConnectorSelect.Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := cs.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (cs *ConnectorSelect) BoolsX(ctx context.Context) []bool {
v, err := cs.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a selector. It is only allowed when selecting one field.
func (cs *ConnectorSelect) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = cs.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{connector.Label}
default:
err = fmt.Errorf("db: ConnectorSelect.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (cs *ConnectorSelect) BoolX(ctx context.Context) bool {
v, err := cs.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
func (cs *ConnectorSelect) sqlScan(ctx context.Context, v interface{}) error {
rows := &sql.Rows{}
query, args := cs.sqlQuery().Query()
if err := cs.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (cs *ConnectorSelect) sqlQuery() sql.Querier {
selector := cs.sql
selector.Select(selector.Columns(cs.fields...)...)
return selector
}

View file

@ -0,0 +1,378 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/connector"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// ConnectorUpdate is the builder for updating Connector entities.
type ConnectorUpdate struct {
config
hooks []Hook
mutation *ConnectorMutation
}
// Where adds a new predicate for the ConnectorUpdate builder.
func (cu *ConnectorUpdate) Where(ps ...predicate.Connector) *ConnectorUpdate {
cu.mutation.predicates = append(cu.mutation.predicates, ps...)
return cu
}
// SetType sets the "type" field.
func (cu *ConnectorUpdate) SetType(s string) *ConnectorUpdate {
cu.mutation.SetType(s)
return cu
}
// SetName sets the "name" field.
func (cu *ConnectorUpdate) SetName(s string) *ConnectorUpdate {
cu.mutation.SetName(s)
return cu
}
// SetResourceVersion sets the "resource_version" field.
func (cu *ConnectorUpdate) SetResourceVersion(s string) *ConnectorUpdate {
cu.mutation.SetResourceVersion(s)
return cu
}
// SetConfig sets the "config" field.
func (cu *ConnectorUpdate) SetConfig(b []byte) *ConnectorUpdate {
cu.mutation.SetConfig(b)
return cu
}
// Mutation returns the ConnectorMutation object of the builder.
func (cu *ConnectorUpdate) Mutation() *ConnectorMutation {
return cu.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) {
var (
err error
affected int
)
if len(cu.hooks) == 0 {
if err = cu.check(); err != nil {
return 0, err
}
affected, err = cu.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*ConnectorMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = cu.check(); err != nil {
return 0, err
}
cu.mutation = mutation
affected, err = cu.sqlSave(ctx)
mutation.done = true
return affected, err
})
for i := len(cu.hooks) - 1; i >= 0; i-- {
mut = cu.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, cu.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// SaveX is like Save, but panics if an error occurs.
func (cu *ConnectorUpdate) SaveX(ctx context.Context) int {
affected, err := cu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (cu *ConnectorUpdate) Exec(ctx context.Context) error {
_, err := cu.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 {
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 {
if err := connector.TypeValidator(v); err != nil {
return &ValidationError{Name: "type", err: fmt.Errorf("db: validator failed for field \"type\": %w", err)}
}
}
if v, ok := cu.mutation.Name(); ok {
if err := connector.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf("db: validator failed for field \"name\": %w", err)}
}
}
return nil
}
func (cu *ConnectorUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: connector.Table,
Columns: connector.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: connector.FieldID,
},
},
}
if ps := cu.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := cu.mutation.GetType(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: connector.FieldType,
})
}
if value, ok := cu.mutation.Name(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: connector.FieldName,
})
}
if value, ok := cu.mutation.ResourceVersion(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: connector.FieldResourceVersion,
})
}
if value, ok := cu.mutation.Config(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: connector.FieldConfig,
})
}
if n, err = sqlgraph.UpdateNodes(ctx, cu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{connector.Label}
} else if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return 0, err
}
return n, nil
}
// ConnectorUpdateOne is the builder for updating a single Connector entity.
type ConnectorUpdateOne struct {
config
fields []string
hooks []Hook
mutation *ConnectorMutation
}
// SetType sets the "type" field.
func (cuo *ConnectorUpdateOne) SetType(s string) *ConnectorUpdateOne {
cuo.mutation.SetType(s)
return cuo
}
// SetName sets the "name" field.
func (cuo *ConnectorUpdateOne) SetName(s string) *ConnectorUpdateOne {
cuo.mutation.SetName(s)
return cuo
}
// SetResourceVersion sets the "resource_version" field.
func (cuo *ConnectorUpdateOne) SetResourceVersion(s string) *ConnectorUpdateOne {
cuo.mutation.SetResourceVersion(s)
return cuo
}
// SetConfig sets the "config" field.
func (cuo *ConnectorUpdateOne) SetConfig(b []byte) *ConnectorUpdateOne {
cuo.mutation.SetConfig(b)
return cuo
}
// Mutation returns the ConnectorMutation object of the builder.
func (cuo *ConnectorUpdateOne) Mutation() *ConnectorMutation {
return cuo.mutation
}
// 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
}
// Save executes the query and returns the updated Connector entity.
func (cuo *ConnectorUpdateOne) Save(ctx context.Context) (*Connector, error) {
var (
err error
node *Connector
)
if len(cuo.hooks) == 0 {
if err = cuo.check(); err != nil {
return nil, err
}
node, err = cuo.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*ConnectorMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = cuo.check(); err != nil {
return nil, err
}
cuo.mutation = mutation
node, err = cuo.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(cuo.hooks) - 1; i >= 0; i-- {
mut = cuo.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, cuo.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX is like Save, but panics if an error occurs.
func (cuo *ConnectorUpdateOne) SaveX(ctx context.Context) *Connector {
node, err := cuo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (cuo *ConnectorUpdateOne) Exec(ctx context.Context) error {
_, err := cuo.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 {
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 {
if err := connector.TypeValidator(v); err != nil {
return &ValidationError{Name: "type", err: fmt.Errorf("db: validator failed for field \"type\": %w", err)}
}
}
if v, ok := cuo.mutation.Name(); ok {
if err := connector.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf("db: validator failed for field \"name\": %w", err)}
}
}
return nil
}
func (cuo *ConnectorUpdateOne) sqlSave(ctx context.Context) (_node *Connector, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: connector.Table,
Columns: connector.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: connector.FieldID,
},
},
}
id, ok := cuo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing Connector.ID for update")}
}
_spec.Node.ID.Value = id
if fields := cuo.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, connector.FieldID)
for _, f := range fields {
if !connector.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
}
if f != connector.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := cuo.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := cuo.mutation.GetType(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: connector.FieldType,
})
}
if value, ok := cuo.mutation.Name(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: connector.FieldName,
})
}
if value, ok := cuo.mutation.ResourceVersion(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: connector.FieldResourceVersion,
})
}
if value, ok := cuo.mutation.Config(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: connector.FieldConfig,
})
}
_node = &Connector{config: cuo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, cuo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{connector.Label}
} else if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return nil, err
}
return _node, nil
}

33
storage/ent/db/context.go Normal file
View file

@ -0,0 +1,33 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
)
type clientCtxKey struct{}
// FromContext returns a Client stored inside a context, or nil if there isn't one.
func FromContext(ctx context.Context) *Client {
c, _ := ctx.Value(clientCtxKey{}).(*Client)
return c
}
// NewContext returns a new context with the given Client attached.
func NewContext(parent context.Context, c *Client) context.Context {
return context.WithValue(parent, clientCtxKey{}, c)
}
type txCtxKey struct{}
// TxFromContext returns a Tx stored inside a context, or nil if there isn't one.
func TxFromContext(ctx context.Context) *Tx {
tx, _ := ctx.Value(txCtxKey{}).(*Tx)
return tx
}
// NewTxContext returns a new context with the given Tx attached.
func NewTxContext(parent context.Context, tx *Tx) context.Context {
return context.WithValue(parent, txCtxKey{}, tx)
}

View file

@ -0,0 +1,158 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"encoding/json"
"fmt"
"strings"
"time"
"entgo.io/ent/dialect/sql"
"github.com/dexidp/dex/storage/ent/db/devicerequest"
)
// DeviceRequest is the model entity for the DeviceRequest schema.
type DeviceRequest struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// UserCode holds the value of the "user_code" field.
UserCode string `json:"user_code,omitempty"`
// DeviceCode holds the value of the "device_code" field.
DeviceCode string `json:"device_code,omitempty"`
// ClientID holds the value of the "client_id" field.
ClientID string `json:"client_id,omitempty"`
// ClientSecret holds the value of the "client_secret" field.
ClientSecret string `json:"client_secret,omitempty"`
// Scopes holds the value of the "scopes" field.
Scopes []string `json:"scopes,omitempty"`
// Expiry holds the value of the "expiry" field.
Expiry time.Time `json:"expiry,omitempty"`
}
// scanValues returns the types for scanning values from sql.Rows.
func (*DeviceRequest) scanValues(columns []string) ([]interface{}, error) {
values := make([]interface{}, len(columns))
for i := range columns {
switch columns[i] {
case devicerequest.FieldScopes:
values[i] = new([]byte)
case devicerequest.FieldID:
values[i] = new(sql.NullInt64)
case devicerequest.FieldUserCode, devicerequest.FieldDeviceCode, devicerequest.FieldClientID, devicerequest.FieldClientSecret:
values[i] = new(sql.NullString)
case devicerequest.FieldExpiry:
values[i] = new(sql.NullTime)
default:
return nil, fmt.Errorf("unexpected column %q for type DeviceRequest", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the DeviceRequest fields.
func (dr *DeviceRequest) assignValues(columns []string, values []interface{}) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case devicerequest.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
dr.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
}
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
}
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
}
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
}
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 {
return fmt.Errorf("unmarshal field scopes: %w", err)
}
}
case devicerequest.FieldExpiry:
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
}
}
}
return nil
}
// 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 (&DeviceRequestClient{config: dr.config}).UpdateOne(dr)
}
// 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)
if !ok {
panic("db: DeviceRequest is not a transactional entity")
}
dr.config.driver = tx.drv
return dr
}
// String implements the fmt.Stringer.
func (dr *DeviceRequest) String() string {
var builder strings.Builder
builder.WriteString("DeviceRequest(")
builder.WriteString(fmt.Sprintf("id=%v", dr.ID))
builder.WriteString(", user_code=")
builder.WriteString(dr.UserCode)
builder.WriteString(", device_code=")
builder.WriteString(dr.DeviceCode)
builder.WriteString(", client_id=")
builder.WriteString(dr.ClientID)
builder.WriteString(", client_secret=")
builder.WriteString(dr.ClientSecret)
builder.WriteString(", scopes=")
builder.WriteString(fmt.Sprintf("%v", dr.Scopes))
builder.WriteString(", expiry=")
builder.WriteString(dr.Expiry.Format(time.ANSIC))
builder.WriteByte(')')
return builder.String()
}
// DeviceRequests is a parsable slice of DeviceRequest.
type DeviceRequests []*DeviceRequest
func (dr DeviceRequests) config(cfg config) {
for _i := range dr {
dr[_i].config = cfg
}
}

View file

@ -0,0 +1,56 @@
// Code generated by entc, DO NOT EDIT.
package devicerequest
const (
// Label holds the string label denoting the devicerequest type in the database.
Label = "device_request"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldUserCode holds the string denoting the user_code field in the database.
FieldUserCode = "user_code"
// FieldDeviceCode holds the string denoting the device_code field in the database.
FieldDeviceCode = "device_code"
// FieldClientID holds the string denoting the client_id field in the database.
FieldClientID = "client_id"
// FieldClientSecret holds the string denoting the client_secret field in the database.
FieldClientSecret = "client_secret"
// FieldScopes holds the string denoting the scopes field in the database.
FieldScopes = "scopes"
// FieldExpiry holds the string denoting the expiry field in the database.
FieldExpiry = "expiry"
// Table holds the table name of the devicerequest in the database.
Table = "device_requests"
)
// Columns holds all SQL columns for devicerequest fields.
var Columns = []string{
FieldID,
FieldUserCode,
FieldDeviceCode,
FieldClientID,
FieldClientSecret,
FieldScopes,
FieldExpiry,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// UserCodeValidator is a validator for the "user_code" field. It is called by the builders before save.
UserCodeValidator func(string) error
// DeviceCodeValidator is a validator for the "device_code" field. It is called by the builders before save.
DeviceCodeValidator func(string) error
// ClientIDValidator is a validator for the "client_id" field. It is called by the builders before save.
ClientIDValidator func(string) error
// ClientSecretValidator is a validator for the "client_secret" field. It is called by the builders before save.
ClientSecretValidator func(string) error
)

View file

@ -0,0 +1,694 @@
// Code generated by entc, DO NOT EDIT.
package devicerequest
import (
"time"
"entgo.io/ent/dialect/sql"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldID), id))
})
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.In(s.C(FieldID), v...))
})
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.NotIn(s.C(FieldID), v...))
})
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldID), id))
})
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldID), id))
})
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldID), id))
})
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldID), id))
})
}
// UserCode applies equality check predicate on the "user_code" field. It's identical to UserCodeEQ.
func UserCode(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUserCode), v))
})
}
// DeviceCode applies equality check predicate on the "device_code" field. It's identical to DeviceCodeEQ.
func DeviceCode(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldDeviceCode), v))
})
}
// ClientID applies equality check predicate on the "client_id" field. It's identical to ClientIDEQ.
func ClientID(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldClientID), v))
})
}
// ClientSecret applies equality check predicate on the "client_secret" field. It's identical to ClientSecretEQ.
func ClientSecret(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldClientSecret), v))
})
}
// Expiry applies equality check predicate on the "expiry" field. It's identical to ExpiryEQ.
func Expiry(v time.Time) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldExpiry), v))
})
}
// UserCodeEQ applies the EQ predicate on the "user_code" field.
func UserCodeEQ(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUserCode), v))
})
}
// UserCodeNEQ applies the NEQ predicate on the "user_code" field.
func UserCodeNEQ(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldUserCode), v))
})
}
// UserCodeIn applies the In predicate on the "user_code" field.
func UserCodeIn(vs ...string) predicate.DeviceRequest {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DeviceRequest(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldUserCode), v...))
})
}
// UserCodeNotIn applies the NotIn predicate on the "user_code" field.
func UserCodeNotIn(vs ...string) predicate.DeviceRequest {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DeviceRequest(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldUserCode), v...))
})
}
// UserCodeGT applies the GT predicate on the "user_code" field.
func UserCodeGT(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldUserCode), v))
})
}
// UserCodeGTE applies the GTE predicate on the "user_code" field.
func UserCodeGTE(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldUserCode), v))
})
}
// UserCodeLT applies the LT predicate on the "user_code" field.
func UserCodeLT(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldUserCode), v))
})
}
// UserCodeLTE applies the LTE predicate on the "user_code" field.
func UserCodeLTE(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldUserCode), v))
})
}
// UserCodeContains applies the Contains predicate on the "user_code" field.
func UserCodeContains(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldUserCode), v))
})
}
// UserCodeHasPrefix applies the HasPrefix predicate on the "user_code" field.
func UserCodeHasPrefix(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldUserCode), v))
})
}
// UserCodeHasSuffix applies the HasSuffix predicate on the "user_code" field.
func UserCodeHasSuffix(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldUserCode), v))
})
}
// UserCodeEqualFold applies the EqualFold predicate on the "user_code" field.
func UserCodeEqualFold(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldUserCode), v))
})
}
// UserCodeContainsFold applies the ContainsFold predicate on the "user_code" field.
func UserCodeContainsFold(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldUserCode), v))
})
}
// DeviceCodeEQ applies the EQ predicate on the "device_code" field.
func DeviceCodeEQ(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldDeviceCode), v))
})
}
// DeviceCodeNEQ applies the NEQ predicate on the "device_code" field.
func DeviceCodeNEQ(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldDeviceCode), v))
})
}
// DeviceCodeIn applies the In predicate on the "device_code" field.
func DeviceCodeIn(vs ...string) predicate.DeviceRequest {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DeviceRequest(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldDeviceCode), v...))
})
}
// DeviceCodeNotIn applies the NotIn predicate on the "device_code" field.
func DeviceCodeNotIn(vs ...string) predicate.DeviceRequest {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DeviceRequest(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldDeviceCode), v...))
})
}
// DeviceCodeGT applies the GT predicate on the "device_code" field.
func DeviceCodeGT(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldDeviceCode), v))
})
}
// DeviceCodeGTE applies the GTE predicate on the "device_code" field.
func DeviceCodeGTE(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldDeviceCode), v))
})
}
// DeviceCodeLT applies the LT predicate on the "device_code" field.
func DeviceCodeLT(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldDeviceCode), v))
})
}
// DeviceCodeLTE applies the LTE predicate on the "device_code" field.
func DeviceCodeLTE(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldDeviceCode), v))
})
}
// DeviceCodeContains applies the Contains predicate on the "device_code" field.
func DeviceCodeContains(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldDeviceCode), v))
})
}
// DeviceCodeHasPrefix applies the HasPrefix predicate on the "device_code" field.
func DeviceCodeHasPrefix(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldDeviceCode), v))
})
}
// DeviceCodeHasSuffix applies the HasSuffix predicate on the "device_code" field.
func DeviceCodeHasSuffix(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldDeviceCode), v))
})
}
// DeviceCodeEqualFold applies the EqualFold predicate on the "device_code" field.
func DeviceCodeEqualFold(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldDeviceCode), v))
})
}
// DeviceCodeContainsFold applies the ContainsFold predicate on the "device_code" field.
func DeviceCodeContainsFold(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldDeviceCode), v))
})
}
// ClientIDEQ applies the EQ predicate on the "client_id" field.
func ClientIDEQ(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldClientID), v))
})
}
// ClientIDNEQ applies the NEQ predicate on the "client_id" field.
func ClientIDNEQ(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldClientID), v))
})
}
// ClientIDIn applies the In predicate on the "client_id" field.
func ClientIDIn(vs ...string) predicate.DeviceRequest {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DeviceRequest(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldClientID), v...))
})
}
// ClientIDNotIn applies the NotIn predicate on the "client_id" field.
func ClientIDNotIn(vs ...string) predicate.DeviceRequest {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DeviceRequest(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldClientID), v...))
})
}
// ClientIDGT applies the GT predicate on the "client_id" field.
func ClientIDGT(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldClientID), v))
})
}
// ClientIDGTE applies the GTE predicate on the "client_id" field.
func ClientIDGTE(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldClientID), v))
})
}
// ClientIDLT applies the LT predicate on the "client_id" field.
func ClientIDLT(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldClientID), v))
})
}
// ClientIDLTE applies the LTE predicate on the "client_id" field.
func ClientIDLTE(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldClientID), v))
})
}
// ClientIDContains applies the Contains predicate on the "client_id" field.
func ClientIDContains(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldClientID), v))
})
}
// ClientIDHasPrefix applies the HasPrefix predicate on the "client_id" field.
func ClientIDHasPrefix(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldClientID), v))
})
}
// ClientIDHasSuffix applies the HasSuffix predicate on the "client_id" field.
func ClientIDHasSuffix(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldClientID), v))
})
}
// ClientIDEqualFold applies the EqualFold predicate on the "client_id" field.
func ClientIDEqualFold(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldClientID), v))
})
}
// ClientIDContainsFold applies the ContainsFold predicate on the "client_id" field.
func ClientIDContainsFold(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldClientID), v))
})
}
// ClientSecretEQ applies the EQ predicate on the "client_secret" field.
func ClientSecretEQ(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldClientSecret), v))
})
}
// ClientSecretNEQ applies the NEQ predicate on the "client_secret" field.
func ClientSecretNEQ(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldClientSecret), v))
})
}
// ClientSecretIn applies the In predicate on the "client_secret" field.
func ClientSecretIn(vs ...string) predicate.DeviceRequest {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DeviceRequest(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldClientSecret), v...))
})
}
// ClientSecretNotIn applies the NotIn predicate on the "client_secret" field.
func ClientSecretNotIn(vs ...string) predicate.DeviceRequest {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DeviceRequest(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldClientSecret), v...))
})
}
// ClientSecretGT applies the GT predicate on the "client_secret" field.
func ClientSecretGT(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldClientSecret), v))
})
}
// ClientSecretGTE applies the GTE predicate on the "client_secret" field.
func ClientSecretGTE(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldClientSecret), v))
})
}
// ClientSecretLT applies the LT predicate on the "client_secret" field.
func ClientSecretLT(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldClientSecret), v))
})
}
// ClientSecretLTE applies the LTE predicate on the "client_secret" field.
func ClientSecretLTE(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldClientSecret), v))
})
}
// ClientSecretContains applies the Contains predicate on the "client_secret" field.
func ClientSecretContains(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldClientSecret), v))
})
}
// ClientSecretHasPrefix applies the HasPrefix predicate on the "client_secret" field.
func ClientSecretHasPrefix(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldClientSecret), v))
})
}
// ClientSecretHasSuffix applies the HasSuffix predicate on the "client_secret" field.
func ClientSecretHasSuffix(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldClientSecret), v))
})
}
// ClientSecretEqualFold applies the EqualFold predicate on the "client_secret" field.
func ClientSecretEqualFold(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldClientSecret), v))
})
}
// ClientSecretContainsFold applies the ContainsFold predicate on the "client_secret" field.
func ClientSecretContainsFold(v string) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldClientSecret), v))
})
}
// ScopesIsNil applies the IsNil predicate on the "scopes" field.
func ScopesIsNil() predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldScopes)))
})
}
// ScopesNotNil applies the NotNil predicate on the "scopes" field.
func ScopesNotNil() predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.NotNull(s.C(FieldScopes)))
})
}
// ExpiryEQ applies the EQ predicate on the "expiry" field.
func ExpiryEQ(v time.Time) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldExpiry), v))
})
}
// ExpiryNEQ applies the NEQ predicate on the "expiry" field.
func ExpiryNEQ(v time.Time) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldExpiry), v))
})
}
// ExpiryIn applies the In predicate on the "expiry" field.
func ExpiryIn(vs ...time.Time) predicate.DeviceRequest {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DeviceRequest(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldExpiry), v...))
})
}
// ExpiryNotIn applies the NotIn predicate on the "expiry" field.
func ExpiryNotIn(vs ...time.Time) predicate.DeviceRequest {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DeviceRequest(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldExpiry), v...))
})
}
// ExpiryGT applies the GT predicate on the "expiry" field.
func ExpiryGT(v time.Time) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldExpiry), v))
})
}
// ExpiryGTE applies the GTE predicate on the "expiry" field.
func ExpiryGTE(v time.Time) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldExpiry), v))
})
}
// ExpiryLT applies the LT predicate on the "expiry" field.
func ExpiryLT(v time.Time) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldExpiry), v))
})
}
// ExpiryLTE applies the LTE predicate on the "expiry" field.
func ExpiryLTE(v time.Time) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldExpiry), v))
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.DeviceRequest) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for _, p := range predicates {
p(s1)
}
s.Where(s1.P())
})
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.DeviceRequest) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for i, p := range predicates {
if i > 0 {
s1.Or()
}
p(s1)
}
s.Where(s1.P())
})
}
// Not applies the not operator on the given predicate.
func Not(p predicate.DeviceRequest) predicate.DeviceRequest {
return predicate.DeviceRequest(func(s *sql.Selector) {
p(s.Not())
})
}

View file

@ -0,0 +1,287 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/devicerequest"
)
// DeviceRequestCreate is the builder for creating a DeviceRequest entity.
type DeviceRequestCreate struct {
config
mutation *DeviceRequestMutation
hooks []Hook
}
// SetUserCode sets the "user_code" field.
func (drc *DeviceRequestCreate) SetUserCode(s string) *DeviceRequestCreate {
drc.mutation.SetUserCode(s)
return drc
}
// SetDeviceCode sets the "device_code" field.
func (drc *DeviceRequestCreate) SetDeviceCode(s string) *DeviceRequestCreate {
drc.mutation.SetDeviceCode(s)
return drc
}
// SetClientID sets the "client_id" field.
func (drc *DeviceRequestCreate) SetClientID(s string) *DeviceRequestCreate {
drc.mutation.SetClientID(s)
return drc
}
// SetClientSecret sets the "client_secret" field.
func (drc *DeviceRequestCreate) SetClientSecret(s string) *DeviceRequestCreate {
drc.mutation.SetClientSecret(s)
return drc
}
// SetScopes sets the "scopes" field.
func (drc *DeviceRequestCreate) SetScopes(s []string) *DeviceRequestCreate {
drc.mutation.SetScopes(s)
return drc
}
// SetExpiry sets the "expiry" field.
func (drc *DeviceRequestCreate) SetExpiry(t time.Time) *DeviceRequestCreate {
drc.mutation.SetExpiry(t)
return drc
}
// Mutation returns the DeviceRequestMutation object of the builder.
func (drc *DeviceRequestCreate) Mutation() *DeviceRequestMutation {
return drc.mutation
}
// Save creates the DeviceRequest in the database.
func (drc *DeviceRequestCreate) Save(ctx context.Context) (*DeviceRequest, error) {
var (
err error
node *DeviceRequest
)
if len(drc.hooks) == 0 {
if err = drc.check(); err != nil {
return nil, err
}
node, err = drc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*DeviceRequestMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = drc.check(); err != nil {
return nil, err
}
drc.mutation = mutation
node, err = drc.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(drc.hooks) - 1; i >= 0; i-- {
mut = drc.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, drc.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (drc *DeviceRequestCreate) SaveX(ctx context.Context) *DeviceRequest {
v, err := drc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// check runs all checks and user-defined validators on the builder.
func (drc *DeviceRequestCreate) check() error {
if _, ok := drc.mutation.UserCode(); !ok {
return &ValidationError{Name: "user_code", err: errors.New("db: missing required field \"user_code\"")}
}
if v, ok := drc.mutation.UserCode(); ok {
if err := devicerequest.UserCodeValidator(v); err != nil {
return &ValidationError{Name: "user_code", err: fmt.Errorf("db: validator failed for field \"user_code\": %w", err)}
}
}
if _, ok := drc.mutation.DeviceCode(); !ok {
return &ValidationError{Name: "device_code", err: errors.New("db: missing required field \"device_code\"")}
}
if v, ok := drc.mutation.DeviceCode(); ok {
if err := devicerequest.DeviceCodeValidator(v); err != nil {
return &ValidationError{Name: "device_code", err: fmt.Errorf("db: validator failed for field \"device_code\": %w", err)}
}
}
if _, ok := drc.mutation.ClientID(); !ok {
return &ValidationError{Name: "client_id", err: errors.New("db: missing required field \"client_id\"")}
}
if v, ok := drc.mutation.ClientID(); ok {
if err := devicerequest.ClientIDValidator(v); err != nil {
return &ValidationError{Name: "client_id", err: fmt.Errorf("db: validator failed for field \"client_id\": %w", err)}
}
}
if _, ok := drc.mutation.ClientSecret(); !ok {
return &ValidationError{Name: "client_secret", err: errors.New("db: missing required field \"client_secret\"")}
}
if v, ok := drc.mutation.ClientSecret(); ok {
if err := devicerequest.ClientSecretValidator(v); err != nil {
return &ValidationError{Name: "client_secret", err: fmt.Errorf("db: validator failed for field \"client_secret\": %w", err)}
}
}
if _, ok := drc.mutation.Expiry(); !ok {
return &ValidationError{Name: "expiry", err: errors.New("db: missing required field \"expiry\"")}
}
return nil
}
func (drc *DeviceRequestCreate) sqlSave(ctx context.Context) (*DeviceRequest, error) {
_node, _spec := drc.createSpec()
if err := sqlgraph.CreateNode(ctx, drc.driver, _spec); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
return _node, nil
}
func (drc *DeviceRequestCreate) createSpec() (*DeviceRequest, *sqlgraph.CreateSpec) {
var (
_node = &DeviceRequest{config: drc.config}
_spec = &sqlgraph.CreateSpec{
Table: devicerequest.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: devicerequest.FieldID,
},
}
)
if value, ok := drc.mutation.UserCode(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: devicerequest.FieldUserCode,
})
_node.UserCode = value
}
if value, ok := drc.mutation.DeviceCode(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: devicerequest.FieldDeviceCode,
})
_node.DeviceCode = value
}
if value, ok := drc.mutation.ClientID(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: devicerequest.FieldClientID,
})
_node.ClientID = value
}
if value, ok := drc.mutation.ClientSecret(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: devicerequest.FieldClientSecret,
})
_node.ClientSecret = value
}
if value, ok := drc.mutation.Scopes(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: devicerequest.FieldScopes,
})
_node.Scopes = value
}
if value, ok := drc.mutation.Expiry(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: devicerequest.FieldExpiry,
})
_node.Expiry = value
}
return _node, _spec
}
// DeviceRequestCreateBulk is the builder for creating many DeviceRequest entities in bulk.
type DeviceRequestCreateBulk struct {
config
builders []*DeviceRequestCreate
}
// Save creates the DeviceRequest entities in the database.
func (drcb *DeviceRequestCreateBulk) Save(ctx context.Context) ([]*DeviceRequest, error) {
specs := make([]*sqlgraph.CreateSpec, len(drcb.builders))
nodes := make([]*DeviceRequest, len(drcb.builders))
mutators := make([]Mutator, len(drcb.builders))
for i := range drcb.builders {
func(i int, root context.Context) {
builder := drcb.builders[i]
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*DeviceRequestMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
nodes[i], specs[i] = builder.createSpec()
var err error
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, drcb.builders[i+1].mutation)
} else {
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, drcb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
}
}
mutation.done = true
if err != nil {
return nil, err
}
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, drcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (drcb *DeviceRequestCreateBulk) SaveX(ctx context.Context) []*DeviceRequest {
v, err := drcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}

View file

@ -0,0 +1,108 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/devicerequest"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// DeviceRequestDelete is the builder for deleting a DeviceRequest entity.
type DeviceRequestDelete struct {
config
hooks []Hook
mutation *DeviceRequestMutation
}
// Where adds a new predicate to the DeviceRequestDelete builder.
func (drd *DeviceRequestDelete) Where(ps ...predicate.DeviceRequest) *DeviceRequestDelete {
drd.mutation.predicates = append(drd.mutation.predicates, ps...)
return drd
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (drd *DeviceRequestDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(drd.hooks) == 0 {
affected, err = drd.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*DeviceRequestMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
drd.mutation = mutation
affected, err = drd.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(drd.hooks) - 1; i >= 0; i-- {
mut = drd.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, drd.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (drd *DeviceRequestDelete) ExecX(ctx context.Context) int {
n, err := drd.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (drd *DeviceRequestDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: devicerequest.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: devicerequest.FieldID,
},
},
}
if ps := drd.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return sqlgraph.DeleteNodes(ctx, drd.driver, _spec)
}
// DeviceRequestDeleteOne is the builder for deleting a single DeviceRequest entity.
type DeviceRequestDeleteOne struct {
drd *DeviceRequestDelete
}
// Exec executes the deletion query.
func (drdo *DeviceRequestDeleteOne) Exec(ctx context.Context) error {
n, err := drdo.drd.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{devicerequest.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (drdo *DeviceRequestDeleteOne) ExecX(ctx context.Context) {
drdo.drd.ExecX(ctx)
}

View file

@ -0,0 +1,906 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"errors"
"fmt"
"math"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/devicerequest"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// DeviceRequestQuery is the builder for querying DeviceRequest entities.
type DeviceRequestQuery struct {
config
limit *int
offset *int
unique *bool
order []OrderFunc
fields []string
predicates []predicate.DeviceRequest
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// 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
}
// Limit adds a limit step to the query.
func (drq *DeviceRequestQuery) Limit(limit int) *DeviceRequestQuery {
drq.limit = &limit
return drq
}
// Offset adds an offset step to the query.
func (drq *DeviceRequestQuery) Offset(offset int) *DeviceRequestQuery {
drq.offset = &offset
return drq
}
// 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.unique = &unique
return drq
}
// Order adds an order step to the query.
func (drq *DeviceRequestQuery) Order(o ...OrderFunc) *DeviceRequestQuery {
drq.order = append(drq.order, o...)
return drq
}
// 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(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{devicerequest.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (drq *DeviceRequestQuery) FirstX(ctx context.Context) *DeviceRequest {
node, err := drq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// 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) {
var ids []int
if ids, err = drq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{devicerequest.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (drq *DeviceRequestQuery) FirstIDX(ctx context.Context) int {
id, err := drq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single DeviceRequest entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when exactly one DeviceRequest entity is not 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(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{devicerequest.Label}
default:
return nil, &NotSingularError{devicerequest.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (drq *DeviceRequestQuery) OnlyX(ctx context.Context) *DeviceRequest {
node, err := drq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only DeviceRequest ID in the query.
// Returns a *NotSingularError when exactly one DeviceRequest ID is not found.
// Returns a *NotFoundError when no entities are found.
func (drq *DeviceRequestQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = drq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{devicerequest.Label}
default:
err = &NotSingularError{devicerequest.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (drq *DeviceRequestQuery) OnlyIDX(ctx context.Context) int {
id, err := drq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of DeviceRequests.
func (drq *DeviceRequestQuery) All(ctx context.Context) ([]*DeviceRequest, error) {
if err := drq.prepareQuery(ctx); err != nil {
return nil, err
}
return drq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (drq *DeviceRequestQuery) AllX(ctx context.Context) []*DeviceRequest {
nodes, err := drq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of DeviceRequest IDs.
func (drq *DeviceRequestQuery) IDs(ctx context.Context) ([]int, error) {
var ids []int
if err := drq.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)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (drq *DeviceRequestQuery) Count(ctx context.Context) (int, error) {
if err := drq.prepareQuery(ctx); err != nil {
return 0, err
}
return drq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (drq *DeviceRequestQuery) CountX(ctx context.Context) int {
count, err := drq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (drq *DeviceRequestQuery) Exist(ctx context.Context) (bool, error) {
if err := drq.prepareQuery(ctx); err != nil {
return false, err
}
return drq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (drq *DeviceRequestQuery) ExistX(ctx context.Context) bool {
exist, err := drq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// 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 {
return nil
}
return &DeviceRequestQuery{
config: drq.config,
limit: drq.limit,
offset: drq.offset,
order: append([]OrderFunc{}, drq.order...),
predicates: append([]predicate.DeviceRequest{}, drq.predicates...),
// clone intermediate query.
sql: drq.sql.Clone(),
path: drq.path,
}
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// UserCode string `json:"user_code,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.DeviceRequest.Query().
// GroupBy(devicerequest.FieldUserCode).
// Aggregate(db.Count()).
// Scan(ctx, &v)
//
func (drq *DeviceRequestQuery) GroupBy(field string, fields ...string) *DeviceRequestGroupBy {
group := &DeviceRequestGroupBy{config: drq.config}
group.fields = append([]string{field}, fields...)
group.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := drq.prepareQuery(ctx); err != nil {
return nil, err
}
return drq.sqlQuery(ctx), nil
}
return group
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// UserCode string `json:"user_code,omitempty"`
// }
//
// client.DeviceRequest.Query().
// Select(devicerequest.FieldUserCode).
// Scan(ctx, &v)
//
func (drq *DeviceRequestQuery) Select(field string, fields ...string) *DeviceRequestSelect {
drq.fields = append([]string{field}, fields...)
return &DeviceRequestSelect{DeviceRequestQuery: drq}
}
func (drq *DeviceRequestQuery) prepareQuery(ctx context.Context) error {
for _, f := range drq.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 err != nil {
return err
}
drq.sql = prev
}
return nil
}
func (drq *DeviceRequestQuery) sqlAll(ctx context.Context) ([]*DeviceRequest, error) {
var (
nodes = []*DeviceRequest{}
_spec = drq.querySpec()
)
_spec.ScanValues = func(columns []string) ([]interface{}, error) {
node := &DeviceRequest{config: drq.config}
nodes = append(nodes, node)
return node.scanValues(columns)
}
_spec.Assign = func(columns []string, values []interface{}) error {
if len(nodes) == 0 {
return fmt.Errorf("db: Assign called without calling ScanValues")
}
node := nodes[len(nodes)-1]
return node.assignValues(columns, values)
}
if err := sqlgraph.QueryNodes(ctx, drq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (drq *DeviceRequestQuery) sqlCount(ctx context.Context) (int, error) {
_spec := drq.querySpec()
return sqlgraph.CountNodes(ctx, drq.driver, _spec)
}
func (drq *DeviceRequestQuery) sqlExist(ctx context.Context) (bool, error) {
n, err := drq.sqlCount(ctx)
if err != nil {
return false, fmt.Errorf("db: check existence: %w", err)
}
return n > 0, nil
}
func (drq *DeviceRequestQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: devicerequest.Table,
Columns: devicerequest.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: devicerequest.FieldID,
},
},
From: drq.sql,
Unique: true,
}
if unique := drq.unique; unique != nil {
_spec.Unique = *unique
}
if fields := drq.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 {
if fields[i] != devicerequest.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := drq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := drq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := drq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := drq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (drq *DeviceRequestQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(drq.driver.Dialect())
t1 := builder.Table(devicerequest.Table)
selector := builder.Select(t1.Columns(devicerequest.Columns...)...).From(t1)
if drq.sql != nil {
selector = drq.sql
selector.Select(selector.Columns(devicerequest.Columns...)...)
}
for _, p := range drq.predicates {
p(selector)
}
for _, p := range drq.order {
p(selector)
}
if offset := drq.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.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// DeviceRequestGroupBy is the group-by builder for DeviceRequest entities.
type DeviceRequestGroupBy struct {
config
fields []string
fns []AggregateFunc
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Aggregate adds the given aggregation functions to the group-by query.
func (drgb *DeviceRequestGroupBy) Aggregate(fns ...AggregateFunc) *DeviceRequestGroupBy {
drgb.fns = append(drgb.fns, fns...)
return drgb
}
// Scan applies the group-by query and scans the result into the given value.
func (drgb *DeviceRequestGroupBy) Scan(ctx context.Context, v interface{}) error {
query, err := drgb.path(ctx)
if err != nil {
return err
}
drgb.sql = query
return drgb.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (drgb *DeviceRequestGroupBy) ScanX(ctx context.Context, v interface{}) {
if err := drgb.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from group-by.
// It is only allowed when executing a group-by query with one field.
func (drgb *DeviceRequestGroupBy) Strings(ctx context.Context) ([]string, error) {
if len(drgb.fields) > 1 {
return nil, errors.New("db: DeviceRequestGroupBy.Strings is not achievable when grouping more than 1 field")
}
var v []string
if err := drgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (drgb *DeviceRequestGroupBy) StringsX(ctx context.Context) []string {
v, err := drgb.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (drgb *DeviceRequestGroupBy) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = drgb.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{devicerequest.Label}
default:
err = fmt.Errorf("db: DeviceRequestGroupBy.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (drgb *DeviceRequestGroupBy) StringX(ctx context.Context) string {
v, err := drgb.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from group-by.
// It is only allowed when executing a group-by query with one field.
func (drgb *DeviceRequestGroupBy) Ints(ctx context.Context) ([]int, error) {
if len(drgb.fields) > 1 {
return nil, errors.New("db: DeviceRequestGroupBy.Ints is not achievable when grouping more than 1 field")
}
var v []int
if err := drgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (drgb *DeviceRequestGroupBy) IntsX(ctx context.Context) []int {
v, err := drgb.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (drgb *DeviceRequestGroupBy) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = drgb.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{devicerequest.Label}
default:
err = fmt.Errorf("db: DeviceRequestGroupBy.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (drgb *DeviceRequestGroupBy) IntX(ctx context.Context) int {
v, err := drgb.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from group-by.
// It is only allowed when executing a group-by query with one field.
func (drgb *DeviceRequestGroupBy) Float64s(ctx context.Context) ([]float64, error) {
if len(drgb.fields) > 1 {
return nil, errors.New("db: DeviceRequestGroupBy.Float64s is not achievable when grouping more than 1 field")
}
var v []float64
if err := drgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (drgb *DeviceRequestGroupBy) Float64sX(ctx context.Context) []float64 {
v, err := drgb.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (drgb *DeviceRequestGroupBy) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = drgb.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{devicerequest.Label}
default:
err = fmt.Errorf("db: DeviceRequestGroupBy.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (drgb *DeviceRequestGroupBy) Float64X(ctx context.Context) float64 {
v, err := drgb.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from group-by.
// It is only allowed when executing a group-by query with one field.
func (drgb *DeviceRequestGroupBy) Bools(ctx context.Context) ([]bool, error) {
if len(drgb.fields) > 1 {
return nil, errors.New("db: DeviceRequestGroupBy.Bools is not achievable when grouping more than 1 field")
}
var v []bool
if err := drgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (drgb *DeviceRequestGroupBy) BoolsX(ctx context.Context) []bool {
v, err := drgb.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (drgb *DeviceRequestGroupBy) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = drgb.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{devicerequest.Label}
default:
err = fmt.Errorf("db: DeviceRequestGroupBy.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (drgb *DeviceRequestGroupBy) BoolX(ctx context.Context) bool {
v, err := drgb.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
func (drgb *DeviceRequestGroupBy) sqlScan(ctx context.Context, v interface{}) error {
for _, f := range drgb.fields {
if !devicerequest.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := drgb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := drgb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (drgb *DeviceRequestGroupBy) sqlQuery() *sql.Selector {
selector := drgb.sql
columns := make([]string, 0, len(drgb.fields)+len(drgb.fns))
columns = append(columns, drgb.fields...)
for _, fn := range drgb.fns {
columns = append(columns, fn(selector))
}
return selector.Select(columns...).GroupBy(drgb.fields...)
}
// DeviceRequestSelect is the builder for selecting fields of DeviceRequest entities.
type DeviceRequestSelect struct {
*DeviceRequestQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
}
// Scan applies the selector query and scans the result into the given value.
func (drs *DeviceRequestSelect) Scan(ctx context.Context, v interface{}) error {
if err := drs.prepareQuery(ctx); err != nil {
return err
}
drs.sql = drs.DeviceRequestQuery.sqlQuery(ctx)
return drs.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (drs *DeviceRequestSelect) ScanX(ctx context.Context, v interface{}) {
if err := drs.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from a selector. It is only allowed when selecting one field.
func (drs *DeviceRequestSelect) Strings(ctx context.Context) ([]string, error) {
if len(drs.fields) > 1 {
return nil, errors.New("db: DeviceRequestSelect.Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := drs.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (drs *DeviceRequestSelect) StringsX(ctx context.Context) []string {
v, err := drs.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a selector. It is only allowed when selecting one field.
func (drs *DeviceRequestSelect) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = drs.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{devicerequest.Label}
default:
err = fmt.Errorf("db: DeviceRequestSelect.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (drs *DeviceRequestSelect) StringX(ctx context.Context) string {
v, err := drs.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from a selector. It is only allowed when selecting one field.
func (drs *DeviceRequestSelect) Ints(ctx context.Context) ([]int, error) {
if len(drs.fields) > 1 {
return nil, errors.New("db: DeviceRequestSelect.Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := drs.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (drs *DeviceRequestSelect) IntsX(ctx context.Context) []int {
v, err := drs.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a selector. It is only allowed when selecting one field.
func (drs *DeviceRequestSelect) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = drs.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{devicerequest.Label}
default:
err = fmt.Errorf("db: DeviceRequestSelect.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (drs *DeviceRequestSelect) IntX(ctx context.Context) int {
v, err := drs.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
func (drs *DeviceRequestSelect) Float64s(ctx context.Context) ([]float64, error) {
if len(drs.fields) > 1 {
return nil, errors.New("db: DeviceRequestSelect.Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := drs.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (drs *DeviceRequestSelect) Float64sX(ctx context.Context) []float64 {
v, err := drs.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
func (drs *DeviceRequestSelect) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = drs.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{devicerequest.Label}
default:
err = fmt.Errorf("db: DeviceRequestSelect.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (drs *DeviceRequestSelect) Float64X(ctx context.Context) float64 {
v, err := drs.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from a selector. It is only allowed when selecting one field.
func (drs *DeviceRequestSelect) Bools(ctx context.Context) ([]bool, error) {
if len(drs.fields) > 1 {
return nil, errors.New("db: DeviceRequestSelect.Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := drs.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (drs *DeviceRequestSelect) BoolsX(ctx context.Context) []bool {
v, err := drs.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a selector. It is only allowed when selecting one field.
func (drs *DeviceRequestSelect) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = drs.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{devicerequest.Label}
default:
err = fmt.Errorf("db: DeviceRequestSelect.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (drs *DeviceRequestSelect) BoolX(ctx context.Context) bool {
v, err := drs.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
func (drs *DeviceRequestSelect) sqlScan(ctx context.Context, v interface{}) error {
rows := &sql.Rows{}
query, args := drs.sqlQuery().Query()
if err := drs.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (drs *DeviceRequestSelect) sqlQuery() sql.Querier {
selector := drs.sql
selector.Select(selector.Columns(drs.fields...)...)
return selector
}

View file

@ -0,0 +1,475 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"fmt"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/devicerequest"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// DeviceRequestUpdate is the builder for updating DeviceRequest entities.
type DeviceRequestUpdate struct {
config
hooks []Hook
mutation *DeviceRequestMutation
}
// Where adds a new predicate for the DeviceRequestUpdate builder.
func (dru *DeviceRequestUpdate) Where(ps ...predicate.DeviceRequest) *DeviceRequestUpdate {
dru.mutation.predicates = append(dru.mutation.predicates, ps...)
return dru
}
// SetUserCode sets the "user_code" field.
func (dru *DeviceRequestUpdate) SetUserCode(s string) *DeviceRequestUpdate {
dru.mutation.SetUserCode(s)
return dru
}
// SetDeviceCode sets the "device_code" field.
func (dru *DeviceRequestUpdate) SetDeviceCode(s string) *DeviceRequestUpdate {
dru.mutation.SetDeviceCode(s)
return dru
}
// SetClientID sets the "client_id" field.
func (dru *DeviceRequestUpdate) SetClientID(s string) *DeviceRequestUpdate {
dru.mutation.SetClientID(s)
return dru
}
// SetClientSecret sets the "client_secret" field.
func (dru *DeviceRequestUpdate) SetClientSecret(s string) *DeviceRequestUpdate {
dru.mutation.SetClientSecret(s)
return dru
}
// SetScopes sets the "scopes" field.
func (dru *DeviceRequestUpdate) SetScopes(s []string) *DeviceRequestUpdate {
dru.mutation.SetScopes(s)
return dru
}
// ClearScopes clears the value of the "scopes" field.
func (dru *DeviceRequestUpdate) ClearScopes() *DeviceRequestUpdate {
dru.mutation.ClearScopes()
return dru
}
// SetExpiry sets the "expiry" field.
func (dru *DeviceRequestUpdate) SetExpiry(t time.Time) *DeviceRequestUpdate {
dru.mutation.SetExpiry(t)
return dru
}
// Mutation returns the DeviceRequestMutation object of the builder.
func (dru *DeviceRequestUpdate) Mutation() *DeviceRequestMutation {
return dru.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) {
var (
err error
affected int
)
if len(dru.hooks) == 0 {
if err = dru.check(); err != nil {
return 0, err
}
affected, err = dru.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*DeviceRequestMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = dru.check(); err != nil {
return 0, err
}
dru.mutation = mutation
affected, err = dru.sqlSave(ctx)
mutation.done = true
return affected, err
})
for i := len(dru.hooks) - 1; i >= 0; i-- {
mut = dru.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, dru.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// SaveX is like Save, but panics if an error occurs.
func (dru *DeviceRequestUpdate) SaveX(ctx context.Context) int {
affected, err := dru.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (dru *DeviceRequestUpdate) Exec(ctx context.Context) error {
_, err := dru.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 {
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 {
if err := devicerequest.UserCodeValidator(v); err != nil {
return &ValidationError{Name: "user_code", err: fmt.Errorf("db: validator failed for field \"user_code\": %w", err)}
}
}
if v, ok := dru.mutation.DeviceCode(); ok {
if err := devicerequest.DeviceCodeValidator(v); err != nil {
return &ValidationError{Name: "device_code", err: fmt.Errorf("db: validator failed for field \"device_code\": %w", err)}
}
}
if v, ok := dru.mutation.ClientID(); ok {
if err := devicerequest.ClientIDValidator(v); err != nil {
return &ValidationError{Name: "client_id", err: fmt.Errorf("db: validator failed for field \"client_id\": %w", err)}
}
}
if v, ok := dru.mutation.ClientSecret(); ok {
if err := devicerequest.ClientSecretValidator(v); err != nil {
return &ValidationError{Name: "client_secret", err: fmt.Errorf("db: validator failed for field \"client_secret\": %w", err)}
}
}
return nil
}
func (dru *DeviceRequestUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: devicerequest.Table,
Columns: devicerequest.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: devicerequest.FieldID,
},
},
}
if ps := dru.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 {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: devicerequest.FieldUserCode,
})
}
if value, ok := dru.mutation.DeviceCode(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: devicerequest.FieldDeviceCode,
})
}
if value, ok := dru.mutation.ClientID(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: devicerequest.FieldClientID,
})
}
if value, ok := dru.mutation.ClientSecret(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: devicerequest.FieldClientSecret,
})
}
if value, ok := dru.mutation.Scopes(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: devicerequest.FieldScopes,
})
}
if dru.mutation.ScopesCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Column: devicerequest.FieldScopes,
})
}
if value, ok := dru.mutation.Expiry(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: devicerequest.FieldExpiry,
})
}
if n, err = sqlgraph.UpdateNodes(ctx, dru.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{devicerequest.Label}
} else if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return 0, err
}
return n, nil
}
// DeviceRequestUpdateOne is the builder for updating a single DeviceRequest entity.
type DeviceRequestUpdateOne struct {
config
fields []string
hooks []Hook
mutation *DeviceRequestMutation
}
// SetUserCode sets the "user_code" field.
func (druo *DeviceRequestUpdateOne) SetUserCode(s string) *DeviceRequestUpdateOne {
druo.mutation.SetUserCode(s)
return druo
}
// SetDeviceCode sets the "device_code" field.
func (druo *DeviceRequestUpdateOne) SetDeviceCode(s string) *DeviceRequestUpdateOne {
druo.mutation.SetDeviceCode(s)
return druo
}
// SetClientID sets the "client_id" field.
func (druo *DeviceRequestUpdateOne) SetClientID(s string) *DeviceRequestUpdateOne {
druo.mutation.SetClientID(s)
return druo
}
// SetClientSecret sets the "client_secret" field.
func (druo *DeviceRequestUpdateOne) SetClientSecret(s string) *DeviceRequestUpdateOne {
druo.mutation.SetClientSecret(s)
return druo
}
// SetScopes sets the "scopes" field.
func (druo *DeviceRequestUpdateOne) SetScopes(s []string) *DeviceRequestUpdateOne {
druo.mutation.SetScopes(s)
return druo
}
// ClearScopes clears the value of the "scopes" field.
func (druo *DeviceRequestUpdateOne) ClearScopes() *DeviceRequestUpdateOne {
druo.mutation.ClearScopes()
return druo
}
// SetExpiry sets the "expiry" field.
func (druo *DeviceRequestUpdateOne) SetExpiry(t time.Time) *DeviceRequestUpdateOne {
druo.mutation.SetExpiry(t)
return druo
}
// Mutation returns the DeviceRequestMutation object of the builder.
func (druo *DeviceRequestUpdateOne) Mutation() *DeviceRequestMutation {
return druo.mutation
}
// 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
}
// Save executes the query and returns the updated DeviceRequest entity.
func (druo *DeviceRequestUpdateOne) Save(ctx context.Context) (*DeviceRequest, error) {
var (
err error
node *DeviceRequest
)
if len(druo.hooks) == 0 {
if err = druo.check(); err != nil {
return nil, err
}
node, err = druo.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*DeviceRequestMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = druo.check(); err != nil {
return nil, err
}
druo.mutation = mutation
node, err = druo.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(druo.hooks) - 1; i >= 0; i-- {
mut = druo.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, druo.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX is like Save, but panics if an error occurs.
func (druo *DeviceRequestUpdateOne) SaveX(ctx context.Context) *DeviceRequest {
node, err := druo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (druo *DeviceRequestUpdateOne) Exec(ctx context.Context) error {
_, err := druo.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 {
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 {
if err := devicerequest.UserCodeValidator(v); err != nil {
return &ValidationError{Name: "user_code", err: fmt.Errorf("db: validator failed for field \"user_code\": %w", err)}
}
}
if v, ok := druo.mutation.DeviceCode(); ok {
if err := devicerequest.DeviceCodeValidator(v); err != nil {
return &ValidationError{Name: "device_code", err: fmt.Errorf("db: validator failed for field \"device_code\": %w", err)}
}
}
if v, ok := druo.mutation.ClientID(); ok {
if err := devicerequest.ClientIDValidator(v); err != nil {
return &ValidationError{Name: "client_id", err: fmt.Errorf("db: validator failed for field \"client_id\": %w", err)}
}
}
if v, ok := druo.mutation.ClientSecret(); ok {
if err := devicerequest.ClientSecretValidator(v); err != nil {
return &ValidationError{Name: "client_secret", err: fmt.Errorf("db: validator failed for field \"client_secret\": %w", err)}
}
}
return nil
}
func (druo *DeviceRequestUpdateOne) sqlSave(ctx context.Context) (_node *DeviceRequest, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: devicerequest.Table,
Columns: devicerequest.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: devicerequest.FieldID,
},
},
}
id, ok := druo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing DeviceRequest.ID for update")}
}
_spec.Node.ID.Value = id
if fields := druo.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 {
if !devicerequest.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
}
if f != devicerequest.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := druo.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 {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: devicerequest.FieldUserCode,
})
}
if value, ok := druo.mutation.DeviceCode(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: devicerequest.FieldDeviceCode,
})
}
if value, ok := druo.mutation.ClientID(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: devicerequest.FieldClientID,
})
}
if value, ok := druo.mutation.ClientSecret(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: devicerequest.FieldClientSecret,
})
}
if value, ok := druo.mutation.Scopes(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: devicerequest.FieldScopes,
})
}
if druo.mutation.ScopesCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Column: devicerequest.FieldScopes,
})
}
if value, ok := druo.mutation.Expiry(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: devicerequest.FieldExpiry,
})
}
_node = &DeviceRequest{config: druo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, druo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{devicerequest.Label}
} else if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return nil, err
}
return _node, nil
}

View file

@ -0,0 +1,156 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"fmt"
"strings"
"time"
"entgo.io/ent/dialect/sql"
"github.com/dexidp/dex/storage/ent/db/devicetoken"
)
// DeviceToken is the model entity for the DeviceToken schema.
type DeviceToken struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// DeviceCode holds the value of the "device_code" field.
DeviceCode string `json:"device_code,omitempty"`
// Status holds the value of the "status" field.
Status string `json:"status,omitempty"`
// Token holds the value of the "token" field.
Token *[]byte `json:"token,omitempty"`
// Expiry holds the value of the "expiry" field.
Expiry time.Time `json:"expiry,omitempty"`
// LastRequest holds the value of the "last_request" field.
LastRequest time.Time `json:"last_request,omitempty"`
// PollInterval holds the value of the "poll_interval" field.
PollInterval int `json:"poll_interval,omitempty"`
}
// scanValues returns the types for scanning values from sql.Rows.
func (*DeviceToken) scanValues(columns []string) ([]interface{}, error) {
values := make([]interface{}, len(columns))
for i := range columns {
switch columns[i] {
case devicetoken.FieldToken:
values[i] = new([]byte)
case devicetoken.FieldID, devicetoken.FieldPollInterval:
values[i] = new(sql.NullInt64)
case devicetoken.FieldDeviceCode, devicetoken.FieldStatus:
values[i] = new(sql.NullString)
case devicetoken.FieldExpiry, devicetoken.FieldLastRequest:
values[i] = new(sql.NullTime)
default:
return nil, fmt.Errorf("unexpected column %q for type DeviceToken", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the DeviceToken fields.
func (dt *DeviceToken) assignValues(columns []string, values []interface{}) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case devicetoken.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
dt.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
}
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
}
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
}
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
}
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
}
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)
}
}
}
return nil
}
// 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 (&DeviceTokenClient{config: dt.config}).UpdateOne(dt)
}
// 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)
if !ok {
panic("db: DeviceToken is not a transactional entity")
}
dt.config.driver = tx.drv
return dt
}
// String implements the fmt.Stringer.
func (dt *DeviceToken) String() string {
var builder strings.Builder
builder.WriteString("DeviceToken(")
builder.WriteString(fmt.Sprintf("id=%v", dt.ID))
builder.WriteString(", device_code=")
builder.WriteString(dt.DeviceCode)
builder.WriteString(", status=")
builder.WriteString(dt.Status)
if v := dt.Token; v != nil {
builder.WriteString(", token=")
builder.WriteString(fmt.Sprintf("%v", *v))
}
builder.WriteString(", expiry=")
builder.WriteString(dt.Expiry.Format(time.ANSIC))
builder.WriteString(", last_request=")
builder.WriteString(dt.LastRequest.Format(time.ANSIC))
builder.WriteString(", poll_interval=")
builder.WriteString(fmt.Sprintf("%v", dt.PollInterval))
builder.WriteByte(')')
return builder.String()
}
// DeviceTokens is a parsable slice of DeviceToken.
type DeviceTokens []*DeviceToken
func (dt DeviceTokens) config(cfg config) {
for _i := range dt {
dt[_i].config = cfg
}
}

View file

@ -0,0 +1,52 @@
// Code generated by entc, DO NOT EDIT.
package devicetoken
const (
// Label holds the string label denoting the devicetoken type in the database.
Label = "device_token"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldDeviceCode holds the string denoting the device_code field in the database.
FieldDeviceCode = "device_code"
// FieldStatus holds the string denoting the status field in the database.
FieldStatus = "status"
// FieldToken holds the string denoting the token field in the database.
FieldToken = "token"
// FieldExpiry holds the string denoting the expiry field in the database.
FieldExpiry = "expiry"
// FieldLastRequest holds the string denoting the last_request field in the database.
FieldLastRequest = "last_request"
// FieldPollInterval holds the string denoting the poll_interval field in the database.
FieldPollInterval = "poll_interval"
// Table holds the table name of the devicetoken in the database.
Table = "device_tokens"
)
// Columns holds all SQL columns for devicetoken fields.
var Columns = []string{
FieldID,
FieldDeviceCode,
FieldStatus,
FieldToken,
FieldExpiry,
FieldLastRequest,
FieldPollInterval,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// DeviceCodeValidator is a validator for the "device_code" field. It is called by the builders before save.
DeviceCodeValidator func(string) error
// StatusValidator is a validator for the "status" field. It is called by the builders before save.
StatusValidator func(string) error
)

View file

@ -0,0 +1,707 @@
// Code generated by entc, DO NOT EDIT.
package devicetoken
import (
"time"
"entgo.io/ent/dialect/sql"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldID), id))
})
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.In(s.C(FieldID), v...))
})
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.NotIn(s.C(FieldID), v...))
})
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldID), id))
})
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldID), id))
})
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldID), id))
})
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldID), id))
})
}
// DeviceCode applies equality check predicate on the "device_code" field. It's identical to DeviceCodeEQ.
func DeviceCode(v string) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldDeviceCode), v))
})
}
// Status applies equality check predicate on the "status" field. It's identical to StatusEQ.
func Status(v string) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldStatus), v))
})
}
// Token applies equality check predicate on the "token" field. It's identical to TokenEQ.
func Token(v []byte) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldToken), v))
})
}
// Expiry applies equality check predicate on the "expiry" field. It's identical to ExpiryEQ.
func Expiry(v time.Time) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldExpiry), v))
})
}
// LastRequest applies equality check predicate on the "last_request" field. It's identical to LastRequestEQ.
func LastRequest(v time.Time) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldLastRequest), v))
})
}
// PollInterval applies equality check predicate on the "poll_interval" field. It's identical to PollIntervalEQ.
func PollInterval(v int) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldPollInterval), v))
})
}
// DeviceCodeEQ applies the EQ predicate on the "device_code" field.
func DeviceCodeEQ(v string) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldDeviceCode), v))
})
}
// DeviceCodeNEQ applies the NEQ predicate on the "device_code" field.
func DeviceCodeNEQ(v string) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldDeviceCode), v))
})
}
// DeviceCodeIn applies the In predicate on the "device_code" field.
func DeviceCodeIn(vs ...string) predicate.DeviceToken {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DeviceToken(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldDeviceCode), v...))
})
}
// DeviceCodeNotIn applies the NotIn predicate on the "device_code" field.
func DeviceCodeNotIn(vs ...string) predicate.DeviceToken {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DeviceToken(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldDeviceCode), v...))
})
}
// DeviceCodeGT applies the GT predicate on the "device_code" field.
func DeviceCodeGT(v string) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldDeviceCode), v))
})
}
// DeviceCodeGTE applies the GTE predicate on the "device_code" field.
func DeviceCodeGTE(v string) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldDeviceCode), v))
})
}
// DeviceCodeLT applies the LT predicate on the "device_code" field.
func DeviceCodeLT(v string) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldDeviceCode), v))
})
}
// DeviceCodeLTE applies the LTE predicate on the "device_code" field.
func DeviceCodeLTE(v string) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldDeviceCode), v))
})
}
// DeviceCodeContains applies the Contains predicate on the "device_code" field.
func DeviceCodeContains(v string) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldDeviceCode), v))
})
}
// DeviceCodeHasPrefix applies the HasPrefix predicate on the "device_code" field.
func DeviceCodeHasPrefix(v string) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldDeviceCode), v))
})
}
// DeviceCodeHasSuffix applies the HasSuffix predicate on the "device_code" field.
func DeviceCodeHasSuffix(v string) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldDeviceCode), v))
})
}
// DeviceCodeEqualFold applies the EqualFold predicate on the "device_code" field.
func DeviceCodeEqualFold(v string) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldDeviceCode), v))
})
}
// DeviceCodeContainsFold applies the ContainsFold predicate on the "device_code" field.
func DeviceCodeContainsFold(v string) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldDeviceCode), v))
})
}
// StatusEQ applies the EQ predicate on the "status" field.
func StatusEQ(v string) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldStatus), v))
})
}
// StatusNEQ applies the NEQ predicate on the "status" field.
func StatusNEQ(v string) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldStatus), v))
})
}
// StatusIn applies the In predicate on the "status" field.
func StatusIn(vs ...string) predicate.DeviceToken {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DeviceToken(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldStatus), v...))
})
}
// StatusNotIn applies the NotIn predicate on the "status" field.
func StatusNotIn(vs ...string) predicate.DeviceToken {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DeviceToken(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldStatus), v...))
})
}
// StatusGT applies the GT predicate on the "status" field.
func StatusGT(v string) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldStatus), v))
})
}
// StatusGTE applies the GTE predicate on the "status" field.
func StatusGTE(v string) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldStatus), v))
})
}
// StatusLT applies the LT predicate on the "status" field.
func StatusLT(v string) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldStatus), v))
})
}
// StatusLTE applies the LTE predicate on the "status" field.
func StatusLTE(v string) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldStatus), v))
})
}
// StatusContains applies the Contains predicate on the "status" field.
func StatusContains(v string) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldStatus), v))
})
}
// StatusHasPrefix applies the HasPrefix predicate on the "status" field.
func StatusHasPrefix(v string) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldStatus), v))
})
}
// StatusHasSuffix applies the HasSuffix predicate on the "status" field.
func StatusHasSuffix(v string) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldStatus), v))
})
}
// StatusEqualFold applies the EqualFold predicate on the "status" field.
func StatusEqualFold(v string) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldStatus), v))
})
}
// StatusContainsFold applies the ContainsFold predicate on the "status" field.
func StatusContainsFold(v string) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldStatus), v))
})
}
// TokenEQ applies the EQ predicate on the "token" field.
func TokenEQ(v []byte) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldToken), v))
})
}
// TokenNEQ applies the NEQ predicate on the "token" field.
func TokenNEQ(v []byte) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldToken), v))
})
}
// TokenIn applies the In predicate on the "token" field.
func TokenIn(vs ...[]byte) predicate.DeviceToken {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DeviceToken(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldToken), v...))
})
}
// TokenNotIn applies the NotIn predicate on the "token" field.
func TokenNotIn(vs ...[]byte) predicate.DeviceToken {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DeviceToken(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldToken), v...))
})
}
// TokenGT applies the GT predicate on the "token" field.
func TokenGT(v []byte) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldToken), v))
})
}
// TokenGTE applies the GTE predicate on the "token" field.
func TokenGTE(v []byte) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldToken), v))
})
}
// TokenLT applies the LT predicate on the "token" field.
func TokenLT(v []byte) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldToken), v))
})
}
// TokenLTE applies the LTE predicate on the "token" field.
func TokenLTE(v []byte) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldToken), v))
})
}
// TokenIsNil applies the IsNil predicate on the "token" field.
func TokenIsNil() predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldToken)))
})
}
// TokenNotNil applies the NotNil predicate on the "token" field.
func TokenNotNil() predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.NotNull(s.C(FieldToken)))
})
}
// ExpiryEQ applies the EQ predicate on the "expiry" field.
func ExpiryEQ(v time.Time) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldExpiry), v))
})
}
// ExpiryNEQ applies the NEQ predicate on the "expiry" field.
func ExpiryNEQ(v time.Time) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldExpiry), v))
})
}
// ExpiryIn applies the In predicate on the "expiry" field.
func ExpiryIn(vs ...time.Time) predicate.DeviceToken {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DeviceToken(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldExpiry), v...))
})
}
// ExpiryNotIn applies the NotIn predicate on the "expiry" field.
func ExpiryNotIn(vs ...time.Time) predicate.DeviceToken {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DeviceToken(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldExpiry), v...))
})
}
// ExpiryGT applies the GT predicate on the "expiry" field.
func ExpiryGT(v time.Time) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldExpiry), v))
})
}
// ExpiryGTE applies the GTE predicate on the "expiry" field.
func ExpiryGTE(v time.Time) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldExpiry), v))
})
}
// ExpiryLT applies the LT predicate on the "expiry" field.
func ExpiryLT(v time.Time) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldExpiry), v))
})
}
// ExpiryLTE applies the LTE predicate on the "expiry" field.
func ExpiryLTE(v time.Time) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldExpiry), v))
})
}
// LastRequestEQ applies the EQ predicate on the "last_request" field.
func LastRequestEQ(v time.Time) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldLastRequest), v))
})
}
// LastRequestNEQ applies the NEQ predicate on the "last_request" field.
func LastRequestNEQ(v time.Time) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldLastRequest), v))
})
}
// LastRequestIn applies the In predicate on the "last_request" field.
func LastRequestIn(vs ...time.Time) predicate.DeviceToken {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DeviceToken(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldLastRequest), v...))
})
}
// LastRequestNotIn applies the NotIn predicate on the "last_request" field.
func LastRequestNotIn(vs ...time.Time) predicate.DeviceToken {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DeviceToken(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldLastRequest), v...))
})
}
// LastRequestGT applies the GT predicate on the "last_request" field.
func LastRequestGT(v time.Time) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldLastRequest), v))
})
}
// LastRequestGTE applies the GTE predicate on the "last_request" field.
func LastRequestGTE(v time.Time) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldLastRequest), v))
})
}
// LastRequestLT applies the LT predicate on the "last_request" field.
func LastRequestLT(v time.Time) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldLastRequest), v))
})
}
// LastRequestLTE applies the LTE predicate on the "last_request" field.
func LastRequestLTE(v time.Time) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldLastRequest), v))
})
}
// PollIntervalEQ applies the EQ predicate on the "poll_interval" field.
func PollIntervalEQ(v int) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldPollInterval), v))
})
}
// PollIntervalNEQ applies the NEQ predicate on the "poll_interval" field.
func PollIntervalNEQ(v int) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldPollInterval), v))
})
}
// PollIntervalIn applies the In predicate on the "poll_interval" field.
func PollIntervalIn(vs ...int) predicate.DeviceToken {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DeviceToken(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldPollInterval), v...))
})
}
// PollIntervalNotIn applies the NotIn predicate on the "poll_interval" field.
func PollIntervalNotIn(vs ...int) predicate.DeviceToken {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.DeviceToken(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldPollInterval), v...))
})
}
// PollIntervalGT applies the GT predicate on the "poll_interval" field.
func PollIntervalGT(v int) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldPollInterval), v))
})
}
// PollIntervalGTE applies the GTE predicate on the "poll_interval" field.
func PollIntervalGTE(v int) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldPollInterval), v))
})
}
// PollIntervalLT applies the LT predicate on the "poll_interval" field.
func PollIntervalLT(v int) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldPollInterval), v))
})
}
// PollIntervalLTE applies the LTE predicate on the "poll_interval" field.
func PollIntervalLTE(v int) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldPollInterval), v))
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.DeviceToken) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for _, p := range predicates {
p(s1)
}
s.Where(s1.P())
})
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.DeviceToken) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for i, p := range predicates {
if i > 0 {
s1.Or()
}
p(s1)
}
s.Where(s1.P())
})
}
// Not applies the not operator on the given predicate.
func Not(p predicate.DeviceToken) predicate.DeviceToken {
return predicate.DeviceToken(func(s *sql.Selector) {
p(s.Not())
})
}

View file

@ -0,0 +1,277 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/devicetoken"
)
// DeviceTokenCreate is the builder for creating a DeviceToken entity.
type DeviceTokenCreate struct {
config
mutation *DeviceTokenMutation
hooks []Hook
}
// SetDeviceCode sets the "device_code" field.
func (dtc *DeviceTokenCreate) SetDeviceCode(s string) *DeviceTokenCreate {
dtc.mutation.SetDeviceCode(s)
return dtc
}
// SetStatus sets the "status" field.
func (dtc *DeviceTokenCreate) SetStatus(s string) *DeviceTokenCreate {
dtc.mutation.SetStatus(s)
return dtc
}
// SetToken sets the "token" field.
func (dtc *DeviceTokenCreate) SetToken(b []byte) *DeviceTokenCreate {
dtc.mutation.SetToken(b)
return dtc
}
// SetExpiry sets the "expiry" field.
func (dtc *DeviceTokenCreate) SetExpiry(t time.Time) *DeviceTokenCreate {
dtc.mutation.SetExpiry(t)
return dtc
}
// SetLastRequest sets the "last_request" field.
func (dtc *DeviceTokenCreate) SetLastRequest(t time.Time) *DeviceTokenCreate {
dtc.mutation.SetLastRequest(t)
return dtc
}
// SetPollInterval sets the "poll_interval" field.
func (dtc *DeviceTokenCreate) SetPollInterval(i int) *DeviceTokenCreate {
dtc.mutation.SetPollInterval(i)
return dtc
}
// Mutation returns the DeviceTokenMutation object of the builder.
func (dtc *DeviceTokenCreate) Mutation() *DeviceTokenMutation {
return dtc.mutation
}
// Save creates the DeviceToken in the database.
func (dtc *DeviceTokenCreate) Save(ctx context.Context) (*DeviceToken, error) {
var (
err error
node *DeviceToken
)
if len(dtc.hooks) == 0 {
if err = dtc.check(); err != nil {
return nil, err
}
node, err = dtc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*DeviceTokenMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = dtc.check(); err != nil {
return nil, err
}
dtc.mutation = mutation
node, err = dtc.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(dtc.hooks) - 1; i >= 0; i-- {
mut = dtc.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, dtc.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (dtc *DeviceTokenCreate) SaveX(ctx context.Context) *DeviceToken {
v, err := dtc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// check runs all checks and user-defined validators on the builder.
func (dtc *DeviceTokenCreate) check() error {
if _, ok := dtc.mutation.DeviceCode(); !ok {
return &ValidationError{Name: "device_code", err: errors.New("db: missing required field \"device_code\"")}
}
if v, ok := dtc.mutation.DeviceCode(); ok {
if err := devicetoken.DeviceCodeValidator(v); err != nil {
return &ValidationError{Name: "device_code", err: fmt.Errorf("db: validator failed for field \"device_code\": %w", err)}
}
}
if _, ok := dtc.mutation.Status(); !ok {
return &ValidationError{Name: "status", err: errors.New("db: missing required field \"status\"")}
}
if v, ok := dtc.mutation.Status(); ok {
if err := devicetoken.StatusValidator(v); err != nil {
return &ValidationError{Name: "status", err: fmt.Errorf("db: validator failed for field \"status\": %w", err)}
}
}
if _, ok := dtc.mutation.Expiry(); !ok {
return &ValidationError{Name: "expiry", err: errors.New("db: missing required field \"expiry\"")}
}
if _, ok := dtc.mutation.LastRequest(); !ok {
return &ValidationError{Name: "last_request", err: errors.New("db: missing required field \"last_request\"")}
}
if _, ok := dtc.mutation.PollInterval(); !ok {
return &ValidationError{Name: "poll_interval", err: errors.New("db: missing required field \"poll_interval\"")}
}
return nil
}
func (dtc *DeviceTokenCreate) sqlSave(ctx context.Context) (*DeviceToken, error) {
_node, _spec := dtc.createSpec()
if err := sqlgraph.CreateNode(ctx, dtc.driver, _spec); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
return _node, nil
}
func (dtc *DeviceTokenCreate) createSpec() (*DeviceToken, *sqlgraph.CreateSpec) {
var (
_node = &DeviceToken{config: dtc.config}
_spec = &sqlgraph.CreateSpec{
Table: devicetoken.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: devicetoken.FieldID,
},
}
)
if value, ok := dtc.mutation.DeviceCode(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: devicetoken.FieldDeviceCode,
})
_node.DeviceCode = value
}
if value, ok := dtc.mutation.Status(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: devicetoken.FieldStatus,
})
_node.Status = value
}
if value, ok := dtc.mutation.Token(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: devicetoken.FieldToken,
})
_node.Token = &value
}
if value, ok := dtc.mutation.Expiry(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: devicetoken.FieldExpiry,
})
_node.Expiry = value
}
if value, ok := dtc.mutation.LastRequest(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: devicetoken.FieldLastRequest,
})
_node.LastRequest = value
}
if value, ok := dtc.mutation.PollInterval(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: devicetoken.FieldPollInterval,
})
_node.PollInterval = value
}
return _node, _spec
}
// DeviceTokenCreateBulk is the builder for creating many DeviceToken entities in bulk.
type DeviceTokenCreateBulk struct {
config
builders []*DeviceTokenCreate
}
// Save creates the DeviceToken entities in the database.
func (dtcb *DeviceTokenCreateBulk) Save(ctx context.Context) ([]*DeviceToken, error) {
specs := make([]*sqlgraph.CreateSpec, len(dtcb.builders))
nodes := make([]*DeviceToken, len(dtcb.builders))
mutators := make([]Mutator, len(dtcb.builders))
for i := range dtcb.builders {
func(i int, root context.Context) {
builder := dtcb.builders[i]
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*DeviceTokenMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
nodes[i], specs[i] = builder.createSpec()
var err error
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, dtcb.builders[i+1].mutation)
} else {
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, dtcb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
}
}
mutation.done = true
if err != nil {
return nil, err
}
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, dtcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (dtcb *DeviceTokenCreateBulk) SaveX(ctx context.Context) []*DeviceToken {
v, err := dtcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}

View file

@ -0,0 +1,108 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/devicetoken"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// DeviceTokenDelete is the builder for deleting a DeviceToken entity.
type DeviceTokenDelete struct {
config
hooks []Hook
mutation *DeviceTokenMutation
}
// Where adds a new predicate to the DeviceTokenDelete builder.
func (dtd *DeviceTokenDelete) Where(ps ...predicate.DeviceToken) *DeviceTokenDelete {
dtd.mutation.predicates = append(dtd.mutation.predicates, ps...)
return dtd
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (dtd *DeviceTokenDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(dtd.hooks) == 0 {
affected, err = dtd.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*DeviceTokenMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
dtd.mutation = mutation
affected, err = dtd.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(dtd.hooks) - 1; i >= 0; i-- {
mut = dtd.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, dtd.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (dtd *DeviceTokenDelete) ExecX(ctx context.Context) int {
n, err := dtd.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (dtd *DeviceTokenDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: devicetoken.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: devicetoken.FieldID,
},
},
}
if ps := dtd.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return sqlgraph.DeleteNodes(ctx, dtd.driver, _spec)
}
// DeviceTokenDeleteOne is the builder for deleting a single DeviceToken entity.
type DeviceTokenDeleteOne struct {
dtd *DeviceTokenDelete
}
// Exec executes the deletion query.
func (dtdo *DeviceTokenDeleteOne) Exec(ctx context.Context) error {
n, err := dtdo.dtd.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{devicetoken.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (dtdo *DeviceTokenDeleteOne) ExecX(ctx context.Context) {
dtdo.dtd.ExecX(ctx)
}

View file

@ -0,0 +1,906 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"errors"
"fmt"
"math"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/devicetoken"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// DeviceTokenQuery is the builder for querying DeviceToken entities.
type DeviceTokenQuery struct {
config
limit *int
offset *int
unique *bool
order []OrderFunc
fields []string
predicates []predicate.DeviceToken
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// 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
}
// Limit adds a limit step to the query.
func (dtq *DeviceTokenQuery) Limit(limit int) *DeviceTokenQuery {
dtq.limit = &limit
return dtq
}
// Offset adds an offset step to the query.
func (dtq *DeviceTokenQuery) Offset(offset int) *DeviceTokenQuery {
dtq.offset = &offset
return dtq
}
// 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.unique = &unique
return dtq
}
// Order adds an order step to the query.
func (dtq *DeviceTokenQuery) Order(o ...OrderFunc) *DeviceTokenQuery {
dtq.order = append(dtq.order, o...)
return dtq
}
// 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(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{devicetoken.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (dtq *DeviceTokenQuery) FirstX(ctx context.Context) *DeviceToken {
node, err := dtq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// 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) {
var ids []int
if ids, err = dtq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{devicetoken.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (dtq *DeviceTokenQuery) FirstIDX(ctx context.Context) int {
id, err := dtq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single DeviceToken entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when exactly one DeviceToken entity is not 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(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{devicetoken.Label}
default:
return nil, &NotSingularError{devicetoken.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (dtq *DeviceTokenQuery) OnlyX(ctx context.Context) *DeviceToken {
node, err := dtq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only DeviceToken ID in the query.
// Returns a *NotSingularError when exactly one DeviceToken ID is not found.
// Returns a *NotFoundError when no entities are found.
func (dtq *DeviceTokenQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = dtq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{devicetoken.Label}
default:
err = &NotSingularError{devicetoken.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (dtq *DeviceTokenQuery) OnlyIDX(ctx context.Context) int {
id, err := dtq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of DeviceTokens.
func (dtq *DeviceTokenQuery) All(ctx context.Context) ([]*DeviceToken, error) {
if err := dtq.prepareQuery(ctx); err != nil {
return nil, err
}
return dtq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (dtq *DeviceTokenQuery) AllX(ctx context.Context) []*DeviceToken {
nodes, err := dtq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of DeviceToken IDs.
func (dtq *DeviceTokenQuery) IDs(ctx context.Context) ([]int, error) {
var ids []int
if err := dtq.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)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (dtq *DeviceTokenQuery) Count(ctx context.Context) (int, error) {
if err := dtq.prepareQuery(ctx); err != nil {
return 0, err
}
return dtq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (dtq *DeviceTokenQuery) CountX(ctx context.Context) int {
count, err := dtq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (dtq *DeviceTokenQuery) Exist(ctx context.Context) (bool, error) {
if err := dtq.prepareQuery(ctx); err != nil {
return false, err
}
return dtq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (dtq *DeviceTokenQuery) ExistX(ctx context.Context) bool {
exist, err := dtq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// 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 {
return nil
}
return &DeviceTokenQuery{
config: dtq.config,
limit: dtq.limit,
offset: dtq.offset,
order: append([]OrderFunc{}, dtq.order...),
predicates: append([]predicate.DeviceToken{}, dtq.predicates...),
// clone intermediate query.
sql: dtq.sql.Clone(),
path: dtq.path,
}
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// DeviceCode string `json:"device_code,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.DeviceToken.Query().
// GroupBy(devicetoken.FieldDeviceCode).
// Aggregate(db.Count()).
// Scan(ctx, &v)
//
func (dtq *DeviceTokenQuery) GroupBy(field string, fields ...string) *DeviceTokenGroupBy {
group := &DeviceTokenGroupBy{config: dtq.config}
group.fields = append([]string{field}, fields...)
group.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := dtq.prepareQuery(ctx); err != nil {
return nil, err
}
return dtq.sqlQuery(ctx), nil
}
return group
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// DeviceCode string `json:"device_code,omitempty"`
// }
//
// client.DeviceToken.Query().
// Select(devicetoken.FieldDeviceCode).
// Scan(ctx, &v)
//
func (dtq *DeviceTokenQuery) Select(field string, fields ...string) *DeviceTokenSelect {
dtq.fields = append([]string{field}, fields...)
return &DeviceTokenSelect{DeviceTokenQuery: dtq}
}
func (dtq *DeviceTokenQuery) prepareQuery(ctx context.Context) error {
for _, f := range dtq.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 err != nil {
return err
}
dtq.sql = prev
}
return nil
}
func (dtq *DeviceTokenQuery) sqlAll(ctx context.Context) ([]*DeviceToken, error) {
var (
nodes = []*DeviceToken{}
_spec = dtq.querySpec()
)
_spec.ScanValues = func(columns []string) ([]interface{}, error) {
node := &DeviceToken{config: dtq.config}
nodes = append(nodes, node)
return node.scanValues(columns)
}
_spec.Assign = func(columns []string, values []interface{}) error {
if len(nodes) == 0 {
return fmt.Errorf("db: Assign called without calling ScanValues")
}
node := nodes[len(nodes)-1]
return node.assignValues(columns, values)
}
if err := sqlgraph.QueryNodes(ctx, dtq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (dtq *DeviceTokenQuery) sqlCount(ctx context.Context) (int, error) {
_spec := dtq.querySpec()
return sqlgraph.CountNodes(ctx, dtq.driver, _spec)
}
func (dtq *DeviceTokenQuery) sqlExist(ctx context.Context) (bool, error) {
n, err := dtq.sqlCount(ctx)
if err != nil {
return false, fmt.Errorf("db: check existence: %w", err)
}
return n > 0, nil
}
func (dtq *DeviceTokenQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: devicetoken.Table,
Columns: devicetoken.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: devicetoken.FieldID,
},
},
From: dtq.sql,
Unique: true,
}
if unique := dtq.unique; unique != nil {
_spec.Unique = *unique
}
if fields := dtq.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 {
if fields[i] != devicetoken.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := dtq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := dtq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := dtq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := dtq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (dtq *DeviceTokenQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(dtq.driver.Dialect())
t1 := builder.Table(devicetoken.Table)
selector := builder.Select(t1.Columns(devicetoken.Columns...)...).From(t1)
if dtq.sql != nil {
selector = dtq.sql
selector.Select(selector.Columns(devicetoken.Columns...)...)
}
for _, p := range dtq.predicates {
p(selector)
}
for _, p := range dtq.order {
p(selector)
}
if offset := dtq.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.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// DeviceTokenGroupBy is the group-by builder for DeviceToken entities.
type DeviceTokenGroupBy struct {
config
fields []string
fns []AggregateFunc
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Aggregate adds the given aggregation functions to the group-by query.
func (dtgb *DeviceTokenGroupBy) Aggregate(fns ...AggregateFunc) *DeviceTokenGroupBy {
dtgb.fns = append(dtgb.fns, fns...)
return dtgb
}
// Scan applies the group-by query and scans the result into the given value.
func (dtgb *DeviceTokenGroupBy) Scan(ctx context.Context, v interface{}) error {
query, err := dtgb.path(ctx)
if err != nil {
return err
}
dtgb.sql = query
return dtgb.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (dtgb *DeviceTokenGroupBy) ScanX(ctx context.Context, v interface{}) {
if err := dtgb.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from group-by.
// It is only allowed when executing a group-by query with one field.
func (dtgb *DeviceTokenGroupBy) Strings(ctx context.Context) ([]string, error) {
if len(dtgb.fields) > 1 {
return nil, errors.New("db: DeviceTokenGroupBy.Strings is not achievable when grouping more than 1 field")
}
var v []string
if err := dtgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (dtgb *DeviceTokenGroupBy) StringsX(ctx context.Context) []string {
v, err := dtgb.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (dtgb *DeviceTokenGroupBy) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = dtgb.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{devicetoken.Label}
default:
err = fmt.Errorf("db: DeviceTokenGroupBy.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (dtgb *DeviceTokenGroupBy) StringX(ctx context.Context) string {
v, err := dtgb.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from group-by.
// It is only allowed when executing a group-by query with one field.
func (dtgb *DeviceTokenGroupBy) Ints(ctx context.Context) ([]int, error) {
if len(dtgb.fields) > 1 {
return nil, errors.New("db: DeviceTokenGroupBy.Ints is not achievable when grouping more than 1 field")
}
var v []int
if err := dtgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (dtgb *DeviceTokenGroupBy) IntsX(ctx context.Context) []int {
v, err := dtgb.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (dtgb *DeviceTokenGroupBy) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = dtgb.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{devicetoken.Label}
default:
err = fmt.Errorf("db: DeviceTokenGroupBy.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (dtgb *DeviceTokenGroupBy) IntX(ctx context.Context) int {
v, err := dtgb.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from group-by.
// It is only allowed when executing a group-by query with one field.
func (dtgb *DeviceTokenGroupBy) Float64s(ctx context.Context) ([]float64, error) {
if len(dtgb.fields) > 1 {
return nil, errors.New("db: DeviceTokenGroupBy.Float64s is not achievable when grouping more than 1 field")
}
var v []float64
if err := dtgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (dtgb *DeviceTokenGroupBy) Float64sX(ctx context.Context) []float64 {
v, err := dtgb.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (dtgb *DeviceTokenGroupBy) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = dtgb.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{devicetoken.Label}
default:
err = fmt.Errorf("db: DeviceTokenGroupBy.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (dtgb *DeviceTokenGroupBy) Float64X(ctx context.Context) float64 {
v, err := dtgb.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from group-by.
// It is only allowed when executing a group-by query with one field.
func (dtgb *DeviceTokenGroupBy) Bools(ctx context.Context) ([]bool, error) {
if len(dtgb.fields) > 1 {
return nil, errors.New("db: DeviceTokenGroupBy.Bools is not achievable when grouping more than 1 field")
}
var v []bool
if err := dtgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (dtgb *DeviceTokenGroupBy) BoolsX(ctx context.Context) []bool {
v, err := dtgb.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (dtgb *DeviceTokenGroupBy) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = dtgb.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{devicetoken.Label}
default:
err = fmt.Errorf("db: DeviceTokenGroupBy.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (dtgb *DeviceTokenGroupBy) BoolX(ctx context.Context) bool {
v, err := dtgb.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
func (dtgb *DeviceTokenGroupBy) sqlScan(ctx context.Context, v interface{}) error {
for _, f := range dtgb.fields {
if !devicetoken.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := dtgb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := dtgb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (dtgb *DeviceTokenGroupBy) sqlQuery() *sql.Selector {
selector := dtgb.sql
columns := make([]string, 0, len(dtgb.fields)+len(dtgb.fns))
columns = append(columns, dtgb.fields...)
for _, fn := range dtgb.fns {
columns = append(columns, fn(selector))
}
return selector.Select(columns...).GroupBy(dtgb.fields...)
}
// DeviceTokenSelect is the builder for selecting fields of DeviceToken entities.
type DeviceTokenSelect struct {
*DeviceTokenQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
}
// Scan applies the selector query and scans the result into the given value.
func (dts *DeviceTokenSelect) Scan(ctx context.Context, v interface{}) error {
if err := dts.prepareQuery(ctx); err != nil {
return err
}
dts.sql = dts.DeviceTokenQuery.sqlQuery(ctx)
return dts.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (dts *DeviceTokenSelect) ScanX(ctx context.Context, v interface{}) {
if err := dts.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from a selector. It is only allowed when selecting one field.
func (dts *DeviceTokenSelect) Strings(ctx context.Context) ([]string, error) {
if len(dts.fields) > 1 {
return nil, errors.New("db: DeviceTokenSelect.Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := dts.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (dts *DeviceTokenSelect) StringsX(ctx context.Context) []string {
v, err := dts.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a selector. It is only allowed when selecting one field.
func (dts *DeviceTokenSelect) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = dts.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{devicetoken.Label}
default:
err = fmt.Errorf("db: DeviceTokenSelect.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (dts *DeviceTokenSelect) StringX(ctx context.Context) string {
v, err := dts.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from a selector. It is only allowed when selecting one field.
func (dts *DeviceTokenSelect) Ints(ctx context.Context) ([]int, error) {
if len(dts.fields) > 1 {
return nil, errors.New("db: DeviceTokenSelect.Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := dts.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (dts *DeviceTokenSelect) IntsX(ctx context.Context) []int {
v, err := dts.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a selector. It is only allowed when selecting one field.
func (dts *DeviceTokenSelect) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = dts.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{devicetoken.Label}
default:
err = fmt.Errorf("db: DeviceTokenSelect.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (dts *DeviceTokenSelect) IntX(ctx context.Context) int {
v, err := dts.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
func (dts *DeviceTokenSelect) Float64s(ctx context.Context) ([]float64, error) {
if len(dts.fields) > 1 {
return nil, errors.New("db: DeviceTokenSelect.Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := dts.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (dts *DeviceTokenSelect) Float64sX(ctx context.Context) []float64 {
v, err := dts.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
func (dts *DeviceTokenSelect) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = dts.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{devicetoken.Label}
default:
err = fmt.Errorf("db: DeviceTokenSelect.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (dts *DeviceTokenSelect) Float64X(ctx context.Context) float64 {
v, err := dts.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from a selector. It is only allowed when selecting one field.
func (dts *DeviceTokenSelect) Bools(ctx context.Context) ([]bool, error) {
if len(dts.fields) > 1 {
return nil, errors.New("db: DeviceTokenSelect.Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := dts.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (dts *DeviceTokenSelect) BoolsX(ctx context.Context) []bool {
v, err := dts.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a selector. It is only allowed when selecting one field.
func (dts *DeviceTokenSelect) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = dts.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{devicetoken.Label}
default:
err = fmt.Errorf("db: DeviceTokenSelect.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (dts *DeviceTokenSelect) BoolX(ctx context.Context) bool {
v, err := dts.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
func (dts *DeviceTokenSelect) sqlScan(ctx context.Context, v interface{}) error {
rows := &sql.Rows{}
query, args := dts.sqlQuery().Query()
if err := dts.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (dts *DeviceTokenSelect) sqlQuery() sql.Querier {
selector := dts.sql
selector.Select(selector.Columns(dts.fields...)...)
return selector
}

View file

@ -0,0 +1,483 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"fmt"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/devicetoken"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// DeviceTokenUpdate is the builder for updating DeviceToken entities.
type DeviceTokenUpdate struct {
config
hooks []Hook
mutation *DeviceTokenMutation
}
// Where adds a new predicate for the DeviceTokenUpdate builder.
func (dtu *DeviceTokenUpdate) Where(ps ...predicate.DeviceToken) *DeviceTokenUpdate {
dtu.mutation.predicates = append(dtu.mutation.predicates, ps...)
return dtu
}
// SetDeviceCode sets the "device_code" field.
func (dtu *DeviceTokenUpdate) SetDeviceCode(s string) *DeviceTokenUpdate {
dtu.mutation.SetDeviceCode(s)
return dtu
}
// SetStatus sets the "status" field.
func (dtu *DeviceTokenUpdate) SetStatus(s string) *DeviceTokenUpdate {
dtu.mutation.SetStatus(s)
return dtu
}
// SetToken sets the "token" field.
func (dtu *DeviceTokenUpdate) SetToken(b []byte) *DeviceTokenUpdate {
dtu.mutation.SetToken(b)
return dtu
}
// ClearToken clears the value of the "token" field.
func (dtu *DeviceTokenUpdate) ClearToken() *DeviceTokenUpdate {
dtu.mutation.ClearToken()
return dtu
}
// SetExpiry sets the "expiry" field.
func (dtu *DeviceTokenUpdate) SetExpiry(t time.Time) *DeviceTokenUpdate {
dtu.mutation.SetExpiry(t)
return dtu
}
// SetLastRequest sets the "last_request" field.
func (dtu *DeviceTokenUpdate) SetLastRequest(t time.Time) *DeviceTokenUpdate {
dtu.mutation.SetLastRequest(t)
return dtu
}
// SetPollInterval sets the "poll_interval" field.
func (dtu *DeviceTokenUpdate) SetPollInterval(i int) *DeviceTokenUpdate {
dtu.mutation.ResetPollInterval()
dtu.mutation.SetPollInterval(i)
return dtu
}
// AddPollInterval adds i to the "poll_interval" field.
func (dtu *DeviceTokenUpdate) AddPollInterval(i int) *DeviceTokenUpdate {
dtu.mutation.AddPollInterval(i)
return dtu
}
// Mutation returns the DeviceTokenMutation object of the builder.
func (dtu *DeviceTokenUpdate) Mutation() *DeviceTokenMutation {
return dtu.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) {
var (
err error
affected int
)
if len(dtu.hooks) == 0 {
if err = dtu.check(); err != nil {
return 0, err
}
affected, err = dtu.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*DeviceTokenMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = dtu.check(); err != nil {
return 0, err
}
dtu.mutation = mutation
affected, err = dtu.sqlSave(ctx)
mutation.done = true
return affected, err
})
for i := len(dtu.hooks) - 1; i >= 0; i-- {
mut = dtu.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, dtu.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// SaveX is like Save, but panics if an error occurs.
func (dtu *DeviceTokenUpdate) SaveX(ctx context.Context) int {
affected, err := dtu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (dtu *DeviceTokenUpdate) Exec(ctx context.Context) error {
_, err := dtu.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 {
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 {
if err := devicetoken.DeviceCodeValidator(v); err != nil {
return &ValidationError{Name: "device_code", err: fmt.Errorf("db: validator failed for field \"device_code\": %w", err)}
}
}
if v, ok := dtu.mutation.Status(); ok {
if err := devicetoken.StatusValidator(v); err != nil {
return &ValidationError{Name: "status", err: fmt.Errorf("db: validator failed for field \"status\": %w", err)}
}
}
return nil
}
func (dtu *DeviceTokenUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: devicetoken.Table,
Columns: devicetoken.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: devicetoken.FieldID,
},
},
}
if ps := dtu.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 {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: devicetoken.FieldDeviceCode,
})
}
if value, ok := dtu.mutation.Status(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: devicetoken.FieldStatus,
})
}
if value, ok := dtu.mutation.Token(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: devicetoken.FieldToken,
})
}
if dtu.mutation.TokenCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Column: devicetoken.FieldToken,
})
}
if value, ok := dtu.mutation.Expiry(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: devicetoken.FieldExpiry,
})
}
if value, ok := dtu.mutation.LastRequest(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: devicetoken.FieldLastRequest,
})
}
if value, ok := dtu.mutation.PollInterval(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: devicetoken.FieldPollInterval,
})
}
if value, ok := dtu.mutation.AddedPollInterval(); ok {
_spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: devicetoken.FieldPollInterval,
})
}
if n, err = sqlgraph.UpdateNodes(ctx, dtu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{devicetoken.Label}
} else if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return 0, err
}
return n, nil
}
// DeviceTokenUpdateOne is the builder for updating a single DeviceToken entity.
type DeviceTokenUpdateOne struct {
config
fields []string
hooks []Hook
mutation *DeviceTokenMutation
}
// SetDeviceCode sets the "device_code" field.
func (dtuo *DeviceTokenUpdateOne) SetDeviceCode(s string) *DeviceTokenUpdateOne {
dtuo.mutation.SetDeviceCode(s)
return dtuo
}
// SetStatus sets the "status" field.
func (dtuo *DeviceTokenUpdateOne) SetStatus(s string) *DeviceTokenUpdateOne {
dtuo.mutation.SetStatus(s)
return dtuo
}
// SetToken sets the "token" field.
func (dtuo *DeviceTokenUpdateOne) SetToken(b []byte) *DeviceTokenUpdateOne {
dtuo.mutation.SetToken(b)
return dtuo
}
// ClearToken clears the value of the "token" field.
func (dtuo *DeviceTokenUpdateOne) ClearToken() *DeviceTokenUpdateOne {
dtuo.mutation.ClearToken()
return dtuo
}
// SetExpiry sets the "expiry" field.
func (dtuo *DeviceTokenUpdateOne) SetExpiry(t time.Time) *DeviceTokenUpdateOne {
dtuo.mutation.SetExpiry(t)
return dtuo
}
// SetLastRequest sets the "last_request" field.
func (dtuo *DeviceTokenUpdateOne) SetLastRequest(t time.Time) *DeviceTokenUpdateOne {
dtuo.mutation.SetLastRequest(t)
return dtuo
}
// SetPollInterval sets the "poll_interval" field.
func (dtuo *DeviceTokenUpdateOne) SetPollInterval(i int) *DeviceTokenUpdateOne {
dtuo.mutation.ResetPollInterval()
dtuo.mutation.SetPollInterval(i)
return dtuo
}
// AddPollInterval adds i to the "poll_interval" field.
func (dtuo *DeviceTokenUpdateOne) AddPollInterval(i int) *DeviceTokenUpdateOne {
dtuo.mutation.AddPollInterval(i)
return dtuo
}
// Mutation returns the DeviceTokenMutation object of the builder.
func (dtuo *DeviceTokenUpdateOne) Mutation() *DeviceTokenMutation {
return dtuo.mutation
}
// 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
}
// Save executes the query and returns the updated DeviceToken entity.
func (dtuo *DeviceTokenUpdateOne) Save(ctx context.Context) (*DeviceToken, error) {
var (
err error
node *DeviceToken
)
if len(dtuo.hooks) == 0 {
if err = dtuo.check(); err != nil {
return nil, err
}
node, err = dtuo.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*DeviceTokenMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = dtuo.check(); err != nil {
return nil, err
}
dtuo.mutation = mutation
node, err = dtuo.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(dtuo.hooks) - 1; i >= 0; i-- {
mut = dtuo.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, dtuo.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX is like Save, but panics if an error occurs.
func (dtuo *DeviceTokenUpdateOne) SaveX(ctx context.Context) *DeviceToken {
node, err := dtuo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (dtuo *DeviceTokenUpdateOne) Exec(ctx context.Context) error {
_, err := dtuo.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 {
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 {
if err := devicetoken.DeviceCodeValidator(v); err != nil {
return &ValidationError{Name: "device_code", err: fmt.Errorf("db: validator failed for field \"device_code\": %w", err)}
}
}
if v, ok := dtuo.mutation.Status(); ok {
if err := devicetoken.StatusValidator(v); err != nil {
return &ValidationError{Name: "status", err: fmt.Errorf("db: validator failed for field \"status\": %w", err)}
}
}
return nil
}
func (dtuo *DeviceTokenUpdateOne) sqlSave(ctx context.Context) (_node *DeviceToken, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: devicetoken.Table,
Columns: devicetoken.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: devicetoken.FieldID,
},
},
}
id, ok := dtuo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing DeviceToken.ID for update")}
}
_spec.Node.ID.Value = id
if fields := dtuo.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 {
if !devicetoken.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
}
if f != devicetoken.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := dtuo.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 {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: devicetoken.FieldDeviceCode,
})
}
if value, ok := dtuo.mutation.Status(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: devicetoken.FieldStatus,
})
}
if value, ok := dtuo.mutation.Token(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: devicetoken.FieldToken,
})
}
if dtuo.mutation.TokenCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Column: devicetoken.FieldToken,
})
}
if value, ok := dtuo.mutation.Expiry(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: devicetoken.FieldExpiry,
})
}
if value, ok := dtuo.mutation.LastRequest(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: devicetoken.FieldLastRequest,
})
}
if value, ok := dtuo.mutation.PollInterval(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: devicetoken.FieldPollInterval,
})
}
if value, ok := dtuo.mutation.AddedPollInterval(); ok {
_spec.Fields.Add = append(_spec.Fields.Add, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: devicetoken.FieldPollInterval,
})
}
_node = &DeviceToken{config: dtuo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, dtuo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{devicetoken.Label}
} else if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return nil, err
}
return _node, nil
}

297
storage/ent/db/ent.go Normal file
View file

@ -0,0 +1,297 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"errors"
"fmt"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"github.com/dexidp/dex/storage/ent/db/authcode"
"github.com/dexidp/dex/storage/ent/db/authrequest"
"github.com/dexidp/dex/storage/ent/db/connector"
"github.com/dexidp/dex/storage/ent/db/devicerequest"
"github.com/dexidp/dex/storage/ent/db/devicetoken"
"github.com/dexidp/dex/storage/ent/db/keys"
"github.com/dexidp/dex/storage/ent/db/oauth2client"
"github.com/dexidp/dex/storage/ent/db/offlinesession"
"github.com/dexidp/dex/storage/ent/db/password"
"github.com/dexidp/dex/storage/ent/db/refreshtoken"
)
// ent aliases to avoid import conflicts in user's code.
type (
Op = ent.Op
Hook = ent.Hook
Value = ent.Value
Query = ent.Query
Policy = ent.Policy
Mutator = ent.Mutator
Mutation = ent.Mutation
MutateFunc = ent.MutateFunc
)
// OrderFunc applies an ordering on the sql selector.
type OrderFunc func(*sql.Selector)
// columnChecker returns a function indicates if the column exists in the given column.
func columnChecker(table string) func(string) error {
checks := map[string]func(string) bool{
authcode.Table: authcode.ValidColumn,
authrequest.Table: authrequest.ValidColumn,
connector.Table: connector.ValidColumn,
devicerequest.Table: devicerequest.ValidColumn,
devicetoken.Table: devicetoken.ValidColumn,
keys.Table: keys.ValidColumn,
oauth2client.Table: oauth2client.ValidColumn,
offlinesession.Table: offlinesession.ValidColumn,
password.Table: password.ValidColumn,
refreshtoken.Table: refreshtoken.ValidColumn,
}
check, ok := checks[table]
if !ok {
return func(string) error {
return fmt.Errorf("unknown table %q", table)
}
}
return func(column string) error {
if !check(column) {
return fmt.Errorf("unknown column %q for table %q", column, table)
}
return nil
}
}
// Asc applies the given fields in ASC order.
func Asc(fields ...string) OrderFunc {
return func(s *sql.Selector) {
check := columnChecker(s.TableName())
for _, f := range fields {
if err := check(f); err != nil {
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("db: %w", err)})
}
s.OrderBy(sql.Asc(s.C(f)))
}
}
}
// Desc applies the given fields in DESC order.
func Desc(fields ...string) OrderFunc {
return func(s *sql.Selector) {
check := columnChecker(s.TableName())
for _, f := range fields {
if err := check(f); err != nil {
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("db: %w", err)})
}
s.OrderBy(sql.Desc(s.C(f)))
}
}
}
// AggregateFunc applies an aggregation step on the group-by traversal/selector.
type AggregateFunc func(*sql.Selector) string
// As is a pseudo aggregation function for renaming another other functions with custom names. For example:
//
// GroupBy(field1, field2).
// Aggregate(db.As(db.Sum(field1), "sum_field1"), (db.As(db.Sum(field2), "sum_field2")).
// Scan(ctx, &v)
//
func As(fn AggregateFunc, end string) AggregateFunc {
return func(s *sql.Selector) string {
return sql.As(fn(s), end)
}
}
// Count applies the "count" aggregation function on each group.
func Count() AggregateFunc {
return func(s *sql.Selector) string {
return sql.Count("*")
}
}
// Max applies the "max" aggregation function on the given field of each group.
func Max(field string) AggregateFunc {
return func(s *sql.Selector) string {
check := columnChecker(s.TableName())
if err := check(field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("db: %w", err)})
return ""
}
return sql.Max(s.C(field))
}
}
// Mean applies the "mean" aggregation function on the given field of each group.
func Mean(field string) AggregateFunc {
return func(s *sql.Selector) string {
check := columnChecker(s.TableName())
if err := check(field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("db: %w", err)})
return ""
}
return sql.Avg(s.C(field))
}
}
// Min applies the "min" aggregation function on the given field of each group.
func Min(field string) AggregateFunc {
return func(s *sql.Selector) string {
check := columnChecker(s.TableName())
if err := check(field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("db: %w", err)})
return ""
}
return sql.Min(s.C(field))
}
}
// Sum applies the "sum" aggregation function on the given field of each group.
func Sum(field string) AggregateFunc {
return func(s *sql.Selector) string {
check := columnChecker(s.TableName())
if err := check(field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("db: %w", err)})
return ""
}
return sql.Sum(s.C(field))
}
}
// ValidationError returns when validating a field fails.
type ValidationError struct {
Name string // Field or edge name.
err error
}
// Error implements the error interface.
func (e *ValidationError) Error() string {
return e.err.Error()
}
// Unwrap implements the errors.Wrapper interface.
func (e *ValidationError) Unwrap() error {
return e.err
}
// IsValidationError returns a boolean indicating whether the error is a validaton error.
func IsValidationError(err error) bool {
if err == nil {
return false
}
var e *ValidationError
return errors.As(err, &e)
}
// NotFoundError returns when trying to fetch a specific entity and it was not found in the database.
type NotFoundError struct {
label string
}
// Error implements the error interface.
func (e *NotFoundError) Error() string {
return "db: " + e.label + " not found"
}
// IsNotFound returns a boolean indicating whether the error is a not found error.
func IsNotFound(err error) bool {
if err == nil {
return false
}
var e *NotFoundError
return errors.As(err, &e)
}
// MaskNotFound masks not found error.
func MaskNotFound(err error) error {
if IsNotFound(err) {
return nil
}
return err
}
// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database.
type NotSingularError struct {
label string
}
// Error implements the error interface.
func (e *NotSingularError) Error() string {
return "db: " + e.label + " not singular"
}
// IsNotSingular returns a boolean indicating whether the error is a not singular error.
func IsNotSingular(err error) bool {
if err == nil {
return false
}
var e *NotSingularError
return errors.As(err, &e)
}
// NotLoadedError returns when trying to get a node that was not loaded by the query.
type NotLoadedError struct {
edge string
}
// Error implements the error interface.
func (e *NotLoadedError) Error() string {
return "db: " + e.edge + " edge was not loaded"
}
// IsNotLoaded returns a boolean indicating whether the error is a not loaded error.
func IsNotLoaded(err error) bool {
if err == nil {
return false
}
var e *NotLoadedError
return errors.As(err, &e)
}
// ConstraintError returns when trying to create/update one or more entities and
// one or more of their constraints failed. For example, violation of edge or
// field uniqueness.
type ConstraintError struct {
msg string
wrap error
}
// Error implements the error interface.
func (e ConstraintError) Error() string {
return "db: constraint failed: " + e.msg
}
// Unwrap implements the errors.Wrapper interface.
func (e *ConstraintError) Unwrap() error {
return e.wrap
}
// IsConstraintError returns a boolean indicating whether the error is a constraint failure.
func IsConstraintError(err error) bool {
if err == nil {
return false
}
var e *ConstraintError
return errors.As(err, &e)
}
func isSQLConstraintError(err error) (*ConstraintError, bool) {
if sqlgraph.IsConstraintError(err) {
return &ConstraintError{err.Error(), err}, true
}
return nil, false
}
// rollback calls tx.Rollback and wraps the given error with the rollback error if present.
func rollback(tx dialect.Tx, err error) error {
if rerr := tx.Rollback(); rerr != nil {
err = fmt.Errorf("%w: %v", err, rerr)
}
if err, ok := isSQLConstraintError(err); ok {
return err
}
return err
}

View file

@ -0,0 +1,78 @@
// Code generated by entc, DO NOT EDIT.
package enttest
import (
"context"
"github.com/dexidp/dex/storage/ent/db"
// required by schema hooks.
_ "github.com/dexidp/dex/storage/ent/db/runtime"
"entgo.io/ent/dialect/sql/schema"
)
type (
// TestingT is the interface that is shared between
// testing.T and testing.B and used by enttest.
TestingT interface {
FailNow()
Error(...interface{})
}
// Option configures client creation.
Option func(*options)
options struct {
opts []db.Option
migrateOpts []schema.MigrateOption
}
)
// WithOptions forwards options to client creation.
func WithOptions(opts ...db.Option) Option {
return func(o *options) {
o.opts = append(o.opts, opts...)
}
}
// WithMigrateOptions forwards options to auto migration.
func WithMigrateOptions(opts ...schema.MigrateOption) Option {
return func(o *options) {
o.migrateOpts = append(o.migrateOpts, opts...)
}
}
func newOptions(opts []Option) *options {
o := &options{}
for _, opt := range opts {
opt(o)
}
return o
}
// Open calls db.Open and auto-run migration.
func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *db.Client {
o := newOptions(opts)
c, err := db.Open(driverName, dataSourceName, o.opts...)
if err != nil {
t.Error(err)
t.FailNow()
}
if err := c.Schema.Create(context.Background(), o.migrateOpts...); err != nil {
t.Error(err)
t.FailNow()
}
return c
}
// NewClient calls db.NewClient and auto-run migration.
func NewClient(t TestingT, opts ...Option) *db.Client {
o := newOptions(opts)
c := db.NewClient(o.opts...)
if err := c.Schema.Create(context.Background(), o.migrateOpts...); err != nil {
t.Error(err)
t.FailNow()
}
return c
}

321
storage/ent/db/hook/hook.go Normal file
View file

@ -0,0 +1,321 @@
// Code generated by entc, DO NOT EDIT.
package hook
import (
"context"
"fmt"
"github.com/dexidp/dex/storage/ent/db"
)
// The AuthCodeFunc type is an adapter to allow the use of ordinary
// function as AuthCode mutator.
type AuthCodeFunc func(context.Context, *db.AuthCodeMutation) (db.Value, error)
// Mutate calls f(ctx, m).
func (f AuthCodeFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) {
mv, ok := m.(*db.AuthCodeMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *db.AuthCodeMutation", m)
}
return f(ctx, mv)
}
// The AuthRequestFunc type is an adapter to allow the use of ordinary
// function as AuthRequest mutator.
type AuthRequestFunc func(context.Context, *db.AuthRequestMutation) (db.Value, error)
// Mutate calls f(ctx, m).
func (f AuthRequestFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) {
mv, ok := m.(*db.AuthRequestMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *db.AuthRequestMutation", m)
}
return f(ctx, mv)
}
// The ConnectorFunc type is an adapter to allow the use of ordinary
// function as Connector mutator.
type ConnectorFunc func(context.Context, *db.ConnectorMutation) (db.Value, error)
// Mutate calls f(ctx, m).
func (f ConnectorFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) {
mv, ok := m.(*db.ConnectorMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *db.ConnectorMutation", m)
}
return f(ctx, mv)
}
// The DeviceRequestFunc type is an adapter to allow the use of ordinary
// function as DeviceRequest mutator.
type DeviceRequestFunc func(context.Context, *db.DeviceRequestMutation) (db.Value, error)
// Mutate calls f(ctx, m).
func (f DeviceRequestFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) {
mv, ok := m.(*db.DeviceRequestMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *db.DeviceRequestMutation", m)
}
return f(ctx, mv)
}
// The DeviceTokenFunc type is an adapter to allow the use of ordinary
// function as DeviceToken mutator.
type DeviceTokenFunc func(context.Context, *db.DeviceTokenMutation) (db.Value, error)
// Mutate calls f(ctx, m).
func (f DeviceTokenFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) {
mv, ok := m.(*db.DeviceTokenMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *db.DeviceTokenMutation", m)
}
return f(ctx, mv)
}
// The KeysFunc type is an adapter to allow the use of ordinary
// function as Keys mutator.
type KeysFunc func(context.Context, *db.KeysMutation) (db.Value, error)
// Mutate calls f(ctx, m).
func (f KeysFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) {
mv, ok := m.(*db.KeysMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *db.KeysMutation", m)
}
return f(ctx, mv)
}
// The OAuth2ClientFunc type is an adapter to allow the use of ordinary
// function as OAuth2Client mutator.
type OAuth2ClientFunc func(context.Context, *db.OAuth2ClientMutation) (db.Value, error)
// Mutate calls f(ctx, m).
func (f OAuth2ClientFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) {
mv, ok := m.(*db.OAuth2ClientMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *db.OAuth2ClientMutation", m)
}
return f(ctx, mv)
}
// The OfflineSessionFunc type is an adapter to allow the use of ordinary
// function as OfflineSession mutator.
type OfflineSessionFunc func(context.Context, *db.OfflineSessionMutation) (db.Value, error)
// Mutate calls f(ctx, m).
func (f OfflineSessionFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) {
mv, ok := m.(*db.OfflineSessionMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *db.OfflineSessionMutation", m)
}
return f(ctx, mv)
}
// The PasswordFunc type is an adapter to allow the use of ordinary
// function as Password mutator.
type PasswordFunc func(context.Context, *db.PasswordMutation) (db.Value, error)
// Mutate calls f(ctx, m).
func (f PasswordFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) {
mv, ok := m.(*db.PasswordMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *db.PasswordMutation", m)
}
return f(ctx, mv)
}
// The RefreshTokenFunc type is an adapter to allow the use of ordinary
// function as RefreshToken mutator.
type RefreshTokenFunc func(context.Context, *db.RefreshTokenMutation) (db.Value, error)
// Mutate calls f(ctx, m).
func (f RefreshTokenFunc) Mutate(ctx context.Context, m db.Mutation) (db.Value, error) {
mv, ok := m.(*db.RefreshTokenMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *db.RefreshTokenMutation", m)
}
return f(ctx, mv)
}
// Condition is a hook condition function.
type Condition func(context.Context, db.Mutation) bool
// And groups conditions with the AND operator.
func And(first, second Condition, rest ...Condition) Condition {
return func(ctx context.Context, m db.Mutation) bool {
if !first(ctx, m) || !second(ctx, m) {
return false
}
for _, cond := range rest {
if !cond(ctx, m) {
return false
}
}
return true
}
}
// Or groups conditions with the OR operator.
func Or(first, second Condition, rest ...Condition) Condition {
return func(ctx context.Context, m db.Mutation) bool {
if first(ctx, m) || second(ctx, m) {
return true
}
for _, cond := range rest {
if cond(ctx, m) {
return true
}
}
return false
}
}
// Not negates a given condition.
func Not(cond Condition) Condition {
return func(ctx context.Context, m db.Mutation) bool {
return !cond(ctx, m)
}
}
// HasOp is a condition testing mutation operation.
func HasOp(op db.Op) Condition {
return func(_ context.Context, m db.Mutation) bool {
return m.Op().Is(op)
}
}
// HasAddedFields is a condition validating `.AddedField` on fields.
func HasAddedFields(field string, fields ...string) Condition {
return func(_ context.Context, m db.Mutation) bool {
if _, exists := m.AddedField(field); !exists {
return false
}
for _, field := range fields {
if _, exists := m.AddedField(field); !exists {
return false
}
}
return true
}
}
// HasClearedFields is a condition validating `.FieldCleared` on fields.
func HasClearedFields(field string, fields ...string) Condition {
return func(_ context.Context, m db.Mutation) bool {
if exists := m.FieldCleared(field); !exists {
return false
}
for _, field := range fields {
if exists := m.FieldCleared(field); !exists {
return false
}
}
return true
}
}
// HasFields is a condition validating `.Field` on fields.
func HasFields(field string, fields ...string) Condition {
return func(_ context.Context, m db.Mutation) bool {
if _, exists := m.Field(field); !exists {
return false
}
for _, field := range fields {
if _, exists := m.Field(field); !exists {
return false
}
}
return true
}
}
// If executes the given hook under condition.
//
// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...)))
//
func If(hk db.Hook, cond Condition) db.Hook {
return func(next db.Mutator) db.Mutator {
return db.MutateFunc(func(ctx context.Context, m db.Mutation) (db.Value, error) {
if cond(ctx, m) {
return hk(next).Mutate(ctx, m)
}
return next.Mutate(ctx, m)
})
}
}
// On executes the given hook only for the given operation.
//
// hook.On(Log, db.Delete|db.Create)
//
func On(hk db.Hook, op db.Op) db.Hook {
return If(hk, HasOp(op))
}
// Unless skips the given hook only for the given operation.
//
// hook.Unless(Log, db.Update|db.UpdateOne)
//
func Unless(hk db.Hook, op db.Op) db.Hook {
return If(hk, Not(HasOp(op)))
}
// FixedError is a hook returning a fixed error.
func FixedError(err error) db.Hook {
return func(db.Mutator) db.Mutator {
return db.MutateFunc(func(context.Context, db.Mutation) (db.Value, error) {
return nil, err
})
}
}
// Reject returns a hook that rejects all operations that match op.
//
// func (T) Hooks() []db.Hook {
// return []db.Hook{
// Reject(db.Delete|db.Update),
// }
// }
//
func Reject(op db.Op) db.Hook {
hk := FixedError(fmt.Errorf("%s operation is not allowed", op))
return On(hk, op)
}
// Chain acts as a list of hooks and is effectively immutable.
// Once created, it will always hold the same set of hooks in the same order.
type Chain struct {
hooks []db.Hook
}
// NewChain creates a new chain of hooks.
func NewChain(hooks ...db.Hook) Chain {
return Chain{append([]db.Hook(nil), hooks...)}
}
// Hook chains the list of hooks and returns the final hook.
func (c Chain) Hook() db.Hook {
return func(mutator db.Mutator) db.Mutator {
for i := len(c.hooks) - 1; i >= 0; i-- {
mutator = c.hooks[i](mutator)
}
return mutator
}
}
// Append extends a chain, adding the specified hook
// as the last ones in the mutation flow.
func (c Chain) Append(hooks ...db.Hook) Chain {
newHooks := make([]db.Hook, 0, len(c.hooks)+len(hooks))
newHooks = append(newHooks, c.hooks...)
newHooks = append(newHooks, hooks...)
return Chain{newHooks}
}
// Extend extends a chain, adding the specified chain
// as the last ones in the mutation flow.
func (c Chain) Extend(chain Chain) Chain {
return c.Append(chain.hooks...)
}

144
storage/ent/db/keys.go Normal file
View file

@ -0,0 +1,144 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"encoding/json"
"fmt"
"strings"
"time"
"entgo.io/ent/dialect/sql"
"github.com/dexidp/dex/storage"
"github.com/dexidp/dex/storage/ent/db/keys"
"gopkg.in/square/go-jose.v2"
)
// Keys is the model entity for the Keys schema.
type Keys struct {
config `json:"-"`
// ID of the ent.
ID string `json:"id,omitempty"`
// VerificationKeys holds the value of the "verification_keys" field.
VerificationKeys []storage.VerificationKey `json:"verification_keys,omitempty"`
// SigningKey holds the value of the "signing_key" field.
SigningKey jose.JSONWebKey `json:"signing_key,omitempty"`
// SigningKeyPub holds the value of the "signing_key_pub" field.
SigningKeyPub jose.JSONWebKey `json:"signing_key_pub,omitempty"`
// NextRotation holds the value of the "next_rotation" field.
NextRotation time.Time `json:"next_rotation,omitempty"`
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Keys) scanValues(columns []string) ([]interface{}, error) {
values := make([]interface{}, len(columns))
for i := range columns {
switch columns[i] {
case keys.FieldVerificationKeys, keys.FieldSigningKey, keys.FieldSigningKeyPub:
values[i] = new([]byte)
case keys.FieldID:
values[i] = new(sql.NullString)
case keys.FieldNextRotation:
values[i] = new(sql.NullTime)
default:
return nil, fmt.Errorf("unexpected column %q for type Keys", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Keys fields.
func (k *Keys) assignValues(columns []string, values []interface{}) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case keys.FieldID:
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
}
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 {
return fmt.Errorf("unmarshal field verification_keys: %w", err)
}
}
case keys.FieldSigningKey:
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 {
return fmt.Errorf("unmarshal field signing_key: %w", err)
}
}
case keys.FieldSigningKeyPub:
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 {
return fmt.Errorf("unmarshal field signing_key_pub: %w", err)
}
}
case keys.FieldNextRotation:
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
}
}
}
return nil
}
// 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 (&KeysClient{config: k.config}).UpdateOne(k)
}
// 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)
if !ok {
panic("db: Keys is not a transactional entity")
}
k.config.driver = tx.drv
return k
}
// String implements the fmt.Stringer.
func (k *Keys) String() string {
var builder strings.Builder
builder.WriteString("Keys(")
builder.WriteString(fmt.Sprintf("id=%v", k.ID))
builder.WriteString(", verification_keys=")
builder.WriteString(fmt.Sprintf("%v", k.VerificationKeys))
builder.WriteString(", signing_key=")
builder.WriteString(fmt.Sprintf("%v", k.SigningKey))
builder.WriteString(", signing_key_pub=")
builder.WriteString(fmt.Sprintf("%v", k.SigningKeyPub))
builder.WriteString(", next_rotation=")
builder.WriteString(k.NextRotation.Format(time.ANSIC))
builder.WriteByte(')')
return builder.String()
}
// KeysSlice is a parsable slice of Keys.
type KeysSlice []*Keys
func (k KeysSlice) config(cfg config) {
for _i := range k {
k[_i].config = cfg
}
}

View file

@ -0,0 +1,44 @@
// Code generated by entc, DO NOT EDIT.
package keys
const (
// Label holds the string label denoting the keys type in the database.
Label = "keys"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldVerificationKeys holds the string denoting the verification_keys field in the database.
FieldVerificationKeys = "verification_keys"
// FieldSigningKey holds the string denoting the signing_key field in the database.
FieldSigningKey = "signing_key"
// FieldSigningKeyPub holds the string denoting the signing_key_pub field in the database.
FieldSigningKeyPub = "signing_key_pub"
// FieldNextRotation holds the string denoting the next_rotation field in the database.
FieldNextRotation = "next_rotation"
// Table holds the table name of the keys in the database.
Table = "keys"
)
// Columns holds all SQL columns for keys fields.
var Columns = []string{
FieldID,
FieldVerificationKeys,
FieldSigningKey,
FieldSigningKeyPub,
FieldNextRotation,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// IDValidator is a validator for the "id" field. It is called by the builders before save.
IDValidator func(string) error
)

View file

@ -0,0 +1,208 @@
// Code generated by entc, DO NOT EDIT.
package keys
import (
"time"
"entgo.io/ent/dialect/sql"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// ID filters vertices based on their ID field.
func ID(id string) predicate.Keys {
return predicate.Keys(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id string) predicate.Keys {
return predicate.Keys(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id string) predicate.Keys {
return predicate.Keys(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldID), id))
})
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...string) predicate.Keys {
return predicate.Keys(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.In(s.C(FieldID), v...))
})
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...string) predicate.Keys {
return predicate.Keys(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.NotIn(s.C(FieldID), v...))
})
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id string) predicate.Keys {
return predicate.Keys(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldID), id))
})
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id string) predicate.Keys {
return predicate.Keys(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldID), id))
})
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id string) predicate.Keys {
return predicate.Keys(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldID), id))
})
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id string) predicate.Keys {
return predicate.Keys(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldID), id))
})
}
// NextRotation applies equality check predicate on the "next_rotation" field. It's identical to NextRotationEQ.
func NextRotation(v time.Time) predicate.Keys {
return predicate.Keys(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldNextRotation), v))
})
}
// NextRotationEQ applies the EQ predicate on the "next_rotation" field.
func NextRotationEQ(v time.Time) predicate.Keys {
return predicate.Keys(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldNextRotation), v))
})
}
// NextRotationNEQ applies the NEQ predicate on the "next_rotation" field.
func NextRotationNEQ(v time.Time) predicate.Keys {
return predicate.Keys(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldNextRotation), v))
})
}
// NextRotationIn applies the In predicate on the "next_rotation" field.
func NextRotationIn(vs ...time.Time) predicate.Keys {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Keys(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldNextRotation), v...))
})
}
// NextRotationNotIn applies the NotIn predicate on the "next_rotation" field.
func NextRotationNotIn(vs ...time.Time) predicate.Keys {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Keys(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldNextRotation), v...))
})
}
// NextRotationGT applies the GT predicate on the "next_rotation" field.
func NextRotationGT(v time.Time) predicate.Keys {
return predicate.Keys(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldNextRotation), v))
})
}
// NextRotationGTE applies the GTE predicate on the "next_rotation" field.
func NextRotationGTE(v time.Time) predicate.Keys {
return predicate.Keys(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldNextRotation), v))
})
}
// NextRotationLT applies the LT predicate on the "next_rotation" field.
func NextRotationLT(v time.Time) predicate.Keys {
return predicate.Keys(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldNextRotation), v))
})
}
// NextRotationLTE applies the LTE predicate on the "next_rotation" field.
func NextRotationLTE(v time.Time) predicate.Keys {
return predicate.Keys(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldNextRotation), v))
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Keys) predicate.Keys {
return predicate.Keys(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for _, p := range predicates {
p(s1)
}
s.Where(s1.P())
})
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Keys) predicate.Keys {
return predicate.Keys(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for i, p := range predicates {
if i > 0 {
s1.Or()
}
p(s1)
}
s.Where(s1.P())
})
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Keys) predicate.Keys {
return predicate.Keys(func(s *sql.Selector) {
p(s.Not())
})
}

View file

@ -0,0 +1,249 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage"
"github.com/dexidp/dex/storage/ent/db/keys"
"gopkg.in/square/go-jose.v2"
)
// KeysCreate is the builder for creating a Keys entity.
type KeysCreate struct {
config
mutation *KeysMutation
hooks []Hook
}
// SetVerificationKeys sets the "verification_keys" field.
func (kc *KeysCreate) SetVerificationKeys(sk []storage.VerificationKey) *KeysCreate {
kc.mutation.SetVerificationKeys(sk)
return kc
}
// SetSigningKey sets the "signing_key" field.
func (kc *KeysCreate) SetSigningKey(jwk jose.JSONWebKey) *KeysCreate {
kc.mutation.SetSigningKey(jwk)
return kc
}
// SetSigningKeyPub sets the "signing_key_pub" field.
func (kc *KeysCreate) SetSigningKeyPub(jwk jose.JSONWebKey) *KeysCreate {
kc.mutation.SetSigningKeyPub(jwk)
return kc
}
// SetNextRotation sets the "next_rotation" field.
func (kc *KeysCreate) SetNextRotation(t time.Time) *KeysCreate {
kc.mutation.SetNextRotation(t)
return kc
}
// SetID sets the "id" field.
func (kc *KeysCreate) SetID(s string) *KeysCreate {
kc.mutation.SetID(s)
return kc
}
// Mutation returns the KeysMutation object of the builder.
func (kc *KeysCreate) Mutation() *KeysMutation {
return kc.mutation
}
// Save creates the Keys in the database.
func (kc *KeysCreate) Save(ctx context.Context) (*Keys, error) {
var (
err error
node *Keys
)
if len(kc.hooks) == 0 {
if err = kc.check(); err != nil {
return nil, err
}
node, err = kc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*KeysMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = kc.check(); err != nil {
return nil, err
}
kc.mutation = mutation
node, err = kc.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(kc.hooks) - 1; i >= 0; i-- {
mut = kc.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, kc.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (kc *KeysCreate) SaveX(ctx context.Context) *Keys {
v, err := kc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// check runs all checks and user-defined validators on the builder.
func (kc *KeysCreate) check() error {
if _, ok := kc.mutation.VerificationKeys(); !ok {
return &ValidationError{Name: "verification_keys", err: errors.New("db: missing required field \"verification_keys\"")}
}
if _, ok := kc.mutation.SigningKey(); !ok {
return &ValidationError{Name: "signing_key", err: errors.New("db: missing required field \"signing_key\"")}
}
if _, ok := kc.mutation.SigningKeyPub(); !ok {
return &ValidationError{Name: "signing_key_pub", err: errors.New("db: missing required field \"signing_key_pub\"")}
}
if _, ok := kc.mutation.NextRotation(); !ok {
return &ValidationError{Name: "next_rotation", err: errors.New("db: missing required field \"next_rotation\"")}
}
if v, ok := kc.mutation.ID(); ok {
if err := keys.IDValidator(v); err != nil {
return &ValidationError{Name: "id", err: fmt.Errorf("db: validator failed for field \"id\": %w", err)}
}
}
return nil
}
func (kc *KeysCreate) sqlSave(ctx context.Context) (*Keys, error) {
_node, _spec := kc.createSpec()
if err := sqlgraph.CreateNode(ctx, kc.driver, _spec); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return nil, err
}
return _node, nil
}
func (kc *KeysCreate) createSpec() (*Keys, *sqlgraph.CreateSpec) {
var (
_node = &Keys{config: kc.config}
_spec = &sqlgraph.CreateSpec{
Table: keys.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: keys.FieldID,
},
}
)
if id, ok := kc.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = id
}
if value, ok := kc.mutation.VerificationKeys(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: keys.FieldVerificationKeys,
})
_node.VerificationKeys = value
}
if value, ok := kc.mutation.SigningKey(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: keys.FieldSigningKey,
})
_node.SigningKey = value
}
if value, ok := kc.mutation.SigningKeyPub(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: keys.FieldSigningKeyPub,
})
_node.SigningKeyPub = value
}
if value, ok := kc.mutation.NextRotation(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: keys.FieldNextRotation,
})
_node.NextRotation = value
}
return _node, _spec
}
// KeysCreateBulk is the builder for creating many Keys entities in bulk.
type KeysCreateBulk struct {
config
builders []*KeysCreate
}
// Save creates the Keys entities in the database.
func (kcb *KeysCreateBulk) Save(ctx context.Context) ([]*Keys, error) {
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(i int, root context.Context) {
builder := kcb.builders[i]
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*KeysMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
nodes[i], specs[i] = builder.createSpec()
var err error
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, kcb.builders[i+1].mutation)
} else {
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, kcb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
}
}
mutation.done = true
if err != nil {
return nil, err
}
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, kcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (kcb *KeysCreateBulk) SaveX(ctx context.Context) []*Keys {
v, err := kcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}

View file

@ -0,0 +1,108 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/keys"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// KeysDelete is the builder for deleting a Keys entity.
type KeysDelete struct {
config
hooks []Hook
mutation *KeysMutation
}
// Where adds a new predicate to the KeysDelete builder.
func (kd *KeysDelete) Where(ps ...predicate.Keys) *KeysDelete {
kd.mutation.predicates = append(kd.mutation.predicates, ps...)
return kd
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (kd *KeysDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(kd.hooks) == 0 {
affected, err = kd.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*KeysMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
kd.mutation = mutation
affected, err = kd.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(kd.hooks) - 1; i >= 0; i-- {
mut = kd.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, kd.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (kd *KeysDelete) ExecX(ctx context.Context) int {
n, err := kd.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (kd *KeysDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: keys.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: keys.FieldID,
},
},
}
if ps := kd.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return sqlgraph.DeleteNodes(ctx, kd.driver, _spec)
}
// KeysDeleteOne is the builder for deleting a single Keys entity.
type KeysDeleteOne struct {
kd *KeysDelete
}
// Exec executes the deletion query.
func (kdo *KeysDeleteOne) Exec(ctx context.Context) error {
n, err := kdo.kd.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{keys.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (kdo *KeysDeleteOne) ExecX(ctx context.Context) {
kdo.kd.ExecX(ctx)
}

View file

@ -0,0 +1,906 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"errors"
"fmt"
"math"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/keys"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// KeysQuery is the builder for querying Keys entities.
type KeysQuery struct {
config
limit *int
offset *int
unique *bool
order []OrderFunc
fields []string
predicates []predicate.Keys
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// 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
}
// Limit adds a limit step to the query.
func (kq *KeysQuery) Limit(limit int) *KeysQuery {
kq.limit = &limit
return kq
}
// Offset adds an offset step to the query.
func (kq *KeysQuery) Offset(offset int) *KeysQuery {
kq.offset = &offset
return kq
}
// 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.unique = &unique
return kq
}
// Order adds an order step to the query.
func (kq *KeysQuery) Order(o ...OrderFunc) *KeysQuery {
kq.order = append(kq.order, o...)
return kq
}
// 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(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{keys.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (kq *KeysQuery) FirstX(ctx context.Context) *Keys {
node, err := kq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// 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) {
var ids []string
if ids, err = kq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{keys.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (kq *KeysQuery) FirstIDX(ctx context.Context) string {
id, err := kq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Keys entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when exactly one Keys entity is not 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(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{keys.Label}
default:
return nil, &NotSingularError{keys.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (kq *KeysQuery) OnlyX(ctx context.Context) *Keys {
node, err := kq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Keys ID in the query.
// Returns a *NotSingularError when exactly one Keys ID is not found.
// Returns a *NotFoundError when no entities are found.
func (kq *KeysQuery) OnlyID(ctx context.Context) (id string, err error) {
var ids []string
if ids, err = kq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{keys.Label}
default:
err = &NotSingularError{keys.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (kq *KeysQuery) OnlyIDX(ctx context.Context) string {
id, err := kq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of KeysSlice.
func (kq *KeysQuery) All(ctx context.Context) ([]*Keys, error) {
if err := kq.prepareQuery(ctx); err != nil {
return nil, err
}
return kq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (kq *KeysQuery) AllX(ctx context.Context) []*Keys {
nodes, err := kq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Keys IDs.
func (kq *KeysQuery) IDs(ctx context.Context) ([]string, error) {
var ids []string
if err := kq.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)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (kq *KeysQuery) Count(ctx context.Context) (int, error) {
if err := kq.prepareQuery(ctx); err != nil {
return 0, err
}
return kq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (kq *KeysQuery) CountX(ctx context.Context) int {
count, err := kq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (kq *KeysQuery) Exist(ctx context.Context) (bool, error) {
if err := kq.prepareQuery(ctx); err != nil {
return false, err
}
return kq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (kq *KeysQuery) ExistX(ctx context.Context) bool {
exist, err := kq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// 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 {
return nil
}
return &KeysQuery{
config: kq.config,
limit: kq.limit,
offset: kq.offset,
order: append([]OrderFunc{}, kq.order...),
predicates: append([]predicate.Keys{}, kq.predicates...),
// clone intermediate query.
sql: kq.sql.Clone(),
path: kq.path,
}
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// VerificationKeys []storage.VerificationKey `json:"verification_keys,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Keys.Query().
// GroupBy(keys.FieldVerificationKeys).
// Aggregate(db.Count()).
// Scan(ctx, &v)
//
func (kq *KeysQuery) GroupBy(field string, fields ...string) *KeysGroupBy {
group := &KeysGroupBy{config: kq.config}
group.fields = append([]string{field}, fields...)
group.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := kq.prepareQuery(ctx); err != nil {
return nil, err
}
return kq.sqlQuery(ctx), nil
}
return group
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// VerificationKeys []storage.VerificationKey `json:"verification_keys,omitempty"`
// }
//
// client.Keys.Query().
// Select(keys.FieldVerificationKeys).
// Scan(ctx, &v)
//
func (kq *KeysQuery) Select(field string, fields ...string) *KeysSelect {
kq.fields = append([]string{field}, fields...)
return &KeysSelect{KeysQuery: kq}
}
func (kq *KeysQuery) prepareQuery(ctx context.Context) error {
for _, f := range kq.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 err != nil {
return err
}
kq.sql = prev
}
return nil
}
func (kq *KeysQuery) sqlAll(ctx context.Context) ([]*Keys, error) {
var (
nodes = []*Keys{}
_spec = kq.querySpec()
)
_spec.ScanValues = func(columns []string) ([]interface{}, error) {
node := &Keys{config: kq.config}
nodes = append(nodes, node)
return node.scanValues(columns)
}
_spec.Assign = func(columns []string, values []interface{}) error {
if len(nodes) == 0 {
return fmt.Errorf("db: Assign called without calling ScanValues")
}
node := nodes[len(nodes)-1]
return node.assignValues(columns, values)
}
if err := sqlgraph.QueryNodes(ctx, kq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (kq *KeysQuery) sqlCount(ctx context.Context) (int, error) {
_spec := kq.querySpec()
return sqlgraph.CountNodes(ctx, kq.driver, _spec)
}
func (kq *KeysQuery) sqlExist(ctx context.Context) (bool, error) {
n, err := kq.sqlCount(ctx)
if err != nil {
return false, fmt.Errorf("db: check existence: %w", err)
}
return n > 0, nil
}
func (kq *KeysQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: keys.Table,
Columns: keys.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: keys.FieldID,
},
},
From: kq.sql,
Unique: true,
}
if unique := kq.unique; unique != nil {
_spec.Unique = *unique
}
if fields := kq.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 {
if fields[i] != keys.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := kq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := kq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := kq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := kq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (kq *KeysQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(kq.driver.Dialect())
t1 := builder.Table(keys.Table)
selector := builder.Select(t1.Columns(keys.Columns...)...).From(t1)
if kq.sql != nil {
selector = kq.sql
selector.Select(selector.Columns(keys.Columns...)...)
}
for _, p := range kq.predicates {
p(selector)
}
for _, p := range kq.order {
p(selector)
}
if offset := kq.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.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// KeysGroupBy is the group-by builder for Keys entities.
type KeysGroupBy struct {
config
fields []string
fns []AggregateFunc
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Aggregate adds the given aggregation functions to the group-by query.
func (kgb *KeysGroupBy) Aggregate(fns ...AggregateFunc) *KeysGroupBy {
kgb.fns = append(kgb.fns, fns...)
return kgb
}
// Scan applies the group-by query and scans the result into the given value.
func (kgb *KeysGroupBy) Scan(ctx context.Context, v interface{}) error {
query, err := kgb.path(ctx)
if err != nil {
return err
}
kgb.sql = query
return kgb.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (kgb *KeysGroupBy) ScanX(ctx context.Context, v interface{}) {
if err := kgb.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from group-by.
// It is only allowed when executing a group-by query with one field.
func (kgb *KeysGroupBy) Strings(ctx context.Context) ([]string, error) {
if len(kgb.fields) > 1 {
return nil, errors.New("db: KeysGroupBy.Strings is not achievable when grouping more than 1 field")
}
var v []string
if err := kgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (kgb *KeysGroupBy) StringsX(ctx context.Context) []string {
v, err := kgb.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (kgb *KeysGroupBy) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = kgb.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{keys.Label}
default:
err = fmt.Errorf("db: KeysGroupBy.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (kgb *KeysGroupBy) StringX(ctx context.Context) string {
v, err := kgb.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from group-by.
// It is only allowed when executing a group-by query with one field.
func (kgb *KeysGroupBy) Ints(ctx context.Context) ([]int, error) {
if len(kgb.fields) > 1 {
return nil, errors.New("db: KeysGroupBy.Ints is not achievable when grouping more than 1 field")
}
var v []int
if err := kgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (kgb *KeysGroupBy) IntsX(ctx context.Context) []int {
v, err := kgb.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (kgb *KeysGroupBy) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = kgb.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{keys.Label}
default:
err = fmt.Errorf("db: KeysGroupBy.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (kgb *KeysGroupBy) IntX(ctx context.Context) int {
v, err := kgb.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from group-by.
// It is only allowed when executing a group-by query with one field.
func (kgb *KeysGroupBy) Float64s(ctx context.Context) ([]float64, error) {
if len(kgb.fields) > 1 {
return nil, errors.New("db: KeysGroupBy.Float64s is not achievable when grouping more than 1 field")
}
var v []float64
if err := kgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (kgb *KeysGroupBy) Float64sX(ctx context.Context) []float64 {
v, err := kgb.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (kgb *KeysGroupBy) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = kgb.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{keys.Label}
default:
err = fmt.Errorf("db: KeysGroupBy.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (kgb *KeysGroupBy) Float64X(ctx context.Context) float64 {
v, err := kgb.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from group-by.
// It is only allowed when executing a group-by query with one field.
func (kgb *KeysGroupBy) Bools(ctx context.Context) ([]bool, error) {
if len(kgb.fields) > 1 {
return nil, errors.New("db: KeysGroupBy.Bools is not achievable when grouping more than 1 field")
}
var v []bool
if err := kgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (kgb *KeysGroupBy) BoolsX(ctx context.Context) []bool {
v, err := kgb.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (kgb *KeysGroupBy) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = kgb.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{keys.Label}
default:
err = fmt.Errorf("db: KeysGroupBy.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (kgb *KeysGroupBy) BoolX(ctx context.Context) bool {
v, err := kgb.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
func (kgb *KeysGroupBy) sqlScan(ctx context.Context, v interface{}) error {
for _, f := range kgb.fields {
if !keys.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := kgb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := kgb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (kgb *KeysGroupBy) sqlQuery() *sql.Selector {
selector := kgb.sql
columns := make([]string, 0, len(kgb.fields)+len(kgb.fns))
columns = append(columns, kgb.fields...)
for _, fn := range kgb.fns {
columns = append(columns, fn(selector))
}
return selector.Select(columns...).GroupBy(kgb.fields...)
}
// KeysSelect is the builder for selecting fields of Keys entities.
type KeysSelect struct {
*KeysQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
}
// Scan applies the selector query and scans the result into the given value.
func (ks *KeysSelect) Scan(ctx context.Context, v interface{}) error {
if err := ks.prepareQuery(ctx); err != nil {
return err
}
ks.sql = ks.KeysQuery.sqlQuery(ctx)
return ks.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (ks *KeysSelect) ScanX(ctx context.Context, v interface{}) {
if err := ks.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from a selector. It is only allowed when selecting one field.
func (ks *KeysSelect) Strings(ctx context.Context) ([]string, error) {
if len(ks.fields) > 1 {
return nil, errors.New("db: KeysSelect.Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := ks.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (ks *KeysSelect) StringsX(ctx context.Context) []string {
v, err := ks.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a selector. It is only allowed when selecting one field.
func (ks *KeysSelect) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = ks.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{keys.Label}
default:
err = fmt.Errorf("db: KeysSelect.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (ks *KeysSelect) StringX(ctx context.Context) string {
v, err := ks.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from a selector. It is only allowed when selecting one field.
func (ks *KeysSelect) Ints(ctx context.Context) ([]int, error) {
if len(ks.fields) > 1 {
return nil, errors.New("db: KeysSelect.Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := ks.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (ks *KeysSelect) IntsX(ctx context.Context) []int {
v, err := ks.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a selector. It is only allowed when selecting one field.
func (ks *KeysSelect) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = ks.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{keys.Label}
default:
err = fmt.Errorf("db: KeysSelect.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (ks *KeysSelect) IntX(ctx context.Context) int {
v, err := ks.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
func (ks *KeysSelect) Float64s(ctx context.Context) ([]float64, error) {
if len(ks.fields) > 1 {
return nil, errors.New("db: KeysSelect.Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := ks.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (ks *KeysSelect) Float64sX(ctx context.Context) []float64 {
v, err := ks.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
func (ks *KeysSelect) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = ks.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{keys.Label}
default:
err = fmt.Errorf("db: KeysSelect.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (ks *KeysSelect) Float64X(ctx context.Context) float64 {
v, err := ks.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from a selector. It is only allowed when selecting one field.
func (ks *KeysSelect) Bools(ctx context.Context) ([]bool, error) {
if len(ks.fields) > 1 {
return nil, errors.New("db: KeysSelect.Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := ks.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (ks *KeysSelect) BoolsX(ctx context.Context) []bool {
v, err := ks.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a selector. It is only allowed when selecting one field.
func (ks *KeysSelect) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = ks.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{keys.Label}
default:
err = fmt.Errorf("db: KeysSelect.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (ks *KeysSelect) BoolX(ctx context.Context) bool {
v, err := ks.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
func (ks *KeysSelect) sqlScan(ctx context.Context, v interface{}) error {
rows := &sql.Rows{}
query, args := ks.sqlQuery().Query()
if err := ks.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (ks *KeysSelect) sqlQuery() sql.Querier {
selector := ks.sql
selector.Select(selector.Columns(ks.fields...)...)
return selector
}

View file

@ -0,0 +1,339 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"fmt"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage"
"github.com/dexidp/dex/storage/ent/db/keys"
"github.com/dexidp/dex/storage/ent/db/predicate"
"gopkg.in/square/go-jose.v2"
)
// KeysUpdate is the builder for updating Keys entities.
type KeysUpdate struct {
config
hooks []Hook
mutation *KeysMutation
}
// Where adds a new predicate for the KeysUpdate builder.
func (ku *KeysUpdate) Where(ps ...predicate.Keys) *KeysUpdate {
ku.mutation.predicates = append(ku.mutation.predicates, ps...)
return ku
}
// SetVerificationKeys sets the "verification_keys" field.
func (ku *KeysUpdate) SetVerificationKeys(sk []storage.VerificationKey) *KeysUpdate {
ku.mutation.SetVerificationKeys(sk)
return ku
}
// SetSigningKey sets the "signing_key" field.
func (ku *KeysUpdate) SetSigningKey(jwk jose.JSONWebKey) *KeysUpdate {
ku.mutation.SetSigningKey(jwk)
return ku
}
// SetSigningKeyPub sets the "signing_key_pub" field.
func (ku *KeysUpdate) SetSigningKeyPub(jwk jose.JSONWebKey) *KeysUpdate {
ku.mutation.SetSigningKeyPub(jwk)
return ku
}
// SetNextRotation sets the "next_rotation" field.
func (ku *KeysUpdate) SetNextRotation(t time.Time) *KeysUpdate {
ku.mutation.SetNextRotation(t)
return ku
}
// Mutation returns the KeysMutation object of the builder.
func (ku *KeysUpdate) Mutation() *KeysMutation {
return ku.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) {
var (
err error
affected int
)
if len(ku.hooks) == 0 {
affected, err = ku.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*KeysMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
ku.mutation = mutation
affected, err = ku.sqlSave(ctx)
mutation.done = true
return affected, err
})
for i := len(ku.hooks) - 1; i >= 0; i-- {
mut = ku.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, ku.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// SaveX is like Save, but panics if an error occurs.
func (ku *KeysUpdate) SaveX(ctx context.Context) int {
affected, err := ku.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (ku *KeysUpdate) Exec(ctx context.Context) error {
_, err := ku.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 {
panic(err)
}
}
func (ku *KeysUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: keys.Table,
Columns: keys.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: keys.FieldID,
},
},
}
if ps := ku.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 {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: keys.FieldVerificationKeys,
})
}
if value, ok := ku.mutation.SigningKey(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: keys.FieldSigningKey,
})
}
if value, ok := ku.mutation.SigningKeyPub(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: keys.FieldSigningKeyPub,
})
}
if value, ok := ku.mutation.NextRotation(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: keys.FieldNextRotation,
})
}
if n, err = sqlgraph.UpdateNodes(ctx, ku.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{keys.Label}
} else if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return 0, err
}
return n, nil
}
// KeysUpdateOne is the builder for updating a single Keys entity.
type KeysUpdateOne struct {
config
fields []string
hooks []Hook
mutation *KeysMutation
}
// SetVerificationKeys sets the "verification_keys" field.
func (kuo *KeysUpdateOne) SetVerificationKeys(sk []storage.VerificationKey) *KeysUpdateOne {
kuo.mutation.SetVerificationKeys(sk)
return kuo
}
// SetSigningKey sets the "signing_key" field.
func (kuo *KeysUpdateOne) SetSigningKey(jwk jose.JSONWebKey) *KeysUpdateOne {
kuo.mutation.SetSigningKey(jwk)
return kuo
}
// SetSigningKeyPub sets the "signing_key_pub" field.
func (kuo *KeysUpdateOne) SetSigningKeyPub(jwk jose.JSONWebKey) *KeysUpdateOne {
kuo.mutation.SetSigningKeyPub(jwk)
return kuo
}
// SetNextRotation sets the "next_rotation" field.
func (kuo *KeysUpdateOne) SetNextRotation(t time.Time) *KeysUpdateOne {
kuo.mutation.SetNextRotation(t)
return kuo
}
// Mutation returns the KeysMutation object of the builder.
func (kuo *KeysUpdateOne) Mutation() *KeysMutation {
return kuo.mutation
}
// 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
}
// Save executes the query and returns the updated Keys entity.
func (kuo *KeysUpdateOne) Save(ctx context.Context) (*Keys, error) {
var (
err error
node *Keys
)
if len(kuo.hooks) == 0 {
node, err = kuo.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*KeysMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
kuo.mutation = mutation
node, err = kuo.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(kuo.hooks) - 1; i >= 0; i-- {
mut = kuo.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, kuo.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX is like Save, but panics if an error occurs.
func (kuo *KeysUpdateOne) SaveX(ctx context.Context) *Keys {
node, err := kuo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (kuo *KeysUpdateOne) Exec(ctx context.Context) error {
_, err := kuo.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 {
panic(err)
}
}
func (kuo *KeysUpdateOne) sqlSave(ctx context.Context) (_node *Keys, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: keys.Table,
Columns: keys.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: keys.FieldID,
},
},
}
id, ok := kuo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing Keys.ID for update")}
}
_spec.Node.ID.Value = id
if fields := kuo.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 {
if !keys.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
}
if f != keys.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := kuo.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 {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: keys.FieldVerificationKeys,
})
}
if value, ok := kuo.mutation.SigningKey(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: keys.FieldSigningKey,
})
}
if value, ok := kuo.mutation.SigningKeyPub(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: keys.FieldSigningKeyPub,
})
}
if value, ok := kuo.mutation.NextRotation(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: keys.FieldNextRotation,
})
}
_node = &Keys{config: kuo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, kuo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{keys.Label}
} else if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return nil, err
}
return _node, nil
}

View file

@ -0,0 +1,72 @@
// Code generated by entc, DO NOT EDIT.
package migrate
import (
"context"
"fmt"
"io"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql/schema"
)
var (
// WithGlobalUniqueID sets the universal ids options to the migration.
// If this option is enabled, ent migration will allocate a 1<<32 range
// for the ids of each entity (table).
// Note that this option cannot be applied on tables that already exist.
WithGlobalUniqueID = schema.WithGlobalUniqueID
// WithDropColumn sets the drop column option to the migration.
// If this option is enabled, ent migration will drop old columns
// that were used for both fields and edges. This defaults to false.
WithDropColumn = schema.WithDropColumn
// WithDropIndex sets the drop index option to the migration.
// If this option is enabled, ent migration will drop old indexes
// that were defined in the schema. This defaults to false.
// Note that unique constraints are defined using `UNIQUE INDEX`,
// and therefore, it's recommended to enable this option to get more
// flexibility in the schema changes.
WithDropIndex = schema.WithDropIndex
// WithFixture sets the foreign-key renaming option to the migration when upgrading
// ent from v0.1.0 (issue-#285). Defaults to false.
WithFixture = schema.WithFixture
// WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true.
WithForeignKeys = schema.WithForeignKeys
)
// Schema is the API for creating, migrating and dropping a schema.
type Schema struct {
drv dialect.Driver
universalID bool
}
// NewSchema creates a new schema client.
func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} }
// Create creates all schema resources.
func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error {
migrate, err := schema.NewMigrate(s.drv, opts...)
if err != nil {
return fmt.Errorf("ent/migrate: %w", err)
}
return migrate.Create(ctx, Tables...)
}
// WriteTo writes the schema changes to w instead of running them against the database.
//
// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil {
// log.Fatal(err)
// }
//
func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error {
drv := &schema.WriteDriver{
Writer: w,
Driver: s.drv,
}
migrate, err := schema.NewMigrate(drv, opts...)
if err != nil {
return fmt.Errorf("ent/migrate: %w", err)
}
return migrate.Create(ctx, Tables...)
}

View file

@ -0,0 +1,220 @@
// Code generated by entc, DO NOT EDIT.
package migrate
import (
"entgo.io/ent/dialect/sql/schema"
"entgo.io/ent/schema/field"
)
var (
// AuthCodesColumns holds the columns for the "auth_codes" table.
AuthCodesColumns = []*schema.Column{
{Name: "id", Type: field.TypeString, Unique: true, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "client_id", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "scopes", Type: field.TypeJSON, Nullable: true},
{Name: "nonce", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "redirect_uri", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "claims_user_id", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "claims_username", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "claims_email", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "claims_email_verified", Type: field.TypeBool},
{Name: "claims_groups", Type: field.TypeJSON, Nullable: true},
{Name: "claims_preferred_username", Type: field.TypeString, Size: 2147483647, Default: "", SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "connector_id", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "connector_data", Type: field.TypeBytes, Nullable: true},
{Name: "expiry", Type: field.TypeTime},
{Name: "code_challenge", Type: field.TypeString, Size: 2147483647, Default: "", SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "code_challenge_method", Type: field.TypeString, Size: 2147483647, Default: "", SchemaType: map[string]string{"sqlite3": "text"}},
}
// AuthCodesTable holds the schema information for the "auth_codes" table.
AuthCodesTable = &schema.Table{
Name: "auth_codes",
Columns: AuthCodesColumns,
PrimaryKey: []*schema.Column{AuthCodesColumns[0]},
ForeignKeys: []*schema.ForeignKey{},
}
// AuthRequestsColumns holds the columns for the "auth_requests" table.
AuthRequestsColumns = []*schema.Column{
{Name: "id", Type: field.TypeString, Unique: true, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "client_id", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "scopes", Type: field.TypeJSON, Nullable: true},
{Name: "response_types", Type: field.TypeJSON, Nullable: true},
{Name: "redirect_uri", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "nonce", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "state", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "force_approval_prompt", Type: field.TypeBool},
{Name: "logged_in", Type: field.TypeBool},
{Name: "claims_user_id", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "claims_username", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "claims_email", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "claims_email_verified", Type: field.TypeBool},
{Name: "claims_groups", Type: field.TypeJSON, Nullable: true},
{Name: "claims_preferred_username", Type: field.TypeString, Size: 2147483647, Default: "", SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "connector_id", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "connector_data", Type: field.TypeBytes, Nullable: true},
{Name: "expiry", Type: field.TypeTime},
{Name: "code_challenge", Type: field.TypeString, Size: 2147483647, Default: "", SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "code_challenge_method", Type: field.TypeString, Size: 2147483647, Default: "", SchemaType: map[string]string{"sqlite3": "text"}},
}
// AuthRequestsTable holds the schema information for the "auth_requests" table.
AuthRequestsTable = &schema.Table{
Name: "auth_requests",
Columns: AuthRequestsColumns,
PrimaryKey: []*schema.Column{AuthRequestsColumns[0]},
ForeignKeys: []*schema.ForeignKey{},
}
// ConnectorsColumns holds the columns for the "connectors" table.
ConnectorsColumns = []*schema.Column{
{Name: "id", Type: field.TypeString, Unique: true, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "type", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "name", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "resource_version", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "config", Type: field.TypeBytes},
}
// ConnectorsTable holds the schema information for the "connectors" table.
ConnectorsTable = &schema.Table{
Name: "connectors",
Columns: ConnectorsColumns,
PrimaryKey: []*schema.Column{ConnectorsColumns[0]},
ForeignKeys: []*schema.ForeignKey{},
}
// DeviceRequestsColumns holds the columns for the "device_requests" table.
DeviceRequestsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "user_code", Type: field.TypeString, Unique: true, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "device_code", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "client_id", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "client_secret", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "scopes", Type: field.TypeJSON, Nullable: true},
{Name: "expiry", Type: field.TypeTime},
}
// DeviceRequestsTable holds the schema information for the "device_requests" table.
DeviceRequestsTable = &schema.Table{
Name: "device_requests",
Columns: DeviceRequestsColumns,
PrimaryKey: []*schema.Column{DeviceRequestsColumns[0]},
ForeignKeys: []*schema.ForeignKey{},
}
// DeviceTokensColumns holds the columns for the "device_tokens" table.
DeviceTokensColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "device_code", Type: field.TypeString, Unique: true, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "status", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "token", Type: field.TypeBytes, Nullable: true},
{Name: "expiry", Type: field.TypeTime},
{Name: "last_request", Type: field.TypeTime},
{Name: "poll_interval", Type: field.TypeInt},
}
// DeviceTokensTable holds the schema information for the "device_tokens" table.
DeviceTokensTable = &schema.Table{
Name: "device_tokens",
Columns: DeviceTokensColumns,
PrimaryKey: []*schema.Column{DeviceTokensColumns[0]},
ForeignKeys: []*schema.ForeignKey{},
}
// KeysColumns holds the columns for the "keys" table.
KeysColumns = []*schema.Column{
{Name: "id", Type: field.TypeString, Unique: true, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "verification_keys", Type: field.TypeJSON},
{Name: "signing_key", Type: field.TypeJSON},
{Name: "signing_key_pub", Type: field.TypeJSON},
{Name: "next_rotation", Type: field.TypeTime},
}
// KeysTable holds the schema information for the "keys" table.
KeysTable = &schema.Table{
Name: "keys",
Columns: KeysColumns,
PrimaryKey: []*schema.Column{KeysColumns[0]},
ForeignKeys: []*schema.ForeignKey{},
}
// Oauth2clientsColumns holds the columns for the "oauth2clients" table.
Oauth2clientsColumns = []*schema.Column{
{Name: "id", Type: field.TypeString, Unique: true, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "secret", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "redirect_uris", Type: field.TypeJSON, Nullable: true},
{Name: "trusted_peers", Type: field.TypeJSON, Nullable: true},
{Name: "public", Type: field.TypeBool},
{Name: "name", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "logo_url", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
}
// Oauth2clientsTable holds the schema information for the "oauth2clients" table.
Oauth2clientsTable = &schema.Table{
Name: "oauth2clients",
Columns: Oauth2clientsColumns,
PrimaryKey: []*schema.Column{Oauth2clientsColumns[0]},
ForeignKeys: []*schema.ForeignKey{},
}
// OfflineSessionsColumns holds the columns for the "offline_sessions" table.
OfflineSessionsColumns = []*schema.Column{
{Name: "id", Type: field.TypeString, Unique: true, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "user_id", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "conn_id", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "refresh", Type: field.TypeBytes},
{Name: "connector_data", Type: field.TypeBytes, Nullable: true},
}
// OfflineSessionsTable holds the schema information for the "offline_sessions" table.
OfflineSessionsTable = &schema.Table{
Name: "offline_sessions",
Columns: OfflineSessionsColumns,
PrimaryKey: []*schema.Column{OfflineSessionsColumns[0]},
ForeignKeys: []*schema.ForeignKey{},
}
// PasswordsColumns holds the columns for the "passwords" table.
PasswordsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "email", Type: field.TypeString, Unique: true, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "hash", Type: field.TypeBytes},
{Name: "username", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "user_id", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
}
// PasswordsTable holds the schema information for the "passwords" table.
PasswordsTable = &schema.Table{
Name: "passwords",
Columns: PasswordsColumns,
PrimaryKey: []*schema.Column{PasswordsColumns[0]},
ForeignKeys: []*schema.ForeignKey{},
}
// RefreshTokensColumns holds the columns for the "refresh_tokens" table.
RefreshTokensColumns = []*schema.Column{
{Name: "id", Type: field.TypeString, Unique: true, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "client_id", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "scopes", Type: field.TypeJSON, Nullable: true},
{Name: "nonce", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "claims_user_id", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "claims_username", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "claims_email", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "claims_email_verified", Type: field.TypeBool},
{Name: "claims_groups", Type: field.TypeJSON, Nullable: true},
{Name: "claims_preferred_username", Type: field.TypeString, Size: 2147483647, Default: "", SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "connector_id", Type: field.TypeString, Size: 2147483647, SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "connector_data", Type: field.TypeBytes, Nullable: true},
{Name: "token", Type: field.TypeString, Size: 2147483647, Default: "", SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "obsolete_token", Type: field.TypeString, Size: 2147483647, Default: "", SchemaType: map[string]string{"sqlite3": "text"}},
{Name: "created_at", Type: field.TypeTime},
{Name: "last_used", Type: field.TypeTime},
}
// RefreshTokensTable holds the schema information for the "refresh_tokens" table.
RefreshTokensTable = &schema.Table{
Name: "refresh_tokens",
Columns: RefreshTokensColumns,
PrimaryKey: []*schema.Column{RefreshTokensColumns[0]},
ForeignKeys: []*schema.ForeignKey{},
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
AuthCodesTable,
AuthRequestsTable,
ConnectorsTable,
DeviceRequestsTable,
DeviceTokensTable,
KeysTable,
Oauth2clientsTable,
OfflineSessionsTable,
PasswordsTable,
RefreshTokensTable,
}
)
func init() {
}

7243
storage/ent/db/mutation.go Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,158 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"encoding/json"
"fmt"
"strings"
"entgo.io/ent/dialect/sql"
"github.com/dexidp/dex/storage/ent/db/oauth2client"
)
// OAuth2Client is the model entity for the OAuth2Client schema.
type OAuth2Client struct {
config `json:"-"`
// ID of the ent.
ID string `json:"id,omitempty"`
// Secret holds the value of the "secret" field.
Secret string `json:"secret,omitempty"`
// RedirectUris holds the value of the "redirect_uris" field.
RedirectUris []string `json:"redirect_uris,omitempty"`
// TrustedPeers holds the value of the "trusted_peers" field.
TrustedPeers []string `json:"trusted_peers,omitempty"`
// Public holds the value of the "public" field.
Public bool `json:"public,omitempty"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// LogoURL holds the value of the "logo_url" field.
LogoURL string `json:"logo_url,omitempty"`
}
// scanValues returns the types for scanning values from sql.Rows.
func (*OAuth2Client) scanValues(columns []string) ([]interface{}, error) {
values := make([]interface{}, len(columns))
for i := range columns {
switch columns[i] {
case oauth2client.FieldRedirectUris, oauth2client.FieldTrustedPeers:
values[i] = new([]byte)
case oauth2client.FieldPublic:
values[i] = new(sql.NullBool)
case oauth2client.FieldID, oauth2client.FieldSecret, oauth2client.FieldName, oauth2client.FieldLogoURL:
values[i] = new(sql.NullString)
default:
return nil, fmt.Errorf("unexpected column %q for type OAuth2Client", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the OAuth2Client fields.
func (o *OAuth2Client) assignValues(columns []string, values []interface{}) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case oauth2client.FieldID:
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
}
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
}
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 {
return fmt.Errorf("unmarshal field redirect_uris: %w", err)
}
}
case oauth2client.FieldTrustedPeers:
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 {
return fmt.Errorf("unmarshal field trusted_peers: %w", err)
}
}
case oauth2client.FieldPublic:
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
}
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
}
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
}
}
}
return nil
}
// 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 (&OAuth2ClientClient{config: o.config}).UpdateOne(o)
}
// 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)
if !ok {
panic("db: OAuth2Client is not a transactional entity")
}
o.config.driver = tx.drv
return o
}
// String implements the fmt.Stringer.
func (o *OAuth2Client) String() string {
var builder strings.Builder
builder.WriteString("OAuth2Client(")
builder.WriteString(fmt.Sprintf("id=%v", o.ID))
builder.WriteString(", secret=")
builder.WriteString(o.Secret)
builder.WriteString(", redirect_uris=")
builder.WriteString(fmt.Sprintf("%v", o.RedirectUris))
builder.WriteString(", trusted_peers=")
builder.WriteString(fmt.Sprintf("%v", o.TrustedPeers))
builder.WriteString(", public=")
builder.WriteString(fmt.Sprintf("%v", o.Public))
builder.WriteString(", name=")
builder.WriteString(o.Name)
builder.WriteString(", logo_url=")
builder.WriteString(o.LogoURL)
builder.WriteByte(')')
return builder.String()
}
// OAuth2Clients is a parsable slice of OAuth2Client.
type OAuth2Clients []*OAuth2Client
func (o OAuth2Clients) config(cfg config) {
for _i := range o {
o[_i].config = cfg
}
}

View file

@ -0,0 +1,56 @@
// Code generated by entc, DO NOT EDIT.
package oauth2client
const (
// Label holds the string label denoting the oauth2client type in the database.
Label = "oauth2client"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldSecret holds the string denoting the secret field in the database.
FieldSecret = "secret"
// FieldRedirectUris holds the string denoting the redirect_uris field in the database.
FieldRedirectUris = "redirect_uris"
// FieldTrustedPeers holds the string denoting the trusted_peers field in the database.
FieldTrustedPeers = "trusted_peers"
// FieldPublic holds the string denoting the public field in the database.
FieldPublic = "public"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// FieldLogoURL holds the string denoting the logo_url field in the database.
FieldLogoURL = "logo_url"
// Table holds the table name of the oauth2client in the database.
Table = "oauth2clients"
)
// Columns holds all SQL columns for oauth2client fields.
var Columns = []string{
FieldID,
FieldSecret,
FieldRedirectUris,
FieldTrustedPeers,
FieldPublic,
FieldName,
FieldLogoURL,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// SecretValidator is a validator for the "secret" field. It is called by the builders before save.
SecretValidator func(string) error
// NameValidator is a validator for the "name" field. It is called by the builders before save.
NameValidator func(string) error
// LogoURLValidator is a validator for the "logo_url" field. It is called by the builders before save.
LogoURLValidator func(string) error
// IDValidator is a validator for the "id" field. It is called by the builders before save.
IDValidator func(string) error
)

View file

@ -0,0 +1,526 @@
// Code generated by entc, DO NOT EDIT.
package oauth2client
import (
"entgo.io/ent/dialect/sql"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// ID filters vertices based on their ID field.
func ID(id string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldID), id))
})
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.In(s.C(FieldID), v...))
})
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.NotIn(s.C(FieldID), v...))
})
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldID), id))
})
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldID), id))
})
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldID), id))
})
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldID), id))
})
}
// Secret applies equality check predicate on the "secret" field. It's identical to SecretEQ.
func Secret(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldSecret), v))
})
}
// Public applies equality check predicate on the "public" field. It's identical to PublicEQ.
func Public(v bool) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldPublic), v))
})
}
// Name applies equality check predicate on the "name" field. It's identical to NameEQ.
func Name(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldName), v))
})
}
// LogoURL applies equality check predicate on the "logo_url" field. It's identical to LogoURLEQ.
func LogoURL(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldLogoURL), v))
})
}
// SecretEQ applies the EQ predicate on the "secret" field.
func SecretEQ(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldSecret), v))
})
}
// SecretNEQ applies the NEQ predicate on the "secret" field.
func SecretNEQ(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldSecret), v))
})
}
// SecretIn applies the In predicate on the "secret" field.
func SecretIn(vs ...string) predicate.OAuth2Client {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.OAuth2Client(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldSecret), v...))
})
}
// SecretNotIn applies the NotIn predicate on the "secret" field.
func SecretNotIn(vs ...string) predicate.OAuth2Client {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.OAuth2Client(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldSecret), v...))
})
}
// SecretGT applies the GT predicate on the "secret" field.
func SecretGT(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldSecret), v))
})
}
// SecretGTE applies the GTE predicate on the "secret" field.
func SecretGTE(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldSecret), v))
})
}
// SecretLT applies the LT predicate on the "secret" field.
func SecretLT(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldSecret), v))
})
}
// SecretLTE applies the LTE predicate on the "secret" field.
func SecretLTE(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldSecret), v))
})
}
// SecretContains applies the Contains predicate on the "secret" field.
func SecretContains(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldSecret), v))
})
}
// SecretHasPrefix applies the HasPrefix predicate on the "secret" field.
func SecretHasPrefix(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldSecret), v))
})
}
// SecretHasSuffix applies the HasSuffix predicate on the "secret" field.
func SecretHasSuffix(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldSecret), v))
})
}
// SecretEqualFold applies the EqualFold predicate on the "secret" field.
func SecretEqualFold(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldSecret), v))
})
}
// SecretContainsFold applies the ContainsFold predicate on the "secret" field.
func SecretContainsFold(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldSecret), v))
})
}
// RedirectUrisIsNil applies the IsNil predicate on the "redirect_uris" field.
func RedirectUrisIsNil() predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldRedirectUris)))
})
}
// RedirectUrisNotNil applies the NotNil predicate on the "redirect_uris" field.
func RedirectUrisNotNil() predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.NotNull(s.C(FieldRedirectUris)))
})
}
// TrustedPeersIsNil applies the IsNil predicate on the "trusted_peers" field.
func TrustedPeersIsNil() predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldTrustedPeers)))
})
}
// TrustedPeersNotNil applies the NotNil predicate on the "trusted_peers" field.
func TrustedPeersNotNil() predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.NotNull(s.C(FieldTrustedPeers)))
})
}
// PublicEQ applies the EQ predicate on the "public" field.
func PublicEQ(v bool) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldPublic), v))
})
}
// PublicNEQ applies the NEQ predicate on the "public" field.
func PublicNEQ(v bool) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldPublic), v))
})
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldName), v))
})
}
// NameNEQ applies the NEQ predicate on the "name" field.
func NameNEQ(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldName), v))
})
}
// NameIn applies the In predicate on the "name" field.
func NameIn(vs ...string) predicate.OAuth2Client {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.OAuth2Client(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldName), v...))
})
}
// NameNotIn applies the NotIn predicate on the "name" field.
func NameNotIn(vs ...string) predicate.OAuth2Client {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.OAuth2Client(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldName), v...))
})
}
// NameGT applies the GT predicate on the "name" field.
func NameGT(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldName), v))
})
}
// NameGTE applies the GTE predicate on the "name" field.
func NameGTE(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldName), v))
})
}
// NameLT applies the LT predicate on the "name" field.
func NameLT(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldName), v))
})
}
// NameLTE applies the LTE predicate on the "name" field.
func NameLTE(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldName), v))
})
}
// NameContains applies the Contains predicate on the "name" field.
func NameContains(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldName), v))
})
}
// NameHasPrefix applies the HasPrefix predicate on the "name" field.
func NameHasPrefix(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldName), v))
})
}
// NameHasSuffix applies the HasSuffix predicate on the "name" field.
func NameHasSuffix(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldName), v))
})
}
// NameEqualFold applies the EqualFold predicate on the "name" field.
func NameEqualFold(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldName), v))
})
}
// NameContainsFold applies the ContainsFold predicate on the "name" field.
func NameContainsFold(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldName), v))
})
}
// LogoURLEQ applies the EQ predicate on the "logo_url" field.
func LogoURLEQ(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldLogoURL), v))
})
}
// LogoURLNEQ applies the NEQ predicate on the "logo_url" field.
func LogoURLNEQ(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldLogoURL), v))
})
}
// LogoURLIn applies the In predicate on the "logo_url" field.
func LogoURLIn(vs ...string) predicate.OAuth2Client {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.OAuth2Client(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldLogoURL), v...))
})
}
// LogoURLNotIn applies the NotIn predicate on the "logo_url" field.
func LogoURLNotIn(vs ...string) predicate.OAuth2Client {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.OAuth2Client(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldLogoURL), v...))
})
}
// LogoURLGT applies the GT predicate on the "logo_url" field.
func LogoURLGT(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldLogoURL), v))
})
}
// LogoURLGTE applies the GTE predicate on the "logo_url" field.
func LogoURLGTE(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldLogoURL), v))
})
}
// LogoURLLT applies the LT predicate on the "logo_url" field.
func LogoURLLT(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldLogoURL), v))
})
}
// LogoURLLTE applies the LTE predicate on the "logo_url" field.
func LogoURLLTE(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldLogoURL), v))
})
}
// LogoURLContains applies the Contains predicate on the "logo_url" field.
func LogoURLContains(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldLogoURL), v))
})
}
// LogoURLHasPrefix applies the HasPrefix predicate on the "logo_url" field.
func LogoURLHasPrefix(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldLogoURL), v))
})
}
// LogoURLHasSuffix applies the HasSuffix predicate on the "logo_url" field.
func LogoURLHasSuffix(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldLogoURL), v))
})
}
// LogoURLEqualFold applies the EqualFold predicate on the "logo_url" field.
func LogoURLEqualFold(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldLogoURL), v))
})
}
// LogoURLContainsFold applies the ContainsFold predicate on the "logo_url" field.
func LogoURLContainsFold(v string) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldLogoURL), v))
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.OAuth2Client) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for _, p := range predicates {
p(s1)
}
s.Where(s1.P())
})
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.OAuth2Client) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for i, p := range predicates {
if i > 0 {
s1.Or()
}
p(s1)
}
s.Where(s1.P())
})
}
// Not applies the not operator on the given predicate.
func Not(p predicate.OAuth2Client) predicate.OAuth2Client {
return predicate.OAuth2Client(func(s *sql.Selector) {
p(s.Not())
})
}

View file

@ -0,0 +1,289 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/oauth2client"
)
// OAuth2ClientCreate is the builder for creating a OAuth2Client entity.
type OAuth2ClientCreate struct {
config
mutation *OAuth2ClientMutation
hooks []Hook
}
// SetSecret sets the "secret" field.
func (oc *OAuth2ClientCreate) SetSecret(s string) *OAuth2ClientCreate {
oc.mutation.SetSecret(s)
return oc
}
// SetRedirectUris sets the "redirect_uris" field.
func (oc *OAuth2ClientCreate) SetRedirectUris(s []string) *OAuth2ClientCreate {
oc.mutation.SetRedirectUris(s)
return oc
}
// SetTrustedPeers sets the "trusted_peers" field.
func (oc *OAuth2ClientCreate) SetTrustedPeers(s []string) *OAuth2ClientCreate {
oc.mutation.SetTrustedPeers(s)
return oc
}
// SetPublic sets the "public" field.
func (oc *OAuth2ClientCreate) SetPublic(b bool) *OAuth2ClientCreate {
oc.mutation.SetPublic(b)
return oc
}
// SetName sets the "name" field.
func (oc *OAuth2ClientCreate) SetName(s string) *OAuth2ClientCreate {
oc.mutation.SetName(s)
return oc
}
// SetLogoURL sets the "logo_url" field.
func (oc *OAuth2ClientCreate) SetLogoURL(s string) *OAuth2ClientCreate {
oc.mutation.SetLogoURL(s)
return oc
}
// SetID sets the "id" field.
func (oc *OAuth2ClientCreate) SetID(s string) *OAuth2ClientCreate {
oc.mutation.SetID(s)
return oc
}
// Mutation returns the OAuth2ClientMutation object of the builder.
func (oc *OAuth2ClientCreate) Mutation() *OAuth2ClientMutation {
return oc.mutation
}
// Save creates the OAuth2Client in the database.
func (oc *OAuth2ClientCreate) Save(ctx context.Context) (*OAuth2Client, error) {
var (
err error
node *OAuth2Client
)
if len(oc.hooks) == 0 {
if err = oc.check(); err != nil {
return nil, err
}
node, err = oc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*OAuth2ClientMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = oc.check(); err != nil {
return nil, err
}
oc.mutation = mutation
node, err = oc.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(oc.hooks) - 1; i >= 0; i-- {
mut = oc.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, oc.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (oc *OAuth2ClientCreate) SaveX(ctx context.Context) *OAuth2Client {
v, err := oc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// check runs all checks and user-defined validators on the builder.
func (oc *OAuth2ClientCreate) check() error {
if _, ok := oc.mutation.Secret(); !ok {
return &ValidationError{Name: "secret", err: errors.New("db: missing required field \"secret\"")}
}
if v, ok := oc.mutation.Secret(); ok {
if err := oauth2client.SecretValidator(v); err != nil {
return &ValidationError{Name: "secret", err: fmt.Errorf("db: validator failed for field \"secret\": %w", err)}
}
}
if _, ok := oc.mutation.Public(); !ok {
return &ValidationError{Name: "public", err: errors.New("db: missing required field \"public\"")}
}
if _, ok := oc.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New("db: missing required field \"name\"")}
}
if v, ok := oc.mutation.Name(); ok {
if err := oauth2client.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf("db: validator failed for field \"name\": %w", err)}
}
}
if _, ok := oc.mutation.LogoURL(); !ok {
return &ValidationError{Name: "logo_url", err: errors.New("db: missing required field \"logo_url\"")}
}
if v, ok := oc.mutation.LogoURL(); ok {
if err := oauth2client.LogoURLValidator(v); err != nil {
return &ValidationError{Name: "logo_url", err: fmt.Errorf("db: validator failed for field \"logo_url\": %w", err)}
}
}
if v, ok := oc.mutation.ID(); ok {
if err := oauth2client.IDValidator(v); err != nil {
return &ValidationError{Name: "id", err: fmt.Errorf("db: validator failed for field \"id\": %w", err)}
}
}
return nil
}
func (oc *OAuth2ClientCreate) sqlSave(ctx context.Context) (*OAuth2Client, error) {
_node, _spec := oc.createSpec()
if err := sqlgraph.CreateNode(ctx, oc.driver, _spec); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return nil, err
}
return _node, nil
}
func (oc *OAuth2ClientCreate) createSpec() (*OAuth2Client, *sqlgraph.CreateSpec) {
var (
_node = &OAuth2Client{config: oc.config}
_spec = &sqlgraph.CreateSpec{
Table: oauth2client.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: oauth2client.FieldID,
},
}
)
if id, ok := oc.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = id
}
if value, ok := oc.mutation.Secret(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: oauth2client.FieldSecret,
})
_node.Secret = value
}
if value, ok := oc.mutation.RedirectUris(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: oauth2client.FieldRedirectUris,
})
_node.RedirectUris = value
}
if value, ok := oc.mutation.TrustedPeers(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: oauth2client.FieldTrustedPeers,
})
_node.TrustedPeers = value
}
if value, ok := oc.mutation.Public(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: oauth2client.FieldPublic,
})
_node.Public = value
}
if value, ok := oc.mutation.Name(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: oauth2client.FieldName,
})
_node.Name = value
}
if value, ok := oc.mutation.LogoURL(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: oauth2client.FieldLogoURL,
})
_node.LogoURL = value
}
return _node, _spec
}
// OAuth2ClientCreateBulk is the builder for creating many OAuth2Client entities in bulk.
type OAuth2ClientCreateBulk struct {
config
builders []*OAuth2ClientCreate
}
// Save creates the OAuth2Client entities in the database.
func (ocb *OAuth2ClientCreateBulk) Save(ctx context.Context) ([]*OAuth2Client, error) {
specs := make([]*sqlgraph.CreateSpec, len(ocb.builders))
nodes := make([]*OAuth2Client, len(ocb.builders))
mutators := make([]Mutator, len(ocb.builders))
for i := range ocb.builders {
func(i int, root context.Context) {
builder := ocb.builders[i]
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*OAuth2ClientMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
nodes[i], specs[i] = builder.createSpec()
var err error
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, ocb.builders[i+1].mutation)
} else {
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, ocb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
}
}
mutation.done = true
if err != nil {
return nil, err
}
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, ocb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (ocb *OAuth2ClientCreateBulk) SaveX(ctx context.Context) []*OAuth2Client {
v, err := ocb.Save(ctx)
if err != nil {
panic(err)
}
return v
}

View file

@ -0,0 +1,108 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/oauth2client"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// OAuth2ClientDelete is the builder for deleting a OAuth2Client entity.
type OAuth2ClientDelete struct {
config
hooks []Hook
mutation *OAuth2ClientMutation
}
// Where adds a new predicate to the OAuth2ClientDelete builder.
func (od *OAuth2ClientDelete) Where(ps ...predicate.OAuth2Client) *OAuth2ClientDelete {
od.mutation.predicates = append(od.mutation.predicates, ps...)
return od
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (od *OAuth2ClientDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(od.hooks) == 0 {
affected, err = od.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*OAuth2ClientMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
od.mutation = mutation
affected, err = od.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(od.hooks) - 1; i >= 0; i-- {
mut = od.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, od.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (od *OAuth2ClientDelete) ExecX(ctx context.Context) int {
n, err := od.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (od *OAuth2ClientDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: oauth2client.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: oauth2client.FieldID,
},
},
}
if ps := od.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return sqlgraph.DeleteNodes(ctx, od.driver, _spec)
}
// OAuth2ClientDeleteOne is the builder for deleting a single OAuth2Client entity.
type OAuth2ClientDeleteOne struct {
od *OAuth2ClientDelete
}
// Exec executes the deletion query.
func (odo *OAuth2ClientDeleteOne) Exec(ctx context.Context) error {
n, err := odo.od.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{oauth2client.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (odo *OAuth2ClientDeleteOne) ExecX(ctx context.Context) {
odo.od.ExecX(ctx)
}

View file

@ -0,0 +1,906 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"errors"
"fmt"
"math"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/oauth2client"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// OAuth2ClientQuery is the builder for querying OAuth2Client entities.
type OAuth2ClientQuery struct {
config
limit *int
offset *int
unique *bool
order []OrderFunc
fields []string
predicates []predicate.OAuth2Client
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// 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
}
// Limit adds a limit step to the query.
func (oq *OAuth2ClientQuery) Limit(limit int) *OAuth2ClientQuery {
oq.limit = &limit
return oq
}
// Offset adds an offset step to the query.
func (oq *OAuth2ClientQuery) Offset(offset int) *OAuth2ClientQuery {
oq.offset = &offset
return oq
}
// 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.unique = &unique
return oq
}
// Order adds an order step to the query.
func (oq *OAuth2ClientQuery) Order(o ...OrderFunc) *OAuth2ClientQuery {
oq.order = append(oq.order, o...)
return oq
}
// 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(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{oauth2client.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (oq *OAuth2ClientQuery) FirstX(ctx context.Context) *OAuth2Client {
node, err := oq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// 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) {
var ids []string
if ids, err = oq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{oauth2client.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (oq *OAuth2ClientQuery) FirstIDX(ctx context.Context) string {
id, err := oq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single OAuth2Client entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when exactly one OAuth2Client entity is not 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(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{oauth2client.Label}
default:
return nil, &NotSingularError{oauth2client.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (oq *OAuth2ClientQuery) OnlyX(ctx context.Context) *OAuth2Client {
node, err := oq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only OAuth2Client ID in the query.
// Returns a *NotSingularError when exactly one OAuth2Client ID is not found.
// Returns a *NotFoundError when no entities are found.
func (oq *OAuth2ClientQuery) OnlyID(ctx context.Context) (id string, err error) {
var ids []string
if ids, err = oq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{oauth2client.Label}
default:
err = &NotSingularError{oauth2client.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (oq *OAuth2ClientQuery) OnlyIDX(ctx context.Context) string {
id, err := oq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of OAuth2Clients.
func (oq *OAuth2ClientQuery) All(ctx context.Context) ([]*OAuth2Client, error) {
if err := oq.prepareQuery(ctx); err != nil {
return nil, err
}
return oq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (oq *OAuth2ClientQuery) AllX(ctx context.Context) []*OAuth2Client {
nodes, err := oq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of OAuth2Client IDs.
func (oq *OAuth2ClientQuery) IDs(ctx context.Context) ([]string, error) {
var ids []string
if err := oq.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)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (oq *OAuth2ClientQuery) Count(ctx context.Context) (int, error) {
if err := oq.prepareQuery(ctx); err != nil {
return 0, err
}
return oq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (oq *OAuth2ClientQuery) CountX(ctx context.Context) int {
count, err := oq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (oq *OAuth2ClientQuery) Exist(ctx context.Context) (bool, error) {
if err := oq.prepareQuery(ctx); err != nil {
return false, err
}
return oq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (oq *OAuth2ClientQuery) ExistX(ctx context.Context) bool {
exist, err := oq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// 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 {
return nil
}
return &OAuth2ClientQuery{
config: oq.config,
limit: oq.limit,
offset: oq.offset,
order: append([]OrderFunc{}, oq.order...),
predicates: append([]predicate.OAuth2Client{}, oq.predicates...),
// clone intermediate query.
sql: oq.sql.Clone(),
path: oq.path,
}
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// Secret string `json:"secret,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.OAuth2Client.Query().
// GroupBy(oauth2client.FieldSecret).
// Aggregate(db.Count()).
// Scan(ctx, &v)
//
func (oq *OAuth2ClientQuery) GroupBy(field string, fields ...string) *OAuth2ClientGroupBy {
group := &OAuth2ClientGroupBy{config: oq.config}
group.fields = append([]string{field}, fields...)
group.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := oq.prepareQuery(ctx); err != nil {
return nil, err
}
return oq.sqlQuery(ctx), nil
}
return group
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// Secret string `json:"secret,omitempty"`
// }
//
// client.OAuth2Client.Query().
// Select(oauth2client.FieldSecret).
// Scan(ctx, &v)
//
func (oq *OAuth2ClientQuery) Select(field string, fields ...string) *OAuth2ClientSelect {
oq.fields = append([]string{field}, fields...)
return &OAuth2ClientSelect{OAuth2ClientQuery: oq}
}
func (oq *OAuth2ClientQuery) prepareQuery(ctx context.Context) error {
for _, f := range oq.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 err != nil {
return err
}
oq.sql = prev
}
return nil
}
func (oq *OAuth2ClientQuery) sqlAll(ctx context.Context) ([]*OAuth2Client, error) {
var (
nodes = []*OAuth2Client{}
_spec = oq.querySpec()
)
_spec.ScanValues = func(columns []string) ([]interface{}, error) {
node := &OAuth2Client{config: oq.config}
nodes = append(nodes, node)
return node.scanValues(columns)
}
_spec.Assign = func(columns []string, values []interface{}) error {
if len(nodes) == 0 {
return fmt.Errorf("db: Assign called without calling ScanValues")
}
node := nodes[len(nodes)-1]
return node.assignValues(columns, values)
}
if err := sqlgraph.QueryNodes(ctx, oq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (oq *OAuth2ClientQuery) sqlCount(ctx context.Context) (int, error) {
_spec := oq.querySpec()
return sqlgraph.CountNodes(ctx, oq.driver, _spec)
}
func (oq *OAuth2ClientQuery) sqlExist(ctx context.Context) (bool, error) {
n, err := oq.sqlCount(ctx)
if err != nil {
return false, fmt.Errorf("db: check existence: %w", err)
}
return n > 0, nil
}
func (oq *OAuth2ClientQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: oauth2client.Table,
Columns: oauth2client.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: oauth2client.FieldID,
},
},
From: oq.sql,
Unique: true,
}
if unique := oq.unique; unique != nil {
_spec.Unique = *unique
}
if fields := oq.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 {
if fields[i] != oauth2client.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := oq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := oq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := oq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := oq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (oq *OAuth2ClientQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(oq.driver.Dialect())
t1 := builder.Table(oauth2client.Table)
selector := builder.Select(t1.Columns(oauth2client.Columns...)...).From(t1)
if oq.sql != nil {
selector = oq.sql
selector.Select(selector.Columns(oauth2client.Columns...)...)
}
for _, p := range oq.predicates {
p(selector)
}
for _, p := range oq.order {
p(selector)
}
if offset := oq.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.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// OAuth2ClientGroupBy is the group-by builder for OAuth2Client entities.
type OAuth2ClientGroupBy struct {
config
fields []string
fns []AggregateFunc
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Aggregate adds the given aggregation functions to the group-by query.
func (ogb *OAuth2ClientGroupBy) Aggregate(fns ...AggregateFunc) *OAuth2ClientGroupBy {
ogb.fns = append(ogb.fns, fns...)
return ogb
}
// Scan applies the group-by query and scans the result into the given value.
func (ogb *OAuth2ClientGroupBy) Scan(ctx context.Context, v interface{}) error {
query, err := ogb.path(ctx)
if err != nil {
return err
}
ogb.sql = query
return ogb.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (ogb *OAuth2ClientGroupBy) ScanX(ctx context.Context, v interface{}) {
if err := ogb.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from group-by.
// It is only allowed when executing a group-by query with one field.
func (ogb *OAuth2ClientGroupBy) Strings(ctx context.Context) ([]string, error) {
if len(ogb.fields) > 1 {
return nil, errors.New("db: OAuth2ClientGroupBy.Strings is not achievable when grouping more than 1 field")
}
var v []string
if err := ogb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (ogb *OAuth2ClientGroupBy) StringsX(ctx context.Context) []string {
v, err := ogb.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (ogb *OAuth2ClientGroupBy) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = ogb.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{oauth2client.Label}
default:
err = fmt.Errorf("db: OAuth2ClientGroupBy.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (ogb *OAuth2ClientGroupBy) StringX(ctx context.Context) string {
v, err := ogb.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from group-by.
// It is only allowed when executing a group-by query with one field.
func (ogb *OAuth2ClientGroupBy) Ints(ctx context.Context) ([]int, error) {
if len(ogb.fields) > 1 {
return nil, errors.New("db: OAuth2ClientGroupBy.Ints is not achievable when grouping more than 1 field")
}
var v []int
if err := ogb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (ogb *OAuth2ClientGroupBy) IntsX(ctx context.Context) []int {
v, err := ogb.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (ogb *OAuth2ClientGroupBy) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = ogb.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{oauth2client.Label}
default:
err = fmt.Errorf("db: OAuth2ClientGroupBy.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (ogb *OAuth2ClientGroupBy) IntX(ctx context.Context) int {
v, err := ogb.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from group-by.
// It is only allowed when executing a group-by query with one field.
func (ogb *OAuth2ClientGroupBy) Float64s(ctx context.Context) ([]float64, error) {
if len(ogb.fields) > 1 {
return nil, errors.New("db: OAuth2ClientGroupBy.Float64s is not achievable when grouping more than 1 field")
}
var v []float64
if err := ogb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (ogb *OAuth2ClientGroupBy) Float64sX(ctx context.Context) []float64 {
v, err := ogb.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (ogb *OAuth2ClientGroupBy) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = ogb.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{oauth2client.Label}
default:
err = fmt.Errorf("db: OAuth2ClientGroupBy.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (ogb *OAuth2ClientGroupBy) Float64X(ctx context.Context) float64 {
v, err := ogb.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from group-by.
// It is only allowed when executing a group-by query with one field.
func (ogb *OAuth2ClientGroupBy) Bools(ctx context.Context) ([]bool, error) {
if len(ogb.fields) > 1 {
return nil, errors.New("db: OAuth2ClientGroupBy.Bools is not achievable when grouping more than 1 field")
}
var v []bool
if err := ogb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (ogb *OAuth2ClientGroupBy) BoolsX(ctx context.Context) []bool {
v, err := ogb.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (ogb *OAuth2ClientGroupBy) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = ogb.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{oauth2client.Label}
default:
err = fmt.Errorf("db: OAuth2ClientGroupBy.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (ogb *OAuth2ClientGroupBy) BoolX(ctx context.Context) bool {
v, err := ogb.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
func (ogb *OAuth2ClientGroupBy) sqlScan(ctx context.Context, v interface{}) error {
for _, f := range ogb.fields {
if !oauth2client.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := ogb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := ogb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (ogb *OAuth2ClientGroupBy) sqlQuery() *sql.Selector {
selector := ogb.sql
columns := make([]string, 0, len(ogb.fields)+len(ogb.fns))
columns = append(columns, ogb.fields...)
for _, fn := range ogb.fns {
columns = append(columns, fn(selector))
}
return selector.Select(columns...).GroupBy(ogb.fields...)
}
// OAuth2ClientSelect is the builder for selecting fields of OAuth2Client entities.
type OAuth2ClientSelect struct {
*OAuth2ClientQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
}
// Scan applies the selector query and scans the result into the given value.
func (os *OAuth2ClientSelect) Scan(ctx context.Context, v interface{}) error {
if err := os.prepareQuery(ctx); err != nil {
return err
}
os.sql = os.OAuth2ClientQuery.sqlQuery(ctx)
return os.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (os *OAuth2ClientSelect) ScanX(ctx context.Context, v interface{}) {
if err := os.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from a selector. It is only allowed when selecting one field.
func (os *OAuth2ClientSelect) Strings(ctx context.Context) ([]string, error) {
if len(os.fields) > 1 {
return nil, errors.New("db: OAuth2ClientSelect.Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := os.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (os *OAuth2ClientSelect) StringsX(ctx context.Context) []string {
v, err := os.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a selector. It is only allowed when selecting one field.
func (os *OAuth2ClientSelect) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = os.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{oauth2client.Label}
default:
err = fmt.Errorf("db: OAuth2ClientSelect.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (os *OAuth2ClientSelect) StringX(ctx context.Context) string {
v, err := os.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from a selector. It is only allowed when selecting one field.
func (os *OAuth2ClientSelect) Ints(ctx context.Context) ([]int, error) {
if len(os.fields) > 1 {
return nil, errors.New("db: OAuth2ClientSelect.Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := os.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (os *OAuth2ClientSelect) IntsX(ctx context.Context) []int {
v, err := os.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a selector. It is only allowed when selecting one field.
func (os *OAuth2ClientSelect) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = os.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{oauth2client.Label}
default:
err = fmt.Errorf("db: OAuth2ClientSelect.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (os *OAuth2ClientSelect) IntX(ctx context.Context) int {
v, err := os.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
func (os *OAuth2ClientSelect) Float64s(ctx context.Context) ([]float64, error) {
if len(os.fields) > 1 {
return nil, errors.New("db: OAuth2ClientSelect.Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := os.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (os *OAuth2ClientSelect) Float64sX(ctx context.Context) []float64 {
v, err := os.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
func (os *OAuth2ClientSelect) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = os.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{oauth2client.Label}
default:
err = fmt.Errorf("db: OAuth2ClientSelect.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (os *OAuth2ClientSelect) Float64X(ctx context.Context) float64 {
v, err := os.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from a selector. It is only allowed when selecting one field.
func (os *OAuth2ClientSelect) Bools(ctx context.Context) ([]bool, error) {
if len(os.fields) > 1 {
return nil, errors.New("db: OAuth2ClientSelect.Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := os.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (os *OAuth2ClientSelect) BoolsX(ctx context.Context) []bool {
v, err := os.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a selector. It is only allowed when selecting one field.
func (os *OAuth2ClientSelect) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = os.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{oauth2client.Label}
default:
err = fmt.Errorf("db: OAuth2ClientSelect.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (os *OAuth2ClientSelect) BoolX(ctx context.Context) bool {
v, err := os.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
func (os *OAuth2ClientSelect) sqlScan(ctx context.Context, v interface{}) error {
rows := &sql.Rows{}
query, args := os.sqlQuery().Query()
if err := os.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (os *OAuth2ClientSelect) sqlQuery() sql.Querier {
selector := os.sql
selector.Select(selector.Columns(os.fields...)...)
return selector
}

View file

@ -0,0 +1,488 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/oauth2client"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// OAuth2ClientUpdate is the builder for updating OAuth2Client entities.
type OAuth2ClientUpdate struct {
config
hooks []Hook
mutation *OAuth2ClientMutation
}
// Where adds a new predicate for the OAuth2ClientUpdate builder.
func (ou *OAuth2ClientUpdate) Where(ps ...predicate.OAuth2Client) *OAuth2ClientUpdate {
ou.mutation.predicates = append(ou.mutation.predicates, ps...)
return ou
}
// SetSecret sets the "secret" field.
func (ou *OAuth2ClientUpdate) SetSecret(s string) *OAuth2ClientUpdate {
ou.mutation.SetSecret(s)
return ou
}
// SetRedirectUris sets the "redirect_uris" field.
func (ou *OAuth2ClientUpdate) SetRedirectUris(s []string) *OAuth2ClientUpdate {
ou.mutation.SetRedirectUris(s)
return ou
}
// ClearRedirectUris clears the value of the "redirect_uris" field.
func (ou *OAuth2ClientUpdate) ClearRedirectUris() *OAuth2ClientUpdate {
ou.mutation.ClearRedirectUris()
return ou
}
// SetTrustedPeers sets the "trusted_peers" field.
func (ou *OAuth2ClientUpdate) SetTrustedPeers(s []string) *OAuth2ClientUpdate {
ou.mutation.SetTrustedPeers(s)
return ou
}
// ClearTrustedPeers clears the value of the "trusted_peers" field.
func (ou *OAuth2ClientUpdate) ClearTrustedPeers() *OAuth2ClientUpdate {
ou.mutation.ClearTrustedPeers()
return ou
}
// SetPublic sets the "public" field.
func (ou *OAuth2ClientUpdate) SetPublic(b bool) *OAuth2ClientUpdate {
ou.mutation.SetPublic(b)
return ou
}
// SetName sets the "name" field.
func (ou *OAuth2ClientUpdate) SetName(s string) *OAuth2ClientUpdate {
ou.mutation.SetName(s)
return ou
}
// SetLogoURL sets the "logo_url" field.
func (ou *OAuth2ClientUpdate) SetLogoURL(s string) *OAuth2ClientUpdate {
ou.mutation.SetLogoURL(s)
return ou
}
// Mutation returns the OAuth2ClientMutation object of the builder.
func (ou *OAuth2ClientUpdate) Mutation() *OAuth2ClientMutation {
return ou.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) {
var (
err error
affected int
)
if len(ou.hooks) == 0 {
if err = ou.check(); err != nil {
return 0, err
}
affected, err = ou.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*OAuth2ClientMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = ou.check(); err != nil {
return 0, err
}
ou.mutation = mutation
affected, err = ou.sqlSave(ctx)
mutation.done = true
return affected, err
})
for i := len(ou.hooks) - 1; i >= 0; i-- {
mut = ou.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, ou.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// SaveX is like Save, but panics if an error occurs.
func (ou *OAuth2ClientUpdate) SaveX(ctx context.Context) int {
affected, err := ou.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (ou *OAuth2ClientUpdate) Exec(ctx context.Context) error {
_, err := ou.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 {
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 {
if err := oauth2client.SecretValidator(v); err != nil {
return &ValidationError{Name: "secret", err: fmt.Errorf("db: validator failed for field \"secret\": %w", err)}
}
}
if v, ok := ou.mutation.Name(); ok {
if err := oauth2client.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf("db: validator failed for field \"name\": %w", err)}
}
}
if v, ok := ou.mutation.LogoURL(); ok {
if err := oauth2client.LogoURLValidator(v); err != nil {
return &ValidationError{Name: "logo_url", err: fmt.Errorf("db: validator failed for field \"logo_url\": %w", err)}
}
}
return nil
}
func (ou *OAuth2ClientUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: oauth2client.Table,
Columns: oauth2client.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: oauth2client.FieldID,
},
},
}
if ps := ou.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 {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: oauth2client.FieldSecret,
})
}
if value, ok := ou.mutation.RedirectUris(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: oauth2client.FieldRedirectUris,
})
}
if ou.mutation.RedirectUrisCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Column: oauth2client.FieldRedirectUris,
})
}
if value, ok := ou.mutation.TrustedPeers(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: oauth2client.FieldTrustedPeers,
})
}
if ou.mutation.TrustedPeersCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Column: oauth2client.FieldTrustedPeers,
})
}
if value, ok := ou.mutation.Public(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: oauth2client.FieldPublic,
})
}
if value, ok := ou.mutation.Name(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: oauth2client.FieldName,
})
}
if value, ok := ou.mutation.LogoURL(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: oauth2client.FieldLogoURL,
})
}
if n, err = sqlgraph.UpdateNodes(ctx, ou.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{oauth2client.Label}
} else if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return 0, err
}
return n, nil
}
// OAuth2ClientUpdateOne is the builder for updating a single OAuth2Client entity.
type OAuth2ClientUpdateOne struct {
config
fields []string
hooks []Hook
mutation *OAuth2ClientMutation
}
// SetSecret sets the "secret" field.
func (ouo *OAuth2ClientUpdateOne) SetSecret(s string) *OAuth2ClientUpdateOne {
ouo.mutation.SetSecret(s)
return ouo
}
// SetRedirectUris sets the "redirect_uris" field.
func (ouo *OAuth2ClientUpdateOne) SetRedirectUris(s []string) *OAuth2ClientUpdateOne {
ouo.mutation.SetRedirectUris(s)
return ouo
}
// ClearRedirectUris clears the value of the "redirect_uris" field.
func (ouo *OAuth2ClientUpdateOne) ClearRedirectUris() *OAuth2ClientUpdateOne {
ouo.mutation.ClearRedirectUris()
return ouo
}
// SetTrustedPeers sets the "trusted_peers" field.
func (ouo *OAuth2ClientUpdateOne) SetTrustedPeers(s []string) *OAuth2ClientUpdateOne {
ouo.mutation.SetTrustedPeers(s)
return ouo
}
// ClearTrustedPeers clears the value of the "trusted_peers" field.
func (ouo *OAuth2ClientUpdateOne) ClearTrustedPeers() *OAuth2ClientUpdateOne {
ouo.mutation.ClearTrustedPeers()
return ouo
}
// SetPublic sets the "public" field.
func (ouo *OAuth2ClientUpdateOne) SetPublic(b bool) *OAuth2ClientUpdateOne {
ouo.mutation.SetPublic(b)
return ouo
}
// SetName sets the "name" field.
func (ouo *OAuth2ClientUpdateOne) SetName(s string) *OAuth2ClientUpdateOne {
ouo.mutation.SetName(s)
return ouo
}
// SetLogoURL sets the "logo_url" field.
func (ouo *OAuth2ClientUpdateOne) SetLogoURL(s string) *OAuth2ClientUpdateOne {
ouo.mutation.SetLogoURL(s)
return ouo
}
// Mutation returns the OAuth2ClientMutation object of the builder.
func (ouo *OAuth2ClientUpdateOne) Mutation() *OAuth2ClientMutation {
return ouo.mutation
}
// 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
}
// Save executes the query and returns the updated OAuth2Client entity.
func (ouo *OAuth2ClientUpdateOne) Save(ctx context.Context) (*OAuth2Client, error) {
var (
err error
node *OAuth2Client
)
if len(ouo.hooks) == 0 {
if err = ouo.check(); err != nil {
return nil, err
}
node, err = ouo.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*OAuth2ClientMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = ouo.check(); err != nil {
return nil, err
}
ouo.mutation = mutation
node, err = ouo.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(ouo.hooks) - 1; i >= 0; i-- {
mut = ouo.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, ouo.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX is like Save, but panics if an error occurs.
func (ouo *OAuth2ClientUpdateOne) SaveX(ctx context.Context) *OAuth2Client {
node, err := ouo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (ouo *OAuth2ClientUpdateOne) Exec(ctx context.Context) error {
_, err := ouo.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 {
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 {
if err := oauth2client.SecretValidator(v); err != nil {
return &ValidationError{Name: "secret", err: fmt.Errorf("db: validator failed for field \"secret\": %w", err)}
}
}
if v, ok := ouo.mutation.Name(); ok {
if err := oauth2client.NameValidator(v); err != nil {
return &ValidationError{Name: "name", err: fmt.Errorf("db: validator failed for field \"name\": %w", err)}
}
}
if v, ok := ouo.mutation.LogoURL(); ok {
if err := oauth2client.LogoURLValidator(v); err != nil {
return &ValidationError{Name: "logo_url", err: fmt.Errorf("db: validator failed for field \"logo_url\": %w", err)}
}
}
return nil
}
func (ouo *OAuth2ClientUpdateOne) sqlSave(ctx context.Context) (_node *OAuth2Client, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: oauth2client.Table,
Columns: oauth2client.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: oauth2client.FieldID,
},
},
}
id, ok := ouo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing OAuth2Client.ID for update")}
}
_spec.Node.ID.Value = id
if fields := ouo.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 {
if !oauth2client.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
}
if f != oauth2client.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := ouo.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 {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: oauth2client.FieldSecret,
})
}
if value, ok := ouo.mutation.RedirectUris(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: oauth2client.FieldRedirectUris,
})
}
if ouo.mutation.RedirectUrisCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Column: oauth2client.FieldRedirectUris,
})
}
if value, ok := ouo.mutation.TrustedPeers(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: oauth2client.FieldTrustedPeers,
})
}
if ouo.mutation.TrustedPeersCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Column: oauth2client.FieldTrustedPeers,
})
}
if value, ok := ouo.mutation.Public(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: oauth2client.FieldPublic,
})
}
if value, ok := ouo.mutation.Name(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: oauth2client.FieldName,
})
}
if value, ok := ouo.mutation.LogoURL(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: oauth2client.FieldLogoURL,
})
}
_node = &OAuth2Client{config: ouo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, ouo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{oauth2client.Label}
} else if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return nil, err
}
return _node, nil
}

View file

@ -0,0 +1,131 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"fmt"
"strings"
"entgo.io/ent/dialect/sql"
"github.com/dexidp/dex/storage/ent/db/offlinesession"
)
// OfflineSession is the model entity for the OfflineSession schema.
type OfflineSession struct {
config `json:"-"`
// ID of the ent.
ID string `json:"id,omitempty"`
// UserID holds the value of the "user_id" field.
UserID string `json:"user_id,omitempty"`
// ConnID holds the value of the "conn_id" field.
ConnID string `json:"conn_id,omitempty"`
// Refresh holds the value of the "refresh" field.
Refresh []byte `json:"refresh,omitempty"`
// ConnectorData holds the value of the "connector_data" field.
ConnectorData *[]byte `json:"connector_data,omitempty"`
}
// scanValues returns the types for scanning values from sql.Rows.
func (*OfflineSession) scanValues(columns []string) ([]interface{}, error) {
values := make([]interface{}, len(columns))
for i := range columns {
switch columns[i] {
case offlinesession.FieldRefresh, offlinesession.FieldConnectorData:
values[i] = new([]byte)
case offlinesession.FieldID, offlinesession.FieldUserID, offlinesession.FieldConnID:
values[i] = new(sql.NullString)
default:
return nil, fmt.Errorf("unexpected column %q for type OfflineSession", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the OfflineSession fields.
func (os *OfflineSession) assignValues(columns []string, values []interface{}) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case offlinesession.FieldID:
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
}
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
}
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
}
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
}
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
}
}
}
return nil
}
// 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 (&OfflineSessionClient{config: os.config}).UpdateOne(os)
}
// 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)
if !ok {
panic("db: OfflineSession is not a transactional entity")
}
os.config.driver = tx.drv
return os
}
// String implements the fmt.Stringer.
func (os *OfflineSession) String() string {
var builder strings.Builder
builder.WriteString("OfflineSession(")
builder.WriteString(fmt.Sprintf("id=%v", os.ID))
builder.WriteString(", user_id=")
builder.WriteString(os.UserID)
builder.WriteString(", conn_id=")
builder.WriteString(os.ConnID)
builder.WriteString(", refresh=")
builder.WriteString(fmt.Sprintf("%v", os.Refresh))
if v := os.ConnectorData; v != nil {
builder.WriteString(", connector_data=")
builder.WriteString(fmt.Sprintf("%v", *v))
}
builder.WriteByte(')')
return builder.String()
}
// OfflineSessions is a parsable slice of OfflineSession.
type OfflineSessions []*OfflineSession
func (os OfflineSessions) config(cfg config) {
for _i := range os {
os[_i].config = cfg
}
}

View file

@ -0,0 +1,48 @@
// Code generated by entc, DO NOT EDIT.
package offlinesession
const (
// Label holds the string label denoting the offlinesession type in the database.
Label = "offline_session"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldUserID holds the string denoting the user_id field in the database.
FieldUserID = "user_id"
// FieldConnID holds the string denoting the conn_id field in the database.
FieldConnID = "conn_id"
// FieldRefresh holds the string denoting the refresh field in the database.
FieldRefresh = "refresh"
// FieldConnectorData holds the string denoting the connector_data field in the database.
FieldConnectorData = "connector_data"
// Table holds the table name of the offlinesession in the database.
Table = "offline_sessions"
)
// Columns holds all SQL columns for offlinesession fields.
var Columns = []string{
FieldID,
FieldUserID,
FieldConnID,
FieldRefresh,
FieldConnectorData,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// UserIDValidator is a validator for the "user_id" field. It is called by the builders before save.
UserIDValidator func(string) error
// ConnIDValidator is a validator for the "conn_id" field. It is called by the builders before save.
ConnIDValidator func(string) error
// IDValidator is a validator for the "id" field. It is called by the builders before save.
IDValidator func(string) error
)

View file

@ -0,0 +1,539 @@
// Code generated by entc, DO NOT EDIT.
package offlinesession
import (
"entgo.io/ent/dialect/sql"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// ID filters vertices based on their ID field.
func ID(id string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldID), id))
})
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.In(s.C(FieldID), v...))
})
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.NotIn(s.C(FieldID), v...))
})
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldID), id))
})
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldID), id))
})
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldID), id))
})
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldID), id))
})
}
// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ.
func UserID(v string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUserID), v))
})
}
// ConnID applies equality check predicate on the "conn_id" field. It's identical to ConnIDEQ.
func ConnID(v string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldConnID), v))
})
}
// Refresh applies equality check predicate on the "refresh" field. It's identical to RefreshEQ.
func Refresh(v []byte) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldRefresh), v))
})
}
// ConnectorData applies equality check predicate on the "connector_data" field. It's identical to ConnectorDataEQ.
func ConnectorData(v []byte) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldConnectorData), v))
})
}
// UserIDEQ applies the EQ predicate on the "user_id" field.
func UserIDEQ(v string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUserID), v))
})
}
// UserIDNEQ applies the NEQ predicate on the "user_id" field.
func UserIDNEQ(v string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldUserID), v))
})
}
// UserIDIn applies the In predicate on the "user_id" field.
func UserIDIn(vs ...string) predicate.OfflineSession {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.OfflineSession(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldUserID), v...))
})
}
// UserIDNotIn applies the NotIn predicate on the "user_id" field.
func UserIDNotIn(vs ...string) predicate.OfflineSession {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.OfflineSession(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldUserID), v...))
})
}
// UserIDGT applies the GT predicate on the "user_id" field.
func UserIDGT(v string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldUserID), v))
})
}
// UserIDGTE applies the GTE predicate on the "user_id" field.
func UserIDGTE(v string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldUserID), v))
})
}
// UserIDLT applies the LT predicate on the "user_id" field.
func UserIDLT(v string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldUserID), v))
})
}
// UserIDLTE applies the LTE predicate on the "user_id" field.
func UserIDLTE(v string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldUserID), v))
})
}
// UserIDContains applies the Contains predicate on the "user_id" field.
func UserIDContains(v string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldUserID), v))
})
}
// UserIDHasPrefix applies the HasPrefix predicate on the "user_id" field.
func UserIDHasPrefix(v string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldUserID), v))
})
}
// UserIDHasSuffix applies the HasSuffix predicate on the "user_id" field.
func UserIDHasSuffix(v string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldUserID), v))
})
}
// UserIDEqualFold applies the EqualFold predicate on the "user_id" field.
func UserIDEqualFold(v string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldUserID), v))
})
}
// UserIDContainsFold applies the ContainsFold predicate on the "user_id" field.
func UserIDContainsFold(v string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldUserID), v))
})
}
// ConnIDEQ applies the EQ predicate on the "conn_id" field.
func ConnIDEQ(v string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldConnID), v))
})
}
// ConnIDNEQ applies the NEQ predicate on the "conn_id" field.
func ConnIDNEQ(v string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldConnID), v))
})
}
// ConnIDIn applies the In predicate on the "conn_id" field.
func ConnIDIn(vs ...string) predicate.OfflineSession {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.OfflineSession(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldConnID), v...))
})
}
// ConnIDNotIn applies the NotIn predicate on the "conn_id" field.
func ConnIDNotIn(vs ...string) predicate.OfflineSession {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.OfflineSession(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldConnID), v...))
})
}
// ConnIDGT applies the GT predicate on the "conn_id" field.
func ConnIDGT(v string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldConnID), v))
})
}
// ConnIDGTE applies the GTE predicate on the "conn_id" field.
func ConnIDGTE(v string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldConnID), v))
})
}
// ConnIDLT applies the LT predicate on the "conn_id" field.
func ConnIDLT(v string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldConnID), v))
})
}
// ConnIDLTE applies the LTE predicate on the "conn_id" field.
func ConnIDLTE(v string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldConnID), v))
})
}
// ConnIDContains applies the Contains predicate on the "conn_id" field.
func ConnIDContains(v string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldConnID), v))
})
}
// ConnIDHasPrefix applies the HasPrefix predicate on the "conn_id" field.
func ConnIDHasPrefix(v string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldConnID), v))
})
}
// ConnIDHasSuffix applies the HasSuffix predicate on the "conn_id" field.
func ConnIDHasSuffix(v string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldConnID), v))
})
}
// ConnIDEqualFold applies the EqualFold predicate on the "conn_id" field.
func ConnIDEqualFold(v string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldConnID), v))
})
}
// ConnIDContainsFold applies the ContainsFold predicate on the "conn_id" field.
func ConnIDContainsFold(v string) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldConnID), v))
})
}
// RefreshEQ applies the EQ predicate on the "refresh" field.
func RefreshEQ(v []byte) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldRefresh), v))
})
}
// RefreshNEQ applies the NEQ predicate on the "refresh" field.
func RefreshNEQ(v []byte) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldRefresh), v))
})
}
// RefreshIn applies the In predicate on the "refresh" field.
func RefreshIn(vs ...[]byte) predicate.OfflineSession {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.OfflineSession(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldRefresh), v...))
})
}
// RefreshNotIn applies the NotIn predicate on the "refresh" field.
func RefreshNotIn(vs ...[]byte) predicate.OfflineSession {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.OfflineSession(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldRefresh), v...))
})
}
// RefreshGT applies the GT predicate on the "refresh" field.
func RefreshGT(v []byte) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldRefresh), v))
})
}
// RefreshGTE applies the GTE predicate on the "refresh" field.
func RefreshGTE(v []byte) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldRefresh), v))
})
}
// RefreshLT applies the LT predicate on the "refresh" field.
func RefreshLT(v []byte) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldRefresh), v))
})
}
// RefreshLTE applies the LTE predicate on the "refresh" field.
func RefreshLTE(v []byte) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldRefresh), v))
})
}
// ConnectorDataEQ applies the EQ predicate on the "connector_data" field.
func ConnectorDataEQ(v []byte) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldConnectorData), v))
})
}
// ConnectorDataNEQ applies the NEQ predicate on the "connector_data" field.
func ConnectorDataNEQ(v []byte) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldConnectorData), v))
})
}
// ConnectorDataIn applies the In predicate on the "connector_data" field.
func ConnectorDataIn(vs ...[]byte) predicate.OfflineSession {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.OfflineSession(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldConnectorData), v...))
})
}
// ConnectorDataNotIn applies the NotIn predicate on the "connector_data" field.
func ConnectorDataNotIn(vs ...[]byte) predicate.OfflineSession {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.OfflineSession(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldConnectorData), v...))
})
}
// ConnectorDataGT applies the GT predicate on the "connector_data" field.
func ConnectorDataGT(v []byte) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldConnectorData), v))
})
}
// ConnectorDataGTE applies the GTE predicate on the "connector_data" field.
func ConnectorDataGTE(v []byte) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldConnectorData), v))
})
}
// ConnectorDataLT applies the LT predicate on the "connector_data" field.
func ConnectorDataLT(v []byte) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldConnectorData), v))
})
}
// ConnectorDataLTE applies the LTE predicate on the "connector_data" field.
func ConnectorDataLTE(v []byte) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldConnectorData), v))
})
}
// ConnectorDataIsNil applies the IsNil predicate on the "connector_data" field.
func ConnectorDataIsNil() predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldConnectorData)))
})
}
// ConnectorDataNotNil applies the NotNil predicate on the "connector_data" field.
func ConnectorDataNotNil() predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s.Where(sql.NotNull(s.C(FieldConnectorData)))
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.OfflineSession) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for _, p := range predicates {
p(s1)
}
s.Where(s1.P())
})
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.OfflineSession) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for i, p := range predicates {
if i > 0 {
s1.Or()
}
p(s1)
}
s.Where(s1.P())
})
}
// Not applies the not operator on the given predicate.
func Not(p predicate.OfflineSession) predicate.OfflineSession {
return predicate.OfflineSession(func(s *sql.Selector) {
p(s.Not())
})
}

View file

@ -0,0 +1,253 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/offlinesession"
)
// OfflineSessionCreate is the builder for creating a OfflineSession entity.
type OfflineSessionCreate struct {
config
mutation *OfflineSessionMutation
hooks []Hook
}
// SetUserID sets the "user_id" field.
func (osc *OfflineSessionCreate) SetUserID(s string) *OfflineSessionCreate {
osc.mutation.SetUserID(s)
return osc
}
// SetConnID sets the "conn_id" field.
func (osc *OfflineSessionCreate) SetConnID(s string) *OfflineSessionCreate {
osc.mutation.SetConnID(s)
return osc
}
// SetRefresh sets the "refresh" field.
func (osc *OfflineSessionCreate) SetRefresh(b []byte) *OfflineSessionCreate {
osc.mutation.SetRefresh(b)
return osc
}
// SetConnectorData sets the "connector_data" field.
func (osc *OfflineSessionCreate) SetConnectorData(b []byte) *OfflineSessionCreate {
osc.mutation.SetConnectorData(b)
return osc
}
// SetID sets the "id" field.
func (osc *OfflineSessionCreate) SetID(s string) *OfflineSessionCreate {
osc.mutation.SetID(s)
return osc
}
// Mutation returns the OfflineSessionMutation object of the builder.
func (osc *OfflineSessionCreate) Mutation() *OfflineSessionMutation {
return osc.mutation
}
// Save creates the OfflineSession in the database.
func (osc *OfflineSessionCreate) Save(ctx context.Context) (*OfflineSession, error) {
var (
err error
node *OfflineSession
)
if len(osc.hooks) == 0 {
if err = osc.check(); err != nil {
return nil, err
}
node, err = osc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*OfflineSessionMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = osc.check(); err != nil {
return nil, err
}
osc.mutation = mutation
node, err = osc.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(osc.hooks) - 1; i >= 0; i-- {
mut = osc.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, osc.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (osc *OfflineSessionCreate) SaveX(ctx context.Context) *OfflineSession {
v, err := osc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// check runs all checks and user-defined validators on the builder.
func (osc *OfflineSessionCreate) check() error {
if _, ok := osc.mutation.UserID(); !ok {
return &ValidationError{Name: "user_id", err: errors.New("db: missing required field \"user_id\"")}
}
if v, ok := osc.mutation.UserID(); ok {
if err := offlinesession.UserIDValidator(v); err != nil {
return &ValidationError{Name: "user_id", err: fmt.Errorf("db: validator failed for field \"user_id\": %w", err)}
}
}
if _, ok := osc.mutation.ConnID(); !ok {
return &ValidationError{Name: "conn_id", err: errors.New("db: missing required field \"conn_id\"")}
}
if v, ok := osc.mutation.ConnID(); ok {
if err := offlinesession.ConnIDValidator(v); err != nil {
return &ValidationError{Name: "conn_id", err: fmt.Errorf("db: validator failed for field \"conn_id\": %w", err)}
}
}
if _, ok := osc.mutation.Refresh(); !ok {
return &ValidationError{Name: "refresh", err: errors.New("db: missing required field \"refresh\"")}
}
if v, ok := osc.mutation.ID(); ok {
if err := offlinesession.IDValidator(v); err != nil {
return &ValidationError{Name: "id", err: fmt.Errorf("db: validator failed for field \"id\": %w", err)}
}
}
return nil
}
func (osc *OfflineSessionCreate) sqlSave(ctx context.Context) (*OfflineSession, error) {
_node, _spec := osc.createSpec()
if err := sqlgraph.CreateNode(ctx, osc.driver, _spec); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return nil, err
}
return _node, nil
}
func (osc *OfflineSessionCreate) createSpec() (*OfflineSession, *sqlgraph.CreateSpec) {
var (
_node = &OfflineSession{config: osc.config}
_spec = &sqlgraph.CreateSpec{
Table: offlinesession.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: offlinesession.FieldID,
},
}
)
if id, ok := osc.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = id
}
if value, ok := osc.mutation.UserID(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: offlinesession.FieldUserID,
})
_node.UserID = value
}
if value, ok := osc.mutation.ConnID(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: offlinesession.FieldConnID,
})
_node.ConnID = value
}
if value, ok := osc.mutation.Refresh(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: offlinesession.FieldRefresh,
})
_node.Refresh = value
}
if value, ok := osc.mutation.ConnectorData(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: offlinesession.FieldConnectorData,
})
_node.ConnectorData = &value
}
return _node, _spec
}
// OfflineSessionCreateBulk is the builder for creating many OfflineSession entities in bulk.
type OfflineSessionCreateBulk struct {
config
builders []*OfflineSessionCreate
}
// Save creates the OfflineSession entities in the database.
func (oscb *OfflineSessionCreateBulk) Save(ctx context.Context) ([]*OfflineSession, error) {
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(i int, root context.Context) {
builder := oscb.builders[i]
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*OfflineSessionMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
nodes[i], specs[i] = builder.createSpec()
var err error
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, oscb.builders[i+1].mutation)
} else {
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, oscb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
}
}
mutation.done = true
if err != nil {
return nil, err
}
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, oscb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (oscb *OfflineSessionCreateBulk) SaveX(ctx context.Context) []*OfflineSession {
v, err := oscb.Save(ctx)
if err != nil {
panic(err)
}
return v
}

View file

@ -0,0 +1,108 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/offlinesession"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// OfflineSessionDelete is the builder for deleting a OfflineSession entity.
type OfflineSessionDelete struct {
config
hooks []Hook
mutation *OfflineSessionMutation
}
// Where adds a new predicate to the OfflineSessionDelete builder.
func (osd *OfflineSessionDelete) Where(ps ...predicate.OfflineSession) *OfflineSessionDelete {
osd.mutation.predicates = append(osd.mutation.predicates, ps...)
return osd
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (osd *OfflineSessionDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(osd.hooks) == 0 {
affected, err = osd.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*OfflineSessionMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
osd.mutation = mutation
affected, err = osd.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(osd.hooks) - 1; i >= 0; i-- {
mut = osd.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, osd.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (osd *OfflineSessionDelete) ExecX(ctx context.Context) int {
n, err := osd.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (osd *OfflineSessionDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: offlinesession.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: offlinesession.FieldID,
},
},
}
if ps := osd.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return sqlgraph.DeleteNodes(ctx, osd.driver, _spec)
}
// OfflineSessionDeleteOne is the builder for deleting a single OfflineSession entity.
type OfflineSessionDeleteOne struct {
osd *OfflineSessionDelete
}
// Exec executes the deletion query.
func (osdo *OfflineSessionDeleteOne) Exec(ctx context.Context) error {
n, err := osdo.osd.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{offlinesession.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (osdo *OfflineSessionDeleteOne) ExecX(ctx context.Context) {
osdo.osd.ExecX(ctx)
}

View file

@ -0,0 +1,906 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"errors"
"fmt"
"math"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/offlinesession"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// OfflineSessionQuery is the builder for querying OfflineSession entities.
type OfflineSessionQuery struct {
config
limit *int
offset *int
unique *bool
order []OrderFunc
fields []string
predicates []predicate.OfflineSession
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// 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
}
// Limit adds a limit step to the query.
func (osq *OfflineSessionQuery) Limit(limit int) *OfflineSessionQuery {
osq.limit = &limit
return osq
}
// Offset adds an offset step to the query.
func (osq *OfflineSessionQuery) Offset(offset int) *OfflineSessionQuery {
osq.offset = &offset
return osq
}
// 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.unique = &unique
return osq
}
// Order adds an order step to the query.
func (osq *OfflineSessionQuery) Order(o ...OrderFunc) *OfflineSessionQuery {
osq.order = append(osq.order, o...)
return osq
}
// 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(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{offlinesession.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (osq *OfflineSessionQuery) FirstX(ctx context.Context) *OfflineSession {
node, err := osq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// 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) {
var ids []string
if ids, err = osq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{offlinesession.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (osq *OfflineSessionQuery) FirstIDX(ctx context.Context) string {
id, err := osq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single OfflineSession entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when exactly one OfflineSession entity is not 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(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{offlinesession.Label}
default:
return nil, &NotSingularError{offlinesession.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (osq *OfflineSessionQuery) OnlyX(ctx context.Context) *OfflineSession {
node, err := osq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only OfflineSession ID in the query.
// Returns a *NotSingularError when exactly one OfflineSession ID is not found.
// Returns a *NotFoundError when no entities are found.
func (osq *OfflineSessionQuery) OnlyID(ctx context.Context) (id string, err error) {
var ids []string
if ids, err = osq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{offlinesession.Label}
default:
err = &NotSingularError{offlinesession.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (osq *OfflineSessionQuery) OnlyIDX(ctx context.Context) string {
id, err := osq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of OfflineSessions.
func (osq *OfflineSessionQuery) All(ctx context.Context) ([]*OfflineSession, error) {
if err := osq.prepareQuery(ctx); err != nil {
return nil, err
}
return osq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (osq *OfflineSessionQuery) AllX(ctx context.Context) []*OfflineSession {
nodes, err := osq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of OfflineSession IDs.
func (osq *OfflineSessionQuery) IDs(ctx context.Context) ([]string, error) {
var ids []string
if err := osq.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)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (osq *OfflineSessionQuery) Count(ctx context.Context) (int, error) {
if err := osq.prepareQuery(ctx); err != nil {
return 0, err
}
return osq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (osq *OfflineSessionQuery) CountX(ctx context.Context) int {
count, err := osq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (osq *OfflineSessionQuery) Exist(ctx context.Context) (bool, error) {
if err := osq.prepareQuery(ctx); err != nil {
return false, err
}
return osq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (osq *OfflineSessionQuery) ExistX(ctx context.Context) bool {
exist, err := osq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// 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 {
return nil
}
return &OfflineSessionQuery{
config: osq.config,
limit: osq.limit,
offset: osq.offset,
order: append([]OrderFunc{}, osq.order...),
predicates: append([]predicate.OfflineSession{}, osq.predicates...),
// clone intermediate query.
sql: osq.sql.Clone(),
path: osq.path,
}
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// UserID string `json:"user_id,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.OfflineSession.Query().
// GroupBy(offlinesession.FieldUserID).
// Aggregate(db.Count()).
// Scan(ctx, &v)
//
func (osq *OfflineSessionQuery) GroupBy(field string, fields ...string) *OfflineSessionGroupBy {
group := &OfflineSessionGroupBy{config: osq.config}
group.fields = append([]string{field}, fields...)
group.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := osq.prepareQuery(ctx); err != nil {
return nil, err
}
return osq.sqlQuery(ctx), nil
}
return group
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// UserID string `json:"user_id,omitempty"`
// }
//
// client.OfflineSession.Query().
// Select(offlinesession.FieldUserID).
// Scan(ctx, &v)
//
func (osq *OfflineSessionQuery) Select(field string, fields ...string) *OfflineSessionSelect {
osq.fields = append([]string{field}, fields...)
return &OfflineSessionSelect{OfflineSessionQuery: osq}
}
func (osq *OfflineSessionQuery) prepareQuery(ctx context.Context) error {
for _, f := range osq.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 err != nil {
return err
}
osq.sql = prev
}
return nil
}
func (osq *OfflineSessionQuery) sqlAll(ctx context.Context) ([]*OfflineSession, error) {
var (
nodes = []*OfflineSession{}
_spec = osq.querySpec()
)
_spec.ScanValues = func(columns []string) ([]interface{}, error) {
node := &OfflineSession{config: osq.config}
nodes = append(nodes, node)
return node.scanValues(columns)
}
_spec.Assign = func(columns []string, values []interface{}) error {
if len(nodes) == 0 {
return fmt.Errorf("db: Assign called without calling ScanValues")
}
node := nodes[len(nodes)-1]
return node.assignValues(columns, values)
}
if err := sqlgraph.QueryNodes(ctx, osq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (osq *OfflineSessionQuery) sqlCount(ctx context.Context) (int, error) {
_spec := osq.querySpec()
return sqlgraph.CountNodes(ctx, osq.driver, _spec)
}
func (osq *OfflineSessionQuery) sqlExist(ctx context.Context) (bool, error) {
n, err := osq.sqlCount(ctx)
if err != nil {
return false, fmt.Errorf("db: check existence: %w", err)
}
return n > 0, nil
}
func (osq *OfflineSessionQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: offlinesession.Table,
Columns: offlinesession.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: offlinesession.FieldID,
},
},
From: osq.sql,
Unique: true,
}
if unique := osq.unique; unique != nil {
_spec.Unique = *unique
}
if fields := osq.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 {
if fields[i] != offlinesession.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := osq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := osq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := osq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := osq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (osq *OfflineSessionQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(osq.driver.Dialect())
t1 := builder.Table(offlinesession.Table)
selector := builder.Select(t1.Columns(offlinesession.Columns...)...).From(t1)
if osq.sql != nil {
selector = osq.sql
selector.Select(selector.Columns(offlinesession.Columns...)...)
}
for _, p := range osq.predicates {
p(selector)
}
for _, p := range osq.order {
p(selector)
}
if offset := osq.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.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// OfflineSessionGroupBy is the group-by builder for OfflineSession entities.
type OfflineSessionGroupBy struct {
config
fields []string
fns []AggregateFunc
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Aggregate adds the given aggregation functions to the group-by query.
func (osgb *OfflineSessionGroupBy) Aggregate(fns ...AggregateFunc) *OfflineSessionGroupBy {
osgb.fns = append(osgb.fns, fns...)
return osgb
}
// Scan applies the group-by query and scans the result into the given value.
func (osgb *OfflineSessionGroupBy) Scan(ctx context.Context, v interface{}) error {
query, err := osgb.path(ctx)
if err != nil {
return err
}
osgb.sql = query
return osgb.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (osgb *OfflineSessionGroupBy) ScanX(ctx context.Context, v interface{}) {
if err := osgb.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from group-by.
// It is only allowed when executing a group-by query with one field.
func (osgb *OfflineSessionGroupBy) Strings(ctx context.Context) ([]string, error) {
if len(osgb.fields) > 1 {
return nil, errors.New("db: OfflineSessionGroupBy.Strings is not achievable when grouping more than 1 field")
}
var v []string
if err := osgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (osgb *OfflineSessionGroupBy) StringsX(ctx context.Context) []string {
v, err := osgb.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (osgb *OfflineSessionGroupBy) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = osgb.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{offlinesession.Label}
default:
err = fmt.Errorf("db: OfflineSessionGroupBy.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (osgb *OfflineSessionGroupBy) StringX(ctx context.Context) string {
v, err := osgb.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from group-by.
// It is only allowed when executing a group-by query with one field.
func (osgb *OfflineSessionGroupBy) Ints(ctx context.Context) ([]int, error) {
if len(osgb.fields) > 1 {
return nil, errors.New("db: OfflineSessionGroupBy.Ints is not achievable when grouping more than 1 field")
}
var v []int
if err := osgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (osgb *OfflineSessionGroupBy) IntsX(ctx context.Context) []int {
v, err := osgb.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (osgb *OfflineSessionGroupBy) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = osgb.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{offlinesession.Label}
default:
err = fmt.Errorf("db: OfflineSessionGroupBy.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (osgb *OfflineSessionGroupBy) IntX(ctx context.Context) int {
v, err := osgb.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from group-by.
// It is only allowed when executing a group-by query with one field.
func (osgb *OfflineSessionGroupBy) Float64s(ctx context.Context) ([]float64, error) {
if len(osgb.fields) > 1 {
return nil, errors.New("db: OfflineSessionGroupBy.Float64s is not achievable when grouping more than 1 field")
}
var v []float64
if err := osgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (osgb *OfflineSessionGroupBy) Float64sX(ctx context.Context) []float64 {
v, err := osgb.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (osgb *OfflineSessionGroupBy) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = osgb.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{offlinesession.Label}
default:
err = fmt.Errorf("db: OfflineSessionGroupBy.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (osgb *OfflineSessionGroupBy) Float64X(ctx context.Context) float64 {
v, err := osgb.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from group-by.
// It is only allowed when executing a group-by query with one field.
func (osgb *OfflineSessionGroupBy) Bools(ctx context.Context) ([]bool, error) {
if len(osgb.fields) > 1 {
return nil, errors.New("db: OfflineSessionGroupBy.Bools is not achievable when grouping more than 1 field")
}
var v []bool
if err := osgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (osgb *OfflineSessionGroupBy) BoolsX(ctx context.Context) []bool {
v, err := osgb.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (osgb *OfflineSessionGroupBy) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = osgb.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{offlinesession.Label}
default:
err = fmt.Errorf("db: OfflineSessionGroupBy.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (osgb *OfflineSessionGroupBy) BoolX(ctx context.Context) bool {
v, err := osgb.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
func (osgb *OfflineSessionGroupBy) sqlScan(ctx context.Context, v interface{}) error {
for _, f := range osgb.fields {
if !offlinesession.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := osgb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := osgb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (osgb *OfflineSessionGroupBy) sqlQuery() *sql.Selector {
selector := osgb.sql
columns := make([]string, 0, len(osgb.fields)+len(osgb.fns))
columns = append(columns, osgb.fields...)
for _, fn := range osgb.fns {
columns = append(columns, fn(selector))
}
return selector.Select(columns...).GroupBy(osgb.fields...)
}
// OfflineSessionSelect is the builder for selecting fields of OfflineSession entities.
type OfflineSessionSelect struct {
*OfflineSessionQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
}
// Scan applies the selector query and scans the result into the given value.
func (oss *OfflineSessionSelect) Scan(ctx context.Context, v interface{}) error {
if err := oss.prepareQuery(ctx); err != nil {
return err
}
oss.sql = oss.OfflineSessionQuery.sqlQuery(ctx)
return oss.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (oss *OfflineSessionSelect) ScanX(ctx context.Context, v interface{}) {
if err := oss.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from a selector. It is only allowed when selecting one field.
func (oss *OfflineSessionSelect) Strings(ctx context.Context) ([]string, error) {
if len(oss.fields) > 1 {
return nil, errors.New("db: OfflineSessionSelect.Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := oss.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (oss *OfflineSessionSelect) StringsX(ctx context.Context) []string {
v, err := oss.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a selector. It is only allowed when selecting one field.
func (oss *OfflineSessionSelect) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = oss.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{offlinesession.Label}
default:
err = fmt.Errorf("db: OfflineSessionSelect.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (oss *OfflineSessionSelect) StringX(ctx context.Context) string {
v, err := oss.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from a selector. It is only allowed when selecting one field.
func (oss *OfflineSessionSelect) Ints(ctx context.Context) ([]int, error) {
if len(oss.fields) > 1 {
return nil, errors.New("db: OfflineSessionSelect.Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := oss.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (oss *OfflineSessionSelect) IntsX(ctx context.Context) []int {
v, err := oss.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a selector. It is only allowed when selecting one field.
func (oss *OfflineSessionSelect) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = oss.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{offlinesession.Label}
default:
err = fmt.Errorf("db: OfflineSessionSelect.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (oss *OfflineSessionSelect) IntX(ctx context.Context) int {
v, err := oss.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
func (oss *OfflineSessionSelect) Float64s(ctx context.Context) ([]float64, error) {
if len(oss.fields) > 1 {
return nil, errors.New("db: OfflineSessionSelect.Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := oss.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (oss *OfflineSessionSelect) Float64sX(ctx context.Context) []float64 {
v, err := oss.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
func (oss *OfflineSessionSelect) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = oss.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{offlinesession.Label}
default:
err = fmt.Errorf("db: OfflineSessionSelect.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (oss *OfflineSessionSelect) Float64X(ctx context.Context) float64 {
v, err := oss.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from a selector. It is only allowed when selecting one field.
func (oss *OfflineSessionSelect) Bools(ctx context.Context) ([]bool, error) {
if len(oss.fields) > 1 {
return nil, errors.New("db: OfflineSessionSelect.Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := oss.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (oss *OfflineSessionSelect) BoolsX(ctx context.Context) []bool {
v, err := oss.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a selector. It is only allowed when selecting one field.
func (oss *OfflineSessionSelect) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = oss.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{offlinesession.Label}
default:
err = fmt.Errorf("db: OfflineSessionSelect.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (oss *OfflineSessionSelect) BoolX(ctx context.Context) bool {
v, err := oss.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
func (oss *OfflineSessionSelect) sqlScan(ctx context.Context, v interface{}) error {
rows := &sql.Rows{}
query, args := oss.sqlQuery().Query()
if err := oss.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (oss *OfflineSessionSelect) sqlQuery() sql.Querier {
selector := oss.sql
selector.Select(selector.Columns(oss.fields...)...)
return selector
}

View file

@ -0,0 +1,402 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/offlinesession"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// OfflineSessionUpdate is the builder for updating OfflineSession entities.
type OfflineSessionUpdate struct {
config
hooks []Hook
mutation *OfflineSessionMutation
}
// Where adds a new predicate for the OfflineSessionUpdate builder.
func (osu *OfflineSessionUpdate) Where(ps ...predicate.OfflineSession) *OfflineSessionUpdate {
osu.mutation.predicates = append(osu.mutation.predicates, ps...)
return osu
}
// SetUserID sets the "user_id" field.
func (osu *OfflineSessionUpdate) SetUserID(s string) *OfflineSessionUpdate {
osu.mutation.SetUserID(s)
return osu
}
// SetConnID sets the "conn_id" field.
func (osu *OfflineSessionUpdate) SetConnID(s string) *OfflineSessionUpdate {
osu.mutation.SetConnID(s)
return osu
}
// SetRefresh sets the "refresh" field.
func (osu *OfflineSessionUpdate) SetRefresh(b []byte) *OfflineSessionUpdate {
osu.mutation.SetRefresh(b)
return osu
}
// SetConnectorData sets the "connector_data" field.
func (osu *OfflineSessionUpdate) SetConnectorData(b []byte) *OfflineSessionUpdate {
osu.mutation.SetConnectorData(b)
return osu
}
// ClearConnectorData clears the value of the "connector_data" field.
func (osu *OfflineSessionUpdate) ClearConnectorData() *OfflineSessionUpdate {
osu.mutation.ClearConnectorData()
return osu
}
// Mutation returns the OfflineSessionMutation object of the builder.
func (osu *OfflineSessionUpdate) Mutation() *OfflineSessionMutation {
return osu.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) {
var (
err error
affected int
)
if len(osu.hooks) == 0 {
if err = osu.check(); err != nil {
return 0, err
}
affected, err = osu.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*OfflineSessionMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = osu.check(); err != nil {
return 0, err
}
osu.mutation = mutation
affected, err = osu.sqlSave(ctx)
mutation.done = true
return affected, err
})
for i := len(osu.hooks) - 1; i >= 0; i-- {
mut = osu.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, osu.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// SaveX is like Save, but panics if an error occurs.
func (osu *OfflineSessionUpdate) SaveX(ctx context.Context) int {
affected, err := osu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (osu *OfflineSessionUpdate) Exec(ctx context.Context) error {
_, err := osu.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 {
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 {
if err := offlinesession.UserIDValidator(v); err != nil {
return &ValidationError{Name: "user_id", err: fmt.Errorf("db: validator failed for field \"user_id\": %w", err)}
}
}
if v, ok := osu.mutation.ConnID(); ok {
if err := offlinesession.ConnIDValidator(v); err != nil {
return &ValidationError{Name: "conn_id", err: fmt.Errorf("db: validator failed for field \"conn_id\": %w", err)}
}
}
return nil
}
func (osu *OfflineSessionUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: offlinesession.Table,
Columns: offlinesession.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: offlinesession.FieldID,
},
},
}
if ps := osu.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 {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: offlinesession.FieldUserID,
})
}
if value, ok := osu.mutation.ConnID(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: offlinesession.FieldConnID,
})
}
if value, ok := osu.mutation.Refresh(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: offlinesession.FieldRefresh,
})
}
if value, ok := osu.mutation.ConnectorData(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: offlinesession.FieldConnectorData,
})
}
if osu.mutation.ConnectorDataCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Column: offlinesession.FieldConnectorData,
})
}
if n, err = sqlgraph.UpdateNodes(ctx, osu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{offlinesession.Label}
} else if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return 0, err
}
return n, nil
}
// OfflineSessionUpdateOne is the builder for updating a single OfflineSession entity.
type OfflineSessionUpdateOne struct {
config
fields []string
hooks []Hook
mutation *OfflineSessionMutation
}
// SetUserID sets the "user_id" field.
func (osuo *OfflineSessionUpdateOne) SetUserID(s string) *OfflineSessionUpdateOne {
osuo.mutation.SetUserID(s)
return osuo
}
// SetConnID sets the "conn_id" field.
func (osuo *OfflineSessionUpdateOne) SetConnID(s string) *OfflineSessionUpdateOne {
osuo.mutation.SetConnID(s)
return osuo
}
// SetRefresh sets the "refresh" field.
func (osuo *OfflineSessionUpdateOne) SetRefresh(b []byte) *OfflineSessionUpdateOne {
osuo.mutation.SetRefresh(b)
return osuo
}
// SetConnectorData sets the "connector_data" field.
func (osuo *OfflineSessionUpdateOne) SetConnectorData(b []byte) *OfflineSessionUpdateOne {
osuo.mutation.SetConnectorData(b)
return osuo
}
// ClearConnectorData clears the value of the "connector_data" field.
func (osuo *OfflineSessionUpdateOne) ClearConnectorData() *OfflineSessionUpdateOne {
osuo.mutation.ClearConnectorData()
return osuo
}
// Mutation returns the OfflineSessionMutation object of the builder.
func (osuo *OfflineSessionUpdateOne) Mutation() *OfflineSessionMutation {
return osuo.mutation
}
// 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
}
// Save executes the query and returns the updated OfflineSession entity.
func (osuo *OfflineSessionUpdateOne) Save(ctx context.Context) (*OfflineSession, error) {
var (
err error
node *OfflineSession
)
if len(osuo.hooks) == 0 {
if err = osuo.check(); err != nil {
return nil, err
}
node, err = osuo.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*OfflineSessionMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = osuo.check(); err != nil {
return nil, err
}
osuo.mutation = mutation
node, err = osuo.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(osuo.hooks) - 1; i >= 0; i-- {
mut = osuo.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, osuo.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX is like Save, but panics if an error occurs.
func (osuo *OfflineSessionUpdateOne) SaveX(ctx context.Context) *OfflineSession {
node, err := osuo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (osuo *OfflineSessionUpdateOne) Exec(ctx context.Context) error {
_, err := osuo.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 {
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 {
if err := offlinesession.UserIDValidator(v); err != nil {
return &ValidationError{Name: "user_id", err: fmt.Errorf("db: validator failed for field \"user_id\": %w", err)}
}
}
if v, ok := osuo.mutation.ConnID(); ok {
if err := offlinesession.ConnIDValidator(v); err != nil {
return &ValidationError{Name: "conn_id", err: fmt.Errorf("db: validator failed for field \"conn_id\": %w", err)}
}
}
return nil
}
func (osuo *OfflineSessionUpdateOne) sqlSave(ctx context.Context) (_node *OfflineSession, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: offlinesession.Table,
Columns: offlinesession.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: offlinesession.FieldID,
},
},
}
id, ok := osuo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing OfflineSession.ID for update")}
}
_spec.Node.ID.Value = id
if fields := osuo.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 {
if !offlinesession.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
}
if f != offlinesession.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := osuo.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 {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: offlinesession.FieldUserID,
})
}
if value, ok := osuo.mutation.ConnID(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: offlinesession.FieldConnID,
})
}
if value, ok := osuo.mutation.Refresh(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: offlinesession.FieldRefresh,
})
}
if value, ok := osuo.mutation.ConnectorData(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: offlinesession.FieldConnectorData,
})
}
if osuo.mutation.ConnectorDataCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Column: offlinesession.FieldConnectorData,
})
}
_node = &OfflineSession{config: osuo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, osuo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{offlinesession.Label}
} else if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return nil, err
}
return _node, nil
}

131
storage/ent/db/password.go Normal file
View file

@ -0,0 +1,131 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"fmt"
"strings"
"entgo.io/ent/dialect/sql"
"github.com/dexidp/dex/storage/ent/db/password"
)
// Password is the model entity for the Password schema.
type Password struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// Email holds the value of the "email" field.
Email string `json:"email,omitempty"`
// Hash holds the value of the "hash" field.
Hash []byte `json:"hash,omitempty"`
// Username holds the value of the "username" field.
Username string `json:"username,omitempty"`
// UserID holds the value of the "user_id" field.
UserID string `json:"user_id,omitempty"`
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Password) scanValues(columns []string) ([]interface{}, error) {
values := make([]interface{}, len(columns))
for i := range columns {
switch columns[i] {
case password.FieldHash:
values[i] = new([]byte)
case password.FieldID:
values[i] = new(sql.NullInt64)
case password.FieldEmail, password.FieldUsername, password.FieldUserID:
values[i] = new(sql.NullString)
default:
return nil, fmt.Errorf("unexpected column %q for type Password", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Password fields.
func (pa *Password) assignValues(columns []string, values []interface{}) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case password.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
pa.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
}
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
}
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
}
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
}
}
}
return nil
}
// 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 (&PasswordClient{config: pa.config}).UpdateOne(pa)
}
// 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)
if !ok {
panic("db: Password is not a transactional entity")
}
pa.config.driver = tx.drv
return pa
}
// String implements the fmt.Stringer.
func (pa *Password) String() string {
var builder strings.Builder
builder.WriteString("Password(")
builder.WriteString(fmt.Sprintf("id=%v", pa.ID))
builder.WriteString(", email=")
builder.WriteString(pa.Email)
builder.WriteString(", hash=")
builder.WriteString(fmt.Sprintf("%v", pa.Hash))
builder.WriteString(", username=")
builder.WriteString(pa.Username)
builder.WriteString(", user_id=")
builder.WriteString(pa.UserID)
builder.WriteByte(')')
return builder.String()
}
// Passwords is a parsable slice of Password.
type Passwords []*Password
func (pa Passwords) config(cfg config) {
for _i := range pa {
pa[_i].config = cfg
}
}

View file

@ -0,0 +1,48 @@
// Code generated by entc, DO NOT EDIT.
package password
const (
// Label holds the string label denoting the password type in the database.
Label = "password"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldEmail holds the string denoting the email field in the database.
FieldEmail = "email"
// FieldHash holds the string denoting the hash field in the database.
FieldHash = "hash"
// FieldUsername holds the string denoting the username field in the database.
FieldUsername = "username"
// FieldUserID holds the string denoting the user_id field in the database.
FieldUserID = "user_id"
// Table holds the table name of the password in the database.
Table = "passwords"
)
// Columns holds all SQL columns for password fields.
var Columns = []string{
FieldID,
FieldEmail,
FieldHash,
FieldUsername,
FieldUserID,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// EmailValidator is a validator for the "email" field. It is called by the builders before save.
EmailValidator func(string) error
// UsernameValidator is a validator for the "username" field. It is called by the builders before save.
UsernameValidator func(string) error
// UserIDValidator is a validator for the "user_id" field. It is called by the builders before save.
UserIDValidator func(string) error
)

View file

@ -0,0 +1,560 @@
// Code generated by entc, DO NOT EDIT.
package password
import (
"entgo.io/ent/dialect/sql"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldID), id))
})
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.In(s.C(FieldID), v...))
})
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.NotIn(s.C(FieldID), v...))
})
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldID), id))
})
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldID), id))
})
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldID), id))
})
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldID), id))
})
}
// Email applies equality check predicate on the "email" field. It's identical to EmailEQ.
func Email(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldEmail), v))
})
}
// Hash applies equality check predicate on the "hash" field. It's identical to HashEQ.
func Hash(v []byte) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldHash), v))
})
}
// Username applies equality check predicate on the "username" field. It's identical to UsernameEQ.
func Username(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUsername), v))
})
}
// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ.
func UserID(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUserID), v))
})
}
// EmailEQ applies the EQ predicate on the "email" field.
func EmailEQ(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldEmail), v))
})
}
// EmailNEQ applies the NEQ predicate on the "email" field.
func EmailNEQ(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldEmail), v))
})
}
// EmailIn applies the In predicate on the "email" field.
func EmailIn(vs ...string) predicate.Password {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Password(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldEmail), v...))
})
}
// EmailNotIn applies the NotIn predicate on the "email" field.
func EmailNotIn(vs ...string) predicate.Password {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Password(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldEmail), v...))
})
}
// EmailGT applies the GT predicate on the "email" field.
func EmailGT(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldEmail), v))
})
}
// EmailGTE applies the GTE predicate on the "email" field.
func EmailGTE(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldEmail), v))
})
}
// EmailLT applies the LT predicate on the "email" field.
func EmailLT(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldEmail), v))
})
}
// EmailLTE applies the LTE predicate on the "email" field.
func EmailLTE(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldEmail), v))
})
}
// EmailContains applies the Contains predicate on the "email" field.
func EmailContains(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldEmail), v))
})
}
// EmailHasPrefix applies the HasPrefix predicate on the "email" field.
func EmailHasPrefix(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldEmail), v))
})
}
// EmailHasSuffix applies the HasSuffix predicate on the "email" field.
func EmailHasSuffix(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldEmail), v))
})
}
// EmailEqualFold applies the EqualFold predicate on the "email" field.
func EmailEqualFold(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldEmail), v))
})
}
// EmailContainsFold applies the ContainsFold predicate on the "email" field.
func EmailContainsFold(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldEmail), v))
})
}
// HashEQ applies the EQ predicate on the "hash" field.
func HashEQ(v []byte) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldHash), v))
})
}
// HashNEQ applies the NEQ predicate on the "hash" field.
func HashNEQ(v []byte) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldHash), v))
})
}
// HashIn applies the In predicate on the "hash" field.
func HashIn(vs ...[]byte) predicate.Password {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Password(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldHash), v...))
})
}
// HashNotIn applies the NotIn predicate on the "hash" field.
func HashNotIn(vs ...[]byte) predicate.Password {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Password(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldHash), v...))
})
}
// HashGT applies the GT predicate on the "hash" field.
func HashGT(v []byte) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldHash), v))
})
}
// HashGTE applies the GTE predicate on the "hash" field.
func HashGTE(v []byte) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldHash), v))
})
}
// HashLT applies the LT predicate on the "hash" field.
func HashLT(v []byte) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldHash), v))
})
}
// HashLTE applies the LTE predicate on the "hash" field.
func HashLTE(v []byte) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldHash), v))
})
}
// UsernameEQ applies the EQ predicate on the "username" field.
func UsernameEQ(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUsername), v))
})
}
// UsernameNEQ applies the NEQ predicate on the "username" field.
func UsernameNEQ(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldUsername), v))
})
}
// UsernameIn applies the In predicate on the "username" field.
func UsernameIn(vs ...string) predicate.Password {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Password(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldUsername), v...))
})
}
// UsernameNotIn applies the NotIn predicate on the "username" field.
func UsernameNotIn(vs ...string) predicate.Password {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Password(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldUsername), v...))
})
}
// UsernameGT applies the GT predicate on the "username" field.
func UsernameGT(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldUsername), v))
})
}
// UsernameGTE applies the GTE predicate on the "username" field.
func UsernameGTE(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldUsername), v))
})
}
// UsernameLT applies the LT predicate on the "username" field.
func UsernameLT(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldUsername), v))
})
}
// UsernameLTE applies the LTE predicate on the "username" field.
func UsernameLTE(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldUsername), v))
})
}
// UsernameContains applies the Contains predicate on the "username" field.
func UsernameContains(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldUsername), v))
})
}
// UsernameHasPrefix applies the HasPrefix predicate on the "username" field.
func UsernameHasPrefix(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldUsername), v))
})
}
// UsernameHasSuffix applies the HasSuffix predicate on the "username" field.
func UsernameHasSuffix(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldUsername), v))
})
}
// UsernameEqualFold applies the EqualFold predicate on the "username" field.
func UsernameEqualFold(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldUsername), v))
})
}
// UsernameContainsFold applies the ContainsFold predicate on the "username" field.
func UsernameContainsFold(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldUsername), v))
})
}
// UserIDEQ applies the EQ predicate on the "user_id" field.
func UserIDEQ(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldUserID), v))
})
}
// UserIDNEQ applies the NEQ predicate on the "user_id" field.
func UserIDNEQ(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldUserID), v))
})
}
// UserIDIn applies the In predicate on the "user_id" field.
func UserIDIn(vs ...string) predicate.Password {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Password(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldUserID), v...))
})
}
// UserIDNotIn applies the NotIn predicate on the "user_id" field.
func UserIDNotIn(vs ...string) predicate.Password {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Password(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldUserID), v...))
})
}
// UserIDGT applies the GT predicate on the "user_id" field.
func UserIDGT(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldUserID), v))
})
}
// UserIDGTE applies the GTE predicate on the "user_id" field.
func UserIDGTE(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldUserID), v))
})
}
// UserIDLT applies the LT predicate on the "user_id" field.
func UserIDLT(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldUserID), v))
})
}
// UserIDLTE applies the LTE predicate on the "user_id" field.
func UserIDLTE(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldUserID), v))
})
}
// UserIDContains applies the Contains predicate on the "user_id" field.
func UserIDContains(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.Contains(s.C(FieldUserID), v))
})
}
// UserIDHasPrefix applies the HasPrefix predicate on the "user_id" field.
func UserIDHasPrefix(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.HasPrefix(s.C(FieldUserID), v))
})
}
// UserIDHasSuffix applies the HasSuffix predicate on the "user_id" field.
func UserIDHasSuffix(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.HasSuffix(s.C(FieldUserID), v))
})
}
// UserIDEqualFold applies the EqualFold predicate on the "user_id" field.
func UserIDEqualFold(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.EqualFold(s.C(FieldUserID), v))
})
}
// UserIDContainsFold applies the ContainsFold predicate on the "user_id" field.
func UserIDContainsFold(v string) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s.Where(sql.ContainsFold(s.C(FieldUserID), v))
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Password) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for _, p := range predicates {
p(s1)
}
s.Where(s1.P())
})
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Password) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for i, p := range predicates {
if i > 0 {
s1.Or()
}
p(s1)
}
s.Where(s1.P())
})
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Password) predicate.Password {
return predicate.Password(func(s *sql.Selector) {
p(s.Not())
})
}

View file

@ -0,0 +1,250 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"errors"
"fmt"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/password"
)
// PasswordCreate is the builder for creating a Password entity.
type PasswordCreate struct {
config
mutation *PasswordMutation
hooks []Hook
}
// SetEmail sets the "email" field.
func (pc *PasswordCreate) SetEmail(s string) *PasswordCreate {
pc.mutation.SetEmail(s)
return pc
}
// SetHash sets the "hash" field.
func (pc *PasswordCreate) SetHash(b []byte) *PasswordCreate {
pc.mutation.SetHash(b)
return pc
}
// SetUsername sets the "username" field.
func (pc *PasswordCreate) SetUsername(s string) *PasswordCreate {
pc.mutation.SetUsername(s)
return pc
}
// SetUserID sets the "user_id" field.
func (pc *PasswordCreate) SetUserID(s string) *PasswordCreate {
pc.mutation.SetUserID(s)
return pc
}
// Mutation returns the PasswordMutation object of the builder.
func (pc *PasswordCreate) Mutation() *PasswordMutation {
return pc.mutation
}
// Save creates the Password in the database.
func (pc *PasswordCreate) Save(ctx context.Context) (*Password, error) {
var (
err error
node *Password
)
if len(pc.hooks) == 0 {
if err = pc.check(); err != nil {
return nil, err
}
node, err = pc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*PasswordMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = pc.check(); err != nil {
return nil, err
}
pc.mutation = mutation
node, err = pc.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(pc.hooks) - 1; i >= 0; i-- {
mut = pc.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, pc.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (pc *PasswordCreate) SaveX(ctx context.Context) *Password {
v, err := pc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// check runs all checks and user-defined validators on the builder.
func (pc *PasswordCreate) check() error {
if _, ok := pc.mutation.Email(); !ok {
return &ValidationError{Name: "email", err: errors.New("db: missing required field \"email\"")}
}
if v, ok := pc.mutation.Email(); ok {
if err := password.EmailValidator(v); err != nil {
return &ValidationError{Name: "email", err: fmt.Errorf("db: validator failed for field \"email\": %w", err)}
}
}
if _, ok := pc.mutation.Hash(); !ok {
return &ValidationError{Name: "hash", err: errors.New("db: missing required field \"hash\"")}
}
if _, ok := pc.mutation.Username(); !ok {
return &ValidationError{Name: "username", err: errors.New("db: missing required field \"username\"")}
}
if v, ok := pc.mutation.Username(); ok {
if err := password.UsernameValidator(v); err != nil {
return &ValidationError{Name: "username", err: fmt.Errorf("db: validator failed for field \"username\": %w", err)}
}
}
if _, ok := pc.mutation.UserID(); !ok {
return &ValidationError{Name: "user_id", err: errors.New("db: missing required field \"user_id\"")}
}
if v, ok := pc.mutation.UserID(); ok {
if err := password.UserIDValidator(v); err != nil {
return &ValidationError{Name: "user_id", err: fmt.Errorf("db: validator failed for field \"user_id\": %w", err)}
}
}
return nil
}
func (pc *PasswordCreate) sqlSave(ctx context.Context) (*Password, error) {
_node, _spec := pc.createSpec()
if err := sqlgraph.CreateNode(ctx, pc.driver, _spec); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
return _node, nil
}
func (pc *PasswordCreate) createSpec() (*Password, *sqlgraph.CreateSpec) {
var (
_node = &Password{config: pc.config}
_spec = &sqlgraph.CreateSpec{
Table: password.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: password.FieldID,
},
}
)
if value, ok := pc.mutation.Email(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: password.FieldEmail,
})
_node.Email = value
}
if value, ok := pc.mutation.Hash(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: password.FieldHash,
})
_node.Hash = value
}
if value, ok := pc.mutation.Username(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: password.FieldUsername,
})
_node.Username = value
}
if value, ok := pc.mutation.UserID(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: password.FieldUserID,
})
_node.UserID = value
}
return _node, _spec
}
// PasswordCreateBulk is the builder for creating many Password entities in bulk.
type PasswordCreateBulk struct {
config
builders []*PasswordCreate
}
// Save creates the Password entities in the database.
func (pcb *PasswordCreateBulk) Save(ctx context.Context) ([]*Password, error) {
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(i int, root context.Context) {
builder := pcb.builders[i]
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*PasswordMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
nodes[i], specs[i] = builder.createSpec()
var err error
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, pcb.builders[i+1].mutation)
} else {
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, pcb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
}
}
mutation.done = true
if err != nil {
return nil, err
}
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, pcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (pcb *PasswordCreateBulk) SaveX(ctx context.Context) []*Password {
v, err := pcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}

View file

@ -0,0 +1,108 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/password"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// PasswordDelete is the builder for deleting a Password entity.
type PasswordDelete struct {
config
hooks []Hook
mutation *PasswordMutation
}
// Where adds a new predicate to the PasswordDelete builder.
func (pd *PasswordDelete) Where(ps ...predicate.Password) *PasswordDelete {
pd.mutation.predicates = append(pd.mutation.predicates, ps...)
return pd
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (pd *PasswordDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(pd.hooks) == 0 {
affected, err = pd.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*PasswordMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
pd.mutation = mutation
affected, err = pd.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(pd.hooks) - 1; i >= 0; i-- {
mut = pd.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, pd.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (pd *PasswordDelete) ExecX(ctx context.Context) int {
n, err := pd.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (pd *PasswordDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: password.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: password.FieldID,
},
},
}
if ps := pd.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return sqlgraph.DeleteNodes(ctx, pd.driver, _spec)
}
// PasswordDeleteOne is the builder for deleting a single Password entity.
type PasswordDeleteOne struct {
pd *PasswordDelete
}
// Exec executes the deletion query.
func (pdo *PasswordDeleteOne) Exec(ctx context.Context) error {
n, err := pdo.pd.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{password.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (pdo *PasswordDeleteOne) ExecX(ctx context.Context) {
pdo.pd.ExecX(ctx)
}

View file

@ -0,0 +1,906 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"errors"
"fmt"
"math"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/password"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// PasswordQuery is the builder for querying Password entities.
type PasswordQuery struct {
config
limit *int
offset *int
unique *bool
order []OrderFunc
fields []string
predicates []predicate.Password
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// 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
}
// Limit adds a limit step to the query.
func (pq *PasswordQuery) Limit(limit int) *PasswordQuery {
pq.limit = &limit
return pq
}
// Offset adds an offset step to the query.
func (pq *PasswordQuery) Offset(offset int) *PasswordQuery {
pq.offset = &offset
return pq
}
// Unique configures the query builder to filter duplicate records on query.
// By default, unique is set to true, and can be disabled using this method.
func (pq *PasswordQuery) Unique(unique bool) *PasswordQuery {
pq.unique = &unique
return pq
}
// Order adds an order step to the query.
func (pq *PasswordQuery) Order(o ...OrderFunc) *PasswordQuery {
pq.order = append(pq.order, o...)
return pq
}
// 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(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{password.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (pq *PasswordQuery) FirstX(ctx context.Context) *Password {
node, err := pq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// 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) {
var ids []int
if ids, err = pq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{password.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (pq *PasswordQuery) FirstIDX(ctx context.Context) int {
id, err := pq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Password entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when exactly one Password entity is not 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(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{password.Label}
default:
return nil, &NotSingularError{password.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (pq *PasswordQuery) OnlyX(ctx context.Context) *Password {
node, err := pq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Password ID in the query.
// Returns a *NotSingularError when exactly one Password ID is not found.
// Returns a *NotFoundError when no entities are found.
func (pq *PasswordQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = pq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{password.Label}
default:
err = &NotSingularError{password.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (pq *PasswordQuery) OnlyIDX(ctx context.Context) int {
id, err := pq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Passwords.
func (pq *PasswordQuery) All(ctx context.Context) ([]*Password, error) {
if err := pq.prepareQuery(ctx); err != nil {
return nil, err
}
return pq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (pq *PasswordQuery) AllX(ctx context.Context) []*Password {
nodes, err := pq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Password IDs.
func (pq *PasswordQuery) IDs(ctx context.Context) ([]int, error) {
var ids []int
if err := pq.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)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (pq *PasswordQuery) Count(ctx context.Context) (int, error) {
if err := pq.prepareQuery(ctx); err != nil {
return 0, err
}
return pq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (pq *PasswordQuery) CountX(ctx context.Context) int {
count, err := pq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (pq *PasswordQuery) Exist(ctx context.Context) (bool, error) {
if err := pq.prepareQuery(ctx); err != nil {
return false, err
}
return pq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (pq *PasswordQuery) ExistX(ctx context.Context) bool {
exist, err := pq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// 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 {
return nil
}
return &PasswordQuery{
config: pq.config,
limit: pq.limit,
offset: pq.offset,
order: append([]OrderFunc{}, pq.order...),
predicates: append([]predicate.Password{}, pq.predicates...),
// clone intermediate query.
sql: pq.sql.Clone(),
path: pq.path,
}
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// Email string `json:"email,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Password.Query().
// GroupBy(password.FieldEmail).
// Aggregate(db.Count()).
// Scan(ctx, &v)
//
func (pq *PasswordQuery) GroupBy(field string, fields ...string) *PasswordGroupBy {
group := &PasswordGroupBy{config: pq.config}
group.fields = append([]string{field}, fields...)
group.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := pq.prepareQuery(ctx); err != nil {
return nil, err
}
return pq.sqlQuery(ctx), nil
}
return group
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// Email string `json:"email,omitempty"`
// }
//
// client.Password.Query().
// Select(password.FieldEmail).
// Scan(ctx, &v)
//
func (pq *PasswordQuery) Select(field string, fields ...string) *PasswordSelect {
pq.fields = append([]string{field}, fields...)
return &PasswordSelect{PasswordQuery: pq}
}
func (pq *PasswordQuery) prepareQuery(ctx context.Context) error {
for _, f := range pq.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 err != nil {
return err
}
pq.sql = prev
}
return nil
}
func (pq *PasswordQuery) sqlAll(ctx context.Context) ([]*Password, error) {
var (
nodes = []*Password{}
_spec = pq.querySpec()
)
_spec.ScanValues = func(columns []string) ([]interface{}, error) {
node := &Password{config: pq.config}
nodes = append(nodes, node)
return node.scanValues(columns)
}
_spec.Assign = func(columns []string, values []interface{}) error {
if len(nodes) == 0 {
return fmt.Errorf("db: Assign called without calling ScanValues")
}
node := nodes[len(nodes)-1]
return node.assignValues(columns, values)
}
if err := sqlgraph.QueryNodes(ctx, pq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (pq *PasswordQuery) sqlCount(ctx context.Context) (int, error) {
_spec := pq.querySpec()
return sqlgraph.CountNodes(ctx, pq.driver, _spec)
}
func (pq *PasswordQuery) sqlExist(ctx context.Context) (bool, error) {
n, err := pq.sqlCount(ctx)
if err != nil {
return false, fmt.Errorf("db: check existence: %w", err)
}
return n > 0, nil
}
func (pq *PasswordQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: password.Table,
Columns: password.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: password.FieldID,
},
},
From: pq.sql,
Unique: true,
}
if unique := pq.unique; unique != nil {
_spec.Unique = *unique
}
if fields := pq.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 {
if fields[i] != password.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := pq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := pq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := pq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := pq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (pq *PasswordQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(pq.driver.Dialect())
t1 := builder.Table(password.Table)
selector := builder.Select(t1.Columns(password.Columns...)...).From(t1)
if pq.sql != nil {
selector = pq.sql
selector.Select(selector.Columns(password.Columns...)...)
}
for _, p := range pq.predicates {
p(selector)
}
for _, p := range pq.order {
p(selector)
}
if offset := pq.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.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// PasswordGroupBy is the group-by builder for Password entities.
type PasswordGroupBy struct {
config
fields []string
fns []AggregateFunc
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Aggregate adds the given aggregation functions to the group-by query.
func (pgb *PasswordGroupBy) Aggregate(fns ...AggregateFunc) *PasswordGroupBy {
pgb.fns = append(pgb.fns, fns...)
return pgb
}
// Scan applies the group-by query and scans the result into the given value.
func (pgb *PasswordGroupBy) Scan(ctx context.Context, v interface{}) error {
query, err := pgb.path(ctx)
if err != nil {
return err
}
pgb.sql = query
return pgb.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (pgb *PasswordGroupBy) ScanX(ctx context.Context, v interface{}) {
if err := pgb.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from group-by.
// It is only allowed when executing a group-by query with one field.
func (pgb *PasswordGroupBy) Strings(ctx context.Context) ([]string, error) {
if len(pgb.fields) > 1 {
return nil, errors.New("db: PasswordGroupBy.Strings is not achievable when grouping more than 1 field")
}
var v []string
if err := pgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (pgb *PasswordGroupBy) StringsX(ctx context.Context) []string {
v, err := pgb.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (pgb *PasswordGroupBy) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = pgb.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{password.Label}
default:
err = fmt.Errorf("db: PasswordGroupBy.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (pgb *PasswordGroupBy) StringX(ctx context.Context) string {
v, err := pgb.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from group-by.
// It is only allowed when executing a group-by query with one field.
func (pgb *PasswordGroupBy) Ints(ctx context.Context) ([]int, error) {
if len(pgb.fields) > 1 {
return nil, errors.New("db: PasswordGroupBy.Ints is not achievable when grouping more than 1 field")
}
var v []int
if err := pgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (pgb *PasswordGroupBy) IntsX(ctx context.Context) []int {
v, err := pgb.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (pgb *PasswordGroupBy) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = pgb.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{password.Label}
default:
err = fmt.Errorf("db: PasswordGroupBy.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (pgb *PasswordGroupBy) IntX(ctx context.Context) int {
v, err := pgb.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from group-by.
// It is only allowed when executing a group-by query with one field.
func (pgb *PasswordGroupBy) Float64s(ctx context.Context) ([]float64, error) {
if len(pgb.fields) > 1 {
return nil, errors.New("db: PasswordGroupBy.Float64s is not achievable when grouping more than 1 field")
}
var v []float64
if err := pgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (pgb *PasswordGroupBy) Float64sX(ctx context.Context) []float64 {
v, err := pgb.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (pgb *PasswordGroupBy) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = pgb.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{password.Label}
default:
err = fmt.Errorf("db: PasswordGroupBy.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (pgb *PasswordGroupBy) Float64X(ctx context.Context) float64 {
v, err := pgb.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from group-by.
// It is only allowed when executing a group-by query with one field.
func (pgb *PasswordGroupBy) Bools(ctx context.Context) ([]bool, error) {
if len(pgb.fields) > 1 {
return nil, errors.New("db: PasswordGroupBy.Bools is not achievable when grouping more than 1 field")
}
var v []bool
if err := pgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (pgb *PasswordGroupBy) BoolsX(ctx context.Context) []bool {
v, err := pgb.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (pgb *PasswordGroupBy) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = pgb.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{password.Label}
default:
err = fmt.Errorf("db: PasswordGroupBy.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (pgb *PasswordGroupBy) BoolX(ctx context.Context) bool {
v, err := pgb.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
func (pgb *PasswordGroupBy) sqlScan(ctx context.Context, v interface{}) error {
for _, f := range pgb.fields {
if !password.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := pgb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := pgb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (pgb *PasswordGroupBy) sqlQuery() *sql.Selector {
selector := pgb.sql
columns := make([]string, 0, len(pgb.fields)+len(pgb.fns))
columns = append(columns, pgb.fields...)
for _, fn := range pgb.fns {
columns = append(columns, fn(selector))
}
return selector.Select(columns...).GroupBy(pgb.fields...)
}
// PasswordSelect is the builder for selecting fields of Password entities.
type PasswordSelect struct {
*PasswordQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
}
// Scan applies the selector query and scans the result into the given value.
func (ps *PasswordSelect) Scan(ctx context.Context, v interface{}) error {
if err := ps.prepareQuery(ctx); err != nil {
return err
}
ps.sql = ps.PasswordQuery.sqlQuery(ctx)
return ps.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (ps *PasswordSelect) ScanX(ctx context.Context, v interface{}) {
if err := ps.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from a selector. It is only allowed when selecting one field.
func (ps *PasswordSelect) Strings(ctx context.Context) ([]string, error) {
if len(ps.fields) > 1 {
return nil, errors.New("db: PasswordSelect.Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := ps.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (ps *PasswordSelect) StringsX(ctx context.Context) []string {
v, err := ps.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a selector. It is only allowed when selecting one field.
func (ps *PasswordSelect) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = ps.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{password.Label}
default:
err = fmt.Errorf("db: PasswordSelect.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (ps *PasswordSelect) StringX(ctx context.Context) string {
v, err := ps.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from a selector. It is only allowed when selecting one field.
func (ps *PasswordSelect) Ints(ctx context.Context) ([]int, error) {
if len(ps.fields) > 1 {
return nil, errors.New("db: PasswordSelect.Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := ps.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (ps *PasswordSelect) IntsX(ctx context.Context) []int {
v, err := ps.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a selector. It is only allowed when selecting one field.
func (ps *PasswordSelect) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = ps.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{password.Label}
default:
err = fmt.Errorf("db: PasswordSelect.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (ps *PasswordSelect) IntX(ctx context.Context) int {
v, err := ps.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
func (ps *PasswordSelect) Float64s(ctx context.Context) ([]float64, error) {
if len(ps.fields) > 1 {
return nil, errors.New("db: PasswordSelect.Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := ps.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (ps *PasswordSelect) Float64sX(ctx context.Context) []float64 {
v, err := ps.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
func (ps *PasswordSelect) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = ps.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{password.Label}
default:
err = fmt.Errorf("db: PasswordSelect.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (ps *PasswordSelect) Float64X(ctx context.Context) float64 {
v, err := ps.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from a selector. It is only allowed when selecting one field.
func (ps *PasswordSelect) Bools(ctx context.Context) ([]bool, error) {
if len(ps.fields) > 1 {
return nil, errors.New("db: PasswordSelect.Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := ps.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (ps *PasswordSelect) BoolsX(ctx context.Context) []bool {
v, err := ps.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a selector. It is only allowed when selecting one field.
func (ps *PasswordSelect) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = ps.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{password.Label}
default:
err = fmt.Errorf("db: PasswordSelect.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (ps *PasswordSelect) BoolX(ctx context.Context) bool {
v, err := ps.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
func (ps *PasswordSelect) sqlScan(ctx context.Context, v interface{}) error {
rows := &sql.Rows{}
query, args := ps.sqlQuery().Query()
if err := ps.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (ps *PasswordSelect) sqlQuery() sql.Querier {
selector := ps.sql
selector.Select(selector.Columns(ps.fields...)...)
return selector
}

View file

@ -0,0 +1,388 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/password"
"github.com/dexidp/dex/storage/ent/db/predicate"
)
// PasswordUpdate is the builder for updating Password entities.
type PasswordUpdate struct {
config
hooks []Hook
mutation *PasswordMutation
}
// Where adds a new predicate for the PasswordUpdate builder.
func (pu *PasswordUpdate) Where(ps ...predicate.Password) *PasswordUpdate {
pu.mutation.predicates = append(pu.mutation.predicates, ps...)
return pu
}
// SetEmail sets the "email" field.
func (pu *PasswordUpdate) SetEmail(s string) *PasswordUpdate {
pu.mutation.SetEmail(s)
return pu
}
// SetHash sets the "hash" field.
func (pu *PasswordUpdate) SetHash(b []byte) *PasswordUpdate {
pu.mutation.SetHash(b)
return pu
}
// SetUsername sets the "username" field.
func (pu *PasswordUpdate) SetUsername(s string) *PasswordUpdate {
pu.mutation.SetUsername(s)
return pu
}
// SetUserID sets the "user_id" field.
func (pu *PasswordUpdate) SetUserID(s string) *PasswordUpdate {
pu.mutation.SetUserID(s)
return pu
}
// Mutation returns the PasswordMutation object of the builder.
func (pu *PasswordUpdate) Mutation() *PasswordMutation {
return pu.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) {
var (
err error
affected int
)
if len(pu.hooks) == 0 {
if err = pu.check(); err != nil {
return 0, err
}
affected, err = pu.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*PasswordMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = pu.check(); err != nil {
return 0, err
}
pu.mutation = mutation
affected, err = pu.sqlSave(ctx)
mutation.done = true
return affected, err
})
for i := len(pu.hooks) - 1; i >= 0; i-- {
mut = pu.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, pu.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// SaveX is like Save, but panics if an error occurs.
func (pu *PasswordUpdate) SaveX(ctx context.Context) int {
affected, err := pu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (pu *PasswordUpdate) Exec(ctx context.Context) error {
_, err := pu.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 {
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 {
if err := password.EmailValidator(v); err != nil {
return &ValidationError{Name: "email", err: fmt.Errorf("db: validator failed for field \"email\": %w", err)}
}
}
if v, ok := pu.mutation.Username(); ok {
if err := password.UsernameValidator(v); err != nil {
return &ValidationError{Name: "username", err: fmt.Errorf("db: validator failed for field \"username\": %w", err)}
}
}
if v, ok := pu.mutation.UserID(); ok {
if err := password.UserIDValidator(v); err != nil {
return &ValidationError{Name: "user_id", err: fmt.Errorf("db: validator failed for field \"user_id\": %w", err)}
}
}
return nil
}
func (pu *PasswordUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: password.Table,
Columns: password.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: password.FieldID,
},
},
}
if ps := pu.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 {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: password.FieldEmail,
})
}
if value, ok := pu.mutation.Hash(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: password.FieldHash,
})
}
if value, ok := pu.mutation.Username(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: password.FieldUsername,
})
}
if value, ok := pu.mutation.UserID(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: password.FieldUserID,
})
}
if n, err = sqlgraph.UpdateNodes(ctx, pu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{password.Label}
} else if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return 0, err
}
return n, nil
}
// PasswordUpdateOne is the builder for updating a single Password entity.
type PasswordUpdateOne struct {
config
fields []string
hooks []Hook
mutation *PasswordMutation
}
// SetEmail sets the "email" field.
func (puo *PasswordUpdateOne) SetEmail(s string) *PasswordUpdateOne {
puo.mutation.SetEmail(s)
return puo
}
// SetHash sets the "hash" field.
func (puo *PasswordUpdateOne) SetHash(b []byte) *PasswordUpdateOne {
puo.mutation.SetHash(b)
return puo
}
// SetUsername sets the "username" field.
func (puo *PasswordUpdateOne) SetUsername(s string) *PasswordUpdateOne {
puo.mutation.SetUsername(s)
return puo
}
// SetUserID sets the "user_id" field.
func (puo *PasswordUpdateOne) SetUserID(s string) *PasswordUpdateOne {
puo.mutation.SetUserID(s)
return puo
}
// Mutation returns the PasswordMutation object of the builder.
func (puo *PasswordUpdateOne) Mutation() *PasswordMutation {
return puo.mutation
}
// 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
}
// Save executes the query and returns the updated Password entity.
func (puo *PasswordUpdateOne) Save(ctx context.Context) (*Password, error) {
var (
err error
node *Password
)
if len(puo.hooks) == 0 {
if err = puo.check(); err != nil {
return nil, err
}
node, err = puo.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*PasswordMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = puo.check(); err != nil {
return nil, err
}
puo.mutation = mutation
node, err = puo.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(puo.hooks) - 1; i >= 0; i-- {
mut = puo.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, puo.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX is like Save, but panics if an error occurs.
func (puo *PasswordUpdateOne) SaveX(ctx context.Context) *Password {
node, err := puo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (puo *PasswordUpdateOne) Exec(ctx context.Context) error {
_, err := puo.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 {
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 {
if err := password.EmailValidator(v); err != nil {
return &ValidationError{Name: "email", err: fmt.Errorf("db: validator failed for field \"email\": %w", err)}
}
}
if v, ok := puo.mutation.Username(); ok {
if err := password.UsernameValidator(v); err != nil {
return &ValidationError{Name: "username", err: fmt.Errorf("db: validator failed for field \"username\": %w", err)}
}
}
if v, ok := puo.mutation.UserID(); ok {
if err := password.UserIDValidator(v); err != nil {
return &ValidationError{Name: "user_id", err: fmt.Errorf("db: validator failed for field \"user_id\": %w", err)}
}
}
return nil
}
func (puo *PasswordUpdateOne) sqlSave(ctx context.Context) (_node *Password, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: password.Table,
Columns: password.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: password.FieldID,
},
},
}
id, ok := puo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing Password.ID for update")}
}
_spec.Node.ID.Value = id
if fields := puo.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, password.FieldID)
for _, f := range fields {
if !password.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
}
if f != password.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := puo.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := puo.mutation.Email(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: password.FieldEmail,
})
}
if value, ok := puo.mutation.Hash(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: password.FieldHash,
})
}
if value, ok := puo.mutation.Username(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: password.FieldUsername,
})
}
if value, ok := puo.mutation.UserID(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: password.FieldUserID,
})
}
_node = &Password{config: puo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, puo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{password.Label}
} else if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return nil, err
}
return _node, nil
}

View file

@ -0,0 +1,37 @@
// Code generated by entc, DO NOT EDIT.
package predicate
import (
"entgo.io/ent/dialect/sql"
)
// AuthCode is the predicate function for authcode builders.
type AuthCode func(*sql.Selector)
// AuthRequest is the predicate function for authrequest builders.
type AuthRequest func(*sql.Selector)
// Connector is the predicate function for connector builders.
type Connector func(*sql.Selector)
// DeviceRequest is the predicate function for devicerequest builders.
type DeviceRequest func(*sql.Selector)
// DeviceToken is the predicate function for devicetoken builders.
type DeviceToken func(*sql.Selector)
// Keys is the predicate function for keys builders.
type Keys func(*sql.Selector)
// OAuth2Client is the predicate function for oauth2client builders.
type OAuth2Client func(*sql.Selector)
// OfflineSession is the predicate function for offlinesession builders.
type OfflineSession func(*sql.Selector)
// Password is the predicate function for password builders.
type Password func(*sql.Selector)
// RefreshToken is the predicate function for refreshtoken builders.
type RefreshToken func(*sql.Selector)

View file

@ -0,0 +1,253 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"encoding/json"
"fmt"
"strings"
"time"
"entgo.io/ent/dialect/sql"
"github.com/dexidp/dex/storage/ent/db/refreshtoken"
)
// RefreshToken is the model entity for the RefreshToken schema.
type RefreshToken struct {
config `json:"-"`
// ID of the ent.
ID string `json:"id,omitempty"`
// ClientID holds the value of the "client_id" field.
ClientID string `json:"client_id,omitempty"`
// Scopes holds the value of the "scopes" field.
Scopes []string `json:"scopes,omitempty"`
// Nonce holds the value of the "nonce" field.
Nonce string `json:"nonce,omitempty"`
// ClaimsUserID holds the value of the "claims_user_id" field.
ClaimsUserID string `json:"claims_user_id,omitempty"`
// ClaimsUsername holds the value of the "claims_username" field.
ClaimsUsername string `json:"claims_username,omitempty"`
// ClaimsEmail holds the value of the "claims_email" field.
ClaimsEmail string `json:"claims_email,omitempty"`
// ClaimsEmailVerified holds the value of the "claims_email_verified" field.
ClaimsEmailVerified bool `json:"claims_email_verified,omitempty"`
// ClaimsGroups holds the value of the "claims_groups" field.
ClaimsGroups []string `json:"claims_groups,omitempty"`
// ClaimsPreferredUsername holds the value of the "claims_preferred_username" field.
ClaimsPreferredUsername string `json:"claims_preferred_username,omitempty"`
// ConnectorID holds the value of the "connector_id" field.
ConnectorID string `json:"connector_id,omitempty"`
// ConnectorData holds the value of the "connector_data" field.
ConnectorData *[]byte `json:"connector_data,omitempty"`
// Token holds the value of the "token" field.
Token string `json:"token,omitempty"`
// ObsoleteToken holds the value of the "obsolete_token" field.
ObsoleteToken string `json:"obsolete_token,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt time.Time `json:"created_at,omitempty"`
// LastUsed holds the value of the "last_used" field.
LastUsed time.Time `json:"last_used,omitempty"`
}
// scanValues returns the types for scanning values from sql.Rows.
func (*RefreshToken) scanValues(columns []string) ([]interface{}, error) {
values := make([]interface{}, len(columns))
for i := range columns {
switch columns[i] {
case refreshtoken.FieldScopes, refreshtoken.FieldClaimsGroups, refreshtoken.FieldConnectorData:
values[i] = new([]byte)
case refreshtoken.FieldClaimsEmailVerified:
values[i] = new(sql.NullBool)
case refreshtoken.FieldID, refreshtoken.FieldClientID, refreshtoken.FieldNonce, refreshtoken.FieldClaimsUserID, refreshtoken.FieldClaimsUsername, refreshtoken.FieldClaimsEmail, refreshtoken.FieldClaimsPreferredUsername, refreshtoken.FieldConnectorID, refreshtoken.FieldToken, refreshtoken.FieldObsoleteToken:
values[i] = new(sql.NullString)
case refreshtoken.FieldCreatedAt, refreshtoken.FieldLastUsed:
values[i] = new(sql.NullTime)
default:
return nil, fmt.Errorf("unexpected column %q for type RefreshToken", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the RefreshToken fields.
func (rt *RefreshToken) assignValues(columns []string, values []interface{}) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case refreshtoken.FieldID:
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
}
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
}
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 {
return fmt.Errorf("unmarshal field scopes: %w", err)
}
}
case refreshtoken.FieldNonce:
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
}
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
}
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
}
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
}
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
}
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 {
return fmt.Errorf("unmarshal field claims_groups: %w", err)
}
}
case refreshtoken.FieldClaimsPreferredUsername:
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
}
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
}
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
}
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
}
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
}
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
}
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
}
}
}
return nil
}
// 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 (&RefreshTokenClient{config: rt.config}).UpdateOne(rt)
}
// 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)
if !ok {
panic("db: RefreshToken is not a transactional entity")
}
rt.config.driver = tx.drv
return rt
}
// String implements the fmt.Stringer.
func (rt *RefreshToken) String() string {
var builder strings.Builder
builder.WriteString("RefreshToken(")
builder.WriteString(fmt.Sprintf("id=%v", rt.ID))
builder.WriteString(", client_id=")
builder.WriteString(rt.ClientID)
builder.WriteString(", scopes=")
builder.WriteString(fmt.Sprintf("%v", rt.Scopes))
builder.WriteString(", nonce=")
builder.WriteString(rt.Nonce)
builder.WriteString(", claims_user_id=")
builder.WriteString(rt.ClaimsUserID)
builder.WriteString(", claims_username=")
builder.WriteString(rt.ClaimsUsername)
builder.WriteString(", claims_email=")
builder.WriteString(rt.ClaimsEmail)
builder.WriteString(", claims_email_verified=")
builder.WriteString(fmt.Sprintf("%v", rt.ClaimsEmailVerified))
builder.WriteString(", claims_groups=")
builder.WriteString(fmt.Sprintf("%v", rt.ClaimsGroups))
builder.WriteString(", claims_preferred_username=")
builder.WriteString(rt.ClaimsPreferredUsername)
builder.WriteString(", connector_id=")
builder.WriteString(rt.ConnectorID)
if v := rt.ConnectorData; v != nil {
builder.WriteString(", connector_data=")
builder.WriteString(fmt.Sprintf("%v", *v))
}
builder.WriteString(", token=")
builder.WriteString(rt.Token)
builder.WriteString(", obsolete_token=")
builder.WriteString(rt.ObsoleteToken)
builder.WriteString(", created_at=")
builder.WriteString(rt.CreatedAt.Format(time.ANSIC))
builder.WriteString(", last_used=")
builder.WriteString(rt.LastUsed.Format(time.ANSIC))
builder.WriteByte(')')
return builder.String()
}
// RefreshTokens is a parsable slice of RefreshToken.
type RefreshTokens []*RefreshToken
func (rt RefreshTokens) config(cfg config) {
for _i := range rt {
rt[_i].config = cfg
}
}

View file

@ -0,0 +1,103 @@
// Code generated by entc, DO NOT EDIT.
package refreshtoken
import (
"time"
)
const (
// Label holds the string label denoting the refreshtoken type in the database.
Label = "refresh_token"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldClientID holds the string denoting the client_id field in the database.
FieldClientID = "client_id"
// FieldScopes holds the string denoting the scopes field in the database.
FieldScopes = "scopes"
// FieldNonce holds the string denoting the nonce field in the database.
FieldNonce = "nonce"
// FieldClaimsUserID holds the string denoting the claims_user_id field in the database.
FieldClaimsUserID = "claims_user_id"
// FieldClaimsUsername holds the string denoting the claims_username field in the database.
FieldClaimsUsername = "claims_username"
// FieldClaimsEmail holds the string denoting the claims_email field in the database.
FieldClaimsEmail = "claims_email"
// FieldClaimsEmailVerified holds the string denoting the claims_email_verified field in the database.
FieldClaimsEmailVerified = "claims_email_verified"
// FieldClaimsGroups holds the string denoting the claims_groups field in the database.
FieldClaimsGroups = "claims_groups"
// FieldClaimsPreferredUsername holds the string denoting the claims_preferred_username field in the database.
FieldClaimsPreferredUsername = "claims_preferred_username"
// FieldConnectorID holds the string denoting the connector_id field in the database.
FieldConnectorID = "connector_id"
// FieldConnectorData holds the string denoting the connector_data field in the database.
FieldConnectorData = "connector_data"
// FieldToken holds the string denoting the token field in the database.
FieldToken = "token"
// FieldObsoleteToken holds the string denoting the obsolete_token field in the database.
FieldObsoleteToken = "obsolete_token"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// FieldLastUsed holds the string denoting the last_used field in the database.
FieldLastUsed = "last_used"
// Table holds the table name of the refreshtoken in the database.
Table = "refresh_tokens"
)
// Columns holds all SQL columns for refreshtoken fields.
var Columns = []string{
FieldID,
FieldClientID,
FieldScopes,
FieldNonce,
FieldClaimsUserID,
FieldClaimsUsername,
FieldClaimsEmail,
FieldClaimsEmailVerified,
FieldClaimsGroups,
FieldClaimsPreferredUsername,
FieldConnectorID,
FieldConnectorData,
FieldToken,
FieldObsoleteToken,
FieldCreatedAt,
FieldLastUsed,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// ClientIDValidator is a validator for the "client_id" field. It is called by the builders before save.
ClientIDValidator func(string) error
// NonceValidator is a validator for the "nonce" field. It is called by the builders before save.
NonceValidator func(string) error
// ClaimsUserIDValidator is a validator for the "claims_user_id" field. It is called by the builders before save.
ClaimsUserIDValidator func(string) error
// ClaimsUsernameValidator is a validator for the "claims_username" field. It is called by the builders before save.
ClaimsUsernameValidator func(string) error
// ClaimsEmailValidator is a validator for the "claims_email" field. It is called by the builders before save.
ClaimsEmailValidator func(string) error
// DefaultClaimsPreferredUsername holds the default value on creation for the "claims_preferred_username" field.
DefaultClaimsPreferredUsername string
// ConnectorIDValidator is a validator for the "connector_id" field. It is called by the builders before save.
ConnectorIDValidator func(string) error
// DefaultToken holds the default value on creation for the "token" field.
DefaultToken string
// DefaultObsoleteToken holds the default value on creation for the "obsolete_token" field.
DefaultObsoleteToken string
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// DefaultLastUsed holds the default value on creation for the "last_used" field.
DefaultLastUsed func() time.Time
// IDValidator is a validator for the "id" field. It is called by the builders before save.
IDValidator func(string) error
)

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,521 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/refreshtoken"
)
// RefreshTokenCreate is the builder for creating a RefreshToken entity.
type RefreshTokenCreate struct {
config
mutation *RefreshTokenMutation
hooks []Hook
}
// SetClientID sets the "client_id" field.
func (rtc *RefreshTokenCreate) SetClientID(s string) *RefreshTokenCreate {
rtc.mutation.SetClientID(s)
return rtc
}
// SetScopes sets the "scopes" field.
func (rtc *RefreshTokenCreate) SetScopes(s []string) *RefreshTokenCreate {
rtc.mutation.SetScopes(s)
return rtc
}
// SetNonce sets the "nonce" field.
func (rtc *RefreshTokenCreate) SetNonce(s string) *RefreshTokenCreate {
rtc.mutation.SetNonce(s)
return rtc
}
// SetClaimsUserID sets the "claims_user_id" field.
func (rtc *RefreshTokenCreate) SetClaimsUserID(s string) *RefreshTokenCreate {
rtc.mutation.SetClaimsUserID(s)
return rtc
}
// SetClaimsUsername sets the "claims_username" field.
func (rtc *RefreshTokenCreate) SetClaimsUsername(s string) *RefreshTokenCreate {
rtc.mutation.SetClaimsUsername(s)
return rtc
}
// SetClaimsEmail sets the "claims_email" field.
func (rtc *RefreshTokenCreate) SetClaimsEmail(s string) *RefreshTokenCreate {
rtc.mutation.SetClaimsEmail(s)
return rtc
}
// SetClaimsEmailVerified sets the "claims_email_verified" field.
func (rtc *RefreshTokenCreate) SetClaimsEmailVerified(b bool) *RefreshTokenCreate {
rtc.mutation.SetClaimsEmailVerified(b)
return rtc
}
// SetClaimsGroups sets the "claims_groups" field.
func (rtc *RefreshTokenCreate) SetClaimsGroups(s []string) *RefreshTokenCreate {
rtc.mutation.SetClaimsGroups(s)
return rtc
}
// SetClaimsPreferredUsername sets the "claims_preferred_username" field.
func (rtc *RefreshTokenCreate) SetClaimsPreferredUsername(s string) *RefreshTokenCreate {
rtc.mutation.SetClaimsPreferredUsername(s)
return rtc
}
// 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)
}
return rtc
}
// SetConnectorID sets the "connector_id" field.
func (rtc *RefreshTokenCreate) SetConnectorID(s string) *RefreshTokenCreate {
rtc.mutation.SetConnectorID(s)
return rtc
}
// SetConnectorData sets the "connector_data" field.
func (rtc *RefreshTokenCreate) SetConnectorData(b []byte) *RefreshTokenCreate {
rtc.mutation.SetConnectorData(b)
return rtc
}
// SetToken sets the "token" field.
func (rtc *RefreshTokenCreate) SetToken(s string) *RefreshTokenCreate {
rtc.mutation.SetToken(s)
return rtc
}
// 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)
}
return rtc
}
// SetObsoleteToken sets the "obsolete_token" field.
func (rtc *RefreshTokenCreate) SetObsoleteToken(s string) *RefreshTokenCreate {
rtc.mutation.SetObsoleteToken(s)
return rtc
}
// 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)
}
return rtc
}
// SetCreatedAt sets the "created_at" field.
func (rtc *RefreshTokenCreate) SetCreatedAt(t time.Time) *RefreshTokenCreate {
rtc.mutation.SetCreatedAt(t)
return rtc
}
// 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)
}
return rtc
}
// SetLastUsed sets the "last_used" field.
func (rtc *RefreshTokenCreate) SetLastUsed(t time.Time) *RefreshTokenCreate {
rtc.mutation.SetLastUsed(t)
return rtc
}
// 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)
}
return rtc
}
// SetID sets the "id" field.
func (rtc *RefreshTokenCreate) SetID(s string) *RefreshTokenCreate {
rtc.mutation.SetID(s)
return rtc
}
// Mutation returns the RefreshTokenMutation object of the builder.
func (rtc *RefreshTokenCreate) Mutation() *RefreshTokenMutation {
return rtc.mutation
}
// Save creates the RefreshToken in the database.
func (rtc *RefreshTokenCreate) Save(ctx context.Context) (*RefreshToken, error) {
var (
err error
node *RefreshToken
)
rtc.defaults()
if len(rtc.hooks) == 0 {
if err = rtc.check(); err != nil {
return nil, err
}
node, err = rtc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*RefreshTokenMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = rtc.check(); err != nil {
return nil, err
}
rtc.mutation = mutation
node, err = rtc.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(rtc.hooks) - 1; i >= 0; i-- {
mut = rtc.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, rtc.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (rtc *RefreshTokenCreate) SaveX(ctx context.Context) *RefreshToken {
v, err := rtc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// defaults sets the default values of the builder before save.
func (rtc *RefreshTokenCreate) defaults() {
if _, ok := rtc.mutation.ClaimsPreferredUsername(); !ok {
v := refreshtoken.DefaultClaimsPreferredUsername
rtc.mutation.SetClaimsPreferredUsername(v)
}
if _, ok := rtc.mutation.Token(); !ok {
v := refreshtoken.DefaultToken
rtc.mutation.SetToken(v)
}
if _, ok := rtc.mutation.ObsoleteToken(); !ok {
v := refreshtoken.DefaultObsoleteToken
rtc.mutation.SetObsoleteToken(v)
}
if _, ok := rtc.mutation.CreatedAt(); !ok {
v := refreshtoken.DefaultCreatedAt()
rtc.mutation.SetCreatedAt(v)
}
if _, ok := rtc.mutation.LastUsed(); !ok {
v := refreshtoken.DefaultLastUsed()
rtc.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 {
return &ValidationError{Name: "client_id", err: errors.New("db: missing required field \"client_id\"")}
}
if v, ok := rtc.mutation.ClientID(); ok {
if err := refreshtoken.ClientIDValidator(v); err != nil {
return &ValidationError{Name: "client_id", err: fmt.Errorf("db: validator failed for field \"client_id\": %w", err)}
}
}
if _, ok := rtc.mutation.Nonce(); !ok {
return &ValidationError{Name: "nonce", err: errors.New("db: missing required field \"nonce\"")}
}
if v, ok := rtc.mutation.Nonce(); ok {
if err := refreshtoken.NonceValidator(v); err != nil {
return &ValidationError{Name: "nonce", err: fmt.Errorf("db: validator failed for field \"nonce\": %w", err)}
}
}
if _, ok := rtc.mutation.ClaimsUserID(); !ok {
return &ValidationError{Name: "claims_user_id", err: errors.New("db: missing required field \"claims_user_id\"")}
}
if v, ok := rtc.mutation.ClaimsUserID(); ok {
if err := refreshtoken.ClaimsUserIDValidator(v); err != nil {
return &ValidationError{Name: "claims_user_id", err: fmt.Errorf("db: validator failed for field \"claims_user_id\": %w", err)}
}
}
if _, ok := rtc.mutation.ClaimsUsername(); !ok {
return &ValidationError{Name: "claims_username", err: errors.New("db: missing required field \"claims_username\"")}
}
if v, ok := rtc.mutation.ClaimsUsername(); ok {
if err := refreshtoken.ClaimsUsernameValidator(v); err != nil {
return &ValidationError{Name: "claims_username", err: fmt.Errorf("db: validator failed for field \"claims_username\": %w", err)}
}
}
if _, ok := rtc.mutation.ClaimsEmail(); !ok {
return &ValidationError{Name: "claims_email", err: errors.New("db: missing required field \"claims_email\"")}
}
if v, ok := rtc.mutation.ClaimsEmail(); ok {
if err := refreshtoken.ClaimsEmailValidator(v); err != nil {
return &ValidationError{Name: "claims_email", err: fmt.Errorf("db: validator failed for field \"claims_email\": %w", err)}
}
}
if _, ok := rtc.mutation.ClaimsEmailVerified(); !ok {
return &ValidationError{Name: "claims_email_verified", err: errors.New("db: missing required field \"claims_email_verified\"")}
}
if _, ok := rtc.mutation.ClaimsPreferredUsername(); !ok {
return &ValidationError{Name: "claims_preferred_username", err: errors.New("db: missing required field \"claims_preferred_username\"")}
}
if _, ok := rtc.mutation.ConnectorID(); !ok {
return &ValidationError{Name: "connector_id", err: errors.New("db: missing required field \"connector_id\"")}
}
if v, ok := rtc.mutation.ConnectorID(); ok {
if err := refreshtoken.ConnectorIDValidator(v); err != nil {
return &ValidationError{Name: "connector_id", err: fmt.Errorf("db: validator failed for field \"connector_id\": %w", err)}
}
}
if _, ok := rtc.mutation.Token(); !ok {
return &ValidationError{Name: "token", err: errors.New("db: missing required field \"token\"")}
}
if _, ok := rtc.mutation.ObsoleteToken(); !ok {
return &ValidationError{Name: "obsolete_token", err: errors.New("db: missing required field \"obsolete_token\"")}
}
if _, ok := rtc.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New("db: missing required field \"created_at\"")}
}
if _, ok := rtc.mutation.LastUsed(); !ok {
return &ValidationError{Name: "last_used", err: errors.New("db: missing required field \"last_used\"")}
}
if v, ok := rtc.mutation.ID(); ok {
if err := refreshtoken.IDValidator(v); err != nil {
return &ValidationError{Name: "id", err: fmt.Errorf("db: validator failed for field \"id\": %w", err)}
}
}
return nil
}
func (rtc *RefreshTokenCreate) sqlSave(ctx context.Context) (*RefreshToken, error) {
_node, _spec := rtc.createSpec()
if err := sqlgraph.CreateNode(ctx, rtc.driver, _spec); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return nil, err
}
return _node, nil
}
func (rtc *RefreshTokenCreate) createSpec() (*RefreshToken, *sqlgraph.CreateSpec) {
var (
_node = &RefreshToken{config: rtc.config}
_spec = &sqlgraph.CreateSpec{
Table: refreshtoken.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: refreshtoken.FieldID,
},
}
)
if id, ok := rtc.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = id
}
if value, ok := rtc.mutation.ClientID(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: refreshtoken.FieldClientID,
})
_node.ClientID = value
}
if value, ok := rtc.mutation.Scopes(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: refreshtoken.FieldScopes,
})
_node.Scopes = value
}
if value, ok := rtc.mutation.Nonce(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: refreshtoken.FieldNonce,
})
_node.Nonce = value
}
if value, ok := rtc.mutation.ClaimsUserID(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: refreshtoken.FieldClaimsUserID,
})
_node.ClaimsUserID = value
}
if value, ok := rtc.mutation.ClaimsUsername(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: refreshtoken.FieldClaimsUsername,
})
_node.ClaimsUsername = value
}
if value, ok := rtc.mutation.ClaimsEmail(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: refreshtoken.FieldClaimsEmail,
})
_node.ClaimsEmail = value
}
if value, ok := rtc.mutation.ClaimsEmailVerified(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: refreshtoken.FieldClaimsEmailVerified,
})
_node.ClaimsEmailVerified = value
}
if value, ok := rtc.mutation.ClaimsGroups(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: refreshtoken.FieldClaimsGroups,
})
_node.ClaimsGroups = value
}
if value, ok := rtc.mutation.ClaimsPreferredUsername(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: refreshtoken.FieldClaimsPreferredUsername,
})
_node.ClaimsPreferredUsername = value
}
if value, ok := rtc.mutation.ConnectorID(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: refreshtoken.FieldConnectorID,
})
_node.ConnectorID = value
}
if value, ok := rtc.mutation.ConnectorData(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: refreshtoken.FieldConnectorData,
})
_node.ConnectorData = &value
}
if value, ok := rtc.mutation.Token(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: refreshtoken.FieldToken,
})
_node.Token = value
}
if value, ok := rtc.mutation.ObsoleteToken(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: refreshtoken.FieldObsoleteToken,
})
_node.ObsoleteToken = value
}
if value, ok := rtc.mutation.CreatedAt(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: refreshtoken.FieldCreatedAt,
})
_node.CreatedAt = value
}
if value, ok := rtc.mutation.LastUsed(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: refreshtoken.FieldLastUsed,
})
_node.LastUsed = value
}
return _node, _spec
}
// RefreshTokenCreateBulk is the builder for creating many RefreshToken entities in bulk.
type RefreshTokenCreateBulk struct {
config
builders []*RefreshTokenCreate
}
// Save creates the RefreshToken entities in the database.
func (rtcb *RefreshTokenCreateBulk) Save(ctx context.Context) ([]*RefreshToken, error) {
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(i int, root context.Context) {
builder := rtcb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*RefreshTokenMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
nodes[i], specs[i] = builder.createSpec()
var err error
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, rtcb.builders[i+1].mutation)
} else {
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, rtcb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil {
if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
}
}
mutation.done = true
if err != nil {
return nil, err
}
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, rtcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (rtcb *RefreshTokenCreateBulk) SaveX(ctx context.Context) []*RefreshToken {
v, err := rtcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}

View file

@ -0,0 +1,108 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/predicate"
"github.com/dexidp/dex/storage/ent/db/refreshtoken"
)
// RefreshTokenDelete is the builder for deleting a RefreshToken entity.
type RefreshTokenDelete struct {
config
hooks []Hook
mutation *RefreshTokenMutation
}
// Where adds a new predicate to the RefreshTokenDelete builder.
func (rtd *RefreshTokenDelete) Where(ps ...predicate.RefreshToken) *RefreshTokenDelete {
rtd.mutation.predicates = append(rtd.mutation.predicates, ps...)
return rtd
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (rtd *RefreshTokenDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(rtd.hooks) == 0 {
affected, err = rtd.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*RefreshTokenMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
rtd.mutation = mutation
affected, err = rtd.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(rtd.hooks) - 1; i >= 0; i-- {
mut = rtd.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, rtd.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (rtd *RefreshTokenDelete) ExecX(ctx context.Context) int {
n, err := rtd.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (rtd *RefreshTokenDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: refreshtoken.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: refreshtoken.FieldID,
},
},
}
if ps := rtd.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return sqlgraph.DeleteNodes(ctx, rtd.driver, _spec)
}
// RefreshTokenDeleteOne is the builder for deleting a single RefreshToken entity.
type RefreshTokenDeleteOne struct {
rtd *RefreshTokenDelete
}
// Exec executes the deletion query.
func (rtdo *RefreshTokenDeleteOne) Exec(ctx context.Context) error {
n, err := rtdo.rtd.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{refreshtoken.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (rtdo *RefreshTokenDeleteOne) ExecX(ctx context.Context) {
rtdo.rtd.ExecX(ctx)
}

View file

@ -0,0 +1,906 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"errors"
"fmt"
"math"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/predicate"
"github.com/dexidp/dex/storage/ent/db/refreshtoken"
)
// RefreshTokenQuery is the builder for querying RefreshToken entities.
type RefreshTokenQuery struct {
config
limit *int
offset *int
unique *bool
order []OrderFunc
fields []string
predicates []predicate.RefreshToken
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// 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
}
// Limit adds a limit step to the query.
func (rtq *RefreshTokenQuery) Limit(limit int) *RefreshTokenQuery {
rtq.limit = &limit
return rtq
}
// Offset adds an offset step to the query.
func (rtq *RefreshTokenQuery) Offset(offset int) *RefreshTokenQuery {
rtq.offset = &offset
return rtq
}
// 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.unique = &unique
return rtq
}
// Order adds an order step to the query.
func (rtq *RefreshTokenQuery) Order(o ...OrderFunc) *RefreshTokenQuery {
rtq.order = append(rtq.order, o...)
return rtq
}
// 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(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{refreshtoken.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (rtq *RefreshTokenQuery) FirstX(ctx context.Context) *RefreshToken {
node, err := rtq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// 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) {
var ids []string
if ids, err = rtq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{refreshtoken.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (rtq *RefreshTokenQuery) FirstIDX(ctx context.Context) string {
id, err := rtq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single RefreshToken entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when exactly one RefreshToken entity is not 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(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{refreshtoken.Label}
default:
return nil, &NotSingularError{refreshtoken.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (rtq *RefreshTokenQuery) OnlyX(ctx context.Context) *RefreshToken {
node, err := rtq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only RefreshToken ID in the query.
// Returns a *NotSingularError when exactly one RefreshToken ID is not found.
// Returns a *NotFoundError when no entities are found.
func (rtq *RefreshTokenQuery) OnlyID(ctx context.Context) (id string, err error) {
var ids []string
if ids, err = rtq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{refreshtoken.Label}
default:
err = &NotSingularError{refreshtoken.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (rtq *RefreshTokenQuery) OnlyIDX(ctx context.Context) string {
id, err := rtq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of RefreshTokens.
func (rtq *RefreshTokenQuery) All(ctx context.Context) ([]*RefreshToken, error) {
if err := rtq.prepareQuery(ctx); err != nil {
return nil, err
}
return rtq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (rtq *RefreshTokenQuery) AllX(ctx context.Context) []*RefreshToken {
nodes, err := rtq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of RefreshToken IDs.
func (rtq *RefreshTokenQuery) IDs(ctx context.Context) ([]string, error) {
var ids []string
if err := rtq.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)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (rtq *RefreshTokenQuery) Count(ctx context.Context) (int, error) {
if err := rtq.prepareQuery(ctx); err != nil {
return 0, err
}
return rtq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (rtq *RefreshTokenQuery) CountX(ctx context.Context) int {
count, err := rtq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (rtq *RefreshTokenQuery) Exist(ctx context.Context) (bool, error) {
if err := rtq.prepareQuery(ctx); err != nil {
return false, err
}
return rtq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (rtq *RefreshTokenQuery) ExistX(ctx context.Context) bool {
exist, err := rtq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// 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 {
return nil
}
return &RefreshTokenQuery{
config: rtq.config,
limit: rtq.limit,
offset: rtq.offset,
order: append([]OrderFunc{}, rtq.order...),
predicates: append([]predicate.RefreshToken{}, rtq.predicates...),
// clone intermediate query.
sql: rtq.sql.Clone(),
path: rtq.path,
}
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// ClientID string `json:"client_id,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.RefreshToken.Query().
// GroupBy(refreshtoken.FieldClientID).
// Aggregate(db.Count()).
// Scan(ctx, &v)
//
func (rtq *RefreshTokenQuery) GroupBy(field string, fields ...string) *RefreshTokenGroupBy {
group := &RefreshTokenGroupBy{config: rtq.config}
group.fields = append([]string{field}, fields...)
group.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := rtq.prepareQuery(ctx); err != nil {
return nil, err
}
return rtq.sqlQuery(ctx), nil
}
return group
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// ClientID string `json:"client_id,omitempty"`
// }
//
// client.RefreshToken.Query().
// Select(refreshtoken.FieldClientID).
// Scan(ctx, &v)
//
func (rtq *RefreshTokenQuery) Select(field string, fields ...string) *RefreshTokenSelect {
rtq.fields = append([]string{field}, fields...)
return &RefreshTokenSelect{RefreshTokenQuery: rtq}
}
func (rtq *RefreshTokenQuery) prepareQuery(ctx context.Context) error {
for _, f := range rtq.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 err != nil {
return err
}
rtq.sql = prev
}
return nil
}
func (rtq *RefreshTokenQuery) sqlAll(ctx context.Context) ([]*RefreshToken, error) {
var (
nodes = []*RefreshToken{}
_spec = rtq.querySpec()
)
_spec.ScanValues = func(columns []string) ([]interface{}, error) {
node := &RefreshToken{config: rtq.config}
nodes = append(nodes, node)
return node.scanValues(columns)
}
_spec.Assign = func(columns []string, values []interface{}) error {
if len(nodes) == 0 {
return fmt.Errorf("db: Assign called without calling ScanValues")
}
node := nodes[len(nodes)-1]
return node.assignValues(columns, values)
}
if err := sqlgraph.QueryNodes(ctx, rtq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (rtq *RefreshTokenQuery) sqlCount(ctx context.Context) (int, error) {
_spec := rtq.querySpec()
return sqlgraph.CountNodes(ctx, rtq.driver, _spec)
}
func (rtq *RefreshTokenQuery) sqlExist(ctx context.Context) (bool, error) {
n, err := rtq.sqlCount(ctx)
if err != nil {
return false, fmt.Errorf("db: check existence: %w", err)
}
return n > 0, nil
}
func (rtq *RefreshTokenQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: refreshtoken.Table,
Columns: refreshtoken.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: refreshtoken.FieldID,
},
},
From: rtq.sql,
Unique: true,
}
if unique := rtq.unique; unique != nil {
_spec.Unique = *unique
}
if fields := rtq.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 {
if fields[i] != refreshtoken.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := rtq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := rtq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := rtq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := rtq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (rtq *RefreshTokenQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(rtq.driver.Dialect())
t1 := builder.Table(refreshtoken.Table)
selector := builder.Select(t1.Columns(refreshtoken.Columns...)...).From(t1)
if rtq.sql != nil {
selector = rtq.sql
selector.Select(selector.Columns(refreshtoken.Columns...)...)
}
for _, p := range rtq.predicates {
p(selector)
}
for _, p := range rtq.order {
p(selector)
}
if offset := rtq.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.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// RefreshTokenGroupBy is the group-by builder for RefreshToken entities.
type RefreshTokenGroupBy struct {
config
fields []string
fns []AggregateFunc
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Aggregate adds the given aggregation functions to the group-by query.
func (rtgb *RefreshTokenGroupBy) Aggregate(fns ...AggregateFunc) *RefreshTokenGroupBy {
rtgb.fns = append(rtgb.fns, fns...)
return rtgb
}
// Scan applies the group-by query and scans the result into the given value.
func (rtgb *RefreshTokenGroupBy) Scan(ctx context.Context, v interface{}) error {
query, err := rtgb.path(ctx)
if err != nil {
return err
}
rtgb.sql = query
return rtgb.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (rtgb *RefreshTokenGroupBy) ScanX(ctx context.Context, v interface{}) {
if err := rtgb.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from group-by.
// It is only allowed when executing a group-by query with one field.
func (rtgb *RefreshTokenGroupBy) Strings(ctx context.Context) ([]string, error) {
if len(rtgb.fields) > 1 {
return nil, errors.New("db: RefreshTokenGroupBy.Strings is not achievable when grouping more than 1 field")
}
var v []string
if err := rtgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (rtgb *RefreshTokenGroupBy) StringsX(ctx context.Context) []string {
v, err := rtgb.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (rtgb *RefreshTokenGroupBy) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = rtgb.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{refreshtoken.Label}
default:
err = fmt.Errorf("db: RefreshTokenGroupBy.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (rtgb *RefreshTokenGroupBy) StringX(ctx context.Context) string {
v, err := rtgb.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from group-by.
// It is only allowed when executing a group-by query with one field.
func (rtgb *RefreshTokenGroupBy) Ints(ctx context.Context) ([]int, error) {
if len(rtgb.fields) > 1 {
return nil, errors.New("db: RefreshTokenGroupBy.Ints is not achievable when grouping more than 1 field")
}
var v []int
if err := rtgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (rtgb *RefreshTokenGroupBy) IntsX(ctx context.Context) []int {
v, err := rtgb.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (rtgb *RefreshTokenGroupBy) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = rtgb.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{refreshtoken.Label}
default:
err = fmt.Errorf("db: RefreshTokenGroupBy.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (rtgb *RefreshTokenGroupBy) IntX(ctx context.Context) int {
v, err := rtgb.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from group-by.
// It is only allowed when executing a group-by query with one field.
func (rtgb *RefreshTokenGroupBy) Float64s(ctx context.Context) ([]float64, error) {
if len(rtgb.fields) > 1 {
return nil, errors.New("db: RefreshTokenGroupBy.Float64s is not achievable when grouping more than 1 field")
}
var v []float64
if err := rtgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (rtgb *RefreshTokenGroupBy) Float64sX(ctx context.Context) []float64 {
v, err := rtgb.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (rtgb *RefreshTokenGroupBy) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = rtgb.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{refreshtoken.Label}
default:
err = fmt.Errorf("db: RefreshTokenGroupBy.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (rtgb *RefreshTokenGroupBy) Float64X(ctx context.Context) float64 {
v, err := rtgb.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from group-by.
// It is only allowed when executing a group-by query with one field.
func (rtgb *RefreshTokenGroupBy) Bools(ctx context.Context) ([]bool, error) {
if len(rtgb.fields) > 1 {
return nil, errors.New("db: RefreshTokenGroupBy.Bools is not achievable when grouping more than 1 field")
}
var v []bool
if err := rtgb.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (rtgb *RefreshTokenGroupBy) BoolsX(ctx context.Context) []bool {
v, err := rtgb.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a group-by query.
// It is only allowed when executing a group-by query with one field.
func (rtgb *RefreshTokenGroupBy) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = rtgb.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{refreshtoken.Label}
default:
err = fmt.Errorf("db: RefreshTokenGroupBy.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (rtgb *RefreshTokenGroupBy) BoolX(ctx context.Context) bool {
v, err := rtgb.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
func (rtgb *RefreshTokenGroupBy) sqlScan(ctx context.Context, v interface{}) error {
for _, f := range rtgb.fields {
if !refreshtoken.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := rtgb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := rtgb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (rtgb *RefreshTokenGroupBy) sqlQuery() *sql.Selector {
selector := rtgb.sql
columns := make([]string, 0, len(rtgb.fields)+len(rtgb.fns))
columns = append(columns, rtgb.fields...)
for _, fn := range rtgb.fns {
columns = append(columns, fn(selector))
}
return selector.Select(columns...).GroupBy(rtgb.fields...)
}
// RefreshTokenSelect is the builder for selecting fields of RefreshToken entities.
type RefreshTokenSelect struct {
*RefreshTokenQuery
// intermediate query (i.e. traversal path).
sql *sql.Selector
}
// Scan applies the selector query and scans the result into the given value.
func (rts *RefreshTokenSelect) Scan(ctx context.Context, v interface{}) error {
if err := rts.prepareQuery(ctx); err != nil {
return err
}
rts.sql = rts.RefreshTokenQuery.sqlQuery(ctx)
return rts.sqlScan(ctx, v)
}
// ScanX is like Scan, but panics if an error occurs.
func (rts *RefreshTokenSelect) ScanX(ctx context.Context, v interface{}) {
if err := rts.Scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from a selector. It is only allowed when selecting one field.
func (rts *RefreshTokenSelect) Strings(ctx context.Context) ([]string, error) {
if len(rts.fields) > 1 {
return nil, errors.New("db: RefreshTokenSelect.Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := rts.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (rts *RefreshTokenSelect) StringsX(ctx context.Context) []string {
v, err := rts.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a selector. It is only allowed when selecting one field.
func (rts *RefreshTokenSelect) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = rts.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{refreshtoken.Label}
default:
err = fmt.Errorf("db: RefreshTokenSelect.Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (rts *RefreshTokenSelect) StringX(ctx context.Context) string {
v, err := rts.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from a selector. It is only allowed when selecting one field.
func (rts *RefreshTokenSelect) Ints(ctx context.Context) ([]int, error) {
if len(rts.fields) > 1 {
return nil, errors.New("db: RefreshTokenSelect.Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := rts.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (rts *RefreshTokenSelect) IntsX(ctx context.Context) []int {
v, err := rts.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a selector. It is only allowed when selecting one field.
func (rts *RefreshTokenSelect) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = rts.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{refreshtoken.Label}
default:
err = fmt.Errorf("db: RefreshTokenSelect.Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (rts *RefreshTokenSelect) IntX(ctx context.Context) int {
v, err := rts.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
func (rts *RefreshTokenSelect) Float64s(ctx context.Context) ([]float64, error) {
if len(rts.fields) > 1 {
return nil, errors.New("db: RefreshTokenSelect.Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := rts.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (rts *RefreshTokenSelect) Float64sX(ctx context.Context) []float64 {
v, err := rts.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
func (rts *RefreshTokenSelect) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = rts.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{refreshtoken.Label}
default:
err = fmt.Errorf("db: RefreshTokenSelect.Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (rts *RefreshTokenSelect) Float64X(ctx context.Context) float64 {
v, err := rts.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from a selector. It is only allowed when selecting one field.
func (rts *RefreshTokenSelect) Bools(ctx context.Context) ([]bool, error) {
if len(rts.fields) > 1 {
return nil, errors.New("db: RefreshTokenSelect.Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := rts.Scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (rts *RefreshTokenSelect) BoolsX(ctx context.Context) []bool {
v, err := rts.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a selector. It is only allowed when selecting one field.
func (rts *RefreshTokenSelect) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = rts.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{refreshtoken.Label}
default:
err = fmt.Errorf("db: RefreshTokenSelect.Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (rts *RefreshTokenSelect) BoolX(ctx context.Context) bool {
v, err := rts.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
func (rts *RefreshTokenSelect) sqlScan(ctx context.Context, v interface{}) error {
rows := &sql.Rows{}
query, args := rts.sqlQuery().Query()
if err := rts.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (rts *RefreshTokenSelect) sqlQuery() sql.Querier {
selector := rts.sql
selector.Select(selector.Columns(rts.fields...)...)
return selector
}

View file

@ -0,0 +1,857 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"fmt"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/dexidp/dex/storage/ent/db/predicate"
"github.com/dexidp/dex/storage/ent/db/refreshtoken"
)
// RefreshTokenUpdate is the builder for updating RefreshToken entities.
type RefreshTokenUpdate struct {
config
hooks []Hook
mutation *RefreshTokenMutation
}
// Where adds a new predicate for the RefreshTokenUpdate builder.
func (rtu *RefreshTokenUpdate) Where(ps ...predicate.RefreshToken) *RefreshTokenUpdate {
rtu.mutation.predicates = append(rtu.mutation.predicates, ps...)
return rtu
}
// SetClientID sets the "client_id" field.
func (rtu *RefreshTokenUpdate) SetClientID(s string) *RefreshTokenUpdate {
rtu.mutation.SetClientID(s)
return rtu
}
// SetScopes sets the "scopes" field.
func (rtu *RefreshTokenUpdate) SetScopes(s []string) *RefreshTokenUpdate {
rtu.mutation.SetScopes(s)
return rtu
}
// ClearScopes clears the value of the "scopes" field.
func (rtu *RefreshTokenUpdate) ClearScopes() *RefreshTokenUpdate {
rtu.mutation.ClearScopes()
return rtu
}
// SetNonce sets the "nonce" field.
func (rtu *RefreshTokenUpdate) SetNonce(s string) *RefreshTokenUpdate {
rtu.mutation.SetNonce(s)
return rtu
}
// SetClaimsUserID sets the "claims_user_id" field.
func (rtu *RefreshTokenUpdate) SetClaimsUserID(s string) *RefreshTokenUpdate {
rtu.mutation.SetClaimsUserID(s)
return rtu
}
// SetClaimsUsername sets the "claims_username" field.
func (rtu *RefreshTokenUpdate) SetClaimsUsername(s string) *RefreshTokenUpdate {
rtu.mutation.SetClaimsUsername(s)
return rtu
}
// SetClaimsEmail sets the "claims_email" field.
func (rtu *RefreshTokenUpdate) SetClaimsEmail(s string) *RefreshTokenUpdate {
rtu.mutation.SetClaimsEmail(s)
return rtu
}
// SetClaimsEmailVerified sets the "claims_email_verified" field.
func (rtu *RefreshTokenUpdate) SetClaimsEmailVerified(b bool) *RefreshTokenUpdate {
rtu.mutation.SetClaimsEmailVerified(b)
return rtu
}
// SetClaimsGroups sets the "claims_groups" field.
func (rtu *RefreshTokenUpdate) SetClaimsGroups(s []string) *RefreshTokenUpdate {
rtu.mutation.SetClaimsGroups(s)
return rtu
}
// ClearClaimsGroups clears the value of the "claims_groups" field.
func (rtu *RefreshTokenUpdate) ClearClaimsGroups() *RefreshTokenUpdate {
rtu.mutation.ClearClaimsGroups()
return rtu
}
// SetClaimsPreferredUsername sets the "claims_preferred_username" field.
func (rtu *RefreshTokenUpdate) SetClaimsPreferredUsername(s string) *RefreshTokenUpdate {
rtu.mutation.SetClaimsPreferredUsername(s)
return rtu
}
// 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)
}
return rtu
}
// SetConnectorID sets the "connector_id" field.
func (rtu *RefreshTokenUpdate) SetConnectorID(s string) *RefreshTokenUpdate {
rtu.mutation.SetConnectorID(s)
return rtu
}
// SetConnectorData sets the "connector_data" field.
func (rtu *RefreshTokenUpdate) SetConnectorData(b []byte) *RefreshTokenUpdate {
rtu.mutation.SetConnectorData(b)
return rtu
}
// ClearConnectorData clears the value of the "connector_data" field.
func (rtu *RefreshTokenUpdate) ClearConnectorData() *RefreshTokenUpdate {
rtu.mutation.ClearConnectorData()
return rtu
}
// SetToken sets the "token" field.
func (rtu *RefreshTokenUpdate) SetToken(s string) *RefreshTokenUpdate {
rtu.mutation.SetToken(s)
return rtu
}
// 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)
}
return rtu
}
// SetObsoleteToken sets the "obsolete_token" field.
func (rtu *RefreshTokenUpdate) SetObsoleteToken(s string) *RefreshTokenUpdate {
rtu.mutation.SetObsoleteToken(s)
return rtu
}
// 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)
}
return rtu
}
// SetCreatedAt sets the "created_at" field.
func (rtu *RefreshTokenUpdate) SetCreatedAt(t time.Time) *RefreshTokenUpdate {
rtu.mutation.SetCreatedAt(t)
return rtu
}
// 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)
}
return rtu
}
// SetLastUsed sets the "last_used" field.
func (rtu *RefreshTokenUpdate) SetLastUsed(t time.Time) *RefreshTokenUpdate {
rtu.mutation.SetLastUsed(t)
return rtu
}
// 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)
}
return rtu
}
// Mutation returns the RefreshTokenMutation object of the builder.
func (rtu *RefreshTokenUpdate) Mutation() *RefreshTokenMutation {
return rtu.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) {
var (
err error
affected int
)
if len(rtu.hooks) == 0 {
if err = rtu.check(); err != nil {
return 0, err
}
affected, err = rtu.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*RefreshTokenMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = rtu.check(); err != nil {
return 0, err
}
rtu.mutation = mutation
affected, err = rtu.sqlSave(ctx)
mutation.done = true
return affected, err
})
for i := len(rtu.hooks) - 1; i >= 0; i-- {
mut = rtu.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, rtu.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// SaveX is like Save, but panics if an error occurs.
func (rtu *RefreshTokenUpdate) SaveX(ctx context.Context) int {
affected, err := rtu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (rtu *RefreshTokenUpdate) Exec(ctx context.Context) error {
_, err := rtu.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 {
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 {
if err := refreshtoken.ClientIDValidator(v); err != nil {
return &ValidationError{Name: "client_id", err: fmt.Errorf("db: validator failed for field \"client_id\": %w", err)}
}
}
if v, ok := rtu.mutation.Nonce(); ok {
if err := refreshtoken.NonceValidator(v); err != nil {
return &ValidationError{Name: "nonce", err: fmt.Errorf("db: validator failed for field \"nonce\": %w", err)}
}
}
if v, ok := rtu.mutation.ClaimsUserID(); ok {
if err := refreshtoken.ClaimsUserIDValidator(v); err != nil {
return &ValidationError{Name: "claims_user_id", err: fmt.Errorf("db: validator failed for field \"claims_user_id\": %w", err)}
}
}
if v, ok := rtu.mutation.ClaimsUsername(); ok {
if err := refreshtoken.ClaimsUsernameValidator(v); err != nil {
return &ValidationError{Name: "claims_username", err: fmt.Errorf("db: validator failed for field \"claims_username\": %w", err)}
}
}
if v, ok := rtu.mutation.ClaimsEmail(); ok {
if err := refreshtoken.ClaimsEmailValidator(v); err != nil {
return &ValidationError{Name: "claims_email", err: fmt.Errorf("db: validator failed for field \"claims_email\": %w", err)}
}
}
if v, ok := rtu.mutation.ConnectorID(); ok {
if err := refreshtoken.ConnectorIDValidator(v); err != nil {
return &ValidationError{Name: "connector_id", err: fmt.Errorf("db: validator failed for field \"connector_id\": %w", err)}
}
}
return nil
}
func (rtu *RefreshTokenUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: refreshtoken.Table,
Columns: refreshtoken.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: refreshtoken.FieldID,
},
},
}
if ps := rtu.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 {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: refreshtoken.FieldClientID,
})
}
if value, ok := rtu.mutation.Scopes(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: refreshtoken.FieldScopes,
})
}
if rtu.mutation.ScopesCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Column: refreshtoken.FieldScopes,
})
}
if value, ok := rtu.mutation.Nonce(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: refreshtoken.FieldNonce,
})
}
if value, ok := rtu.mutation.ClaimsUserID(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: refreshtoken.FieldClaimsUserID,
})
}
if value, ok := rtu.mutation.ClaimsUsername(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: refreshtoken.FieldClaimsUsername,
})
}
if value, ok := rtu.mutation.ClaimsEmail(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: refreshtoken.FieldClaimsEmail,
})
}
if value, ok := rtu.mutation.ClaimsEmailVerified(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: refreshtoken.FieldClaimsEmailVerified,
})
}
if value, ok := rtu.mutation.ClaimsGroups(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: refreshtoken.FieldClaimsGroups,
})
}
if rtu.mutation.ClaimsGroupsCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Column: refreshtoken.FieldClaimsGroups,
})
}
if value, ok := rtu.mutation.ClaimsPreferredUsername(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: refreshtoken.FieldClaimsPreferredUsername,
})
}
if value, ok := rtu.mutation.ConnectorID(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: refreshtoken.FieldConnectorID,
})
}
if value, ok := rtu.mutation.ConnectorData(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: refreshtoken.FieldConnectorData,
})
}
if rtu.mutation.ConnectorDataCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Column: refreshtoken.FieldConnectorData,
})
}
if value, ok := rtu.mutation.Token(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: refreshtoken.FieldToken,
})
}
if value, ok := rtu.mutation.ObsoleteToken(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: refreshtoken.FieldObsoleteToken,
})
}
if value, ok := rtu.mutation.CreatedAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: refreshtoken.FieldCreatedAt,
})
}
if value, ok := rtu.mutation.LastUsed(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: refreshtoken.FieldLastUsed,
})
}
if n, err = sqlgraph.UpdateNodes(ctx, rtu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{refreshtoken.Label}
} else if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return 0, err
}
return n, nil
}
// RefreshTokenUpdateOne is the builder for updating a single RefreshToken entity.
type RefreshTokenUpdateOne struct {
config
fields []string
hooks []Hook
mutation *RefreshTokenMutation
}
// SetClientID sets the "client_id" field.
func (rtuo *RefreshTokenUpdateOne) SetClientID(s string) *RefreshTokenUpdateOne {
rtuo.mutation.SetClientID(s)
return rtuo
}
// SetScopes sets the "scopes" field.
func (rtuo *RefreshTokenUpdateOne) SetScopes(s []string) *RefreshTokenUpdateOne {
rtuo.mutation.SetScopes(s)
return rtuo
}
// ClearScopes clears the value of the "scopes" field.
func (rtuo *RefreshTokenUpdateOne) ClearScopes() *RefreshTokenUpdateOne {
rtuo.mutation.ClearScopes()
return rtuo
}
// SetNonce sets the "nonce" field.
func (rtuo *RefreshTokenUpdateOne) SetNonce(s string) *RefreshTokenUpdateOne {
rtuo.mutation.SetNonce(s)
return rtuo
}
// SetClaimsUserID sets the "claims_user_id" field.
func (rtuo *RefreshTokenUpdateOne) SetClaimsUserID(s string) *RefreshTokenUpdateOne {
rtuo.mutation.SetClaimsUserID(s)
return rtuo
}
// SetClaimsUsername sets the "claims_username" field.
func (rtuo *RefreshTokenUpdateOne) SetClaimsUsername(s string) *RefreshTokenUpdateOne {
rtuo.mutation.SetClaimsUsername(s)
return rtuo
}
// SetClaimsEmail sets the "claims_email" field.
func (rtuo *RefreshTokenUpdateOne) SetClaimsEmail(s string) *RefreshTokenUpdateOne {
rtuo.mutation.SetClaimsEmail(s)
return rtuo
}
// SetClaimsEmailVerified sets the "claims_email_verified" field.
func (rtuo *RefreshTokenUpdateOne) SetClaimsEmailVerified(b bool) *RefreshTokenUpdateOne {
rtuo.mutation.SetClaimsEmailVerified(b)
return rtuo
}
// SetClaimsGroups sets the "claims_groups" field.
func (rtuo *RefreshTokenUpdateOne) SetClaimsGroups(s []string) *RefreshTokenUpdateOne {
rtuo.mutation.SetClaimsGroups(s)
return rtuo
}
// ClearClaimsGroups clears the value of the "claims_groups" field.
func (rtuo *RefreshTokenUpdateOne) ClearClaimsGroups() *RefreshTokenUpdateOne {
rtuo.mutation.ClearClaimsGroups()
return rtuo
}
// SetClaimsPreferredUsername sets the "claims_preferred_username" field.
func (rtuo *RefreshTokenUpdateOne) SetClaimsPreferredUsername(s string) *RefreshTokenUpdateOne {
rtuo.mutation.SetClaimsPreferredUsername(s)
return rtuo
}
// 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)
}
return rtuo
}
// SetConnectorID sets the "connector_id" field.
func (rtuo *RefreshTokenUpdateOne) SetConnectorID(s string) *RefreshTokenUpdateOne {
rtuo.mutation.SetConnectorID(s)
return rtuo
}
// SetConnectorData sets the "connector_data" field.
func (rtuo *RefreshTokenUpdateOne) SetConnectorData(b []byte) *RefreshTokenUpdateOne {
rtuo.mutation.SetConnectorData(b)
return rtuo
}
// ClearConnectorData clears the value of the "connector_data" field.
func (rtuo *RefreshTokenUpdateOne) ClearConnectorData() *RefreshTokenUpdateOne {
rtuo.mutation.ClearConnectorData()
return rtuo
}
// SetToken sets the "token" field.
func (rtuo *RefreshTokenUpdateOne) SetToken(s string) *RefreshTokenUpdateOne {
rtuo.mutation.SetToken(s)
return rtuo
}
// 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)
}
return rtuo
}
// SetObsoleteToken sets the "obsolete_token" field.
func (rtuo *RefreshTokenUpdateOne) SetObsoleteToken(s string) *RefreshTokenUpdateOne {
rtuo.mutation.SetObsoleteToken(s)
return rtuo
}
// 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)
}
return rtuo
}
// SetCreatedAt sets the "created_at" field.
func (rtuo *RefreshTokenUpdateOne) SetCreatedAt(t time.Time) *RefreshTokenUpdateOne {
rtuo.mutation.SetCreatedAt(t)
return rtuo
}
// 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)
}
return rtuo
}
// SetLastUsed sets the "last_used" field.
func (rtuo *RefreshTokenUpdateOne) SetLastUsed(t time.Time) *RefreshTokenUpdateOne {
rtuo.mutation.SetLastUsed(t)
return rtuo
}
// 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)
}
return rtuo
}
// Mutation returns the RefreshTokenMutation object of the builder.
func (rtuo *RefreshTokenUpdateOne) Mutation() *RefreshTokenMutation {
return rtuo.mutation
}
// 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
}
// Save executes the query and returns the updated RefreshToken entity.
func (rtuo *RefreshTokenUpdateOne) Save(ctx context.Context) (*RefreshToken, error) {
var (
err error
node *RefreshToken
)
if len(rtuo.hooks) == 0 {
if err = rtuo.check(); err != nil {
return nil, err
}
node, err = rtuo.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*RefreshTokenMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = rtuo.check(); err != nil {
return nil, err
}
rtuo.mutation = mutation
node, err = rtuo.sqlSave(ctx)
mutation.done = true
return node, err
})
for i := len(rtuo.hooks) - 1; i >= 0; i-- {
mut = rtuo.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, rtuo.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX is like Save, but panics if an error occurs.
func (rtuo *RefreshTokenUpdateOne) SaveX(ctx context.Context) *RefreshToken {
node, err := rtuo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (rtuo *RefreshTokenUpdateOne) Exec(ctx context.Context) error {
_, err := rtuo.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 {
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 {
if err := refreshtoken.ClientIDValidator(v); err != nil {
return &ValidationError{Name: "client_id", err: fmt.Errorf("db: validator failed for field \"client_id\": %w", err)}
}
}
if v, ok := rtuo.mutation.Nonce(); ok {
if err := refreshtoken.NonceValidator(v); err != nil {
return &ValidationError{Name: "nonce", err: fmt.Errorf("db: validator failed for field \"nonce\": %w", err)}
}
}
if v, ok := rtuo.mutation.ClaimsUserID(); ok {
if err := refreshtoken.ClaimsUserIDValidator(v); err != nil {
return &ValidationError{Name: "claims_user_id", err: fmt.Errorf("db: validator failed for field \"claims_user_id\": %w", err)}
}
}
if v, ok := rtuo.mutation.ClaimsUsername(); ok {
if err := refreshtoken.ClaimsUsernameValidator(v); err != nil {
return &ValidationError{Name: "claims_username", err: fmt.Errorf("db: validator failed for field \"claims_username\": %w", err)}
}
}
if v, ok := rtuo.mutation.ClaimsEmail(); ok {
if err := refreshtoken.ClaimsEmailValidator(v); err != nil {
return &ValidationError{Name: "claims_email", err: fmt.Errorf("db: validator failed for field \"claims_email\": %w", err)}
}
}
if v, ok := rtuo.mutation.ConnectorID(); ok {
if err := refreshtoken.ConnectorIDValidator(v); err != nil {
return &ValidationError{Name: "connector_id", err: fmt.Errorf("db: validator failed for field \"connector_id\": %w", err)}
}
}
return nil
}
func (rtuo *RefreshTokenUpdateOne) sqlSave(ctx context.Context) (_node *RefreshToken, err error) {
_spec := &sqlgraph.UpdateSpec{
Node: &sqlgraph.NodeSpec{
Table: refreshtoken.Table,
Columns: refreshtoken.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeString,
Column: refreshtoken.FieldID,
},
},
}
id, ok := rtuo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "ID", err: fmt.Errorf("missing RefreshToken.ID for update")}
}
_spec.Node.ID.Value = id
if fields := rtuo.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 {
if !refreshtoken.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("db: invalid field %q for query", f)}
}
if f != refreshtoken.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := rtuo.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 {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: refreshtoken.FieldClientID,
})
}
if value, ok := rtuo.mutation.Scopes(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: refreshtoken.FieldScopes,
})
}
if rtuo.mutation.ScopesCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Column: refreshtoken.FieldScopes,
})
}
if value, ok := rtuo.mutation.Nonce(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: refreshtoken.FieldNonce,
})
}
if value, ok := rtuo.mutation.ClaimsUserID(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: refreshtoken.FieldClaimsUserID,
})
}
if value, ok := rtuo.mutation.ClaimsUsername(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: refreshtoken.FieldClaimsUsername,
})
}
if value, ok := rtuo.mutation.ClaimsEmail(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: refreshtoken.FieldClaimsEmail,
})
}
if value, ok := rtuo.mutation.ClaimsEmailVerified(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: refreshtoken.FieldClaimsEmailVerified,
})
}
if value, ok := rtuo.mutation.ClaimsGroups(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: refreshtoken.FieldClaimsGroups,
})
}
if rtuo.mutation.ClaimsGroupsCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Column: refreshtoken.FieldClaimsGroups,
})
}
if value, ok := rtuo.mutation.ClaimsPreferredUsername(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: refreshtoken.FieldClaimsPreferredUsername,
})
}
if value, ok := rtuo.mutation.ConnectorID(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: refreshtoken.FieldConnectorID,
})
}
if value, ok := rtuo.mutation.ConnectorData(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Value: value,
Column: refreshtoken.FieldConnectorData,
})
}
if rtuo.mutation.ConnectorDataCleared() {
_spec.Fields.Clear = append(_spec.Fields.Clear, &sqlgraph.FieldSpec{
Type: field.TypeBytes,
Column: refreshtoken.FieldConnectorData,
})
}
if value, ok := rtuo.mutation.Token(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: refreshtoken.FieldToken,
})
}
if value, ok := rtuo.mutation.ObsoleteToken(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: refreshtoken.FieldObsoleteToken,
})
}
if value, ok := rtuo.mutation.CreatedAt(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: refreshtoken.FieldCreatedAt,
})
}
if value, ok := rtuo.mutation.LastUsed(); ok {
_spec.Fields.Set = append(_spec.Fields.Set, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: refreshtoken.FieldLastUsed,
})
}
_node = &RefreshToken{config: rtuo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, rtuo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{refreshtoken.Label}
} else if cerr, ok := isSQLConstraintError(err); ok {
err = cerr
}
return nil, err
}
return _node, nil
}

233
storage/ent/db/runtime.go Normal file
View file

@ -0,0 +1,233 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"time"
"github.com/dexidp/dex/storage/ent/db/authcode"
"github.com/dexidp/dex/storage/ent/db/authrequest"
"github.com/dexidp/dex/storage/ent/db/connector"
"github.com/dexidp/dex/storage/ent/db/devicerequest"
"github.com/dexidp/dex/storage/ent/db/devicetoken"
"github.com/dexidp/dex/storage/ent/db/keys"
"github.com/dexidp/dex/storage/ent/db/oauth2client"
"github.com/dexidp/dex/storage/ent/db/offlinesession"
"github.com/dexidp/dex/storage/ent/db/password"
"github.com/dexidp/dex/storage/ent/db/refreshtoken"
"github.com/dexidp/dex/storage/ent/schema"
)
// The init function reads all schema descriptors with runtime code
// (default values, validators, hooks and policies) and stitches it
// to their package variables.
func init() {
authcodeFields := schema.AuthCode{}.Fields()
_ = authcodeFields
// authcodeDescClientID is the schema descriptor for client_id field.
authcodeDescClientID := authcodeFields[1].Descriptor()
// authcode.ClientIDValidator is a validator for the "client_id" field. It is called by the builders before save.
authcode.ClientIDValidator = authcodeDescClientID.Validators[0].(func(string) error)
// authcodeDescNonce is the schema descriptor for nonce field.
authcodeDescNonce := authcodeFields[3].Descriptor()
// authcode.NonceValidator is a validator for the "nonce" field. It is called by the builders before save.
authcode.NonceValidator = authcodeDescNonce.Validators[0].(func(string) error)
// authcodeDescRedirectURI is the schema descriptor for redirect_uri field.
authcodeDescRedirectURI := authcodeFields[4].Descriptor()
// authcode.RedirectURIValidator is a validator for the "redirect_uri" field. It is called by the builders before save.
authcode.RedirectURIValidator = authcodeDescRedirectURI.Validators[0].(func(string) error)
// authcodeDescClaimsUserID is the schema descriptor for claims_user_id field.
authcodeDescClaimsUserID := authcodeFields[5].Descriptor()
// authcode.ClaimsUserIDValidator is a validator for the "claims_user_id" field. It is called by the builders before save.
authcode.ClaimsUserIDValidator = authcodeDescClaimsUserID.Validators[0].(func(string) error)
// authcodeDescClaimsUsername is the schema descriptor for claims_username field.
authcodeDescClaimsUsername := authcodeFields[6].Descriptor()
// authcode.ClaimsUsernameValidator is a validator for the "claims_username" field. It is called by the builders before save.
authcode.ClaimsUsernameValidator = authcodeDescClaimsUsername.Validators[0].(func(string) error)
// authcodeDescClaimsEmail is the schema descriptor for claims_email field.
authcodeDescClaimsEmail := authcodeFields[7].Descriptor()
// authcode.ClaimsEmailValidator is a validator for the "claims_email" field. It is called by the builders before save.
authcode.ClaimsEmailValidator = authcodeDescClaimsEmail.Validators[0].(func(string) error)
// authcodeDescClaimsPreferredUsername is the schema descriptor for claims_preferred_username field.
authcodeDescClaimsPreferredUsername := authcodeFields[10].Descriptor()
// authcode.DefaultClaimsPreferredUsername holds the default value on creation for the claims_preferred_username field.
authcode.DefaultClaimsPreferredUsername = authcodeDescClaimsPreferredUsername.Default.(string)
// authcodeDescConnectorID is the schema descriptor for connector_id field.
authcodeDescConnectorID := authcodeFields[11].Descriptor()
// authcode.ConnectorIDValidator is a validator for the "connector_id" field. It is called by the builders before save.
authcode.ConnectorIDValidator = authcodeDescConnectorID.Validators[0].(func(string) error)
// authcodeDescCodeChallenge is the schema descriptor for code_challenge field.
authcodeDescCodeChallenge := authcodeFields[14].Descriptor()
// authcode.DefaultCodeChallenge holds the default value on creation for the code_challenge field.
authcode.DefaultCodeChallenge = authcodeDescCodeChallenge.Default.(string)
// authcodeDescCodeChallengeMethod is the schema descriptor for code_challenge_method field.
authcodeDescCodeChallengeMethod := authcodeFields[15].Descriptor()
// authcode.DefaultCodeChallengeMethod holds the default value on creation for the code_challenge_method field.
authcode.DefaultCodeChallengeMethod = authcodeDescCodeChallengeMethod.Default.(string)
// authcodeDescID is the schema descriptor for id field.
authcodeDescID := authcodeFields[0].Descriptor()
// authcode.IDValidator is a validator for the "id" field. It is called by the builders before save.
authcode.IDValidator = authcodeDescID.Validators[0].(func(string) error)
authrequestFields := schema.AuthRequest{}.Fields()
_ = authrequestFields
// authrequestDescClaimsPreferredUsername is the schema descriptor for claims_preferred_username field.
authrequestDescClaimsPreferredUsername := authrequestFields[14].Descriptor()
// authrequest.DefaultClaimsPreferredUsername holds the default value on creation for the claims_preferred_username field.
authrequest.DefaultClaimsPreferredUsername = authrequestDescClaimsPreferredUsername.Default.(string)
// authrequestDescCodeChallenge is the schema descriptor for code_challenge field.
authrequestDescCodeChallenge := authrequestFields[18].Descriptor()
// authrequest.DefaultCodeChallenge holds the default value on creation for the code_challenge field.
authrequest.DefaultCodeChallenge = authrequestDescCodeChallenge.Default.(string)
// authrequestDescCodeChallengeMethod is the schema descriptor for code_challenge_method field.
authrequestDescCodeChallengeMethod := authrequestFields[19].Descriptor()
// authrequest.DefaultCodeChallengeMethod holds the default value on creation for the code_challenge_method field.
authrequest.DefaultCodeChallengeMethod = authrequestDescCodeChallengeMethod.Default.(string)
// authrequestDescID is the schema descriptor for id field.
authrequestDescID := authrequestFields[0].Descriptor()
// authrequest.IDValidator is a validator for the "id" field. It is called by the builders before save.
authrequest.IDValidator = authrequestDescID.Validators[0].(func(string) error)
connectorFields := schema.Connector{}.Fields()
_ = connectorFields
// connectorDescType is the schema descriptor for type field.
connectorDescType := connectorFields[1].Descriptor()
// connector.TypeValidator is a validator for the "type" field. It is called by the builders before save.
connector.TypeValidator = connectorDescType.Validators[0].(func(string) error)
// connectorDescName is the schema descriptor for name field.
connectorDescName := connectorFields[2].Descriptor()
// connector.NameValidator is a validator for the "name" field. It is called by the builders before save.
connector.NameValidator = connectorDescName.Validators[0].(func(string) error)
// connectorDescID is the schema descriptor for id field.
connectorDescID := connectorFields[0].Descriptor()
// connector.IDValidator is a validator for the "id" field. It is called by the builders before save.
connector.IDValidator = connectorDescID.Validators[0].(func(string) error)
devicerequestFields := schema.DeviceRequest{}.Fields()
_ = devicerequestFields
// devicerequestDescUserCode is the schema descriptor for user_code field.
devicerequestDescUserCode := devicerequestFields[0].Descriptor()
// devicerequest.UserCodeValidator is a validator for the "user_code" field. It is called by the builders before save.
devicerequest.UserCodeValidator = devicerequestDescUserCode.Validators[0].(func(string) error)
// devicerequestDescDeviceCode is the schema descriptor for device_code field.
devicerequestDescDeviceCode := devicerequestFields[1].Descriptor()
// devicerequest.DeviceCodeValidator is a validator for the "device_code" field. It is called by the builders before save.
devicerequest.DeviceCodeValidator = devicerequestDescDeviceCode.Validators[0].(func(string) error)
// devicerequestDescClientID is the schema descriptor for client_id field.
devicerequestDescClientID := devicerequestFields[2].Descriptor()
// devicerequest.ClientIDValidator is a validator for the "client_id" field. It is called by the builders before save.
devicerequest.ClientIDValidator = devicerequestDescClientID.Validators[0].(func(string) error)
// devicerequestDescClientSecret is the schema descriptor for client_secret field.
devicerequestDescClientSecret := devicerequestFields[3].Descriptor()
// devicerequest.ClientSecretValidator is a validator for the "client_secret" field. It is called by the builders before save.
devicerequest.ClientSecretValidator = devicerequestDescClientSecret.Validators[0].(func(string) error)
devicetokenFields := schema.DeviceToken{}.Fields()
_ = devicetokenFields
// devicetokenDescDeviceCode is the schema descriptor for device_code field.
devicetokenDescDeviceCode := devicetokenFields[0].Descriptor()
// devicetoken.DeviceCodeValidator is a validator for the "device_code" field. It is called by the builders before save.
devicetoken.DeviceCodeValidator = devicetokenDescDeviceCode.Validators[0].(func(string) error)
// devicetokenDescStatus is the schema descriptor for status field.
devicetokenDescStatus := devicetokenFields[1].Descriptor()
// devicetoken.StatusValidator is a validator for the "status" field. It is called by the builders before save.
devicetoken.StatusValidator = devicetokenDescStatus.Validators[0].(func(string) error)
keysFields := schema.Keys{}.Fields()
_ = keysFields
// keysDescID is the schema descriptor for id field.
keysDescID := keysFields[0].Descriptor()
// keys.IDValidator is a validator for the "id" field. It is called by the builders before save.
keys.IDValidator = keysDescID.Validators[0].(func(string) error)
oauth2clientFields := schema.OAuth2Client{}.Fields()
_ = oauth2clientFields
// oauth2clientDescSecret is the schema descriptor for secret field.
oauth2clientDescSecret := oauth2clientFields[1].Descriptor()
// oauth2client.SecretValidator is a validator for the "secret" field. It is called by the builders before save.
oauth2client.SecretValidator = oauth2clientDescSecret.Validators[0].(func(string) error)
// oauth2clientDescName is the schema descriptor for name field.
oauth2clientDescName := oauth2clientFields[5].Descriptor()
// oauth2client.NameValidator is a validator for the "name" field. It is called by the builders before save.
oauth2client.NameValidator = oauth2clientDescName.Validators[0].(func(string) error)
// oauth2clientDescLogoURL is the schema descriptor for logo_url field.
oauth2clientDescLogoURL := oauth2clientFields[6].Descriptor()
// oauth2client.LogoURLValidator is a validator for the "logo_url" field. It is called by the builders before save.
oauth2client.LogoURLValidator = oauth2clientDescLogoURL.Validators[0].(func(string) error)
// oauth2clientDescID is the schema descriptor for id field.
oauth2clientDescID := oauth2clientFields[0].Descriptor()
// oauth2client.IDValidator is a validator for the "id" field. It is called by the builders before save.
oauth2client.IDValidator = oauth2clientDescID.Validators[0].(func(string) error)
offlinesessionFields := schema.OfflineSession{}.Fields()
_ = offlinesessionFields
// offlinesessionDescUserID is the schema descriptor for user_id field.
offlinesessionDescUserID := offlinesessionFields[1].Descriptor()
// offlinesession.UserIDValidator is a validator for the "user_id" field. It is called by the builders before save.
offlinesession.UserIDValidator = offlinesessionDescUserID.Validators[0].(func(string) error)
// offlinesessionDescConnID is the schema descriptor for conn_id field.
offlinesessionDescConnID := offlinesessionFields[2].Descriptor()
// offlinesession.ConnIDValidator is a validator for the "conn_id" field. It is called by the builders before save.
offlinesession.ConnIDValidator = offlinesessionDescConnID.Validators[0].(func(string) error)
// offlinesessionDescID is the schema descriptor for id field.
offlinesessionDescID := offlinesessionFields[0].Descriptor()
// offlinesession.IDValidator is a validator for the "id" field. It is called by the builders before save.
offlinesession.IDValidator = offlinesessionDescID.Validators[0].(func(string) error)
passwordFields := schema.Password{}.Fields()
_ = passwordFields
// passwordDescEmail is the schema descriptor for email field.
passwordDescEmail := passwordFields[0].Descriptor()
// password.EmailValidator is a validator for the "email" field. It is called by the builders before save.
password.EmailValidator = passwordDescEmail.Validators[0].(func(string) error)
// passwordDescUsername is the schema descriptor for username field.
passwordDescUsername := passwordFields[2].Descriptor()
// password.UsernameValidator is a validator for the "username" field. It is called by the builders before save.
password.UsernameValidator = passwordDescUsername.Validators[0].(func(string) error)
// passwordDescUserID is the schema descriptor for user_id field.
passwordDescUserID := passwordFields[3].Descriptor()
// password.UserIDValidator is a validator for the "user_id" field. It is called by the builders before save.
password.UserIDValidator = passwordDescUserID.Validators[0].(func(string) error)
refreshtokenFields := schema.RefreshToken{}.Fields()
_ = refreshtokenFields
// refreshtokenDescClientID is the schema descriptor for client_id field.
refreshtokenDescClientID := refreshtokenFields[1].Descriptor()
// refreshtoken.ClientIDValidator is a validator for the "client_id" field. It is called by the builders before save.
refreshtoken.ClientIDValidator = refreshtokenDescClientID.Validators[0].(func(string) error)
// refreshtokenDescNonce is the schema descriptor for nonce field.
refreshtokenDescNonce := refreshtokenFields[3].Descriptor()
// refreshtoken.NonceValidator is a validator for the "nonce" field. It is called by the builders before save.
refreshtoken.NonceValidator = refreshtokenDescNonce.Validators[0].(func(string) error)
// refreshtokenDescClaimsUserID is the schema descriptor for claims_user_id field.
refreshtokenDescClaimsUserID := refreshtokenFields[4].Descriptor()
// refreshtoken.ClaimsUserIDValidator is a validator for the "claims_user_id" field. It is called by the builders before save.
refreshtoken.ClaimsUserIDValidator = refreshtokenDescClaimsUserID.Validators[0].(func(string) error)
// refreshtokenDescClaimsUsername is the schema descriptor for claims_username field.
refreshtokenDescClaimsUsername := refreshtokenFields[5].Descriptor()
// refreshtoken.ClaimsUsernameValidator is a validator for the "claims_username" field. It is called by the builders before save.
refreshtoken.ClaimsUsernameValidator = refreshtokenDescClaimsUsername.Validators[0].(func(string) error)
// refreshtokenDescClaimsEmail is the schema descriptor for claims_email field.
refreshtokenDescClaimsEmail := refreshtokenFields[6].Descriptor()
// refreshtoken.ClaimsEmailValidator is a validator for the "claims_email" field. It is called by the builders before save.
refreshtoken.ClaimsEmailValidator = refreshtokenDescClaimsEmail.Validators[0].(func(string) error)
// refreshtokenDescClaimsPreferredUsername is the schema descriptor for claims_preferred_username field.
refreshtokenDescClaimsPreferredUsername := refreshtokenFields[9].Descriptor()
// refreshtoken.DefaultClaimsPreferredUsername holds the default value on creation for the claims_preferred_username field.
refreshtoken.DefaultClaimsPreferredUsername = refreshtokenDescClaimsPreferredUsername.Default.(string)
// refreshtokenDescConnectorID is the schema descriptor for connector_id field.
refreshtokenDescConnectorID := refreshtokenFields[10].Descriptor()
// refreshtoken.ConnectorIDValidator is a validator for the "connector_id" field. It is called by the builders before save.
refreshtoken.ConnectorIDValidator = refreshtokenDescConnectorID.Validators[0].(func(string) error)
// refreshtokenDescToken is the schema descriptor for token field.
refreshtokenDescToken := refreshtokenFields[12].Descriptor()
// refreshtoken.DefaultToken holds the default value on creation for the token field.
refreshtoken.DefaultToken = refreshtokenDescToken.Default.(string)
// refreshtokenDescObsoleteToken is the schema descriptor for obsolete_token field.
refreshtokenDescObsoleteToken := refreshtokenFields[13].Descriptor()
// refreshtoken.DefaultObsoleteToken holds the default value on creation for the obsolete_token field.
refreshtoken.DefaultObsoleteToken = refreshtokenDescObsoleteToken.Default.(string)
// refreshtokenDescCreatedAt is the schema descriptor for created_at field.
refreshtokenDescCreatedAt := refreshtokenFields[14].Descriptor()
// refreshtoken.DefaultCreatedAt holds the default value on creation for the created_at field.
refreshtoken.DefaultCreatedAt = refreshtokenDescCreatedAt.Default.(func() time.Time)
// refreshtokenDescLastUsed is the schema descriptor for last_used field.
refreshtokenDescLastUsed := refreshtokenFields[15].Descriptor()
// refreshtoken.DefaultLastUsed holds the default value on creation for the last_used field.
refreshtoken.DefaultLastUsed = refreshtokenDescLastUsed.Default.(func() time.Time)
// refreshtokenDescID is the schema descriptor for id field.
refreshtokenDescID := refreshtokenFields[0].Descriptor()
// refreshtoken.IDValidator is a validator for the "id" field. It is called by the builders before save.
refreshtoken.IDValidator = refreshtokenDescID.Validators[0].(func(string) error)
}

View file

@ -0,0 +1,10 @@
// Code generated by entc, DO NOT EDIT.
package runtime
// The schema-stitching logic is generated in github.com/dexidp/dex/storage/ent/db/runtime.go
const (
Version = "v0.8.0" // Version of ent codegen.
Sum = "h1:xirrW//1oda7pp0bz+XssSOv4/C3nmgYQOxjIfljFt8=" // Sum of ent codegen.
)

237
storage/ent/db/tx.go Normal file
View file

@ -0,0 +1,237 @@
// Code generated by entc, DO NOT EDIT.
package db
import (
"context"
"sync"
"entgo.io/ent/dialect"
)
// Tx is a transactional client that is created by calling Client.Tx().
type Tx struct {
config
// AuthCode is the client for interacting with the AuthCode builders.
AuthCode *AuthCodeClient
// AuthRequest is the client for interacting with the AuthRequest builders.
AuthRequest *AuthRequestClient
// Connector is the client for interacting with the Connector builders.
Connector *ConnectorClient
// DeviceRequest is the client for interacting with the DeviceRequest builders.
DeviceRequest *DeviceRequestClient
// DeviceToken is the client for interacting with the DeviceToken builders.
DeviceToken *DeviceTokenClient
// Keys is the client for interacting with the Keys builders.
Keys *KeysClient
// OAuth2Client is the client for interacting with the OAuth2Client builders.
OAuth2Client *OAuth2ClientClient
// OfflineSession is the client for interacting with the OfflineSession builders.
OfflineSession *OfflineSessionClient
// Password is the client for interacting with the Password builders.
Password *PasswordClient
// RefreshToken is the client for interacting with the RefreshToken builders.
RefreshToken *RefreshTokenClient
// lazily loaded.
client *Client
clientOnce sync.Once
// completion callbacks.
mu sync.Mutex
onCommit []CommitHook
onRollback []RollbackHook
// ctx lives for the life of the transaction. It is
// the same context used by the underlying connection.
ctx context.Context
}
type (
// Committer is the interface that wraps the Committer method.
Committer interface {
Commit(context.Context, *Tx) error
}
// The CommitFunc type is an adapter to allow the use of ordinary
// function as a Committer. If f is a function with the appropriate
// signature, CommitFunc(f) is a Committer that calls f.
CommitFunc func(context.Context, *Tx) error
// CommitHook defines the "commit middleware". A function that gets a Committer
// and returns a Committer. For example:
//
// hook := func(next ent.Committer) ent.Committer {
// return ent.CommitFunc(func(context.Context, tx *ent.Tx) error {
// // Do some stuff before.
// if err := next.Commit(ctx, tx); err != nil {
// return err
// }
// // Do some stuff after.
// return nil
// })
// }
//
CommitHook func(Committer) Committer
)
// Commit calls f(ctx, m).
func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error {
return f(ctx, tx)
}
// Commit commits the transaction.
func (tx *Tx) Commit() error {
txDriver := tx.config.driver.(*txDriver)
var fn Committer = CommitFunc(func(context.Context, *Tx) error {
return txDriver.tx.Commit()
})
tx.mu.Lock()
hooks := append([]CommitHook(nil), tx.onCommit...)
tx.mu.Unlock()
for i := len(hooks) - 1; i >= 0; i-- {
fn = hooks[i](fn)
}
return fn.Commit(tx.ctx, tx)
}
// OnCommit adds a hook to call on commit.
func (tx *Tx) OnCommit(f CommitHook) {
tx.mu.Lock()
defer tx.mu.Unlock()
tx.onCommit = append(tx.onCommit, f)
}
type (
// Rollbacker is the interface that wraps the Rollbacker method.
Rollbacker interface {
Rollback(context.Context, *Tx) error
}
// The RollbackFunc type is an adapter to allow the use of ordinary
// function as a Rollbacker. If f is a function with the appropriate
// signature, RollbackFunc(f) is a Rollbacker that calls f.
RollbackFunc func(context.Context, *Tx) error
// RollbackHook defines the "rollback middleware". A function that gets a Rollbacker
// and returns a Rollbacker. For example:
//
// hook := func(next ent.Rollbacker) ent.Rollbacker {
// return ent.RollbackFunc(func(context.Context, tx *ent.Tx) error {
// // Do some stuff before.
// if err := next.Rollback(ctx, tx); err != nil {
// return err
// }
// // Do some stuff after.
// return nil
// })
// }
//
RollbackHook func(Rollbacker) Rollbacker
)
// Rollback calls f(ctx, m).
func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error {
return f(ctx, tx)
}
// Rollback rollbacks the transaction.
func (tx *Tx) Rollback() error {
txDriver := tx.config.driver.(*txDriver)
var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error {
return txDriver.tx.Rollback()
})
tx.mu.Lock()
hooks := append([]RollbackHook(nil), tx.onRollback...)
tx.mu.Unlock()
for i := len(hooks) - 1; i >= 0; i-- {
fn = hooks[i](fn)
}
return fn.Rollback(tx.ctx, tx)
}
// OnRollback adds a hook to call on rollback.
func (tx *Tx) OnRollback(f RollbackHook) {
tx.mu.Lock()
defer tx.mu.Unlock()
tx.onRollback = append(tx.onRollback, f)
}
// Client returns a Client that binds to current transaction.
func (tx *Tx) Client() *Client {
tx.clientOnce.Do(func() {
tx.client = &Client{config: tx.config}
tx.client.init()
})
return tx.client
}
func (tx *Tx) init() {
tx.AuthCode = NewAuthCodeClient(tx.config)
tx.AuthRequest = NewAuthRequestClient(tx.config)
tx.Connector = NewConnectorClient(tx.config)
tx.DeviceRequest = NewDeviceRequestClient(tx.config)
tx.DeviceToken = NewDeviceTokenClient(tx.config)
tx.Keys = NewKeysClient(tx.config)
tx.OAuth2Client = NewOAuth2ClientClient(tx.config)
tx.OfflineSession = NewOfflineSessionClient(tx.config)
tx.Password = NewPasswordClient(tx.config)
tx.RefreshToken = NewRefreshTokenClient(tx.config)
}
// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation.
// The idea is to support transactions without adding any extra code to the builders.
// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance.
// Commit and Rollback are nop for the internal builders and the user must call one
// of them in order to commit or rollback the transaction.
//
// If a closed transaction is embedded in one of the generated entities, and the entity
// applies a query, for example: AuthCode.QueryXXX(), the query will be executed
// through the driver which created this transaction.
//
// Note that txDriver is not goroutine safe.
type txDriver struct {
// the driver we started the transaction from.
drv dialect.Driver
// tx is the underlying transaction.
tx dialect.Tx
}
// newTx creates a new transactional driver.
func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) {
tx, err := drv.Tx(ctx)
if err != nil {
return nil, err
}
return &txDriver{tx: tx, drv: drv}, nil
}
// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls
// from the internal builders. Should be called only by the internal builders.
func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil }
// Dialect returns the dialect of the driver we started the transaction from.
func (tx *txDriver) Dialect() string { return tx.drv.Dialect() }
// Close is a nop close.
func (*txDriver) Close() error { return nil }
// Commit is a nop commit for the internal builders.
// User must call `Tx.Commit` in order to commit the transaction.
func (*txDriver) Commit() error { return nil }
// Rollback is a nop rollback for the internal builders.
// User must call `Tx.Rollback` in order to rollback the transaction.
func (*txDriver) Rollback() error { return nil }
// Exec calls tx.Exec.
func (tx *txDriver) Exec(ctx context.Context, query string, args, v interface{}) error {
return tx.tx.Exec(ctx, query, args, v)
}
// Query calls tx.Query.
func (tx *txDriver) Query(ctx context.Context, query string, args, v interface{}) error {
return tx.tx.Query(ctx, query, args, v)
}
var _ dialect.Driver = (*txDriver)(nil)

Some files were not shown because too many files have changed in this diff Show more