diff --git a/.direnv/nix-profile-25.05-j95fcik6rzsydwip b/.direnv/nix-profile-25.05-j95fcik6rzsydwip deleted file mode 120000 index a68282a..0000000 --- a/.direnv/nix-profile-25.05-j95fcik6rzsydwip +++ /dev/null @@ -1 +0,0 @@ -/nix/store/743wjvr7d1qr3jqkvfc1980q45yhrcyf-nix-shell-env \ No newline at end of file diff --git a/.direnv/nix-profile-25.05-j95fcik6rzsydwip.rc b/.direnv/nix-profile-25.05-j95fcik6rzsydwip.rc deleted file mode 100644 index f0c8642..0000000 --- a/.direnv/nix-profile-25.05-j95fcik6rzsydwip.rc +++ /dev/null @@ -1,2163 +0,0 @@ -unset shellHook -PATH=${PATH:-} -nix_saved_PATH="$PATH" -XDG_DATA_DIRS=${XDG_DATA_DIRS:-} -nix_saved_XDG_DATA_DIRS="$XDG_DATA_DIRS" -AR='ar' -export AR -AR_FOR_TARGET='ar' -export AR_FOR_TARGET -AS='as' -export AS -AS_FOR_TARGET='as' -export AS_FOR_TARGET -BASH='/nix/store/xy4jjgw87sbgwylm5kn047d9gkbhsr9x-bash-5.2p37/bin/bash' -CC='gcc' -export CC -CC_FOR_TARGET='gcc' -export CC_FOR_TARGET -CONFIG_SHELL='/nix/store/xy4jjgw87sbgwylm5kn047d9gkbhsr9x-bash-5.2p37/bin/bash' -export CONFIG_SHELL -CXX='g++' -export CXX -CXX_FOR_TARGET='g++' -export CXX_FOR_TARGET -HOSTTYPE='x86_64' -HOST_PATH='/nix/store/5xvi25nqmbrg58aixp4zgczilfnp7pwg-go-1.24.3/bin:/nix/store/88ma4lbybcpdg0z8745nw9mvj5anb7mq-protobuf-30.2/bin:/nix/store/2ic27p3bb3b03a8aa54k55yymmy22yly-go-tools-2025.1.1/bin:/nix/store/snqg2xccy7fb6q6n2dw3bfql6mqbh6ar-golangci-lint-2.1.6/bin:/nix/store/ybp8dsnmsfpx0daxhkhvfn2iaighgfw6-grpcurl-1.9.3/bin:/nix/store/0fsnicvfpf55nkza12cjnad0w84d6ba7-gcc-wrapper-14.2.1.20250322/bin:/nix/store/hhfm5fkvb1alg1np5a69m2qlcjqhr062-binutils-wrapper-2.44/bin:/nix/store/303islqk386z1w2g1ngvxnkl4glfpgrs-glibc-2.40-66-bin/bin:/nix/store/805a5wv1cyah5awij184yfad1ksmbh9f-git-2.49.0/bin:/nix/store/578hp6h741gwi4wh1nx6rflsnicp2hwn-postgresql-17.5-dev/bin:/nix/store/jgvr5576yv6vxaxn9ps09222ii889zhk-postgresql-17.5/bin:/nix/store/axrxs03qfy56v212mdyrrsiys9ia1ss8-consul-1.21.2/bin:/nix/store/8ahj9mdnpl30yligq6cscqcghxrdqpzq-docker-27.5.1/bin:/nix/store/q5fhdbyd3dk8jybnji6cpkn96907ldcp-docker-compose-2.36.0/bin:/nix/store/87fck6hm17chxjq7badb11mq036zbyv9-coreutils-9.7/bin:/nix/store/7y59hzi3svdj1xjddjn2k7km96pifcyl-findutils-4.10.0/bin:/nix/store/7h0sard22wnbz0jyz07w8y9y0fcs795r-diffutils-3.12/bin:/nix/store/clbb2cvigynr235ab5zgi18dyavznlk2-gnused-4.9/bin:/nix/store/gqmr3gixlddz3667ba1iyqck3c0dkpvd-gnugrep-3.11/bin:/nix/store/fcyn0dqszgfysiasdmkv1jh3syncajay-gawk-5.3.2/bin:/nix/store/wrxvqj822kz8746608lgns7h8mkpn79f-gnutar-1.35/bin:/nix/store/afhkqb5a94zlwjxigsnwsfwkf38h21dk-gzip-1.14/bin:/nix/store/1abbyfv3bpxalfjfgpmwg8jcy931bf76-bzip2-1.0.8-bin/bin:/nix/store/kv10h4pidkmx8cjs2sw2pi9rlcnighbc-gnumake-4.4.1/bin:/nix/store/xy4jjgw87sbgwylm5kn047d9gkbhsr9x-bash-5.2p37/bin:/nix/store/x0kaspzb5jqvgp357bj27z6iq24ximfg-patch-2.7.6/bin:/nix/store/98zamhd8d0jq3skqwz28dlgph94mrqir-xz-5.8.1-bin/bin:/nix/store/imhzyxqr7swq08ip81az5kfa07r07kg0-file-5.46/bin' -export HOST_PATH -IFS=' -' -IN_NIX_SHELL='impure' -export IN_NIX_SHELL -LD='ld' -export LD -LD_FOR_TARGET='ld' -export LD_FOR_TARGET -LINENO='76' -MACHTYPE='x86_64-pc-linux-gnu' -NIX_BINTOOLS='/nix/store/hhfm5fkvb1alg1np5a69m2qlcjqhr062-binutils-wrapper-2.44' -export NIX_BINTOOLS -NIX_BINTOOLS_FOR_TARGET='/nix/store/hhfm5fkvb1alg1np5a69m2qlcjqhr062-binutils-wrapper-2.44' -export NIX_BINTOOLS_FOR_TARGET -NIX_BINTOOLS_WRAPPER_TARGET_HOST_x86_64_unknown_linux_gnu='1' -export NIX_BINTOOLS_WRAPPER_TARGET_HOST_x86_64_unknown_linux_gnu -NIX_BINTOOLS_WRAPPER_TARGET_TARGET_x86_64_unknown_linux_gnu='1' -export NIX_BINTOOLS_WRAPPER_TARGET_TARGET_x86_64_unknown_linux_gnu -NIX_BUILD_CORES='8' -export NIX_BUILD_CORES -NIX_CC='/nix/store/0fsnicvfpf55nkza12cjnad0w84d6ba7-gcc-wrapper-14.2.1.20250322' -export NIX_CC -NIX_CC_FOR_TARGET='/nix/store/0fsnicvfpf55nkza12cjnad0w84d6ba7-gcc-wrapper-14.2.1.20250322' -export NIX_CC_FOR_TARGET -NIX_CC_WRAPPER_TARGET_HOST_x86_64_unknown_linux_gnu='1' -export NIX_CC_WRAPPER_TARGET_HOST_x86_64_unknown_linux_gnu -NIX_CC_WRAPPER_TARGET_TARGET_x86_64_unknown_linux_gnu='1' -export NIX_CC_WRAPPER_TARGET_TARGET_x86_64_unknown_linux_gnu -NIX_CFLAGS_COMPILE=' -frandom-seed=743wjvr7d1 -isystem /nix/store/88ma4lbybcpdg0z8745nw9mvj5anb7mq-protobuf-30.2/include -isystem /nix/store/afacgi173j35xdc3rih1i2iadx8k68vr-abseil-cpp-20250127.1/include -isystem /nix/store/r25srliigrrv5q3n7y8ms6z10spvjcd9-glibc-2.40-66-dev/include -isystem /nix/store/578hp6h741gwi4wh1nx6rflsnicp2hwn-postgresql-17.5-dev/include -isystem /nix/store/88ma4lbybcpdg0z8745nw9mvj5anb7mq-protobuf-30.2/include -isystem /nix/store/afacgi173j35xdc3rih1i2iadx8k68vr-abseil-cpp-20250127.1/include -isystem /nix/store/r25srliigrrv5q3n7y8ms6z10spvjcd9-glibc-2.40-66-dev/include -isystem /nix/store/578hp6h741gwi4wh1nx6rflsnicp2hwn-postgresql-17.5-dev/include' -export NIX_CFLAGS_COMPILE -NIX_CFLAGS_COMPILE_FOR_TARGET=' -isystem /nix/store/88ma4lbybcpdg0z8745nw9mvj5anb7mq-protobuf-30.2/include -isystem /nix/store/afacgi173j35xdc3rih1i2iadx8k68vr-abseil-cpp-20250127.1/include -isystem /nix/store/r25srliigrrv5q3n7y8ms6z10spvjcd9-glibc-2.40-66-dev/include -isystem /nix/store/578hp6h741gwi4wh1nx6rflsnicp2hwn-postgresql-17.5-dev/include' -export NIX_CFLAGS_COMPILE_FOR_TARGET -NIX_ENFORCE_NO_NATIVE='1' -export NIX_ENFORCE_NO_NATIVE -NIX_HARDENING_ENABLE='bindnow format fortify fortify3 pic relro stackclashprotection stackprotector strictoverflow zerocallusedregs' -export NIX_HARDENING_ENABLE -NIX_LDFLAGS='-rpath /home/master/src/paaf/goplt/outputs/out/lib -L/nix/store/88ma4lbybcpdg0z8745nw9mvj5anb7mq-protobuf-30.2/lib -L/nix/store/afacgi173j35xdc3rih1i2iadx8k68vr-abseil-cpp-20250127.1/lib -L/nix/store/cg9s562sa33k78m63njfn1rw47dp9z0i-glibc-2.40-66/lib -L/nix/store/578hp6h741gwi4wh1nx6rflsnicp2hwn-postgresql-17.5-dev/lib -L/nix/store/zxafhaznnkcv8ixp56f0b3hymjn71xb3-postgresql-17.5-lib/lib -L/nix/store/jgvr5576yv6vxaxn9ps09222ii889zhk-postgresql-17.5/lib -L/nix/store/88ma4lbybcpdg0z8745nw9mvj5anb7mq-protobuf-30.2/lib -L/nix/store/afacgi173j35xdc3rih1i2iadx8k68vr-abseil-cpp-20250127.1/lib -L/nix/store/cg9s562sa33k78m63njfn1rw47dp9z0i-glibc-2.40-66/lib -L/nix/store/578hp6h741gwi4wh1nx6rflsnicp2hwn-postgresql-17.5-dev/lib -L/nix/store/zxafhaznnkcv8ixp56f0b3hymjn71xb3-postgresql-17.5-lib/lib -L/nix/store/jgvr5576yv6vxaxn9ps09222ii889zhk-postgresql-17.5/lib' -export NIX_LDFLAGS -NIX_LDFLAGS_FOR_TARGET=' -L/nix/store/88ma4lbybcpdg0z8745nw9mvj5anb7mq-protobuf-30.2/lib -L/nix/store/afacgi173j35xdc3rih1i2iadx8k68vr-abseil-cpp-20250127.1/lib -L/nix/store/cg9s562sa33k78m63njfn1rw47dp9z0i-glibc-2.40-66/lib -L/nix/store/578hp6h741gwi4wh1nx6rflsnicp2hwn-postgresql-17.5-dev/lib -L/nix/store/zxafhaznnkcv8ixp56f0b3hymjn71xb3-postgresql-17.5-lib/lib -L/nix/store/jgvr5576yv6vxaxn9ps09222ii889zhk-postgresql-17.5/lib' -export NIX_LDFLAGS_FOR_TARGET -NIX_NO_SELF_RPATH='1' -NIX_STORE='/nix/store' -export NIX_STORE -NM='nm' -export NM -NM_FOR_TARGET='nm' -export NM_FOR_TARGET -OBJCOPY='objcopy' -export OBJCOPY -OBJCOPY_FOR_TARGET='objcopy' -export OBJCOPY_FOR_TARGET -OBJDUMP='objdump' -export OBJDUMP -OBJDUMP_FOR_TARGET='objdump' -export OBJDUMP_FOR_TARGET -OLDPWD='' -export OLDPWD -OPTERR='1' -OSTYPE='linux-gnu' -PATH='/nix/store/2jc1jmzis19adawjwhl8qhdvh7vlbk0q-patchelf-0.15.0/bin:/nix/store/0fsnicvfpf55nkza12cjnad0w84d6ba7-gcc-wrapper-14.2.1.20250322/bin:/nix/store/9ds850ifd4jwcccpp3v14818kk74ldf2-gcc-14.2.1.20250322/bin:/nix/store/303islqk386z1w2g1ngvxnkl4glfpgrs-glibc-2.40-66-bin/bin:/nix/store/87fck6hm17chxjq7badb11mq036zbyv9-coreutils-9.7/bin:/nix/store/hhfm5fkvb1alg1np5a69m2qlcjqhr062-binutils-wrapper-2.44/bin:/nix/store/v63bxfiacw082c7ijshf60alvvrpfxsq-binutils-2.44/bin:/nix/store/5xvi25nqmbrg58aixp4zgczilfnp7pwg-go-1.24.3/bin:/nix/store/88ma4lbybcpdg0z8745nw9mvj5anb7mq-protobuf-30.2/bin:/nix/store/2ic27p3bb3b03a8aa54k55yymmy22yly-go-tools-2025.1.1/bin:/nix/store/snqg2xccy7fb6q6n2dw3bfql6mqbh6ar-golangci-lint-2.1.6/bin:/nix/store/ybp8dsnmsfpx0daxhkhvfn2iaighgfw6-grpcurl-1.9.3/bin:/nix/store/805a5wv1cyah5awij184yfad1ksmbh9f-git-2.49.0/bin:/nix/store/578hp6h741gwi4wh1nx6rflsnicp2hwn-postgresql-17.5-dev/bin:/nix/store/jgvr5576yv6vxaxn9ps09222ii889zhk-postgresql-17.5/bin:/nix/store/axrxs03qfy56v212mdyrrsiys9ia1ss8-consul-1.21.2/bin:/nix/store/8ahj9mdnpl30yligq6cscqcghxrdqpzq-docker-27.5.1/bin:/nix/store/q5fhdbyd3dk8jybnji6cpkn96907ldcp-docker-compose-2.36.0/bin:/nix/store/87fck6hm17chxjq7badb11mq036zbyv9-coreutils-9.7/bin:/nix/store/7y59hzi3svdj1xjddjn2k7km96pifcyl-findutils-4.10.0/bin:/nix/store/7h0sard22wnbz0jyz07w8y9y0fcs795r-diffutils-3.12/bin:/nix/store/clbb2cvigynr235ab5zgi18dyavznlk2-gnused-4.9/bin:/nix/store/gqmr3gixlddz3667ba1iyqck3c0dkpvd-gnugrep-3.11/bin:/nix/store/fcyn0dqszgfysiasdmkv1jh3syncajay-gawk-5.3.2/bin:/nix/store/wrxvqj822kz8746608lgns7h8mkpn79f-gnutar-1.35/bin:/nix/store/afhkqb5a94zlwjxigsnwsfwkf38h21dk-gzip-1.14/bin:/nix/store/1abbyfv3bpxalfjfgpmwg8jcy931bf76-bzip2-1.0.8-bin/bin:/nix/store/kv10h4pidkmx8cjs2sw2pi9rlcnighbc-gnumake-4.4.1/bin:/nix/store/xy4jjgw87sbgwylm5kn047d9gkbhsr9x-bash-5.2p37/bin:/nix/store/x0kaspzb5jqvgp357bj27z6iq24ximfg-patch-2.7.6/bin:/nix/store/98zamhd8d0jq3skqwz28dlgph94mrqir-xz-5.8.1-bin/bin:/nix/store/imhzyxqr7swq08ip81az5kfa07r07kg0-file-5.46/bin' -export PATH -PS4='+ ' -RANLIB='ranlib' -export RANLIB -RANLIB_FOR_TARGET='ranlib' -export RANLIB_FOR_TARGET -READELF='readelf' -export READELF -READELF_FOR_TARGET='readelf' -export READELF_FOR_TARGET -SHELL='/nix/store/xy4jjgw87sbgwylm5kn047d9gkbhsr9x-bash-5.2p37/bin/bash' -export SHELL -SIZE='size' -export SIZE -SIZE_FOR_TARGET='size' -export SIZE_FOR_TARGET -SOURCE_DATE_EPOCH='315532800' -export SOURCE_DATE_EPOCH -STRINGS='strings' -export STRINGS -STRINGS_FOR_TARGET='strings' -export STRINGS_FOR_TARGET -STRIP='strip' -export STRIP -STRIP_FOR_TARGET='strip' -export STRIP_FOR_TARGET -XDG_DATA_DIRS='/nix/store/2jc1jmzis19adawjwhl8qhdvh7vlbk0q-patchelf-0.15.0/share' -export XDG_DATA_DIRS -__structuredAttrs='' -export __structuredAttrs -_substituteStream_has_warned_replace_deprecation='false' -buildInputs='/nix/store/5xvi25nqmbrg58aixp4zgczilfnp7pwg-go-1.24.3 /nix/store/88ma4lbybcpdg0z8745nw9mvj5anb7mq-protobuf-30.2 /nix/store/2ic27p3bb3b03a8aa54k55yymmy22yly-go-tools-2025.1.1 /nix/store/snqg2xccy7fb6q6n2dw3bfql6mqbh6ar-golangci-lint-2.1.6 /nix/store/ybp8dsnmsfpx0daxhkhvfn2iaighgfw6-grpcurl-1.9.3 /nix/store/0fsnicvfpf55nkza12cjnad0w84d6ba7-gcc-wrapper-14.2.1.20250322 /nix/store/r25srliigrrv5q3n7y8ms6z10spvjcd9-glibc-2.40-66-dev /nix/store/805a5wv1cyah5awij184yfad1ksmbh9f-git-2.49.0 /nix/store/578hp6h741gwi4wh1nx6rflsnicp2hwn-postgresql-17.5-dev /nix/store/axrxs03qfy56v212mdyrrsiys9ia1ss8-consul-1.21.2 /nix/store/8ahj9mdnpl30yligq6cscqcghxrdqpzq-docker-27.5.1 /nix/store/q5fhdbyd3dk8jybnji6cpkn96907ldcp-docker-compose-2.36.0' -export buildInputs -buildPhase='{ echo "------------------------------------------------------------"; - echo " WARNING: the existence of this path is not guaranteed."; - echo " It is an internal implementation detail for pkgs.mkShell."; - echo "------------------------------------------------------------"; - echo; - # Record all build inputs as runtime dependencies - export; -} >> "$out" -' -export buildPhase -builder='/nix/store/xy4jjgw87sbgwylm5kn047d9gkbhsr9x-bash-5.2p37/bin/bash' -export builder -cmakeFlags='' -export cmakeFlags -configureFlags='' -export configureFlags -defaultBuildInputs='' -defaultNativeBuildInputs='/nix/store/2jc1jmzis19adawjwhl8qhdvh7vlbk0q-patchelf-0.15.0 /nix/store/lmc7x75jvrca79fc2r2j1frmklzvh04h-update-autotools-gnu-config-scripts-hook /nix/store/jjhw2phnaip4kg0qjas3x3fsaifi8y0w-no-broken-symlinks.sh /nix/store/h9lc1dpi14z7is86ffhl3ld569138595-audit-tmpdir.sh /nix/store/m54bmrhj6fqz8nds5zcj97w9s9bckc9v-compress-man-pages.sh /nix/store/wgrbkkaldkrlrni33ccvm3b6vbxzb656-make-symlinks-relative.sh /nix/store/5yzw0vhkyszf2d179m0qfkgxmp5wjjx4-move-docs.sh /nix/store/fyaryjvghbkpfnsyw97hb3lyb37s1pd6-move-lib64.sh /nix/store/kd4xwxjpjxi71jkm6ka0np72if9rm3y0-move-sbin.sh /nix/store/pag6l61paj1dc9sv15l7bm5c17xn5kyk-move-systemd-user-units.sh /nix/store/cmzya9irvxzlkh7lfy6i82gbp0saxqj3-multiple-outputs.sh /nix/store/hxv896faph0rqxjq2ycxpcrbnngc95sz-patch-shebangs.sh /nix/store/cickvswrvann041nqxb0rxilc46svw1n-prune-libtool-files.sh /nix/store/xyff06pkhki3qy1ls77w10s0v79c9il0-reproducible-builds.sh /nix/store/z7k98578dfzi6l3hsvbivzm7hfqlk0zc-set-source-date-epoch-to-latest.sh /nix/store/pilsssjjdxvdphlg2h19p0bfx5q0jzkn-strip.sh /nix/store/0fsnicvfpf55nkza12cjnad0w84d6ba7-gcc-wrapper-14.2.1.20250322' -depsBuildBuild='' -export depsBuildBuild -depsBuildBuildPropagated='' -export depsBuildBuildPropagated -depsBuildTarget='' -export depsBuildTarget -depsBuildTargetPropagated='' -export depsBuildTargetPropagated -depsHostHost='' -export depsHostHost -depsHostHostPropagated='' -export depsHostHostPropagated -depsTargetTarget='' -export depsTargetTarget -depsTargetTargetPropagated='' -export depsTargetTargetPropagated -doCheck='' -export doCheck -doInstallCheck='' -export doInstallCheck -dontAddDisableDepTrack='1' -export dontAddDisableDepTrack -declare -a envBuildBuildHooks=() -declare -a envBuildHostHooks=() -declare -a envBuildTargetHooks=() -declare -a envHostHostHooks=('ccWrapper_addCVars' 'bintoolsWrapper_addLDVars' ) -declare -a envHostTargetHooks=('ccWrapper_addCVars' 'bintoolsWrapper_addLDVars' ) -declare -a envTargetTargetHooks=('ccWrapper_addCVars' 'bintoolsWrapper_addLDVars' ) -declare -a fixupOutputHooks=('if [ -z "${dontPatchELF-}" ]; then patchELF "$prefix"; fi' 'if [[ -z "${noAuditTmpdir-}" && -e "$prefix" ]]; then auditTmpdir "$prefix"; fi' 'if [ -z "${dontGzipMan-}" ]; then compressManPages "$prefix"; fi' '_moveLib64' '_moveSbin' '_moveSystemdUserUnits' 'patchShebangsAuto' '_pruneLibtoolFiles' '_doStrip' ) -guess='8' -initialPath='/nix/store/87fck6hm17chxjq7badb11mq036zbyv9-coreutils-9.7 /nix/store/7y59hzi3svdj1xjddjn2k7km96pifcyl-findutils-4.10.0 /nix/store/7h0sard22wnbz0jyz07w8y9y0fcs795r-diffutils-3.12 /nix/store/clbb2cvigynr235ab5zgi18dyavznlk2-gnused-4.9 /nix/store/gqmr3gixlddz3667ba1iyqck3c0dkpvd-gnugrep-3.11 /nix/store/fcyn0dqszgfysiasdmkv1jh3syncajay-gawk-5.3.2 /nix/store/wrxvqj822kz8746608lgns7h8mkpn79f-gnutar-1.35 /nix/store/afhkqb5a94zlwjxigsnwsfwkf38h21dk-gzip-1.14 /nix/store/1abbyfv3bpxalfjfgpmwg8jcy931bf76-bzip2-1.0.8-bin /nix/store/kv10h4pidkmx8cjs2sw2pi9rlcnighbc-gnumake-4.4.1 /nix/store/xy4jjgw87sbgwylm5kn047d9gkbhsr9x-bash-5.2p37 /nix/store/x0kaspzb5jqvgp357bj27z6iq24ximfg-patch-2.7.6 /nix/store/98zamhd8d0jq3skqwz28dlgph94mrqir-xz-5.8.1-bin /nix/store/imhzyxqr7swq08ip81az5kfa07r07kg0-file-5.46' -mesonFlags='' -export mesonFlags -name='nix-shell-env' -export name -nativeBuildInputs='' -export nativeBuildInputs -out='/home/master/src/paaf/goplt/outputs/out' -export out -outputBin='out' -outputDev='out' -outputDevdoc='REMOVE' -outputDevman='out' -outputDoc='out' -outputInclude='out' -outputInfo='out' -outputLib='out' -outputMan='out' -outputs='out' -export outputs -patches='' -export patches -phases='buildPhase' -export phases -pkg='/nix/store/0fsnicvfpf55nkza12cjnad0w84d6ba7-gcc-wrapper-14.2.1.20250322' -declare -a pkgsBuildBuild=() -declare -a pkgsBuildHost=('/nix/store/2jc1jmzis19adawjwhl8qhdvh7vlbk0q-patchelf-0.15.0' '/nix/store/lmc7x75jvrca79fc2r2j1frmklzvh04h-update-autotools-gnu-config-scripts-hook' '/nix/store/jjhw2phnaip4kg0qjas3x3fsaifi8y0w-no-broken-symlinks.sh' '/nix/store/h9lc1dpi14z7is86ffhl3ld569138595-audit-tmpdir.sh' '/nix/store/m54bmrhj6fqz8nds5zcj97w9s9bckc9v-compress-man-pages.sh' '/nix/store/wgrbkkaldkrlrni33ccvm3b6vbxzb656-make-symlinks-relative.sh' '/nix/store/5yzw0vhkyszf2d179m0qfkgxmp5wjjx4-move-docs.sh' '/nix/store/fyaryjvghbkpfnsyw97hb3lyb37s1pd6-move-lib64.sh' '/nix/store/kd4xwxjpjxi71jkm6ka0np72if9rm3y0-move-sbin.sh' '/nix/store/pag6l61paj1dc9sv15l7bm5c17xn5kyk-move-systemd-user-units.sh' '/nix/store/cmzya9irvxzlkh7lfy6i82gbp0saxqj3-multiple-outputs.sh' '/nix/store/hxv896faph0rqxjq2ycxpcrbnngc95sz-patch-shebangs.sh' '/nix/store/cickvswrvann041nqxb0rxilc46svw1n-prune-libtool-files.sh' '/nix/store/xyff06pkhki3qy1ls77w10s0v79c9il0-reproducible-builds.sh' '/nix/store/z7k98578dfzi6l3hsvbivzm7hfqlk0zc-set-source-date-epoch-to-latest.sh' '/nix/store/pilsssjjdxvdphlg2h19p0bfx5q0jzkn-strip.sh' '/nix/store/0fsnicvfpf55nkza12cjnad0w84d6ba7-gcc-wrapper-14.2.1.20250322' '/nix/store/hhfm5fkvb1alg1np5a69m2qlcjqhr062-binutils-wrapper-2.44' ) -declare -a pkgsBuildTarget=() -declare -a pkgsHostHost=() -declare -a pkgsHostTarget=('/nix/store/5xvi25nqmbrg58aixp4zgczilfnp7pwg-go-1.24.3' '/nix/store/88ma4lbybcpdg0z8745nw9mvj5anb7mq-protobuf-30.2' '/nix/store/afacgi173j35xdc3rih1i2iadx8k68vr-abseil-cpp-20250127.1' '/nix/store/2ic27p3bb3b03a8aa54k55yymmy22yly-go-tools-2025.1.1' '/nix/store/snqg2xccy7fb6q6n2dw3bfql6mqbh6ar-golangci-lint-2.1.6' '/nix/store/ybp8dsnmsfpx0daxhkhvfn2iaighgfw6-grpcurl-1.9.3' '/nix/store/0fsnicvfpf55nkza12cjnad0w84d6ba7-gcc-wrapper-14.2.1.20250322' '/nix/store/hhfm5fkvb1alg1np5a69m2qlcjqhr062-binutils-wrapper-2.44' '/nix/store/r25srliigrrv5q3n7y8ms6z10spvjcd9-glibc-2.40-66-dev' '/nix/store/303islqk386z1w2g1ngvxnkl4glfpgrs-glibc-2.40-66-bin' '/nix/store/cg9s562sa33k78m63njfn1rw47dp9z0i-glibc-2.40-66' '/nix/store/805a5wv1cyah5awij184yfad1ksmbh9f-git-2.49.0' '/nix/store/578hp6h741gwi4wh1nx6rflsnicp2hwn-postgresql-17.5-dev' '/nix/store/zxafhaznnkcv8ixp56f0b3hymjn71xb3-postgresql-17.5-lib' '/nix/store/jgvr5576yv6vxaxn9ps09222ii889zhk-postgresql-17.5' '/nix/store/axrxs03qfy56v212mdyrrsiys9ia1ss8-consul-1.21.2' '/nix/store/8ahj9mdnpl30yligq6cscqcghxrdqpzq-docker-27.5.1' '/nix/store/q5fhdbyd3dk8jybnji6cpkn96907ldcp-docker-compose-2.36.0' ) -declare -a pkgsTargetTarget=() -declare -a postFixupHooks=('noBrokenSymlinksInAllOutputs' '_makeSymlinksRelativeInAllOutputs' '_multioutPropagateDev' ) -declare -a postUnpackHooks=('_updateSourceDateEpochFromSourceRoot' ) -declare -a preConfigureHooks=('_multioutConfig' 'ProtobufCMakeFlags' ) -preConfigurePhases=' updateAutotoolsGnuConfigScriptsPhase' -declare -a preFixupHooks=('_moveToShare' '_multioutDocs' '_multioutDevs' ) -preferLocalBuild='1' -export preferLocalBuild -prefix='/home/master/src/paaf/goplt/outputs/out' -declare -a propagatedBuildDepFiles=('propagated-build-build-deps' 'propagated-native-build-inputs' 'propagated-build-target-deps' ) -propagatedBuildInputs='' -export propagatedBuildInputs -declare -a propagatedHostDepFiles=('propagated-host-host-deps' 'propagated-build-inputs' ) -propagatedNativeBuildInputs='' -export propagatedNativeBuildInputs -declare -a propagatedTargetDepFiles=('propagated-target-target-deps' ) -shell='/nix/store/xy4jjgw87sbgwylm5kn047d9gkbhsr9x-bash-5.2p37/bin/bash' -export shell -shellHook='# Set Go environment -export GOPATH="$HOME/go" -export GOBIN="$GOPATH/bin" -export PATH="$PATH:$GOBIN" -export PATH="$PATH:/nix/store/5xvi25nqmbrg58aixp4zgczilfnp7pwg-go-1.24.3/bin" - -# Install Go tools if not already installed -if ! command -v protoc-gen-go > /dev/null 2>&1; then - echo "Installing protoc-gen-go..." - /nix/store/5xvi25nqmbrg58aixp4zgczilfnp7pwg-go-1.24.3/bin/go install google.golang.org/protobuf/cmd/protoc-gen-go@latest -fi - -if ! command -v protoc-gen-go-grpc > /dev/null 2>&1; then - echo "Installing protoc-gen-go-grpc..." - /nix/store/5xvi25nqmbrg58aixp4zgczilfnp7pwg-go-1.24.3/bin/go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest -fi - -# Verify tools are available -echo "" -echo "=== Development Environment Ready ===" -echo "Go version: $(/nix/store/5xvi25nqmbrg58aixp4zgczilfnp7pwg-go-1.24.3/bin/go version)" -echo "protoc version: $(protoc --version 2>/dev/null || echo '\''not found'\'')" -echo "golangci-lint version: $(golangci-lint --version 2>/dev/null || echo '\''not found'\'')" -echo "grpcurl version: $(grpcurl --version 2>/dev/null || echo '\''not found'\'')" -echo "" -echo "Go tools:" -echo " protoc-gen-go: $(command -v protoc-gen-go > /dev/null 2>&1 && echo '\''✓ installed'\'' || echo '\''✗ not found'\'')" -echo " protoc-gen-go-grpc: $(command -v protoc-gen-go-grpc > /dev/null 2>&1 && echo '\''✓ installed'\'' || echo '\''✗ not found'\'')" -echo " goimports: $(command -v goimports > /dev/null 2>&1 && echo '\''✓ installed'\'' || echo '\''✗ not found'\'')" -echo "======================================" -echo "" -' -export shellHook -stdenv='/nix/store/nivcx63drxqzm6pic6vm2wbkxl368w83-stdenv-linux' -export stdenv -strictDeps='' -export strictDeps -system='x86_64-linux' -export system -declare -a unpackCmdHooks=('_defaultUnpack' ) -ProtobufCMakeFlags () -{ - - cmakeFlagsArray+=(-DPROTOC_EXE="/nix/store/88ma4lbybcpdg0z8745nw9mvj5anb7mq-protobuf-30.2/bin/protoc" -DProtobuf_PROTOC_EXE="/nix/store/88ma4lbybcpdg0z8745nw9mvj5anb7mq-protobuf-30.2/bin/protoc" -DProtobuf_PROTOC_EXECUTABLE="/nix/store/88ma4lbybcpdg0z8745nw9mvj5anb7mq-protobuf-30.2/bin/protoc") -} -_activatePkgs () -{ - - local hostOffset targetOffset; - local pkg; - for hostOffset in "${allPlatOffsets[@]}"; - do - local pkgsVar="${pkgAccumVarVars[hostOffset + 1]}"; - for targetOffset in "${allPlatOffsets[@]}"; - do - (( hostOffset <= targetOffset )) || continue; - local pkgsRef="${pkgsVar}[$targetOffset - $hostOffset]"; - local pkgsSlice="${!pkgsRef}[@]"; - for pkg in ${!pkgsSlice+"${!pkgsSlice}"}; - do - activatePackage "$pkg" "$hostOffset" "$targetOffset"; - done; - done; - done -} -_addRpathPrefix () -{ - - if [ "${NIX_NO_SELF_RPATH:-0}" != 1 ]; then - export NIX_LDFLAGS="-rpath $1/lib ${NIX_LDFLAGS-}"; - fi -} -_addToEnv () -{ - - local depHostOffset depTargetOffset; - local pkg; - for depHostOffset in "${allPlatOffsets[@]}"; - do - local hookVar="${pkgHookVarVars[depHostOffset + 1]}"; - local pkgsVar="${pkgAccumVarVars[depHostOffset + 1]}"; - for depTargetOffset in "${allPlatOffsets[@]}"; - do - (( depHostOffset <= depTargetOffset )) || continue; - local hookRef="${hookVar}[$depTargetOffset - $depHostOffset]"; - if [[ -z "${strictDeps-}" ]]; then - local visitedPkgs=""; - for pkg in "${pkgsBuildBuild[@]}" "${pkgsBuildHost[@]}" "${pkgsBuildTarget[@]}" "${pkgsHostHost[@]}" "${pkgsHostTarget[@]}" "${pkgsTargetTarget[@]}"; - do - if [[ "$visitedPkgs" = *"$pkg"* ]]; then - continue; - fi; - runHook "${!hookRef}" "$pkg"; - visitedPkgs+=" $pkg"; - done; - else - local pkgsRef="${pkgsVar}[$depTargetOffset - $depHostOffset]"; - local pkgsSlice="${!pkgsRef}[@]"; - for pkg in ${!pkgsSlice+"${!pkgsSlice}"}; - do - runHook "${!hookRef}" "$pkg"; - done; - fi; - done; - done -} -_allFlags () -{ - - export system pname name version; - while IFS='' read -r varName; do - nixTalkativeLog "@${varName}@ -> ${!varName}"; - args+=("--subst-var" "$varName"); - done < <(awk 'BEGIN { for (v in ENVIRON) if (v ~ /^[a-z][a-zA-Z0-9_]*$/) print v }') -} -_assignFirst () -{ - - local varName="$1"; - local _var; - local REMOVE=REMOVE; - shift; - for _var in "$@"; - do - if [ -n "${!_var-}" ]; then - eval "${varName}"="${_var}"; - return; - fi; - done; - echo; - echo "error: _assignFirst: could not find a non-empty variable whose name to assign to ${varName}."; - echo " The following variables were all unset or empty:"; - echo " $*"; - if [ -z "${out:-}" ]; then - echo ' If you do not want an "out" output in your derivation, make sure to define'; - echo ' the other specific required outputs. This can be achieved by picking one'; - echo " of the above as an output."; - echo ' You do not have to remove "out" if you want to have a different default'; - echo ' output, because the first output is taken as a default.'; - echo; - fi; - return 1 -} -_callImplicitHook () -{ - - local def="$1"; - local hookName="$2"; - if declare -F "$hookName" > /dev/null; then - nixTalkativeLog "calling implicit '$hookName' function hook"; - "$hookName"; - else - if type -p "$hookName" > /dev/null; then - nixTalkativeLog "sourcing implicit '$hookName' script hook"; - source "$hookName"; - else - if [ -n "${!hookName:-}" ]; then - nixTalkativeLog "evaling implicit '$hookName' string hook"; - eval "${!hookName}"; - else - return "$def"; - fi; - fi; - fi -} -_defaultUnpack () -{ - - local fn="$1"; - local destination; - if [ -d "$fn" ]; then - destination="$(stripHash "$fn")"; - if [ -e "$destination" ]; then - echo "Cannot copy $fn to $destination: destination already exists!"; - echo "Did you specify two \"srcs\" with the same \"name\"?"; - return 1; - fi; - cp -r --preserve=mode,timestamps --reflink=auto -- "$fn" "$destination"; - else - case "$fn" in - *.tar.xz | *.tar.lzma | *.txz) - ( XZ_OPT="--threads=$NIX_BUILD_CORES" xz -d < "$fn"; - true ) | tar xf - --mode=+w --warning=no-timestamp - ;; - *.tar | *.tar.* | *.tgz | *.tbz2 | *.tbz) - tar xf "$fn" --mode=+w --warning=no-timestamp - ;; - *) - return 1 - ;; - esac; - fi -} -_doStrip () -{ - - local -ra flags=(dontStripHost dontStripTarget); - local -ra debugDirs=(stripDebugList stripDebugListTarget); - local -ra allDirs=(stripAllList stripAllListTarget); - local -ra stripCmds=(STRIP STRIP_FOR_TARGET); - local -ra ranlibCmds=(RANLIB RANLIB_FOR_TARGET); - stripDebugList=${stripDebugList[*]:-lib lib32 lib64 libexec bin sbin Applications Library/Frameworks}; - stripDebugListTarget=${stripDebugListTarget[*]:-}; - stripAllList=${stripAllList[*]:-}; - stripAllListTarget=${stripAllListTarget[*]:-}; - local i; - for i in ${!stripCmds[@]}; - do - local -n flag="${flags[$i]}"; - local -n debugDirList="${debugDirs[$i]}"; - local -n allDirList="${allDirs[$i]}"; - local -n stripCmd="${stripCmds[$i]}"; - local -n ranlibCmd="${ranlibCmds[$i]}"; - if [[ -n "${dontStrip-}" || -n "${flag-}" ]] || ! type -f "${stripCmd-}" 2> /dev/null 1>&2; then - continue; - fi; - stripDirs "$stripCmd" "$ranlibCmd" "$debugDirList" "${stripDebugFlags[*]:--S -p}"; - stripDirs "$stripCmd" "$ranlibCmd" "$allDirList" "${stripAllFlags[*]:--s -p}"; - done -} -_eval () -{ - - if declare -F "$1" > /dev/null 2>&1; then - "$@"; - else - eval "$1"; - fi -} -_logHook () -{ - - if [[ -z ${NIX_LOG_FD-} ]]; then - return; - fi; - local hookKind="$1"; - local hookExpr="$2"; - shift 2; - if declare -F "$hookExpr" > /dev/null 2>&1; then - nixTalkativeLog "calling '$hookKind' function hook '$hookExpr'" "$@"; - else - if type -p "$hookExpr" > /dev/null; then - nixTalkativeLog "sourcing '$hookKind' script hook '$hookExpr'"; - else - if [[ "$hookExpr" != "_callImplicitHook"* ]]; then - local exprToOutput; - if [[ ${NIX_DEBUG:-0} -ge 5 ]]; then - exprToOutput="$hookExpr"; - else - local hookExprLine; - while IFS= read -r hookExprLine; do - hookExprLine="${hookExprLine#"${hookExprLine%%[![:space:]]*}"}"; - if [[ -n "$hookExprLine" ]]; then - exprToOutput+="$hookExprLine\\n "; - fi; - done <<< "$hookExpr"; - exprToOutput="${exprToOutput%%\\n }"; - fi; - nixTalkativeLog "evaling '$hookKind' string hook '$exprToOutput'"; - fi; - fi; - fi -} -_makeSymlinksRelative () -{ - - local symlinkTarget; - if [ "${dontRewriteSymlinks-}" ] || [ ! -e "$prefix" ]; then - return; - fi; - while IFS= read -r -d '' f; do - symlinkTarget=$(readlink "$f"); - if [[ "$symlinkTarget"/ != "$prefix"/* ]]; then - continue; - fi; - if [ ! -e "$symlinkTarget" ]; then - echo "the symlink $f is broken, it points to $symlinkTarget (which is missing)"; - fi; - echo "rewriting symlink $f to be relative to $prefix"; - ln -snrf "$symlinkTarget" "$f"; - done < <(find $prefix -type l -print0) -} -_makeSymlinksRelativeInAllOutputs () -{ - - local output; - for output in $(getAllOutputNames); - do - prefix="${!output}" _makeSymlinksRelative; - done -} -_moveLib64 () -{ - - if [ "${dontMoveLib64-}" = 1 ]; then - return; - fi; - if [ ! -e "$prefix/lib64" -o -L "$prefix/lib64" ]; then - return; - fi; - echo "moving $prefix/lib64/* to $prefix/lib"; - mkdir -p $prefix/lib; - shopt -s dotglob; - for i in $prefix/lib64/*; - do - mv --no-clobber "$i" $prefix/lib; - done; - shopt -u dotglob; - rmdir $prefix/lib64; - ln -s lib $prefix/lib64 -} -_moveSbin () -{ - - if [ "${dontMoveSbin-}" = 1 ]; then - return; - fi; - if [ ! -e "$prefix/sbin" -o -L "$prefix/sbin" ]; then - return; - fi; - echo "moving $prefix/sbin/* to $prefix/bin"; - mkdir -p $prefix/bin; - shopt -s dotglob; - for i in $prefix/sbin/*; - do - mv "$i" $prefix/bin; - done; - shopt -u dotglob; - rmdir $prefix/sbin; - ln -s bin $prefix/sbin -} -_moveSystemdUserUnits () -{ - - if [ "${dontMoveSystemdUserUnits:-0}" = 1 ]; then - return; - fi; - if [ ! -e "${prefix:?}/lib/systemd/user" ]; then - return; - fi; - local source="$prefix/lib/systemd/user"; - local target="$prefix/share/systemd/user"; - echo "moving $source/* to $target"; - mkdir -p "$target"; - ( shopt -s dotglob; - for i in "$source"/*; - do - mv "$i" "$target"; - done ); - rmdir "$source"; - ln -s "$target" "$source" -} -_moveToShare () -{ - - if [ -n "$__structuredAttrs" ]; then - if [ -z "${forceShare-}" ]; then - forceShare=(man doc info); - fi; - else - forceShare=(${forceShare:-man doc info}); - fi; - if [[ -z "$out" ]]; then - return; - fi; - for d in "${forceShare[@]}"; - do - if [ -d "$out/$d" ]; then - if [ -d "$out/share/$d" ]; then - echo "both $d/ and share/$d/ exist!"; - else - echo "moving $out/$d to $out/share/$d"; - mkdir -p $out/share; - mv $out/$d $out/share/; - fi; - fi; - done -} -_multioutConfig () -{ - - if [ "$(getAllOutputNames)" = "out" ] || [ -z "${setOutputFlags-1}" ]; then - return; - fi; - if [ -z "${shareDocName:-}" ]; then - local confScript="${configureScript:-}"; - if [ -z "$confScript" ] && [ -x ./configure ]; then - confScript=./configure; - fi; - if [ -f "$confScript" ]; then - local shareDocName="$(sed -n "s/^PACKAGE_TARNAME='\(.*\)'$/\1/p" < "$confScript")"; - fi; - if [ -z "$shareDocName" ] || echo "$shareDocName" | grep -q '[^a-zA-Z0-9_-]'; then - shareDocName="$(echo "$name" | sed 's/-[^a-zA-Z].*//')"; - fi; - fi; - prependToVar configureFlags --bindir="${!outputBin}"/bin --sbindir="${!outputBin}"/sbin --includedir="${!outputInclude}"/include --mandir="${!outputMan}"/share/man --infodir="${!outputInfo}"/share/info --docdir="${!outputDoc}"/share/doc/"${shareDocName}" --libdir="${!outputLib}"/lib --libexecdir="${!outputLib}"/libexec --localedir="${!outputLib}"/share/locale; - prependToVar installFlags pkgconfigdir="${!outputDev}"/lib/pkgconfig m4datadir="${!outputDev}"/share/aclocal aclocaldir="${!outputDev}"/share/aclocal -} -_multioutDevs () -{ - - if [ "$(getAllOutputNames)" = "out" ] || [ -z "${moveToDev-1}" ]; then - return; - fi; - moveToOutput include "${!outputInclude}"; - moveToOutput lib/pkgconfig "${!outputDev}"; - moveToOutput share/pkgconfig "${!outputDev}"; - moveToOutput lib/cmake "${!outputDev}"; - moveToOutput share/aclocal "${!outputDev}"; - for f in "${!outputDev}"/{lib,share}/pkgconfig/*.pc; - do - echo "Patching '$f' includedir to output ${!outputInclude}"; - sed -i "/^includedir=/s,=\${prefix},=${!outputInclude}," "$f"; - done -} -_multioutDocs () -{ - - local REMOVE=REMOVE; - moveToOutput share/info "${!outputInfo}"; - moveToOutput share/doc "${!outputDoc}"; - moveToOutput share/gtk-doc "${!outputDevdoc}"; - moveToOutput share/devhelp/books "${!outputDevdoc}"; - moveToOutput share/man "${!outputMan}"; - moveToOutput share/man/man3 "${!outputDevman}" -} -_multioutPropagateDev () -{ - - if [ "$(getAllOutputNames)" = "out" ]; then - return; - fi; - local outputFirst; - for outputFirst in $(getAllOutputNames); - do - break; - done; - local propagaterOutput="$outputDev"; - if [ -z "$propagaterOutput" ]; then - propagaterOutput="$outputFirst"; - fi; - if [ -z "${propagatedBuildOutputs+1}" ]; then - local po_dirty="$outputBin $outputInclude $outputLib"; - set +o pipefail; - propagatedBuildOutputs=`echo "$po_dirty" | tr -s ' ' '\n' | grep -v -F "$propagaterOutput" | sort -u | tr '\n' ' ' `; - set -o pipefail; - fi; - if [ -z "$propagatedBuildOutputs" ]; then - return; - fi; - mkdir -p "${!propagaterOutput}"/nix-support; - for output in $propagatedBuildOutputs; - do - echo -n " ${!output}" >> "${!propagaterOutput}"/nix-support/propagated-build-inputs; - done -} -_nixLogWithLevel () -{ - - [[ -z ${NIX_LOG_FD-} || ${NIX_DEBUG:-0} -lt ${1:?} ]] && return 0; - local logLevel; - case "${1:?}" in - 0) - logLevel=ERROR - ;; - 1) - logLevel=WARN - ;; - 2) - logLevel=NOTICE - ;; - 3) - logLevel=INFO - ;; - 4) - logLevel=TALKATIVE - ;; - 5) - logLevel=CHATTY - ;; - 6) - logLevel=DEBUG - ;; - 7) - logLevel=VOMIT - ;; - *) - echo "_nixLogWithLevel: called with invalid log level: ${1:?}" >&"$NIX_LOG_FD"; - return 1 - ;; - esac; - local callerName="${FUNCNAME[2]}"; - if [[ $callerName == "_callImplicitHook" ]]; then - callerName="${hookName:?}"; - fi; - printf "%s: %s: %s\n" "$logLevel" "$callerName" "${2:?}" >&"$NIX_LOG_FD" -} -_overrideFirst () -{ - - if [ -z "${!1-}" ]; then - _assignFirst "$@"; - fi -} -_pruneLibtoolFiles () -{ - - if [ "${dontPruneLibtoolFiles-}" ] || [ ! -e "$prefix" ]; then - return; - fi; - find "$prefix" -type f -name '*.la' -exec grep -q '^# Generated by .*libtool' {} \; -exec grep -q "^old_library=''" {} \; -exec sed -i {} -e "/^dependency_libs='[^']/ c dependency_libs='' #pruned" \; -} -_updateSourceDateEpochFromSourceRoot () -{ - - if [ -n "$sourceRoot" ]; then - updateSourceDateEpoch "$sourceRoot"; - fi -} -activatePackage () -{ - - local pkg="$1"; - local -r hostOffset="$2"; - local -r targetOffset="$3"; - (( hostOffset <= targetOffset )) || exit 1; - if [ -f "$pkg" ]; then - nixTalkativeLog "sourcing setup hook '$pkg'"; - source "$pkg"; - fi; - if [[ -z "${strictDeps-}" || "$hostOffset" -le -1 ]]; then - addToSearchPath _PATH "$pkg/bin"; - fi; - if (( hostOffset <= -1 )); then - addToSearchPath _XDG_DATA_DIRS "$pkg/share"; - fi; - if [[ "$hostOffset" -eq 0 && -d "$pkg/bin" ]]; then - addToSearchPath _HOST_PATH "$pkg/bin"; - fi; - if [[ -f "$pkg/nix-support/setup-hook" ]]; then - nixTalkativeLog "sourcing setup hook '$pkg/nix-support/setup-hook'"; - source "$pkg/nix-support/setup-hook"; - fi -} -addEnvHooks () -{ - - local depHostOffset="$1"; - shift; - local pkgHookVarsSlice="${pkgHookVarVars[$depHostOffset + 1]}[@]"; - local pkgHookVar; - for pkgHookVar in "${!pkgHookVarsSlice}"; - do - eval "${pkgHookVar}s"'+=("$@")'; - done -} -addToSearchPath () -{ - - addToSearchPathWithCustomDelimiter ":" "$@" -} -addToSearchPathWithCustomDelimiter () -{ - - local delimiter="$1"; - local varName="$2"; - local dir="$3"; - if [[ -d "$dir" && "${!varName:+${delimiter}${!varName}${delimiter}}" != *"${delimiter}${dir}${delimiter}"* ]]; then - export "${varName}=${!varName:+${!varName}${delimiter}}${dir}"; - fi -} -appendToVar () -{ - - local -n nameref="$1"; - local useArray type; - if [ -n "$__structuredAttrs" ]; then - useArray=true; - else - useArray=false; - fi; - if type=$(declare -p "$1" 2> /dev/null); then - case "${type#* }" in - -A*) - echo "appendToVar(): ERROR: trying to use appendToVar on an associative array, use variable+=([\"X\"]=\"Y\") instead." 1>&2; - return 1 - ;; - -a*) - useArray=true - ;; - *) - useArray=false - ;; - esac; - fi; - shift; - if $useArray; then - nameref=(${nameref+"${nameref[@]}"} "$@"); - else - nameref="${nameref-} $*"; - fi -} -auditTmpdir () -{ - - local dir="$1"; - [ -e "$dir" ] || return 0; - echo "checking for references to $TMPDIR/ in $dir..."; - local i; - find "$dir" -type f -print0 | while IFS= read -r -d '' i; do - if [[ "$i" =~ .build-id ]]; then - continue; - fi; - if isELF "$i"; then - if { - printf :; - patchelf --print-rpath "$i" - } | grep -q -F ":$TMPDIR/"; then - echo "RPATH of binary $i contains a forbidden reference to $TMPDIR/"; - exit 1; - fi; - fi; - if isScript "$i"; then - if [ -e "$(dirname "$i")/.$(basename "$i")-wrapped" ]; then - if grep -q -F "$TMPDIR/" "$i"; then - echo "wrapper script $i contains a forbidden reference to $TMPDIR/"; - exit 1; - fi; - fi; - fi; - done -} -bintoolsWrapper_addLDVars () -{ - - local role_post; - getHostRoleEnvHook; - if [[ -d "$1/lib64" && ! -L "$1/lib64" ]]; then - export NIX_LDFLAGS${role_post}+=" -L$1/lib64"; - fi; - if [[ -d "$1/lib" ]]; then - local -a glob=($1/lib/lib*); - if [ "${#glob[*]}" -gt 0 ]; then - export NIX_LDFLAGS${role_post}+=" -L$1/lib"; - fi; - fi -} -buildPhase () -{ - - runHook preBuild; - if [[ -z "${makeFlags-}" && -z "${makefile:-}" && ! ( -e Makefile || -e makefile || -e GNUmakefile ) ]]; then - echo "no Makefile or custom buildPhase, doing nothing"; - else - foundMakefile=1; - local flagsArray=(${enableParallelBuilding:+-j${NIX_BUILD_CORES}} SHELL="$SHELL"); - concatTo flagsArray makeFlags makeFlagsArray buildFlags buildFlagsArray; - echoCmd 'build flags' "${flagsArray[@]}"; - make ${makefile:+-f $makefile} "${flagsArray[@]}"; - unset flagsArray; - fi; - runHook postBuild -} -ccWrapper_addCVars () -{ - - local role_post; - getHostRoleEnvHook; - if [ -d "$1/include" ]; then - export NIX_CFLAGS_COMPILE${role_post}+=" -isystem $1/include"; - fi; - if [ -d "$1/Library/Frameworks" ]; then - export NIX_CFLAGS_COMPILE${role_post}+=" -iframework $1/Library/Frameworks"; - fi -} -checkPhase () -{ - - runHook preCheck; - if [[ -z "${foundMakefile:-}" ]]; then - echo "no Makefile or custom checkPhase, doing nothing"; - runHook postCheck; - return; - fi; - if [[ -z "${checkTarget:-}" ]]; then - if make -n ${makefile:+-f $makefile} check > /dev/null 2>&1; then - checkTarget="check"; - else - if make -n ${makefile:+-f $makefile} test > /dev/null 2>&1; then - checkTarget="test"; - fi; - fi; - fi; - if [[ -z "${checkTarget:-}" ]]; then - echo "no check/test target in ${makefile:-Makefile}, doing nothing"; - else - local flagsArray=(${enableParallelChecking:+-j${NIX_BUILD_CORES}} SHELL="$SHELL"); - concatTo flagsArray makeFlags makeFlagsArray checkFlags=VERBOSE=y checkFlagsArray checkTarget; - echoCmd 'check flags' "${flagsArray[@]}"; - make ${makefile:+-f $makefile} "${flagsArray[@]}"; - unset flagsArray; - fi; - runHook postCheck -} -compressManPages () -{ - - local dir="$1"; - if [ -L "$dir"/share ] || [ -L "$dir"/share/man ] || [ ! -d "$dir/share/man" ]; then - return; - fi; - echo "gzipping man pages under $dir/share/man/"; - find "$dir"/share/man/ -type f -a '!' -regex '.*\.\(bz2\|gz\|xz\)$' -print0 | while IFS= read -r -d '' f; do - if gzip -c -n "$f" > "$f".gz; then - rm "$f"; - else - rm "$f".gz; - fi; - done; - find "$dir"/share/man/ -type l -a '!' -regex '.*\.\(bz2\|gz\|xz\)$' -print0 | sort -z | while IFS= read -r -d '' f; do - local target; - target="$(readlink -f "$f")"; - if [ -f "$target".gz ]; then - ln -sf "$target".gz "$f".gz && rm "$f"; - fi; - done -} -concatStringsSep () -{ - - local sep="$1"; - local name="$2"; - local type oldifs; - if type=$(declare -p "$name" 2> /dev/null); then - local -n nameref="$name"; - case "${type#* }" in - -A*) - echo "concatStringsSep(): ERROR: trying to use concatStringsSep on an associative array." 1>&2; - return 1 - ;; - -a*) - local IFS="$(printf '\036')" - ;; - *) - local IFS=" " - ;; - esac; - local ifs_separated="${nameref[*]}"; - echo -n "${ifs_separated//"$IFS"/"$sep"}"; - fi -} -concatTo () -{ - - local -; - set -o noglob; - local -n targetref="$1"; - shift; - local arg default name type; - for arg in "$@"; - do - IFS="=" read -r name default <<< "$arg"; - local -n nameref="$name"; - if [[ -z "${nameref[*]}" && -n "$default" ]]; then - targetref+=("$default"); - else - if type=$(declare -p "$name" 2> /dev/null); then - case "${type#* }" in - -A*) - echo "concatTo(): ERROR: trying to use concatTo on an associative array." 1>&2; - return 1 - ;; - -a*) - targetref+=("${nameref[@]}") - ;; - *) - if [[ "$name" = *"Array" ]]; then - nixErrorLog "concatTo(): $name is not declared as array, treating as a singleton. This will become an error in future"; - targetref+=(${nameref+"${nameref[@]}"}); - else - targetref+=(${nameref-}); - fi - ;; - esac; - fi; - fi; - done -} -configurePhase () -{ - - runHook preConfigure; - : "${configureScript=}"; - if [[ -z "$configureScript" && -x ./configure ]]; then - configureScript=./configure; - fi; - if [ -z "${dontFixLibtool:-}" ]; then - export lt_cv_deplibs_check_method="${lt_cv_deplibs_check_method-pass_all}"; - local i; - find . -iname "ltmain.sh" -print0 | while IFS='' read -r -d '' i; do - echo "fixing libtool script $i"; - fixLibtool "$i"; - done; - CONFIGURE_MTIME_REFERENCE=$(mktemp configure.mtime.reference.XXXXXX); - find . -executable -type f -name configure -exec grep -l 'GNU Libtool is free software; you can redistribute it and/or modify' {} \; -exec touch -r {} "$CONFIGURE_MTIME_REFERENCE" \; -exec sed -i s_/usr/bin/file_file_g {} \; -exec touch -r "$CONFIGURE_MTIME_REFERENCE" {} \;; - rm -f "$CONFIGURE_MTIME_REFERENCE"; - fi; - if [[ -z "${dontAddPrefix:-}" && -n "$prefix" ]]; then - prependToVar configureFlags "${prefixKey:---prefix=}$prefix"; - fi; - if [[ -f "$configureScript" ]]; then - if [ -z "${dontAddDisableDepTrack:-}" ]; then - if grep -q dependency-tracking "$configureScript"; then - prependToVar configureFlags --disable-dependency-tracking; - fi; - fi; - if [ -z "${dontDisableStatic:-}" ]; then - if grep -q enable-static "$configureScript"; then - prependToVar configureFlags --disable-static; - fi; - fi; - if [ -z "${dontPatchShebangsInConfigure:-}" ]; then - patchShebangs --build "$configureScript"; - fi; - fi; - if [ -n "$configureScript" ]; then - local -a flagsArray; - concatTo flagsArray configureFlags configureFlagsArray; - echoCmd 'configure flags' "${flagsArray[@]}"; - $configureScript "${flagsArray[@]}"; - unset flagsArray; - else - echo "no configure script, doing nothing"; - fi; - runHook postConfigure -} -consumeEntire () -{ - - if IFS='' read -r -d '' "$1"; then - echo "consumeEntire(): ERROR: Input null bytes, won't process" 1>&2; - return 1; - fi -} -distPhase () -{ - - runHook preDist; - local flagsArray=(); - concatTo flagsArray distFlags distFlagsArray distTarget=dist; - echo 'dist flags: %q' "${flagsArray[@]}"; - make ${makefile:+-f $makefile} "${flagsArray[@]}"; - if [ "${dontCopyDist:-0}" != 1 ]; then - mkdir -p "$out/tarballs"; - cp -pvd ${tarballs[*]:-*.tar.gz} "$out/tarballs"; - fi; - runHook postDist -} -dumpVars () -{ - - if [ "${noDumpEnvVars:-0}" != 1 ]; then - { - install -m 0600 /dev/null "$NIX_BUILD_TOP/env-vars" && export 2> /dev/null >| "$NIX_BUILD_TOP/env-vars" - } || true; - fi -} -echoCmd () -{ - - printf "%s:" "$1"; - shift; - printf ' %q' "$@"; - echo -} -exitHandler () -{ - - exitCode="$?"; - set +e; - if [ -n "${showBuildStats:-}" ]; then - read -r -d '' -a buildTimes < <(times); - echo "build times:"; - echo "user time for the shell ${buildTimes[0]}"; - echo "system time for the shell ${buildTimes[1]}"; - echo "user time for all child processes ${buildTimes[2]}"; - echo "system time for all child processes ${buildTimes[3]}"; - fi; - if (( "$exitCode" != 0 )); then - runHook failureHook; - if [ -n "${succeedOnFailure:-}" ]; then - echo "build failed with exit code $exitCode (ignored)"; - mkdir -p "$out/nix-support"; - printf "%s" "$exitCode" > "$out/nix-support/failed"; - exit 0; - fi; - else - runHook exitHook; - fi; - return "$exitCode" -} -findInputs () -{ - - local -r pkg="$1"; - local -r hostOffset="$2"; - local -r targetOffset="$3"; - (( hostOffset <= targetOffset )) || exit 1; - local varVar="${pkgAccumVarVars[hostOffset + 1]}"; - local varRef="$varVar[$((targetOffset - hostOffset))]"; - local var="${!varRef}"; - unset -v varVar varRef; - local varSlice="$var[*]"; - case " ${!varSlice-} " in - *" $pkg "*) - return 0 - ;; - esac; - unset -v varSlice; - eval "$var"'+=("$pkg")'; - if ! [ -e "$pkg" ]; then - echo "build input $pkg does not exist" 1>&2; - exit 1; - fi; - function mapOffset () - { - local -r inputOffset="$1"; - local -n outputOffset="$2"; - if (( inputOffset <= 0 )); then - outputOffset=$((inputOffset + hostOffset)); - else - outputOffset=$((inputOffset - 1 + targetOffset)); - fi - }; - local relHostOffset; - for relHostOffset in "${allPlatOffsets[@]}"; - do - local files="${propagatedDepFilesVars[relHostOffset + 1]}"; - local hostOffsetNext; - mapOffset "$relHostOffset" hostOffsetNext; - (( -1 <= hostOffsetNext && hostOffsetNext <= 1 )) || continue; - local relTargetOffset; - for relTargetOffset in "${allPlatOffsets[@]}"; - do - (( "$relHostOffset" <= "$relTargetOffset" )) || continue; - local fileRef="${files}[$relTargetOffset - $relHostOffset]"; - local file="${!fileRef}"; - unset -v fileRef; - local targetOffsetNext; - mapOffset "$relTargetOffset" targetOffsetNext; - (( -1 <= hostOffsetNext && hostOffsetNext <= 1 )) || continue; - [[ -f "$pkg/nix-support/$file" ]] || continue; - local pkgNext; - read -r -d '' pkgNext < "$pkg/nix-support/$file" || true; - for pkgNext in $pkgNext; - do - findInputs "$pkgNext" "$hostOffsetNext" "$targetOffsetNext"; - done; - done; - done -} -fixLibtool () -{ - - local search_path; - for flag in $NIX_LDFLAGS; - do - case $flag in - -L*) - search_path+=" ${flag#-L}" - ;; - esac; - done; - sed -i "$1" -e "s^eval \(sys_lib_search_path=\).*^\1'${search_path:-}'^" -e 's^eval sys_lib_.+search_path=.*^^' -} -fixupPhase () -{ - - local output; - for output in $(getAllOutputNames); - do - if [ -e "${!output}" ]; then - chmod -R u+w,u-s,g-s "${!output}"; - fi; - done; - runHook preFixup; - local output; - for output in $(getAllOutputNames); - do - prefix="${!output}" runHook fixupOutput; - done; - recordPropagatedDependencies; - if [ -n "${setupHook:-}" ]; then - mkdir -p "${!outputDev}/nix-support"; - substituteAll "$setupHook" "${!outputDev}/nix-support/setup-hook"; - fi; - if [ -n "${setupHooks:-}" ]; then - mkdir -p "${!outputDev}/nix-support"; - local hook; - for hook in ${setupHooks[@]}; - do - local content; - consumeEntire content < "$hook"; - substituteAllStream content "file '$hook'" >> "${!outputDev}/nix-support/setup-hook"; - unset -v content; - done; - unset -v hook; - fi; - if [ -n "${propagatedUserEnvPkgs[*]:-}" ]; then - mkdir -p "${!outputBin}/nix-support"; - printWords "${propagatedUserEnvPkgs[@]}" > "${!outputBin}/nix-support/propagated-user-env-packages"; - fi; - runHook postFixup -} -genericBuild () -{ - - export GZIP_NO_TIMESTAMPS=1; - if [ -f "${buildCommandPath:-}" ]; then - source "$buildCommandPath"; - return; - fi; - if [ -n "${buildCommand:-}" ]; then - eval "$buildCommand"; - return; - fi; - if [ -z "${phases[*]:-}" ]; then - phases="${prePhases[*]:-} unpackPhase patchPhase ${preConfigurePhases[*]:-} configurePhase ${preBuildPhases[*]:-} buildPhase checkPhase ${preInstallPhases[*]:-} installPhase ${preFixupPhases[*]:-} fixupPhase installCheckPhase ${preDistPhases[*]:-} distPhase ${postPhases[*]:-}"; - fi; - for curPhase in ${phases[*]}; - do - runPhase "$curPhase"; - done -} -getAllOutputNames () -{ - - if [ -n "$__structuredAttrs" ]; then - echo "${!outputs[*]}"; - else - echo "$outputs"; - fi -} -getHostRole () -{ - - getRole "$hostOffset" -} -getHostRoleEnvHook () -{ - - getRole "$depHostOffset" -} -getRole () -{ - - case $1 in - -1) - role_post='_FOR_BUILD' - ;; - 0) - role_post='' - ;; - 1) - role_post='_FOR_TARGET' - ;; - *) - echo "binutils-wrapper-2.44: used as improper sort of dependency" 1>&2; - return 1 - ;; - esac -} -getTargetRole () -{ - - getRole "$targetOffset" -} -getTargetRoleEnvHook () -{ - - getRole "$depTargetOffset" -} -getTargetRoleWrapper () -{ - - case $targetOffset in - -1) - export NIX_BINTOOLS_WRAPPER_TARGET_BUILD_x86_64_unknown_linux_gnu=1 - ;; - 0) - export NIX_BINTOOLS_WRAPPER_TARGET_HOST_x86_64_unknown_linux_gnu=1 - ;; - 1) - export NIX_BINTOOLS_WRAPPER_TARGET_TARGET_x86_64_unknown_linux_gnu=1 - ;; - *) - echo "binutils-wrapper-2.44: used as improper sort of dependency" 1>&2; - return 1 - ;; - esac -} -installCheckPhase () -{ - - runHook preInstallCheck; - if [[ -z "${foundMakefile:-}" ]]; then - echo "no Makefile or custom installCheckPhase, doing nothing"; - else - if [[ -z "${installCheckTarget:-}" ]] && ! make -n ${makefile:+-f $makefile} "${installCheckTarget:-installcheck}" > /dev/null 2>&1; then - echo "no installcheck target in ${makefile:-Makefile}, doing nothing"; - else - local flagsArray=(${enableParallelChecking:+-j${NIX_BUILD_CORES}} SHELL="$SHELL"); - concatTo flagsArray makeFlags makeFlagsArray installCheckFlags installCheckFlagsArray installCheckTarget=installcheck; - echoCmd 'installcheck flags' "${flagsArray[@]}"; - make ${makefile:+-f $makefile} "${flagsArray[@]}"; - unset flagsArray; - fi; - fi; - runHook postInstallCheck -} -installPhase () -{ - - runHook preInstall; - if [[ -z "${makeFlags-}" && -z "${makefile:-}" && ! ( -e Makefile || -e makefile || -e GNUmakefile ) ]]; then - echo "no Makefile or custom installPhase, doing nothing"; - runHook postInstall; - return; - else - foundMakefile=1; - fi; - if [ -n "$prefix" ]; then - mkdir -p "$prefix"; - fi; - local flagsArray=(${enableParallelInstalling:+-j${NIX_BUILD_CORES}} SHELL="$SHELL"); - concatTo flagsArray makeFlags makeFlagsArray installFlags installFlagsArray installTargets=install; - echoCmd 'install flags' "${flagsArray[@]}"; - make ${makefile:+-f $makefile} "${flagsArray[@]}"; - unset flagsArray; - runHook postInstall -} -isELF () -{ - - local fn="$1"; - local fd; - local magic; - exec {fd}< "$fn"; - read -r -n 4 -u "$fd" magic; - exec {fd}>&-; - if [ "$magic" = 'ELF' ]; then - return 0; - else - return 1; - fi -} -isMachO () -{ - - local fn="$1"; - local fd; - local magic; - exec {fd}< "$fn"; - read -r -n 4 -u "$fd" magic; - exec {fd}>&-; - if [[ "$magic" = $(echo -ne "\xfe\xed\xfa\xcf") || "$magic" = $(echo -ne "\xcf\xfa\xed\xfe") ]]; then - return 0; - else - if [[ "$magic" = $(echo -ne "\xfe\xed\xfa\xce") || "$magic" = $(echo -ne "\xce\xfa\xed\xfe") ]]; then - return 0; - else - if [[ "$magic" = $(echo -ne "\xca\xfe\xba\xbe") || "$magic" = $(echo -ne "\xbe\xba\xfe\xca") ]]; then - return 0; - else - return 1; - fi; - fi; - fi -} -isScript () -{ - - local fn="$1"; - local fd; - local magic; - exec {fd}< "$fn"; - read -r -n 2 -u "$fd" magic; - exec {fd}>&-; - if [[ "$magic" =~ \#! ]]; then - return 0; - else - return 1; - fi -} -mapOffset () -{ - - local -r inputOffset="$1"; - local -n outputOffset="$2"; - if (( inputOffset <= 0 )); then - outputOffset=$((inputOffset + hostOffset)); - else - outputOffset=$((inputOffset - 1 + targetOffset)); - fi -} -moveToOutput () -{ - - local patt="$1"; - local dstOut="$2"; - local output; - for output in $(getAllOutputNames); - do - if [ "${!output}" = "$dstOut" ]; then - continue; - fi; - local srcPath; - for srcPath in "${!output}"/$patt; - do - if [ ! -e "$srcPath" ] && [ ! -L "$srcPath" ]; then - continue; - fi; - if [ "$dstOut" = REMOVE ]; then - echo "Removing $srcPath"; - rm -r "$srcPath"; - else - local dstPath="$dstOut${srcPath#${!output}}"; - echo "Moving $srcPath to $dstPath"; - if [ -d "$dstPath" ] && [ -d "$srcPath" ]; then - rmdir "$srcPath" --ignore-fail-on-non-empty; - if [ -d "$srcPath" ]; then - mv -t "$dstPath" "$srcPath"/*; - rmdir "$srcPath"; - fi; - else - mkdir -p "$(readlink -m "$dstPath/..")"; - mv "$srcPath" "$dstPath"; - fi; - fi; - local srcParent="$(readlink -m "$srcPath/..")"; - if [ -n "$(find "$srcParent" -maxdepth 0 -type d -empty 2> /dev/null)" ]; then - echo "Removing empty $srcParent/ and (possibly) its parents"; - rmdir -p --ignore-fail-on-non-empty "$srcParent" 2> /dev/null || true; - fi; - done; - done -} -nixChattyLog () -{ - - _nixLogWithLevel 5 "$*" -} -nixDebugLog () -{ - - _nixLogWithLevel 6 "$*" -} -nixErrorLog () -{ - - _nixLogWithLevel 0 "$*" -} -nixInfoLog () -{ - - _nixLogWithLevel 3 "$*" -} -nixLog () -{ - - [[ -z ${NIX_LOG_FD-} ]] && return 0; - local callerName="${FUNCNAME[1]}"; - if [[ $callerName == "_callImplicitHook" ]]; then - callerName="${hookName:?}"; - fi; - printf "%s: %s\n" "$callerName" "$*" >&"$NIX_LOG_FD" -} -nixNoticeLog () -{ - - _nixLogWithLevel 2 "$*" -} -nixTalkativeLog () -{ - - _nixLogWithLevel 4 "$*" -} -nixVomitLog () -{ - - _nixLogWithLevel 7 "$*" -} -nixWarnLog () -{ - - _nixLogWithLevel 1 "$*" -} -noBrokenSymlinks () -{ - - local -r output="${1:?}"; - local path; - local pathParent; - local symlinkTarget; - local -i numDanglingSymlinks=0; - local -i numReflexiveSymlinks=0; - local -i numUnreadableSymlinks=0; - if [[ ! -e $output ]]; then - nixWarnLog "skipping non-existent output $output"; - return 0; - fi; - nixInfoLog "running on $output"; - while IFS= read -r -d '' path; do - pathParent="$(dirname "$path")"; - if ! symlinkTarget="$(readlink "$path")"; then - nixErrorLog "the symlink $path is unreadable"; - numUnreadableSymlinks+=1; - continue; - fi; - if [[ $symlinkTarget == /* ]]; then - nixInfoLog "symlink $path points to absolute target $symlinkTarget"; - else - nixInfoLog "symlink $path points to relative target $symlinkTarget"; - symlinkTarget="$(realpath --no-symlinks --canonicalize-missing "$pathParent/$symlinkTarget")"; - fi; - if [[ $symlinkTarget != "$NIX_STORE"/* ]]; then - nixInfoLog "symlink $path points outside the Nix store; ignoring"; - continue; - fi; - if [[ $path == "$symlinkTarget" ]]; then - nixErrorLog "the symlink $path is reflexive"; - numReflexiveSymlinks+=1; - else - if [[ ! -e $symlinkTarget ]]; then - nixErrorLog "the symlink $path points to a missing target: $symlinkTarget"; - numDanglingSymlinks+=1; - else - nixDebugLog "the symlink $path is irreflexive and points to a target which exists"; - fi; - fi; - done < <(find "$output" -type l -print0); - if ((numDanglingSymlinks > 0 || numReflexiveSymlinks > 0 || numUnreadableSymlinks > 0)); then - nixErrorLog "found $numDanglingSymlinks dangling symlinks, $numReflexiveSymlinks reflexive symlinks and $numUnreadableSymlinks unreadable symlinks"; - exit 1; - fi; - return 0 -} -noBrokenSymlinksInAllOutputs () -{ - - if [[ -z ${dontCheckForBrokenSymlinks-} ]]; then - for output in $(getAllOutputNames); - do - noBrokenSymlinks "${!output}"; - done; - fi -} -patchELF () -{ - - local dir="$1"; - [ -e "$dir" ] || return 0; - echo "shrinking RPATHs of ELF executables and libraries in $dir"; - local i; - while IFS= read -r -d '' i; do - if [[ "$i" =~ .build-id ]]; then - continue; - fi; - if ! isELF "$i"; then - continue; - fi; - echo "shrinking $i"; - patchelf --shrink-rpath "$i" || true; - done < <(find "$dir" -type f -print0) -} -patchPhase () -{ - - runHook prePatch; - local -a patchesArray; - concatTo patchesArray patches; - for i in "${patchesArray[@]}"; - do - echo "applying patch $i"; - local uncompress=cat; - case "$i" in - *.gz) - uncompress="gzip -d" - ;; - *.bz2) - uncompress="bzip2 -d" - ;; - *.xz) - uncompress="xz -d" - ;; - *.lzma) - uncompress="lzma -d" - ;; - esac; - local -a flagsArray; - concatTo flagsArray patchFlags=-p1; - $uncompress < "$i" 2>&1 | patch "${flagsArray[@]}"; - done; - runHook postPatch -} -patchShebangs () -{ - - local pathName; - local update=false; - while [[ $# -gt 0 ]]; do - case "$1" in - --host) - pathName=HOST_PATH; - shift - ;; - --build) - pathName=PATH; - shift - ;; - --update) - update=true; - shift - ;; - --) - shift; - break - ;; - -* | --*) - echo "Unknown option $1 supplied to patchShebangs" 1>&2; - return 1 - ;; - *) - break - ;; - esac; - done; - echo "patching script interpreter paths in $@"; - local f; - local oldPath; - local newPath; - local arg0; - local args; - local oldInterpreterLine; - local newInterpreterLine; - if [[ $# -eq 0 ]]; then - echo "No arguments supplied to patchShebangs" 1>&2; - return 0; - fi; - local f; - while IFS= read -r -d '' f; do - isScript "$f" || continue; - read -r oldInterpreterLine < "$f" || [ "$oldInterpreterLine" ]; - read -r oldPath arg0 args <<< "${oldInterpreterLine:2}"; - if [[ -z "${pathName:-}" ]]; then - if [[ -n $strictDeps && $f == "$NIX_STORE"* ]]; then - pathName=HOST_PATH; - else - pathName=PATH; - fi; - fi; - if [[ "$oldPath" == *"/bin/env" ]]; then - if [[ $arg0 == "-S" ]]; then - arg0=${args%% *}; - [[ "$args" == *" "* ]] && args=${args#* } || args=; - newPath="$(PATH="${!pathName}" type -P "env" || true)"; - args="-S $(PATH="${!pathName}" type -P "$arg0" || true) $args"; - else - if [[ $arg0 == "-"* || $arg0 == *"="* ]]; then - echo "$f: unsupported interpreter directive \"$oldInterpreterLine\" (set dontPatchShebangs=1 and handle shebang patching yourself)" 1>&2; - exit 1; - else - newPath="$(PATH="${!pathName}" type -P "$arg0" || true)"; - fi; - fi; - else - if [[ -z $oldPath ]]; then - oldPath="/bin/sh"; - fi; - newPath="$(PATH="${!pathName}" type -P "$(basename "$oldPath")" || true)"; - args="$arg0 $args"; - fi; - newInterpreterLine="$newPath $args"; - newInterpreterLine=${newInterpreterLine%${newInterpreterLine##*[![:space:]]}}; - if [[ -n "$oldPath" && ( "$update" == true || "${oldPath:0:${#NIX_STORE}}" != "$NIX_STORE" ) ]]; then - if [[ -n "$newPath" && "$newPath" != "$oldPath" ]]; then - echo "$f: interpreter directive changed from \"$oldInterpreterLine\" to \"$newInterpreterLine\""; - escapedInterpreterLine=${newInterpreterLine//\\/\\\\}; - timestamp=$(stat --printf "%y" "$f"); - sed -i -e "1 s|.*|#\!$escapedInterpreterLine|" "$f"; - touch --date "$timestamp" "$f"; - fi; - fi; - done < <(find "$@" -type f -perm -0100 -print0) -} -patchShebangsAuto () -{ - - if [[ -z "${dontPatchShebangs-}" && -e "$prefix" ]]; then - if [[ "$output" != out && "$output" = "$outputDev" ]]; then - patchShebangs --build "$prefix"; - else - patchShebangs --host "$prefix"; - fi; - fi -} -prependToVar () -{ - - local -n nameref="$1"; - local useArray type; - if [ -n "$__structuredAttrs" ]; then - useArray=true; - else - useArray=false; - fi; - if type=$(declare -p "$1" 2> /dev/null); then - case "${type#* }" in - -A*) - echo "prependToVar(): ERROR: trying to use prependToVar on an associative array." 1>&2; - return 1 - ;; - -a*) - useArray=true - ;; - *) - useArray=false - ;; - esac; - fi; - shift; - if $useArray; then - nameref=("$@" ${nameref+"${nameref[@]}"}); - else - nameref="$* ${nameref-}"; - fi -} -printLines () -{ - - (( "$#" > 0 )) || return 0; - printf '%s\n' "$@" -} -printWords () -{ - - (( "$#" > 0 )) || return 0; - printf '%s ' "$@" -} -recordPropagatedDependencies () -{ - - declare -ra flatVars=(depsBuildBuildPropagated propagatedNativeBuildInputs depsBuildTargetPropagated depsHostHostPropagated propagatedBuildInputs depsTargetTargetPropagated); - declare -ra flatFiles=("${propagatedBuildDepFiles[@]}" "${propagatedHostDepFiles[@]}" "${propagatedTargetDepFiles[@]}"); - local propagatedInputsIndex; - for propagatedInputsIndex in "${!flatVars[@]}"; - do - local propagatedInputsSlice="${flatVars[$propagatedInputsIndex]}[@]"; - local propagatedInputsFile="${flatFiles[$propagatedInputsIndex]}"; - [[ -n "${!propagatedInputsSlice}" ]] || continue; - mkdir -p "${!outputDev}/nix-support"; - printWords ${!propagatedInputsSlice} > "${!outputDev}/nix-support/$propagatedInputsFile"; - done -} -runHook () -{ - - local hookName="$1"; - shift; - local hooksSlice="${hookName%Hook}Hooks[@]"; - local hook; - for hook in "_callImplicitHook 0 $hookName" ${!hooksSlice+"${!hooksSlice}"}; - do - _logHook "$hookName" "$hook" "$@"; - _eval "$hook" "$@"; - done; - return 0 -} -runOneHook () -{ - - local hookName="$1"; - shift; - local hooksSlice="${hookName%Hook}Hooks[@]"; - local hook ret=1; - for hook in "_callImplicitHook 1 $hookName" ${!hooksSlice+"${!hooksSlice}"}; - do - _logHook "$hookName" "$hook" "$@"; - if _eval "$hook" "$@"; then - ret=0; - break; - fi; - done; - return "$ret" -} -runPhase () -{ - - local curPhase="$*"; - if [[ "$curPhase" = unpackPhase && -n "${dontUnpack:-}" ]]; then - return; - fi; - if [[ "$curPhase" = patchPhase && -n "${dontPatch:-}" ]]; then - return; - fi; - if [[ "$curPhase" = configurePhase && -n "${dontConfigure:-}" ]]; then - return; - fi; - if [[ "$curPhase" = buildPhase && -n "${dontBuild:-}" ]]; then - return; - fi; - if [[ "$curPhase" = checkPhase && -z "${doCheck:-}" ]]; then - return; - fi; - if [[ "$curPhase" = installPhase && -n "${dontInstall:-}" ]]; then - return; - fi; - if [[ "$curPhase" = fixupPhase && -n "${dontFixup:-}" ]]; then - return; - fi; - if [[ "$curPhase" = installCheckPhase && -z "${doInstallCheck:-}" ]]; then - return; - fi; - if [[ "$curPhase" = distPhase && -z "${doDist:-}" ]]; then - return; - fi; - showPhaseHeader "$curPhase"; - dumpVars; - local startTime endTime; - startTime=$(date +"%s"); - eval "${!curPhase:-$curPhase}"; - endTime=$(date +"%s"); - showPhaseFooter "$curPhase" "$startTime" "$endTime"; - if [ "$curPhase" = unpackPhase ]; then - [ -n "${sourceRoot:-}" ] && chmod +x -- "${sourceRoot}"; - cd -- "${sourceRoot:-.}"; - fi -} -showPhaseFooter () -{ - - local phase="$1"; - local startTime="$2"; - local endTime="$3"; - local delta=$(( endTime - startTime )); - (( delta < 30 )) && return; - local H=$((delta/3600)); - local M=$((delta%3600/60)); - local S=$((delta%60)); - echo -n "$phase completed in "; - (( H > 0 )) && echo -n "$H hours "; - (( M > 0 )) && echo -n "$M minutes "; - echo "$S seconds" -} -showPhaseHeader () -{ - - local phase="$1"; - echo "Running phase: $phase"; - if [[ -z ${NIX_LOG_FD-} ]]; then - return; - fi; - printf "@nix { \"action\": \"setPhase\", \"phase\": \"%s\" }\n" "$phase" >&"$NIX_LOG_FD" -} -stripDirs () -{ - - local cmd="$1"; - local ranlibCmd="$2"; - local paths="$3"; - local stripFlags="$4"; - local excludeFlags=(); - local pathsNew=; - [ -z "$cmd" ] && echo "stripDirs: Strip command is empty" 1>&2 && exit 1; - [ -z "$ranlibCmd" ] && echo "stripDirs: Ranlib command is empty" 1>&2 && exit 1; - local pattern; - if [ -n "${stripExclude:-}" ]; then - for pattern in "${stripExclude[@]}"; - do - excludeFlags+=(-a '!' '(' -name "$pattern" -o -wholename "$prefix/$pattern" ')'); - done; - fi; - local p; - for p in ${paths}; - do - if [ -e "$prefix/$p" ]; then - pathsNew="${pathsNew} $prefix/$p"; - fi; - done; - paths=${pathsNew}; - if [ -n "${paths}" ]; then - echo "stripping (with command $cmd and flags $stripFlags) in $paths"; - local striperr; - striperr="$(mktemp --tmpdir="$TMPDIR" 'striperr.XXXXXX')"; - find $paths -type f "${excludeFlags[@]}" -a '!' -path "$prefix/lib/debug/*" -printf '%D-%i,%p\0' | sort -t, -k1,1 -u -z | cut -d, -f2- -z | xargs -r -0 -n1 -P "$NIX_BUILD_CORES" -- $cmd $stripFlags 2> "$striperr" || exit_code=$?; - [[ "$exit_code" = 123 || -z "$exit_code" ]] || ( cat "$striperr" 1>&2 && exit 1 ); - rm "$striperr"; - find $paths -name '*.a' -type f -exec $ranlibCmd '{}' \; 2> /dev/null; - fi -} -stripHash () -{ - - local strippedName casematchOpt=0; - strippedName="$(basename -- "$1")"; - shopt -q nocasematch && casematchOpt=1; - shopt -u nocasematch; - if [[ "$strippedName" =~ ^[a-z0-9]{32}- ]]; then - echo "${strippedName:33}"; - else - echo "$strippedName"; - fi; - if (( casematchOpt )); then - shopt -s nocasematch; - fi -} -substitute () -{ - - local input="$1"; - local output="$2"; - shift 2; - if [ ! -f "$input" ]; then - echo "substitute(): ERROR: file '$input' does not exist" 1>&2; - return 1; - fi; - local content; - consumeEntire content < "$input"; - if [ -e "$output" ]; then - chmod +w "$output"; - fi; - substituteStream content "file '$input'" "$@" > "$output" -} -substituteAll () -{ - - local input="$1"; - local output="$2"; - local -a args=(); - _allFlags; - substitute "$input" "$output" "${args[@]}" -} -substituteAllInPlace () -{ - - local fileName="$1"; - shift; - substituteAll "$fileName" "$fileName" "$@" -} -substituteAllStream () -{ - - local -a args=(); - _allFlags; - substituteStream "$1" "$2" "${args[@]}" -} -substituteInPlace () -{ - - local -a fileNames=(); - for arg in "$@"; - do - if [[ "$arg" = "--"* ]]; then - break; - fi; - fileNames+=("$arg"); - shift; - done; - if ! [[ "${#fileNames[@]}" -gt 0 ]]; then - echo "substituteInPlace called without any files to operate on (files must come before options!)" 1>&2; - return 1; - fi; - for file in "${fileNames[@]}"; - do - substitute "$file" "$file" "$@"; - done -} -substituteStream () -{ - - local var=$1; - local description=$2; - shift 2; - while (( "$#" )); do - local replace_mode="$1"; - case "$1" in - --replace) - if ! "$_substituteStream_has_warned_replace_deprecation"; then - echo "substituteStream() in derivation $name: WARNING: '--replace' is deprecated, use --replace-{fail,warn,quiet}. ($description)" 1>&2; - _substituteStream_has_warned_replace_deprecation=true; - fi; - replace_mode='--replace-warn' - ;& - --replace-quiet | --replace-warn | --replace-fail) - pattern="$2"; - replacement="$3"; - shift 3; - if ! [[ "${!var}" == *"$pattern"* ]]; then - if [ "$replace_mode" == --replace-warn ]; then - printf "substituteStream() in derivation $name: WARNING: pattern %q doesn't match anything in %s\n" "$pattern" "$description" 1>&2; - else - if [ "$replace_mode" == --replace-fail ]; then - printf "substituteStream() in derivation $name: ERROR: pattern %q doesn't match anything in %s\n" "$pattern" "$description" 1>&2; - return 1; - fi; - fi; - fi; - eval "$var"'=${'"$var"'//"$pattern"/"$replacement"}' - ;; - --subst-var) - local varName="$2"; - shift 2; - if ! [[ "$varName" =~ ^[a-zA-Z_][a-zA-Z0-9_]*$ ]]; then - echo "substituteStream() in derivation $name: ERROR: substitution variables must be valid Bash names, \"$varName\" isn't." 1>&2; - return 1; - fi; - if [ -z ${!varName+x} ]; then - echo "substituteStream() in derivation $name: ERROR: variable \$$varName is unset" 1>&2; - return 1; - fi; - pattern="@$varName@"; - replacement="${!varName}"; - eval "$var"'=${'"$var"'//"$pattern"/"$replacement"}' - ;; - --subst-var-by) - pattern="@$2@"; - replacement="$3"; - eval "$var"'=${'"$var"'//"$pattern"/"$replacement"}'; - shift 3 - ;; - *) - echo "substituteStream() in derivation $name: ERROR: Invalid command line argument: $1" 1>&2; - return 1 - ;; - esac; - done; - printf "%s" "${!var}" -} -unpackFile () -{ - - curSrc="$1"; - echo "unpacking source archive $curSrc"; - if ! runOneHook unpackCmd "$curSrc"; then - echo "do not know how to unpack source archive $curSrc"; - exit 1; - fi -} -unpackPhase () -{ - - runHook preUnpack; - if [ -z "${srcs:-}" ]; then - if [ -z "${src:-}" ]; then - echo 'variable $src or $srcs should point to the source'; - exit 1; - fi; - srcs="$src"; - fi; - local -a srcsArray; - concatTo srcsArray srcs; - local dirsBefore=""; - for i in *; - do - if [ -d "$i" ]; then - dirsBefore="$dirsBefore $i "; - fi; - done; - for i in "${srcsArray[@]}"; - do - unpackFile "$i"; - done; - : "${sourceRoot=}"; - if [ -n "${setSourceRoot:-}" ]; then - runOneHook setSourceRoot; - else - if [ -z "$sourceRoot" ]; then - for i in *; - do - if [ -d "$i" ]; then - case $dirsBefore in - *\ $i\ *) - - ;; - *) - if [ -n "$sourceRoot" ]; then - echo "unpacker produced multiple directories"; - exit 1; - fi; - sourceRoot="$i" - ;; - esac; - fi; - done; - fi; - fi; - if [ -z "$sourceRoot" ]; then - echo "unpacker appears to have produced no directories"; - exit 1; - fi; - echo "source root is $sourceRoot"; - if [ "${dontMakeSourcesWritable:-0}" != 1 ]; then - chmod -R u+w -- "$sourceRoot"; - fi; - runHook postUnpack -} -updateAutotoolsGnuConfigScriptsPhase () -{ - - if [ -n "${dontUpdateAutotoolsGnuConfigScripts-}" ]; then - return; - fi; - for script in config.sub config.guess; - do - for f in $(find . -type f -name "$script"); - do - echo "Updating Autotools / GNU config script to a newer upstream version: $f"; - cp -f "/nix/store/rzdjxxf4jkv3qdsjxkg54fxbma5zr05k-gnu-config-2024-01-01/$script" "$f"; - done; - done -} -updateSourceDateEpoch () -{ - - local path="$1"; - [[ $path == -* ]] && path="./$path"; - local -a res=($(find "$path" -type f -not -newer "$NIX_BUILD_TOP/.." -printf '%T@ "%p"\0' | sort -n --zero-terminated | tail -n1 --zero-terminated | head -c -1)); - local time="${res[0]//\.[0-9]*/}"; - local newestFile="${res[1]}"; - if [ "${time:-0}" -gt "$SOURCE_DATE_EPOCH" ]; then - echo "setting SOURCE_DATE_EPOCH to timestamp $time of file $newestFile"; - export SOURCE_DATE_EPOCH="$time"; - local now="$(date +%s)"; - if [ "$time" -gt $((now - 60)) ]; then - echo "warning: file $newestFile may be generated; SOURCE_DATE_EPOCH may be non-deterministic"; - fi; - fi -} -PATH="$PATH${nix_saved_PATH:+:$nix_saved_PATH}" -XDG_DATA_DIRS="$XDG_DATA_DIRS${nix_saved_XDG_DATA_DIRS:+:$nix_saved_XDG_DATA_DIRS}" -export NIX_BUILD_TOP="$(mktemp -d -t nix-shell.XXXXXX)" -export TMP="$NIX_BUILD_TOP" -export TMPDIR="$NIX_BUILD_TOP" -export TEMP="$NIX_BUILD_TOP" -export TEMPDIR="$NIX_BUILD_TOP" -eval "${shellHook:-}" diff --git a/.gitignore b/.gitignore index 6b16ce2..c9f0071 100644 --- a/.gitignore +++ b/.gitignore @@ -62,4 +62,13 @@ docs/.mkdocs_cache/ # OS-specific -Thumbs.db \ No newline at end of file +Thumbs.db + +.direnv/ + +# Generated protobuf files +api/proto/generated/ + +# Generated Ent ORM files +internal/ent/ +ent/ \ No newline at end of file diff --git a/api/proto/generated/api/proto/identity.pb.go b/api/proto/generated/api/proto/identity.pb.go deleted file mode 100644 index f2efad4..0000000 --- a/api/proto/generated/api/proto/identity.pb.go +++ /dev/null @@ -1,1187 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.36.10 -// protoc v6.30.2 -// source: api/proto/identity.proto - -package identityv1 - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - reflect "reflect" - sync "sync" - unsafe "unsafe" -) - -const ( - // Verify that this generated code is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) - // Verify that runtime/protoimpl is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) -) - -// User represents a user in the system. -type User struct { - state protoimpl.MessageState `protogen:"open.v1"` - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - Email string `protobuf:"bytes,2,opt,name=email,proto3" json:"email,omitempty"` - Username string `protobuf:"bytes,3,opt,name=username,proto3" json:"username,omitempty"` - FirstName string `protobuf:"bytes,4,opt,name=first_name,json=firstName,proto3" json:"first_name,omitempty"` - LastName string `protobuf:"bytes,5,opt,name=last_name,json=lastName,proto3" json:"last_name,omitempty"` - EmailVerified bool `protobuf:"varint,6,opt,name=email_verified,json=emailVerified,proto3" json:"email_verified,omitempty"` - CreatedAt int64 `protobuf:"varint,7,opt,name=created_at,json=createdAt,proto3" json:"created_at,omitempty"` - UpdatedAt int64 `protobuf:"varint,8,opt,name=updated_at,json=updatedAt,proto3" json:"updated_at,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *User) Reset() { - *x = User{} - mi := &file_api_proto_identity_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *User) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*User) ProtoMessage() {} - -func (x *User) ProtoReflect() protoreflect.Message { - mi := &file_api_proto_identity_proto_msgTypes[0] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use User.ProtoReflect.Descriptor instead. -func (*User) Descriptor() ([]byte, []int) { - return file_api_proto_identity_proto_rawDescGZIP(), []int{0} -} - -func (x *User) GetId() string { - if x != nil { - return x.Id - } - return "" -} - -func (x *User) GetEmail() string { - if x != nil { - return x.Email - } - return "" -} - -func (x *User) GetUsername() string { - if x != nil { - return x.Username - } - return "" -} - -func (x *User) GetFirstName() string { - if x != nil { - return x.FirstName - } - return "" -} - -func (x *User) GetLastName() string { - if x != nil { - return x.LastName - } - return "" -} - -func (x *User) GetEmailVerified() bool { - if x != nil { - return x.EmailVerified - } - return false -} - -func (x *User) GetCreatedAt() int64 { - if x != nil { - return x.CreatedAt - } - return 0 -} - -func (x *User) GetUpdatedAt() int64 { - if x != nil { - return x.UpdatedAt - } - return 0 -} - -// GetUserRequest contains a user ID. -type GetUserRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *GetUserRequest) Reset() { - *x = GetUserRequest{} - mi := &file_api_proto_identity_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *GetUserRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*GetUserRequest) ProtoMessage() {} - -func (x *GetUserRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_proto_identity_proto_msgTypes[1] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use GetUserRequest.ProtoReflect.Descriptor instead. -func (*GetUserRequest) Descriptor() ([]byte, []int) { - return file_api_proto_identity_proto_rawDescGZIP(), []int{1} -} - -func (x *GetUserRequest) GetId() string { - if x != nil { - return x.Id - } - return "" -} - -// GetUserResponse contains a user. -type GetUserResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - User *User `protobuf:"bytes,1,opt,name=user,proto3" json:"user,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *GetUserResponse) Reset() { - *x = GetUserResponse{} - mi := &file_api_proto_identity_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *GetUserResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*GetUserResponse) ProtoMessage() {} - -func (x *GetUserResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_proto_identity_proto_msgTypes[2] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use GetUserResponse.ProtoReflect.Descriptor instead. -func (*GetUserResponse) Descriptor() ([]byte, []int) { - return file_api_proto_identity_proto_rawDescGZIP(), []int{2} -} - -func (x *GetUserResponse) GetUser() *User { - if x != nil { - return x.User - } - return nil -} - -// GetUserByEmailRequest contains an email address. -type GetUserByEmailRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Email string `protobuf:"bytes,1,opt,name=email,proto3" json:"email,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *GetUserByEmailRequest) Reset() { - *x = GetUserByEmailRequest{} - mi := &file_api_proto_identity_proto_msgTypes[3] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *GetUserByEmailRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*GetUserByEmailRequest) ProtoMessage() {} - -func (x *GetUserByEmailRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_proto_identity_proto_msgTypes[3] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use GetUserByEmailRequest.ProtoReflect.Descriptor instead. -func (*GetUserByEmailRequest) Descriptor() ([]byte, []int) { - return file_api_proto_identity_proto_rawDescGZIP(), []int{3} -} - -func (x *GetUserByEmailRequest) GetEmail() string { - if x != nil { - return x.Email - } - return "" -} - -// GetUserByEmailResponse contains a user. -type GetUserByEmailResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - User *User `protobuf:"bytes,1,opt,name=user,proto3" json:"user,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *GetUserByEmailResponse) Reset() { - *x = GetUserByEmailResponse{} - mi := &file_api_proto_identity_proto_msgTypes[4] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *GetUserByEmailResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*GetUserByEmailResponse) ProtoMessage() {} - -func (x *GetUserByEmailResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_proto_identity_proto_msgTypes[4] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use GetUserByEmailResponse.ProtoReflect.Descriptor instead. -func (*GetUserByEmailResponse) Descriptor() ([]byte, []int) { - return file_api_proto_identity_proto_rawDescGZIP(), []int{4} -} - -func (x *GetUserByEmailResponse) GetUser() *User { - if x != nil { - return x.User - } - return nil -} - -// CreateUserRequest contains user data for creation. -type CreateUserRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Email string `protobuf:"bytes,1,opt,name=email,proto3" json:"email,omitempty"` - Username string `protobuf:"bytes,2,opt,name=username,proto3" json:"username,omitempty"` - Password string `protobuf:"bytes,3,opt,name=password,proto3" json:"password,omitempty"` - FirstName string `protobuf:"bytes,4,opt,name=first_name,json=firstName,proto3" json:"first_name,omitempty"` - LastName string `protobuf:"bytes,5,opt,name=last_name,json=lastName,proto3" json:"last_name,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *CreateUserRequest) Reset() { - *x = CreateUserRequest{} - mi := &file_api_proto_identity_proto_msgTypes[5] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *CreateUserRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*CreateUserRequest) ProtoMessage() {} - -func (x *CreateUserRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_proto_identity_proto_msgTypes[5] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use CreateUserRequest.ProtoReflect.Descriptor instead. -func (*CreateUserRequest) Descriptor() ([]byte, []int) { - return file_api_proto_identity_proto_rawDescGZIP(), []int{5} -} - -func (x *CreateUserRequest) GetEmail() string { - if x != nil { - return x.Email - } - return "" -} - -func (x *CreateUserRequest) GetUsername() string { - if x != nil { - return x.Username - } - return "" -} - -func (x *CreateUserRequest) GetPassword() string { - if x != nil { - return x.Password - } - return "" -} - -func (x *CreateUserRequest) GetFirstName() string { - if x != nil { - return x.FirstName - } - return "" -} - -func (x *CreateUserRequest) GetLastName() string { - if x != nil { - return x.LastName - } - return "" -} - -// CreateUserResponse contains the created user. -type CreateUserResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - User *User `protobuf:"bytes,1,opt,name=user,proto3" json:"user,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *CreateUserResponse) Reset() { - *x = CreateUserResponse{} - mi := &file_api_proto_identity_proto_msgTypes[6] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *CreateUserResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*CreateUserResponse) ProtoMessage() {} - -func (x *CreateUserResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_proto_identity_proto_msgTypes[6] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use CreateUserResponse.ProtoReflect.Descriptor instead. -func (*CreateUserResponse) Descriptor() ([]byte, []int) { - return file_api_proto_identity_proto_rawDescGZIP(), []int{6} -} - -func (x *CreateUserResponse) GetUser() *User { - if x != nil { - return x.User - } - return nil -} - -// UpdateUserRequest contains user data for update. -type UpdateUserRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - Email *string `protobuf:"bytes,2,opt,name=email,proto3,oneof" json:"email,omitempty"` - Username *string `protobuf:"bytes,3,opt,name=username,proto3,oneof" json:"username,omitempty"` - FirstName *string `protobuf:"bytes,4,opt,name=first_name,json=firstName,proto3,oneof" json:"first_name,omitempty"` - LastName *string `protobuf:"bytes,5,opt,name=last_name,json=lastName,proto3,oneof" json:"last_name,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *UpdateUserRequest) Reset() { - *x = UpdateUserRequest{} - mi := &file_api_proto_identity_proto_msgTypes[7] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *UpdateUserRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*UpdateUserRequest) ProtoMessage() {} - -func (x *UpdateUserRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_proto_identity_proto_msgTypes[7] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use UpdateUserRequest.ProtoReflect.Descriptor instead. -func (*UpdateUserRequest) Descriptor() ([]byte, []int) { - return file_api_proto_identity_proto_rawDescGZIP(), []int{7} -} - -func (x *UpdateUserRequest) GetId() string { - if x != nil { - return x.Id - } - return "" -} - -func (x *UpdateUserRequest) GetEmail() string { - if x != nil && x.Email != nil { - return *x.Email - } - return "" -} - -func (x *UpdateUserRequest) GetUsername() string { - if x != nil && x.Username != nil { - return *x.Username - } - return "" -} - -func (x *UpdateUserRequest) GetFirstName() string { - if x != nil && x.FirstName != nil { - return *x.FirstName - } - return "" -} - -func (x *UpdateUserRequest) GetLastName() string { - if x != nil && x.LastName != nil { - return *x.LastName - } - return "" -} - -// UpdateUserResponse contains the updated user. -type UpdateUserResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - User *User `protobuf:"bytes,1,opt,name=user,proto3" json:"user,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *UpdateUserResponse) Reset() { - *x = UpdateUserResponse{} - mi := &file_api_proto_identity_proto_msgTypes[8] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *UpdateUserResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*UpdateUserResponse) ProtoMessage() {} - -func (x *UpdateUserResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_proto_identity_proto_msgTypes[8] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use UpdateUserResponse.ProtoReflect.Descriptor instead. -func (*UpdateUserResponse) Descriptor() ([]byte, []int) { - return file_api_proto_identity_proto_rawDescGZIP(), []int{8} -} - -func (x *UpdateUserResponse) GetUser() *User { - if x != nil { - return x.User - } - return nil -} - -// DeleteUserRequest contains a user ID. -type DeleteUserRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *DeleteUserRequest) Reset() { - *x = DeleteUserRequest{} - mi := &file_api_proto_identity_proto_msgTypes[9] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *DeleteUserRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*DeleteUserRequest) ProtoMessage() {} - -func (x *DeleteUserRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_proto_identity_proto_msgTypes[9] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use DeleteUserRequest.ProtoReflect.Descriptor instead. -func (*DeleteUserRequest) Descriptor() ([]byte, []int) { - return file_api_proto_identity_proto_rawDescGZIP(), []int{9} -} - -func (x *DeleteUserRequest) GetId() string { - if x != nil { - return x.Id - } - return "" -} - -// DeleteUserResponse indicates success. -type DeleteUserResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *DeleteUserResponse) Reset() { - *x = DeleteUserResponse{} - mi := &file_api_proto_identity_proto_msgTypes[10] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *DeleteUserResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*DeleteUserResponse) ProtoMessage() {} - -func (x *DeleteUserResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_proto_identity_proto_msgTypes[10] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use DeleteUserResponse.ProtoReflect.Descriptor instead. -func (*DeleteUserResponse) Descriptor() ([]byte, []int) { - return file_api_proto_identity_proto_rawDescGZIP(), []int{10} -} - -func (x *DeleteUserResponse) GetSuccess() bool { - if x != nil { - return x.Success - } - return false -} - -// VerifyEmailRequest contains a verification token. -type VerifyEmailRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *VerifyEmailRequest) Reset() { - *x = VerifyEmailRequest{} - mi := &file_api_proto_identity_proto_msgTypes[11] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *VerifyEmailRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*VerifyEmailRequest) ProtoMessage() {} - -func (x *VerifyEmailRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_proto_identity_proto_msgTypes[11] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use VerifyEmailRequest.ProtoReflect.Descriptor instead. -func (*VerifyEmailRequest) Descriptor() ([]byte, []int) { - return file_api_proto_identity_proto_rawDescGZIP(), []int{11} -} - -func (x *VerifyEmailRequest) GetToken() string { - if x != nil { - return x.Token - } - return "" -} - -// VerifyEmailResponse indicates success. -type VerifyEmailResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *VerifyEmailResponse) Reset() { - *x = VerifyEmailResponse{} - mi := &file_api_proto_identity_proto_msgTypes[12] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *VerifyEmailResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*VerifyEmailResponse) ProtoMessage() {} - -func (x *VerifyEmailResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_proto_identity_proto_msgTypes[12] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use VerifyEmailResponse.ProtoReflect.Descriptor instead. -func (*VerifyEmailResponse) Descriptor() ([]byte, []int) { - return file_api_proto_identity_proto_rawDescGZIP(), []int{12} -} - -func (x *VerifyEmailResponse) GetSuccess() bool { - if x != nil { - return x.Success - } - return false -} - -// RequestPasswordResetRequest contains an email address. -type RequestPasswordResetRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Email string `protobuf:"bytes,1,opt,name=email,proto3" json:"email,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *RequestPasswordResetRequest) Reset() { - *x = RequestPasswordResetRequest{} - mi := &file_api_proto_identity_proto_msgTypes[13] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *RequestPasswordResetRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*RequestPasswordResetRequest) ProtoMessage() {} - -func (x *RequestPasswordResetRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_proto_identity_proto_msgTypes[13] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use RequestPasswordResetRequest.ProtoReflect.Descriptor instead. -func (*RequestPasswordResetRequest) Descriptor() ([]byte, []int) { - return file_api_proto_identity_proto_rawDescGZIP(), []int{13} -} - -func (x *RequestPasswordResetRequest) GetEmail() string { - if x != nil { - return x.Email - } - return "" -} - -// RequestPasswordResetResponse indicates success. -type RequestPasswordResetResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *RequestPasswordResetResponse) Reset() { - *x = RequestPasswordResetResponse{} - mi := &file_api_proto_identity_proto_msgTypes[14] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *RequestPasswordResetResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*RequestPasswordResetResponse) ProtoMessage() {} - -func (x *RequestPasswordResetResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_proto_identity_proto_msgTypes[14] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use RequestPasswordResetResponse.ProtoReflect.Descriptor instead. -func (*RequestPasswordResetResponse) Descriptor() ([]byte, []int) { - return file_api_proto_identity_proto_rawDescGZIP(), []int{14} -} - -func (x *RequestPasswordResetResponse) GetSuccess() bool { - if x != nil { - return x.Success - } - return false -} - -// ResetPasswordRequest contains a reset token and new password. -type ResetPasswordRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` - NewPassword string `protobuf:"bytes,2,opt,name=new_password,json=newPassword,proto3" json:"new_password,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *ResetPasswordRequest) Reset() { - *x = ResetPasswordRequest{} - mi := &file_api_proto_identity_proto_msgTypes[15] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *ResetPasswordRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ResetPasswordRequest) ProtoMessage() {} - -func (x *ResetPasswordRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_proto_identity_proto_msgTypes[15] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use ResetPasswordRequest.ProtoReflect.Descriptor instead. -func (*ResetPasswordRequest) Descriptor() ([]byte, []int) { - return file_api_proto_identity_proto_rawDescGZIP(), []int{15} -} - -func (x *ResetPasswordRequest) GetToken() string { - if x != nil { - return x.Token - } - return "" -} - -func (x *ResetPasswordRequest) GetNewPassword() string { - if x != nil { - return x.NewPassword - } - return "" -} - -// ResetPasswordResponse indicates success. -type ResetPasswordResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *ResetPasswordResponse) Reset() { - *x = ResetPasswordResponse{} - mi := &file_api_proto_identity_proto_msgTypes[16] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *ResetPasswordResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ResetPasswordResponse) ProtoMessage() {} - -func (x *ResetPasswordResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_proto_identity_proto_msgTypes[16] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use ResetPasswordResponse.ProtoReflect.Descriptor instead. -func (*ResetPasswordResponse) Descriptor() ([]byte, []int) { - return file_api_proto_identity_proto_rawDescGZIP(), []int{16} -} - -func (x *ResetPasswordResponse) GetSuccess() bool { - if x != nil { - return x.Success - } - return false -} - -// VerifyPasswordRequest contains email and password. -type VerifyPasswordRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Email string `protobuf:"bytes,1,opt,name=email,proto3" json:"email,omitempty"` - Password string `protobuf:"bytes,2,opt,name=password,proto3" json:"password,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *VerifyPasswordRequest) Reset() { - *x = VerifyPasswordRequest{} - mi := &file_api_proto_identity_proto_msgTypes[17] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *VerifyPasswordRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*VerifyPasswordRequest) ProtoMessage() {} - -func (x *VerifyPasswordRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_proto_identity_proto_msgTypes[17] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use VerifyPasswordRequest.ProtoReflect.Descriptor instead. -func (*VerifyPasswordRequest) Descriptor() ([]byte, []int) { - return file_api_proto_identity_proto_rawDescGZIP(), []int{17} -} - -func (x *VerifyPasswordRequest) GetEmail() string { - if x != nil { - return x.Email - } - return "" -} - -func (x *VerifyPasswordRequest) GetPassword() string { - if x != nil { - return x.Password - } - return "" -} - -// VerifyPasswordResponse contains the user if password is valid. -type VerifyPasswordResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - User *User `protobuf:"bytes,1,opt,name=user,proto3" json:"user,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *VerifyPasswordResponse) Reset() { - *x = VerifyPasswordResponse{} - mi := &file_api_proto_identity_proto_msgTypes[18] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *VerifyPasswordResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*VerifyPasswordResponse) ProtoMessage() {} - -func (x *VerifyPasswordResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_proto_identity_proto_msgTypes[18] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use VerifyPasswordResponse.ProtoReflect.Descriptor instead. -func (*VerifyPasswordResponse) Descriptor() ([]byte, []int) { - return file_api_proto_identity_proto_rawDescGZIP(), []int{18} -} - -func (x *VerifyPasswordResponse) GetUser() *User { - if x != nil { - return x.User - } - return nil -} - -var File_api_proto_identity_proto protoreflect.FileDescriptor - -const file_api_proto_identity_proto_rawDesc = "" + - "\n" + - "\x18api/proto/identity.proto\x12\videntity.v1\"\xe9\x01\n" + - "\x04User\x12\x0e\n" + - "\x02id\x18\x01 \x01(\tR\x02id\x12\x14\n" + - "\x05email\x18\x02 \x01(\tR\x05email\x12\x1a\n" + - "\busername\x18\x03 \x01(\tR\busername\x12\x1d\n" + - "\n" + - "first_name\x18\x04 \x01(\tR\tfirstName\x12\x1b\n" + - "\tlast_name\x18\x05 \x01(\tR\blastName\x12%\n" + - "\x0eemail_verified\x18\x06 \x01(\bR\remailVerified\x12\x1d\n" + - "\n" + - "created_at\x18\a \x01(\x03R\tcreatedAt\x12\x1d\n" + - "\n" + - "updated_at\x18\b \x01(\x03R\tupdatedAt\" \n" + - "\x0eGetUserRequest\x12\x0e\n" + - "\x02id\x18\x01 \x01(\tR\x02id\"8\n" + - "\x0fGetUserResponse\x12%\n" + - "\x04user\x18\x01 \x01(\v2\x11.identity.v1.UserR\x04user\"-\n" + - "\x15GetUserByEmailRequest\x12\x14\n" + - "\x05email\x18\x01 \x01(\tR\x05email\"?\n" + - "\x16GetUserByEmailResponse\x12%\n" + - "\x04user\x18\x01 \x01(\v2\x11.identity.v1.UserR\x04user\"\x9d\x01\n" + - "\x11CreateUserRequest\x12\x14\n" + - "\x05email\x18\x01 \x01(\tR\x05email\x12\x1a\n" + - "\busername\x18\x02 \x01(\tR\busername\x12\x1a\n" + - "\bpassword\x18\x03 \x01(\tR\bpassword\x12\x1d\n" + - "\n" + - "first_name\x18\x04 \x01(\tR\tfirstName\x12\x1b\n" + - "\tlast_name\x18\x05 \x01(\tR\blastName\";\n" + - "\x12CreateUserResponse\x12%\n" + - "\x04user\x18\x01 \x01(\v2\x11.identity.v1.UserR\x04user\"\xd9\x01\n" + - "\x11UpdateUserRequest\x12\x0e\n" + - "\x02id\x18\x01 \x01(\tR\x02id\x12\x19\n" + - "\x05email\x18\x02 \x01(\tH\x00R\x05email\x88\x01\x01\x12\x1f\n" + - "\busername\x18\x03 \x01(\tH\x01R\busername\x88\x01\x01\x12\"\n" + - "\n" + - "first_name\x18\x04 \x01(\tH\x02R\tfirstName\x88\x01\x01\x12 \n" + - "\tlast_name\x18\x05 \x01(\tH\x03R\blastName\x88\x01\x01B\b\n" + - "\x06_emailB\v\n" + - "\t_usernameB\r\n" + - "\v_first_nameB\f\n" + - "\n" + - "_last_name\";\n" + - "\x12UpdateUserResponse\x12%\n" + - "\x04user\x18\x01 \x01(\v2\x11.identity.v1.UserR\x04user\"#\n" + - "\x11DeleteUserRequest\x12\x0e\n" + - "\x02id\x18\x01 \x01(\tR\x02id\".\n" + - "\x12DeleteUserResponse\x12\x18\n" + - "\asuccess\x18\x01 \x01(\bR\asuccess\"*\n" + - "\x12VerifyEmailRequest\x12\x14\n" + - "\x05token\x18\x01 \x01(\tR\x05token\"/\n" + - "\x13VerifyEmailResponse\x12\x18\n" + - "\asuccess\x18\x01 \x01(\bR\asuccess\"3\n" + - "\x1bRequestPasswordResetRequest\x12\x14\n" + - "\x05email\x18\x01 \x01(\tR\x05email\"8\n" + - "\x1cRequestPasswordResetResponse\x12\x18\n" + - "\asuccess\x18\x01 \x01(\bR\asuccess\"O\n" + - "\x14ResetPasswordRequest\x12\x14\n" + - "\x05token\x18\x01 \x01(\tR\x05token\x12!\n" + - "\fnew_password\x18\x02 \x01(\tR\vnewPassword\"1\n" + - "\x15ResetPasswordResponse\x12\x18\n" + - "\asuccess\x18\x01 \x01(\bR\asuccess\"I\n" + - "\x15VerifyPasswordRequest\x12\x14\n" + - "\x05email\x18\x01 \x01(\tR\x05email\x12\x1a\n" + - "\bpassword\x18\x02 \x01(\tR\bpassword\"?\n" + - "\x16VerifyPasswordResponse\x12%\n" + - "\x04user\x18\x01 \x01(\v2\x11.identity.v1.UserR\x04user2\x91\x06\n" + - "\x0fIdentityService\x12D\n" + - "\aGetUser\x12\x1b.identity.v1.GetUserRequest\x1a\x1c.identity.v1.GetUserResponse\x12Y\n" + - "\x0eGetUserByEmail\x12\".identity.v1.GetUserByEmailRequest\x1a#.identity.v1.GetUserByEmailResponse\x12M\n" + - "\n" + - "CreateUser\x12\x1e.identity.v1.CreateUserRequest\x1a\x1f.identity.v1.CreateUserResponse\x12M\n" + - "\n" + - "UpdateUser\x12\x1e.identity.v1.UpdateUserRequest\x1a\x1f.identity.v1.UpdateUserResponse\x12M\n" + - "\n" + - "DeleteUser\x12\x1e.identity.v1.DeleteUserRequest\x1a\x1f.identity.v1.DeleteUserResponse\x12P\n" + - "\vVerifyEmail\x12\x1f.identity.v1.VerifyEmailRequest\x1a .identity.v1.VerifyEmailResponse\x12k\n" + - "\x14RequestPasswordReset\x12(.identity.v1.RequestPasswordResetRequest\x1a).identity.v1.RequestPasswordResetResponse\x12V\n" + - "\rResetPassword\x12!.identity.v1.ResetPasswordRequest\x1a\".identity.v1.ResetPasswordResponse\x12Y\n" + - "\x0eVerifyPassword\x12\".identity.v1.VerifyPasswordRequest\x1a#.identity.v1.VerifyPasswordResponseBMZKgit.dcentral.systems/toolz/goplt/api/proto/generated/identity/v1;identityv1b\x06proto3" - -var ( - file_api_proto_identity_proto_rawDescOnce sync.Once - file_api_proto_identity_proto_rawDescData []byte -) - -func file_api_proto_identity_proto_rawDescGZIP() []byte { - file_api_proto_identity_proto_rawDescOnce.Do(func() { - file_api_proto_identity_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_api_proto_identity_proto_rawDesc), len(file_api_proto_identity_proto_rawDesc))) - }) - return file_api_proto_identity_proto_rawDescData -} - -var file_api_proto_identity_proto_msgTypes = make([]protoimpl.MessageInfo, 19) -var file_api_proto_identity_proto_goTypes = []any{ - (*User)(nil), // 0: identity.v1.User - (*GetUserRequest)(nil), // 1: identity.v1.GetUserRequest - (*GetUserResponse)(nil), // 2: identity.v1.GetUserResponse - (*GetUserByEmailRequest)(nil), // 3: identity.v1.GetUserByEmailRequest - (*GetUserByEmailResponse)(nil), // 4: identity.v1.GetUserByEmailResponse - (*CreateUserRequest)(nil), // 5: identity.v1.CreateUserRequest - (*CreateUserResponse)(nil), // 6: identity.v1.CreateUserResponse - (*UpdateUserRequest)(nil), // 7: identity.v1.UpdateUserRequest - (*UpdateUserResponse)(nil), // 8: identity.v1.UpdateUserResponse - (*DeleteUserRequest)(nil), // 9: identity.v1.DeleteUserRequest - (*DeleteUserResponse)(nil), // 10: identity.v1.DeleteUserResponse - (*VerifyEmailRequest)(nil), // 11: identity.v1.VerifyEmailRequest - (*VerifyEmailResponse)(nil), // 12: identity.v1.VerifyEmailResponse - (*RequestPasswordResetRequest)(nil), // 13: identity.v1.RequestPasswordResetRequest - (*RequestPasswordResetResponse)(nil), // 14: identity.v1.RequestPasswordResetResponse - (*ResetPasswordRequest)(nil), // 15: identity.v1.ResetPasswordRequest - (*ResetPasswordResponse)(nil), // 16: identity.v1.ResetPasswordResponse - (*VerifyPasswordRequest)(nil), // 17: identity.v1.VerifyPasswordRequest - (*VerifyPasswordResponse)(nil), // 18: identity.v1.VerifyPasswordResponse -} -var file_api_proto_identity_proto_depIdxs = []int32{ - 0, // 0: identity.v1.GetUserResponse.user:type_name -> identity.v1.User - 0, // 1: identity.v1.GetUserByEmailResponse.user:type_name -> identity.v1.User - 0, // 2: identity.v1.CreateUserResponse.user:type_name -> identity.v1.User - 0, // 3: identity.v1.UpdateUserResponse.user:type_name -> identity.v1.User - 0, // 4: identity.v1.VerifyPasswordResponse.user:type_name -> identity.v1.User - 1, // 5: identity.v1.IdentityService.GetUser:input_type -> identity.v1.GetUserRequest - 3, // 6: identity.v1.IdentityService.GetUserByEmail:input_type -> identity.v1.GetUserByEmailRequest - 5, // 7: identity.v1.IdentityService.CreateUser:input_type -> identity.v1.CreateUserRequest - 7, // 8: identity.v1.IdentityService.UpdateUser:input_type -> identity.v1.UpdateUserRequest - 9, // 9: identity.v1.IdentityService.DeleteUser:input_type -> identity.v1.DeleteUserRequest - 11, // 10: identity.v1.IdentityService.VerifyEmail:input_type -> identity.v1.VerifyEmailRequest - 13, // 11: identity.v1.IdentityService.RequestPasswordReset:input_type -> identity.v1.RequestPasswordResetRequest - 15, // 12: identity.v1.IdentityService.ResetPassword:input_type -> identity.v1.ResetPasswordRequest - 17, // 13: identity.v1.IdentityService.VerifyPassword:input_type -> identity.v1.VerifyPasswordRequest - 2, // 14: identity.v1.IdentityService.GetUser:output_type -> identity.v1.GetUserResponse - 4, // 15: identity.v1.IdentityService.GetUserByEmail:output_type -> identity.v1.GetUserByEmailResponse - 6, // 16: identity.v1.IdentityService.CreateUser:output_type -> identity.v1.CreateUserResponse - 8, // 17: identity.v1.IdentityService.UpdateUser:output_type -> identity.v1.UpdateUserResponse - 10, // 18: identity.v1.IdentityService.DeleteUser:output_type -> identity.v1.DeleteUserResponse - 12, // 19: identity.v1.IdentityService.VerifyEmail:output_type -> identity.v1.VerifyEmailResponse - 14, // 20: identity.v1.IdentityService.RequestPasswordReset:output_type -> identity.v1.RequestPasswordResetResponse - 16, // 21: identity.v1.IdentityService.ResetPassword:output_type -> identity.v1.ResetPasswordResponse - 18, // 22: identity.v1.IdentityService.VerifyPassword:output_type -> identity.v1.VerifyPasswordResponse - 14, // [14:23] is the sub-list for method output_type - 5, // [5:14] is the sub-list for method input_type - 5, // [5:5] is the sub-list for extension type_name - 5, // [5:5] is the sub-list for extension extendee - 0, // [0:5] is the sub-list for field type_name -} - -func init() { file_api_proto_identity_proto_init() } -func file_api_proto_identity_proto_init() { - if File_api_proto_identity_proto != nil { - return - } - file_api_proto_identity_proto_msgTypes[7].OneofWrappers = []any{} - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: unsafe.Slice(unsafe.StringData(file_api_proto_identity_proto_rawDesc), len(file_api_proto_identity_proto_rawDesc)), - NumEnums: 0, - NumMessages: 19, - NumExtensions: 0, - NumServices: 1, - }, - GoTypes: file_api_proto_identity_proto_goTypes, - DependencyIndexes: file_api_proto_identity_proto_depIdxs, - MessageInfos: file_api_proto_identity_proto_msgTypes, - }.Build() - File_api_proto_identity_proto = out.File - file_api_proto_identity_proto_goTypes = nil - file_api_proto_identity_proto_depIdxs = nil -} diff --git a/api/proto/generated/api/proto/identity_grpc.pb.go b/api/proto/generated/api/proto/identity_grpc.pb.go deleted file mode 100644 index 1bf7882..0000000 --- a/api/proto/generated/api/proto/identity_grpc.pb.go +++ /dev/null @@ -1,447 +0,0 @@ -// Code generated by protoc-gen-go-grpc. DO NOT EDIT. -// versions: -// - protoc-gen-go-grpc v1.5.1 -// - protoc v6.30.2 -// source: api/proto/identity.proto - -package identityv1 - -import ( - context "context" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" -) - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -// Requires gRPC-Go v1.64.0 or later. -const _ = grpc.SupportPackageIsVersion9 - -const ( - IdentityService_GetUser_FullMethodName = "/identity.v1.IdentityService/GetUser" - IdentityService_GetUserByEmail_FullMethodName = "/identity.v1.IdentityService/GetUserByEmail" - IdentityService_CreateUser_FullMethodName = "/identity.v1.IdentityService/CreateUser" - IdentityService_UpdateUser_FullMethodName = "/identity.v1.IdentityService/UpdateUser" - IdentityService_DeleteUser_FullMethodName = "/identity.v1.IdentityService/DeleteUser" - IdentityService_VerifyEmail_FullMethodName = "/identity.v1.IdentityService/VerifyEmail" - IdentityService_RequestPasswordReset_FullMethodName = "/identity.v1.IdentityService/RequestPasswordReset" - IdentityService_ResetPassword_FullMethodName = "/identity.v1.IdentityService/ResetPassword" - IdentityService_VerifyPassword_FullMethodName = "/identity.v1.IdentityService/VerifyPassword" -) - -// IdentityServiceClient is the client API for IdentityService service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. -// -// IdentityService provides user management operations. -type IdentityServiceClient interface { - // GetUser retrieves a user by ID. - GetUser(ctx context.Context, in *GetUserRequest, opts ...grpc.CallOption) (*GetUserResponse, error) - // GetUserByEmail retrieves a user by email address. - GetUserByEmail(ctx context.Context, in *GetUserByEmailRequest, opts ...grpc.CallOption) (*GetUserByEmailResponse, error) - // CreateUser creates a new user. - CreateUser(ctx context.Context, in *CreateUserRequest, opts ...grpc.CallOption) (*CreateUserResponse, error) - // UpdateUser updates an existing user. - UpdateUser(ctx context.Context, in *UpdateUserRequest, opts ...grpc.CallOption) (*UpdateUserResponse, error) - // DeleteUser deletes a user. - DeleteUser(ctx context.Context, in *DeleteUserRequest, opts ...grpc.CallOption) (*DeleteUserResponse, error) - // VerifyEmail verifies a user's email address using a verification token. - VerifyEmail(ctx context.Context, in *VerifyEmailRequest, opts ...grpc.CallOption) (*VerifyEmailResponse, error) - // RequestPasswordReset requests a password reset token. - RequestPasswordReset(ctx context.Context, in *RequestPasswordResetRequest, opts ...grpc.CallOption) (*RequestPasswordResetResponse, error) - // ResetPassword resets a user's password using a reset token. - ResetPassword(ctx context.Context, in *ResetPasswordRequest, opts ...grpc.CallOption) (*ResetPasswordResponse, error) - // VerifyPassword verifies a user's password. - VerifyPassword(ctx context.Context, in *VerifyPasswordRequest, opts ...grpc.CallOption) (*VerifyPasswordResponse, error) -} - -type identityServiceClient struct { - cc grpc.ClientConnInterface -} - -func NewIdentityServiceClient(cc grpc.ClientConnInterface) IdentityServiceClient { - return &identityServiceClient{cc} -} - -func (c *identityServiceClient) GetUser(ctx context.Context, in *GetUserRequest, opts ...grpc.CallOption) (*GetUserResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(GetUserResponse) - err := c.cc.Invoke(ctx, IdentityService_GetUser_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *identityServiceClient) GetUserByEmail(ctx context.Context, in *GetUserByEmailRequest, opts ...grpc.CallOption) (*GetUserByEmailResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(GetUserByEmailResponse) - err := c.cc.Invoke(ctx, IdentityService_GetUserByEmail_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *identityServiceClient) CreateUser(ctx context.Context, in *CreateUserRequest, opts ...grpc.CallOption) (*CreateUserResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(CreateUserResponse) - err := c.cc.Invoke(ctx, IdentityService_CreateUser_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *identityServiceClient) UpdateUser(ctx context.Context, in *UpdateUserRequest, opts ...grpc.CallOption) (*UpdateUserResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(UpdateUserResponse) - err := c.cc.Invoke(ctx, IdentityService_UpdateUser_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *identityServiceClient) DeleteUser(ctx context.Context, in *DeleteUserRequest, opts ...grpc.CallOption) (*DeleteUserResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(DeleteUserResponse) - err := c.cc.Invoke(ctx, IdentityService_DeleteUser_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *identityServiceClient) VerifyEmail(ctx context.Context, in *VerifyEmailRequest, opts ...grpc.CallOption) (*VerifyEmailResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(VerifyEmailResponse) - err := c.cc.Invoke(ctx, IdentityService_VerifyEmail_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *identityServiceClient) RequestPasswordReset(ctx context.Context, in *RequestPasswordResetRequest, opts ...grpc.CallOption) (*RequestPasswordResetResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(RequestPasswordResetResponse) - err := c.cc.Invoke(ctx, IdentityService_RequestPasswordReset_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *identityServiceClient) ResetPassword(ctx context.Context, in *ResetPasswordRequest, opts ...grpc.CallOption) (*ResetPasswordResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(ResetPasswordResponse) - err := c.cc.Invoke(ctx, IdentityService_ResetPassword_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *identityServiceClient) VerifyPassword(ctx context.Context, in *VerifyPasswordRequest, opts ...grpc.CallOption) (*VerifyPasswordResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(VerifyPasswordResponse) - err := c.cc.Invoke(ctx, IdentityService_VerifyPassword_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -// IdentityServiceServer is the server API for IdentityService service. -// All implementations must embed UnimplementedIdentityServiceServer -// for forward compatibility. -// -// IdentityService provides user management operations. -type IdentityServiceServer interface { - // GetUser retrieves a user by ID. - GetUser(context.Context, *GetUserRequest) (*GetUserResponse, error) - // GetUserByEmail retrieves a user by email address. - GetUserByEmail(context.Context, *GetUserByEmailRequest) (*GetUserByEmailResponse, error) - // CreateUser creates a new user. - CreateUser(context.Context, *CreateUserRequest) (*CreateUserResponse, error) - // UpdateUser updates an existing user. - UpdateUser(context.Context, *UpdateUserRequest) (*UpdateUserResponse, error) - // DeleteUser deletes a user. - DeleteUser(context.Context, *DeleteUserRequest) (*DeleteUserResponse, error) - // VerifyEmail verifies a user's email address using a verification token. - VerifyEmail(context.Context, *VerifyEmailRequest) (*VerifyEmailResponse, error) - // RequestPasswordReset requests a password reset token. - RequestPasswordReset(context.Context, *RequestPasswordResetRequest) (*RequestPasswordResetResponse, error) - // ResetPassword resets a user's password using a reset token. - ResetPassword(context.Context, *ResetPasswordRequest) (*ResetPasswordResponse, error) - // VerifyPassword verifies a user's password. - VerifyPassword(context.Context, *VerifyPasswordRequest) (*VerifyPasswordResponse, error) - mustEmbedUnimplementedIdentityServiceServer() -} - -// UnimplementedIdentityServiceServer must be embedded to have -// forward compatible implementations. -// -// NOTE: this should be embedded by value instead of pointer to avoid a nil -// pointer dereference when methods are called. -type UnimplementedIdentityServiceServer struct{} - -func (UnimplementedIdentityServiceServer) GetUser(context.Context, *GetUserRequest) (*GetUserResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetUser not implemented") -} -func (UnimplementedIdentityServiceServer) GetUserByEmail(context.Context, *GetUserByEmailRequest) (*GetUserByEmailResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetUserByEmail not implemented") -} -func (UnimplementedIdentityServiceServer) CreateUser(context.Context, *CreateUserRequest) (*CreateUserResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method CreateUser not implemented") -} -func (UnimplementedIdentityServiceServer) UpdateUser(context.Context, *UpdateUserRequest) (*UpdateUserResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UpdateUser not implemented") -} -func (UnimplementedIdentityServiceServer) DeleteUser(context.Context, *DeleteUserRequest) (*DeleteUserResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method DeleteUser not implemented") -} -func (UnimplementedIdentityServiceServer) VerifyEmail(context.Context, *VerifyEmailRequest) (*VerifyEmailResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method VerifyEmail not implemented") -} -func (UnimplementedIdentityServiceServer) RequestPasswordReset(context.Context, *RequestPasswordResetRequest) (*RequestPasswordResetResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method RequestPasswordReset not implemented") -} -func (UnimplementedIdentityServiceServer) ResetPassword(context.Context, *ResetPasswordRequest) (*ResetPasswordResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ResetPassword not implemented") -} -func (UnimplementedIdentityServiceServer) VerifyPassword(context.Context, *VerifyPasswordRequest) (*VerifyPasswordResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method VerifyPassword not implemented") -} -func (UnimplementedIdentityServiceServer) mustEmbedUnimplementedIdentityServiceServer() {} -func (UnimplementedIdentityServiceServer) testEmbeddedByValue() {} - -// UnsafeIdentityServiceServer may be embedded to opt out of forward compatibility for this service. -// Use of this interface is not recommended, as added methods to IdentityServiceServer will -// result in compilation errors. -type UnsafeIdentityServiceServer interface { - mustEmbedUnimplementedIdentityServiceServer() -} - -func RegisterIdentityServiceServer(s grpc.ServiceRegistrar, srv IdentityServiceServer) { - // If the following call pancis, it indicates UnimplementedIdentityServiceServer was - // embedded by pointer and is nil. This will cause panics if an - // unimplemented method is ever invoked, so we test this at initialization - // time to prevent it from happening at runtime later due to I/O. - if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { - t.testEmbeddedByValue() - } - s.RegisterService(&IdentityService_ServiceDesc, srv) -} - -func _IdentityService_GetUser_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(GetUserRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(IdentityServiceServer).GetUser(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: IdentityService_GetUser_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(IdentityServiceServer).GetUser(ctx, req.(*GetUserRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _IdentityService_GetUserByEmail_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(GetUserByEmailRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(IdentityServiceServer).GetUserByEmail(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: IdentityService_GetUserByEmail_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(IdentityServiceServer).GetUserByEmail(ctx, req.(*GetUserByEmailRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _IdentityService_CreateUser_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(CreateUserRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(IdentityServiceServer).CreateUser(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: IdentityService_CreateUser_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(IdentityServiceServer).CreateUser(ctx, req.(*CreateUserRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _IdentityService_UpdateUser_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(UpdateUserRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(IdentityServiceServer).UpdateUser(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: IdentityService_UpdateUser_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(IdentityServiceServer).UpdateUser(ctx, req.(*UpdateUserRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _IdentityService_DeleteUser_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(DeleteUserRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(IdentityServiceServer).DeleteUser(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: IdentityService_DeleteUser_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(IdentityServiceServer).DeleteUser(ctx, req.(*DeleteUserRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _IdentityService_VerifyEmail_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(VerifyEmailRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(IdentityServiceServer).VerifyEmail(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: IdentityService_VerifyEmail_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(IdentityServiceServer).VerifyEmail(ctx, req.(*VerifyEmailRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _IdentityService_RequestPasswordReset_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(RequestPasswordResetRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(IdentityServiceServer).RequestPasswordReset(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: IdentityService_RequestPasswordReset_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(IdentityServiceServer).RequestPasswordReset(ctx, req.(*RequestPasswordResetRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _IdentityService_ResetPassword_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ResetPasswordRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(IdentityServiceServer).ResetPassword(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: IdentityService_ResetPassword_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(IdentityServiceServer).ResetPassword(ctx, req.(*ResetPasswordRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _IdentityService_VerifyPassword_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(VerifyPasswordRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(IdentityServiceServer).VerifyPassword(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: IdentityService_VerifyPassword_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(IdentityServiceServer).VerifyPassword(ctx, req.(*VerifyPasswordRequest)) - } - return interceptor(ctx, in, info, handler) -} - -// IdentityService_ServiceDesc is the grpc.ServiceDesc for IdentityService service. -// It's only intended for direct use with grpc.RegisterService, -// and not to be introspected or modified (even as a copy) -var IdentityService_ServiceDesc = grpc.ServiceDesc{ - ServiceName: "identity.v1.IdentityService", - HandlerType: (*IdentityServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "GetUser", - Handler: _IdentityService_GetUser_Handler, - }, - { - MethodName: "GetUserByEmail", - Handler: _IdentityService_GetUserByEmail_Handler, - }, - { - MethodName: "CreateUser", - Handler: _IdentityService_CreateUser_Handler, - }, - { - MethodName: "UpdateUser", - Handler: _IdentityService_UpdateUser_Handler, - }, - { - MethodName: "DeleteUser", - Handler: _IdentityService_DeleteUser_Handler, - }, - { - MethodName: "VerifyEmail", - Handler: _IdentityService_VerifyEmail_Handler, - }, - { - MethodName: "RequestPasswordReset", - Handler: _IdentityService_RequestPasswordReset_Handler, - }, - { - MethodName: "ResetPassword", - Handler: _IdentityService_ResetPassword_Handler, - }, - { - MethodName: "VerifyPassword", - Handler: _IdentityService_VerifyPassword_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "api/proto/identity.proto", -} diff --git a/api/proto/generated/audit.pb.go b/api/proto/generated/audit.pb.go deleted file mode 100644 index cb9ca82..0000000 --- a/api/proto/generated/audit.pb.go +++ /dev/null @@ -1,486 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.36.10 -// protoc v6.30.2 -// source: audit.proto - -package auditv1 - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - reflect "reflect" - sync "sync" - unsafe "unsafe" -) - -const ( - // Verify that this generated code is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) - // Verify that runtime/protoimpl is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) -) - -// AuditLogEntry represents an audit log entry. -type AuditLogEntry struct { - state protoimpl.MessageState `protogen:"open.v1"` - UserId string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"` - Action string `protobuf:"bytes,2,opt,name=action,proto3" json:"action,omitempty"` // e.g., "user.create", "user.update" - Resource string `protobuf:"bytes,3,opt,name=resource,proto3" json:"resource,omitempty"` // e.g., "user", "role" - ResourceId string `protobuf:"bytes,4,opt,name=resource_id,json=resourceId,proto3" json:"resource_id,omitempty"` - IpAddress string `protobuf:"bytes,5,opt,name=ip_address,json=ipAddress,proto3" json:"ip_address,omitempty"` - UserAgent string `protobuf:"bytes,6,opt,name=user_agent,json=userAgent,proto3" json:"user_agent,omitempty"` - Metadata map[string]string `protobuf:"bytes,7,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - Timestamp int64 `protobuf:"varint,8,opt,name=timestamp,proto3" json:"timestamp,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *AuditLogEntry) Reset() { - *x = AuditLogEntry{} - mi := &file_audit_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *AuditLogEntry) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*AuditLogEntry) ProtoMessage() {} - -func (x *AuditLogEntry) ProtoReflect() protoreflect.Message { - mi := &file_audit_proto_msgTypes[0] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use AuditLogEntry.ProtoReflect.Descriptor instead. -func (*AuditLogEntry) Descriptor() ([]byte, []int) { - return file_audit_proto_rawDescGZIP(), []int{0} -} - -func (x *AuditLogEntry) GetUserId() string { - if x != nil { - return x.UserId - } - return "" -} - -func (x *AuditLogEntry) GetAction() string { - if x != nil { - return x.Action - } - return "" -} - -func (x *AuditLogEntry) GetResource() string { - if x != nil { - return x.Resource - } - return "" -} - -func (x *AuditLogEntry) GetResourceId() string { - if x != nil { - return x.ResourceId - } - return "" -} - -func (x *AuditLogEntry) GetIpAddress() string { - if x != nil { - return x.IpAddress - } - return "" -} - -func (x *AuditLogEntry) GetUserAgent() string { - if x != nil { - return x.UserAgent - } - return "" -} - -func (x *AuditLogEntry) GetMetadata() map[string]string { - if x != nil { - return x.Metadata - } - return nil -} - -func (x *AuditLogEntry) GetTimestamp() int64 { - if x != nil { - return x.Timestamp - } - return 0 -} - -// RecordRequest contains an audit log entry to record. -type RecordRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Entry *AuditLogEntry `protobuf:"bytes,1,opt,name=entry,proto3" json:"entry,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *RecordRequest) Reset() { - *x = RecordRequest{} - mi := &file_audit_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *RecordRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*RecordRequest) ProtoMessage() {} - -func (x *RecordRequest) ProtoReflect() protoreflect.Message { - mi := &file_audit_proto_msgTypes[1] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use RecordRequest.ProtoReflect.Descriptor instead. -func (*RecordRequest) Descriptor() ([]byte, []int) { - return file_audit_proto_rawDescGZIP(), []int{1} -} - -func (x *RecordRequest) GetEntry() *AuditLogEntry { - if x != nil { - return x.Entry - } - return nil -} - -// RecordResponse indicates success. -type RecordResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` - Id string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"` // Audit log entry ID - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *RecordResponse) Reset() { - *x = RecordResponse{} - mi := &file_audit_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *RecordResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*RecordResponse) ProtoMessage() {} - -func (x *RecordResponse) ProtoReflect() protoreflect.Message { - mi := &file_audit_proto_msgTypes[2] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use RecordResponse.ProtoReflect.Descriptor instead. -func (*RecordResponse) Descriptor() ([]byte, []int) { - return file_audit_proto_rawDescGZIP(), []int{2} -} - -func (x *RecordResponse) GetSuccess() bool { - if x != nil { - return x.Success - } - return false -} - -func (x *RecordResponse) GetId() string { - if x != nil { - return x.Id - } - return "" -} - -// QueryRequest contains filters for querying audit logs. -type QueryRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - UserId *string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3,oneof" json:"user_id,omitempty"` - Action *string `protobuf:"bytes,2,opt,name=action,proto3,oneof" json:"action,omitempty"` - Resource *string `protobuf:"bytes,3,opt,name=resource,proto3,oneof" json:"resource,omitempty"` - ResourceId *string `protobuf:"bytes,4,opt,name=resource_id,json=resourceId,proto3,oneof" json:"resource_id,omitempty"` - StartTime *int64 `protobuf:"varint,5,opt,name=start_time,json=startTime,proto3,oneof" json:"start_time,omitempty"` - EndTime *int64 `protobuf:"varint,6,opt,name=end_time,json=endTime,proto3,oneof" json:"end_time,omitempty"` - Limit int32 `protobuf:"varint,7,opt,name=limit,proto3" json:"limit,omitempty"` // Max number of results - Offset int32 `protobuf:"varint,8,opt,name=offset,proto3" json:"offset,omitempty"` // Pagination offset - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *QueryRequest) Reset() { - *x = QueryRequest{} - mi := &file_audit_proto_msgTypes[3] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *QueryRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*QueryRequest) ProtoMessage() {} - -func (x *QueryRequest) ProtoReflect() protoreflect.Message { - mi := &file_audit_proto_msgTypes[3] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use QueryRequest.ProtoReflect.Descriptor instead. -func (*QueryRequest) Descriptor() ([]byte, []int) { - return file_audit_proto_rawDescGZIP(), []int{3} -} - -func (x *QueryRequest) GetUserId() string { - if x != nil && x.UserId != nil { - return *x.UserId - } - return "" -} - -func (x *QueryRequest) GetAction() string { - if x != nil && x.Action != nil { - return *x.Action - } - return "" -} - -func (x *QueryRequest) GetResource() string { - if x != nil && x.Resource != nil { - return *x.Resource - } - return "" -} - -func (x *QueryRequest) GetResourceId() string { - if x != nil && x.ResourceId != nil { - return *x.ResourceId - } - return "" -} - -func (x *QueryRequest) GetStartTime() int64 { - if x != nil && x.StartTime != nil { - return *x.StartTime - } - return 0 -} - -func (x *QueryRequest) GetEndTime() int64 { - if x != nil && x.EndTime != nil { - return *x.EndTime - } - return 0 -} - -func (x *QueryRequest) GetLimit() int32 { - if x != nil { - return x.Limit - } - return 0 -} - -func (x *QueryRequest) GetOffset() int32 { - if x != nil { - return x.Offset - } - return 0 -} - -// QueryResponse contains audit log entries. -type QueryResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Entries []*AuditLogEntry `protobuf:"bytes,1,rep,name=entries,proto3" json:"entries,omitempty"` - Total int32 `protobuf:"varint,2,opt,name=total,proto3" json:"total,omitempty"` // Total number of matching entries - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *QueryResponse) Reset() { - *x = QueryResponse{} - mi := &file_audit_proto_msgTypes[4] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *QueryResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*QueryResponse) ProtoMessage() {} - -func (x *QueryResponse) ProtoReflect() protoreflect.Message { - mi := &file_audit_proto_msgTypes[4] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use QueryResponse.ProtoReflect.Descriptor instead. -func (*QueryResponse) Descriptor() ([]byte, []int) { - return file_audit_proto_rawDescGZIP(), []int{4} -} - -func (x *QueryResponse) GetEntries() []*AuditLogEntry { - if x != nil { - return x.Entries - } - return nil -} - -func (x *QueryResponse) GetTotal() int32 { - if x != nil { - return x.Total - } - return 0 -} - -var File_audit_proto protoreflect.FileDescriptor - -const file_audit_proto_rawDesc = "" + - "\n" + - "\vaudit.proto\x12\baudit.v1\"\xd9\x02\n" + - "\rAuditLogEntry\x12\x17\n" + - "\auser_id\x18\x01 \x01(\tR\x06userId\x12\x16\n" + - "\x06action\x18\x02 \x01(\tR\x06action\x12\x1a\n" + - "\bresource\x18\x03 \x01(\tR\bresource\x12\x1f\n" + - "\vresource_id\x18\x04 \x01(\tR\n" + - "resourceId\x12\x1d\n" + - "\n" + - "ip_address\x18\x05 \x01(\tR\tipAddress\x12\x1d\n" + - "\n" + - "user_agent\x18\x06 \x01(\tR\tuserAgent\x12A\n" + - "\bmetadata\x18\a \x03(\v2%.audit.v1.AuditLogEntry.MetadataEntryR\bmetadata\x12\x1c\n" + - "\ttimestamp\x18\b \x01(\x03R\ttimestamp\x1a;\n" + - "\rMetadataEntry\x12\x10\n" + - "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + - "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\">\n" + - "\rRecordRequest\x12-\n" + - "\x05entry\x18\x01 \x01(\v2\x17.audit.v1.AuditLogEntryR\x05entry\":\n" + - "\x0eRecordResponse\x12\x18\n" + - "\asuccess\x18\x01 \x01(\bR\asuccess\x12\x0e\n" + - "\x02id\x18\x02 \x01(\tR\x02id\"\xd2\x02\n" + - "\fQueryRequest\x12\x1c\n" + - "\auser_id\x18\x01 \x01(\tH\x00R\x06userId\x88\x01\x01\x12\x1b\n" + - "\x06action\x18\x02 \x01(\tH\x01R\x06action\x88\x01\x01\x12\x1f\n" + - "\bresource\x18\x03 \x01(\tH\x02R\bresource\x88\x01\x01\x12$\n" + - "\vresource_id\x18\x04 \x01(\tH\x03R\n" + - "resourceId\x88\x01\x01\x12\"\n" + - "\n" + - "start_time\x18\x05 \x01(\x03H\x04R\tstartTime\x88\x01\x01\x12\x1e\n" + - "\bend_time\x18\x06 \x01(\x03H\x05R\aendTime\x88\x01\x01\x12\x14\n" + - "\x05limit\x18\a \x01(\x05R\x05limit\x12\x16\n" + - "\x06offset\x18\b \x01(\x05R\x06offsetB\n" + - "\n" + - "\b_user_idB\t\n" + - "\a_actionB\v\n" + - "\t_resourceB\x0e\n" + - "\f_resource_idB\r\n" + - "\v_start_timeB\v\n" + - "\t_end_time\"X\n" + - "\rQueryResponse\x121\n" + - "\aentries\x18\x01 \x03(\v2\x17.audit.v1.AuditLogEntryR\aentries\x12\x14\n" + - "\x05total\x18\x02 \x01(\x05R\x05total2\x85\x01\n" + - "\fAuditService\x12;\n" + - "\x06Record\x12\x17.audit.v1.RecordRequest\x1a\x18.audit.v1.RecordResponse\x128\n" + - "\x05Query\x12\x16.audit.v1.QueryRequest\x1a\x17.audit.v1.QueryResponseBGZEgit.dcentral.systems/toolz/goplt/api/proto/generated/audit/v1;auditv1b\x06proto3" - -var ( - file_audit_proto_rawDescOnce sync.Once - file_audit_proto_rawDescData []byte -) - -func file_audit_proto_rawDescGZIP() []byte { - file_audit_proto_rawDescOnce.Do(func() { - file_audit_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_audit_proto_rawDesc), len(file_audit_proto_rawDesc))) - }) - return file_audit_proto_rawDescData -} - -var file_audit_proto_msgTypes = make([]protoimpl.MessageInfo, 6) -var file_audit_proto_goTypes = []any{ - (*AuditLogEntry)(nil), // 0: audit.v1.AuditLogEntry - (*RecordRequest)(nil), // 1: audit.v1.RecordRequest - (*RecordResponse)(nil), // 2: audit.v1.RecordResponse - (*QueryRequest)(nil), // 3: audit.v1.QueryRequest - (*QueryResponse)(nil), // 4: audit.v1.QueryResponse - nil, // 5: audit.v1.AuditLogEntry.MetadataEntry -} -var file_audit_proto_depIdxs = []int32{ - 5, // 0: audit.v1.AuditLogEntry.metadata:type_name -> audit.v1.AuditLogEntry.MetadataEntry - 0, // 1: audit.v1.RecordRequest.entry:type_name -> audit.v1.AuditLogEntry - 0, // 2: audit.v1.QueryResponse.entries:type_name -> audit.v1.AuditLogEntry - 1, // 3: audit.v1.AuditService.Record:input_type -> audit.v1.RecordRequest - 3, // 4: audit.v1.AuditService.Query:input_type -> audit.v1.QueryRequest - 2, // 5: audit.v1.AuditService.Record:output_type -> audit.v1.RecordResponse - 4, // 6: audit.v1.AuditService.Query:output_type -> audit.v1.QueryResponse - 5, // [5:7] is the sub-list for method output_type - 3, // [3:5] is the sub-list for method input_type - 3, // [3:3] is the sub-list for extension type_name - 3, // [3:3] is the sub-list for extension extendee - 0, // [0:3] is the sub-list for field type_name -} - -func init() { file_audit_proto_init() } -func file_audit_proto_init() { - if File_audit_proto != nil { - return - } - file_audit_proto_msgTypes[3].OneofWrappers = []any{} - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: unsafe.Slice(unsafe.StringData(file_audit_proto_rawDesc), len(file_audit_proto_rawDesc)), - NumEnums: 0, - NumMessages: 6, - NumExtensions: 0, - NumServices: 1, - }, - GoTypes: file_audit_proto_goTypes, - DependencyIndexes: file_audit_proto_depIdxs, - MessageInfos: file_audit_proto_msgTypes, - }.Build() - File_audit_proto = out.File - file_audit_proto_goTypes = nil - file_audit_proto_depIdxs = nil -} diff --git a/api/proto/generated/audit/v1/audit.pb.go b/api/proto/generated/audit/v1/audit.pb.go deleted file mode 100644 index cb9ca82..0000000 --- a/api/proto/generated/audit/v1/audit.pb.go +++ /dev/null @@ -1,486 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.36.10 -// protoc v6.30.2 -// source: audit.proto - -package auditv1 - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - reflect "reflect" - sync "sync" - unsafe "unsafe" -) - -const ( - // Verify that this generated code is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) - // Verify that runtime/protoimpl is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) -) - -// AuditLogEntry represents an audit log entry. -type AuditLogEntry struct { - state protoimpl.MessageState `protogen:"open.v1"` - UserId string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"` - Action string `protobuf:"bytes,2,opt,name=action,proto3" json:"action,omitempty"` // e.g., "user.create", "user.update" - Resource string `protobuf:"bytes,3,opt,name=resource,proto3" json:"resource,omitempty"` // e.g., "user", "role" - ResourceId string `protobuf:"bytes,4,opt,name=resource_id,json=resourceId,proto3" json:"resource_id,omitempty"` - IpAddress string `protobuf:"bytes,5,opt,name=ip_address,json=ipAddress,proto3" json:"ip_address,omitempty"` - UserAgent string `protobuf:"bytes,6,opt,name=user_agent,json=userAgent,proto3" json:"user_agent,omitempty"` - Metadata map[string]string `protobuf:"bytes,7,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - Timestamp int64 `protobuf:"varint,8,opt,name=timestamp,proto3" json:"timestamp,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *AuditLogEntry) Reset() { - *x = AuditLogEntry{} - mi := &file_audit_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *AuditLogEntry) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*AuditLogEntry) ProtoMessage() {} - -func (x *AuditLogEntry) ProtoReflect() protoreflect.Message { - mi := &file_audit_proto_msgTypes[0] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use AuditLogEntry.ProtoReflect.Descriptor instead. -func (*AuditLogEntry) Descriptor() ([]byte, []int) { - return file_audit_proto_rawDescGZIP(), []int{0} -} - -func (x *AuditLogEntry) GetUserId() string { - if x != nil { - return x.UserId - } - return "" -} - -func (x *AuditLogEntry) GetAction() string { - if x != nil { - return x.Action - } - return "" -} - -func (x *AuditLogEntry) GetResource() string { - if x != nil { - return x.Resource - } - return "" -} - -func (x *AuditLogEntry) GetResourceId() string { - if x != nil { - return x.ResourceId - } - return "" -} - -func (x *AuditLogEntry) GetIpAddress() string { - if x != nil { - return x.IpAddress - } - return "" -} - -func (x *AuditLogEntry) GetUserAgent() string { - if x != nil { - return x.UserAgent - } - return "" -} - -func (x *AuditLogEntry) GetMetadata() map[string]string { - if x != nil { - return x.Metadata - } - return nil -} - -func (x *AuditLogEntry) GetTimestamp() int64 { - if x != nil { - return x.Timestamp - } - return 0 -} - -// RecordRequest contains an audit log entry to record. -type RecordRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Entry *AuditLogEntry `protobuf:"bytes,1,opt,name=entry,proto3" json:"entry,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *RecordRequest) Reset() { - *x = RecordRequest{} - mi := &file_audit_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *RecordRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*RecordRequest) ProtoMessage() {} - -func (x *RecordRequest) ProtoReflect() protoreflect.Message { - mi := &file_audit_proto_msgTypes[1] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use RecordRequest.ProtoReflect.Descriptor instead. -func (*RecordRequest) Descriptor() ([]byte, []int) { - return file_audit_proto_rawDescGZIP(), []int{1} -} - -func (x *RecordRequest) GetEntry() *AuditLogEntry { - if x != nil { - return x.Entry - } - return nil -} - -// RecordResponse indicates success. -type RecordResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` - Id string `protobuf:"bytes,2,opt,name=id,proto3" json:"id,omitempty"` // Audit log entry ID - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *RecordResponse) Reset() { - *x = RecordResponse{} - mi := &file_audit_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *RecordResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*RecordResponse) ProtoMessage() {} - -func (x *RecordResponse) ProtoReflect() protoreflect.Message { - mi := &file_audit_proto_msgTypes[2] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use RecordResponse.ProtoReflect.Descriptor instead. -func (*RecordResponse) Descriptor() ([]byte, []int) { - return file_audit_proto_rawDescGZIP(), []int{2} -} - -func (x *RecordResponse) GetSuccess() bool { - if x != nil { - return x.Success - } - return false -} - -func (x *RecordResponse) GetId() string { - if x != nil { - return x.Id - } - return "" -} - -// QueryRequest contains filters for querying audit logs. -type QueryRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - UserId *string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3,oneof" json:"user_id,omitempty"` - Action *string `protobuf:"bytes,2,opt,name=action,proto3,oneof" json:"action,omitempty"` - Resource *string `protobuf:"bytes,3,opt,name=resource,proto3,oneof" json:"resource,omitempty"` - ResourceId *string `protobuf:"bytes,4,opt,name=resource_id,json=resourceId,proto3,oneof" json:"resource_id,omitempty"` - StartTime *int64 `protobuf:"varint,5,opt,name=start_time,json=startTime,proto3,oneof" json:"start_time,omitempty"` - EndTime *int64 `protobuf:"varint,6,opt,name=end_time,json=endTime,proto3,oneof" json:"end_time,omitempty"` - Limit int32 `protobuf:"varint,7,opt,name=limit,proto3" json:"limit,omitempty"` // Max number of results - Offset int32 `protobuf:"varint,8,opt,name=offset,proto3" json:"offset,omitempty"` // Pagination offset - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *QueryRequest) Reset() { - *x = QueryRequest{} - mi := &file_audit_proto_msgTypes[3] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *QueryRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*QueryRequest) ProtoMessage() {} - -func (x *QueryRequest) ProtoReflect() protoreflect.Message { - mi := &file_audit_proto_msgTypes[3] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use QueryRequest.ProtoReflect.Descriptor instead. -func (*QueryRequest) Descriptor() ([]byte, []int) { - return file_audit_proto_rawDescGZIP(), []int{3} -} - -func (x *QueryRequest) GetUserId() string { - if x != nil && x.UserId != nil { - return *x.UserId - } - return "" -} - -func (x *QueryRequest) GetAction() string { - if x != nil && x.Action != nil { - return *x.Action - } - return "" -} - -func (x *QueryRequest) GetResource() string { - if x != nil && x.Resource != nil { - return *x.Resource - } - return "" -} - -func (x *QueryRequest) GetResourceId() string { - if x != nil && x.ResourceId != nil { - return *x.ResourceId - } - return "" -} - -func (x *QueryRequest) GetStartTime() int64 { - if x != nil && x.StartTime != nil { - return *x.StartTime - } - return 0 -} - -func (x *QueryRequest) GetEndTime() int64 { - if x != nil && x.EndTime != nil { - return *x.EndTime - } - return 0 -} - -func (x *QueryRequest) GetLimit() int32 { - if x != nil { - return x.Limit - } - return 0 -} - -func (x *QueryRequest) GetOffset() int32 { - if x != nil { - return x.Offset - } - return 0 -} - -// QueryResponse contains audit log entries. -type QueryResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Entries []*AuditLogEntry `protobuf:"bytes,1,rep,name=entries,proto3" json:"entries,omitempty"` - Total int32 `protobuf:"varint,2,opt,name=total,proto3" json:"total,omitempty"` // Total number of matching entries - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *QueryResponse) Reset() { - *x = QueryResponse{} - mi := &file_audit_proto_msgTypes[4] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *QueryResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*QueryResponse) ProtoMessage() {} - -func (x *QueryResponse) ProtoReflect() protoreflect.Message { - mi := &file_audit_proto_msgTypes[4] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use QueryResponse.ProtoReflect.Descriptor instead. -func (*QueryResponse) Descriptor() ([]byte, []int) { - return file_audit_proto_rawDescGZIP(), []int{4} -} - -func (x *QueryResponse) GetEntries() []*AuditLogEntry { - if x != nil { - return x.Entries - } - return nil -} - -func (x *QueryResponse) GetTotal() int32 { - if x != nil { - return x.Total - } - return 0 -} - -var File_audit_proto protoreflect.FileDescriptor - -const file_audit_proto_rawDesc = "" + - "\n" + - "\vaudit.proto\x12\baudit.v1\"\xd9\x02\n" + - "\rAuditLogEntry\x12\x17\n" + - "\auser_id\x18\x01 \x01(\tR\x06userId\x12\x16\n" + - "\x06action\x18\x02 \x01(\tR\x06action\x12\x1a\n" + - "\bresource\x18\x03 \x01(\tR\bresource\x12\x1f\n" + - "\vresource_id\x18\x04 \x01(\tR\n" + - "resourceId\x12\x1d\n" + - "\n" + - "ip_address\x18\x05 \x01(\tR\tipAddress\x12\x1d\n" + - "\n" + - "user_agent\x18\x06 \x01(\tR\tuserAgent\x12A\n" + - "\bmetadata\x18\a \x03(\v2%.audit.v1.AuditLogEntry.MetadataEntryR\bmetadata\x12\x1c\n" + - "\ttimestamp\x18\b \x01(\x03R\ttimestamp\x1a;\n" + - "\rMetadataEntry\x12\x10\n" + - "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + - "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\">\n" + - "\rRecordRequest\x12-\n" + - "\x05entry\x18\x01 \x01(\v2\x17.audit.v1.AuditLogEntryR\x05entry\":\n" + - "\x0eRecordResponse\x12\x18\n" + - "\asuccess\x18\x01 \x01(\bR\asuccess\x12\x0e\n" + - "\x02id\x18\x02 \x01(\tR\x02id\"\xd2\x02\n" + - "\fQueryRequest\x12\x1c\n" + - "\auser_id\x18\x01 \x01(\tH\x00R\x06userId\x88\x01\x01\x12\x1b\n" + - "\x06action\x18\x02 \x01(\tH\x01R\x06action\x88\x01\x01\x12\x1f\n" + - "\bresource\x18\x03 \x01(\tH\x02R\bresource\x88\x01\x01\x12$\n" + - "\vresource_id\x18\x04 \x01(\tH\x03R\n" + - "resourceId\x88\x01\x01\x12\"\n" + - "\n" + - "start_time\x18\x05 \x01(\x03H\x04R\tstartTime\x88\x01\x01\x12\x1e\n" + - "\bend_time\x18\x06 \x01(\x03H\x05R\aendTime\x88\x01\x01\x12\x14\n" + - "\x05limit\x18\a \x01(\x05R\x05limit\x12\x16\n" + - "\x06offset\x18\b \x01(\x05R\x06offsetB\n" + - "\n" + - "\b_user_idB\t\n" + - "\a_actionB\v\n" + - "\t_resourceB\x0e\n" + - "\f_resource_idB\r\n" + - "\v_start_timeB\v\n" + - "\t_end_time\"X\n" + - "\rQueryResponse\x121\n" + - "\aentries\x18\x01 \x03(\v2\x17.audit.v1.AuditLogEntryR\aentries\x12\x14\n" + - "\x05total\x18\x02 \x01(\x05R\x05total2\x85\x01\n" + - "\fAuditService\x12;\n" + - "\x06Record\x12\x17.audit.v1.RecordRequest\x1a\x18.audit.v1.RecordResponse\x128\n" + - "\x05Query\x12\x16.audit.v1.QueryRequest\x1a\x17.audit.v1.QueryResponseBGZEgit.dcentral.systems/toolz/goplt/api/proto/generated/audit/v1;auditv1b\x06proto3" - -var ( - file_audit_proto_rawDescOnce sync.Once - file_audit_proto_rawDescData []byte -) - -func file_audit_proto_rawDescGZIP() []byte { - file_audit_proto_rawDescOnce.Do(func() { - file_audit_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_audit_proto_rawDesc), len(file_audit_proto_rawDesc))) - }) - return file_audit_proto_rawDescData -} - -var file_audit_proto_msgTypes = make([]protoimpl.MessageInfo, 6) -var file_audit_proto_goTypes = []any{ - (*AuditLogEntry)(nil), // 0: audit.v1.AuditLogEntry - (*RecordRequest)(nil), // 1: audit.v1.RecordRequest - (*RecordResponse)(nil), // 2: audit.v1.RecordResponse - (*QueryRequest)(nil), // 3: audit.v1.QueryRequest - (*QueryResponse)(nil), // 4: audit.v1.QueryResponse - nil, // 5: audit.v1.AuditLogEntry.MetadataEntry -} -var file_audit_proto_depIdxs = []int32{ - 5, // 0: audit.v1.AuditLogEntry.metadata:type_name -> audit.v1.AuditLogEntry.MetadataEntry - 0, // 1: audit.v1.RecordRequest.entry:type_name -> audit.v1.AuditLogEntry - 0, // 2: audit.v1.QueryResponse.entries:type_name -> audit.v1.AuditLogEntry - 1, // 3: audit.v1.AuditService.Record:input_type -> audit.v1.RecordRequest - 3, // 4: audit.v1.AuditService.Query:input_type -> audit.v1.QueryRequest - 2, // 5: audit.v1.AuditService.Record:output_type -> audit.v1.RecordResponse - 4, // 6: audit.v1.AuditService.Query:output_type -> audit.v1.QueryResponse - 5, // [5:7] is the sub-list for method output_type - 3, // [3:5] is the sub-list for method input_type - 3, // [3:3] is the sub-list for extension type_name - 3, // [3:3] is the sub-list for extension extendee - 0, // [0:3] is the sub-list for field type_name -} - -func init() { file_audit_proto_init() } -func file_audit_proto_init() { - if File_audit_proto != nil { - return - } - file_audit_proto_msgTypes[3].OneofWrappers = []any{} - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: unsafe.Slice(unsafe.StringData(file_audit_proto_rawDesc), len(file_audit_proto_rawDesc)), - NumEnums: 0, - NumMessages: 6, - NumExtensions: 0, - NumServices: 1, - }, - GoTypes: file_audit_proto_goTypes, - DependencyIndexes: file_audit_proto_depIdxs, - MessageInfos: file_audit_proto_msgTypes, - }.Build() - File_audit_proto = out.File - file_audit_proto_goTypes = nil - file_audit_proto_depIdxs = nil -} diff --git a/api/proto/generated/audit/v1/audit_grpc.pb.go b/api/proto/generated/audit/v1/audit_grpc.pb.go deleted file mode 100644 index a632c99..0000000 --- a/api/proto/generated/audit/v1/audit_grpc.pb.go +++ /dev/null @@ -1,167 +0,0 @@ -// Code generated by protoc-gen-go-grpc. DO NOT EDIT. -// versions: -// - protoc-gen-go-grpc v1.5.1 -// - protoc v6.30.2 -// source: audit.proto - -package auditv1 - -import ( - context "context" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" -) - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -// Requires gRPC-Go v1.64.0 or later. -const _ = grpc.SupportPackageIsVersion9 - -const ( - AuditService_Record_FullMethodName = "/audit.v1.AuditService/Record" - AuditService_Query_FullMethodName = "/audit.v1.AuditService/Query" -) - -// AuditServiceClient is the client API for AuditService service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. -// -// AuditService provides audit logging operations. -type AuditServiceClient interface { - // Record records an audit log entry. - Record(ctx context.Context, in *RecordRequest, opts ...grpc.CallOption) (*RecordResponse, error) - // Query queries audit logs based on filters. - Query(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error) -} - -type auditServiceClient struct { - cc grpc.ClientConnInterface -} - -func NewAuditServiceClient(cc grpc.ClientConnInterface) AuditServiceClient { - return &auditServiceClient{cc} -} - -func (c *auditServiceClient) Record(ctx context.Context, in *RecordRequest, opts ...grpc.CallOption) (*RecordResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(RecordResponse) - err := c.cc.Invoke(ctx, AuditService_Record_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *auditServiceClient) Query(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(QueryResponse) - err := c.cc.Invoke(ctx, AuditService_Query_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -// AuditServiceServer is the server API for AuditService service. -// All implementations must embed UnimplementedAuditServiceServer -// for forward compatibility. -// -// AuditService provides audit logging operations. -type AuditServiceServer interface { - // Record records an audit log entry. - Record(context.Context, *RecordRequest) (*RecordResponse, error) - // Query queries audit logs based on filters. - Query(context.Context, *QueryRequest) (*QueryResponse, error) - mustEmbedUnimplementedAuditServiceServer() -} - -// UnimplementedAuditServiceServer must be embedded to have -// forward compatible implementations. -// -// NOTE: this should be embedded by value instead of pointer to avoid a nil -// pointer dereference when methods are called. -type UnimplementedAuditServiceServer struct{} - -func (UnimplementedAuditServiceServer) Record(context.Context, *RecordRequest) (*RecordResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Record not implemented") -} -func (UnimplementedAuditServiceServer) Query(context.Context, *QueryRequest) (*QueryResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Query not implemented") -} -func (UnimplementedAuditServiceServer) mustEmbedUnimplementedAuditServiceServer() {} -func (UnimplementedAuditServiceServer) testEmbeddedByValue() {} - -// UnsafeAuditServiceServer may be embedded to opt out of forward compatibility for this service. -// Use of this interface is not recommended, as added methods to AuditServiceServer will -// result in compilation errors. -type UnsafeAuditServiceServer interface { - mustEmbedUnimplementedAuditServiceServer() -} - -func RegisterAuditServiceServer(s grpc.ServiceRegistrar, srv AuditServiceServer) { - // If the following call pancis, it indicates UnimplementedAuditServiceServer was - // embedded by pointer and is nil. This will cause panics if an - // unimplemented method is ever invoked, so we test this at initialization - // time to prevent it from happening at runtime later due to I/O. - if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { - t.testEmbeddedByValue() - } - s.RegisterService(&AuditService_ServiceDesc, srv) -} - -func _AuditService_Record_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(RecordRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuditServiceServer).Record(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuditService_Record_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuditServiceServer).Record(ctx, req.(*RecordRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _AuditService_Query_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuditServiceServer).Query(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuditService_Query_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuditServiceServer).Query(ctx, req.(*QueryRequest)) - } - return interceptor(ctx, in, info, handler) -} - -// AuditService_ServiceDesc is the grpc.ServiceDesc for AuditService service. -// It's only intended for direct use with grpc.RegisterService, -// and not to be introspected or modified (even as a copy) -var AuditService_ServiceDesc = grpc.ServiceDesc{ - ServiceName: "audit.v1.AuditService", - HandlerType: (*AuditServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Record", - Handler: _AuditService_Record_Handler, - }, - { - MethodName: "Query", - Handler: _AuditService_Query_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "audit.proto", -} diff --git a/api/proto/generated/audit_grpc.pb.go b/api/proto/generated/audit_grpc.pb.go deleted file mode 100644 index a632c99..0000000 --- a/api/proto/generated/audit_grpc.pb.go +++ /dev/null @@ -1,167 +0,0 @@ -// Code generated by protoc-gen-go-grpc. DO NOT EDIT. -// versions: -// - protoc-gen-go-grpc v1.5.1 -// - protoc v6.30.2 -// source: audit.proto - -package auditv1 - -import ( - context "context" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" -) - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -// Requires gRPC-Go v1.64.0 or later. -const _ = grpc.SupportPackageIsVersion9 - -const ( - AuditService_Record_FullMethodName = "/audit.v1.AuditService/Record" - AuditService_Query_FullMethodName = "/audit.v1.AuditService/Query" -) - -// AuditServiceClient is the client API for AuditService service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. -// -// AuditService provides audit logging operations. -type AuditServiceClient interface { - // Record records an audit log entry. - Record(ctx context.Context, in *RecordRequest, opts ...grpc.CallOption) (*RecordResponse, error) - // Query queries audit logs based on filters. - Query(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error) -} - -type auditServiceClient struct { - cc grpc.ClientConnInterface -} - -func NewAuditServiceClient(cc grpc.ClientConnInterface) AuditServiceClient { - return &auditServiceClient{cc} -} - -func (c *auditServiceClient) Record(ctx context.Context, in *RecordRequest, opts ...grpc.CallOption) (*RecordResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(RecordResponse) - err := c.cc.Invoke(ctx, AuditService_Record_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *auditServiceClient) Query(ctx context.Context, in *QueryRequest, opts ...grpc.CallOption) (*QueryResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(QueryResponse) - err := c.cc.Invoke(ctx, AuditService_Query_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -// AuditServiceServer is the server API for AuditService service. -// All implementations must embed UnimplementedAuditServiceServer -// for forward compatibility. -// -// AuditService provides audit logging operations. -type AuditServiceServer interface { - // Record records an audit log entry. - Record(context.Context, *RecordRequest) (*RecordResponse, error) - // Query queries audit logs based on filters. - Query(context.Context, *QueryRequest) (*QueryResponse, error) - mustEmbedUnimplementedAuditServiceServer() -} - -// UnimplementedAuditServiceServer must be embedded to have -// forward compatible implementations. -// -// NOTE: this should be embedded by value instead of pointer to avoid a nil -// pointer dereference when methods are called. -type UnimplementedAuditServiceServer struct{} - -func (UnimplementedAuditServiceServer) Record(context.Context, *RecordRequest) (*RecordResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Record not implemented") -} -func (UnimplementedAuditServiceServer) Query(context.Context, *QueryRequest) (*QueryResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Query not implemented") -} -func (UnimplementedAuditServiceServer) mustEmbedUnimplementedAuditServiceServer() {} -func (UnimplementedAuditServiceServer) testEmbeddedByValue() {} - -// UnsafeAuditServiceServer may be embedded to opt out of forward compatibility for this service. -// Use of this interface is not recommended, as added methods to AuditServiceServer will -// result in compilation errors. -type UnsafeAuditServiceServer interface { - mustEmbedUnimplementedAuditServiceServer() -} - -func RegisterAuditServiceServer(s grpc.ServiceRegistrar, srv AuditServiceServer) { - // If the following call pancis, it indicates UnimplementedAuditServiceServer was - // embedded by pointer and is nil. This will cause panics if an - // unimplemented method is ever invoked, so we test this at initialization - // time to prevent it from happening at runtime later due to I/O. - if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { - t.testEmbeddedByValue() - } - s.RegisterService(&AuditService_ServiceDesc, srv) -} - -func _AuditService_Record_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(RecordRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuditServiceServer).Record(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuditService_Record_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuditServiceServer).Record(ctx, req.(*RecordRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _AuditService_Query_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(QueryRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuditServiceServer).Query(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuditService_Query_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuditServiceServer).Query(ctx, req.(*QueryRequest)) - } - return interceptor(ctx, in, info, handler) -} - -// AuditService_ServiceDesc is the grpc.ServiceDesc for AuditService service. -// It's only intended for direct use with grpc.RegisterService, -// and not to be introspected or modified (even as a copy) -var AuditService_ServiceDesc = grpc.ServiceDesc{ - ServiceName: "audit.v1.AuditService", - HandlerType: (*AuditServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Record", - Handler: _AuditService_Record_Handler, - }, - { - MethodName: "Query", - Handler: _AuditService_Query_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "audit.proto", -} diff --git a/api/proto/generated/auth.pb.go b/api/proto/generated/auth.pb.go deleted file mode 100644 index ed71954..0000000 --- a/api/proto/generated/auth.pb.go +++ /dev/null @@ -1,568 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.36.10 -// protoc v6.30.2 -// source: auth.proto - -package authv1 - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - reflect "reflect" - sync "sync" - unsafe "unsafe" -) - -const ( - // Verify that this generated code is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) - // Verify that runtime/protoimpl is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) -) - -// LoginRequest contains login credentials. -type LoginRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Email string `protobuf:"bytes,1,opt,name=email,proto3" json:"email,omitempty"` - Password string `protobuf:"bytes,2,opt,name=password,proto3" json:"password,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *LoginRequest) Reset() { - *x = LoginRequest{} - mi := &file_auth_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *LoginRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*LoginRequest) ProtoMessage() {} - -func (x *LoginRequest) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[0] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use LoginRequest.ProtoReflect.Descriptor instead. -func (*LoginRequest) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{0} -} - -func (x *LoginRequest) GetEmail() string { - if x != nil { - return x.Email - } - return "" -} - -func (x *LoginRequest) GetPassword() string { - if x != nil { - return x.Password - } - return "" -} - -// LoginResponse contains authentication tokens. -type LoginResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - AccessToken string `protobuf:"bytes,1,opt,name=access_token,json=accessToken,proto3" json:"access_token,omitempty"` - RefreshToken string `protobuf:"bytes,2,opt,name=refresh_token,json=refreshToken,proto3" json:"refresh_token,omitempty"` - ExpiresIn int64 `protobuf:"varint,3,opt,name=expires_in,json=expiresIn,proto3" json:"expires_in,omitempty"` // seconds - TokenType string `protobuf:"bytes,4,opt,name=token_type,json=tokenType,proto3" json:"token_type,omitempty"` // "Bearer" - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *LoginResponse) Reset() { - *x = LoginResponse{} - mi := &file_auth_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *LoginResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*LoginResponse) ProtoMessage() {} - -func (x *LoginResponse) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[1] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use LoginResponse.ProtoReflect.Descriptor instead. -func (*LoginResponse) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{1} -} - -func (x *LoginResponse) GetAccessToken() string { - if x != nil { - return x.AccessToken - } - return "" -} - -func (x *LoginResponse) GetRefreshToken() string { - if x != nil { - return x.RefreshToken - } - return "" -} - -func (x *LoginResponse) GetExpiresIn() int64 { - if x != nil { - return x.ExpiresIn - } - return 0 -} - -func (x *LoginResponse) GetTokenType() string { - if x != nil { - return x.TokenType - } - return "" -} - -// RefreshTokenRequest contains a refresh token. -type RefreshTokenRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - RefreshToken string `protobuf:"bytes,1,opt,name=refresh_token,json=refreshToken,proto3" json:"refresh_token,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *RefreshTokenRequest) Reset() { - *x = RefreshTokenRequest{} - mi := &file_auth_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *RefreshTokenRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*RefreshTokenRequest) ProtoMessage() {} - -func (x *RefreshTokenRequest) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[2] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use RefreshTokenRequest.ProtoReflect.Descriptor instead. -func (*RefreshTokenRequest) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{2} -} - -func (x *RefreshTokenRequest) GetRefreshToken() string { - if x != nil { - return x.RefreshToken - } - return "" -} - -// RefreshTokenResponse contains new authentication tokens. -type RefreshTokenResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - AccessToken string `protobuf:"bytes,1,opt,name=access_token,json=accessToken,proto3" json:"access_token,omitempty"` - RefreshToken string `protobuf:"bytes,2,opt,name=refresh_token,json=refreshToken,proto3" json:"refresh_token,omitempty"` - ExpiresIn int64 `protobuf:"varint,3,opt,name=expires_in,json=expiresIn,proto3" json:"expires_in,omitempty"` // seconds - TokenType string `protobuf:"bytes,4,opt,name=token_type,json=tokenType,proto3" json:"token_type,omitempty"` // "Bearer" - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *RefreshTokenResponse) Reset() { - *x = RefreshTokenResponse{} - mi := &file_auth_proto_msgTypes[3] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *RefreshTokenResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*RefreshTokenResponse) ProtoMessage() {} - -func (x *RefreshTokenResponse) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[3] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use RefreshTokenResponse.ProtoReflect.Descriptor instead. -func (*RefreshTokenResponse) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{3} -} - -func (x *RefreshTokenResponse) GetAccessToken() string { - if x != nil { - return x.AccessToken - } - return "" -} - -func (x *RefreshTokenResponse) GetRefreshToken() string { - if x != nil { - return x.RefreshToken - } - return "" -} - -func (x *RefreshTokenResponse) GetExpiresIn() int64 { - if x != nil { - return x.ExpiresIn - } - return 0 -} - -func (x *RefreshTokenResponse) GetTokenType() string { - if x != nil { - return x.TokenType - } - return "" -} - -// ValidateTokenRequest contains a JWT token to validate. -type ValidateTokenRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *ValidateTokenRequest) Reset() { - *x = ValidateTokenRequest{} - mi := &file_auth_proto_msgTypes[4] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *ValidateTokenRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ValidateTokenRequest) ProtoMessage() {} - -func (x *ValidateTokenRequest) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[4] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use ValidateTokenRequest.ProtoReflect.Descriptor instead. -func (*ValidateTokenRequest) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{4} -} - -func (x *ValidateTokenRequest) GetToken() string { - if x != nil { - return x.Token - } - return "" -} - -// ValidateTokenResponse contains token claims. -type ValidateTokenResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - UserId string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"` - Email string `protobuf:"bytes,2,opt,name=email,proto3" json:"email,omitempty"` - Roles []string `protobuf:"bytes,3,rep,name=roles,proto3" json:"roles,omitempty"` - ExpiresAt int64 `protobuf:"varint,4,opt,name=expires_at,json=expiresAt,proto3" json:"expires_at,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *ValidateTokenResponse) Reset() { - *x = ValidateTokenResponse{} - mi := &file_auth_proto_msgTypes[5] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *ValidateTokenResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ValidateTokenResponse) ProtoMessage() {} - -func (x *ValidateTokenResponse) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[5] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use ValidateTokenResponse.ProtoReflect.Descriptor instead. -func (*ValidateTokenResponse) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{5} -} - -func (x *ValidateTokenResponse) GetUserId() string { - if x != nil { - return x.UserId - } - return "" -} - -func (x *ValidateTokenResponse) GetEmail() string { - if x != nil { - return x.Email - } - return "" -} - -func (x *ValidateTokenResponse) GetRoles() []string { - if x != nil { - return x.Roles - } - return nil -} - -func (x *ValidateTokenResponse) GetExpiresAt() int64 { - if x != nil { - return x.ExpiresAt - } - return 0 -} - -// LogoutRequest contains a refresh token to invalidate. -type LogoutRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - RefreshToken string `protobuf:"bytes,1,opt,name=refresh_token,json=refreshToken,proto3" json:"refresh_token,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *LogoutRequest) Reset() { - *x = LogoutRequest{} - mi := &file_auth_proto_msgTypes[6] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *LogoutRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*LogoutRequest) ProtoMessage() {} - -func (x *LogoutRequest) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[6] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use LogoutRequest.ProtoReflect.Descriptor instead. -func (*LogoutRequest) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{6} -} - -func (x *LogoutRequest) GetRefreshToken() string { - if x != nil { - return x.RefreshToken - } - return "" -} - -// LogoutResponse indicates success. -type LogoutResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *LogoutResponse) Reset() { - *x = LogoutResponse{} - mi := &file_auth_proto_msgTypes[7] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *LogoutResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*LogoutResponse) ProtoMessage() {} - -func (x *LogoutResponse) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[7] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use LogoutResponse.ProtoReflect.Descriptor instead. -func (*LogoutResponse) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{7} -} - -func (x *LogoutResponse) GetSuccess() bool { - if x != nil { - return x.Success - } - return false -} - -var File_auth_proto protoreflect.FileDescriptor - -const file_auth_proto_rawDesc = "" + - "\n" + - "\n" + - "auth.proto\x12\aauth.v1\"@\n" + - "\fLoginRequest\x12\x14\n" + - "\x05email\x18\x01 \x01(\tR\x05email\x12\x1a\n" + - "\bpassword\x18\x02 \x01(\tR\bpassword\"\x95\x01\n" + - "\rLoginResponse\x12!\n" + - "\faccess_token\x18\x01 \x01(\tR\vaccessToken\x12#\n" + - "\rrefresh_token\x18\x02 \x01(\tR\frefreshToken\x12\x1d\n" + - "\n" + - "expires_in\x18\x03 \x01(\x03R\texpiresIn\x12\x1d\n" + - "\n" + - "token_type\x18\x04 \x01(\tR\ttokenType\":\n" + - "\x13RefreshTokenRequest\x12#\n" + - "\rrefresh_token\x18\x01 \x01(\tR\frefreshToken\"\x9c\x01\n" + - "\x14RefreshTokenResponse\x12!\n" + - "\faccess_token\x18\x01 \x01(\tR\vaccessToken\x12#\n" + - "\rrefresh_token\x18\x02 \x01(\tR\frefreshToken\x12\x1d\n" + - "\n" + - "expires_in\x18\x03 \x01(\x03R\texpiresIn\x12\x1d\n" + - "\n" + - "token_type\x18\x04 \x01(\tR\ttokenType\",\n" + - "\x14ValidateTokenRequest\x12\x14\n" + - "\x05token\x18\x01 \x01(\tR\x05token\"{\n" + - "\x15ValidateTokenResponse\x12\x17\n" + - "\auser_id\x18\x01 \x01(\tR\x06userId\x12\x14\n" + - "\x05email\x18\x02 \x01(\tR\x05email\x12\x14\n" + - "\x05roles\x18\x03 \x03(\tR\x05roles\x12\x1d\n" + - "\n" + - "expires_at\x18\x04 \x01(\x03R\texpiresAt\"4\n" + - "\rLogoutRequest\x12#\n" + - "\rrefresh_token\x18\x01 \x01(\tR\frefreshToken\"*\n" + - "\x0eLogoutResponse\x12\x18\n" + - "\asuccess\x18\x01 \x01(\bR\asuccess2\x9d\x02\n" + - "\vAuthService\x126\n" + - "\x05Login\x12\x15.auth.v1.LoginRequest\x1a\x16.auth.v1.LoginResponse\x12K\n" + - "\fRefreshToken\x12\x1c.auth.v1.RefreshTokenRequest\x1a\x1d.auth.v1.RefreshTokenResponse\x12N\n" + - "\rValidateToken\x12\x1d.auth.v1.ValidateTokenRequest\x1a\x1e.auth.v1.ValidateTokenResponse\x129\n" + - "\x06Logout\x12\x16.auth.v1.LogoutRequest\x1a\x17.auth.v1.LogoutResponseBEZCgit.dcentral.systems/toolz/goplt/api/proto/generated/auth/v1;authv1b\x06proto3" - -var ( - file_auth_proto_rawDescOnce sync.Once - file_auth_proto_rawDescData []byte -) - -func file_auth_proto_rawDescGZIP() []byte { - file_auth_proto_rawDescOnce.Do(func() { - file_auth_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_auth_proto_rawDesc), len(file_auth_proto_rawDesc))) - }) - return file_auth_proto_rawDescData -} - -var file_auth_proto_msgTypes = make([]protoimpl.MessageInfo, 8) -var file_auth_proto_goTypes = []any{ - (*LoginRequest)(nil), // 0: auth.v1.LoginRequest - (*LoginResponse)(nil), // 1: auth.v1.LoginResponse - (*RefreshTokenRequest)(nil), // 2: auth.v1.RefreshTokenRequest - (*RefreshTokenResponse)(nil), // 3: auth.v1.RefreshTokenResponse - (*ValidateTokenRequest)(nil), // 4: auth.v1.ValidateTokenRequest - (*ValidateTokenResponse)(nil), // 5: auth.v1.ValidateTokenResponse - (*LogoutRequest)(nil), // 6: auth.v1.LogoutRequest - (*LogoutResponse)(nil), // 7: auth.v1.LogoutResponse -} -var file_auth_proto_depIdxs = []int32{ - 0, // 0: auth.v1.AuthService.Login:input_type -> auth.v1.LoginRequest - 2, // 1: auth.v1.AuthService.RefreshToken:input_type -> auth.v1.RefreshTokenRequest - 4, // 2: auth.v1.AuthService.ValidateToken:input_type -> auth.v1.ValidateTokenRequest - 6, // 3: auth.v1.AuthService.Logout:input_type -> auth.v1.LogoutRequest - 1, // 4: auth.v1.AuthService.Login:output_type -> auth.v1.LoginResponse - 3, // 5: auth.v1.AuthService.RefreshToken:output_type -> auth.v1.RefreshTokenResponse - 5, // 6: auth.v1.AuthService.ValidateToken:output_type -> auth.v1.ValidateTokenResponse - 7, // 7: auth.v1.AuthService.Logout:output_type -> auth.v1.LogoutResponse - 4, // [4:8] is the sub-list for method output_type - 0, // [0:4] is the sub-list for method input_type - 0, // [0:0] is the sub-list for extension type_name - 0, // [0:0] is the sub-list for extension extendee - 0, // [0:0] is the sub-list for field type_name -} - -func init() { file_auth_proto_init() } -func file_auth_proto_init() { - if File_auth_proto != nil { - return - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: unsafe.Slice(unsafe.StringData(file_auth_proto_rawDesc), len(file_auth_proto_rawDesc)), - NumEnums: 0, - NumMessages: 8, - NumExtensions: 0, - NumServices: 1, - }, - GoTypes: file_auth_proto_goTypes, - DependencyIndexes: file_auth_proto_depIdxs, - MessageInfos: file_auth_proto_msgTypes, - }.Build() - File_auth_proto = out.File - file_auth_proto_goTypes = nil - file_auth_proto_depIdxs = nil -} diff --git a/api/proto/generated/auth/v1/auth.pb.go b/api/proto/generated/auth/v1/auth.pb.go deleted file mode 100644 index ed71954..0000000 --- a/api/proto/generated/auth/v1/auth.pb.go +++ /dev/null @@ -1,568 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.36.10 -// protoc v6.30.2 -// source: auth.proto - -package authv1 - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - reflect "reflect" - sync "sync" - unsafe "unsafe" -) - -const ( - // Verify that this generated code is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) - // Verify that runtime/protoimpl is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) -) - -// LoginRequest contains login credentials. -type LoginRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Email string `protobuf:"bytes,1,opt,name=email,proto3" json:"email,omitempty"` - Password string `protobuf:"bytes,2,opt,name=password,proto3" json:"password,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *LoginRequest) Reset() { - *x = LoginRequest{} - mi := &file_auth_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *LoginRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*LoginRequest) ProtoMessage() {} - -func (x *LoginRequest) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[0] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use LoginRequest.ProtoReflect.Descriptor instead. -func (*LoginRequest) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{0} -} - -func (x *LoginRequest) GetEmail() string { - if x != nil { - return x.Email - } - return "" -} - -func (x *LoginRequest) GetPassword() string { - if x != nil { - return x.Password - } - return "" -} - -// LoginResponse contains authentication tokens. -type LoginResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - AccessToken string `protobuf:"bytes,1,opt,name=access_token,json=accessToken,proto3" json:"access_token,omitempty"` - RefreshToken string `protobuf:"bytes,2,opt,name=refresh_token,json=refreshToken,proto3" json:"refresh_token,omitempty"` - ExpiresIn int64 `protobuf:"varint,3,opt,name=expires_in,json=expiresIn,proto3" json:"expires_in,omitempty"` // seconds - TokenType string `protobuf:"bytes,4,opt,name=token_type,json=tokenType,proto3" json:"token_type,omitempty"` // "Bearer" - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *LoginResponse) Reset() { - *x = LoginResponse{} - mi := &file_auth_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *LoginResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*LoginResponse) ProtoMessage() {} - -func (x *LoginResponse) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[1] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use LoginResponse.ProtoReflect.Descriptor instead. -func (*LoginResponse) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{1} -} - -func (x *LoginResponse) GetAccessToken() string { - if x != nil { - return x.AccessToken - } - return "" -} - -func (x *LoginResponse) GetRefreshToken() string { - if x != nil { - return x.RefreshToken - } - return "" -} - -func (x *LoginResponse) GetExpiresIn() int64 { - if x != nil { - return x.ExpiresIn - } - return 0 -} - -func (x *LoginResponse) GetTokenType() string { - if x != nil { - return x.TokenType - } - return "" -} - -// RefreshTokenRequest contains a refresh token. -type RefreshTokenRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - RefreshToken string `protobuf:"bytes,1,opt,name=refresh_token,json=refreshToken,proto3" json:"refresh_token,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *RefreshTokenRequest) Reset() { - *x = RefreshTokenRequest{} - mi := &file_auth_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *RefreshTokenRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*RefreshTokenRequest) ProtoMessage() {} - -func (x *RefreshTokenRequest) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[2] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use RefreshTokenRequest.ProtoReflect.Descriptor instead. -func (*RefreshTokenRequest) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{2} -} - -func (x *RefreshTokenRequest) GetRefreshToken() string { - if x != nil { - return x.RefreshToken - } - return "" -} - -// RefreshTokenResponse contains new authentication tokens. -type RefreshTokenResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - AccessToken string `protobuf:"bytes,1,opt,name=access_token,json=accessToken,proto3" json:"access_token,omitempty"` - RefreshToken string `protobuf:"bytes,2,opt,name=refresh_token,json=refreshToken,proto3" json:"refresh_token,omitempty"` - ExpiresIn int64 `protobuf:"varint,3,opt,name=expires_in,json=expiresIn,proto3" json:"expires_in,omitempty"` // seconds - TokenType string `protobuf:"bytes,4,opt,name=token_type,json=tokenType,proto3" json:"token_type,omitempty"` // "Bearer" - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *RefreshTokenResponse) Reset() { - *x = RefreshTokenResponse{} - mi := &file_auth_proto_msgTypes[3] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *RefreshTokenResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*RefreshTokenResponse) ProtoMessage() {} - -func (x *RefreshTokenResponse) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[3] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use RefreshTokenResponse.ProtoReflect.Descriptor instead. -func (*RefreshTokenResponse) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{3} -} - -func (x *RefreshTokenResponse) GetAccessToken() string { - if x != nil { - return x.AccessToken - } - return "" -} - -func (x *RefreshTokenResponse) GetRefreshToken() string { - if x != nil { - return x.RefreshToken - } - return "" -} - -func (x *RefreshTokenResponse) GetExpiresIn() int64 { - if x != nil { - return x.ExpiresIn - } - return 0 -} - -func (x *RefreshTokenResponse) GetTokenType() string { - if x != nil { - return x.TokenType - } - return "" -} - -// ValidateTokenRequest contains a JWT token to validate. -type ValidateTokenRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *ValidateTokenRequest) Reset() { - *x = ValidateTokenRequest{} - mi := &file_auth_proto_msgTypes[4] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *ValidateTokenRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ValidateTokenRequest) ProtoMessage() {} - -func (x *ValidateTokenRequest) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[4] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use ValidateTokenRequest.ProtoReflect.Descriptor instead. -func (*ValidateTokenRequest) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{4} -} - -func (x *ValidateTokenRequest) GetToken() string { - if x != nil { - return x.Token - } - return "" -} - -// ValidateTokenResponse contains token claims. -type ValidateTokenResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - UserId string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"` - Email string `protobuf:"bytes,2,opt,name=email,proto3" json:"email,omitempty"` - Roles []string `protobuf:"bytes,3,rep,name=roles,proto3" json:"roles,omitempty"` - ExpiresAt int64 `protobuf:"varint,4,opt,name=expires_at,json=expiresAt,proto3" json:"expires_at,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *ValidateTokenResponse) Reset() { - *x = ValidateTokenResponse{} - mi := &file_auth_proto_msgTypes[5] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *ValidateTokenResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ValidateTokenResponse) ProtoMessage() {} - -func (x *ValidateTokenResponse) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[5] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use ValidateTokenResponse.ProtoReflect.Descriptor instead. -func (*ValidateTokenResponse) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{5} -} - -func (x *ValidateTokenResponse) GetUserId() string { - if x != nil { - return x.UserId - } - return "" -} - -func (x *ValidateTokenResponse) GetEmail() string { - if x != nil { - return x.Email - } - return "" -} - -func (x *ValidateTokenResponse) GetRoles() []string { - if x != nil { - return x.Roles - } - return nil -} - -func (x *ValidateTokenResponse) GetExpiresAt() int64 { - if x != nil { - return x.ExpiresAt - } - return 0 -} - -// LogoutRequest contains a refresh token to invalidate. -type LogoutRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - RefreshToken string `protobuf:"bytes,1,opt,name=refresh_token,json=refreshToken,proto3" json:"refresh_token,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *LogoutRequest) Reset() { - *x = LogoutRequest{} - mi := &file_auth_proto_msgTypes[6] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *LogoutRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*LogoutRequest) ProtoMessage() {} - -func (x *LogoutRequest) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[6] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use LogoutRequest.ProtoReflect.Descriptor instead. -func (*LogoutRequest) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{6} -} - -func (x *LogoutRequest) GetRefreshToken() string { - if x != nil { - return x.RefreshToken - } - return "" -} - -// LogoutResponse indicates success. -type LogoutResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *LogoutResponse) Reset() { - *x = LogoutResponse{} - mi := &file_auth_proto_msgTypes[7] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *LogoutResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*LogoutResponse) ProtoMessage() {} - -func (x *LogoutResponse) ProtoReflect() protoreflect.Message { - mi := &file_auth_proto_msgTypes[7] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use LogoutResponse.ProtoReflect.Descriptor instead. -func (*LogoutResponse) Descriptor() ([]byte, []int) { - return file_auth_proto_rawDescGZIP(), []int{7} -} - -func (x *LogoutResponse) GetSuccess() bool { - if x != nil { - return x.Success - } - return false -} - -var File_auth_proto protoreflect.FileDescriptor - -const file_auth_proto_rawDesc = "" + - "\n" + - "\n" + - "auth.proto\x12\aauth.v1\"@\n" + - "\fLoginRequest\x12\x14\n" + - "\x05email\x18\x01 \x01(\tR\x05email\x12\x1a\n" + - "\bpassword\x18\x02 \x01(\tR\bpassword\"\x95\x01\n" + - "\rLoginResponse\x12!\n" + - "\faccess_token\x18\x01 \x01(\tR\vaccessToken\x12#\n" + - "\rrefresh_token\x18\x02 \x01(\tR\frefreshToken\x12\x1d\n" + - "\n" + - "expires_in\x18\x03 \x01(\x03R\texpiresIn\x12\x1d\n" + - "\n" + - "token_type\x18\x04 \x01(\tR\ttokenType\":\n" + - "\x13RefreshTokenRequest\x12#\n" + - "\rrefresh_token\x18\x01 \x01(\tR\frefreshToken\"\x9c\x01\n" + - "\x14RefreshTokenResponse\x12!\n" + - "\faccess_token\x18\x01 \x01(\tR\vaccessToken\x12#\n" + - "\rrefresh_token\x18\x02 \x01(\tR\frefreshToken\x12\x1d\n" + - "\n" + - "expires_in\x18\x03 \x01(\x03R\texpiresIn\x12\x1d\n" + - "\n" + - "token_type\x18\x04 \x01(\tR\ttokenType\",\n" + - "\x14ValidateTokenRequest\x12\x14\n" + - "\x05token\x18\x01 \x01(\tR\x05token\"{\n" + - "\x15ValidateTokenResponse\x12\x17\n" + - "\auser_id\x18\x01 \x01(\tR\x06userId\x12\x14\n" + - "\x05email\x18\x02 \x01(\tR\x05email\x12\x14\n" + - "\x05roles\x18\x03 \x03(\tR\x05roles\x12\x1d\n" + - "\n" + - "expires_at\x18\x04 \x01(\x03R\texpiresAt\"4\n" + - "\rLogoutRequest\x12#\n" + - "\rrefresh_token\x18\x01 \x01(\tR\frefreshToken\"*\n" + - "\x0eLogoutResponse\x12\x18\n" + - "\asuccess\x18\x01 \x01(\bR\asuccess2\x9d\x02\n" + - "\vAuthService\x126\n" + - "\x05Login\x12\x15.auth.v1.LoginRequest\x1a\x16.auth.v1.LoginResponse\x12K\n" + - "\fRefreshToken\x12\x1c.auth.v1.RefreshTokenRequest\x1a\x1d.auth.v1.RefreshTokenResponse\x12N\n" + - "\rValidateToken\x12\x1d.auth.v1.ValidateTokenRequest\x1a\x1e.auth.v1.ValidateTokenResponse\x129\n" + - "\x06Logout\x12\x16.auth.v1.LogoutRequest\x1a\x17.auth.v1.LogoutResponseBEZCgit.dcentral.systems/toolz/goplt/api/proto/generated/auth/v1;authv1b\x06proto3" - -var ( - file_auth_proto_rawDescOnce sync.Once - file_auth_proto_rawDescData []byte -) - -func file_auth_proto_rawDescGZIP() []byte { - file_auth_proto_rawDescOnce.Do(func() { - file_auth_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_auth_proto_rawDesc), len(file_auth_proto_rawDesc))) - }) - return file_auth_proto_rawDescData -} - -var file_auth_proto_msgTypes = make([]protoimpl.MessageInfo, 8) -var file_auth_proto_goTypes = []any{ - (*LoginRequest)(nil), // 0: auth.v1.LoginRequest - (*LoginResponse)(nil), // 1: auth.v1.LoginResponse - (*RefreshTokenRequest)(nil), // 2: auth.v1.RefreshTokenRequest - (*RefreshTokenResponse)(nil), // 3: auth.v1.RefreshTokenResponse - (*ValidateTokenRequest)(nil), // 4: auth.v1.ValidateTokenRequest - (*ValidateTokenResponse)(nil), // 5: auth.v1.ValidateTokenResponse - (*LogoutRequest)(nil), // 6: auth.v1.LogoutRequest - (*LogoutResponse)(nil), // 7: auth.v1.LogoutResponse -} -var file_auth_proto_depIdxs = []int32{ - 0, // 0: auth.v1.AuthService.Login:input_type -> auth.v1.LoginRequest - 2, // 1: auth.v1.AuthService.RefreshToken:input_type -> auth.v1.RefreshTokenRequest - 4, // 2: auth.v1.AuthService.ValidateToken:input_type -> auth.v1.ValidateTokenRequest - 6, // 3: auth.v1.AuthService.Logout:input_type -> auth.v1.LogoutRequest - 1, // 4: auth.v1.AuthService.Login:output_type -> auth.v1.LoginResponse - 3, // 5: auth.v1.AuthService.RefreshToken:output_type -> auth.v1.RefreshTokenResponse - 5, // 6: auth.v1.AuthService.ValidateToken:output_type -> auth.v1.ValidateTokenResponse - 7, // 7: auth.v1.AuthService.Logout:output_type -> auth.v1.LogoutResponse - 4, // [4:8] is the sub-list for method output_type - 0, // [0:4] is the sub-list for method input_type - 0, // [0:0] is the sub-list for extension type_name - 0, // [0:0] is the sub-list for extension extendee - 0, // [0:0] is the sub-list for field type_name -} - -func init() { file_auth_proto_init() } -func file_auth_proto_init() { - if File_auth_proto != nil { - return - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: unsafe.Slice(unsafe.StringData(file_auth_proto_rawDesc), len(file_auth_proto_rawDesc)), - NumEnums: 0, - NumMessages: 8, - NumExtensions: 0, - NumServices: 1, - }, - GoTypes: file_auth_proto_goTypes, - DependencyIndexes: file_auth_proto_depIdxs, - MessageInfos: file_auth_proto_msgTypes, - }.Build() - File_auth_proto = out.File - file_auth_proto_goTypes = nil - file_auth_proto_depIdxs = nil -} diff --git a/api/proto/generated/auth/v1/auth_grpc.pb.go b/api/proto/generated/auth/v1/auth_grpc.pb.go deleted file mode 100644 index 1df8cf4..0000000 --- a/api/proto/generated/auth/v1/auth_grpc.pb.go +++ /dev/null @@ -1,247 +0,0 @@ -// Code generated by protoc-gen-go-grpc. DO NOT EDIT. -// versions: -// - protoc-gen-go-grpc v1.5.1 -// - protoc v6.30.2 -// source: auth.proto - -package authv1 - -import ( - context "context" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" -) - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -// Requires gRPC-Go v1.64.0 or later. -const _ = grpc.SupportPackageIsVersion9 - -const ( - AuthService_Login_FullMethodName = "/auth.v1.AuthService/Login" - AuthService_RefreshToken_FullMethodName = "/auth.v1.AuthService/RefreshToken" - AuthService_ValidateToken_FullMethodName = "/auth.v1.AuthService/ValidateToken" - AuthService_Logout_FullMethodName = "/auth.v1.AuthService/Logout" -) - -// AuthServiceClient is the client API for AuthService service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. -// -// AuthService provides authentication operations. -type AuthServiceClient interface { - // Login authenticates a user and returns access and refresh tokens. - Login(ctx context.Context, in *LoginRequest, opts ...grpc.CallOption) (*LoginResponse, error) - // RefreshToken refreshes an access token using a refresh token. - RefreshToken(ctx context.Context, in *RefreshTokenRequest, opts ...grpc.CallOption) (*RefreshTokenResponse, error) - // ValidateToken validates a JWT token and returns the token claims. - ValidateToken(ctx context.Context, in *ValidateTokenRequest, opts ...grpc.CallOption) (*ValidateTokenResponse, error) - // Logout invalidates a refresh token. - Logout(ctx context.Context, in *LogoutRequest, opts ...grpc.CallOption) (*LogoutResponse, error) -} - -type authServiceClient struct { - cc grpc.ClientConnInterface -} - -func NewAuthServiceClient(cc grpc.ClientConnInterface) AuthServiceClient { - return &authServiceClient{cc} -} - -func (c *authServiceClient) Login(ctx context.Context, in *LoginRequest, opts ...grpc.CallOption) (*LoginResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(LoginResponse) - err := c.cc.Invoke(ctx, AuthService_Login_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *authServiceClient) RefreshToken(ctx context.Context, in *RefreshTokenRequest, opts ...grpc.CallOption) (*RefreshTokenResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(RefreshTokenResponse) - err := c.cc.Invoke(ctx, AuthService_RefreshToken_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *authServiceClient) ValidateToken(ctx context.Context, in *ValidateTokenRequest, opts ...grpc.CallOption) (*ValidateTokenResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(ValidateTokenResponse) - err := c.cc.Invoke(ctx, AuthService_ValidateToken_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *authServiceClient) Logout(ctx context.Context, in *LogoutRequest, opts ...grpc.CallOption) (*LogoutResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(LogoutResponse) - err := c.cc.Invoke(ctx, AuthService_Logout_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -// AuthServiceServer is the server API for AuthService service. -// All implementations must embed UnimplementedAuthServiceServer -// for forward compatibility. -// -// AuthService provides authentication operations. -type AuthServiceServer interface { - // Login authenticates a user and returns access and refresh tokens. - Login(context.Context, *LoginRequest) (*LoginResponse, error) - // RefreshToken refreshes an access token using a refresh token. - RefreshToken(context.Context, *RefreshTokenRequest) (*RefreshTokenResponse, error) - // ValidateToken validates a JWT token and returns the token claims. - ValidateToken(context.Context, *ValidateTokenRequest) (*ValidateTokenResponse, error) - // Logout invalidates a refresh token. - Logout(context.Context, *LogoutRequest) (*LogoutResponse, error) - mustEmbedUnimplementedAuthServiceServer() -} - -// UnimplementedAuthServiceServer must be embedded to have -// forward compatible implementations. -// -// NOTE: this should be embedded by value instead of pointer to avoid a nil -// pointer dereference when methods are called. -type UnimplementedAuthServiceServer struct{} - -func (UnimplementedAuthServiceServer) Login(context.Context, *LoginRequest) (*LoginResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Login not implemented") -} -func (UnimplementedAuthServiceServer) RefreshToken(context.Context, *RefreshTokenRequest) (*RefreshTokenResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method RefreshToken not implemented") -} -func (UnimplementedAuthServiceServer) ValidateToken(context.Context, *ValidateTokenRequest) (*ValidateTokenResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ValidateToken not implemented") -} -func (UnimplementedAuthServiceServer) Logout(context.Context, *LogoutRequest) (*LogoutResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Logout not implemented") -} -func (UnimplementedAuthServiceServer) mustEmbedUnimplementedAuthServiceServer() {} -func (UnimplementedAuthServiceServer) testEmbeddedByValue() {} - -// UnsafeAuthServiceServer may be embedded to opt out of forward compatibility for this service. -// Use of this interface is not recommended, as added methods to AuthServiceServer will -// result in compilation errors. -type UnsafeAuthServiceServer interface { - mustEmbedUnimplementedAuthServiceServer() -} - -func RegisterAuthServiceServer(s grpc.ServiceRegistrar, srv AuthServiceServer) { - // If the following call pancis, it indicates UnimplementedAuthServiceServer was - // embedded by pointer and is nil. This will cause panics if an - // unimplemented method is ever invoked, so we test this at initialization - // time to prevent it from happening at runtime later due to I/O. - if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { - t.testEmbeddedByValue() - } - s.RegisterService(&AuthService_ServiceDesc, srv) -} - -func _AuthService_Login_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(LoginRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthServiceServer).Login(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthService_Login_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthServiceServer).Login(ctx, req.(*LoginRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _AuthService_RefreshToken_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(RefreshTokenRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthServiceServer).RefreshToken(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthService_RefreshToken_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthServiceServer).RefreshToken(ctx, req.(*RefreshTokenRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _AuthService_ValidateToken_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ValidateTokenRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthServiceServer).ValidateToken(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthService_ValidateToken_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthServiceServer).ValidateToken(ctx, req.(*ValidateTokenRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _AuthService_Logout_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(LogoutRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthServiceServer).Logout(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthService_Logout_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthServiceServer).Logout(ctx, req.(*LogoutRequest)) - } - return interceptor(ctx, in, info, handler) -} - -// AuthService_ServiceDesc is the grpc.ServiceDesc for AuthService service. -// It's only intended for direct use with grpc.RegisterService, -// and not to be introspected or modified (even as a copy) -var AuthService_ServiceDesc = grpc.ServiceDesc{ - ServiceName: "auth.v1.AuthService", - HandlerType: (*AuthServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Login", - Handler: _AuthService_Login_Handler, - }, - { - MethodName: "RefreshToken", - Handler: _AuthService_RefreshToken_Handler, - }, - { - MethodName: "ValidateToken", - Handler: _AuthService_ValidateToken_Handler, - }, - { - MethodName: "Logout", - Handler: _AuthService_Logout_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "auth.proto", -} diff --git a/api/proto/generated/auth_grpc.pb.go b/api/proto/generated/auth_grpc.pb.go deleted file mode 100644 index 1df8cf4..0000000 --- a/api/proto/generated/auth_grpc.pb.go +++ /dev/null @@ -1,247 +0,0 @@ -// Code generated by protoc-gen-go-grpc. DO NOT EDIT. -// versions: -// - protoc-gen-go-grpc v1.5.1 -// - protoc v6.30.2 -// source: auth.proto - -package authv1 - -import ( - context "context" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" -) - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -// Requires gRPC-Go v1.64.0 or later. -const _ = grpc.SupportPackageIsVersion9 - -const ( - AuthService_Login_FullMethodName = "/auth.v1.AuthService/Login" - AuthService_RefreshToken_FullMethodName = "/auth.v1.AuthService/RefreshToken" - AuthService_ValidateToken_FullMethodName = "/auth.v1.AuthService/ValidateToken" - AuthService_Logout_FullMethodName = "/auth.v1.AuthService/Logout" -) - -// AuthServiceClient is the client API for AuthService service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. -// -// AuthService provides authentication operations. -type AuthServiceClient interface { - // Login authenticates a user and returns access and refresh tokens. - Login(ctx context.Context, in *LoginRequest, opts ...grpc.CallOption) (*LoginResponse, error) - // RefreshToken refreshes an access token using a refresh token. - RefreshToken(ctx context.Context, in *RefreshTokenRequest, opts ...grpc.CallOption) (*RefreshTokenResponse, error) - // ValidateToken validates a JWT token and returns the token claims. - ValidateToken(ctx context.Context, in *ValidateTokenRequest, opts ...grpc.CallOption) (*ValidateTokenResponse, error) - // Logout invalidates a refresh token. - Logout(ctx context.Context, in *LogoutRequest, opts ...grpc.CallOption) (*LogoutResponse, error) -} - -type authServiceClient struct { - cc grpc.ClientConnInterface -} - -func NewAuthServiceClient(cc grpc.ClientConnInterface) AuthServiceClient { - return &authServiceClient{cc} -} - -func (c *authServiceClient) Login(ctx context.Context, in *LoginRequest, opts ...grpc.CallOption) (*LoginResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(LoginResponse) - err := c.cc.Invoke(ctx, AuthService_Login_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *authServiceClient) RefreshToken(ctx context.Context, in *RefreshTokenRequest, opts ...grpc.CallOption) (*RefreshTokenResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(RefreshTokenResponse) - err := c.cc.Invoke(ctx, AuthService_RefreshToken_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *authServiceClient) ValidateToken(ctx context.Context, in *ValidateTokenRequest, opts ...grpc.CallOption) (*ValidateTokenResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(ValidateTokenResponse) - err := c.cc.Invoke(ctx, AuthService_ValidateToken_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *authServiceClient) Logout(ctx context.Context, in *LogoutRequest, opts ...grpc.CallOption) (*LogoutResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(LogoutResponse) - err := c.cc.Invoke(ctx, AuthService_Logout_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -// AuthServiceServer is the server API for AuthService service. -// All implementations must embed UnimplementedAuthServiceServer -// for forward compatibility. -// -// AuthService provides authentication operations. -type AuthServiceServer interface { - // Login authenticates a user and returns access and refresh tokens. - Login(context.Context, *LoginRequest) (*LoginResponse, error) - // RefreshToken refreshes an access token using a refresh token. - RefreshToken(context.Context, *RefreshTokenRequest) (*RefreshTokenResponse, error) - // ValidateToken validates a JWT token and returns the token claims. - ValidateToken(context.Context, *ValidateTokenRequest) (*ValidateTokenResponse, error) - // Logout invalidates a refresh token. - Logout(context.Context, *LogoutRequest) (*LogoutResponse, error) - mustEmbedUnimplementedAuthServiceServer() -} - -// UnimplementedAuthServiceServer must be embedded to have -// forward compatible implementations. -// -// NOTE: this should be embedded by value instead of pointer to avoid a nil -// pointer dereference when methods are called. -type UnimplementedAuthServiceServer struct{} - -func (UnimplementedAuthServiceServer) Login(context.Context, *LoginRequest) (*LoginResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Login not implemented") -} -func (UnimplementedAuthServiceServer) RefreshToken(context.Context, *RefreshTokenRequest) (*RefreshTokenResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method RefreshToken not implemented") -} -func (UnimplementedAuthServiceServer) ValidateToken(context.Context, *ValidateTokenRequest) (*ValidateTokenResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ValidateToken not implemented") -} -func (UnimplementedAuthServiceServer) Logout(context.Context, *LogoutRequest) (*LogoutResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Logout not implemented") -} -func (UnimplementedAuthServiceServer) mustEmbedUnimplementedAuthServiceServer() {} -func (UnimplementedAuthServiceServer) testEmbeddedByValue() {} - -// UnsafeAuthServiceServer may be embedded to opt out of forward compatibility for this service. -// Use of this interface is not recommended, as added methods to AuthServiceServer will -// result in compilation errors. -type UnsafeAuthServiceServer interface { - mustEmbedUnimplementedAuthServiceServer() -} - -func RegisterAuthServiceServer(s grpc.ServiceRegistrar, srv AuthServiceServer) { - // If the following call pancis, it indicates UnimplementedAuthServiceServer was - // embedded by pointer and is nil. This will cause panics if an - // unimplemented method is ever invoked, so we test this at initialization - // time to prevent it from happening at runtime later due to I/O. - if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { - t.testEmbeddedByValue() - } - s.RegisterService(&AuthService_ServiceDesc, srv) -} - -func _AuthService_Login_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(LoginRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthServiceServer).Login(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthService_Login_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthServiceServer).Login(ctx, req.(*LoginRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _AuthService_RefreshToken_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(RefreshTokenRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthServiceServer).RefreshToken(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthService_RefreshToken_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthServiceServer).RefreshToken(ctx, req.(*RefreshTokenRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _AuthService_ValidateToken_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ValidateTokenRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthServiceServer).ValidateToken(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthService_ValidateToken_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthServiceServer).ValidateToken(ctx, req.(*ValidateTokenRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _AuthService_Logout_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(LogoutRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthServiceServer).Logout(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthService_Logout_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthServiceServer).Logout(ctx, req.(*LogoutRequest)) - } - return interceptor(ctx, in, info, handler) -} - -// AuthService_ServiceDesc is the grpc.ServiceDesc for AuthService service. -// It's only intended for direct use with grpc.RegisterService, -// and not to be introspected or modified (even as a copy) -var AuthService_ServiceDesc = grpc.ServiceDesc{ - ServiceName: "auth.v1.AuthService", - HandlerType: (*AuthServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Login", - Handler: _AuthService_Login_Handler, - }, - { - MethodName: "RefreshToken", - Handler: _AuthService_RefreshToken_Handler, - }, - { - MethodName: "ValidateToken", - Handler: _AuthService_ValidateToken_Handler, - }, - { - MethodName: "Logout", - Handler: _AuthService_Logout_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "auth.proto", -} diff --git a/api/proto/generated/authz.pb.go b/api/proto/generated/authz.pb.go deleted file mode 100644 index b1bbb44..0000000 --- a/api/proto/generated/authz.pb.go +++ /dev/null @@ -1,658 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.36.10 -// protoc v6.30.2 -// source: authz.proto - -package authzv1 - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - reflect "reflect" - sync "sync" - unsafe "unsafe" -) - -const ( - // Verify that this generated code is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) - // Verify that runtime/protoimpl is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) -) - -// Permission represents a permission in the system. -type Permission struct { - state protoimpl.MessageState `protogen:"open.v1"` - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - Code string `protobuf:"bytes,2,opt,name=code,proto3" json:"code,omitempty"` - Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` - Description string `protobuf:"bytes,4,opt,name=description,proto3" json:"description,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *Permission) Reset() { - *x = Permission{} - mi := &file_authz_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *Permission) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*Permission) ProtoMessage() {} - -func (x *Permission) ProtoReflect() protoreflect.Message { - mi := &file_authz_proto_msgTypes[0] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use Permission.ProtoReflect.Descriptor instead. -func (*Permission) Descriptor() ([]byte, []int) { - return file_authz_proto_rawDescGZIP(), []int{0} -} - -func (x *Permission) GetId() string { - if x != nil { - return x.Id - } - return "" -} - -func (x *Permission) GetCode() string { - if x != nil { - return x.Code - } - return "" -} - -func (x *Permission) GetName() string { - if x != nil { - return x.Name - } - return "" -} - -func (x *Permission) GetDescription() string { - if x != nil { - return x.Description - } - return "" -} - -// Role represents a role in the system. -type Role struct { - state protoimpl.MessageState `protogen:"open.v1"` - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` - Description string `protobuf:"bytes,3,opt,name=description,proto3" json:"description,omitempty"` - Permissions []string `protobuf:"bytes,4,rep,name=permissions,proto3" json:"permissions,omitempty"` // Permission codes - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *Role) Reset() { - *x = Role{} - mi := &file_authz_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *Role) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*Role) ProtoMessage() {} - -func (x *Role) ProtoReflect() protoreflect.Message { - mi := &file_authz_proto_msgTypes[1] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use Role.ProtoReflect.Descriptor instead. -func (*Role) Descriptor() ([]byte, []int) { - return file_authz_proto_rawDescGZIP(), []int{1} -} - -func (x *Role) GetId() string { - if x != nil { - return x.Id - } - return "" -} - -func (x *Role) GetName() string { - if x != nil { - return x.Name - } - return "" -} - -func (x *Role) GetDescription() string { - if x != nil { - return x.Description - } - return "" -} - -func (x *Role) GetPermissions() []string { - if x != nil { - return x.Permissions - } - return nil -} - -// AuthorizeRequest contains user ID and permission to check. -type AuthorizeRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - UserId string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"` - Permission string `protobuf:"bytes,2,opt,name=permission,proto3" json:"permission,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *AuthorizeRequest) Reset() { - *x = AuthorizeRequest{} - mi := &file_authz_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *AuthorizeRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*AuthorizeRequest) ProtoMessage() {} - -func (x *AuthorizeRequest) ProtoReflect() protoreflect.Message { - mi := &file_authz_proto_msgTypes[2] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use AuthorizeRequest.ProtoReflect.Descriptor instead. -func (*AuthorizeRequest) Descriptor() ([]byte, []int) { - return file_authz_proto_rawDescGZIP(), []int{2} -} - -func (x *AuthorizeRequest) GetUserId() string { - if x != nil { - return x.UserId - } - return "" -} - -func (x *AuthorizeRequest) GetPermission() string { - if x != nil { - return x.Permission - } - return "" -} - -// AuthorizeResponse indicates authorization result. -type AuthorizeResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Authorized bool `protobuf:"varint,1,opt,name=authorized,proto3" json:"authorized,omitempty"` - Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *AuthorizeResponse) Reset() { - *x = AuthorizeResponse{} - mi := &file_authz_proto_msgTypes[3] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *AuthorizeResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*AuthorizeResponse) ProtoMessage() {} - -func (x *AuthorizeResponse) ProtoReflect() protoreflect.Message { - mi := &file_authz_proto_msgTypes[3] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use AuthorizeResponse.ProtoReflect.Descriptor instead. -func (*AuthorizeResponse) Descriptor() ([]byte, []int) { - return file_authz_proto_rawDescGZIP(), []int{3} -} - -func (x *AuthorizeResponse) GetAuthorized() bool { - if x != nil { - return x.Authorized - } - return false -} - -func (x *AuthorizeResponse) GetMessage() string { - if x != nil { - return x.Message - } - return "" -} - -// HasPermissionRequest contains user ID and permission to check. -type HasPermissionRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - UserId string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"` - Permission string `protobuf:"bytes,2,opt,name=permission,proto3" json:"permission,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *HasPermissionRequest) Reset() { - *x = HasPermissionRequest{} - mi := &file_authz_proto_msgTypes[4] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *HasPermissionRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*HasPermissionRequest) ProtoMessage() {} - -func (x *HasPermissionRequest) ProtoReflect() protoreflect.Message { - mi := &file_authz_proto_msgTypes[4] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use HasPermissionRequest.ProtoReflect.Descriptor instead. -func (*HasPermissionRequest) Descriptor() ([]byte, []int) { - return file_authz_proto_rawDescGZIP(), []int{4} -} - -func (x *HasPermissionRequest) GetUserId() string { - if x != nil { - return x.UserId - } - return "" -} - -func (x *HasPermissionRequest) GetPermission() string { - if x != nil { - return x.Permission - } - return "" -} - -// HasPermissionResponse indicates if the user has the permission. -type HasPermissionResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - HasPermission bool `protobuf:"varint,1,opt,name=has_permission,json=hasPermission,proto3" json:"has_permission,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *HasPermissionResponse) Reset() { - *x = HasPermissionResponse{} - mi := &file_authz_proto_msgTypes[5] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *HasPermissionResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*HasPermissionResponse) ProtoMessage() {} - -func (x *HasPermissionResponse) ProtoReflect() protoreflect.Message { - mi := &file_authz_proto_msgTypes[5] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use HasPermissionResponse.ProtoReflect.Descriptor instead. -func (*HasPermissionResponse) Descriptor() ([]byte, []int) { - return file_authz_proto_rawDescGZIP(), []int{5} -} - -func (x *HasPermissionResponse) GetHasPermission() bool { - if x != nil { - return x.HasPermission - } - return false -} - -// GetUserPermissionsRequest contains a user ID. -type GetUserPermissionsRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - UserId string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *GetUserPermissionsRequest) Reset() { - *x = GetUserPermissionsRequest{} - mi := &file_authz_proto_msgTypes[6] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *GetUserPermissionsRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*GetUserPermissionsRequest) ProtoMessage() {} - -func (x *GetUserPermissionsRequest) ProtoReflect() protoreflect.Message { - mi := &file_authz_proto_msgTypes[6] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use GetUserPermissionsRequest.ProtoReflect.Descriptor instead. -func (*GetUserPermissionsRequest) Descriptor() ([]byte, []int) { - return file_authz_proto_rawDescGZIP(), []int{6} -} - -func (x *GetUserPermissionsRequest) GetUserId() string { - if x != nil { - return x.UserId - } - return "" -} - -// GetUserPermissionsResponse contains all permissions for the user. -type GetUserPermissionsResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Permissions []*Permission `protobuf:"bytes,1,rep,name=permissions,proto3" json:"permissions,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *GetUserPermissionsResponse) Reset() { - *x = GetUserPermissionsResponse{} - mi := &file_authz_proto_msgTypes[7] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *GetUserPermissionsResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*GetUserPermissionsResponse) ProtoMessage() {} - -func (x *GetUserPermissionsResponse) ProtoReflect() protoreflect.Message { - mi := &file_authz_proto_msgTypes[7] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use GetUserPermissionsResponse.ProtoReflect.Descriptor instead. -func (*GetUserPermissionsResponse) Descriptor() ([]byte, []int) { - return file_authz_proto_rawDescGZIP(), []int{7} -} - -func (x *GetUserPermissionsResponse) GetPermissions() []*Permission { - if x != nil { - return x.Permissions - } - return nil -} - -// GetUserRolesRequest contains a user ID. -type GetUserRolesRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - UserId string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *GetUserRolesRequest) Reset() { - *x = GetUserRolesRequest{} - mi := &file_authz_proto_msgTypes[8] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *GetUserRolesRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*GetUserRolesRequest) ProtoMessage() {} - -func (x *GetUserRolesRequest) ProtoReflect() protoreflect.Message { - mi := &file_authz_proto_msgTypes[8] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use GetUserRolesRequest.ProtoReflect.Descriptor instead. -func (*GetUserRolesRequest) Descriptor() ([]byte, []int) { - return file_authz_proto_rawDescGZIP(), []int{8} -} - -func (x *GetUserRolesRequest) GetUserId() string { - if x != nil { - return x.UserId - } - return "" -} - -// GetUserRolesResponse contains all roles for the user. -type GetUserRolesResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Roles []*Role `protobuf:"bytes,1,rep,name=roles,proto3" json:"roles,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *GetUserRolesResponse) Reset() { - *x = GetUserRolesResponse{} - mi := &file_authz_proto_msgTypes[9] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *GetUserRolesResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*GetUserRolesResponse) ProtoMessage() {} - -func (x *GetUserRolesResponse) ProtoReflect() protoreflect.Message { - mi := &file_authz_proto_msgTypes[9] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use GetUserRolesResponse.ProtoReflect.Descriptor instead. -func (*GetUserRolesResponse) Descriptor() ([]byte, []int) { - return file_authz_proto_rawDescGZIP(), []int{9} -} - -func (x *GetUserRolesResponse) GetRoles() []*Role { - if x != nil { - return x.Roles - } - return nil -} - -var File_authz_proto protoreflect.FileDescriptor - -const file_authz_proto_rawDesc = "" + - "\n" + - "\vauthz.proto\x12\bauthz.v1\"f\n" + - "\n" + - "Permission\x12\x0e\n" + - "\x02id\x18\x01 \x01(\tR\x02id\x12\x12\n" + - "\x04code\x18\x02 \x01(\tR\x04code\x12\x12\n" + - "\x04name\x18\x03 \x01(\tR\x04name\x12 \n" + - "\vdescription\x18\x04 \x01(\tR\vdescription\"n\n" + - "\x04Role\x12\x0e\n" + - "\x02id\x18\x01 \x01(\tR\x02id\x12\x12\n" + - "\x04name\x18\x02 \x01(\tR\x04name\x12 \n" + - "\vdescription\x18\x03 \x01(\tR\vdescription\x12 \n" + - "\vpermissions\x18\x04 \x03(\tR\vpermissions\"K\n" + - "\x10AuthorizeRequest\x12\x17\n" + - "\auser_id\x18\x01 \x01(\tR\x06userId\x12\x1e\n" + - "\n" + - "permission\x18\x02 \x01(\tR\n" + - "permission\"M\n" + - "\x11AuthorizeResponse\x12\x1e\n" + - "\n" + - "authorized\x18\x01 \x01(\bR\n" + - "authorized\x12\x18\n" + - "\amessage\x18\x02 \x01(\tR\amessage\"O\n" + - "\x14HasPermissionRequest\x12\x17\n" + - "\auser_id\x18\x01 \x01(\tR\x06userId\x12\x1e\n" + - "\n" + - "permission\x18\x02 \x01(\tR\n" + - "permission\">\n" + - "\x15HasPermissionResponse\x12%\n" + - "\x0ehas_permission\x18\x01 \x01(\bR\rhasPermission\"4\n" + - "\x19GetUserPermissionsRequest\x12\x17\n" + - "\auser_id\x18\x01 \x01(\tR\x06userId\"T\n" + - "\x1aGetUserPermissionsResponse\x126\n" + - "\vpermissions\x18\x01 \x03(\v2\x14.authz.v1.PermissionR\vpermissions\".\n" + - "\x13GetUserRolesRequest\x12\x17\n" + - "\auser_id\x18\x01 \x01(\tR\x06userId\"<\n" + - "\x14GetUserRolesResponse\x12$\n" + - "\x05roles\x18\x01 \x03(\v2\x0e.authz.v1.RoleR\x05roles2\xd6\x02\n" + - "\fAuthzService\x12D\n" + - "\tAuthorize\x12\x1a.authz.v1.AuthorizeRequest\x1a\x1b.authz.v1.AuthorizeResponse\x12P\n" + - "\rHasPermission\x12\x1e.authz.v1.HasPermissionRequest\x1a\x1f.authz.v1.HasPermissionResponse\x12_\n" + - "\x12GetUserPermissions\x12#.authz.v1.GetUserPermissionsRequest\x1a$.authz.v1.GetUserPermissionsResponse\x12M\n" + - "\fGetUserRoles\x12\x1d.authz.v1.GetUserRolesRequest\x1a\x1e.authz.v1.GetUserRolesResponseBGZEgit.dcentral.systems/toolz/goplt/api/proto/generated/authz/v1;authzv1b\x06proto3" - -var ( - file_authz_proto_rawDescOnce sync.Once - file_authz_proto_rawDescData []byte -) - -func file_authz_proto_rawDescGZIP() []byte { - file_authz_proto_rawDescOnce.Do(func() { - file_authz_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_authz_proto_rawDesc), len(file_authz_proto_rawDesc))) - }) - return file_authz_proto_rawDescData -} - -var file_authz_proto_msgTypes = make([]protoimpl.MessageInfo, 10) -var file_authz_proto_goTypes = []any{ - (*Permission)(nil), // 0: authz.v1.Permission - (*Role)(nil), // 1: authz.v1.Role - (*AuthorizeRequest)(nil), // 2: authz.v1.AuthorizeRequest - (*AuthorizeResponse)(nil), // 3: authz.v1.AuthorizeResponse - (*HasPermissionRequest)(nil), // 4: authz.v1.HasPermissionRequest - (*HasPermissionResponse)(nil), // 5: authz.v1.HasPermissionResponse - (*GetUserPermissionsRequest)(nil), // 6: authz.v1.GetUserPermissionsRequest - (*GetUserPermissionsResponse)(nil), // 7: authz.v1.GetUserPermissionsResponse - (*GetUserRolesRequest)(nil), // 8: authz.v1.GetUserRolesRequest - (*GetUserRolesResponse)(nil), // 9: authz.v1.GetUserRolesResponse -} -var file_authz_proto_depIdxs = []int32{ - 0, // 0: authz.v1.GetUserPermissionsResponse.permissions:type_name -> authz.v1.Permission - 1, // 1: authz.v1.GetUserRolesResponse.roles:type_name -> authz.v1.Role - 2, // 2: authz.v1.AuthzService.Authorize:input_type -> authz.v1.AuthorizeRequest - 4, // 3: authz.v1.AuthzService.HasPermission:input_type -> authz.v1.HasPermissionRequest - 6, // 4: authz.v1.AuthzService.GetUserPermissions:input_type -> authz.v1.GetUserPermissionsRequest - 8, // 5: authz.v1.AuthzService.GetUserRoles:input_type -> authz.v1.GetUserRolesRequest - 3, // 6: authz.v1.AuthzService.Authorize:output_type -> authz.v1.AuthorizeResponse - 5, // 7: authz.v1.AuthzService.HasPermission:output_type -> authz.v1.HasPermissionResponse - 7, // 8: authz.v1.AuthzService.GetUserPermissions:output_type -> authz.v1.GetUserPermissionsResponse - 9, // 9: authz.v1.AuthzService.GetUserRoles:output_type -> authz.v1.GetUserRolesResponse - 6, // [6:10] is the sub-list for method output_type - 2, // [2:6] is the sub-list for method input_type - 2, // [2:2] is the sub-list for extension type_name - 2, // [2:2] is the sub-list for extension extendee - 0, // [0:2] is the sub-list for field type_name -} - -func init() { file_authz_proto_init() } -func file_authz_proto_init() { - if File_authz_proto != nil { - return - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: unsafe.Slice(unsafe.StringData(file_authz_proto_rawDesc), len(file_authz_proto_rawDesc)), - NumEnums: 0, - NumMessages: 10, - NumExtensions: 0, - NumServices: 1, - }, - GoTypes: file_authz_proto_goTypes, - DependencyIndexes: file_authz_proto_depIdxs, - MessageInfos: file_authz_proto_msgTypes, - }.Build() - File_authz_proto = out.File - file_authz_proto_goTypes = nil - file_authz_proto_depIdxs = nil -} diff --git a/api/proto/generated/authz/v1/authz.pb.go b/api/proto/generated/authz/v1/authz.pb.go deleted file mode 100644 index b1bbb44..0000000 --- a/api/proto/generated/authz/v1/authz.pb.go +++ /dev/null @@ -1,658 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.36.10 -// protoc v6.30.2 -// source: authz.proto - -package authzv1 - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - reflect "reflect" - sync "sync" - unsafe "unsafe" -) - -const ( - // Verify that this generated code is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) - // Verify that runtime/protoimpl is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) -) - -// Permission represents a permission in the system. -type Permission struct { - state protoimpl.MessageState `protogen:"open.v1"` - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - Code string `protobuf:"bytes,2,opt,name=code,proto3" json:"code,omitempty"` - Name string `protobuf:"bytes,3,opt,name=name,proto3" json:"name,omitempty"` - Description string `protobuf:"bytes,4,opt,name=description,proto3" json:"description,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *Permission) Reset() { - *x = Permission{} - mi := &file_authz_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *Permission) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*Permission) ProtoMessage() {} - -func (x *Permission) ProtoReflect() protoreflect.Message { - mi := &file_authz_proto_msgTypes[0] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use Permission.ProtoReflect.Descriptor instead. -func (*Permission) Descriptor() ([]byte, []int) { - return file_authz_proto_rawDescGZIP(), []int{0} -} - -func (x *Permission) GetId() string { - if x != nil { - return x.Id - } - return "" -} - -func (x *Permission) GetCode() string { - if x != nil { - return x.Code - } - return "" -} - -func (x *Permission) GetName() string { - if x != nil { - return x.Name - } - return "" -} - -func (x *Permission) GetDescription() string { - if x != nil { - return x.Description - } - return "" -} - -// Role represents a role in the system. -type Role struct { - state protoimpl.MessageState `protogen:"open.v1"` - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` - Description string `protobuf:"bytes,3,opt,name=description,proto3" json:"description,omitempty"` - Permissions []string `protobuf:"bytes,4,rep,name=permissions,proto3" json:"permissions,omitempty"` // Permission codes - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *Role) Reset() { - *x = Role{} - mi := &file_authz_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *Role) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*Role) ProtoMessage() {} - -func (x *Role) ProtoReflect() protoreflect.Message { - mi := &file_authz_proto_msgTypes[1] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use Role.ProtoReflect.Descriptor instead. -func (*Role) Descriptor() ([]byte, []int) { - return file_authz_proto_rawDescGZIP(), []int{1} -} - -func (x *Role) GetId() string { - if x != nil { - return x.Id - } - return "" -} - -func (x *Role) GetName() string { - if x != nil { - return x.Name - } - return "" -} - -func (x *Role) GetDescription() string { - if x != nil { - return x.Description - } - return "" -} - -func (x *Role) GetPermissions() []string { - if x != nil { - return x.Permissions - } - return nil -} - -// AuthorizeRequest contains user ID and permission to check. -type AuthorizeRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - UserId string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"` - Permission string `protobuf:"bytes,2,opt,name=permission,proto3" json:"permission,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *AuthorizeRequest) Reset() { - *x = AuthorizeRequest{} - mi := &file_authz_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *AuthorizeRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*AuthorizeRequest) ProtoMessage() {} - -func (x *AuthorizeRequest) ProtoReflect() protoreflect.Message { - mi := &file_authz_proto_msgTypes[2] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use AuthorizeRequest.ProtoReflect.Descriptor instead. -func (*AuthorizeRequest) Descriptor() ([]byte, []int) { - return file_authz_proto_rawDescGZIP(), []int{2} -} - -func (x *AuthorizeRequest) GetUserId() string { - if x != nil { - return x.UserId - } - return "" -} - -func (x *AuthorizeRequest) GetPermission() string { - if x != nil { - return x.Permission - } - return "" -} - -// AuthorizeResponse indicates authorization result. -type AuthorizeResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Authorized bool `protobuf:"varint,1,opt,name=authorized,proto3" json:"authorized,omitempty"` - Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *AuthorizeResponse) Reset() { - *x = AuthorizeResponse{} - mi := &file_authz_proto_msgTypes[3] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *AuthorizeResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*AuthorizeResponse) ProtoMessage() {} - -func (x *AuthorizeResponse) ProtoReflect() protoreflect.Message { - mi := &file_authz_proto_msgTypes[3] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use AuthorizeResponse.ProtoReflect.Descriptor instead. -func (*AuthorizeResponse) Descriptor() ([]byte, []int) { - return file_authz_proto_rawDescGZIP(), []int{3} -} - -func (x *AuthorizeResponse) GetAuthorized() bool { - if x != nil { - return x.Authorized - } - return false -} - -func (x *AuthorizeResponse) GetMessage() string { - if x != nil { - return x.Message - } - return "" -} - -// HasPermissionRequest contains user ID and permission to check. -type HasPermissionRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - UserId string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"` - Permission string `protobuf:"bytes,2,opt,name=permission,proto3" json:"permission,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *HasPermissionRequest) Reset() { - *x = HasPermissionRequest{} - mi := &file_authz_proto_msgTypes[4] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *HasPermissionRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*HasPermissionRequest) ProtoMessage() {} - -func (x *HasPermissionRequest) ProtoReflect() protoreflect.Message { - mi := &file_authz_proto_msgTypes[4] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use HasPermissionRequest.ProtoReflect.Descriptor instead. -func (*HasPermissionRequest) Descriptor() ([]byte, []int) { - return file_authz_proto_rawDescGZIP(), []int{4} -} - -func (x *HasPermissionRequest) GetUserId() string { - if x != nil { - return x.UserId - } - return "" -} - -func (x *HasPermissionRequest) GetPermission() string { - if x != nil { - return x.Permission - } - return "" -} - -// HasPermissionResponse indicates if the user has the permission. -type HasPermissionResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - HasPermission bool `protobuf:"varint,1,opt,name=has_permission,json=hasPermission,proto3" json:"has_permission,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *HasPermissionResponse) Reset() { - *x = HasPermissionResponse{} - mi := &file_authz_proto_msgTypes[5] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *HasPermissionResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*HasPermissionResponse) ProtoMessage() {} - -func (x *HasPermissionResponse) ProtoReflect() protoreflect.Message { - mi := &file_authz_proto_msgTypes[5] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use HasPermissionResponse.ProtoReflect.Descriptor instead. -func (*HasPermissionResponse) Descriptor() ([]byte, []int) { - return file_authz_proto_rawDescGZIP(), []int{5} -} - -func (x *HasPermissionResponse) GetHasPermission() bool { - if x != nil { - return x.HasPermission - } - return false -} - -// GetUserPermissionsRequest contains a user ID. -type GetUserPermissionsRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - UserId string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *GetUserPermissionsRequest) Reset() { - *x = GetUserPermissionsRequest{} - mi := &file_authz_proto_msgTypes[6] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *GetUserPermissionsRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*GetUserPermissionsRequest) ProtoMessage() {} - -func (x *GetUserPermissionsRequest) ProtoReflect() protoreflect.Message { - mi := &file_authz_proto_msgTypes[6] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use GetUserPermissionsRequest.ProtoReflect.Descriptor instead. -func (*GetUserPermissionsRequest) Descriptor() ([]byte, []int) { - return file_authz_proto_rawDescGZIP(), []int{6} -} - -func (x *GetUserPermissionsRequest) GetUserId() string { - if x != nil { - return x.UserId - } - return "" -} - -// GetUserPermissionsResponse contains all permissions for the user. -type GetUserPermissionsResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Permissions []*Permission `protobuf:"bytes,1,rep,name=permissions,proto3" json:"permissions,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *GetUserPermissionsResponse) Reset() { - *x = GetUserPermissionsResponse{} - mi := &file_authz_proto_msgTypes[7] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *GetUserPermissionsResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*GetUserPermissionsResponse) ProtoMessage() {} - -func (x *GetUserPermissionsResponse) ProtoReflect() protoreflect.Message { - mi := &file_authz_proto_msgTypes[7] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use GetUserPermissionsResponse.ProtoReflect.Descriptor instead. -func (*GetUserPermissionsResponse) Descriptor() ([]byte, []int) { - return file_authz_proto_rawDescGZIP(), []int{7} -} - -func (x *GetUserPermissionsResponse) GetPermissions() []*Permission { - if x != nil { - return x.Permissions - } - return nil -} - -// GetUserRolesRequest contains a user ID. -type GetUserRolesRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - UserId string `protobuf:"bytes,1,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *GetUserRolesRequest) Reset() { - *x = GetUserRolesRequest{} - mi := &file_authz_proto_msgTypes[8] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *GetUserRolesRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*GetUserRolesRequest) ProtoMessage() {} - -func (x *GetUserRolesRequest) ProtoReflect() protoreflect.Message { - mi := &file_authz_proto_msgTypes[8] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use GetUserRolesRequest.ProtoReflect.Descriptor instead. -func (*GetUserRolesRequest) Descriptor() ([]byte, []int) { - return file_authz_proto_rawDescGZIP(), []int{8} -} - -func (x *GetUserRolesRequest) GetUserId() string { - if x != nil { - return x.UserId - } - return "" -} - -// GetUserRolesResponse contains all roles for the user. -type GetUserRolesResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Roles []*Role `protobuf:"bytes,1,rep,name=roles,proto3" json:"roles,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *GetUserRolesResponse) Reset() { - *x = GetUserRolesResponse{} - mi := &file_authz_proto_msgTypes[9] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *GetUserRolesResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*GetUserRolesResponse) ProtoMessage() {} - -func (x *GetUserRolesResponse) ProtoReflect() protoreflect.Message { - mi := &file_authz_proto_msgTypes[9] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use GetUserRolesResponse.ProtoReflect.Descriptor instead. -func (*GetUserRolesResponse) Descriptor() ([]byte, []int) { - return file_authz_proto_rawDescGZIP(), []int{9} -} - -func (x *GetUserRolesResponse) GetRoles() []*Role { - if x != nil { - return x.Roles - } - return nil -} - -var File_authz_proto protoreflect.FileDescriptor - -const file_authz_proto_rawDesc = "" + - "\n" + - "\vauthz.proto\x12\bauthz.v1\"f\n" + - "\n" + - "Permission\x12\x0e\n" + - "\x02id\x18\x01 \x01(\tR\x02id\x12\x12\n" + - "\x04code\x18\x02 \x01(\tR\x04code\x12\x12\n" + - "\x04name\x18\x03 \x01(\tR\x04name\x12 \n" + - "\vdescription\x18\x04 \x01(\tR\vdescription\"n\n" + - "\x04Role\x12\x0e\n" + - "\x02id\x18\x01 \x01(\tR\x02id\x12\x12\n" + - "\x04name\x18\x02 \x01(\tR\x04name\x12 \n" + - "\vdescription\x18\x03 \x01(\tR\vdescription\x12 \n" + - "\vpermissions\x18\x04 \x03(\tR\vpermissions\"K\n" + - "\x10AuthorizeRequest\x12\x17\n" + - "\auser_id\x18\x01 \x01(\tR\x06userId\x12\x1e\n" + - "\n" + - "permission\x18\x02 \x01(\tR\n" + - "permission\"M\n" + - "\x11AuthorizeResponse\x12\x1e\n" + - "\n" + - "authorized\x18\x01 \x01(\bR\n" + - "authorized\x12\x18\n" + - "\amessage\x18\x02 \x01(\tR\amessage\"O\n" + - "\x14HasPermissionRequest\x12\x17\n" + - "\auser_id\x18\x01 \x01(\tR\x06userId\x12\x1e\n" + - "\n" + - "permission\x18\x02 \x01(\tR\n" + - "permission\">\n" + - "\x15HasPermissionResponse\x12%\n" + - "\x0ehas_permission\x18\x01 \x01(\bR\rhasPermission\"4\n" + - "\x19GetUserPermissionsRequest\x12\x17\n" + - "\auser_id\x18\x01 \x01(\tR\x06userId\"T\n" + - "\x1aGetUserPermissionsResponse\x126\n" + - "\vpermissions\x18\x01 \x03(\v2\x14.authz.v1.PermissionR\vpermissions\".\n" + - "\x13GetUserRolesRequest\x12\x17\n" + - "\auser_id\x18\x01 \x01(\tR\x06userId\"<\n" + - "\x14GetUserRolesResponse\x12$\n" + - "\x05roles\x18\x01 \x03(\v2\x0e.authz.v1.RoleR\x05roles2\xd6\x02\n" + - "\fAuthzService\x12D\n" + - "\tAuthorize\x12\x1a.authz.v1.AuthorizeRequest\x1a\x1b.authz.v1.AuthorizeResponse\x12P\n" + - "\rHasPermission\x12\x1e.authz.v1.HasPermissionRequest\x1a\x1f.authz.v1.HasPermissionResponse\x12_\n" + - "\x12GetUserPermissions\x12#.authz.v1.GetUserPermissionsRequest\x1a$.authz.v1.GetUserPermissionsResponse\x12M\n" + - "\fGetUserRoles\x12\x1d.authz.v1.GetUserRolesRequest\x1a\x1e.authz.v1.GetUserRolesResponseBGZEgit.dcentral.systems/toolz/goplt/api/proto/generated/authz/v1;authzv1b\x06proto3" - -var ( - file_authz_proto_rawDescOnce sync.Once - file_authz_proto_rawDescData []byte -) - -func file_authz_proto_rawDescGZIP() []byte { - file_authz_proto_rawDescOnce.Do(func() { - file_authz_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_authz_proto_rawDesc), len(file_authz_proto_rawDesc))) - }) - return file_authz_proto_rawDescData -} - -var file_authz_proto_msgTypes = make([]protoimpl.MessageInfo, 10) -var file_authz_proto_goTypes = []any{ - (*Permission)(nil), // 0: authz.v1.Permission - (*Role)(nil), // 1: authz.v1.Role - (*AuthorizeRequest)(nil), // 2: authz.v1.AuthorizeRequest - (*AuthorizeResponse)(nil), // 3: authz.v1.AuthorizeResponse - (*HasPermissionRequest)(nil), // 4: authz.v1.HasPermissionRequest - (*HasPermissionResponse)(nil), // 5: authz.v1.HasPermissionResponse - (*GetUserPermissionsRequest)(nil), // 6: authz.v1.GetUserPermissionsRequest - (*GetUserPermissionsResponse)(nil), // 7: authz.v1.GetUserPermissionsResponse - (*GetUserRolesRequest)(nil), // 8: authz.v1.GetUserRolesRequest - (*GetUserRolesResponse)(nil), // 9: authz.v1.GetUserRolesResponse -} -var file_authz_proto_depIdxs = []int32{ - 0, // 0: authz.v1.GetUserPermissionsResponse.permissions:type_name -> authz.v1.Permission - 1, // 1: authz.v1.GetUserRolesResponse.roles:type_name -> authz.v1.Role - 2, // 2: authz.v1.AuthzService.Authorize:input_type -> authz.v1.AuthorizeRequest - 4, // 3: authz.v1.AuthzService.HasPermission:input_type -> authz.v1.HasPermissionRequest - 6, // 4: authz.v1.AuthzService.GetUserPermissions:input_type -> authz.v1.GetUserPermissionsRequest - 8, // 5: authz.v1.AuthzService.GetUserRoles:input_type -> authz.v1.GetUserRolesRequest - 3, // 6: authz.v1.AuthzService.Authorize:output_type -> authz.v1.AuthorizeResponse - 5, // 7: authz.v1.AuthzService.HasPermission:output_type -> authz.v1.HasPermissionResponse - 7, // 8: authz.v1.AuthzService.GetUserPermissions:output_type -> authz.v1.GetUserPermissionsResponse - 9, // 9: authz.v1.AuthzService.GetUserRoles:output_type -> authz.v1.GetUserRolesResponse - 6, // [6:10] is the sub-list for method output_type - 2, // [2:6] is the sub-list for method input_type - 2, // [2:2] is the sub-list for extension type_name - 2, // [2:2] is the sub-list for extension extendee - 0, // [0:2] is the sub-list for field type_name -} - -func init() { file_authz_proto_init() } -func file_authz_proto_init() { - if File_authz_proto != nil { - return - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: unsafe.Slice(unsafe.StringData(file_authz_proto_rawDesc), len(file_authz_proto_rawDesc)), - NumEnums: 0, - NumMessages: 10, - NumExtensions: 0, - NumServices: 1, - }, - GoTypes: file_authz_proto_goTypes, - DependencyIndexes: file_authz_proto_depIdxs, - MessageInfos: file_authz_proto_msgTypes, - }.Build() - File_authz_proto = out.File - file_authz_proto_goTypes = nil - file_authz_proto_depIdxs = nil -} diff --git a/api/proto/generated/authz/v1/authz_grpc.pb.go b/api/proto/generated/authz/v1/authz_grpc.pb.go deleted file mode 100644 index 5f62daf..0000000 --- a/api/proto/generated/authz/v1/authz_grpc.pb.go +++ /dev/null @@ -1,247 +0,0 @@ -// Code generated by protoc-gen-go-grpc. DO NOT EDIT. -// versions: -// - protoc-gen-go-grpc v1.5.1 -// - protoc v6.30.2 -// source: authz.proto - -package authzv1 - -import ( - context "context" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" -) - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -// Requires gRPC-Go v1.64.0 or later. -const _ = grpc.SupportPackageIsVersion9 - -const ( - AuthzService_Authorize_FullMethodName = "/authz.v1.AuthzService/Authorize" - AuthzService_HasPermission_FullMethodName = "/authz.v1.AuthzService/HasPermission" - AuthzService_GetUserPermissions_FullMethodName = "/authz.v1.AuthzService/GetUserPermissions" - AuthzService_GetUserRoles_FullMethodName = "/authz.v1.AuthzService/GetUserRoles" -) - -// AuthzServiceClient is the client API for AuthzService service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. -// -// AuthzService provides authorization operations. -type AuthzServiceClient interface { - // Authorize checks if a user has a specific permission and returns an error if not. - Authorize(ctx context.Context, in *AuthorizeRequest, opts ...grpc.CallOption) (*AuthorizeResponse, error) - // HasPermission checks if a user has a specific permission. - HasPermission(ctx context.Context, in *HasPermissionRequest, opts ...grpc.CallOption) (*HasPermissionResponse, error) - // GetUserPermissions returns all permissions for a user. - GetUserPermissions(ctx context.Context, in *GetUserPermissionsRequest, opts ...grpc.CallOption) (*GetUserPermissionsResponse, error) - // GetUserRoles returns all roles for a user. - GetUserRoles(ctx context.Context, in *GetUserRolesRequest, opts ...grpc.CallOption) (*GetUserRolesResponse, error) -} - -type authzServiceClient struct { - cc grpc.ClientConnInterface -} - -func NewAuthzServiceClient(cc grpc.ClientConnInterface) AuthzServiceClient { - return &authzServiceClient{cc} -} - -func (c *authzServiceClient) Authorize(ctx context.Context, in *AuthorizeRequest, opts ...grpc.CallOption) (*AuthorizeResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(AuthorizeResponse) - err := c.cc.Invoke(ctx, AuthzService_Authorize_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *authzServiceClient) HasPermission(ctx context.Context, in *HasPermissionRequest, opts ...grpc.CallOption) (*HasPermissionResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(HasPermissionResponse) - err := c.cc.Invoke(ctx, AuthzService_HasPermission_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *authzServiceClient) GetUserPermissions(ctx context.Context, in *GetUserPermissionsRequest, opts ...grpc.CallOption) (*GetUserPermissionsResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(GetUserPermissionsResponse) - err := c.cc.Invoke(ctx, AuthzService_GetUserPermissions_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *authzServiceClient) GetUserRoles(ctx context.Context, in *GetUserRolesRequest, opts ...grpc.CallOption) (*GetUserRolesResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(GetUserRolesResponse) - err := c.cc.Invoke(ctx, AuthzService_GetUserRoles_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -// AuthzServiceServer is the server API for AuthzService service. -// All implementations must embed UnimplementedAuthzServiceServer -// for forward compatibility. -// -// AuthzService provides authorization operations. -type AuthzServiceServer interface { - // Authorize checks if a user has a specific permission and returns an error if not. - Authorize(context.Context, *AuthorizeRequest) (*AuthorizeResponse, error) - // HasPermission checks if a user has a specific permission. - HasPermission(context.Context, *HasPermissionRequest) (*HasPermissionResponse, error) - // GetUserPermissions returns all permissions for a user. - GetUserPermissions(context.Context, *GetUserPermissionsRequest) (*GetUserPermissionsResponse, error) - // GetUserRoles returns all roles for a user. - GetUserRoles(context.Context, *GetUserRolesRequest) (*GetUserRolesResponse, error) - mustEmbedUnimplementedAuthzServiceServer() -} - -// UnimplementedAuthzServiceServer must be embedded to have -// forward compatible implementations. -// -// NOTE: this should be embedded by value instead of pointer to avoid a nil -// pointer dereference when methods are called. -type UnimplementedAuthzServiceServer struct{} - -func (UnimplementedAuthzServiceServer) Authorize(context.Context, *AuthorizeRequest) (*AuthorizeResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Authorize not implemented") -} -func (UnimplementedAuthzServiceServer) HasPermission(context.Context, *HasPermissionRequest) (*HasPermissionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method HasPermission not implemented") -} -func (UnimplementedAuthzServiceServer) GetUserPermissions(context.Context, *GetUserPermissionsRequest) (*GetUserPermissionsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetUserPermissions not implemented") -} -func (UnimplementedAuthzServiceServer) GetUserRoles(context.Context, *GetUserRolesRequest) (*GetUserRolesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetUserRoles not implemented") -} -func (UnimplementedAuthzServiceServer) mustEmbedUnimplementedAuthzServiceServer() {} -func (UnimplementedAuthzServiceServer) testEmbeddedByValue() {} - -// UnsafeAuthzServiceServer may be embedded to opt out of forward compatibility for this service. -// Use of this interface is not recommended, as added methods to AuthzServiceServer will -// result in compilation errors. -type UnsafeAuthzServiceServer interface { - mustEmbedUnimplementedAuthzServiceServer() -} - -func RegisterAuthzServiceServer(s grpc.ServiceRegistrar, srv AuthzServiceServer) { - // If the following call pancis, it indicates UnimplementedAuthzServiceServer was - // embedded by pointer and is nil. This will cause panics if an - // unimplemented method is ever invoked, so we test this at initialization - // time to prevent it from happening at runtime later due to I/O. - if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { - t.testEmbeddedByValue() - } - s.RegisterService(&AuthzService_ServiceDesc, srv) -} - -func _AuthzService_Authorize_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(AuthorizeRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthzServiceServer).Authorize(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthzService_Authorize_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthzServiceServer).Authorize(ctx, req.(*AuthorizeRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _AuthzService_HasPermission_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(HasPermissionRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthzServiceServer).HasPermission(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthzService_HasPermission_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthzServiceServer).HasPermission(ctx, req.(*HasPermissionRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _AuthzService_GetUserPermissions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(GetUserPermissionsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthzServiceServer).GetUserPermissions(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthzService_GetUserPermissions_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthzServiceServer).GetUserPermissions(ctx, req.(*GetUserPermissionsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _AuthzService_GetUserRoles_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(GetUserRolesRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthzServiceServer).GetUserRoles(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthzService_GetUserRoles_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthzServiceServer).GetUserRoles(ctx, req.(*GetUserRolesRequest)) - } - return interceptor(ctx, in, info, handler) -} - -// AuthzService_ServiceDesc is the grpc.ServiceDesc for AuthzService service. -// It's only intended for direct use with grpc.RegisterService, -// and not to be introspected or modified (even as a copy) -var AuthzService_ServiceDesc = grpc.ServiceDesc{ - ServiceName: "authz.v1.AuthzService", - HandlerType: (*AuthzServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Authorize", - Handler: _AuthzService_Authorize_Handler, - }, - { - MethodName: "HasPermission", - Handler: _AuthzService_HasPermission_Handler, - }, - { - MethodName: "GetUserPermissions", - Handler: _AuthzService_GetUserPermissions_Handler, - }, - { - MethodName: "GetUserRoles", - Handler: _AuthzService_GetUserRoles_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "authz.proto", -} diff --git a/api/proto/generated/authz_grpc.pb.go b/api/proto/generated/authz_grpc.pb.go deleted file mode 100644 index 5f62daf..0000000 --- a/api/proto/generated/authz_grpc.pb.go +++ /dev/null @@ -1,247 +0,0 @@ -// Code generated by protoc-gen-go-grpc. DO NOT EDIT. -// versions: -// - protoc-gen-go-grpc v1.5.1 -// - protoc v6.30.2 -// source: authz.proto - -package authzv1 - -import ( - context "context" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" -) - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -// Requires gRPC-Go v1.64.0 or later. -const _ = grpc.SupportPackageIsVersion9 - -const ( - AuthzService_Authorize_FullMethodName = "/authz.v1.AuthzService/Authorize" - AuthzService_HasPermission_FullMethodName = "/authz.v1.AuthzService/HasPermission" - AuthzService_GetUserPermissions_FullMethodName = "/authz.v1.AuthzService/GetUserPermissions" - AuthzService_GetUserRoles_FullMethodName = "/authz.v1.AuthzService/GetUserRoles" -) - -// AuthzServiceClient is the client API for AuthzService service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. -// -// AuthzService provides authorization operations. -type AuthzServiceClient interface { - // Authorize checks if a user has a specific permission and returns an error if not. - Authorize(ctx context.Context, in *AuthorizeRequest, opts ...grpc.CallOption) (*AuthorizeResponse, error) - // HasPermission checks if a user has a specific permission. - HasPermission(ctx context.Context, in *HasPermissionRequest, opts ...grpc.CallOption) (*HasPermissionResponse, error) - // GetUserPermissions returns all permissions for a user. - GetUserPermissions(ctx context.Context, in *GetUserPermissionsRequest, opts ...grpc.CallOption) (*GetUserPermissionsResponse, error) - // GetUserRoles returns all roles for a user. - GetUserRoles(ctx context.Context, in *GetUserRolesRequest, opts ...grpc.CallOption) (*GetUserRolesResponse, error) -} - -type authzServiceClient struct { - cc grpc.ClientConnInterface -} - -func NewAuthzServiceClient(cc grpc.ClientConnInterface) AuthzServiceClient { - return &authzServiceClient{cc} -} - -func (c *authzServiceClient) Authorize(ctx context.Context, in *AuthorizeRequest, opts ...grpc.CallOption) (*AuthorizeResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(AuthorizeResponse) - err := c.cc.Invoke(ctx, AuthzService_Authorize_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *authzServiceClient) HasPermission(ctx context.Context, in *HasPermissionRequest, opts ...grpc.CallOption) (*HasPermissionResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(HasPermissionResponse) - err := c.cc.Invoke(ctx, AuthzService_HasPermission_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *authzServiceClient) GetUserPermissions(ctx context.Context, in *GetUserPermissionsRequest, opts ...grpc.CallOption) (*GetUserPermissionsResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(GetUserPermissionsResponse) - err := c.cc.Invoke(ctx, AuthzService_GetUserPermissions_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *authzServiceClient) GetUserRoles(ctx context.Context, in *GetUserRolesRequest, opts ...grpc.CallOption) (*GetUserRolesResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(GetUserRolesResponse) - err := c.cc.Invoke(ctx, AuthzService_GetUserRoles_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -// AuthzServiceServer is the server API for AuthzService service. -// All implementations must embed UnimplementedAuthzServiceServer -// for forward compatibility. -// -// AuthzService provides authorization operations. -type AuthzServiceServer interface { - // Authorize checks if a user has a specific permission and returns an error if not. - Authorize(context.Context, *AuthorizeRequest) (*AuthorizeResponse, error) - // HasPermission checks if a user has a specific permission. - HasPermission(context.Context, *HasPermissionRequest) (*HasPermissionResponse, error) - // GetUserPermissions returns all permissions for a user. - GetUserPermissions(context.Context, *GetUserPermissionsRequest) (*GetUserPermissionsResponse, error) - // GetUserRoles returns all roles for a user. - GetUserRoles(context.Context, *GetUserRolesRequest) (*GetUserRolesResponse, error) - mustEmbedUnimplementedAuthzServiceServer() -} - -// UnimplementedAuthzServiceServer must be embedded to have -// forward compatible implementations. -// -// NOTE: this should be embedded by value instead of pointer to avoid a nil -// pointer dereference when methods are called. -type UnimplementedAuthzServiceServer struct{} - -func (UnimplementedAuthzServiceServer) Authorize(context.Context, *AuthorizeRequest) (*AuthorizeResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method Authorize not implemented") -} -func (UnimplementedAuthzServiceServer) HasPermission(context.Context, *HasPermissionRequest) (*HasPermissionResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method HasPermission not implemented") -} -func (UnimplementedAuthzServiceServer) GetUserPermissions(context.Context, *GetUserPermissionsRequest) (*GetUserPermissionsResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetUserPermissions not implemented") -} -func (UnimplementedAuthzServiceServer) GetUserRoles(context.Context, *GetUserRolesRequest) (*GetUserRolesResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetUserRoles not implemented") -} -func (UnimplementedAuthzServiceServer) mustEmbedUnimplementedAuthzServiceServer() {} -func (UnimplementedAuthzServiceServer) testEmbeddedByValue() {} - -// UnsafeAuthzServiceServer may be embedded to opt out of forward compatibility for this service. -// Use of this interface is not recommended, as added methods to AuthzServiceServer will -// result in compilation errors. -type UnsafeAuthzServiceServer interface { - mustEmbedUnimplementedAuthzServiceServer() -} - -func RegisterAuthzServiceServer(s grpc.ServiceRegistrar, srv AuthzServiceServer) { - // If the following call pancis, it indicates UnimplementedAuthzServiceServer was - // embedded by pointer and is nil. This will cause panics if an - // unimplemented method is ever invoked, so we test this at initialization - // time to prevent it from happening at runtime later due to I/O. - if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { - t.testEmbeddedByValue() - } - s.RegisterService(&AuthzService_ServiceDesc, srv) -} - -func _AuthzService_Authorize_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(AuthorizeRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthzServiceServer).Authorize(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthzService_Authorize_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthzServiceServer).Authorize(ctx, req.(*AuthorizeRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _AuthzService_HasPermission_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(HasPermissionRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthzServiceServer).HasPermission(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthzService_HasPermission_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthzServiceServer).HasPermission(ctx, req.(*HasPermissionRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _AuthzService_GetUserPermissions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(GetUserPermissionsRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthzServiceServer).GetUserPermissions(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthzService_GetUserPermissions_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthzServiceServer).GetUserPermissions(ctx, req.(*GetUserPermissionsRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _AuthzService_GetUserRoles_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(GetUserRolesRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(AuthzServiceServer).GetUserRoles(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: AuthzService_GetUserRoles_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(AuthzServiceServer).GetUserRoles(ctx, req.(*GetUserRolesRequest)) - } - return interceptor(ctx, in, info, handler) -} - -// AuthzService_ServiceDesc is the grpc.ServiceDesc for AuthzService service. -// It's only intended for direct use with grpc.RegisterService, -// and not to be introspected or modified (even as a copy) -var AuthzService_ServiceDesc = grpc.ServiceDesc{ - ServiceName: "authz.v1.AuthzService", - HandlerType: (*AuthzServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "Authorize", - Handler: _AuthzService_Authorize_Handler, - }, - { - MethodName: "HasPermission", - Handler: _AuthzService_HasPermission_Handler, - }, - { - MethodName: "GetUserPermissions", - Handler: _AuthzService_GetUserPermissions_Handler, - }, - { - MethodName: "GetUserRoles", - Handler: _AuthzService_GetUserRoles_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "authz.proto", -} diff --git a/api/proto/generated/identity/v1/identity.pb.go b/api/proto/generated/identity/v1/identity.pb.go deleted file mode 100644 index 4ca88f2..0000000 --- a/api/proto/generated/identity/v1/identity.pb.go +++ /dev/null @@ -1,1187 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// versions: -// protoc-gen-go v1.36.10 -// protoc v6.30.2 -// source: identity.proto - -package identityv1 - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - reflect "reflect" - sync "sync" - unsafe "unsafe" -) - -const ( - // Verify that this generated code is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) - // Verify that runtime/protoimpl is sufficiently up-to-date. - _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) -) - -// User represents a user in the system. -type User struct { - state protoimpl.MessageState `protogen:"open.v1"` - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - Email string `protobuf:"bytes,2,opt,name=email,proto3" json:"email,omitempty"` - Username string `protobuf:"bytes,3,opt,name=username,proto3" json:"username,omitempty"` - FirstName string `protobuf:"bytes,4,opt,name=first_name,json=firstName,proto3" json:"first_name,omitempty"` - LastName string `protobuf:"bytes,5,opt,name=last_name,json=lastName,proto3" json:"last_name,omitempty"` - EmailVerified bool `protobuf:"varint,6,opt,name=email_verified,json=emailVerified,proto3" json:"email_verified,omitempty"` - CreatedAt int64 `protobuf:"varint,7,opt,name=created_at,json=createdAt,proto3" json:"created_at,omitempty"` - UpdatedAt int64 `protobuf:"varint,8,opt,name=updated_at,json=updatedAt,proto3" json:"updated_at,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *User) Reset() { - *x = User{} - mi := &file_identity_proto_msgTypes[0] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *User) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*User) ProtoMessage() {} - -func (x *User) ProtoReflect() protoreflect.Message { - mi := &file_identity_proto_msgTypes[0] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use User.ProtoReflect.Descriptor instead. -func (*User) Descriptor() ([]byte, []int) { - return file_identity_proto_rawDescGZIP(), []int{0} -} - -func (x *User) GetId() string { - if x != nil { - return x.Id - } - return "" -} - -func (x *User) GetEmail() string { - if x != nil { - return x.Email - } - return "" -} - -func (x *User) GetUsername() string { - if x != nil { - return x.Username - } - return "" -} - -func (x *User) GetFirstName() string { - if x != nil { - return x.FirstName - } - return "" -} - -func (x *User) GetLastName() string { - if x != nil { - return x.LastName - } - return "" -} - -func (x *User) GetEmailVerified() bool { - if x != nil { - return x.EmailVerified - } - return false -} - -func (x *User) GetCreatedAt() int64 { - if x != nil { - return x.CreatedAt - } - return 0 -} - -func (x *User) GetUpdatedAt() int64 { - if x != nil { - return x.UpdatedAt - } - return 0 -} - -// GetUserRequest contains a user ID. -type GetUserRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *GetUserRequest) Reset() { - *x = GetUserRequest{} - mi := &file_identity_proto_msgTypes[1] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *GetUserRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*GetUserRequest) ProtoMessage() {} - -func (x *GetUserRequest) ProtoReflect() protoreflect.Message { - mi := &file_identity_proto_msgTypes[1] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use GetUserRequest.ProtoReflect.Descriptor instead. -func (*GetUserRequest) Descriptor() ([]byte, []int) { - return file_identity_proto_rawDescGZIP(), []int{1} -} - -func (x *GetUserRequest) GetId() string { - if x != nil { - return x.Id - } - return "" -} - -// GetUserResponse contains a user. -type GetUserResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - User *User `protobuf:"bytes,1,opt,name=user,proto3" json:"user,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *GetUserResponse) Reset() { - *x = GetUserResponse{} - mi := &file_identity_proto_msgTypes[2] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *GetUserResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*GetUserResponse) ProtoMessage() {} - -func (x *GetUserResponse) ProtoReflect() protoreflect.Message { - mi := &file_identity_proto_msgTypes[2] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use GetUserResponse.ProtoReflect.Descriptor instead. -func (*GetUserResponse) Descriptor() ([]byte, []int) { - return file_identity_proto_rawDescGZIP(), []int{2} -} - -func (x *GetUserResponse) GetUser() *User { - if x != nil { - return x.User - } - return nil -} - -// GetUserByEmailRequest contains an email address. -type GetUserByEmailRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Email string `protobuf:"bytes,1,opt,name=email,proto3" json:"email,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *GetUserByEmailRequest) Reset() { - *x = GetUserByEmailRequest{} - mi := &file_identity_proto_msgTypes[3] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *GetUserByEmailRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*GetUserByEmailRequest) ProtoMessage() {} - -func (x *GetUserByEmailRequest) ProtoReflect() protoreflect.Message { - mi := &file_identity_proto_msgTypes[3] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use GetUserByEmailRequest.ProtoReflect.Descriptor instead. -func (*GetUserByEmailRequest) Descriptor() ([]byte, []int) { - return file_identity_proto_rawDescGZIP(), []int{3} -} - -func (x *GetUserByEmailRequest) GetEmail() string { - if x != nil { - return x.Email - } - return "" -} - -// GetUserByEmailResponse contains a user. -type GetUserByEmailResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - User *User `protobuf:"bytes,1,opt,name=user,proto3" json:"user,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *GetUserByEmailResponse) Reset() { - *x = GetUserByEmailResponse{} - mi := &file_identity_proto_msgTypes[4] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *GetUserByEmailResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*GetUserByEmailResponse) ProtoMessage() {} - -func (x *GetUserByEmailResponse) ProtoReflect() protoreflect.Message { - mi := &file_identity_proto_msgTypes[4] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use GetUserByEmailResponse.ProtoReflect.Descriptor instead. -func (*GetUserByEmailResponse) Descriptor() ([]byte, []int) { - return file_identity_proto_rawDescGZIP(), []int{4} -} - -func (x *GetUserByEmailResponse) GetUser() *User { - if x != nil { - return x.User - } - return nil -} - -// CreateUserRequest contains user data for creation. -type CreateUserRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Email string `protobuf:"bytes,1,opt,name=email,proto3" json:"email,omitempty"` - Username string `protobuf:"bytes,2,opt,name=username,proto3" json:"username,omitempty"` - Password string `protobuf:"bytes,3,opt,name=password,proto3" json:"password,omitempty"` - FirstName string `protobuf:"bytes,4,opt,name=first_name,json=firstName,proto3" json:"first_name,omitempty"` - LastName string `protobuf:"bytes,5,opt,name=last_name,json=lastName,proto3" json:"last_name,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *CreateUserRequest) Reset() { - *x = CreateUserRequest{} - mi := &file_identity_proto_msgTypes[5] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *CreateUserRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*CreateUserRequest) ProtoMessage() {} - -func (x *CreateUserRequest) ProtoReflect() protoreflect.Message { - mi := &file_identity_proto_msgTypes[5] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use CreateUserRequest.ProtoReflect.Descriptor instead. -func (*CreateUserRequest) Descriptor() ([]byte, []int) { - return file_identity_proto_rawDescGZIP(), []int{5} -} - -func (x *CreateUserRequest) GetEmail() string { - if x != nil { - return x.Email - } - return "" -} - -func (x *CreateUserRequest) GetUsername() string { - if x != nil { - return x.Username - } - return "" -} - -func (x *CreateUserRequest) GetPassword() string { - if x != nil { - return x.Password - } - return "" -} - -func (x *CreateUserRequest) GetFirstName() string { - if x != nil { - return x.FirstName - } - return "" -} - -func (x *CreateUserRequest) GetLastName() string { - if x != nil { - return x.LastName - } - return "" -} - -// CreateUserResponse contains the created user. -type CreateUserResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - User *User `protobuf:"bytes,1,opt,name=user,proto3" json:"user,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *CreateUserResponse) Reset() { - *x = CreateUserResponse{} - mi := &file_identity_proto_msgTypes[6] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *CreateUserResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*CreateUserResponse) ProtoMessage() {} - -func (x *CreateUserResponse) ProtoReflect() protoreflect.Message { - mi := &file_identity_proto_msgTypes[6] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use CreateUserResponse.ProtoReflect.Descriptor instead. -func (*CreateUserResponse) Descriptor() ([]byte, []int) { - return file_identity_proto_rawDescGZIP(), []int{6} -} - -func (x *CreateUserResponse) GetUser() *User { - if x != nil { - return x.User - } - return nil -} - -// UpdateUserRequest contains user data for update. -type UpdateUserRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - Email *string `protobuf:"bytes,2,opt,name=email,proto3,oneof" json:"email,omitempty"` - Username *string `protobuf:"bytes,3,opt,name=username,proto3,oneof" json:"username,omitempty"` - FirstName *string `protobuf:"bytes,4,opt,name=first_name,json=firstName,proto3,oneof" json:"first_name,omitempty"` - LastName *string `protobuf:"bytes,5,opt,name=last_name,json=lastName,proto3,oneof" json:"last_name,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *UpdateUserRequest) Reset() { - *x = UpdateUserRequest{} - mi := &file_identity_proto_msgTypes[7] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *UpdateUserRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*UpdateUserRequest) ProtoMessage() {} - -func (x *UpdateUserRequest) ProtoReflect() protoreflect.Message { - mi := &file_identity_proto_msgTypes[7] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use UpdateUserRequest.ProtoReflect.Descriptor instead. -func (*UpdateUserRequest) Descriptor() ([]byte, []int) { - return file_identity_proto_rawDescGZIP(), []int{7} -} - -func (x *UpdateUserRequest) GetId() string { - if x != nil { - return x.Id - } - return "" -} - -func (x *UpdateUserRequest) GetEmail() string { - if x != nil && x.Email != nil { - return *x.Email - } - return "" -} - -func (x *UpdateUserRequest) GetUsername() string { - if x != nil && x.Username != nil { - return *x.Username - } - return "" -} - -func (x *UpdateUserRequest) GetFirstName() string { - if x != nil && x.FirstName != nil { - return *x.FirstName - } - return "" -} - -func (x *UpdateUserRequest) GetLastName() string { - if x != nil && x.LastName != nil { - return *x.LastName - } - return "" -} - -// UpdateUserResponse contains the updated user. -type UpdateUserResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - User *User `protobuf:"bytes,1,opt,name=user,proto3" json:"user,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *UpdateUserResponse) Reset() { - *x = UpdateUserResponse{} - mi := &file_identity_proto_msgTypes[8] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *UpdateUserResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*UpdateUserResponse) ProtoMessage() {} - -func (x *UpdateUserResponse) ProtoReflect() protoreflect.Message { - mi := &file_identity_proto_msgTypes[8] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use UpdateUserResponse.ProtoReflect.Descriptor instead. -func (*UpdateUserResponse) Descriptor() ([]byte, []int) { - return file_identity_proto_rawDescGZIP(), []int{8} -} - -func (x *UpdateUserResponse) GetUser() *User { - if x != nil { - return x.User - } - return nil -} - -// DeleteUserRequest contains a user ID. -type DeleteUserRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *DeleteUserRequest) Reset() { - *x = DeleteUserRequest{} - mi := &file_identity_proto_msgTypes[9] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *DeleteUserRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*DeleteUserRequest) ProtoMessage() {} - -func (x *DeleteUserRequest) ProtoReflect() protoreflect.Message { - mi := &file_identity_proto_msgTypes[9] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use DeleteUserRequest.ProtoReflect.Descriptor instead. -func (*DeleteUserRequest) Descriptor() ([]byte, []int) { - return file_identity_proto_rawDescGZIP(), []int{9} -} - -func (x *DeleteUserRequest) GetId() string { - if x != nil { - return x.Id - } - return "" -} - -// DeleteUserResponse indicates success. -type DeleteUserResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *DeleteUserResponse) Reset() { - *x = DeleteUserResponse{} - mi := &file_identity_proto_msgTypes[10] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *DeleteUserResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*DeleteUserResponse) ProtoMessage() {} - -func (x *DeleteUserResponse) ProtoReflect() protoreflect.Message { - mi := &file_identity_proto_msgTypes[10] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use DeleteUserResponse.ProtoReflect.Descriptor instead. -func (*DeleteUserResponse) Descriptor() ([]byte, []int) { - return file_identity_proto_rawDescGZIP(), []int{10} -} - -func (x *DeleteUserResponse) GetSuccess() bool { - if x != nil { - return x.Success - } - return false -} - -// VerifyEmailRequest contains a verification token. -type VerifyEmailRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *VerifyEmailRequest) Reset() { - *x = VerifyEmailRequest{} - mi := &file_identity_proto_msgTypes[11] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *VerifyEmailRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*VerifyEmailRequest) ProtoMessage() {} - -func (x *VerifyEmailRequest) ProtoReflect() protoreflect.Message { - mi := &file_identity_proto_msgTypes[11] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use VerifyEmailRequest.ProtoReflect.Descriptor instead. -func (*VerifyEmailRequest) Descriptor() ([]byte, []int) { - return file_identity_proto_rawDescGZIP(), []int{11} -} - -func (x *VerifyEmailRequest) GetToken() string { - if x != nil { - return x.Token - } - return "" -} - -// VerifyEmailResponse indicates success. -type VerifyEmailResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *VerifyEmailResponse) Reset() { - *x = VerifyEmailResponse{} - mi := &file_identity_proto_msgTypes[12] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *VerifyEmailResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*VerifyEmailResponse) ProtoMessage() {} - -func (x *VerifyEmailResponse) ProtoReflect() protoreflect.Message { - mi := &file_identity_proto_msgTypes[12] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use VerifyEmailResponse.ProtoReflect.Descriptor instead. -func (*VerifyEmailResponse) Descriptor() ([]byte, []int) { - return file_identity_proto_rawDescGZIP(), []int{12} -} - -func (x *VerifyEmailResponse) GetSuccess() bool { - if x != nil { - return x.Success - } - return false -} - -// RequestPasswordResetRequest contains an email address. -type RequestPasswordResetRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Email string `protobuf:"bytes,1,opt,name=email,proto3" json:"email,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *RequestPasswordResetRequest) Reset() { - *x = RequestPasswordResetRequest{} - mi := &file_identity_proto_msgTypes[13] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *RequestPasswordResetRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*RequestPasswordResetRequest) ProtoMessage() {} - -func (x *RequestPasswordResetRequest) ProtoReflect() protoreflect.Message { - mi := &file_identity_proto_msgTypes[13] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use RequestPasswordResetRequest.ProtoReflect.Descriptor instead. -func (*RequestPasswordResetRequest) Descriptor() ([]byte, []int) { - return file_identity_proto_rawDescGZIP(), []int{13} -} - -func (x *RequestPasswordResetRequest) GetEmail() string { - if x != nil { - return x.Email - } - return "" -} - -// RequestPasswordResetResponse indicates success. -type RequestPasswordResetResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *RequestPasswordResetResponse) Reset() { - *x = RequestPasswordResetResponse{} - mi := &file_identity_proto_msgTypes[14] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *RequestPasswordResetResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*RequestPasswordResetResponse) ProtoMessage() {} - -func (x *RequestPasswordResetResponse) ProtoReflect() protoreflect.Message { - mi := &file_identity_proto_msgTypes[14] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use RequestPasswordResetResponse.ProtoReflect.Descriptor instead. -func (*RequestPasswordResetResponse) Descriptor() ([]byte, []int) { - return file_identity_proto_rawDescGZIP(), []int{14} -} - -func (x *RequestPasswordResetResponse) GetSuccess() bool { - if x != nil { - return x.Success - } - return false -} - -// ResetPasswordRequest contains a reset token and new password. -type ResetPasswordRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` - NewPassword string `protobuf:"bytes,2,opt,name=new_password,json=newPassword,proto3" json:"new_password,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *ResetPasswordRequest) Reset() { - *x = ResetPasswordRequest{} - mi := &file_identity_proto_msgTypes[15] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *ResetPasswordRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ResetPasswordRequest) ProtoMessage() {} - -func (x *ResetPasswordRequest) ProtoReflect() protoreflect.Message { - mi := &file_identity_proto_msgTypes[15] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use ResetPasswordRequest.ProtoReflect.Descriptor instead. -func (*ResetPasswordRequest) Descriptor() ([]byte, []int) { - return file_identity_proto_rawDescGZIP(), []int{15} -} - -func (x *ResetPasswordRequest) GetToken() string { - if x != nil { - return x.Token - } - return "" -} - -func (x *ResetPasswordRequest) GetNewPassword() string { - if x != nil { - return x.NewPassword - } - return "" -} - -// ResetPasswordResponse indicates success. -type ResetPasswordResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - Success bool `protobuf:"varint,1,opt,name=success,proto3" json:"success,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *ResetPasswordResponse) Reset() { - *x = ResetPasswordResponse{} - mi := &file_identity_proto_msgTypes[16] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *ResetPasswordResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*ResetPasswordResponse) ProtoMessage() {} - -func (x *ResetPasswordResponse) ProtoReflect() protoreflect.Message { - mi := &file_identity_proto_msgTypes[16] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use ResetPasswordResponse.ProtoReflect.Descriptor instead. -func (*ResetPasswordResponse) Descriptor() ([]byte, []int) { - return file_identity_proto_rawDescGZIP(), []int{16} -} - -func (x *ResetPasswordResponse) GetSuccess() bool { - if x != nil { - return x.Success - } - return false -} - -// VerifyPasswordRequest contains email and password. -type VerifyPasswordRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Email string `protobuf:"bytes,1,opt,name=email,proto3" json:"email,omitempty"` - Password string `protobuf:"bytes,2,opt,name=password,proto3" json:"password,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *VerifyPasswordRequest) Reset() { - *x = VerifyPasswordRequest{} - mi := &file_identity_proto_msgTypes[17] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *VerifyPasswordRequest) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*VerifyPasswordRequest) ProtoMessage() {} - -func (x *VerifyPasswordRequest) ProtoReflect() protoreflect.Message { - mi := &file_identity_proto_msgTypes[17] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use VerifyPasswordRequest.ProtoReflect.Descriptor instead. -func (*VerifyPasswordRequest) Descriptor() ([]byte, []int) { - return file_identity_proto_rawDescGZIP(), []int{17} -} - -func (x *VerifyPasswordRequest) GetEmail() string { - if x != nil { - return x.Email - } - return "" -} - -func (x *VerifyPasswordRequest) GetPassword() string { - if x != nil { - return x.Password - } - return "" -} - -// VerifyPasswordResponse contains the user if password is valid. -type VerifyPasswordResponse struct { - state protoimpl.MessageState `protogen:"open.v1"` - User *User `protobuf:"bytes,1,opt,name=user,proto3" json:"user,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache -} - -func (x *VerifyPasswordResponse) Reset() { - *x = VerifyPasswordResponse{} - mi := &file_identity_proto_msgTypes[18] - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - ms.StoreMessageInfo(mi) -} - -func (x *VerifyPasswordResponse) String() string { - return protoimpl.X.MessageStringOf(x) -} - -func (*VerifyPasswordResponse) ProtoMessage() {} - -func (x *VerifyPasswordResponse) ProtoReflect() protoreflect.Message { - mi := &file_identity_proto_msgTypes[18] - if x != nil { - ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) - if ms.LoadMessageInfo() == nil { - ms.StoreMessageInfo(mi) - } - return ms - } - return mi.MessageOf(x) -} - -// Deprecated: Use VerifyPasswordResponse.ProtoReflect.Descriptor instead. -func (*VerifyPasswordResponse) Descriptor() ([]byte, []int) { - return file_identity_proto_rawDescGZIP(), []int{18} -} - -func (x *VerifyPasswordResponse) GetUser() *User { - if x != nil { - return x.User - } - return nil -} - -var File_identity_proto protoreflect.FileDescriptor - -const file_identity_proto_rawDesc = "" + - "\n" + - "\x0eidentity.proto\x12\videntity.v1\"\xe9\x01\n" + - "\x04User\x12\x0e\n" + - "\x02id\x18\x01 \x01(\tR\x02id\x12\x14\n" + - "\x05email\x18\x02 \x01(\tR\x05email\x12\x1a\n" + - "\busername\x18\x03 \x01(\tR\busername\x12\x1d\n" + - "\n" + - "first_name\x18\x04 \x01(\tR\tfirstName\x12\x1b\n" + - "\tlast_name\x18\x05 \x01(\tR\blastName\x12%\n" + - "\x0eemail_verified\x18\x06 \x01(\bR\remailVerified\x12\x1d\n" + - "\n" + - "created_at\x18\a \x01(\x03R\tcreatedAt\x12\x1d\n" + - "\n" + - "updated_at\x18\b \x01(\x03R\tupdatedAt\" \n" + - "\x0eGetUserRequest\x12\x0e\n" + - "\x02id\x18\x01 \x01(\tR\x02id\"8\n" + - "\x0fGetUserResponse\x12%\n" + - "\x04user\x18\x01 \x01(\v2\x11.identity.v1.UserR\x04user\"-\n" + - "\x15GetUserByEmailRequest\x12\x14\n" + - "\x05email\x18\x01 \x01(\tR\x05email\"?\n" + - "\x16GetUserByEmailResponse\x12%\n" + - "\x04user\x18\x01 \x01(\v2\x11.identity.v1.UserR\x04user\"\x9d\x01\n" + - "\x11CreateUserRequest\x12\x14\n" + - "\x05email\x18\x01 \x01(\tR\x05email\x12\x1a\n" + - "\busername\x18\x02 \x01(\tR\busername\x12\x1a\n" + - "\bpassword\x18\x03 \x01(\tR\bpassword\x12\x1d\n" + - "\n" + - "first_name\x18\x04 \x01(\tR\tfirstName\x12\x1b\n" + - "\tlast_name\x18\x05 \x01(\tR\blastName\";\n" + - "\x12CreateUserResponse\x12%\n" + - "\x04user\x18\x01 \x01(\v2\x11.identity.v1.UserR\x04user\"\xd9\x01\n" + - "\x11UpdateUserRequest\x12\x0e\n" + - "\x02id\x18\x01 \x01(\tR\x02id\x12\x19\n" + - "\x05email\x18\x02 \x01(\tH\x00R\x05email\x88\x01\x01\x12\x1f\n" + - "\busername\x18\x03 \x01(\tH\x01R\busername\x88\x01\x01\x12\"\n" + - "\n" + - "first_name\x18\x04 \x01(\tH\x02R\tfirstName\x88\x01\x01\x12 \n" + - "\tlast_name\x18\x05 \x01(\tH\x03R\blastName\x88\x01\x01B\b\n" + - "\x06_emailB\v\n" + - "\t_usernameB\r\n" + - "\v_first_nameB\f\n" + - "\n" + - "_last_name\";\n" + - "\x12UpdateUserResponse\x12%\n" + - "\x04user\x18\x01 \x01(\v2\x11.identity.v1.UserR\x04user\"#\n" + - "\x11DeleteUserRequest\x12\x0e\n" + - "\x02id\x18\x01 \x01(\tR\x02id\".\n" + - "\x12DeleteUserResponse\x12\x18\n" + - "\asuccess\x18\x01 \x01(\bR\asuccess\"*\n" + - "\x12VerifyEmailRequest\x12\x14\n" + - "\x05token\x18\x01 \x01(\tR\x05token\"/\n" + - "\x13VerifyEmailResponse\x12\x18\n" + - "\asuccess\x18\x01 \x01(\bR\asuccess\"3\n" + - "\x1bRequestPasswordResetRequest\x12\x14\n" + - "\x05email\x18\x01 \x01(\tR\x05email\"8\n" + - "\x1cRequestPasswordResetResponse\x12\x18\n" + - "\asuccess\x18\x01 \x01(\bR\asuccess\"O\n" + - "\x14ResetPasswordRequest\x12\x14\n" + - "\x05token\x18\x01 \x01(\tR\x05token\x12!\n" + - "\fnew_password\x18\x02 \x01(\tR\vnewPassword\"1\n" + - "\x15ResetPasswordResponse\x12\x18\n" + - "\asuccess\x18\x01 \x01(\bR\asuccess\"I\n" + - "\x15VerifyPasswordRequest\x12\x14\n" + - "\x05email\x18\x01 \x01(\tR\x05email\x12\x1a\n" + - "\bpassword\x18\x02 \x01(\tR\bpassword\"?\n" + - "\x16VerifyPasswordResponse\x12%\n" + - "\x04user\x18\x01 \x01(\v2\x11.identity.v1.UserR\x04user2\x91\x06\n" + - "\x0fIdentityService\x12D\n" + - "\aGetUser\x12\x1b.identity.v1.GetUserRequest\x1a\x1c.identity.v1.GetUserResponse\x12Y\n" + - "\x0eGetUserByEmail\x12\".identity.v1.GetUserByEmailRequest\x1a#.identity.v1.GetUserByEmailResponse\x12M\n" + - "\n" + - "CreateUser\x12\x1e.identity.v1.CreateUserRequest\x1a\x1f.identity.v1.CreateUserResponse\x12M\n" + - "\n" + - "UpdateUser\x12\x1e.identity.v1.UpdateUserRequest\x1a\x1f.identity.v1.UpdateUserResponse\x12M\n" + - "\n" + - "DeleteUser\x12\x1e.identity.v1.DeleteUserRequest\x1a\x1f.identity.v1.DeleteUserResponse\x12P\n" + - "\vVerifyEmail\x12\x1f.identity.v1.VerifyEmailRequest\x1a .identity.v1.VerifyEmailResponse\x12k\n" + - "\x14RequestPasswordReset\x12(.identity.v1.RequestPasswordResetRequest\x1a).identity.v1.RequestPasswordResetResponse\x12V\n" + - "\rResetPassword\x12!.identity.v1.ResetPasswordRequest\x1a\".identity.v1.ResetPasswordResponse\x12Y\n" + - "\x0eVerifyPassword\x12\".identity.v1.VerifyPasswordRequest\x1a#.identity.v1.VerifyPasswordResponseBMZKgit.dcentral.systems/toolz/goplt/api/proto/generated/identity/v1;identityv1b\x06proto3" - -var ( - file_identity_proto_rawDescOnce sync.Once - file_identity_proto_rawDescData []byte -) - -func file_identity_proto_rawDescGZIP() []byte { - file_identity_proto_rawDescOnce.Do(func() { - file_identity_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_identity_proto_rawDesc), len(file_identity_proto_rawDesc))) - }) - return file_identity_proto_rawDescData -} - -var file_identity_proto_msgTypes = make([]protoimpl.MessageInfo, 19) -var file_identity_proto_goTypes = []any{ - (*User)(nil), // 0: identity.v1.User - (*GetUserRequest)(nil), // 1: identity.v1.GetUserRequest - (*GetUserResponse)(nil), // 2: identity.v1.GetUserResponse - (*GetUserByEmailRequest)(nil), // 3: identity.v1.GetUserByEmailRequest - (*GetUserByEmailResponse)(nil), // 4: identity.v1.GetUserByEmailResponse - (*CreateUserRequest)(nil), // 5: identity.v1.CreateUserRequest - (*CreateUserResponse)(nil), // 6: identity.v1.CreateUserResponse - (*UpdateUserRequest)(nil), // 7: identity.v1.UpdateUserRequest - (*UpdateUserResponse)(nil), // 8: identity.v1.UpdateUserResponse - (*DeleteUserRequest)(nil), // 9: identity.v1.DeleteUserRequest - (*DeleteUserResponse)(nil), // 10: identity.v1.DeleteUserResponse - (*VerifyEmailRequest)(nil), // 11: identity.v1.VerifyEmailRequest - (*VerifyEmailResponse)(nil), // 12: identity.v1.VerifyEmailResponse - (*RequestPasswordResetRequest)(nil), // 13: identity.v1.RequestPasswordResetRequest - (*RequestPasswordResetResponse)(nil), // 14: identity.v1.RequestPasswordResetResponse - (*ResetPasswordRequest)(nil), // 15: identity.v1.ResetPasswordRequest - (*ResetPasswordResponse)(nil), // 16: identity.v1.ResetPasswordResponse - (*VerifyPasswordRequest)(nil), // 17: identity.v1.VerifyPasswordRequest - (*VerifyPasswordResponse)(nil), // 18: identity.v1.VerifyPasswordResponse -} -var file_identity_proto_depIdxs = []int32{ - 0, // 0: identity.v1.GetUserResponse.user:type_name -> identity.v1.User - 0, // 1: identity.v1.GetUserByEmailResponse.user:type_name -> identity.v1.User - 0, // 2: identity.v1.CreateUserResponse.user:type_name -> identity.v1.User - 0, // 3: identity.v1.UpdateUserResponse.user:type_name -> identity.v1.User - 0, // 4: identity.v1.VerifyPasswordResponse.user:type_name -> identity.v1.User - 1, // 5: identity.v1.IdentityService.GetUser:input_type -> identity.v1.GetUserRequest - 3, // 6: identity.v1.IdentityService.GetUserByEmail:input_type -> identity.v1.GetUserByEmailRequest - 5, // 7: identity.v1.IdentityService.CreateUser:input_type -> identity.v1.CreateUserRequest - 7, // 8: identity.v1.IdentityService.UpdateUser:input_type -> identity.v1.UpdateUserRequest - 9, // 9: identity.v1.IdentityService.DeleteUser:input_type -> identity.v1.DeleteUserRequest - 11, // 10: identity.v1.IdentityService.VerifyEmail:input_type -> identity.v1.VerifyEmailRequest - 13, // 11: identity.v1.IdentityService.RequestPasswordReset:input_type -> identity.v1.RequestPasswordResetRequest - 15, // 12: identity.v1.IdentityService.ResetPassword:input_type -> identity.v1.ResetPasswordRequest - 17, // 13: identity.v1.IdentityService.VerifyPassword:input_type -> identity.v1.VerifyPasswordRequest - 2, // 14: identity.v1.IdentityService.GetUser:output_type -> identity.v1.GetUserResponse - 4, // 15: identity.v1.IdentityService.GetUserByEmail:output_type -> identity.v1.GetUserByEmailResponse - 6, // 16: identity.v1.IdentityService.CreateUser:output_type -> identity.v1.CreateUserResponse - 8, // 17: identity.v1.IdentityService.UpdateUser:output_type -> identity.v1.UpdateUserResponse - 10, // 18: identity.v1.IdentityService.DeleteUser:output_type -> identity.v1.DeleteUserResponse - 12, // 19: identity.v1.IdentityService.VerifyEmail:output_type -> identity.v1.VerifyEmailResponse - 14, // 20: identity.v1.IdentityService.RequestPasswordReset:output_type -> identity.v1.RequestPasswordResetResponse - 16, // 21: identity.v1.IdentityService.ResetPassword:output_type -> identity.v1.ResetPasswordResponse - 18, // 22: identity.v1.IdentityService.VerifyPassword:output_type -> identity.v1.VerifyPasswordResponse - 14, // [14:23] is the sub-list for method output_type - 5, // [5:14] is the sub-list for method input_type - 5, // [5:5] is the sub-list for extension type_name - 5, // [5:5] is the sub-list for extension extendee - 0, // [0:5] is the sub-list for field type_name -} - -func init() { file_identity_proto_init() } -func file_identity_proto_init() { - if File_identity_proto != nil { - return - } - file_identity_proto_msgTypes[7].OneofWrappers = []any{} - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: unsafe.Slice(unsafe.StringData(file_identity_proto_rawDesc), len(file_identity_proto_rawDesc)), - NumEnums: 0, - NumMessages: 19, - NumExtensions: 0, - NumServices: 1, - }, - GoTypes: file_identity_proto_goTypes, - DependencyIndexes: file_identity_proto_depIdxs, - MessageInfos: file_identity_proto_msgTypes, - }.Build() - File_identity_proto = out.File - file_identity_proto_goTypes = nil - file_identity_proto_depIdxs = nil -} diff --git a/api/proto/generated/identity/v1/identity_grpc.pb.go b/api/proto/generated/identity/v1/identity_grpc.pb.go deleted file mode 100644 index ad3c8d7..0000000 --- a/api/proto/generated/identity/v1/identity_grpc.pb.go +++ /dev/null @@ -1,447 +0,0 @@ -// Code generated by protoc-gen-go-grpc. DO NOT EDIT. -// versions: -// - protoc-gen-go-grpc v1.5.1 -// - protoc v6.30.2 -// source: identity.proto - -package identityv1 - -import ( - context "context" - grpc "google.golang.org/grpc" - codes "google.golang.org/grpc/codes" - status "google.golang.org/grpc/status" -) - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the grpc package it is being compiled against. -// Requires gRPC-Go v1.64.0 or later. -const _ = grpc.SupportPackageIsVersion9 - -const ( - IdentityService_GetUser_FullMethodName = "/identity.v1.IdentityService/GetUser" - IdentityService_GetUserByEmail_FullMethodName = "/identity.v1.IdentityService/GetUserByEmail" - IdentityService_CreateUser_FullMethodName = "/identity.v1.IdentityService/CreateUser" - IdentityService_UpdateUser_FullMethodName = "/identity.v1.IdentityService/UpdateUser" - IdentityService_DeleteUser_FullMethodName = "/identity.v1.IdentityService/DeleteUser" - IdentityService_VerifyEmail_FullMethodName = "/identity.v1.IdentityService/VerifyEmail" - IdentityService_RequestPasswordReset_FullMethodName = "/identity.v1.IdentityService/RequestPasswordReset" - IdentityService_ResetPassword_FullMethodName = "/identity.v1.IdentityService/ResetPassword" - IdentityService_VerifyPassword_FullMethodName = "/identity.v1.IdentityService/VerifyPassword" -) - -// IdentityServiceClient is the client API for IdentityService service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. -// -// IdentityService provides user management operations. -type IdentityServiceClient interface { - // GetUser retrieves a user by ID. - GetUser(ctx context.Context, in *GetUserRequest, opts ...grpc.CallOption) (*GetUserResponse, error) - // GetUserByEmail retrieves a user by email address. - GetUserByEmail(ctx context.Context, in *GetUserByEmailRequest, opts ...grpc.CallOption) (*GetUserByEmailResponse, error) - // CreateUser creates a new user. - CreateUser(ctx context.Context, in *CreateUserRequest, opts ...grpc.CallOption) (*CreateUserResponse, error) - // UpdateUser updates an existing user. - UpdateUser(ctx context.Context, in *UpdateUserRequest, opts ...grpc.CallOption) (*UpdateUserResponse, error) - // DeleteUser deletes a user. - DeleteUser(ctx context.Context, in *DeleteUserRequest, opts ...grpc.CallOption) (*DeleteUserResponse, error) - // VerifyEmail verifies a user's email address using a verification token. - VerifyEmail(ctx context.Context, in *VerifyEmailRequest, opts ...grpc.CallOption) (*VerifyEmailResponse, error) - // RequestPasswordReset requests a password reset token. - RequestPasswordReset(ctx context.Context, in *RequestPasswordResetRequest, opts ...grpc.CallOption) (*RequestPasswordResetResponse, error) - // ResetPassword resets a user's password using a reset token. - ResetPassword(ctx context.Context, in *ResetPasswordRequest, opts ...grpc.CallOption) (*ResetPasswordResponse, error) - // VerifyPassword verifies a user's password. - VerifyPassword(ctx context.Context, in *VerifyPasswordRequest, opts ...grpc.CallOption) (*VerifyPasswordResponse, error) -} - -type identityServiceClient struct { - cc grpc.ClientConnInterface -} - -func NewIdentityServiceClient(cc grpc.ClientConnInterface) IdentityServiceClient { - return &identityServiceClient{cc} -} - -func (c *identityServiceClient) GetUser(ctx context.Context, in *GetUserRequest, opts ...grpc.CallOption) (*GetUserResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(GetUserResponse) - err := c.cc.Invoke(ctx, IdentityService_GetUser_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *identityServiceClient) GetUserByEmail(ctx context.Context, in *GetUserByEmailRequest, opts ...grpc.CallOption) (*GetUserByEmailResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(GetUserByEmailResponse) - err := c.cc.Invoke(ctx, IdentityService_GetUserByEmail_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *identityServiceClient) CreateUser(ctx context.Context, in *CreateUserRequest, opts ...grpc.CallOption) (*CreateUserResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(CreateUserResponse) - err := c.cc.Invoke(ctx, IdentityService_CreateUser_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *identityServiceClient) UpdateUser(ctx context.Context, in *UpdateUserRequest, opts ...grpc.CallOption) (*UpdateUserResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(UpdateUserResponse) - err := c.cc.Invoke(ctx, IdentityService_UpdateUser_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *identityServiceClient) DeleteUser(ctx context.Context, in *DeleteUserRequest, opts ...grpc.CallOption) (*DeleteUserResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(DeleteUserResponse) - err := c.cc.Invoke(ctx, IdentityService_DeleteUser_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *identityServiceClient) VerifyEmail(ctx context.Context, in *VerifyEmailRequest, opts ...grpc.CallOption) (*VerifyEmailResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(VerifyEmailResponse) - err := c.cc.Invoke(ctx, IdentityService_VerifyEmail_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *identityServiceClient) RequestPasswordReset(ctx context.Context, in *RequestPasswordResetRequest, opts ...grpc.CallOption) (*RequestPasswordResetResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(RequestPasswordResetResponse) - err := c.cc.Invoke(ctx, IdentityService_RequestPasswordReset_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *identityServiceClient) ResetPassword(ctx context.Context, in *ResetPasswordRequest, opts ...grpc.CallOption) (*ResetPasswordResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(ResetPasswordResponse) - err := c.cc.Invoke(ctx, IdentityService_ResetPassword_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -func (c *identityServiceClient) VerifyPassword(ctx context.Context, in *VerifyPasswordRequest, opts ...grpc.CallOption) (*VerifyPasswordResponse, error) { - cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) - out := new(VerifyPasswordResponse) - err := c.cc.Invoke(ctx, IdentityService_VerifyPassword_FullMethodName, in, out, cOpts...) - if err != nil { - return nil, err - } - return out, nil -} - -// IdentityServiceServer is the server API for IdentityService service. -// All implementations must embed UnimplementedIdentityServiceServer -// for forward compatibility. -// -// IdentityService provides user management operations. -type IdentityServiceServer interface { - // GetUser retrieves a user by ID. - GetUser(context.Context, *GetUserRequest) (*GetUserResponse, error) - // GetUserByEmail retrieves a user by email address. - GetUserByEmail(context.Context, *GetUserByEmailRequest) (*GetUserByEmailResponse, error) - // CreateUser creates a new user. - CreateUser(context.Context, *CreateUserRequest) (*CreateUserResponse, error) - // UpdateUser updates an existing user. - UpdateUser(context.Context, *UpdateUserRequest) (*UpdateUserResponse, error) - // DeleteUser deletes a user. - DeleteUser(context.Context, *DeleteUserRequest) (*DeleteUserResponse, error) - // VerifyEmail verifies a user's email address using a verification token. - VerifyEmail(context.Context, *VerifyEmailRequest) (*VerifyEmailResponse, error) - // RequestPasswordReset requests a password reset token. - RequestPasswordReset(context.Context, *RequestPasswordResetRequest) (*RequestPasswordResetResponse, error) - // ResetPassword resets a user's password using a reset token. - ResetPassword(context.Context, *ResetPasswordRequest) (*ResetPasswordResponse, error) - // VerifyPassword verifies a user's password. - VerifyPassword(context.Context, *VerifyPasswordRequest) (*VerifyPasswordResponse, error) - mustEmbedUnimplementedIdentityServiceServer() -} - -// UnimplementedIdentityServiceServer must be embedded to have -// forward compatible implementations. -// -// NOTE: this should be embedded by value instead of pointer to avoid a nil -// pointer dereference when methods are called. -type UnimplementedIdentityServiceServer struct{} - -func (UnimplementedIdentityServiceServer) GetUser(context.Context, *GetUserRequest) (*GetUserResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetUser not implemented") -} -func (UnimplementedIdentityServiceServer) GetUserByEmail(context.Context, *GetUserByEmailRequest) (*GetUserByEmailResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method GetUserByEmail not implemented") -} -func (UnimplementedIdentityServiceServer) CreateUser(context.Context, *CreateUserRequest) (*CreateUserResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method CreateUser not implemented") -} -func (UnimplementedIdentityServiceServer) UpdateUser(context.Context, *UpdateUserRequest) (*UpdateUserResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method UpdateUser not implemented") -} -func (UnimplementedIdentityServiceServer) DeleteUser(context.Context, *DeleteUserRequest) (*DeleteUserResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method DeleteUser not implemented") -} -func (UnimplementedIdentityServiceServer) VerifyEmail(context.Context, *VerifyEmailRequest) (*VerifyEmailResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method VerifyEmail not implemented") -} -func (UnimplementedIdentityServiceServer) RequestPasswordReset(context.Context, *RequestPasswordResetRequest) (*RequestPasswordResetResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method RequestPasswordReset not implemented") -} -func (UnimplementedIdentityServiceServer) ResetPassword(context.Context, *ResetPasswordRequest) (*ResetPasswordResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method ResetPassword not implemented") -} -func (UnimplementedIdentityServiceServer) VerifyPassword(context.Context, *VerifyPasswordRequest) (*VerifyPasswordResponse, error) { - return nil, status.Errorf(codes.Unimplemented, "method VerifyPassword not implemented") -} -func (UnimplementedIdentityServiceServer) mustEmbedUnimplementedIdentityServiceServer() {} -func (UnimplementedIdentityServiceServer) testEmbeddedByValue() {} - -// UnsafeIdentityServiceServer may be embedded to opt out of forward compatibility for this service. -// Use of this interface is not recommended, as added methods to IdentityServiceServer will -// result in compilation errors. -type UnsafeIdentityServiceServer interface { - mustEmbedUnimplementedIdentityServiceServer() -} - -func RegisterIdentityServiceServer(s grpc.ServiceRegistrar, srv IdentityServiceServer) { - // If the following call pancis, it indicates UnimplementedIdentityServiceServer was - // embedded by pointer and is nil. This will cause panics if an - // unimplemented method is ever invoked, so we test this at initialization - // time to prevent it from happening at runtime later due to I/O. - if t, ok := srv.(interface{ testEmbeddedByValue() }); ok { - t.testEmbeddedByValue() - } - s.RegisterService(&IdentityService_ServiceDesc, srv) -} - -func _IdentityService_GetUser_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(GetUserRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(IdentityServiceServer).GetUser(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: IdentityService_GetUser_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(IdentityServiceServer).GetUser(ctx, req.(*GetUserRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _IdentityService_GetUserByEmail_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(GetUserByEmailRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(IdentityServiceServer).GetUserByEmail(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: IdentityService_GetUserByEmail_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(IdentityServiceServer).GetUserByEmail(ctx, req.(*GetUserByEmailRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _IdentityService_CreateUser_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(CreateUserRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(IdentityServiceServer).CreateUser(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: IdentityService_CreateUser_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(IdentityServiceServer).CreateUser(ctx, req.(*CreateUserRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _IdentityService_UpdateUser_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(UpdateUserRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(IdentityServiceServer).UpdateUser(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: IdentityService_UpdateUser_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(IdentityServiceServer).UpdateUser(ctx, req.(*UpdateUserRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _IdentityService_DeleteUser_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(DeleteUserRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(IdentityServiceServer).DeleteUser(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: IdentityService_DeleteUser_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(IdentityServiceServer).DeleteUser(ctx, req.(*DeleteUserRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _IdentityService_VerifyEmail_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(VerifyEmailRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(IdentityServiceServer).VerifyEmail(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: IdentityService_VerifyEmail_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(IdentityServiceServer).VerifyEmail(ctx, req.(*VerifyEmailRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _IdentityService_RequestPasswordReset_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(RequestPasswordResetRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(IdentityServiceServer).RequestPasswordReset(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: IdentityService_RequestPasswordReset_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(IdentityServiceServer).RequestPasswordReset(ctx, req.(*RequestPasswordResetRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _IdentityService_ResetPassword_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(ResetPasswordRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(IdentityServiceServer).ResetPassword(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: IdentityService_ResetPassword_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(IdentityServiceServer).ResetPassword(ctx, req.(*ResetPasswordRequest)) - } - return interceptor(ctx, in, info, handler) -} - -func _IdentityService_VerifyPassword_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(VerifyPasswordRequest) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(IdentityServiceServer).VerifyPassword(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: IdentityService_VerifyPassword_FullMethodName, - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(IdentityServiceServer).VerifyPassword(ctx, req.(*VerifyPasswordRequest)) - } - return interceptor(ctx, in, info, handler) -} - -// IdentityService_ServiceDesc is the grpc.ServiceDesc for IdentityService service. -// It's only intended for direct use with grpc.RegisterService, -// and not to be introspected or modified (even as a copy) -var IdentityService_ServiceDesc = grpc.ServiceDesc{ - ServiceName: "identity.v1.IdentityService", - HandlerType: (*IdentityServiceServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "GetUser", - Handler: _IdentityService_GetUser_Handler, - }, - { - MethodName: "GetUserByEmail", - Handler: _IdentityService_GetUserByEmail_Handler, - }, - { - MethodName: "CreateUser", - Handler: _IdentityService_CreateUser_Handler, - }, - { - MethodName: "UpdateUser", - Handler: _IdentityService_UpdateUser_Handler, - }, - { - MethodName: "DeleteUser", - Handler: _IdentityService_DeleteUser_Handler, - }, - { - MethodName: "VerifyEmail", - Handler: _IdentityService_VerifyEmail_Handler, - }, - { - MethodName: "RequestPasswordReset", - Handler: _IdentityService_RequestPasswordReset_Handler, - }, - { - MethodName: "ResetPassword", - Handler: _IdentityService_ResetPassword_Handler, - }, - { - MethodName: "VerifyPassword", - Handler: _IdentityService_VerifyPassword_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "identity.proto", -} diff --git a/ent/auditlog.go b/ent/auditlog.go deleted file mode 100644 index 412961c..0000000 --- a/ent/auditlog.go +++ /dev/null @@ -1,91 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "fmt" - "strings" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "git.dcentral.systems/toolz/goplt/ent/auditlog" -) - -// AuditLog is the model entity for the AuditLog schema. -type AuditLog struct { - config - // ID of the ent. - ID int `json:"id,omitempty"` - selectValues sql.SelectValues -} - -// scanValues returns the types for scanning values from sql.Rows. -func (*AuditLog) scanValues(columns []string) ([]any, error) { - values := make([]any, len(columns)) - for i := range columns { - switch columns[i] { - case auditlog.FieldID: - values[i] = new(sql.NullInt64) - default: - values[i] = new(sql.UnknownType) - } - } - return values, nil -} - -// assignValues assigns the values that were returned from sql.Rows (after scanning) -// to the AuditLog fields. -func (_m *AuditLog) assignValues(columns []string, values []any) error { - if m, n := len(values), len(columns); m < n { - return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) - } - for i := range columns { - switch columns[i] { - case auditlog.FieldID: - value, ok := values[i].(*sql.NullInt64) - if !ok { - return fmt.Errorf("unexpected type %T for field id", value) - } - _m.ID = int(value.Int64) - default: - _m.selectValues.Set(columns[i], values[i]) - } - } - return nil -} - -// Value returns the ent.Value that was dynamically selected and assigned to the AuditLog. -// This includes values selected through modifiers, order, etc. -func (_m *AuditLog) Value(name string) (ent.Value, error) { - return _m.selectValues.Get(name) -} - -// Update returns a builder for updating this AuditLog. -// Note that you need to call AuditLog.Unwrap() before calling this method if this AuditLog -// was returned from a transaction, and the transaction was committed or rolled back. -func (_m *AuditLog) Update() *AuditLogUpdateOne { - return NewAuditLogClient(_m.config).UpdateOne(_m) -} - -// Unwrap unwraps the AuditLog entity that was returned from a transaction after it was closed, -// so that all future queries will be executed through the driver which created the transaction. -func (_m *AuditLog) Unwrap() *AuditLog { - _tx, ok := _m.config.driver.(*txDriver) - if !ok { - panic("ent: AuditLog is not a transactional entity") - } - _m.config.driver = _tx.drv - return _m -} - -// String implements the fmt.Stringer. -func (_m *AuditLog) String() string { - var builder strings.Builder - builder.WriteString("AuditLog(") - builder.WriteString(fmt.Sprintf("id=%v", _m.ID)) - builder.WriteByte(')') - return builder.String() -} - -// AuditLogs is a parsable slice of AuditLog. -type AuditLogs []*AuditLog diff --git a/ent/auditlog/auditlog.go b/ent/auditlog/auditlog.go deleted file mode 100644 index d5f6e52..0000000 --- a/ent/auditlog/auditlog.go +++ /dev/null @@ -1,39 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package auditlog - -import ( - "entgo.io/ent/dialect/sql" -) - -const ( - // Label holds the string label denoting the auditlog type in the database. - Label = "audit_log" - // FieldID holds the string denoting the id field in the database. - FieldID = "id" - // Table holds the table name of the auditlog in the database. - Table = "audit_logs" -) - -// Columns holds all SQL columns for auditlog fields. -var Columns = []string{ - FieldID, -} - -// ValidColumn reports if the column name is valid (part of the table columns). -func ValidColumn(column string) bool { - for i := range Columns { - if column == Columns[i] { - return true - } - } - return false -} - -// OrderOption defines the ordering options for the AuditLog queries. -type OrderOption func(*sql.Selector) - -// ByID orders the results by the id field. -func ByID(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldID, opts...).ToFunc() -} diff --git a/ent/auditlog/where.go b/ent/auditlog/where.go deleted file mode 100644 index 5485d34..0000000 --- a/ent/auditlog/where.go +++ /dev/null @@ -1,68 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package auditlog - -import ( - "entgo.io/ent/dialect/sql" - "git.dcentral.systems/toolz/goplt/ent/predicate" -) - -// ID filters vertices based on their ID field. -func ID(id int) predicate.AuditLog { - return predicate.AuditLog(sql.FieldEQ(FieldID, id)) -} - -// IDEQ applies the EQ predicate on the ID field. -func IDEQ(id int) predicate.AuditLog { - return predicate.AuditLog(sql.FieldEQ(FieldID, id)) -} - -// IDNEQ applies the NEQ predicate on the ID field. -func IDNEQ(id int) predicate.AuditLog { - return predicate.AuditLog(sql.FieldNEQ(FieldID, id)) -} - -// IDIn applies the In predicate on the ID field. -func IDIn(ids ...int) predicate.AuditLog { - return predicate.AuditLog(sql.FieldIn(FieldID, ids...)) -} - -// IDNotIn applies the NotIn predicate on the ID field. -func IDNotIn(ids ...int) predicate.AuditLog { - return predicate.AuditLog(sql.FieldNotIn(FieldID, ids...)) -} - -// IDGT applies the GT predicate on the ID field. -func IDGT(id int) predicate.AuditLog { - return predicate.AuditLog(sql.FieldGT(FieldID, id)) -} - -// IDGTE applies the GTE predicate on the ID field. -func IDGTE(id int) predicate.AuditLog { - return predicate.AuditLog(sql.FieldGTE(FieldID, id)) -} - -// IDLT applies the LT predicate on the ID field. -func IDLT(id int) predicate.AuditLog { - return predicate.AuditLog(sql.FieldLT(FieldID, id)) -} - -// IDLTE applies the LTE predicate on the ID field. -func IDLTE(id int) predicate.AuditLog { - return predicate.AuditLog(sql.FieldLTE(FieldID, id)) -} - -// And groups predicates with the AND operator between them. -func And(predicates ...predicate.AuditLog) predicate.AuditLog { - return predicate.AuditLog(sql.AndPredicates(predicates...)) -} - -// Or groups predicates with the OR operator between them. -func Or(predicates ...predicate.AuditLog) predicate.AuditLog { - return predicate.AuditLog(sql.OrPredicates(predicates...)) -} - -// Not applies the not operator on the given predicate. -func Not(p predicate.AuditLog) predicate.AuditLog { - return predicate.AuditLog(sql.NotPredicates(p)) -} diff --git a/ent/auditlog_create.go b/ent/auditlog_create.go deleted file mode 100644 index 7338594..0000000 --- a/ent/auditlog_create.go +++ /dev/null @@ -1,169 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "fmt" - - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/ent/auditlog" -) - -// AuditLogCreate is the builder for creating a AuditLog entity. -type AuditLogCreate struct { - config - mutation *AuditLogMutation - hooks []Hook -} - -// Mutation returns the AuditLogMutation object of the builder. -func (_c *AuditLogCreate) Mutation() *AuditLogMutation { - return _c.mutation -} - -// Save creates the AuditLog in the database. -func (_c *AuditLogCreate) Save(ctx context.Context) (*AuditLog, error) { - return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) -} - -// SaveX calls Save and panics if Save returns an error. -func (_c *AuditLogCreate) SaveX(ctx context.Context) *AuditLog { - v, err := _c.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (_c *AuditLogCreate) Exec(ctx context.Context) error { - _, err := _c.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_c *AuditLogCreate) ExecX(ctx context.Context) { - if err := _c.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (_c *AuditLogCreate) check() error { - return nil -} - -func (_c *AuditLogCreate) sqlSave(ctx context.Context) (*AuditLog, error) { - if err := _c.check(); err != nil { - return nil, err - } - _node, _spec := _c.createSpec() - if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - id := _spec.ID.Value.(int64) - _node.ID = int(id) - _c.mutation.id = &_node.ID - _c.mutation.done = true - return _node, nil -} - -func (_c *AuditLogCreate) createSpec() (*AuditLog, *sqlgraph.CreateSpec) { - var ( - _node = &AuditLog{config: _c.config} - _spec = sqlgraph.NewCreateSpec(auditlog.Table, sqlgraph.NewFieldSpec(auditlog.FieldID, field.TypeInt)) - ) - return _node, _spec -} - -// AuditLogCreateBulk is the builder for creating many AuditLog entities in bulk. -type AuditLogCreateBulk struct { - config - err error - builders []*AuditLogCreate -} - -// Save creates the AuditLog entities in the database. -func (_c *AuditLogCreateBulk) Save(ctx context.Context) ([]*AuditLog, error) { - if _c.err != nil { - return nil, _c.err - } - specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) - nodes := make([]*AuditLog, len(_c.builders)) - mutators := make([]Mutator, len(_c.builders)) - for i := range _c.builders { - func(i int, root context.Context) { - builder := _c.builders[i] - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*AuditLogMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err := builder.check(); err != nil { - return nil, err - } - builder.mutation = mutation - var err error - nodes[i], specs[i] = builder.createSpec() - if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) - } else { - spec := &sqlgraph.BatchCreateSpec{Nodes: specs} - // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - } - } - if err != nil { - return nil, err - } - mutation.id = &nodes[i].ID - if specs[i].ID.Value != nil { - id := specs[i].ID.Value.(int64) - nodes[i].ID = int(id) - } - mutation.done = true - return nodes[i], nil - }) - for i := len(builder.hooks) - 1; i >= 0; i-- { - mut = builder.hooks[i](mut) - } - mutators[i] = mut - }(i, ctx) - } - if len(mutators) > 0 { - if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { - return nil, err - } - } - return nodes, nil -} - -// SaveX is like Save, but panics if an error occurs. -func (_c *AuditLogCreateBulk) SaveX(ctx context.Context) []*AuditLog { - v, err := _c.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (_c *AuditLogCreateBulk) Exec(ctx context.Context) error { - _, err := _c.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_c *AuditLogCreateBulk) ExecX(ctx context.Context) { - if err := _c.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/ent/auditlog_delete.go b/ent/auditlog_delete.go deleted file mode 100644 index 8997258..0000000 --- a/ent/auditlog_delete.go +++ /dev/null @@ -1,88 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/ent/auditlog" - "git.dcentral.systems/toolz/goplt/ent/predicate" -) - -// AuditLogDelete is the builder for deleting a AuditLog entity. -type AuditLogDelete struct { - config - hooks []Hook - mutation *AuditLogMutation -} - -// Where appends a list predicates to the AuditLogDelete builder. -func (_d *AuditLogDelete) Where(ps ...predicate.AuditLog) *AuditLogDelete { - _d.mutation.Where(ps...) - return _d -} - -// Exec executes the deletion query and returns how many vertices were deleted. -func (_d *AuditLogDelete) Exec(ctx context.Context) (int, error) { - return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) -} - -// ExecX is like Exec, but panics if an error occurs. -func (_d *AuditLogDelete) ExecX(ctx context.Context) int { - n, err := _d.Exec(ctx) - if err != nil { - panic(err) - } - return n -} - -func (_d *AuditLogDelete) sqlExec(ctx context.Context) (int, error) { - _spec := sqlgraph.NewDeleteSpec(auditlog.Table, sqlgraph.NewFieldSpec(auditlog.FieldID, field.TypeInt)) - if ps := _d.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) - if err != nil && sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - _d.mutation.done = true - return affected, err -} - -// AuditLogDeleteOne is the builder for deleting a single AuditLog entity. -type AuditLogDeleteOne struct { - _d *AuditLogDelete -} - -// Where appends a list predicates to the AuditLogDelete builder. -func (_d *AuditLogDeleteOne) Where(ps ...predicate.AuditLog) *AuditLogDeleteOne { - _d._d.mutation.Where(ps...) - return _d -} - -// Exec executes the deletion query. -func (_d *AuditLogDeleteOne) Exec(ctx context.Context) error { - n, err := _d._d.Exec(ctx) - switch { - case err != nil: - return err - case n == 0: - return &NotFoundError{auditlog.Label} - default: - return nil - } -} - -// ExecX is like Exec, but panics if an error occurs. -func (_d *AuditLogDeleteOne) ExecX(ctx context.Context) { - if err := _d.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/ent/auditlog_query.go b/ent/auditlog_query.go deleted file mode 100644 index 1e40153..0000000 --- a/ent/auditlog_query.go +++ /dev/null @@ -1,505 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "fmt" - "math" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/ent/auditlog" - "git.dcentral.systems/toolz/goplt/ent/predicate" -) - -// AuditLogQuery is the builder for querying AuditLog entities. -type AuditLogQuery struct { - config - ctx *QueryContext - order []auditlog.OrderOption - inters []Interceptor - predicates []predicate.AuditLog - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Where adds a new predicate for the AuditLogQuery builder. -func (_q *AuditLogQuery) Where(ps ...predicate.AuditLog) *AuditLogQuery { - _q.predicates = append(_q.predicates, ps...) - return _q -} - -// Limit the number of records to be returned by this query. -func (_q *AuditLogQuery) Limit(limit int) *AuditLogQuery { - _q.ctx.Limit = &limit - return _q -} - -// Offset to start from. -func (_q *AuditLogQuery) Offset(offset int) *AuditLogQuery { - _q.ctx.Offset = &offset - return _q -} - -// Unique configures the query builder to filter duplicate records on query. -// By default, unique is set to true, and can be disabled using this method. -func (_q *AuditLogQuery) Unique(unique bool) *AuditLogQuery { - _q.ctx.Unique = &unique - return _q -} - -// Order specifies how the records should be ordered. -func (_q *AuditLogQuery) Order(o ...auditlog.OrderOption) *AuditLogQuery { - _q.order = append(_q.order, o...) - return _q -} - -// First returns the first AuditLog entity from the query. -// Returns a *NotFoundError when no AuditLog was found. -func (_q *AuditLogQuery) First(ctx context.Context) (*AuditLog, error) { - nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{auditlog.Label} - } - return nodes[0], nil -} - -// FirstX is like First, but panics if an error occurs. -func (_q *AuditLogQuery) FirstX(ctx context.Context) *AuditLog { - node, err := _q.First(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// FirstID returns the first AuditLog ID from the query. -// Returns a *NotFoundError when no AuditLog ID was found. -func (_q *AuditLogQuery) FirstID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{auditlog.Label} - return - } - return ids[0], nil -} - -// FirstIDX is like FirstID, but panics if an error occurs. -func (_q *AuditLogQuery) FirstIDX(ctx context.Context) int { - id, err := _q.FirstID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Only returns a single AuditLog entity found by the query, ensuring it only returns one. -// Returns a *NotSingularError when more than one AuditLog entity is found. -// Returns a *NotFoundError when no AuditLog entities are found. -func (_q *AuditLogQuery) Only(ctx context.Context) (*AuditLog, error) { - nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) - if err != nil { - return nil, err - } - switch len(nodes) { - case 1: - return nodes[0], nil - case 0: - return nil, &NotFoundError{auditlog.Label} - default: - return nil, &NotSingularError{auditlog.Label} - } -} - -// OnlyX is like Only, but panics if an error occurs. -func (_q *AuditLogQuery) OnlyX(ctx context.Context) *AuditLog { - node, err := _q.Only(ctx) - if err != nil { - panic(err) - } - return node -} - -// OnlyID is like Only, but returns the only AuditLog ID in the query. -// Returns a *NotSingularError when more than one AuditLog ID is found. -// Returns a *NotFoundError when no entities are found. -func (_q *AuditLogQuery) OnlyID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { - return - } - switch len(ids) { - case 1: - id = ids[0] - case 0: - err = &NotFoundError{auditlog.Label} - default: - err = &NotSingularError{auditlog.Label} - } - return -} - -// OnlyIDX is like OnlyID, but panics if an error occurs. -func (_q *AuditLogQuery) OnlyIDX(ctx context.Context) int { - id, err := _q.OnlyID(ctx) - if err != nil { - panic(err) - } - return id -} - -// All executes the query and returns a list of AuditLogs. -func (_q *AuditLogQuery) All(ctx context.Context) ([]*AuditLog, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) - if err := _q.prepareQuery(ctx); err != nil { - return nil, err - } - qr := querierAll[[]*AuditLog, *AuditLogQuery]() - return withInterceptors[[]*AuditLog](ctx, _q, qr, _q.inters) -} - -// AllX is like All, but panics if an error occurs. -func (_q *AuditLogQuery) AllX(ctx context.Context) []*AuditLog { - nodes, err := _q.All(ctx) - if err != nil { - panic(err) - } - return nodes -} - -// IDs executes the query and returns a list of AuditLog IDs. -func (_q *AuditLogQuery) IDs(ctx context.Context) (ids []int, err error) { - if _q.ctx.Unique == nil && _q.path != nil { - _q.Unique(true) - } - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) - if err = _q.Select(auditlog.FieldID).Scan(ctx, &ids); err != nil { - return nil, err - } - return ids, nil -} - -// IDsX is like IDs, but panics if an error occurs. -func (_q *AuditLogQuery) IDsX(ctx context.Context) []int { - ids, err := _q.IDs(ctx) - if err != nil { - panic(err) - } - return ids -} - -// Count returns the count of the given query. -func (_q *AuditLogQuery) Count(ctx context.Context) (int, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) - if err := _q.prepareQuery(ctx); err != nil { - return 0, err - } - return withInterceptors[int](ctx, _q, querierCount[*AuditLogQuery](), _q.inters) -} - -// CountX is like Count, but panics if an error occurs. -func (_q *AuditLogQuery) CountX(ctx context.Context) int { - count, err := _q.Count(ctx) - if err != nil { - panic(err) - } - return count -} - -// Exist returns true if the query has elements in the graph. -func (_q *AuditLogQuery) Exist(ctx context.Context) (bool, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) - switch _, err := _q.FirstID(ctx); { - case IsNotFound(err): - return false, nil - case err != nil: - return false, fmt.Errorf("ent: check existence: %w", err) - default: - return true, nil - } -} - -// ExistX is like Exist, but panics if an error occurs. -func (_q *AuditLogQuery) ExistX(ctx context.Context) bool { - exist, err := _q.Exist(ctx) - if err != nil { - panic(err) - } - return exist -} - -// Clone returns a duplicate of the AuditLogQuery builder, including all associated steps. It can be -// used to prepare common query builders and use them differently after the clone is made. -func (_q *AuditLogQuery) Clone() *AuditLogQuery { - if _q == nil { - return nil - } - return &AuditLogQuery{ - config: _q.config, - ctx: _q.ctx.Clone(), - order: append([]auditlog.OrderOption{}, _q.order...), - inters: append([]Interceptor{}, _q.inters...), - predicates: append([]predicate.AuditLog{}, _q.predicates...), - // clone intermediate query. - sql: _q.sql.Clone(), - path: _q.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. -func (_q *AuditLogQuery) GroupBy(field string, fields ...string) *AuditLogGroupBy { - _q.ctx.Fields = append([]string{field}, fields...) - grbuild := &AuditLogGroupBy{build: _q} - grbuild.flds = &_q.ctx.Fields - grbuild.label = auditlog.Label - grbuild.scan = grbuild.Scan - return grbuild -} - -// Select allows the selection one or more fields/columns for the given query, -// instead of selecting all fields in the entity. -func (_q *AuditLogQuery) Select(fields ...string) *AuditLogSelect { - _q.ctx.Fields = append(_q.ctx.Fields, fields...) - sbuild := &AuditLogSelect{AuditLogQuery: _q} - sbuild.label = auditlog.Label - sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan - return sbuild -} - -// Aggregate returns a AuditLogSelect configured with the given aggregations. -func (_q *AuditLogQuery) Aggregate(fns ...AggregateFunc) *AuditLogSelect { - return _q.Select().Aggregate(fns...) -} - -func (_q *AuditLogQuery) prepareQuery(ctx context.Context) error { - for _, inter := range _q.inters { - if inter == nil { - return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") - } - if trv, ok := inter.(Traverser); ok { - if err := trv.Traverse(ctx, _q); err != nil { - return err - } - } - } - for _, f := range _q.ctx.Fields { - if !auditlog.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} - } - } - if _q.path != nil { - prev, err := _q.path(ctx) - if err != nil { - return err - } - _q.sql = prev - } - return nil -} - -func (_q *AuditLogQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AuditLog, error) { - var ( - nodes = []*AuditLog{} - _spec = _q.querySpec() - ) - _spec.ScanValues = func(columns []string) ([]any, error) { - return (*AuditLog).scanValues(nil, columns) - } - _spec.Assign = func(columns []string, values []any) error { - node := &AuditLog{config: _q.config} - nodes = append(nodes, node) - return node.assignValues(columns, values) - } - for i := range hooks { - hooks[i](ctx, _spec) - } - if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { - return nil, err - } - if len(nodes) == 0 { - return nodes, nil - } - return nodes, nil -} - -func (_q *AuditLogQuery) sqlCount(ctx context.Context) (int, error) { - _spec := _q.querySpec() - _spec.Node.Columns = _q.ctx.Fields - if len(_q.ctx.Fields) > 0 { - _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique - } - return sqlgraph.CountNodes(ctx, _q.driver, _spec) -} - -func (_q *AuditLogQuery) querySpec() *sqlgraph.QuerySpec { - _spec := sqlgraph.NewQuerySpec(auditlog.Table, auditlog.Columns, sqlgraph.NewFieldSpec(auditlog.FieldID, field.TypeInt)) - _spec.From = _q.sql - if unique := _q.ctx.Unique; unique != nil { - _spec.Unique = *unique - } else if _q.path != nil { - _spec.Unique = true - } - if fields := _q.ctx.Fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, auditlog.FieldID) - for i := range fields { - if fields[i] != auditlog.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) - } - } - } - if ps := _q.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if limit := _q.ctx.Limit; limit != nil { - _spec.Limit = *limit - } - if offset := _q.ctx.Offset; offset != nil { - _spec.Offset = *offset - } - if ps := _q.order; len(ps) > 0 { - _spec.Order = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return _spec -} - -func (_q *AuditLogQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(_q.driver.Dialect()) - t1 := builder.Table(auditlog.Table) - columns := _q.ctx.Fields - if len(columns) == 0 { - columns = auditlog.Columns - } - selector := builder.Select(t1.Columns(columns...)...).From(t1) - if _q.sql != nil { - selector = _q.sql - selector.Select(selector.Columns(columns...)...) - } - if _q.ctx.Unique != nil && *_q.ctx.Unique { - selector.Distinct() - } - for _, p := range _q.predicates { - p(selector) - } - for _, p := range _q.order { - p(selector) - } - if offset := _q.ctx.Offset; offset != nil { - // limit is mandatory for offset clause. We start - // with default value, and override it below if needed. - selector.Offset(*offset).Limit(math.MaxInt32) - } - if limit := _q.ctx.Limit; limit != nil { - selector.Limit(*limit) - } - return selector -} - -// AuditLogGroupBy is the group-by builder for AuditLog entities. -type AuditLogGroupBy struct { - selector - build *AuditLogQuery -} - -// Aggregate adds the given aggregation functions to the group-by query. -func (_g *AuditLogGroupBy) Aggregate(fns ...AggregateFunc) *AuditLogGroupBy { - _g.fns = append(_g.fns, fns...) - return _g -} - -// Scan applies the selector query and scans the result into the given value. -func (_g *AuditLogGroupBy) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) - if err := _g.build.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*AuditLogQuery, *AuditLogGroupBy](ctx, _g.build, _g, _g.build.inters, v) -} - -func (_g *AuditLogGroupBy) sqlScan(ctx context.Context, root *AuditLogQuery, v any) error { - selector := root.sqlQuery(ctx).Select() - aggregation := make([]string, 0, len(_g.fns)) - for _, fn := range _g.fns { - aggregation = append(aggregation, fn(selector)) - } - if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) - for _, f := range *_g.flds { - columns = append(columns, selector.C(f)) - } - columns = append(columns, aggregation...) - selector.Select(columns...) - } - selector.GroupBy(selector.Columns(*_g.flds...)...) - if err := selector.Err(); err != nil { - return err - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} - -// AuditLogSelect is the builder for selecting fields of AuditLog entities. -type AuditLogSelect struct { - *AuditLogQuery - selector -} - -// Aggregate adds the given aggregation functions to the selector query. -func (_s *AuditLogSelect) Aggregate(fns ...AggregateFunc) *AuditLogSelect { - _s.fns = append(_s.fns, fns...) - return _s -} - -// Scan applies the selector query and scans the result into the given value. -func (_s *AuditLogSelect) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) - if err := _s.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*AuditLogQuery, *AuditLogSelect](ctx, _s.AuditLogQuery, _s, _s.inters, v) -} - -func (_s *AuditLogSelect) sqlScan(ctx context.Context, root *AuditLogQuery, v any) error { - selector := root.sqlQuery(ctx) - aggregation := make([]string, 0, len(_s.fns)) - for _, fn := range _s.fns { - aggregation = append(aggregation, fn(selector)) - } - switch n := len(*_s.selector.flds); { - case n == 0 && len(aggregation) > 0: - selector.Select(aggregation...) - case n != 0 && len(aggregation) > 0: - selector.AppendSelect(aggregation...) - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := _s.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} diff --git a/ent/auditlog_update.go b/ent/auditlog_update.go deleted file mode 100644 index 8ebeb5e..0000000 --- a/ent/auditlog_update.go +++ /dev/null @@ -1,175 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "errors" - "fmt" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/ent/auditlog" - "git.dcentral.systems/toolz/goplt/ent/predicate" -) - -// AuditLogUpdate is the builder for updating AuditLog entities. -type AuditLogUpdate struct { - config - hooks []Hook - mutation *AuditLogMutation -} - -// Where appends a list predicates to the AuditLogUpdate builder. -func (_u *AuditLogUpdate) Where(ps ...predicate.AuditLog) *AuditLogUpdate { - _u.mutation.Where(ps...) - return _u -} - -// Mutation returns the AuditLogMutation object of the builder. -func (_u *AuditLogUpdate) Mutation() *AuditLogMutation { - return _u.mutation -} - -// Save executes the query and returns the number of nodes affected by the update operation. -func (_u *AuditLogUpdate) Save(ctx context.Context) (int, error) { - return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (_u *AuditLogUpdate) SaveX(ctx context.Context) int { - affected, err := _u.Save(ctx) - if err != nil { - panic(err) - } - return affected -} - -// Exec executes the query. -func (_u *AuditLogUpdate) Exec(ctx context.Context) error { - _, err := _u.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_u *AuditLogUpdate) ExecX(ctx context.Context) { - if err := _u.Exec(ctx); err != nil { - panic(err) - } -} - -func (_u *AuditLogUpdate) sqlSave(ctx context.Context) (_node int, err error) { - _spec := sqlgraph.NewUpdateSpec(auditlog.Table, auditlog.Columns, sqlgraph.NewFieldSpec(auditlog.FieldID, field.TypeInt)) - if ps := _u.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{auditlog.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return 0, err - } - _u.mutation.done = true - return _node, nil -} - -// AuditLogUpdateOne is the builder for updating a single AuditLog entity. -type AuditLogUpdateOne struct { - config - fields []string - hooks []Hook - mutation *AuditLogMutation -} - -// Mutation returns the AuditLogMutation object of the builder. -func (_u *AuditLogUpdateOne) Mutation() *AuditLogMutation { - return _u.mutation -} - -// Where appends a list predicates to the AuditLogUpdate builder. -func (_u *AuditLogUpdateOne) Where(ps ...predicate.AuditLog) *AuditLogUpdateOne { - _u.mutation.Where(ps...) - return _u -} - -// Select allows selecting one or more fields (columns) of the returned entity. -// The default is selecting all fields defined in the entity schema. -func (_u *AuditLogUpdateOne) Select(field string, fields ...string) *AuditLogUpdateOne { - _u.fields = append([]string{field}, fields...) - return _u -} - -// Save executes the query and returns the updated AuditLog entity. -func (_u *AuditLogUpdateOne) Save(ctx context.Context) (*AuditLog, error) { - return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (_u *AuditLogUpdateOne) SaveX(ctx context.Context) *AuditLog { - node, err := _u.Save(ctx) - if err != nil { - panic(err) - } - return node -} - -// Exec executes the query on the entity. -func (_u *AuditLogUpdateOne) Exec(ctx context.Context) error { - _, err := _u.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_u *AuditLogUpdateOne) ExecX(ctx context.Context) { - if err := _u.Exec(ctx); err != nil { - panic(err) - } -} - -func (_u *AuditLogUpdateOne) sqlSave(ctx context.Context) (_node *AuditLog, err error) { - _spec := sqlgraph.NewUpdateSpec(auditlog.Table, auditlog.Columns, sqlgraph.NewFieldSpec(auditlog.FieldID, field.TypeInt)) - id, ok := _u.mutation.ID() - if !ok { - return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "AuditLog.id" for update`)} - } - _spec.Node.ID.Value = id - if fields := _u.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, auditlog.FieldID) - for _, f := range fields { - if !auditlog.ValidColumn(f) { - return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} - } - if f != auditlog.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, f) - } - } - } - if ps := _u.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - _node = &AuditLog{config: _u.config} - _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{auditlog.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - _u.mutation.done = true - return _node, nil -} diff --git a/ent/client.go b/ent/client.go deleted file mode 100644 index 652ce20..0000000 --- a/ent/client.go +++ /dev/null @@ -1,769 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "errors" - "fmt" - "log" - "reflect" - - "git.dcentral.systems/toolz/goplt/ent/migrate" - - "entgo.io/ent" - "entgo.io/ent/dialect" - "entgo.io/ent/dialect/sql" - "git.dcentral.systems/toolz/goplt/ent/auditlog" - "git.dcentral.systems/toolz/goplt/ent/permission" - "git.dcentral.systems/toolz/goplt/ent/role" - "git.dcentral.systems/toolz/goplt/ent/user" -) - -// Client is the client that holds all ent builders. -type Client struct { - config - // Schema is the client for creating, migrating and dropping schema. - Schema *migrate.Schema - // AuditLog is the client for interacting with the AuditLog builders. - AuditLog *AuditLogClient - // Permission is the client for interacting with the Permission builders. - Permission *PermissionClient - // Role is the client for interacting with the Role builders. - Role *RoleClient - // User is the client for interacting with the User builders. - User *UserClient -} - -// NewClient creates a new client configured with the given options. -func NewClient(opts ...Option) *Client { - client := &Client{config: newConfig(opts...)} - client.init() - return client -} - -func (c *Client) init() { - c.Schema = migrate.NewSchema(c.driver) - c.AuditLog = NewAuditLogClient(c.config) - c.Permission = NewPermissionClient(c.config) - c.Role = NewRoleClient(c.config) - c.User = NewUserClient(c.config) -} - -type ( - // config is the configuration for the client and its builder. - config struct { - // driver used for executing database requests. - driver dialect.Driver - // debug enable a debug logging. - debug bool - // log used for logging on debug mode. - log func(...any) - // hooks to execute on mutations. - hooks *hooks - // interceptors to execute on queries. - inters *inters - } - // Option function to configure the client. - Option func(*config) -) - -// newConfig creates a new config for the client. -func newConfig(opts ...Option) config { - cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}} - cfg.options(opts...) - return cfg -} - -// options applies the options on the config object. -func (c *config) options(opts ...Option) { - for _, opt := range opts { - opt(c) - } - if c.debug { - c.driver = dialect.Debug(c.driver, c.log) - } -} - -// Debug enables debug logging on the ent.Driver. -func Debug() Option { - return func(c *config) { - c.debug = true - } -} - -// Log sets the logging function for debug mode. -func Log(fn func(...any)) Option { - return func(c *config) { - c.log = fn - } -} - -// Driver configures the client driver. -func Driver(driver dialect.Driver) Option { - return func(c *config) { - c.driver = driver - } -} - -// Open opens a database/sql.DB specified by the driver name and -// the data source name, and returns a new client attached to it. -// Optional parameters can be added for configuring the client. -func Open(driverName, dataSourceName string, options ...Option) (*Client, error) { - switch driverName { - case dialect.MySQL, dialect.Postgres, dialect.SQLite: - drv, err := sql.Open(driverName, dataSourceName) - if err != nil { - return nil, err - } - return NewClient(append(options, Driver(drv))...), nil - default: - return nil, fmt.Errorf("unsupported driver: %q", driverName) - } -} - -// ErrTxStarted is returned when trying to start a new transaction from a transactional client. -var ErrTxStarted = errors.New("ent: cannot start a transaction within a transaction") - -// Tx returns a new transactional client. The provided context -// is used until the transaction is committed or rolled back. -func (c *Client) Tx(ctx context.Context) (*Tx, error) { - if _, ok := c.driver.(*txDriver); ok { - return nil, ErrTxStarted - } - tx, err := newTx(ctx, c.driver) - if err != nil { - return nil, fmt.Errorf("ent: starting a transaction: %w", err) - } - cfg := c.config - cfg.driver = tx - return &Tx{ - ctx: ctx, - config: cfg, - AuditLog: NewAuditLogClient(cfg), - Permission: NewPermissionClient(cfg), - Role: NewRoleClient(cfg), - User: NewUserClient(cfg), - }, nil -} - -// BeginTx returns a transactional client with specified options. -func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) { - if _, ok := c.driver.(*txDriver); ok { - return nil, errors.New("ent: cannot start a transaction within a transaction") - } - tx, err := c.driver.(interface { - BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error) - }).BeginTx(ctx, opts) - if err != nil { - return nil, fmt.Errorf("ent: starting a transaction: %w", err) - } - cfg := c.config - cfg.driver = &txDriver{tx: tx, drv: c.driver} - return &Tx{ - ctx: ctx, - config: cfg, - AuditLog: NewAuditLogClient(cfg), - Permission: NewPermissionClient(cfg), - Role: NewRoleClient(cfg), - User: NewUserClient(cfg), - }, nil -} - -// Debug returns a new debug-client. It's used to get verbose logging on specific operations. -// -// client.Debug(). -// AuditLog. -// Query(). -// Count(ctx) -func (c *Client) Debug() *Client { - if c.debug { - return c - } - cfg := c.config - cfg.driver = dialect.Debug(c.driver, c.log) - client := &Client{config: cfg} - client.init() - return client -} - -// Close closes the database connection and prevents new queries from starting. -func (c *Client) Close() error { - return c.driver.Close() -} - -// Use adds the mutation hooks to all the entity clients. -// In order to add hooks to a specific client, call: `client.Node.Use(...)`. -func (c *Client) Use(hooks ...Hook) { - c.AuditLog.Use(hooks...) - c.Permission.Use(hooks...) - c.Role.Use(hooks...) - c.User.Use(hooks...) -} - -// Intercept adds the query interceptors to all the entity clients. -// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. -func (c *Client) Intercept(interceptors ...Interceptor) { - c.AuditLog.Intercept(interceptors...) - c.Permission.Intercept(interceptors...) - c.Role.Intercept(interceptors...) - c.User.Intercept(interceptors...) -} - -// Mutate implements the ent.Mutator interface. -func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { - switch m := m.(type) { - case *AuditLogMutation: - return c.AuditLog.mutate(ctx, m) - case *PermissionMutation: - return c.Permission.mutate(ctx, m) - case *RoleMutation: - return c.Role.mutate(ctx, m) - case *UserMutation: - return c.User.mutate(ctx, m) - default: - return nil, fmt.Errorf("ent: unknown mutation type %T", m) - } -} - -// AuditLogClient is a client for the AuditLog schema. -type AuditLogClient struct { - config -} - -// NewAuditLogClient returns a client for the AuditLog from the given config. -func NewAuditLogClient(c config) *AuditLogClient { - return &AuditLogClient{config: c} -} - -// Use adds a list of mutation hooks to the hooks stack. -// A call to `Use(f, g, h)` equals to `auditlog.Hooks(f(g(h())))`. -func (c *AuditLogClient) Use(hooks ...Hook) { - c.hooks.AuditLog = append(c.hooks.AuditLog, hooks...) -} - -// Intercept adds a list of query interceptors to the interceptors stack. -// A call to `Intercept(f, g, h)` equals to `auditlog.Intercept(f(g(h())))`. -func (c *AuditLogClient) Intercept(interceptors ...Interceptor) { - c.inters.AuditLog = append(c.inters.AuditLog, interceptors...) -} - -// Create returns a builder for creating a AuditLog entity. -func (c *AuditLogClient) Create() *AuditLogCreate { - mutation := newAuditLogMutation(c.config, OpCreate) - return &AuditLogCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// CreateBulk returns a builder for creating a bulk of AuditLog entities. -func (c *AuditLogClient) CreateBulk(builders ...*AuditLogCreate) *AuditLogCreateBulk { - return &AuditLogCreateBulk{config: c.config, builders: builders} -} - -// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates -// a builder and applies setFunc on it. -func (c *AuditLogClient) MapCreateBulk(slice any, setFunc func(*AuditLogCreate, int)) *AuditLogCreateBulk { - rv := reflect.ValueOf(slice) - if rv.Kind() != reflect.Slice { - return &AuditLogCreateBulk{err: fmt.Errorf("calling to AuditLogClient.MapCreateBulk with wrong type %T, need slice", slice)} - } - builders := make([]*AuditLogCreate, rv.Len()) - for i := 0; i < rv.Len(); i++ { - builders[i] = c.Create() - setFunc(builders[i], i) - } - return &AuditLogCreateBulk{config: c.config, builders: builders} -} - -// Update returns an update builder for AuditLog. -func (c *AuditLogClient) Update() *AuditLogUpdate { - mutation := newAuditLogMutation(c.config, OpUpdate) - return &AuditLogUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOne returns an update builder for the given entity. -func (c *AuditLogClient) UpdateOne(_m *AuditLog) *AuditLogUpdateOne { - mutation := newAuditLogMutation(c.config, OpUpdateOne, withAuditLog(_m)) - return &AuditLogUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOneID returns an update builder for the given id. -func (c *AuditLogClient) UpdateOneID(id int) *AuditLogUpdateOne { - mutation := newAuditLogMutation(c.config, OpUpdateOne, withAuditLogID(id)) - return &AuditLogUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// Delete returns a delete builder for AuditLog. -func (c *AuditLogClient) Delete() *AuditLogDelete { - mutation := newAuditLogMutation(c.config, OpDelete) - return &AuditLogDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// DeleteOne returns a builder for deleting the given entity. -func (c *AuditLogClient) DeleteOne(_m *AuditLog) *AuditLogDeleteOne { - return c.DeleteOneID(_m.ID) -} - -// DeleteOneID returns a builder for deleting the given entity by its id. -func (c *AuditLogClient) DeleteOneID(id int) *AuditLogDeleteOne { - builder := c.Delete().Where(auditlog.ID(id)) - builder.mutation.id = &id - builder.mutation.op = OpDeleteOne - return &AuditLogDeleteOne{builder} -} - -// Query returns a query builder for AuditLog. -func (c *AuditLogClient) Query() *AuditLogQuery { - return &AuditLogQuery{ - config: c.config, - ctx: &QueryContext{Type: TypeAuditLog}, - inters: c.Interceptors(), - } -} - -// Get returns a AuditLog entity by its id. -func (c *AuditLogClient) Get(ctx context.Context, id int) (*AuditLog, error) { - return c.Query().Where(auditlog.ID(id)).Only(ctx) -} - -// GetX is like Get, but panics if an error occurs. -func (c *AuditLogClient) GetX(ctx context.Context, id int) *AuditLog { - obj, err := c.Get(ctx, id) - if err != nil { - panic(err) - } - return obj -} - -// Hooks returns the client hooks. -func (c *AuditLogClient) Hooks() []Hook { - return c.hooks.AuditLog -} - -// Interceptors returns the client interceptors. -func (c *AuditLogClient) Interceptors() []Interceptor { - return c.inters.AuditLog -} - -func (c *AuditLogClient) mutate(ctx context.Context, m *AuditLogMutation) (Value, error) { - switch m.Op() { - case OpCreate: - return (&AuditLogCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdate: - return (&AuditLogUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdateOne: - return (&AuditLogUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpDelete, OpDeleteOne: - return (&AuditLogDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) - default: - return nil, fmt.Errorf("ent: unknown AuditLog mutation op: %q", m.Op()) - } -} - -// PermissionClient is a client for the Permission schema. -type PermissionClient struct { - config -} - -// NewPermissionClient returns a client for the Permission from the given config. -func NewPermissionClient(c config) *PermissionClient { - return &PermissionClient{config: c} -} - -// Use adds a list of mutation hooks to the hooks stack. -// A call to `Use(f, g, h)` equals to `permission.Hooks(f(g(h())))`. -func (c *PermissionClient) Use(hooks ...Hook) { - c.hooks.Permission = append(c.hooks.Permission, hooks...) -} - -// Intercept adds a list of query interceptors to the interceptors stack. -// A call to `Intercept(f, g, h)` equals to `permission.Intercept(f(g(h())))`. -func (c *PermissionClient) Intercept(interceptors ...Interceptor) { - c.inters.Permission = append(c.inters.Permission, interceptors...) -} - -// Create returns a builder for creating a Permission entity. -func (c *PermissionClient) Create() *PermissionCreate { - mutation := newPermissionMutation(c.config, OpCreate) - return &PermissionCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// CreateBulk returns a builder for creating a bulk of Permission entities. -func (c *PermissionClient) CreateBulk(builders ...*PermissionCreate) *PermissionCreateBulk { - return &PermissionCreateBulk{config: c.config, builders: builders} -} - -// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates -// a builder and applies setFunc on it. -func (c *PermissionClient) MapCreateBulk(slice any, setFunc func(*PermissionCreate, int)) *PermissionCreateBulk { - rv := reflect.ValueOf(slice) - if rv.Kind() != reflect.Slice { - return &PermissionCreateBulk{err: fmt.Errorf("calling to PermissionClient.MapCreateBulk with wrong type %T, need slice", slice)} - } - builders := make([]*PermissionCreate, rv.Len()) - for i := 0; i < rv.Len(); i++ { - builders[i] = c.Create() - setFunc(builders[i], i) - } - return &PermissionCreateBulk{config: c.config, builders: builders} -} - -// Update returns an update builder for Permission. -func (c *PermissionClient) Update() *PermissionUpdate { - mutation := newPermissionMutation(c.config, OpUpdate) - return &PermissionUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOne returns an update builder for the given entity. -func (c *PermissionClient) UpdateOne(_m *Permission) *PermissionUpdateOne { - mutation := newPermissionMutation(c.config, OpUpdateOne, withPermission(_m)) - return &PermissionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOneID returns an update builder for the given id. -func (c *PermissionClient) UpdateOneID(id int) *PermissionUpdateOne { - mutation := newPermissionMutation(c.config, OpUpdateOne, withPermissionID(id)) - return &PermissionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// Delete returns a delete builder for Permission. -func (c *PermissionClient) Delete() *PermissionDelete { - mutation := newPermissionMutation(c.config, OpDelete) - return &PermissionDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// DeleteOne returns a builder for deleting the given entity. -func (c *PermissionClient) DeleteOne(_m *Permission) *PermissionDeleteOne { - return c.DeleteOneID(_m.ID) -} - -// DeleteOneID returns a builder for deleting the given entity by its id. -func (c *PermissionClient) DeleteOneID(id int) *PermissionDeleteOne { - builder := c.Delete().Where(permission.ID(id)) - builder.mutation.id = &id - builder.mutation.op = OpDeleteOne - return &PermissionDeleteOne{builder} -} - -// Query returns a query builder for Permission. -func (c *PermissionClient) Query() *PermissionQuery { - return &PermissionQuery{ - config: c.config, - ctx: &QueryContext{Type: TypePermission}, - inters: c.Interceptors(), - } -} - -// Get returns a Permission entity by its id. -func (c *PermissionClient) Get(ctx context.Context, id int) (*Permission, error) { - return c.Query().Where(permission.ID(id)).Only(ctx) -} - -// GetX is like Get, but panics if an error occurs. -func (c *PermissionClient) GetX(ctx context.Context, id int) *Permission { - obj, err := c.Get(ctx, id) - if err != nil { - panic(err) - } - return obj -} - -// Hooks returns the client hooks. -func (c *PermissionClient) Hooks() []Hook { - return c.hooks.Permission -} - -// Interceptors returns the client interceptors. -func (c *PermissionClient) Interceptors() []Interceptor { - return c.inters.Permission -} - -func (c *PermissionClient) mutate(ctx context.Context, m *PermissionMutation) (Value, error) { - switch m.Op() { - case OpCreate: - return (&PermissionCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdate: - return (&PermissionUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdateOne: - return (&PermissionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpDelete, OpDeleteOne: - return (&PermissionDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) - default: - return nil, fmt.Errorf("ent: unknown Permission mutation op: %q", m.Op()) - } -} - -// RoleClient is a client for the Role schema. -type RoleClient struct { - config -} - -// NewRoleClient returns a client for the Role from the given config. -func NewRoleClient(c config) *RoleClient { - return &RoleClient{config: c} -} - -// Use adds a list of mutation hooks to the hooks stack. -// A call to `Use(f, g, h)` equals to `role.Hooks(f(g(h())))`. -func (c *RoleClient) Use(hooks ...Hook) { - c.hooks.Role = append(c.hooks.Role, hooks...) -} - -// Intercept adds a list of query interceptors to the interceptors stack. -// A call to `Intercept(f, g, h)` equals to `role.Intercept(f(g(h())))`. -func (c *RoleClient) Intercept(interceptors ...Interceptor) { - c.inters.Role = append(c.inters.Role, interceptors...) -} - -// Create returns a builder for creating a Role entity. -func (c *RoleClient) Create() *RoleCreate { - mutation := newRoleMutation(c.config, OpCreate) - return &RoleCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// CreateBulk returns a builder for creating a bulk of Role entities. -func (c *RoleClient) CreateBulk(builders ...*RoleCreate) *RoleCreateBulk { - return &RoleCreateBulk{config: c.config, builders: builders} -} - -// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates -// a builder and applies setFunc on it. -func (c *RoleClient) MapCreateBulk(slice any, setFunc func(*RoleCreate, int)) *RoleCreateBulk { - rv := reflect.ValueOf(slice) - if rv.Kind() != reflect.Slice { - return &RoleCreateBulk{err: fmt.Errorf("calling to RoleClient.MapCreateBulk with wrong type %T, need slice", slice)} - } - builders := make([]*RoleCreate, rv.Len()) - for i := 0; i < rv.Len(); i++ { - builders[i] = c.Create() - setFunc(builders[i], i) - } - return &RoleCreateBulk{config: c.config, builders: builders} -} - -// Update returns an update builder for Role. -func (c *RoleClient) Update() *RoleUpdate { - mutation := newRoleMutation(c.config, OpUpdate) - return &RoleUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOne returns an update builder for the given entity. -func (c *RoleClient) UpdateOne(_m *Role) *RoleUpdateOne { - mutation := newRoleMutation(c.config, OpUpdateOne, withRole(_m)) - return &RoleUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOneID returns an update builder for the given id. -func (c *RoleClient) UpdateOneID(id int) *RoleUpdateOne { - mutation := newRoleMutation(c.config, OpUpdateOne, withRoleID(id)) - return &RoleUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// Delete returns a delete builder for Role. -func (c *RoleClient) Delete() *RoleDelete { - mutation := newRoleMutation(c.config, OpDelete) - return &RoleDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// DeleteOne returns a builder for deleting the given entity. -func (c *RoleClient) DeleteOne(_m *Role) *RoleDeleteOne { - return c.DeleteOneID(_m.ID) -} - -// DeleteOneID returns a builder for deleting the given entity by its id. -func (c *RoleClient) DeleteOneID(id int) *RoleDeleteOne { - builder := c.Delete().Where(role.ID(id)) - builder.mutation.id = &id - builder.mutation.op = OpDeleteOne - return &RoleDeleteOne{builder} -} - -// Query returns a query builder for Role. -func (c *RoleClient) Query() *RoleQuery { - return &RoleQuery{ - config: c.config, - ctx: &QueryContext{Type: TypeRole}, - inters: c.Interceptors(), - } -} - -// Get returns a Role entity by its id. -func (c *RoleClient) Get(ctx context.Context, id int) (*Role, error) { - return c.Query().Where(role.ID(id)).Only(ctx) -} - -// GetX is like Get, but panics if an error occurs. -func (c *RoleClient) GetX(ctx context.Context, id int) *Role { - obj, err := c.Get(ctx, id) - if err != nil { - panic(err) - } - return obj -} - -// Hooks returns the client hooks. -func (c *RoleClient) Hooks() []Hook { - return c.hooks.Role -} - -// Interceptors returns the client interceptors. -func (c *RoleClient) Interceptors() []Interceptor { - return c.inters.Role -} - -func (c *RoleClient) mutate(ctx context.Context, m *RoleMutation) (Value, error) { - switch m.Op() { - case OpCreate: - return (&RoleCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdate: - return (&RoleUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdateOne: - return (&RoleUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpDelete, OpDeleteOne: - return (&RoleDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) - default: - return nil, fmt.Errorf("ent: unknown Role mutation op: %q", m.Op()) - } -} - -// UserClient is a client for the User schema. -type UserClient struct { - config -} - -// NewUserClient returns a client for the User from the given config. -func NewUserClient(c config) *UserClient { - return &UserClient{config: c} -} - -// Use adds a list of mutation hooks to the hooks stack. -// A call to `Use(f, g, h)` equals to `user.Hooks(f(g(h())))`. -func (c *UserClient) Use(hooks ...Hook) { - c.hooks.User = append(c.hooks.User, hooks...) -} - -// Intercept adds a list of query interceptors to the interceptors stack. -// A call to `Intercept(f, g, h)` equals to `user.Intercept(f(g(h())))`. -func (c *UserClient) Intercept(interceptors ...Interceptor) { - c.inters.User = append(c.inters.User, interceptors...) -} - -// Create returns a builder for creating a User entity. -func (c *UserClient) Create() *UserCreate { - mutation := newUserMutation(c.config, OpCreate) - return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// CreateBulk returns a builder for creating a bulk of User entities. -func (c *UserClient) CreateBulk(builders ...*UserCreate) *UserCreateBulk { - return &UserCreateBulk{config: c.config, builders: builders} -} - -// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates -// a builder and applies setFunc on it. -func (c *UserClient) MapCreateBulk(slice any, setFunc func(*UserCreate, int)) *UserCreateBulk { - rv := reflect.ValueOf(slice) - if rv.Kind() != reflect.Slice { - return &UserCreateBulk{err: fmt.Errorf("calling to UserClient.MapCreateBulk with wrong type %T, need slice", slice)} - } - builders := make([]*UserCreate, rv.Len()) - for i := 0; i < rv.Len(); i++ { - builders[i] = c.Create() - setFunc(builders[i], i) - } - return &UserCreateBulk{config: c.config, builders: builders} -} - -// Update returns an update builder for User. -func (c *UserClient) Update() *UserUpdate { - mutation := newUserMutation(c.config, OpUpdate) - return &UserUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOne returns an update builder for the given entity. -func (c *UserClient) UpdateOne(_m *User) *UserUpdateOne { - mutation := newUserMutation(c.config, OpUpdateOne, withUser(_m)) - return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOneID returns an update builder for the given id. -func (c *UserClient) UpdateOneID(id int) *UserUpdateOne { - mutation := newUserMutation(c.config, OpUpdateOne, withUserID(id)) - return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// Delete returns a delete builder for User. -func (c *UserClient) Delete() *UserDelete { - mutation := newUserMutation(c.config, OpDelete) - return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// DeleteOne returns a builder for deleting the given entity. -func (c *UserClient) DeleteOne(_m *User) *UserDeleteOne { - return c.DeleteOneID(_m.ID) -} - -// DeleteOneID returns a builder for deleting the given entity by its id. -func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { - builder := c.Delete().Where(user.ID(id)) - builder.mutation.id = &id - builder.mutation.op = OpDeleteOne - return &UserDeleteOne{builder} -} - -// Query returns a query builder for User. -func (c *UserClient) Query() *UserQuery { - return &UserQuery{ - config: c.config, - ctx: &QueryContext{Type: TypeUser}, - inters: c.Interceptors(), - } -} - -// Get returns a User entity by its id. -func (c *UserClient) Get(ctx context.Context, id int) (*User, error) { - return c.Query().Where(user.ID(id)).Only(ctx) -} - -// GetX is like Get, but panics if an error occurs. -func (c *UserClient) GetX(ctx context.Context, id int) *User { - obj, err := c.Get(ctx, id) - if err != nil { - panic(err) - } - return obj -} - -// Hooks returns the client hooks. -func (c *UserClient) Hooks() []Hook { - return c.hooks.User -} - -// Interceptors returns the client interceptors. -func (c *UserClient) Interceptors() []Interceptor { - return c.inters.User -} - -func (c *UserClient) mutate(ctx context.Context, m *UserMutation) (Value, error) { - switch m.Op() { - case OpCreate: - return (&UserCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdate: - return (&UserUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdateOne: - return (&UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpDelete, OpDeleteOne: - return (&UserDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) - default: - return nil, fmt.Errorf("ent: unknown User mutation op: %q", m.Op()) - } -} - -// hooks and interceptors per client, for fast access. -type ( - hooks struct { - AuditLog, Permission, Role, User []ent.Hook - } - inters struct { - AuditLog, Permission, Role, User []ent.Interceptor - } -) diff --git a/ent/ent.go b/ent/ent.go deleted file mode 100644 index 76d55aa..0000000 --- a/ent/ent.go +++ /dev/null @@ -1,614 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "errors" - "fmt" - "reflect" - "sync" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "git.dcentral.systems/toolz/goplt/ent/auditlog" - "git.dcentral.systems/toolz/goplt/ent/permission" - "git.dcentral.systems/toolz/goplt/ent/role" - "git.dcentral.systems/toolz/goplt/ent/user" -) - -// ent aliases to avoid import conflicts in user's code. -type ( - Op = ent.Op - Hook = ent.Hook - Value = ent.Value - Query = ent.Query - QueryContext = ent.QueryContext - Querier = ent.Querier - QuerierFunc = ent.QuerierFunc - Interceptor = ent.Interceptor - InterceptFunc = ent.InterceptFunc - Traverser = ent.Traverser - TraverseFunc = ent.TraverseFunc - Policy = ent.Policy - Mutator = ent.Mutator - Mutation = ent.Mutation - MutateFunc = ent.MutateFunc -) - -type clientCtxKey struct{} - -// FromContext returns a Client stored inside a context, or nil if there isn't one. -func FromContext(ctx context.Context) *Client { - c, _ := ctx.Value(clientCtxKey{}).(*Client) - return c -} - -// NewContext returns a new context with the given Client attached. -func NewContext(parent context.Context, c *Client) context.Context { - return context.WithValue(parent, clientCtxKey{}, c) -} - -type txCtxKey struct{} - -// TxFromContext returns a Tx stored inside a context, or nil if there isn't one. -func TxFromContext(ctx context.Context) *Tx { - tx, _ := ctx.Value(txCtxKey{}).(*Tx) - return tx -} - -// NewTxContext returns a new context with the given Tx attached. -func NewTxContext(parent context.Context, tx *Tx) context.Context { - return context.WithValue(parent, txCtxKey{}, tx) -} - -// OrderFunc applies an ordering on the sql selector. -// Deprecated: Use Asc/Desc functions or the package builders instead. -type OrderFunc func(*sql.Selector) - -var ( - initCheck sync.Once - columnCheck sql.ColumnCheck -) - -// checkColumn checks if the column exists in the given table. -func checkColumn(t, c string) error { - initCheck.Do(func() { - columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ - auditlog.Table: auditlog.ValidColumn, - permission.Table: permission.ValidColumn, - role.Table: role.ValidColumn, - user.Table: user.ValidColumn, - }) - }) - return columnCheck(t, c) -} - -// Asc applies the given fields in ASC order. -func Asc(fields ...string) func(*sql.Selector) { - return func(s *sql.Selector) { - for _, f := range fields { - if err := checkColumn(s.TableName(), f); err != nil { - s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)}) - } - s.OrderBy(sql.Asc(s.C(f))) - } - } -} - -// Desc applies the given fields in DESC order. -func Desc(fields ...string) func(*sql.Selector) { - return func(s *sql.Selector) { - for _, f := range fields { - if err := checkColumn(s.TableName(), f); err != nil { - s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)}) - } - s.OrderBy(sql.Desc(s.C(f))) - } - } -} - -// AggregateFunc applies an aggregation step on the group-by traversal/selector. -type AggregateFunc func(*sql.Selector) string - -// As is a pseudo aggregation function for renaming another other functions with custom names. For example: -// -// GroupBy(field1, field2). -// Aggregate(ent.As(ent.Sum(field1), "sum_field1"), (ent.As(ent.Sum(field2), "sum_field2")). -// Scan(ctx, &v) -func As(fn AggregateFunc, end string) AggregateFunc { - return func(s *sql.Selector) string { - return sql.As(fn(s), end) - } -} - -// Count applies the "count" aggregation function on each group. -func Count() AggregateFunc { - return func(s *sql.Selector) string { - return sql.Count("*") - } -} - -// Max applies the "max" aggregation function on the given field of each group. -func Max(field string) AggregateFunc { - return func(s *sql.Selector) string { - if err := checkColumn(s.TableName(), field); err != nil { - s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) - return "" - } - return sql.Max(s.C(field)) - } -} - -// Mean applies the "mean" aggregation function on the given field of each group. -func Mean(field string) AggregateFunc { - return func(s *sql.Selector) string { - if err := checkColumn(s.TableName(), field); err != nil { - s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) - return "" - } - return sql.Avg(s.C(field)) - } -} - -// Min applies the "min" aggregation function on the given field of each group. -func Min(field string) AggregateFunc { - return func(s *sql.Selector) string { - if err := checkColumn(s.TableName(), field); err != nil { - s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) - return "" - } - return sql.Min(s.C(field)) - } -} - -// Sum applies the "sum" aggregation function on the given field of each group. -func Sum(field string) AggregateFunc { - return func(s *sql.Selector) string { - if err := checkColumn(s.TableName(), field); err != nil { - s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) - return "" - } - return sql.Sum(s.C(field)) - } -} - -// ValidationError returns when validating a field or edge fails. -type ValidationError struct { - Name string // Field or edge name. - err error -} - -// Error implements the error interface. -func (e *ValidationError) Error() string { - return e.err.Error() -} - -// Unwrap implements the errors.Wrapper interface. -func (e *ValidationError) Unwrap() error { - return e.err -} - -// IsValidationError returns a boolean indicating whether the error is a validation error. -func IsValidationError(err error) bool { - if err == nil { - return false - } - var e *ValidationError - return errors.As(err, &e) -} - -// NotFoundError returns when trying to fetch a specific entity and it was not found in the database. -type NotFoundError struct { - label string -} - -// Error implements the error interface. -func (e *NotFoundError) Error() string { - return "ent: " + e.label + " not found" -} - -// IsNotFound returns a boolean indicating whether the error is a not found error. -func IsNotFound(err error) bool { - if err == nil { - return false - } - var e *NotFoundError - return errors.As(err, &e) -} - -// MaskNotFound masks not found error. -func MaskNotFound(err error) error { - if IsNotFound(err) { - return nil - } - return err -} - -// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database. -type NotSingularError struct { - label string -} - -// Error implements the error interface. -func (e *NotSingularError) Error() string { - return "ent: " + e.label + " not singular" -} - -// IsNotSingular returns a boolean indicating whether the error is a not singular error. -func IsNotSingular(err error) bool { - if err == nil { - return false - } - var e *NotSingularError - return errors.As(err, &e) -} - -// NotLoadedError returns when trying to get a node that was not loaded by the query. -type NotLoadedError struct { - edge string -} - -// Error implements the error interface. -func (e *NotLoadedError) Error() string { - return "ent: " + e.edge + " edge was not loaded" -} - -// IsNotLoaded returns a boolean indicating whether the error is a not loaded error. -func IsNotLoaded(err error) bool { - if err == nil { - return false - } - var e *NotLoadedError - return errors.As(err, &e) -} - -// ConstraintError returns when trying to create/update one or more entities and -// one or more of their constraints failed. For example, violation of edge or -// field uniqueness. -type ConstraintError struct { - msg string - wrap error -} - -// Error implements the error interface. -func (e ConstraintError) Error() string { - return "ent: constraint failed: " + e.msg -} - -// Unwrap implements the errors.Wrapper interface. -func (e *ConstraintError) Unwrap() error { - return e.wrap -} - -// IsConstraintError returns a boolean indicating whether the error is a constraint failure. -func IsConstraintError(err error) bool { - if err == nil { - return false - } - var e *ConstraintError - return errors.As(err, &e) -} - -// selector embedded by the different Select/GroupBy builders. -type selector struct { - label string - flds *[]string - fns []AggregateFunc - scan func(context.Context, any) error -} - -// ScanX is like Scan, but panics if an error occurs. -func (s *selector) ScanX(ctx context.Context, v any) { - if err := s.scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from a selector. It is only allowed when selecting one field. -func (s *selector) Strings(ctx context.Context) ([]string, error) { - if len(*s.flds) > 1 { - return nil, errors.New("ent: Strings is not achievable when selecting more than 1 field") - } - var v []string - if err := s.scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (s *selector) StringsX(ctx context.Context) []string { - v, err := s.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from a selector. It is only allowed when selecting one field. -func (s *selector) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = s.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{s.label} - default: - err = fmt.Errorf("ent: Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (s *selector) StringX(ctx context.Context) string { - v, err := s.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from a selector. It is only allowed when selecting one field. -func (s *selector) Ints(ctx context.Context) ([]int, error) { - if len(*s.flds) > 1 { - return nil, errors.New("ent: Ints is not achievable when selecting more than 1 field") - } - var v []int - if err := s.scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (s *selector) IntsX(ctx context.Context) []int { - v, err := s.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from a selector. It is only allowed when selecting one field. -func (s *selector) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = s.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{s.label} - default: - err = fmt.Errorf("ent: Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (s *selector) IntX(ctx context.Context) int { - v, err := s.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. -func (s *selector) Float64s(ctx context.Context) ([]float64, error) { - if len(*s.flds) > 1 { - return nil, errors.New("ent: Float64s is not achievable when selecting more than 1 field") - } - var v []float64 - if err := s.scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (s *selector) Float64sX(ctx context.Context) []float64 { - v, err := s.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. -func (s *selector) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = s.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{s.label} - default: - err = fmt.Errorf("ent: Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (s *selector) Float64X(ctx context.Context) float64 { - v, err := s.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from a selector. It is only allowed when selecting one field. -func (s *selector) Bools(ctx context.Context) ([]bool, error) { - if len(*s.flds) > 1 { - return nil, errors.New("ent: Bools is not achievable when selecting more than 1 field") - } - var v []bool - if err := s.scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (s *selector) BoolsX(ctx context.Context) []bool { - v, err := s.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from a selector. It is only allowed when selecting one field. -func (s *selector) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = s.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{s.label} - default: - err = fmt.Errorf("ent: Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (s *selector) BoolX(ctx context.Context) bool { - v, err := s.Bool(ctx) - if err != nil { - panic(err) - } - return v -} - -// withHooks invokes the builder operation with the given hooks, if any. -func withHooks[V Value, M any, PM interface { - *M - Mutation -}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) { - if len(hooks) == 0 { - return exec(ctx) - } - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutationT, ok := any(m).(PM) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - // Set the mutation to the builder. - *mutation = *mutationT - return exec(ctx) - }) - for i := len(hooks) - 1; i >= 0; i-- { - if hooks[i] == nil { - return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") - } - mut = hooks[i](mut) - } - v, err := mut.Mutate(ctx, mutation) - if err != nil { - return value, err - } - nv, ok := v.(V) - if !ok { - return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation) - } - return nv, nil -} - -// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist. -func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context { - if ent.QueryFromContext(ctx) == nil { - qc.Op = op - ctx = ent.NewQueryContext(ctx, qc) - } - return ctx -} - -func querierAll[V Value, Q interface { - sqlAll(context.Context, ...queryHook) (V, error) -}]() Querier { - return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { - query, ok := q.(Q) - if !ok { - return nil, fmt.Errorf("unexpected query type %T", q) - } - return query.sqlAll(ctx) - }) -} - -func querierCount[Q interface { - sqlCount(context.Context) (int, error) -}]() Querier { - return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { - query, ok := q.(Q) - if !ok { - return nil, fmt.Errorf("unexpected query type %T", q) - } - return query.sqlCount(ctx) - }) -} - -func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) { - for i := len(inters) - 1; i >= 0; i-- { - qr = inters[i].Intercept(qr) - } - rv, err := qr.Query(ctx, q) - if err != nil { - return v, err - } - vt, ok := rv.(V) - if !ok { - return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v) - } - return vt, nil -} - -func scanWithInterceptors[Q1 ent.Query, Q2 interface { - sqlScan(context.Context, Q1, any) error -}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error { - rv := reflect.ValueOf(v) - var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) { - query, ok := q.(Q1) - if !ok { - return nil, fmt.Errorf("unexpected query type %T", q) - } - if err := selectOrGroup.sqlScan(ctx, query, v); err != nil { - return nil, err - } - if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() { - return rv.Elem().Interface(), nil - } - return v, nil - }) - for i := len(inters) - 1; i >= 0; i-- { - qr = inters[i].Intercept(qr) - } - vv, err := qr.Query(ctx, rootQuery) - if err != nil { - return err - } - switch rv2 := reflect.ValueOf(vv); { - case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer: - case rv.Type() == rv2.Type(): - rv.Elem().Set(rv2.Elem()) - case rv.Elem().Type() == rv2.Type(): - rv.Elem().Set(rv2) - } - return nil -} - -// queryHook describes an internal hook for the different sqlAll methods. -type queryHook func(context.Context, *sqlgraph.QuerySpec) diff --git a/ent/enttest/enttest.go b/ent/enttest/enttest.go deleted file mode 100644 index 1b0d49b..0000000 --- a/ent/enttest/enttest.go +++ /dev/null @@ -1,84 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package enttest - -import ( - "context" - - "git.dcentral.systems/toolz/goplt/ent" - // required by schema hooks. - _ "git.dcentral.systems/toolz/goplt/ent/runtime" - - "entgo.io/ent/dialect/sql/schema" - "git.dcentral.systems/toolz/goplt/ent/migrate" -) - -type ( - // TestingT is the interface that is shared between - // testing.T and testing.B and used by enttest. - TestingT interface { - FailNow() - Error(...any) - } - - // Option configures client creation. - Option func(*options) - - options struct { - opts []ent.Option - migrateOpts []schema.MigrateOption - } -) - -// WithOptions forwards options to client creation. -func WithOptions(opts ...ent.Option) Option { - return func(o *options) { - o.opts = append(o.opts, opts...) - } -} - -// WithMigrateOptions forwards options to auto migration. -func WithMigrateOptions(opts ...schema.MigrateOption) Option { - return func(o *options) { - o.migrateOpts = append(o.migrateOpts, opts...) - } -} - -func newOptions(opts []Option) *options { - o := &options{} - for _, opt := range opts { - opt(o) - } - return o -} - -// Open calls ent.Open and auto-run migration. -func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *ent.Client { - o := newOptions(opts) - c, err := ent.Open(driverName, dataSourceName, o.opts...) - if err != nil { - t.Error(err) - t.FailNow() - } - migrateSchema(t, c, o) - return c -} - -// NewClient calls ent.NewClient and auto-run migration. -func NewClient(t TestingT, opts ...Option) *ent.Client { - o := newOptions(opts) - c := ent.NewClient(o.opts...) - migrateSchema(t, c, o) - return c -} -func migrateSchema(t TestingT, c *ent.Client, o *options) { - tables, err := schema.CopyTables(migrate.Tables) - if err != nil { - t.Error(err) - t.FailNow() - } - if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil { - t.Error(err) - t.FailNow() - } -} diff --git a/ent/generate.go b/ent/generate.go deleted file mode 100644 index 2542fa9..0000000 --- a/ent/generate.go +++ /dev/null @@ -1,4 +0,0 @@ -// Package ent provides code generation for Ent schema definitions. -package ent - -//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate ./schema diff --git a/ent/hook/hook.go b/ent/hook/hook.go deleted file mode 100644 index 872e0ee..0000000 --- a/ent/hook/hook.go +++ /dev/null @@ -1,235 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package hook - -import ( - "context" - "fmt" - - "git.dcentral.systems/toolz/goplt/ent" -) - -// The AuditLogFunc type is an adapter to allow the use of ordinary -// function as AuditLog mutator. -type AuditLogFunc func(context.Context, *ent.AuditLogMutation) (ent.Value, error) - -// Mutate calls f(ctx, m). -func (f AuditLogFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { - if mv, ok := m.(*ent.AuditLogMutation); ok { - return f(ctx, mv) - } - return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.AuditLogMutation", m) -} - -// The PermissionFunc type is an adapter to allow the use of ordinary -// function as Permission mutator. -type PermissionFunc func(context.Context, *ent.PermissionMutation) (ent.Value, error) - -// Mutate calls f(ctx, m). -func (f PermissionFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { - if mv, ok := m.(*ent.PermissionMutation); ok { - return f(ctx, mv) - } - return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.PermissionMutation", m) -} - -// The RoleFunc type is an adapter to allow the use of ordinary -// function as Role mutator. -type RoleFunc func(context.Context, *ent.RoleMutation) (ent.Value, error) - -// Mutate calls f(ctx, m). -func (f RoleFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { - if mv, ok := m.(*ent.RoleMutation); ok { - return f(ctx, mv) - } - return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.RoleMutation", m) -} - -// The UserFunc type is an adapter to allow the use of ordinary -// function as User mutator. -type UserFunc func(context.Context, *ent.UserMutation) (ent.Value, error) - -// Mutate calls f(ctx, m). -func (f UserFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { - if mv, ok := m.(*ent.UserMutation); ok { - return f(ctx, mv) - } - return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserMutation", m) -} - -// Condition is a hook condition function. -type Condition func(context.Context, ent.Mutation) bool - -// And groups conditions with the AND operator. -func And(first, second Condition, rest ...Condition) Condition { - return func(ctx context.Context, m ent.Mutation) bool { - if !first(ctx, m) || !second(ctx, m) { - return false - } - for _, cond := range rest { - if !cond(ctx, m) { - return false - } - } - return true - } -} - -// Or groups conditions with the OR operator. -func Or(first, second Condition, rest ...Condition) Condition { - return func(ctx context.Context, m ent.Mutation) bool { - if first(ctx, m) || second(ctx, m) { - return true - } - for _, cond := range rest { - if cond(ctx, m) { - return true - } - } - return false - } -} - -// Not negates a given condition. -func Not(cond Condition) Condition { - return func(ctx context.Context, m ent.Mutation) bool { - return !cond(ctx, m) - } -} - -// HasOp is a condition testing mutation operation. -func HasOp(op ent.Op) Condition { - return func(_ context.Context, m ent.Mutation) bool { - return m.Op().Is(op) - } -} - -// HasAddedFields is a condition validating `.AddedField` on fields. -func HasAddedFields(field string, fields ...string) Condition { - return func(_ context.Context, m ent.Mutation) bool { - if _, exists := m.AddedField(field); !exists { - return false - } - for _, field := range fields { - if _, exists := m.AddedField(field); !exists { - return false - } - } - return true - } -} - -// HasClearedFields is a condition validating `.FieldCleared` on fields. -func HasClearedFields(field string, fields ...string) Condition { - return func(_ context.Context, m ent.Mutation) bool { - if exists := m.FieldCleared(field); !exists { - return false - } - for _, field := range fields { - if exists := m.FieldCleared(field); !exists { - return false - } - } - return true - } -} - -// HasFields is a condition validating `.Field` on fields. -func HasFields(field string, fields ...string) Condition { - return func(_ context.Context, m ent.Mutation) bool { - if _, exists := m.Field(field); !exists { - return false - } - for _, field := range fields { - if _, exists := m.Field(field); !exists { - return false - } - } - return true - } -} - -// If executes the given hook under condition. -// -// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...))) -func If(hk ent.Hook, cond Condition) ent.Hook { - return func(next ent.Mutator) ent.Mutator { - return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) { - if cond(ctx, m) { - return hk(next).Mutate(ctx, m) - } - return next.Mutate(ctx, m) - }) - } -} - -// On executes the given hook only for the given operation. -// -// hook.On(Log, ent.Delete|ent.Create) -func On(hk ent.Hook, op ent.Op) ent.Hook { - return If(hk, HasOp(op)) -} - -// Unless skips the given hook only for the given operation. -// -// hook.Unless(Log, ent.Update|ent.UpdateOne) -func Unless(hk ent.Hook, op ent.Op) ent.Hook { - return If(hk, Not(HasOp(op))) -} - -// FixedError is a hook returning a fixed error. -func FixedError(err error) ent.Hook { - return func(ent.Mutator) ent.Mutator { - return ent.MutateFunc(func(context.Context, ent.Mutation) (ent.Value, error) { - return nil, err - }) - } -} - -// Reject returns a hook that rejects all operations that match op. -// -// func (T) Hooks() []ent.Hook { -// return []ent.Hook{ -// Reject(ent.Delete|ent.Update), -// } -// } -func Reject(op ent.Op) ent.Hook { - hk := FixedError(fmt.Errorf("%s operation is not allowed", op)) - return On(hk, op) -} - -// Chain acts as a list of hooks and is effectively immutable. -// Once created, it will always hold the same set of hooks in the same order. -type Chain struct { - hooks []ent.Hook -} - -// NewChain creates a new chain of hooks. -func NewChain(hooks ...ent.Hook) Chain { - return Chain{append([]ent.Hook(nil), hooks...)} -} - -// Hook chains the list of hooks and returns the final hook. -func (c Chain) Hook() ent.Hook { - return func(mutator ent.Mutator) ent.Mutator { - for i := len(c.hooks) - 1; i >= 0; i-- { - mutator = c.hooks[i](mutator) - } - return mutator - } -} - -// Append extends a chain, adding the specified hook -// as the last ones in the mutation flow. -func (c Chain) Append(hooks ...ent.Hook) Chain { - newHooks := make([]ent.Hook, 0, len(c.hooks)+len(hooks)) - newHooks = append(newHooks, c.hooks...) - newHooks = append(newHooks, hooks...) - return Chain{newHooks} -} - -// Extend extends a chain, adding the specified chain -// as the last ones in the mutation flow. -func (c Chain) Extend(chain Chain) Chain { - return c.Append(chain.hooks...) -} diff --git a/ent/migrate/migrate.go b/ent/migrate/migrate.go deleted file mode 100644 index 1956a6b..0000000 --- a/ent/migrate/migrate.go +++ /dev/null @@ -1,64 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package migrate - -import ( - "context" - "fmt" - "io" - - "entgo.io/ent/dialect" - "entgo.io/ent/dialect/sql/schema" -) - -var ( - // WithGlobalUniqueID sets the universal ids options to the migration. - // If this option is enabled, ent migration will allocate a 1<<32 range - // for the ids of each entity (table). - // Note that this option cannot be applied on tables that already exist. - WithGlobalUniqueID = schema.WithGlobalUniqueID - // WithDropColumn sets the drop column option to the migration. - // If this option is enabled, ent migration will drop old columns - // that were used for both fields and edges. This defaults to false. - WithDropColumn = schema.WithDropColumn - // WithDropIndex sets the drop index option to the migration. - // If this option is enabled, ent migration will drop old indexes - // that were defined in the schema. This defaults to false. - // Note that unique constraints are defined using `UNIQUE INDEX`, - // and therefore, it's recommended to enable this option to get more - // flexibility in the schema changes. - WithDropIndex = schema.WithDropIndex - // WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true. - WithForeignKeys = schema.WithForeignKeys -) - -// Schema is the API for creating, migrating and dropping a schema. -type Schema struct { - drv dialect.Driver -} - -// NewSchema creates a new schema client. -func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} } - -// Create creates all schema resources. -func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error { - return Create(ctx, s, Tables, opts...) -} - -// Create creates all table resources using the given schema driver. -func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error { - migrate, err := schema.NewMigrate(s.drv, opts...) - if err != nil { - return fmt.Errorf("ent/migrate: %w", err) - } - return migrate.Create(ctx, tables...) -} - -// WriteTo writes the schema changes to w instead of running them against the database. -// -// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil { -// log.Fatal(err) -// } -func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error { - return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...) -} diff --git a/ent/migrate/schema.go b/ent/migrate/schema.go deleted file mode 100644 index cc0abe8..0000000 --- a/ent/migrate/schema.go +++ /dev/null @@ -1,61 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package migrate - -import ( - "entgo.io/ent/dialect/sql/schema" - "entgo.io/ent/schema/field" -) - -var ( - // AuditLogsColumns holds the columns for the "audit_logs" table. - AuditLogsColumns = []*schema.Column{ - {Name: "id", Type: field.TypeInt, Increment: true}, - } - // AuditLogsTable holds the schema information for the "audit_logs" table. - AuditLogsTable = &schema.Table{ - Name: "audit_logs", - Columns: AuditLogsColumns, - PrimaryKey: []*schema.Column{AuditLogsColumns[0]}, - } - // PermissionsColumns holds the columns for the "permissions" table. - PermissionsColumns = []*schema.Column{ - {Name: "id", Type: field.TypeInt, Increment: true}, - } - // PermissionsTable holds the schema information for the "permissions" table. - PermissionsTable = &schema.Table{ - Name: "permissions", - Columns: PermissionsColumns, - PrimaryKey: []*schema.Column{PermissionsColumns[0]}, - } - // RolesColumns holds the columns for the "roles" table. - RolesColumns = []*schema.Column{ - {Name: "id", Type: field.TypeInt, Increment: true}, - } - // RolesTable holds the schema information for the "roles" table. - RolesTable = &schema.Table{ - Name: "roles", - Columns: RolesColumns, - PrimaryKey: []*schema.Column{RolesColumns[0]}, - } - // UsersColumns holds the columns for the "users" table. - UsersColumns = []*schema.Column{ - {Name: "id", Type: field.TypeInt, Increment: true}, - } - // UsersTable holds the schema information for the "users" table. - UsersTable = &schema.Table{ - Name: "users", - Columns: UsersColumns, - PrimaryKey: []*schema.Column{UsersColumns[0]}, - } - // Tables holds all the tables in the schema. - Tables = []*schema.Table{ - AuditLogsTable, - PermissionsTable, - RolesTable, - UsersTable, - } -) - -func init() { -} diff --git a/ent/mutation.go b/ent/mutation.go deleted file mode 100644 index 7295954..0000000 --- a/ent/mutation.go +++ /dev/null @@ -1,1085 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "errors" - "fmt" - "sync" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "git.dcentral.systems/toolz/goplt/ent/predicate" -) - -const ( - // Operation types. - OpCreate = ent.OpCreate - OpDelete = ent.OpDelete - OpDeleteOne = ent.OpDeleteOne - OpUpdate = ent.OpUpdate - OpUpdateOne = ent.OpUpdateOne - - // Node types. - TypeAuditLog = "AuditLog" - TypePermission = "Permission" - TypeRole = "Role" - TypeUser = "User" -) - -// AuditLogMutation represents an operation that mutates the AuditLog nodes in the graph. -type AuditLogMutation struct { - config - op Op - typ string - id *int - clearedFields map[string]struct{} - done bool - oldValue func(context.Context) (*AuditLog, error) - predicates []predicate.AuditLog -} - -var _ ent.Mutation = (*AuditLogMutation)(nil) - -// auditlogOption allows management of the mutation configuration using functional options. -type auditlogOption func(*AuditLogMutation) - -// newAuditLogMutation creates new mutation for the AuditLog entity. -func newAuditLogMutation(c config, op Op, opts ...auditlogOption) *AuditLogMutation { - m := &AuditLogMutation{ - config: c, - op: op, - typ: TypeAuditLog, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m -} - -// withAuditLogID sets the ID field of the mutation. -func withAuditLogID(id int) auditlogOption { - return func(m *AuditLogMutation) { - var ( - err error - once sync.Once - value *AuditLog - ) - m.oldValue = func(ctx context.Context) (*AuditLog, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().AuditLog.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } -} - -// withAuditLog sets the old AuditLog of the mutation. -func withAuditLog(node *AuditLog) auditlogOption { - return func(m *AuditLogMutation) { - m.oldValue = func(context.Context) (*AuditLog, error) { - return node, nil - } - m.id = &node.ID - } -} - -// Client returns a new `ent.Client` from the mutation. If the mutation was -// executed in a transaction (ent.Tx), a transactional client is returned. -func (m AuditLogMutation) Client() *Client { - client := &Client{config: m.config} - client.init() - return client -} - -// Tx returns an `ent.Tx` for mutations that were executed in transactions; -// it returns an error otherwise. -func (m AuditLogMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("ent: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil -} - -// ID returns the ID value in the mutation. Note that the ID is only available -// if it was provided to the builder or after it was returned from the database. -func (m *AuditLogMutation) ID() (id int, exists bool) { - if m.id == nil { - return - } - return *m.id, true -} - -// IDs queries the database and returns the entity ids that match the mutation's predicate. -// That means, if the mutation is applied within a transaction with an isolation level such -// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated -// or updated by the mutation. -func (m *AuditLogMutation) IDs(ctx context.Context) ([]int, error) { - switch { - case m.op.Is(OpUpdateOne | OpDeleteOne): - id, exists := m.ID() - if exists { - return []int{id}, nil - } - fallthrough - case m.op.Is(OpUpdate | OpDelete): - return m.Client().AuditLog.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) - } -} - -// Where appends a list predicates to the AuditLogMutation builder. -func (m *AuditLogMutation) Where(ps ...predicate.AuditLog) { - m.predicates = append(m.predicates, ps...) -} - -// WhereP appends storage-level predicates to the AuditLogMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *AuditLogMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.AuditLog, len(ps)) - for i := range ps { - p[i] = ps[i] - } - m.Where(p...) -} - -// Op returns the operation name. -func (m *AuditLogMutation) Op() Op { - return m.op -} - -// SetOp allows setting the mutation operation. -func (m *AuditLogMutation) SetOp(op Op) { - m.op = op -} - -// Type returns the node type of this mutation (AuditLog). -func (m *AuditLogMutation) Type() string { - return m.typ -} - -// Fields returns all fields that were changed during this mutation. Note that in -// order to get all numeric fields that were incremented/decremented, call -// AddedFields(). -func (m *AuditLogMutation) Fields() []string { - fields := make([]string, 0, 0) - return fields -} - -// Field returns the value of a field with the given name. The second boolean -// return value indicates that this field was not set, or was not defined in the -// schema. -func (m *AuditLogMutation) Field(name string) (ent.Value, bool) { - return nil, false -} - -// OldField returns the old value of the field from the database. An error is -// returned if the mutation operation is not UpdateOne, or the query to the -// database failed. -func (m *AuditLogMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - return nil, fmt.Errorf("unknown AuditLog field %s", name) -} - -// SetField sets the value of a field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *AuditLogMutation) SetField(name string, value ent.Value) error { - switch name { - } - return fmt.Errorf("unknown AuditLog field %s", name) -} - -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *AuditLogMutation) AddedFields() []string { - return nil -} - -// AddedField returns the numeric value that was incremented/decremented on a field -// with the given name. The second boolean return value indicates that this field -// was not set, or was not defined in the schema. -func (m *AuditLogMutation) AddedField(name string) (ent.Value, bool) { - return nil, false -} - -// AddField adds the value to the field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *AuditLogMutation) AddField(name string, value ent.Value) error { - return fmt.Errorf("unknown AuditLog numeric field %s", name) -} - -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *AuditLogMutation) ClearedFields() []string { - return nil -} - -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *AuditLogMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok -} - -// ClearField clears the value of the field with the given name. It returns an -// error if the field is not defined in the schema. -func (m *AuditLogMutation) ClearField(name string) error { - return fmt.Errorf("unknown AuditLog nullable field %s", name) -} - -// ResetField resets all changes in the mutation for the field with the given name. -// It returns an error if the field is not defined in the schema. -func (m *AuditLogMutation) ResetField(name string) error { - return fmt.Errorf("unknown AuditLog field %s", name) -} - -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *AuditLogMutation) AddedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *AuditLogMutation) AddedIDs(name string) []ent.Value { - return nil -} - -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *AuditLogMutation) RemovedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *AuditLogMutation) RemovedIDs(name string) []ent.Value { - return nil -} - -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *AuditLogMutation) ClearedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *AuditLogMutation) EdgeCleared(name string) bool { - return false -} - -// ClearEdge clears the value of the edge with the given name. It returns an error -// if that edge is not defined in the schema. -func (m *AuditLogMutation) ClearEdge(name string) error { - return fmt.Errorf("unknown AuditLog unique edge %s", name) -} - -// ResetEdge resets all changes to the edge with the given name in this mutation. -// It returns an error if the edge is not defined in the schema. -func (m *AuditLogMutation) ResetEdge(name string) error { - return fmt.Errorf("unknown AuditLog edge %s", name) -} - -// PermissionMutation represents an operation that mutates the Permission nodes in the graph. -type PermissionMutation struct { - config - op Op - typ string - id *int - clearedFields map[string]struct{} - done bool - oldValue func(context.Context) (*Permission, error) - predicates []predicate.Permission -} - -var _ ent.Mutation = (*PermissionMutation)(nil) - -// permissionOption allows management of the mutation configuration using functional options. -type permissionOption func(*PermissionMutation) - -// newPermissionMutation creates new mutation for the Permission entity. -func newPermissionMutation(c config, op Op, opts ...permissionOption) *PermissionMutation { - m := &PermissionMutation{ - config: c, - op: op, - typ: TypePermission, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m -} - -// withPermissionID sets the ID field of the mutation. -func withPermissionID(id int) permissionOption { - return func(m *PermissionMutation) { - var ( - err error - once sync.Once - value *Permission - ) - m.oldValue = func(ctx context.Context) (*Permission, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().Permission.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } -} - -// withPermission sets the old Permission of the mutation. -func withPermission(node *Permission) permissionOption { - return func(m *PermissionMutation) { - m.oldValue = func(context.Context) (*Permission, error) { - return node, nil - } - m.id = &node.ID - } -} - -// Client returns a new `ent.Client` from the mutation. If the mutation was -// executed in a transaction (ent.Tx), a transactional client is returned. -func (m PermissionMutation) Client() *Client { - client := &Client{config: m.config} - client.init() - return client -} - -// Tx returns an `ent.Tx` for mutations that were executed in transactions; -// it returns an error otherwise. -func (m PermissionMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("ent: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil -} - -// ID returns the ID value in the mutation. Note that the ID is only available -// if it was provided to the builder or after it was returned from the database. -func (m *PermissionMutation) ID() (id int, exists bool) { - if m.id == nil { - return - } - return *m.id, true -} - -// IDs queries the database and returns the entity ids that match the mutation's predicate. -// That means, if the mutation is applied within a transaction with an isolation level such -// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated -// or updated by the mutation. -func (m *PermissionMutation) IDs(ctx context.Context) ([]int, error) { - switch { - case m.op.Is(OpUpdateOne | OpDeleteOne): - id, exists := m.ID() - if exists { - return []int{id}, nil - } - fallthrough - case m.op.Is(OpUpdate | OpDelete): - return m.Client().Permission.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) - } -} - -// Where appends a list predicates to the PermissionMutation builder. -func (m *PermissionMutation) Where(ps ...predicate.Permission) { - m.predicates = append(m.predicates, ps...) -} - -// WhereP appends storage-level predicates to the PermissionMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *PermissionMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.Permission, len(ps)) - for i := range ps { - p[i] = ps[i] - } - m.Where(p...) -} - -// Op returns the operation name. -func (m *PermissionMutation) Op() Op { - return m.op -} - -// SetOp allows setting the mutation operation. -func (m *PermissionMutation) SetOp(op Op) { - m.op = op -} - -// Type returns the node type of this mutation (Permission). -func (m *PermissionMutation) Type() string { - return m.typ -} - -// Fields returns all fields that were changed during this mutation. Note that in -// order to get all numeric fields that were incremented/decremented, call -// AddedFields(). -func (m *PermissionMutation) Fields() []string { - fields := make([]string, 0, 0) - return fields -} - -// Field returns the value of a field with the given name. The second boolean -// return value indicates that this field was not set, or was not defined in the -// schema. -func (m *PermissionMutation) Field(name string) (ent.Value, bool) { - return nil, false -} - -// OldField returns the old value of the field from the database. An error is -// returned if the mutation operation is not UpdateOne, or the query to the -// database failed. -func (m *PermissionMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - return nil, fmt.Errorf("unknown Permission field %s", name) -} - -// SetField sets the value of a field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *PermissionMutation) SetField(name string, value ent.Value) error { - switch name { - } - return fmt.Errorf("unknown Permission field %s", name) -} - -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *PermissionMutation) AddedFields() []string { - return nil -} - -// AddedField returns the numeric value that was incremented/decremented on a field -// with the given name. The second boolean return value indicates that this field -// was not set, or was not defined in the schema. -func (m *PermissionMutation) AddedField(name string) (ent.Value, bool) { - return nil, false -} - -// AddField adds the value to the field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *PermissionMutation) AddField(name string, value ent.Value) error { - return fmt.Errorf("unknown Permission numeric field %s", name) -} - -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *PermissionMutation) ClearedFields() []string { - return nil -} - -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *PermissionMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok -} - -// ClearField clears the value of the field with the given name. It returns an -// error if the field is not defined in the schema. -func (m *PermissionMutation) ClearField(name string) error { - return fmt.Errorf("unknown Permission nullable field %s", name) -} - -// ResetField resets all changes in the mutation for the field with the given name. -// It returns an error if the field is not defined in the schema. -func (m *PermissionMutation) ResetField(name string) error { - return fmt.Errorf("unknown Permission field %s", name) -} - -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *PermissionMutation) AddedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *PermissionMutation) AddedIDs(name string) []ent.Value { - return nil -} - -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *PermissionMutation) RemovedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *PermissionMutation) RemovedIDs(name string) []ent.Value { - return nil -} - -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *PermissionMutation) ClearedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *PermissionMutation) EdgeCleared(name string) bool { - return false -} - -// ClearEdge clears the value of the edge with the given name. It returns an error -// if that edge is not defined in the schema. -func (m *PermissionMutation) ClearEdge(name string) error { - return fmt.Errorf("unknown Permission unique edge %s", name) -} - -// ResetEdge resets all changes to the edge with the given name in this mutation. -// It returns an error if the edge is not defined in the schema. -func (m *PermissionMutation) ResetEdge(name string) error { - return fmt.Errorf("unknown Permission edge %s", name) -} - -// RoleMutation represents an operation that mutates the Role nodes in the graph. -type RoleMutation struct { - config - op Op - typ string - id *int - clearedFields map[string]struct{} - done bool - oldValue func(context.Context) (*Role, error) - predicates []predicate.Role -} - -var _ ent.Mutation = (*RoleMutation)(nil) - -// roleOption allows management of the mutation configuration using functional options. -type roleOption func(*RoleMutation) - -// newRoleMutation creates new mutation for the Role entity. -func newRoleMutation(c config, op Op, opts ...roleOption) *RoleMutation { - m := &RoleMutation{ - config: c, - op: op, - typ: TypeRole, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m -} - -// withRoleID sets the ID field of the mutation. -func withRoleID(id int) roleOption { - return func(m *RoleMutation) { - var ( - err error - once sync.Once - value *Role - ) - m.oldValue = func(ctx context.Context) (*Role, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().Role.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } -} - -// withRole sets the old Role of the mutation. -func withRole(node *Role) roleOption { - return func(m *RoleMutation) { - m.oldValue = func(context.Context) (*Role, error) { - return node, nil - } - m.id = &node.ID - } -} - -// Client returns a new `ent.Client` from the mutation. If the mutation was -// executed in a transaction (ent.Tx), a transactional client is returned. -func (m RoleMutation) Client() *Client { - client := &Client{config: m.config} - client.init() - return client -} - -// Tx returns an `ent.Tx` for mutations that were executed in transactions; -// it returns an error otherwise. -func (m RoleMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("ent: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil -} - -// ID returns the ID value in the mutation. Note that the ID is only available -// if it was provided to the builder or after it was returned from the database. -func (m *RoleMutation) ID() (id int, exists bool) { - if m.id == nil { - return - } - return *m.id, true -} - -// IDs queries the database and returns the entity ids that match the mutation's predicate. -// That means, if the mutation is applied within a transaction with an isolation level such -// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated -// or updated by the mutation. -func (m *RoleMutation) IDs(ctx context.Context) ([]int, error) { - switch { - case m.op.Is(OpUpdateOne | OpDeleteOne): - id, exists := m.ID() - if exists { - return []int{id}, nil - } - fallthrough - case m.op.Is(OpUpdate | OpDelete): - return m.Client().Role.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) - } -} - -// Where appends a list predicates to the RoleMutation builder. -func (m *RoleMutation) Where(ps ...predicate.Role) { - m.predicates = append(m.predicates, ps...) -} - -// WhereP appends storage-level predicates to the RoleMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *RoleMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.Role, len(ps)) - for i := range ps { - p[i] = ps[i] - } - m.Where(p...) -} - -// Op returns the operation name. -func (m *RoleMutation) Op() Op { - return m.op -} - -// SetOp allows setting the mutation operation. -func (m *RoleMutation) SetOp(op Op) { - m.op = op -} - -// Type returns the node type of this mutation (Role). -func (m *RoleMutation) Type() string { - return m.typ -} - -// Fields returns all fields that were changed during this mutation. Note that in -// order to get all numeric fields that were incremented/decremented, call -// AddedFields(). -func (m *RoleMutation) Fields() []string { - fields := make([]string, 0, 0) - return fields -} - -// Field returns the value of a field with the given name. The second boolean -// return value indicates that this field was not set, or was not defined in the -// schema. -func (m *RoleMutation) Field(name string) (ent.Value, bool) { - return nil, false -} - -// OldField returns the old value of the field from the database. An error is -// returned if the mutation operation is not UpdateOne, or the query to the -// database failed. -func (m *RoleMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - return nil, fmt.Errorf("unknown Role field %s", name) -} - -// SetField sets the value of a field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *RoleMutation) SetField(name string, value ent.Value) error { - switch name { - } - return fmt.Errorf("unknown Role field %s", name) -} - -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *RoleMutation) AddedFields() []string { - return nil -} - -// AddedField returns the numeric value that was incremented/decremented on a field -// with the given name. The second boolean return value indicates that this field -// was not set, or was not defined in the schema. -func (m *RoleMutation) AddedField(name string) (ent.Value, bool) { - return nil, false -} - -// AddField adds the value to the field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *RoleMutation) AddField(name string, value ent.Value) error { - return fmt.Errorf("unknown Role numeric field %s", name) -} - -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *RoleMutation) ClearedFields() []string { - return nil -} - -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *RoleMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok -} - -// ClearField clears the value of the field with the given name. It returns an -// error if the field is not defined in the schema. -func (m *RoleMutation) ClearField(name string) error { - return fmt.Errorf("unknown Role nullable field %s", name) -} - -// ResetField resets all changes in the mutation for the field with the given name. -// It returns an error if the field is not defined in the schema. -func (m *RoleMutation) ResetField(name string) error { - return fmt.Errorf("unknown Role field %s", name) -} - -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *RoleMutation) AddedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *RoleMutation) AddedIDs(name string) []ent.Value { - return nil -} - -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *RoleMutation) RemovedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *RoleMutation) RemovedIDs(name string) []ent.Value { - return nil -} - -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *RoleMutation) ClearedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *RoleMutation) EdgeCleared(name string) bool { - return false -} - -// ClearEdge clears the value of the edge with the given name. It returns an error -// if that edge is not defined in the schema. -func (m *RoleMutation) ClearEdge(name string) error { - return fmt.Errorf("unknown Role unique edge %s", name) -} - -// ResetEdge resets all changes to the edge with the given name in this mutation. -// It returns an error if the edge is not defined in the schema. -func (m *RoleMutation) ResetEdge(name string) error { - return fmt.Errorf("unknown Role edge %s", name) -} - -// UserMutation represents an operation that mutates the User nodes in the graph. -type UserMutation struct { - config - op Op - typ string - id *int - clearedFields map[string]struct{} - done bool - oldValue func(context.Context) (*User, error) - predicates []predicate.User -} - -var _ ent.Mutation = (*UserMutation)(nil) - -// userOption allows management of the mutation configuration using functional options. -type userOption func(*UserMutation) - -// newUserMutation creates new mutation for the User entity. -func newUserMutation(c config, op Op, opts ...userOption) *UserMutation { - m := &UserMutation{ - config: c, - op: op, - typ: TypeUser, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m -} - -// withUserID sets the ID field of the mutation. -func withUserID(id int) userOption { - return func(m *UserMutation) { - var ( - err error - once sync.Once - value *User - ) - m.oldValue = func(ctx context.Context) (*User, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().User.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } -} - -// withUser sets the old User of the mutation. -func withUser(node *User) userOption { - return func(m *UserMutation) { - m.oldValue = func(context.Context) (*User, error) { - return node, nil - } - m.id = &node.ID - } -} - -// Client returns a new `ent.Client` from the mutation. If the mutation was -// executed in a transaction (ent.Tx), a transactional client is returned. -func (m UserMutation) Client() *Client { - client := &Client{config: m.config} - client.init() - return client -} - -// Tx returns an `ent.Tx` for mutations that were executed in transactions; -// it returns an error otherwise. -func (m UserMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("ent: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil -} - -// ID returns the ID value in the mutation. Note that the ID is only available -// if it was provided to the builder or after it was returned from the database. -func (m *UserMutation) ID() (id int, exists bool) { - if m.id == nil { - return - } - return *m.id, true -} - -// IDs queries the database and returns the entity ids that match the mutation's predicate. -// That means, if the mutation is applied within a transaction with an isolation level such -// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated -// or updated by the mutation. -func (m *UserMutation) IDs(ctx context.Context) ([]int, error) { - switch { - case m.op.Is(OpUpdateOne | OpDeleteOne): - id, exists := m.ID() - if exists { - return []int{id}, nil - } - fallthrough - case m.op.Is(OpUpdate | OpDelete): - return m.Client().User.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) - } -} - -// Where appends a list predicates to the UserMutation builder. -func (m *UserMutation) Where(ps ...predicate.User) { - m.predicates = append(m.predicates, ps...) -} - -// WhereP appends storage-level predicates to the UserMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *UserMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.User, len(ps)) - for i := range ps { - p[i] = ps[i] - } - m.Where(p...) -} - -// Op returns the operation name. -func (m *UserMutation) Op() Op { - return m.op -} - -// SetOp allows setting the mutation operation. -func (m *UserMutation) SetOp(op Op) { - m.op = op -} - -// Type returns the node type of this mutation (User). -func (m *UserMutation) Type() string { - return m.typ -} - -// Fields returns all fields that were changed during this mutation. Note that in -// order to get all numeric fields that were incremented/decremented, call -// AddedFields(). -func (m *UserMutation) Fields() []string { - fields := make([]string, 0, 0) - return fields -} - -// Field returns the value of a field with the given name. The second boolean -// return value indicates that this field was not set, or was not defined in the -// schema. -func (m *UserMutation) Field(name string) (ent.Value, bool) { - return nil, false -} - -// OldField returns the old value of the field from the database. An error is -// returned if the mutation operation is not UpdateOne, or the query to the -// database failed. -func (m *UserMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - return nil, fmt.Errorf("unknown User field %s", name) -} - -// SetField sets the value of a field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *UserMutation) SetField(name string, value ent.Value) error { - switch name { - } - return fmt.Errorf("unknown User field %s", name) -} - -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *UserMutation) AddedFields() []string { - return nil -} - -// AddedField returns the numeric value that was incremented/decremented on a field -// with the given name. The second boolean return value indicates that this field -// was not set, or was not defined in the schema. -func (m *UserMutation) AddedField(name string) (ent.Value, bool) { - return nil, false -} - -// AddField adds the value to the field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *UserMutation) AddField(name string, value ent.Value) error { - return fmt.Errorf("unknown User numeric field %s", name) -} - -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *UserMutation) ClearedFields() []string { - return nil -} - -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *UserMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok -} - -// ClearField clears the value of the field with the given name. It returns an -// error if the field is not defined in the schema. -func (m *UserMutation) ClearField(name string) error { - return fmt.Errorf("unknown User nullable field %s", name) -} - -// ResetField resets all changes in the mutation for the field with the given name. -// It returns an error if the field is not defined in the schema. -func (m *UserMutation) ResetField(name string) error { - return fmt.Errorf("unknown User field %s", name) -} - -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *UserMutation) AddedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *UserMutation) AddedIDs(name string) []ent.Value { - return nil -} - -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *UserMutation) RemovedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *UserMutation) RemovedIDs(name string) []ent.Value { - return nil -} - -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *UserMutation) ClearedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *UserMutation) EdgeCleared(name string) bool { - return false -} - -// ClearEdge clears the value of the edge with the given name. It returns an error -// if that edge is not defined in the schema. -func (m *UserMutation) ClearEdge(name string) error { - return fmt.Errorf("unknown User unique edge %s", name) -} - -// ResetEdge resets all changes to the edge with the given name in this mutation. -// It returns an error if the edge is not defined in the schema. -func (m *UserMutation) ResetEdge(name string) error { - return fmt.Errorf("unknown User edge %s", name) -} diff --git a/ent/permission.go b/ent/permission.go deleted file mode 100644 index 2fbff48..0000000 --- a/ent/permission.go +++ /dev/null @@ -1,91 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "fmt" - "strings" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "git.dcentral.systems/toolz/goplt/ent/permission" -) - -// Permission is the model entity for the Permission schema. -type Permission struct { - config - // ID of the ent. - ID int `json:"id,omitempty"` - selectValues sql.SelectValues -} - -// scanValues returns the types for scanning values from sql.Rows. -func (*Permission) scanValues(columns []string) ([]any, error) { - values := make([]any, len(columns)) - for i := range columns { - switch columns[i] { - case permission.FieldID: - values[i] = new(sql.NullInt64) - default: - values[i] = new(sql.UnknownType) - } - } - return values, nil -} - -// assignValues assigns the values that were returned from sql.Rows (after scanning) -// to the Permission fields. -func (_m *Permission) assignValues(columns []string, values []any) error { - if m, n := len(values), len(columns); m < n { - return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) - } - for i := range columns { - switch columns[i] { - case permission.FieldID: - value, ok := values[i].(*sql.NullInt64) - if !ok { - return fmt.Errorf("unexpected type %T for field id", value) - } - _m.ID = int(value.Int64) - default: - _m.selectValues.Set(columns[i], values[i]) - } - } - return nil -} - -// Value returns the ent.Value that was dynamically selected and assigned to the Permission. -// This includes values selected through modifiers, order, etc. -func (_m *Permission) Value(name string) (ent.Value, error) { - return _m.selectValues.Get(name) -} - -// Update returns a builder for updating this Permission. -// Note that you need to call Permission.Unwrap() before calling this method if this Permission -// was returned from a transaction, and the transaction was committed or rolled back. -func (_m *Permission) Update() *PermissionUpdateOne { - return NewPermissionClient(_m.config).UpdateOne(_m) -} - -// Unwrap unwraps the Permission entity that was returned from a transaction after it was closed, -// so that all future queries will be executed through the driver which created the transaction. -func (_m *Permission) Unwrap() *Permission { - _tx, ok := _m.config.driver.(*txDriver) - if !ok { - panic("ent: Permission is not a transactional entity") - } - _m.config.driver = _tx.drv - return _m -} - -// String implements the fmt.Stringer. -func (_m *Permission) String() string { - var builder strings.Builder - builder.WriteString("Permission(") - builder.WriteString(fmt.Sprintf("id=%v", _m.ID)) - builder.WriteByte(')') - return builder.String() -} - -// Permissions is a parsable slice of Permission. -type Permissions []*Permission diff --git a/ent/permission/permission.go b/ent/permission/permission.go deleted file mode 100644 index 3833b7c..0000000 --- a/ent/permission/permission.go +++ /dev/null @@ -1,39 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package permission - -import ( - "entgo.io/ent/dialect/sql" -) - -const ( - // Label holds the string label denoting the permission type in the database. - Label = "permission" - // FieldID holds the string denoting the id field in the database. - FieldID = "id" - // Table holds the table name of the permission in the database. - Table = "permissions" -) - -// Columns holds all SQL columns for permission fields. -var Columns = []string{ - FieldID, -} - -// ValidColumn reports if the column name is valid (part of the table columns). -func ValidColumn(column string) bool { - for i := range Columns { - if column == Columns[i] { - return true - } - } - return false -} - -// OrderOption defines the ordering options for the Permission queries. -type OrderOption func(*sql.Selector) - -// ByID orders the results by the id field. -func ByID(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldID, opts...).ToFunc() -} diff --git a/ent/permission/where.go b/ent/permission/where.go deleted file mode 100644 index 62b4224..0000000 --- a/ent/permission/where.go +++ /dev/null @@ -1,68 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package permission - -import ( - "entgo.io/ent/dialect/sql" - "git.dcentral.systems/toolz/goplt/ent/predicate" -) - -// ID filters vertices based on their ID field. -func ID(id int) predicate.Permission { - return predicate.Permission(sql.FieldEQ(FieldID, id)) -} - -// IDEQ applies the EQ predicate on the ID field. -func IDEQ(id int) predicate.Permission { - return predicate.Permission(sql.FieldEQ(FieldID, id)) -} - -// IDNEQ applies the NEQ predicate on the ID field. -func IDNEQ(id int) predicate.Permission { - return predicate.Permission(sql.FieldNEQ(FieldID, id)) -} - -// IDIn applies the In predicate on the ID field. -func IDIn(ids ...int) predicate.Permission { - return predicate.Permission(sql.FieldIn(FieldID, ids...)) -} - -// IDNotIn applies the NotIn predicate on the ID field. -func IDNotIn(ids ...int) predicate.Permission { - return predicate.Permission(sql.FieldNotIn(FieldID, ids...)) -} - -// IDGT applies the GT predicate on the ID field. -func IDGT(id int) predicate.Permission { - return predicate.Permission(sql.FieldGT(FieldID, id)) -} - -// IDGTE applies the GTE predicate on the ID field. -func IDGTE(id int) predicate.Permission { - return predicate.Permission(sql.FieldGTE(FieldID, id)) -} - -// IDLT applies the LT predicate on the ID field. -func IDLT(id int) predicate.Permission { - return predicate.Permission(sql.FieldLT(FieldID, id)) -} - -// IDLTE applies the LTE predicate on the ID field. -func IDLTE(id int) predicate.Permission { - return predicate.Permission(sql.FieldLTE(FieldID, id)) -} - -// And groups predicates with the AND operator between them. -func And(predicates ...predicate.Permission) predicate.Permission { - return predicate.Permission(sql.AndPredicates(predicates...)) -} - -// Or groups predicates with the OR operator between them. -func Or(predicates ...predicate.Permission) predicate.Permission { - return predicate.Permission(sql.OrPredicates(predicates...)) -} - -// Not applies the not operator on the given predicate. -func Not(p predicate.Permission) predicate.Permission { - return predicate.Permission(sql.NotPredicates(p)) -} diff --git a/ent/permission_create.go b/ent/permission_create.go deleted file mode 100644 index 59da5ad..0000000 --- a/ent/permission_create.go +++ /dev/null @@ -1,169 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "fmt" - - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/ent/permission" -) - -// PermissionCreate is the builder for creating a Permission entity. -type PermissionCreate struct { - config - mutation *PermissionMutation - hooks []Hook -} - -// Mutation returns the PermissionMutation object of the builder. -func (_c *PermissionCreate) Mutation() *PermissionMutation { - return _c.mutation -} - -// Save creates the Permission in the database. -func (_c *PermissionCreate) Save(ctx context.Context) (*Permission, error) { - return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) -} - -// SaveX calls Save and panics if Save returns an error. -func (_c *PermissionCreate) SaveX(ctx context.Context) *Permission { - v, err := _c.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (_c *PermissionCreate) Exec(ctx context.Context) error { - _, err := _c.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_c *PermissionCreate) ExecX(ctx context.Context) { - if err := _c.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (_c *PermissionCreate) check() error { - return nil -} - -func (_c *PermissionCreate) sqlSave(ctx context.Context) (*Permission, error) { - if err := _c.check(); err != nil { - return nil, err - } - _node, _spec := _c.createSpec() - if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - id := _spec.ID.Value.(int64) - _node.ID = int(id) - _c.mutation.id = &_node.ID - _c.mutation.done = true - return _node, nil -} - -func (_c *PermissionCreate) createSpec() (*Permission, *sqlgraph.CreateSpec) { - var ( - _node = &Permission{config: _c.config} - _spec = sqlgraph.NewCreateSpec(permission.Table, sqlgraph.NewFieldSpec(permission.FieldID, field.TypeInt)) - ) - return _node, _spec -} - -// PermissionCreateBulk is the builder for creating many Permission entities in bulk. -type PermissionCreateBulk struct { - config - err error - builders []*PermissionCreate -} - -// Save creates the Permission entities in the database. -func (_c *PermissionCreateBulk) Save(ctx context.Context) ([]*Permission, error) { - if _c.err != nil { - return nil, _c.err - } - specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) - nodes := make([]*Permission, len(_c.builders)) - mutators := make([]Mutator, len(_c.builders)) - for i := range _c.builders { - func(i int, root context.Context) { - builder := _c.builders[i] - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*PermissionMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err := builder.check(); err != nil { - return nil, err - } - builder.mutation = mutation - var err error - nodes[i], specs[i] = builder.createSpec() - if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) - } else { - spec := &sqlgraph.BatchCreateSpec{Nodes: specs} - // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - } - } - if err != nil { - return nil, err - } - mutation.id = &nodes[i].ID - if specs[i].ID.Value != nil { - id := specs[i].ID.Value.(int64) - nodes[i].ID = int(id) - } - mutation.done = true - return nodes[i], nil - }) - for i := len(builder.hooks) - 1; i >= 0; i-- { - mut = builder.hooks[i](mut) - } - mutators[i] = mut - }(i, ctx) - } - if len(mutators) > 0 { - if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { - return nil, err - } - } - return nodes, nil -} - -// SaveX is like Save, but panics if an error occurs. -func (_c *PermissionCreateBulk) SaveX(ctx context.Context) []*Permission { - v, err := _c.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (_c *PermissionCreateBulk) Exec(ctx context.Context) error { - _, err := _c.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_c *PermissionCreateBulk) ExecX(ctx context.Context) { - if err := _c.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/ent/permission_delete.go b/ent/permission_delete.go deleted file mode 100644 index 570e6b0..0000000 --- a/ent/permission_delete.go +++ /dev/null @@ -1,88 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/ent/permission" - "git.dcentral.systems/toolz/goplt/ent/predicate" -) - -// PermissionDelete is the builder for deleting a Permission entity. -type PermissionDelete struct { - config - hooks []Hook - mutation *PermissionMutation -} - -// Where appends a list predicates to the PermissionDelete builder. -func (_d *PermissionDelete) Where(ps ...predicate.Permission) *PermissionDelete { - _d.mutation.Where(ps...) - return _d -} - -// Exec executes the deletion query and returns how many vertices were deleted. -func (_d *PermissionDelete) Exec(ctx context.Context) (int, error) { - return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) -} - -// ExecX is like Exec, but panics if an error occurs. -func (_d *PermissionDelete) ExecX(ctx context.Context) int { - n, err := _d.Exec(ctx) - if err != nil { - panic(err) - } - return n -} - -func (_d *PermissionDelete) sqlExec(ctx context.Context) (int, error) { - _spec := sqlgraph.NewDeleteSpec(permission.Table, sqlgraph.NewFieldSpec(permission.FieldID, field.TypeInt)) - if ps := _d.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) - if err != nil && sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - _d.mutation.done = true - return affected, err -} - -// PermissionDeleteOne is the builder for deleting a single Permission entity. -type PermissionDeleteOne struct { - _d *PermissionDelete -} - -// Where appends a list predicates to the PermissionDelete builder. -func (_d *PermissionDeleteOne) Where(ps ...predicate.Permission) *PermissionDeleteOne { - _d._d.mutation.Where(ps...) - return _d -} - -// Exec executes the deletion query. -func (_d *PermissionDeleteOne) Exec(ctx context.Context) error { - n, err := _d._d.Exec(ctx) - switch { - case err != nil: - return err - case n == 0: - return &NotFoundError{permission.Label} - default: - return nil - } -} - -// ExecX is like Exec, but panics if an error occurs. -func (_d *PermissionDeleteOne) ExecX(ctx context.Context) { - if err := _d.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/ent/permission_query.go b/ent/permission_query.go deleted file mode 100644 index a6c3885..0000000 --- a/ent/permission_query.go +++ /dev/null @@ -1,505 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "fmt" - "math" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/ent/permission" - "git.dcentral.systems/toolz/goplt/ent/predicate" -) - -// PermissionQuery is the builder for querying Permission entities. -type PermissionQuery struct { - config - ctx *QueryContext - order []permission.OrderOption - inters []Interceptor - predicates []predicate.Permission - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Where adds a new predicate for the PermissionQuery builder. -func (_q *PermissionQuery) Where(ps ...predicate.Permission) *PermissionQuery { - _q.predicates = append(_q.predicates, ps...) - return _q -} - -// Limit the number of records to be returned by this query. -func (_q *PermissionQuery) Limit(limit int) *PermissionQuery { - _q.ctx.Limit = &limit - return _q -} - -// Offset to start from. -func (_q *PermissionQuery) Offset(offset int) *PermissionQuery { - _q.ctx.Offset = &offset - return _q -} - -// Unique configures the query builder to filter duplicate records on query. -// By default, unique is set to true, and can be disabled using this method. -func (_q *PermissionQuery) Unique(unique bool) *PermissionQuery { - _q.ctx.Unique = &unique - return _q -} - -// Order specifies how the records should be ordered. -func (_q *PermissionQuery) Order(o ...permission.OrderOption) *PermissionQuery { - _q.order = append(_q.order, o...) - return _q -} - -// First returns the first Permission entity from the query. -// Returns a *NotFoundError when no Permission was found. -func (_q *PermissionQuery) First(ctx context.Context) (*Permission, error) { - nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{permission.Label} - } - return nodes[0], nil -} - -// FirstX is like First, but panics if an error occurs. -func (_q *PermissionQuery) FirstX(ctx context.Context) *Permission { - node, err := _q.First(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// FirstID returns the first Permission ID from the query. -// Returns a *NotFoundError when no Permission ID was found. -func (_q *PermissionQuery) FirstID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{permission.Label} - return - } - return ids[0], nil -} - -// FirstIDX is like FirstID, but panics if an error occurs. -func (_q *PermissionQuery) FirstIDX(ctx context.Context) int { - id, err := _q.FirstID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Only returns a single Permission entity found by the query, ensuring it only returns one. -// Returns a *NotSingularError when more than one Permission entity is found. -// Returns a *NotFoundError when no Permission entities are found. -func (_q *PermissionQuery) Only(ctx context.Context) (*Permission, error) { - nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) - if err != nil { - return nil, err - } - switch len(nodes) { - case 1: - return nodes[0], nil - case 0: - return nil, &NotFoundError{permission.Label} - default: - return nil, &NotSingularError{permission.Label} - } -} - -// OnlyX is like Only, but panics if an error occurs. -func (_q *PermissionQuery) OnlyX(ctx context.Context) *Permission { - node, err := _q.Only(ctx) - if err != nil { - panic(err) - } - return node -} - -// OnlyID is like Only, but returns the only Permission ID in the query. -// Returns a *NotSingularError when more than one Permission ID is found. -// Returns a *NotFoundError when no entities are found. -func (_q *PermissionQuery) OnlyID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { - return - } - switch len(ids) { - case 1: - id = ids[0] - case 0: - err = &NotFoundError{permission.Label} - default: - err = &NotSingularError{permission.Label} - } - return -} - -// OnlyIDX is like OnlyID, but panics if an error occurs. -func (_q *PermissionQuery) OnlyIDX(ctx context.Context) int { - id, err := _q.OnlyID(ctx) - if err != nil { - panic(err) - } - return id -} - -// All executes the query and returns a list of Permissions. -func (_q *PermissionQuery) All(ctx context.Context) ([]*Permission, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) - if err := _q.prepareQuery(ctx); err != nil { - return nil, err - } - qr := querierAll[[]*Permission, *PermissionQuery]() - return withInterceptors[[]*Permission](ctx, _q, qr, _q.inters) -} - -// AllX is like All, but panics if an error occurs. -func (_q *PermissionQuery) AllX(ctx context.Context) []*Permission { - nodes, err := _q.All(ctx) - if err != nil { - panic(err) - } - return nodes -} - -// IDs executes the query and returns a list of Permission IDs. -func (_q *PermissionQuery) IDs(ctx context.Context) (ids []int, err error) { - if _q.ctx.Unique == nil && _q.path != nil { - _q.Unique(true) - } - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) - if err = _q.Select(permission.FieldID).Scan(ctx, &ids); err != nil { - return nil, err - } - return ids, nil -} - -// IDsX is like IDs, but panics if an error occurs. -func (_q *PermissionQuery) IDsX(ctx context.Context) []int { - ids, err := _q.IDs(ctx) - if err != nil { - panic(err) - } - return ids -} - -// Count returns the count of the given query. -func (_q *PermissionQuery) Count(ctx context.Context) (int, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) - if err := _q.prepareQuery(ctx); err != nil { - return 0, err - } - return withInterceptors[int](ctx, _q, querierCount[*PermissionQuery](), _q.inters) -} - -// CountX is like Count, but panics if an error occurs. -func (_q *PermissionQuery) CountX(ctx context.Context) int { - count, err := _q.Count(ctx) - if err != nil { - panic(err) - } - return count -} - -// Exist returns true if the query has elements in the graph. -func (_q *PermissionQuery) Exist(ctx context.Context) (bool, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) - switch _, err := _q.FirstID(ctx); { - case IsNotFound(err): - return false, nil - case err != nil: - return false, fmt.Errorf("ent: check existence: %w", err) - default: - return true, nil - } -} - -// ExistX is like Exist, but panics if an error occurs. -func (_q *PermissionQuery) ExistX(ctx context.Context) bool { - exist, err := _q.Exist(ctx) - if err != nil { - panic(err) - } - return exist -} - -// Clone returns a duplicate of the PermissionQuery builder, including all associated steps. It can be -// used to prepare common query builders and use them differently after the clone is made. -func (_q *PermissionQuery) Clone() *PermissionQuery { - if _q == nil { - return nil - } - return &PermissionQuery{ - config: _q.config, - ctx: _q.ctx.Clone(), - order: append([]permission.OrderOption{}, _q.order...), - inters: append([]Interceptor{}, _q.inters...), - predicates: append([]predicate.Permission{}, _q.predicates...), - // clone intermediate query. - sql: _q.sql.Clone(), - path: _q.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. -func (_q *PermissionQuery) GroupBy(field string, fields ...string) *PermissionGroupBy { - _q.ctx.Fields = append([]string{field}, fields...) - grbuild := &PermissionGroupBy{build: _q} - grbuild.flds = &_q.ctx.Fields - grbuild.label = permission.Label - grbuild.scan = grbuild.Scan - return grbuild -} - -// Select allows the selection one or more fields/columns for the given query, -// instead of selecting all fields in the entity. -func (_q *PermissionQuery) Select(fields ...string) *PermissionSelect { - _q.ctx.Fields = append(_q.ctx.Fields, fields...) - sbuild := &PermissionSelect{PermissionQuery: _q} - sbuild.label = permission.Label - sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan - return sbuild -} - -// Aggregate returns a PermissionSelect configured with the given aggregations. -func (_q *PermissionQuery) Aggregate(fns ...AggregateFunc) *PermissionSelect { - return _q.Select().Aggregate(fns...) -} - -func (_q *PermissionQuery) prepareQuery(ctx context.Context) error { - for _, inter := range _q.inters { - if inter == nil { - return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") - } - if trv, ok := inter.(Traverser); ok { - if err := trv.Traverse(ctx, _q); err != nil { - return err - } - } - } - for _, f := range _q.ctx.Fields { - if !permission.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} - } - } - if _q.path != nil { - prev, err := _q.path(ctx) - if err != nil { - return err - } - _q.sql = prev - } - return nil -} - -func (_q *PermissionQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Permission, error) { - var ( - nodes = []*Permission{} - _spec = _q.querySpec() - ) - _spec.ScanValues = func(columns []string) ([]any, error) { - return (*Permission).scanValues(nil, columns) - } - _spec.Assign = func(columns []string, values []any) error { - node := &Permission{config: _q.config} - nodes = append(nodes, node) - return node.assignValues(columns, values) - } - for i := range hooks { - hooks[i](ctx, _spec) - } - if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { - return nil, err - } - if len(nodes) == 0 { - return nodes, nil - } - return nodes, nil -} - -func (_q *PermissionQuery) sqlCount(ctx context.Context) (int, error) { - _spec := _q.querySpec() - _spec.Node.Columns = _q.ctx.Fields - if len(_q.ctx.Fields) > 0 { - _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique - } - return sqlgraph.CountNodes(ctx, _q.driver, _spec) -} - -func (_q *PermissionQuery) querySpec() *sqlgraph.QuerySpec { - _spec := sqlgraph.NewQuerySpec(permission.Table, permission.Columns, sqlgraph.NewFieldSpec(permission.FieldID, field.TypeInt)) - _spec.From = _q.sql - if unique := _q.ctx.Unique; unique != nil { - _spec.Unique = *unique - } else if _q.path != nil { - _spec.Unique = true - } - if fields := _q.ctx.Fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, permission.FieldID) - for i := range fields { - if fields[i] != permission.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) - } - } - } - if ps := _q.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if limit := _q.ctx.Limit; limit != nil { - _spec.Limit = *limit - } - if offset := _q.ctx.Offset; offset != nil { - _spec.Offset = *offset - } - if ps := _q.order; len(ps) > 0 { - _spec.Order = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return _spec -} - -func (_q *PermissionQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(_q.driver.Dialect()) - t1 := builder.Table(permission.Table) - columns := _q.ctx.Fields - if len(columns) == 0 { - columns = permission.Columns - } - selector := builder.Select(t1.Columns(columns...)...).From(t1) - if _q.sql != nil { - selector = _q.sql - selector.Select(selector.Columns(columns...)...) - } - if _q.ctx.Unique != nil && *_q.ctx.Unique { - selector.Distinct() - } - for _, p := range _q.predicates { - p(selector) - } - for _, p := range _q.order { - p(selector) - } - if offset := _q.ctx.Offset; offset != nil { - // limit is mandatory for offset clause. We start - // with default value, and override it below if needed. - selector.Offset(*offset).Limit(math.MaxInt32) - } - if limit := _q.ctx.Limit; limit != nil { - selector.Limit(*limit) - } - return selector -} - -// PermissionGroupBy is the group-by builder for Permission entities. -type PermissionGroupBy struct { - selector - build *PermissionQuery -} - -// Aggregate adds the given aggregation functions to the group-by query. -func (_g *PermissionGroupBy) Aggregate(fns ...AggregateFunc) *PermissionGroupBy { - _g.fns = append(_g.fns, fns...) - return _g -} - -// Scan applies the selector query and scans the result into the given value. -func (_g *PermissionGroupBy) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) - if err := _g.build.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*PermissionQuery, *PermissionGroupBy](ctx, _g.build, _g, _g.build.inters, v) -} - -func (_g *PermissionGroupBy) sqlScan(ctx context.Context, root *PermissionQuery, v any) error { - selector := root.sqlQuery(ctx).Select() - aggregation := make([]string, 0, len(_g.fns)) - for _, fn := range _g.fns { - aggregation = append(aggregation, fn(selector)) - } - if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) - for _, f := range *_g.flds { - columns = append(columns, selector.C(f)) - } - columns = append(columns, aggregation...) - selector.Select(columns...) - } - selector.GroupBy(selector.Columns(*_g.flds...)...) - if err := selector.Err(); err != nil { - return err - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} - -// PermissionSelect is the builder for selecting fields of Permission entities. -type PermissionSelect struct { - *PermissionQuery - selector -} - -// Aggregate adds the given aggregation functions to the selector query. -func (_s *PermissionSelect) Aggregate(fns ...AggregateFunc) *PermissionSelect { - _s.fns = append(_s.fns, fns...) - return _s -} - -// Scan applies the selector query and scans the result into the given value. -func (_s *PermissionSelect) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) - if err := _s.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*PermissionQuery, *PermissionSelect](ctx, _s.PermissionQuery, _s, _s.inters, v) -} - -func (_s *PermissionSelect) sqlScan(ctx context.Context, root *PermissionQuery, v any) error { - selector := root.sqlQuery(ctx) - aggregation := make([]string, 0, len(_s.fns)) - for _, fn := range _s.fns { - aggregation = append(aggregation, fn(selector)) - } - switch n := len(*_s.selector.flds); { - case n == 0 && len(aggregation) > 0: - selector.Select(aggregation...) - case n != 0 && len(aggregation) > 0: - selector.AppendSelect(aggregation...) - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := _s.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} diff --git a/ent/permission_update.go b/ent/permission_update.go deleted file mode 100644 index 8218739..0000000 --- a/ent/permission_update.go +++ /dev/null @@ -1,175 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "errors" - "fmt" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/ent/permission" - "git.dcentral.systems/toolz/goplt/ent/predicate" -) - -// PermissionUpdate is the builder for updating Permission entities. -type PermissionUpdate struct { - config - hooks []Hook - mutation *PermissionMutation -} - -// Where appends a list predicates to the PermissionUpdate builder. -func (_u *PermissionUpdate) Where(ps ...predicate.Permission) *PermissionUpdate { - _u.mutation.Where(ps...) - return _u -} - -// Mutation returns the PermissionMutation object of the builder. -func (_u *PermissionUpdate) Mutation() *PermissionMutation { - return _u.mutation -} - -// Save executes the query and returns the number of nodes affected by the update operation. -func (_u *PermissionUpdate) Save(ctx context.Context) (int, error) { - return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (_u *PermissionUpdate) SaveX(ctx context.Context) int { - affected, err := _u.Save(ctx) - if err != nil { - panic(err) - } - return affected -} - -// Exec executes the query. -func (_u *PermissionUpdate) Exec(ctx context.Context) error { - _, err := _u.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_u *PermissionUpdate) ExecX(ctx context.Context) { - if err := _u.Exec(ctx); err != nil { - panic(err) - } -} - -func (_u *PermissionUpdate) sqlSave(ctx context.Context) (_node int, err error) { - _spec := sqlgraph.NewUpdateSpec(permission.Table, permission.Columns, sqlgraph.NewFieldSpec(permission.FieldID, field.TypeInt)) - if ps := _u.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{permission.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return 0, err - } - _u.mutation.done = true - return _node, nil -} - -// PermissionUpdateOne is the builder for updating a single Permission entity. -type PermissionUpdateOne struct { - config - fields []string - hooks []Hook - mutation *PermissionMutation -} - -// Mutation returns the PermissionMutation object of the builder. -func (_u *PermissionUpdateOne) Mutation() *PermissionMutation { - return _u.mutation -} - -// Where appends a list predicates to the PermissionUpdate builder. -func (_u *PermissionUpdateOne) Where(ps ...predicate.Permission) *PermissionUpdateOne { - _u.mutation.Where(ps...) - return _u -} - -// Select allows selecting one or more fields (columns) of the returned entity. -// The default is selecting all fields defined in the entity schema. -func (_u *PermissionUpdateOne) Select(field string, fields ...string) *PermissionUpdateOne { - _u.fields = append([]string{field}, fields...) - return _u -} - -// Save executes the query and returns the updated Permission entity. -func (_u *PermissionUpdateOne) Save(ctx context.Context) (*Permission, error) { - return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (_u *PermissionUpdateOne) SaveX(ctx context.Context) *Permission { - node, err := _u.Save(ctx) - if err != nil { - panic(err) - } - return node -} - -// Exec executes the query on the entity. -func (_u *PermissionUpdateOne) Exec(ctx context.Context) error { - _, err := _u.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_u *PermissionUpdateOne) ExecX(ctx context.Context) { - if err := _u.Exec(ctx); err != nil { - panic(err) - } -} - -func (_u *PermissionUpdateOne) sqlSave(ctx context.Context) (_node *Permission, err error) { - _spec := sqlgraph.NewUpdateSpec(permission.Table, permission.Columns, sqlgraph.NewFieldSpec(permission.FieldID, field.TypeInt)) - id, ok := _u.mutation.ID() - if !ok { - return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Permission.id" for update`)} - } - _spec.Node.ID.Value = id - if fields := _u.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, permission.FieldID) - for _, f := range fields { - if !permission.ValidColumn(f) { - return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} - } - if f != permission.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, f) - } - } - } - if ps := _u.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - _node = &Permission{config: _u.config} - _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{permission.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - _u.mutation.done = true - return _node, nil -} diff --git a/ent/predicate/predicate.go b/ent/predicate/predicate.go deleted file mode 100644 index 7604a5d..0000000 --- a/ent/predicate/predicate.go +++ /dev/null @@ -1,19 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package predicate - -import ( - "entgo.io/ent/dialect/sql" -) - -// AuditLog is the predicate function for auditlog builders. -type AuditLog func(*sql.Selector) - -// Permission is the predicate function for permission builders. -type Permission func(*sql.Selector) - -// Role is the predicate function for role builders. -type Role func(*sql.Selector) - -// User is the predicate function for user builders. -type User func(*sql.Selector) diff --git a/ent/role.go b/ent/role.go deleted file mode 100644 index ec2bd74..0000000 --- a/ent/role.go +++ /dev/null @@ -1,91 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "fmt" - "strings" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "git.dcentral.systems/toolz/goplt/ent/role" -) - -// Role is the model entity for the Role schema. -type Role struct { - config - // ID of the ent. - ID int `json:"id,omitempty"` - selectValues sql.SelectValues -} - -// scanValues returns the types for scanning values from sql.Rows. -func (*Role) scanValues(columns []string) ([]any, error) { - values := make([]any, len(columns)) - for i := range columns { - switch columns[i] { - case role.FieldID: - values[i] = new(sql.NullInt64) - default: - values[i] = new(sql.UnknownType) - } - } - return values, nil -} - -// assignValues assigns the values that were returned from sql.Rows (after scanning) -// to the Role fields. -func (_m *Role) assignValues(columns []string, values []any) error { - if m, n := len(values), len(columns); m < n { - return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) - } - for i := range columns { - switch columns[i] { - case role.FieldID: - value, ok := values[i].(*sql.NullInt64) - if !ok { - return fmt.Errorf("unexpected type %T for field id", value) - } - _m.ID = int(value.Int64) - default: - _m.selectValues.Set(columns[i], values[i]) - } - } - return nil -} - -// Value returns the ent.Value that was dynamically selected and assigned to the Role. -// This includes values selected through modifiers, order, etc. -func (_m *Role) Value(name string) (ent.Value, error) { - return _m.selectValues.Get(name) -} - -// Update returns a builder for updating this Role. -// Note that you need to call Role.Unwrap() before calling this method if this Role -// was returned from a transaction, and the transaction was committed or rolled back. -func (_m *Role) Update() *RoleUpdateOne { - return NewRoleClient(_m.config).UpdateOne(_m) -} - -// Unwrap unwraps the Role entity that was returned from a transaction after it was closed, -// so that all future queries will be executed through the driver which created the transaction. -func (_m *Role) Unwrap() *Role { - _tx, ok := _m.config.driver.(*txDriver) - if !ok { - panic("ent: Role is not a transactional entity") - } - _m.config.driver = _tx.drv - return _m -} - -// String implements the fmt.Stringer. -func (_m *Role) String() string { - var builder strings.Builder - builder.WriteString("Role(") - builder.WriteString(fmt.Sprintf("id=%v", _m.ID)) - builder.WriteByte(')') - return builder.String() -} - -// Roles is a parsable slice of Role. -type Roles []*Role diff --git a/ent/role/role.go b/ent/role/role.go deleted file mode 100644 index 94965fa..0000000 --- a/ent/role/role.go +++ /dev/null @@ -1,39 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package role - -import ( - "entgo.io/ent/dialect/sql" -) - -const ( - // Label holds the string label denoting the role type in the database. - Label = "role" - // FieldID holds the string denoting the id field in the database. - FieldID = "id" - // Table holds the table name of the role in the database. - Table = "roles" -) - -// Columns holds all SQL columns for role fields. -var Columns = []string{ - FieldID, -} - -// ValidColumn reports if the column name is valid (part of the table columns). -func ValidColumn(column string) bool { - for i := range Columns { - if column == Columns[i] { - return true - } - } - return false -} - -// OrderOption defines the ordering options for the Role queries. -type OrderOption func(*sql.Selector) - -// ByID orders the results by the id field. -func ByID(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldID, opts...).ToFunc() -} diff --git a/ent/role/where.go b/ent/role/where.go deleted file mode 100644 index fc0ba91..0000000 --- a/ent/role/where.go +++ /dev/null @@ -1,68 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package role - -import ( - "entgo.io/ent/dialect/sql" - "git.dcentral.systems/toolz/goplt/ent/predicate" -) - -// ID filters vertices based on their ID field. -func ID(id int) predicate.Role { - return predicate.Role(sql.FieldEQ(FieldID, id)) -} - -// IDEQ applies the EQ predicate on the ID field. -func IDEQ(id int) predicate.Role { - return predicate.Role(sql.FieldEQ(FieldID, id)) -} - -// IDNEQ applies the NEQ predicate on the ID field. -func IDNEQ(id int) predicate.Role { - return predicate.Role(sql.FieldNEQ(FieldID, id)) -} - -// IDIn applies the In predicate on the ID field. -func IDIn(ids ...int) predicate.Role { - return predicate.Role(sql.FieldIn(FieldID, ids...)) -} - -// IDNotIn applies the NotIn predicate on the ID field. -func IDNotIn(ids ...int) predicate.Role { - return predicate.Role(sql.FieldNotIn(FieldID, ids...)) -} - -// IDGT applies the GT predicate on the ID field. -func IDGT(id int) predicate.Role { - return predicate.Role(sql.FieldGT(FieldID, id)) -} - -// IDGTE applies the GTE predicate on the ID field. -func IDGTE(id int) predicate.Role { - return predicate.Role(sql.FieldGTE(FieldID, id)) -} - -// IDLT applies the LT predicate on the ID field. -func IDLT(id int) predicate.Role { - return predicate.Role(sql.FieldLT(FieldID, id)) -} - -// IDLTE applies the LTE predicate on the ID field. -func IDLTE(id int) predicate.Role { - return predicate.Role(sql.FieldLTE(FieldID, id)) -} - -// And groups predicates with the AND operator between them. -func And(predicates ...predicate.Role) predicate.Role { - return predicate.Role(sql.AndPredicates(predicates...)) -} - -// Or groups predicates with the OR operator between them. -func Or(predicates ...predicate.Role) predicate.Role { - return predicate.Role(sql.OrPredicates(predicates...)) -} - -// Not applies the not operator on the given predicate. -func Not(p predicate.Role) predicate.Role { - return predicate.Role(sql.NotPredicates(p)) -} diff --git a/ent/role_create.go b/ent/role_create.go deleted file mode 100644 index 4dac1e7..0000000 --- a/ent/role_create.go +++ /dev/null @@ -1,169 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "fmt" - - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/ent/role" -) - -// RoleCreate is the builder for creating a Role entity. -type RoleCreate struct { - config - mutation *RoleMutation - hooks []Hook -} - -// Mutation returns the RoleMutation object of the builder. -func (_c *RoleCreate) Mutation() *RoleMutation { - return _c.mutation -} - -// Save creates the Role in the database. -func (_c *RoleCreate) Save(ctx context.Context) (*Role, error) { - return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) -} - -// SaveX calls Save and panics if Save returns an error. -func (_c *RoleCreate) SaveX(ctx context.Context) *Role { - v, err := _c.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (_c *RoleCreate) Exec(ctx context.Context) error { - _, err := _c.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_c *RoleCreate) ExecX(ctx context.Context) { - if err := _c.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (_c *RoleCreate) check() error { - return nil -} - -func (_c *RoleCreate) sqlSave(ctx context.Context) (*Role, error) { - if err := _c.check(); err != nil { - return nil, err - } - _node, _spec := _c.createSpec() - if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - id := _spec.ID.Value.(int64) - _node.ID = int(id) - _c.mutation.id = &_node.ID - _c.mutation.done = true - return _node, nil -} - -func (_c *RoleCreate) createSpec() (*Role, *sqlgraph.CreateSpec) { - var ( - _node = &Role{config: _c.config} - _spec = sqlgraph.NewCreateSpec(role.Table, sqlgraph.NewFieldSpec(role.FieldID, field.TypeInt)) - ) - return _node, _spec -} - -// RoleCreateBulk is the builder for creating many Role entities in bulk. -type RoleCreateBulk struct { - config - err error - builders []*RoleCreate -} - -// Save creates the Role entities in the database. -func (_c *RoleCreateBulk) Save(ctx context.Context) ([]*Role, error) { - if _c.err != nil { - return nil, _c.err - } - specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) - nodes := make([]*Role, len(_c.builders)) - mutators := make([]Mutator, len(_c.builders)) - for i := range _c.builders { - func(i int, root context.Context) { - builder := _c.builders[i] - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*RoleMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err := builder.check(); err != nil { - return nil, err - } - builder.mutation = mutation - var err error - nodes[i], specs[i] = builder.createSpec() - if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) - } else { - spec := &sqlgraph.BatchCreateSpec{Nodes: specs} - // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - } - } - if err != nil { - return nil, err - } - mutation.id = &nodes[i].ID - if specs[i].ID.Value != nil { - id := specs[i].ID.Value.(int64) - nodes[i].ID = int(id) - } - mutation.done = true - return nodes[i], nil - }) - for i := len(builder.hooks) - 1; i >= 0; i-- { - mut = builder.hooks[i](mut) - } - mutators[i] = mut - }(i, ctx) - } - if len(mutators) > 0 { - if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { - return nil, err - } - } - return nodes, nil -} - -// SaveX is like Save, but panics if an error occurs. -func (_c *RoleCreateBulk) SaveX(ctx context.Context) []*Role { - v, err := _c.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (_c *RoleCreateBulk) Exec(ctx context.Context) error { - _, err := _c.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_c *RoleCreateBulk) ExecX(ctx context.Context) { - if err := _c.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/ent/role_delete.go b/ent/role_delete.go deleted file mode 100644 index b10dc0c..0000000 --- a/ent/role_delete.go +++ /dev/null @@ -1,88 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/ent/predicate" - "git.dcentral.systems/toolz/goplt/ent/role" -) - -// RoleDelete is the builder for deleting a Role entity. -type RoleDelete struct { - config - hooks []Hook - mutation *RoleMutation -} - -// Where appends a list predicates to the RoleDelete builder. -func (_d *RoleDelete) Where(ps ...predicate.Role) *RoleDelete { - _d.mutation.Where(ps...) - return _d -} - -// Exec executes the deletion query and returns how many vertices were deleted. -func (_d *RoleDelete) Exec(ctx context.Context) (int, error) { - return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) -} - -// ExecX is like Exec, but panics if an error occurs. -func (_d *RoleDelete) ExecX(ctx context.Context) int { - n, err := _d.Exec(ctx) - if err != nil { - panic(err) - } - return n -} - -func (_d *RoleDelete) sqlExec(ctx context.Context) (int, error) { - _spec := sqlgraph.NewDeleteSpec(role.Table, sqlgraph.NewFieldSpec(role.FieldID, field.TypeInt)) - if ps := _d.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) - if err != nil && sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - _d.mutation.done = true - return affected, err -} - -// RoleDeleteOne is the builder for deleting a single Role entity. -type RoleDeleteOne struct { - _d *RoleDelete -} - -// Where appends a list predicates to the RoleDelete builder. -func (_d *RoleDeleteOne) Where(ps ...predicate.Role) *RoleDeleteOne { - _d._d.mutation.Where(ps...) - return _d -} - -// Exec executes the deletion query. -func (_d *RoleDeleteOne) Exec(ctx context.Context) error { - n, err := _d._d.Exec(ctx) - switch { - case err != nil: - return err - case n == 0: - return &NotFoundError{role.Label} - default: - return nil - } -} - -// ExecX is like Exec, but panics if an error occurs. -func (_d *RoleDeleteOne) ExecX(ctx context.Context) { - if err := _d.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/ent/role_query.go b/ent/role_query.go deleted file mode 100644 index ddc0fd8..0000000 --- a/ent/role_query.go +++ /dev/null @@ -1,505 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "fmt" - "math" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/ent/predicate" - "git.dcentral.systems/toolz/goplt/ent/role" -) - -// RoleQuery is the builder for querying Role entities. -type RoleQuery struct { - config - ctx *QueryContext - order []role.OrderOption - inters []Interceptor - predicates []predicate.Role - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Where adds a new predicate for the RoleQuery builder. -func (_q *RoleQuery) Where(ps ...predicate.Role) *RoleQuery { - _q.predicates = append(_q.predicates, ps...) - return _q -} - -// Limit the number of records to be returned by this query. -func (_q *RoleQuery) Limit(limit int) *RoleQuery { - _q.ctx.Limit = &limit - return _q -} - -// Offset to start from. -func (_q *RoleQuery) Offset(offset int) *RoleQuery { - _q.ctx.Offset = &offset - return _q -} - -// Unique configures the query builder to filter duplicate records on query. -// By default, unique is set to true, and can be disabled using this method. -func (_q *RoleQuery) Unique(unique bool) *RoleQuery { - _q.ctx.Unique = &unique - return _q -} - -// Order specifies how the records should be ordered. -func (_q *RoleQuery) Order(o ...role.OrderOption) *RoleQuery { - _q.order = append(_q.order, o...) - return _q -} - -// First returns the first Role entity from the query. -// Returns a *NotFoundError when no Role was found. -func (_q *RoleQuery) First(ctx context.Context) (*Role, error) { - nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{role.Label} - } - return nodes[0], nil -} - -// FirstX is like First, but panics if an error occurs. -func (_q *RoleQuery) FirstX(ctx context.Context) *Role { - node, err := _q.First(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// FirstID returns the first Role ID from the query. -// Returns a *NotFoundError when no Role ID was found. -func (_q *RoleQuery) FirstID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{role.Label} - return - } - return ids[0], nil -} - -// FirstIDX is like FirstID, but panics if an error occurs. -func (_q *RoleQuery) FirstIDX(ctx context.Context) int { - id, err := _q.FirstID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Only returns a single Role entity found by the query, ensuring it only returns one. -// Returns a *NotSingularError when more than one Role entity is found. -// Returns a *NotFoundError when no Role entities are found. -func (_q *RoleQuery) Only(ctx context.Context) (*Role, error) { - nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) - if err != nil { - return nil, err - } - switch len(nodes) { - case 1: - return nodes[0], nil - case 0: - return nil, &NotFoundError{role.Label} - default: - return nil, &NotSingularError{role.Label} - } -} - -// OnlyX is like Only, but panics if an error occurs. -func (_q *RoleQuery) OnlyX(ctx context.Context) *Role { - node, err := _q.Only(ctx) - if err != nil { - panic(err) - } - return node -} - -// OnlyID is like Only, but returns the only Role ID in the query. -// Returns a *NotSingularError when more than one Role ID is found. -// Returns a *NotFoundError when no entities are found. -func (_q *RoleQuery) OnlyID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { - return - } - switch len(ids) { - case 1: - id = ids[0] - case 0: - err = &NotFoundError{role.Label} - default: - err = &NotSingularError{role.Label} - } - return -} - -// OnlyIDX is like OnlyID, but panics if an error occurs. -func (_q *RoleQuery) OnlyIDX(ctx context.Context) int { - id, err := _q.OnlyID(ctx) - if err != nil { - panic(err) - } - return id -} - -// All executes the query and returns a list of Roles. -func (_q *RoleQuery) All(ctx context.Context) ([]*Role, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) - if err := _q.prepareQuery(ctx); err != nil { - return nil, err - } - qr := querierAll[[]*Role, *RoleQuery]() - return withInterceptors[[]*Role](ctx, _q, qr, _q.inters) -} - -// AllX is like All, but panics if an error occurs. -func (_q *RoleQuery) AllX(ctx context.Context) []*Role { - nodes, err := _q.All(ctx) - if err != nil { - panic(err) - } - return nodes -} - -// IDs executes the query and returns a list of Role IDs. -func (_q *RoleQuery) IDs(ctx context.Context) (ids []int, err error) { - if _q.ctx.Unique == nil && _q.path != nil { - _q.Unique(true) - } - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) - if err = _q.Select(role.FieldID).Scan(ctx, &ids); err != nil { - return nil, err - } - return ids, nil -} - -// IDsX is like IDs, but panics if an error occurs. -func (_q *RoleQuery) IDsX(ctx context.Context) []int { - ids, err := _q.IDs(ctx) - if err != nil { - panic(err) - } - return ids -} - -// Count returns the count of the given query. -func (_q *RoleQuery) Count(ctx context.Context) (int, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) - if err := _q.prepareQuery(ctx); err != nil { - return 0, err - } - return withInterceptors[int](ctx, _q, querierCount[*RoleQuery](), _q.inters) -} - -// CountX is like Count, but panics if an error occurs. -func (_q *RoleQuery) CountX(ctx context.Context) int { - count, err := _q.Count(ctx) - if err != nil { - panic(err) - } - return count -} - -// Exist returns true if the query has elements in the graph. -func (_q *RoleQuery) Exist(ctx context.Context) (bool, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) - switch _, err := _q.FirstID(ctx); { - case IsNotFound(err): - return false, nil - case err != nil: - return false, fmt.Errorf("ent: check existence: %w", err) - default: - return true, nil - } -} - -// ExistX is like Exist, but panics if an error occurs. -func (_q *RoleQuery) ExistX(ctx context.Context) bool { - exist, err := _q.Exist(ctx) - if err != nil { - panic(err) - } - return exist -} - -// Clone returns a duplicate of the RoleQuery builder, including all associated steps. It can be -// used to prepare common query builders and use them differently after the clone is made. -func (_q *RoleQuery) Clone() *RoleQuery { - if _q == nil { - return nil - } - return &RoleQuery{ - config: _q.config, - ctx: _q.ctx.Clone(), - order: append([]role.OrderOption{}, _q.order...), - inters: append([]Interceptor{}, _q.inters...), - predicates: append([]predicate.Role{}, _q.predicates...), - // clone intermediate query. - sql: _q.sql.Clone(), - path: _q.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. -func (_q *RoleQuery) GroupBy(field string, fields ...string) *RoleGroupBy { - _q.ctx.Fields = append([]string{field}, fields...) - grbuild := &RoleGroupBy{build: _q} - grbuild.flds = &_q.ctx.Fields - grbuild.label = role.Label - grbuild.scan = grbuild.Scan - return grbuild -} - -// Select allows the selection one or more fields/columns for the given query, -// instead of selecting all fields in the entity. -func (_q *RoleQuery) Select(fields ...string) *RoleSelect { - _q.ctx.Fields = append(_q.ctx.Fields, fields...) - sbuild := &RoleSelect{RoleQuery: _q} - sbuild.label = role.Label - sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan - return sbuild -} - -// Aggregate returns a RoleSelect configured with the given aggregations. -func (_q *RoleQuery) Aggregate(fns ...AggregateFunc) *RoleSelect { - return _q.Select().Aggregate(fns...) -} - -func (_q *RoleQuery) prepareQuery(ctx context.Context) error { - for _, inter := range _q.inters { - if inter == nil { - return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") - } - if trv, ok := inter.(Traverser); ok { - if err := trv.Traverse(ctx, _q); err != nil { - return err - } - } - } - for _, f := range _q.ctx.Fields { - if !role.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} - } - } - if _q.path != nil { - prev, err := _q.path(ctx) - if err != nil { - return err - } - _q.sql = prev - } - return nil -} - -func (_q *RoleQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Role, error) { - var ( - nodes = []*Role{} - _spec = _q.querySpec() - ) - _spec.ScanValues = func(columns []string) ([]any, error) { - return (*Role).scanValues(nil, columns) - } - _spec.Assign = func(columns []string, values []any) error { - node := &Role{config: _q.config} - nodes = append(nodes, node) - return node.assignValues(columns, values) - } - for i := range hooks { - hooks[i](ctx, _spec) - } - if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { - return nil, err - } - if len(nodes) == 0 { - return nodes, nil - } - return nodes, nil -} - -func (_q *RoleQuery) sqlCount(ctx context.Context) (int, error) { - _spec := _q.querySpec() - _spec.Node.Columns = _q.ctx.Fields - if len(_q.ctx.Fields) > 0 { - _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique - } - return sqlgraph.CountNodes(ctx, _q.driver, _spec) -} - -func (_q *RoleQuery) querySpec() *sqlgraph.QuerySpec { - _spec := sqlgraph.NewQuerySpec(role.Table, role.Columns, sqlgraph.NewFieldSpec(role.FieldID, field.TypeInt)) - _spec.From = _q.sql - if unique := _q.ctx.Unique; unique != nil { - _spec.Unique = *unique - } else if _q.path != nil { - _spec.Unique = true - } - if fields := _q.ctx.Fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, role.FieldID) - for i := range fields { - if fields[i] != role.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) - } - } - } - if ps := _q.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if limit := _q.ctx.Limit; limit != nil { - _spec.Limit = *limit - } - if offset := _q.ctx.Offset; offset != nil { - _spec.Offset = *offset - } - if ps := _q.order; len(ps) > 0 { - _spec.Order = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return _spec -} - -func (_q *RoleQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(_q.driver.Dialect()) - t1 := builder.Table(role.Table) - columns := _q.ctx.Fields - if len(columns) == 0 { - columns = role.Columns - } - selector := builder.Select(t1.Columns(columns...)...).From(t1) - if _q.sql != nil { - selector = _q.sql - selector.Select(selector.Columns(columns...)...) - } - if _q.ctx.Unique != nil && *_q.ctx.Unique { - selector.Distinct() - } - for _, p := range _q.predicates { - p(selector) - } - for _, p := range _q.order { - p(selector) - } - if offset := _q.ctx.Offset; offset != nil { - // limit is mandatory for offset clause. We start - // with default value, and override it below if needed. - selector.Offset(*offset).Limit(math.MaxInt32) - } - if limit := _q.ctx.Limit; limit != nil { - selector.Limit(*limit) - } - return selector -} - -// RoleGroupBy is the group-by builder for Role entities. -type RoleGroupBy struct { - selector - build *RoleQuery -} - -// Aggregate adds the given aggregation functions to the group-by query. -func (_g *RoleGroupBy) Aggregate(fns ...AggregateFunc) *RoleGroupBy { - _g.fns = append(_g.fns, fns...) - return _g -} - -// Scan applies the selector query and scans the result into the given value. -func (_g *RoleGroupBy) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) - if err := _g.build.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*RoleQuery, *RoleGroupBy](ctx, _g.build, _g, _g.build.inters, v) -} - -func (_g *RoleGroupBy) sqlScan(ctx context.Context, root *RoleQuery, v any) error { - selector := root.sqlQuery(ctx).Select() - aggregation := make([]string, 0, len(_g.fns)) - for _, fn := range _g.fns { - aggregation = append(aggregation, fn(selector)) - } - if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) - for _, f := range *_g.flds { - columns = append(columns, selector.C(f)) - } - columns = append(columns, aggregation...) - selector.Select(columns...) - } - selector.GroupBy(selector.Columns(*_g.flds...)...) - if err := selector.Err(); err != nil { - return err - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} - -// RoleSelect is the builder for selecting fields of Role entities. -type RoleSelect struct { - *RoleQuery - selector -} - -// Aggregate adds the given aggregation functions to the selector query. -func (_s *RoleSelect) Aggregate(fns ...AggregateFunc) *RoleSelect { - _s.fns = append(_s.fns, fns...) - return _s -} - -// Scan applies the selector query and scans the result into the given value. -func (_s *RoleSelect) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) - if err := _s.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*RoleQuery, *RoleSelect](ctx, _s.RoleQuery, _s, _s.inters, v) -} - -func (_s *RoleSelect) sqlScan(ctx context.Context, root *RoleQuery, v any) error { - selector := root.sqlQuery(ctx) - aggregation := make([]string, 0, len(_s.fns)) - for _, fn := range _s.fns { - aggregation = append(aggregation, fn(selector)) - } - switch n := len(*_s.selector.flds); { - case n == 0 && len(aggregation) > 0: - selector.Select(aggregation...) - case n != 0 && len(aggregation) > 0: - selector.AppendSelect(aggregation...) - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := _s.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} diff --git a/ent/role_update.go b/ent/role_update.go deleted file mode 100644 index 3873cbe..0000000 --- a/ent/role_update.go +++ /dev/null @@ -1,175 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "errors" - "fmt" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/ent/predicate" - "git.dcentral.systems/toolz/goplt/ent/role" -) - -// RoleUpdate is the builder for updating Role entities. -type RoleUpdate struct { - config - hooks []Hook - mutation *RoleMutation -} - -// Where appends a list predicates to the RoleUpdate builder. -func (_u *RoleUpdate) Where(ps ...predicate.Role) *RoleUpdate { - _u.mutation.Where(ps...) - return _u -} - -// Mutation returns the RoleMutation object of the builder. -func (_u *RoleUpdate) Mutation() *RoleMutation { - return _u.mutation -} - -// Save executes the query and returns the number of nodes affected by the update operation. -func (_u *RoleUpdate) Save(ctx context.Context) (int, error) { - return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (_u *RoleUpdate) SaveX(ctx context.Context) int { - affected, err := _u.Save(ctx) - if err != nil { - panic(err) - } - return affected -} - -// Exec executes the query. -func (_u *RoleUpdate) Exec(ctx context.Context) error { - _, err := _u.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_u *RoleUpdate) ExecX(ctx context.Context) { - if err := _u.Exec(ctx); err != nil { - panic(err) - } -} - -func (_u *RoleUpdate) sqlSave(ctx context.Context) (_node int, err error) { - _spec := sqlgraph.NewUpdateSpec(role.Table, role.Columns, sqlgraph.NewFieldSpec(role.FieldID, field.TypeInt)) - if ps := _u.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{role.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return 0, err - } - _u.mutation.done = true - return _node, nil -} - -// RoleUpdateOne is the builder for updating a single Role entity. -type RoleUpdateOne struct { - config - fields []string - hooks []Hook - mutation *RoleMutation -} - -// Mutation returns the RoleMutation object of the builder. -func (_u *RoleUpdateOne) Mutation() *RoleMutation { - return _u.mutation -} - -// Where appends a list predicates to the RoleUpdate builder. -func (_u *RoleUpdateOne) Where(ps ...predicate.Role) *RoleUpdateOne { - _u.mutation.Where(ps...) - return _u -} - -// Select allows selecting one or more fields (columns) of the returned entity. -// The default is selecting all fields defined in the entity schema. -func (_u *RoleUpdateOne) Select(field string, fields ...string) *RoleUpdateOne { - _u.fields = append([]string{field}, fields...) - return _u -} - -// Save executes the query and returns the updated Role entity. -func (_u *RoleUpdateOne) Save(ctx context.Context) (*Role, error) { - return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (_u *RoleUpdateOne) SaveX(ctx context.Context) *Role { - node, err := _u.Save(ctx) - if err != nil { - panic(err) - } - return node -} - -// Exec executes the query on the entity. -func (_u *RoleUpdateOne) Exec(ctx context.Context) error { - _, err := _u.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_u *RoleUpdateOne) ExecX(ctx context.Context) { - if err := _u.Exec(ctx); err != nil { - panic(err) - } -} - -func (_u *RoleUpdateOne) sqlSave(ctx context.Context) (_node *Role, err error) { - _spec := sqlgraph.NewUpdateSpec(role.Table, role.Columns, sqlgraph.NewFieldSpec(role.FieldID, field.TypeInt)) - id, ok := _u.mutation.ID() - if !ok { - return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Role.id" for update`)} - } - _spec.Node.ID.Value = id - if fields := _u.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, role.FieldID) - for _, f := range fields { - if !role.ValidColumn(f) { - return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} - } - if f != role.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, f) - } - } - } - if ps := _u.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - _node = &Role{config: _u.config} - _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{role.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - _u.mutation.done = true - return _node, nil -} diff --git a/ent/runtime.go b/ent/runtime.go deleted file mode 100644 index 793d053..0000000 --- a/ent/runtime.go +++ /dev/null @@ -1,9 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -// 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() { -} diff --git a/ent/runtime/runtime.go b/ent/runtime/runtime.go deleted file mode 100644 index 46a88a0..0000000 --- a/ent/runtime/runtime.go +++ /dev/null @@ -1,10 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package runtime - -// The schema-stitching logic is generated in git.dcentral.systems/toolz/goplt/ent/runtime.go - -const ( - Version = "v0.14.5" // Version of ent codegen. - Sum = "h1:Rj2WOYJtCkWyFo6a+5wB3EfBRP0rnx1fMk6gGA0UUe4=" // Sum of ent codegen. -) diff --git a/ent/schema/auditlog.go b/ent/schema/auditlog.go deleted file mode 100644 index 1fe5105..0000000 --- a/ent/schema/auditlog.go +++ /dev/null @@ -1,19 +0,0 @@ -// Package schema defines the Ent schema for audit log entities. -package schema - -import "entgo.io/ent" - -// AuditLog holds the schema definition for the AuditLog entity. -type AuditLog struct { - ent.Schema -} - -// Fields of the AuditLog. -func (AuditLog) Fields() []ent.Field { - return nil -} - -// Edges of the AuditLog. -func (AuditLog) Edges() []ent.Edge { - return nil -} diff --git a/ent/schema/permission.go b/ent/schema/permission.go deleted file mode 100644 index cd589ec..0000000 --- a/ent/schema/permission.go +++ /dev/null @@ -1,18 +0,0 @@ -package schema - -import "entgo.io/ent" - -// Permission holds the schema definition for the Permission entity. -type Permission struct { - ent.Schema -} - -// Fields of the Permission. -func (Permission) Fields() []ent.Field { - return nil -} - -// Edges of the Permission. -func (Permission) Edges() []ent.Edge { - return nil -} diff --git a/ent/schema/role.go b/ent/schema/role.go deleted file mode 100644 index b80c4da..0000000 --- a/ent/schema/role.go +++ /dev/null @@ -1,18 +0,0 @@ -package schema - -import "entgo.io/ent" - -// Role holds the schema definition for the Role entity. -type Role struct { - ent.Schema -} - -// Fields of the Role. -func (Role) Fields() []ent.Field { - return nil -} - -// Edges of the Role. -func (Role) Edges() []ent.Edge { - return nil -} diff --git a/ent/schema/user.go b/ent/schema/user.go deleted file mode 100644 index 7c14fb8..0000000 --- a/ent/schema/user.go +++ /dev/null @@ -1,18 +0,0 @@ -package schema - -import "entgo.io/ent" - -// User holds the schema definition for the User entity. -type User struct { - ent.Schema -} - -// Fields of the User. -func (User) Fields() []ent.Field { - return nil -} - -// Edges of the User. -func (User) Edges() []ent.Edge { - return nil -} diff --git a/ent/tx.go b/ent/tx.go deleted file mode 100644 index f65f61d..0000000 --- a/ent/tx.go +++ /dev/null @@ -1,219 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "sync" - - "entgo.io/ent/dialect" -) - -// Tx is a transactional client that is created by calling Client.Tx(). -type Tx struct { - config - // AuditLog is the client for interacting with the AuditLog builders. - AuditLog *AuditLogClient - // Permission is the client for interacting with the Permission builders. - Permission *PermissionClient - // Role is the client for interacting with the Role builders. - Role *RoleClient - // User is the client for interacting with the User builders. - User *UserClient - - // lazily loaded. - client *Client - clientOnce sync.Once - // ctx lives for the life of the transaction. It is - // the same context used by the underlying connection. - ctx context.Context -} - -type ( - // Committer is the interface that wraps the Commit method. - Committer interface { - Commit(context.Context, *Tx) error - } - - // The CommitFunc type is an adapter to allow the use of ordinary - // function as a Committer. If f is a function with the appropriate - // signature, CommitFunc(f) is a Committer that calls f. - CommitFunc func(context.Context, *Tx) error - - // CommitHook defines the "commit middleware". A function that gets a Committer - // and returns a Committer. For example: - // - // hook := func(next ent.Committer) ent.Committer { - // return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error { - // // Do some stuff before. - // if err := next.Commit(ctx, tx); err != nil { - // return err - // } - // // Do some stuff after. - // return nil - // }) - // } - // - CommitHook func(Committer) Committer -) - -// Commit calls f(ctx, m). -func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error { - return f(ctx, tx) -} - -// Commit commits the transaction. -func (tx *Tx) Commit() error { - txDriver := tx.config.driver.(*txDriver) - var fn Committer = CommitFunc(func(context.Context, *Tx) error { - return txDriver.tx.Commit() - }) - txDriver.mu.Lock() - hooks := append([]CommitHook(nil), txDriver.onCommit...) - txDriver.mu.Unlock() - for i := len(hooks) - 1; i >= 0; i-- { - fn = hooks[i](fn) - } - return fn.Commit(tx.ctx, tx) -} - -// OnCommit adds a hook to call on commit. -func (tx *Tx) OnCommit(f CommitHook) { - txDriver := tx.config.driver.(*txDriver) - txDriver.mu.Lock() - txDriver.onCommit = append(txDriver.onCommit, f) - txDriver.mu.Unlock() -} - -type ( - // Rollbacker is the interface that wraps the Rollback method. - Rollbacker interface { - Rollback(context.Context, *Tx) error - } - - // The RollbackFunc type is an adapter to allow the use of ordinary - // function as a Rollbacker. If f is a function with the appropriate - // signature, RollbackFunc(f) is a Rollbacker that calls f. - RollbackFunc func(context.Context, *Tx) error - - // RollbackHook defines the "rollback middleware". A function that gets a Rollbacker - // and returns a Rollbacker. For example: - // - // hook := func(next ent.Rollbacker) ent.Rollbacker { - // return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error { - // // Do some stuff before. - // if err := next.Rollback(ctx, tx); err != nil { - // return err - // } - // // Do some stuff after. - // return nil - // }) - // } - // - RollbackHook func(Rollbacker) Rollbacker -) - -// Rollback calls f(ctx, m). -func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error { - return f(ctx, tx) -} - -// Rollback rollbacks the transaction. -func (tx *Tx) Rollback() error { - txDriver := tx.config.driver.(*txDriver) - var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error { - return txDriver.tx.Rollback() - }) - txDriver.mu.Lock() - hooks := append([]RollbackHook(nil), txDriver.onRollback...) - txDriver.mu.Unlock() - for i := len(hooks) - 1; i >= 0; i-- { - fn = hooks[i](fn) - } - return fn.Rollback(tx.ctx, tx) -} - -// OnRollback adds a hook to call on rollback. -func (tx *Tx) OnRollback(f RollbackHook) { - txDriver := tx.config.driver.(*txDriver) - txDriver.mu.Lock() - txDriver.onRollback = append(txDriver.onRollback, f) - txDriver.mu.Unlock() -} - -// Client returns a Client that binds to current transaction. -func (tx *Tx) Client() *Client { - tx.clientOnce.Do(func() { - tx.client = &Client{config: tx.config} - tx.client.init() - }) - return tx.client -} - -func (tx *Tx) init() { - tx.AuditLog = NewAuditLogClient(tx.config) - tx.Permission = NewPermissionClient(tx.config) - tx.Role = NewRoleClient(tx.config) - tx.User = NewUserClient(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: AuditLog.QueryXXX(), the query will be executed -// through the driver which created this transaction. -// -// Note that txDriver is not goroutine safe. -type txDriver struct { - // the driver we started the transaction from. - drv dialect.Driver - // tx is the underlying transaction. - tx dialect.Tx - // completion hooks. - mu sync.Mutex - onCommit []CommitHook - onRollback []RollbackHook -} - -// newTx creates a new transactional driver. -func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) { - tx, err := drv.Tx(ctx) - if err != nil { - return nil, err - } - return &txDriver{tx: tx, drv: drv}, nil -} - -// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls -// from the internal builders. Should be called only by the internal builders. -func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil } - -// Dialect returns the dialect of the driver we started the transaction from. -func (tx *txDriver) Dialect() string { return tx.drv.Dialect() } - -// Close is a nop close. -func (*txDriver) Close() error { return nil } - -// Commit is a nop commit for the internal builders. -// User must call `Tx.Commit` in order to commit the transaction. -func (*txDriver) Commit() error { return nil } - -// Rollback is a nop rollback for the internal builders. -// User must call `Tx.Rollback` in order to rollback the transaction. -func (*txDriver) Rollback() error { return nil } - -// Exec calls tx.Exec. -func (tx *txDriver) Exec(ctx context.Context, query string, args, v any) error { - return tx.tx.Exec(ctx, query, args, v) -} - -// Query calls tx.Query. -func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error { - return tx.tx.Query(ctx, query, args, v) -} - -var _ dialect.Driver = (*txDriver)(nil) diff --git a/ent/user.go b/ent/user.go deleted file mode 100644 index 3bf0ad7..0000000 --- a/ent/user.go +++ /dev/null @@ -1,91 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "fmt" - "strings" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "git.dcentral.systems/toolz/goplt/ent/user" -) - -// User is the model entity for the User schema. -type User struct { - config - // ID of the ent. - ID int `json:"id,omitempty"` - selectValues sql.SelectValues -} - -// scanValues returns the types for scanning values from sql.Rows. -func (*User) scanValues(columns []string) ([]any, error) { - values := make([]any, len(columns)) - for i := range columns { - switch columns[i] { - case user.FieldID: - values[i] = new(sql.NullInt64) - default: - values[i] = new(sql.UnknownType) - } - } - return values, nil -} - -// assignValues assigns the values that were returned from sql.Rows (after scanning) -// to the User fields. -func (_m *User) assignValues(columns []string, values []any) error { - if m, n := len(values), len(columns); m < n { - return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) - } - for i := range columns { - switch columns[i] { - case user.FieldID: - value, ok := values[i].(*sql.NullInt64) - if !ok { - return fmt.Errorf("unexpected type %T for field id", value) - } - _m.ID = int(value.Int64) - default: - _m.selectValues.Set(columns[i], values[i]) - } - } - return nil -} - -// Value returns the ent.Value that was dynamically selected and assigned to the User. -// This includes values selected through modifiers, order, etc. -func (_m *User) Value(name string) (ent.Value, error) { - return _m.selectValues.Get(name) -} - -// Update returns a builder for updating this User. -// Note that you need to call User.Unwrap() before calling this method if this User -// was returned from a transaction, and the transaction was committed or rolled back. -func (_m *User) Update() *UserUpdateOne { - return NewUserClient(_m.config).UpdateOne(_m) -} - -// Unwrap unwraps the User entity that was returned from a transaction after it was closed, -// so that all future queries will be executed through the driver which created the transaction. -func (_m *User) Unwrap() *User { - _tx, ok := _m.config.driver.(*txDriver) - if !ok { - panic("ent: User is not a transactional entity") - } - _m.config.driver = _tx.drv - return _m -} - -// String implements the fmt.Stringer. -func (_m *User) String() string { - var builder strings.Builder - builder.WriteString("User(") - builder.WriteString(fmt.Sprintf("id=%v", _m.ID)) - builder.WriteByte(')') - return builder.String() -} - -// Users is a parsable slice of User. -type Users []*User diff --git a/ent/user/user.go b/ent/user/user.go deleted file mode 100644 index da6bed9..0000000 --- a/ent/user/user.go +++ /dev/null @@ -1,39 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package user - -import ( - "entgo.io/ent/dialect/sql" -) - -const ( - // Label holds the string label denoting the user type in the database. - Label = "user" - // FieldID holds the string denoting the id field in the database. - FieldID = "id" - // Table holds the table name of the user in the database. - Table = "users" -) - -// Columns holds all SQL columns for user fields. -var Columns = []string{ - FieldID, -} - -// ValidColumn reports if the column name is valid (part of the table columns). -func ValidColumn(column string) bool { - for i := range Columns { - if column == Columns[i] { - return true - } - } - return false -} - -// OrderOption defines the ordering options for the User queries. -type OrderOption func(*sql.Selector) - -// ByID orders the results by the id field. -func ByID(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldID, opts...).ToFunc() -} diff --git a/ent/user/where.go b/ent/user/where.go deleted file mode 100644 index 5933ebd..0000000 --- a/ent/user/where.go +++ /dev/null @@ -1,68 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package user - -import ( - "entgo.io/ent/dialect/sql" - "git.dcentral.systems/toolz/goplt/ent/predicate" -) - -// ID filters vertices based on their ID field. -func ID(id int) predicate.User { - return predicate.User(sql.FieldEQ(FieldID, id)) -} - -// IDEQ applies the EQ predicate on the ID field. -func IDEQ(id int) predicate.User { - return predicate.User(sql.FieldEQ(FieldID, id)) -} - -// IDNEQ applies the NEQ predicate on the ID field. -func IDNEQ(id int) predicate.User { - return predicate.User(sql.FieldNEQ(FieldID, id)) -} - -// IDIn applies the In predicate on the ID field. -func IDIn(ids ...int) predicate.User { - return predicate.User(sql.FieldIn(FieldID, ids...)) -} - -// IDNotIn applies the NotIn predicate on the ID field. -func IDNotIn(ids ...int) predicate.User { - return predicate.User(sql.FieldNotIn(FieldID, ids...)) -} - -// IDGT applies the GT predicate on the ID field. -func IDGT(id int) predicate.User { - return predicate.User(sql.FieldGT(FieldID, id)) -} - -// IDGTE applies the GTE predicate on the ID field. -func IDGTE(id int) predicate.User { - return predicate.User(sql.FieldGTE(FieldID, id)) -} - -// IDLT applies the LT predicate on the ID field. -func IDLT(id int) predicate.User { - return predicate.User(sql.FieldLT(FieldID, id)) -} - -// IDLTE applies the LTE predicate on the ID field. -func IDLTE(id int) predicate.User { - return predicate.User(sql.FieldLTE(FieldID, id)) -} - -// And groups predicates with the AND operator between them. -func And(predicates ...predicate.User) predicate.User { - return predicate.User(sql.AndPredicates(predicates...)) -} - -// Or groups predicates with the OR operator between them. -func Or(predicates ...predicate.User) predicate.User { - return predicate.User(sql.OrPredicates(predicates...)) -} - -// Not applies the not operator on the given predicate. -func Not(p predicate.User) predicate.User { - return predicate.User(sql.NotPredicates(p)) -} diff --git a/ent/user_create.go b/ent/user_create.go deleted file mode 100644 index a6ad074..0000000 --- a/ent/user_create.go +++ /dev/null @@ -1,169 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "fmt" - - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/ent/user" -) - -// UserCreate is the builder for creating a User entity. -type UserCreate struct { - config - mutation *UserMutation - hooks []Hook -} - -// Mutation returns the UserMutation object of the builder. -func (_c *UserCreate) Mutation() *UserMutation { - return _c.mutation -} - -// Save creates the User in the database. -func (_c *UserCreate) Save(ctx context.Context) (*User, error) { - return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) -} - -// SaveX calls Save and panics if Save returns an error. -func (_c *UserCreate) SaveX(ctx context.Context) *User { - v, err := _c.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (_c *UserCreate) Exec(ctx context.Context) error { - _, err := _c.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_c *UserCreate) ExecX(ctx context.Context) { - if err := _c.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (_c *UserCreate) check() error { - return nil -} - -func (_c *UserCreate) sqlSave(ctx context.Context) (*User, error) { - if err := _c.check(); err != nil { - return nil, err - } - _node, _spec := _c.createSpec() - if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - id := _spec.ID.Value.(int64) - _node.ID = int(id) - _c.mutation.id = &_node.ID - _c.mutation.done = true - return _node, nil -} - -func (_c *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) { - var ( - _node = &User{config: _c.config} - _spec = sqlgraph.NewCreateSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt)) - ) - return _node, _spec -} - -// UserCreateBulk is the builder for creating many User entities in bulk. -type UserCreateBulk struct { - config - err error - builders []*UserCreate -} - -// Save creates the User entities in the database. -func (_c *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { - if _c.err != nil { - return nil, _c.err - } - specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) - nodes := make([]*User, len(_c.builders)) - mutators := make([]Mutator, len(_c.builders)) - for i := range _c.builders { - func(i int, root context.Context) { - builder := _c.builders[i] - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*UserMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err := builder.check(); err != nil { - return nil, err - } - builder.mutation = mutation - var err error - nodes[i], specs[i] = builder.createSpec() - if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) - } else { - spec := &sqlgraph.BatchCreateSpec{Nodes: specs} - // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - } - } - if err != nil { - return nil, err - } - mutation.id = &nodes[i].ID - if specs[i].ID.Value != nil { - id := specs[i].ID.Value.(int64) - nodes[i].ID = int(id) - } - mutation.done = true - return nodes[i], nil - }) - for i := len(builder.hooks) - 1; i >= 0; i-- { - mut = builder.hooks[i](mut) - } - mutators[i] = mut - }(i, ctx) - } - if len(mutators) > 0 { - if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { - return nil, err - } - } - return nodes, nil -} - -// SaveX is like Save, but panics if an error occurs. -func (_c *UserCreateBulk) SaveX(ctx context.Context) []*User { - v, err := _c.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (_c *UserCreateBulk) Exec(ctx context.Context) error { - _, err := _c.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_c *UserCreateBulk) ExecX(ctx context.Context) { - if err := _c.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/ent/user_delete.go b/ent/user_delete.go deleted file mode 100644 index 1d0d762..0000000 --- a/ent/user_delete.go +++ /dev/null @@ -1,88 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/ent/predicate" - "git.dcentral.systems/toolz/goplt/ent/user" -) - -// UserDelete is the builder for deleting a User entity. -type UserDelete struct { - config - hooks []Hook - mutation *UserMutation -} - -// Where appends a list predicates to the UserDelete builder. -func (_d *UserDelete) Where(ps ...predicate.User) *UserDelete { - _d.mutation.Where(ps...) - return _d -} - -// Exec executes the deletion query and returns how many vertices were deleted. -func (_d *UserDelete) Exec(ctx context.Context) (int, error) { - return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) -} - -// ExecX is like Exec, but panics if an error occurs. -func (_d *UserDelete) ExecX(ctx context.Context) int { - n, err := _d.Exec(ctx) - if err != nil { - panic(err) - } - return n -} - -func (_d *UserDelete) sqlExec(ctx context.Context) (int, error) { - _spec := sqlgraph.NewDeleteSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt)) - if ps := _d.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) - if err != nil && sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - _d.mutation.done = true - return affected, err -} - -// UserDeleteOne is the builder for deleting a single User entity. -type UserDeleteOne struct { - _d *UserDelete -} - -// Where appends a list predicates to the UserDelete builder. -func (_d *UserDeleteOne) Where(ps ...predicate.User) *UserDeleteOne { - _d._d.mutation.Where(ps...) - return _d -} - -// Exec executes the deletion query. -func (_d *UserDeleteOne) Exec(ctx context.Context) error { - n, err := _d._d.Exec(ctx) - switch { - case err != nil: - return err - case n == 0: - return &NotFoundError{user.Label} - default: - return nil - } -} - -// ExecX is like Exec, but panics if an error occurs. -func (_d *UserDeleteOne) ExecX(ctx context.Context) { - if err := _d.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/ent/user_query.go b/ent/user_query.go deleted file mode 100644 index ff22528..0000000 --- a/ent/user_query.go +++ /dev/null @@ -1,505 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "fmt" - "math" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/ent/predicate" - "git.dcentral.systems/toolz/goplt/ent/user" -) - -// UserQuery is the builder for querying User entities. -type UserQuery struct { - config - ctx *QueryContext - order []user.OrderOption - inters []Interceptor - predicates []predicate.User - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Where adds a new predicate for the UserQuery builder. -func (_q *UserQuery) Where(ps ...predicate.User) *UserQuery { - _q.predicates = append(_q.predicates, ps...) - return _q -} - -// Limit the number of records to be returned by this query. -func (_q *UserQuery) Limit(limit int) *UserQuery { - _q.ctx.Limit = &limit - return _q -} - -// Offset to start from. -func (_q *UserQuery) Offset(offset int) *UserQuery { - _q.ctx.Offset = &offset - return _q -} - -// Unique configures the query builder to filter duplicate records on query. -// By default, unique is set to true, and can be disabled using this method. -func (_q *UserQuery) Unique(unique bool) *UserQuery { - _q.ctx.Unique = &unique - return _q -} - -// Order specifies how the records should be ordered. -func (_q *UserQuery) Order(o ...user.OrderOption) *UserQuery { - _q.order = append(_q.order, o...) - return _q -} - -// First returns the first User entity from the query. -// Returns a *NotFoundError when no User was found. -func (_q *UserQuery) First(ctx context.Context) (*User, error) { - nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{user.Label} - } - return nodes[0], nil -} - -// FirstX is like First, but panics if an error occurs. -func (_q *UserQuery) FirstX(ctx context.Context) *User { - node, err := _q.First(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// FirstID returns the first User ID from the query. -// Returns a *NotFoundError when no User ID was found. -func (_q *UserQuery) FirstID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{user.Label} - return - } - return ids[0], nil -} - -// FirstIDX is like FirstID, but panics if an error occurs. -func (_q *UserQuery) FirstIDX(ctx context.Context) int { - id, err := _q.FirstID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Only returns a single User entity found by the query, ensuring it only returns one. -// Returns a *NotSingularError when more than one User entity is found. -// Returns a *NotFoundError when no User entities are found. -func (_q *UserQuery) Only(ctx context.Context) (*User, error) { - nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) - if err != nil { - return nil, err - } - switch len(nodes) { - case 1: - return nodes[0], nil - case 0: - return nil, &NotFoundError{user.Label} - default: - return nil, &NotSingularError{user.Label} - } -} - -// OnlyX is like Only, but panics if an error occurs. -func (_q *UserQuery) OnlyX(ctx context.Context) *User { - node, err := _q.Only(ctx) - if err != nil { - panic(err) - } - return node -} - -// OnlyID is like Only, but returns the only User ID in the query. -// Returns a *NotSingularError when more than one User ID is found. -// Returns a *NotFoundError when no entities are found. -func (_q *UserQuery) OnlyID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { - return - } - switch len(ids) { - case 1: - id = ids[0] - case 0: - err = &NotFoundError{user.Label} - default: - err = &NotSingularError{user.Label} - } - return -} - -// OnlyIDX is like OnlyID, but panics if an error occurs. -func (_q *UserQuery) OnlyIDX(ctx context.Context) int { - id, err := _q.OnlyID(ctx) - if err != nil { - panic(err) - } - return id -} - -// All executes the query and returns a list of Users. -func (_q *UserQuery) All(ctx context.Context) ([]*User, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) - if err := _q.prepareQuery(ctx); err != nil { - return nil, err - } - qr := querierAll[[]*User, *UserQuery]() - return withInterceptors[[]*User](ctx, _q, qr, _q.inters) -} - -// AllX is like All, but panics if an error occurs. -func (_q *UserQuery) AllX(ctx context.Context) []*User { - nodes, err := _q.All(ctx) - if err != nil { - panic(err) - } - return nodes -} - -// IDs executes the query and returns a list of User IDs. -func (_q *UserQuery) IDs(ctx context.Context) (ids []int, err error) { - if _q.ctx.Unique == nil && _q.path != nil { - _q.Unique(true) - } - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) - if err = _q.Select(user.FieldID).Scan(ctx, &ids); err != nil { - return nil, err - } - return ids, nil -} - -// IDsX is like IDs, but panics if an error occurs. -func (_q *UserQuery) IDsX(ctx context.Context) []int { - ids, err := _q.IDs(ctx) - if err != nil { - panic(err) - } - return ids -} - -// Count returns the count of the given query. -func (_q *UserQuery) Count(ctx context.Context) (int, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) - if err := _q.prepareQuery(ctx); err != nil { - return 0, err - } - return withInterceptors[int](ctx, _q, querierCount[*UserQuery](), _q.inters) -} - -// CountX is like Count, but panics if an error occurs. -func (_q *UserQuery) CountX(ctx context.Context) int { - count, err := _q.Count(ctx) - if err != nil { - panic(err) - } - return count -} - -// Exist returns true if the query has elements in the graph. -func (_q *UserQuery) Exist(ctx context.Context) (bool, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) - switch _, err := _q.FirstID(ctx); { - case IsNotFound(err): - return false, nil - case err != nil: - return false, fmt.Errorf("ent: check existence: %w", err) - default: - return true, nil - } -} - -// ExistX is like Exist, but panics if an error occurs. -func (_q *UserQuery) ExistX(ctx context.Context) bool { - exist, err := _q.Exist(ctx) - if err != nil { - panic(err) - } - return exist -} - -// Clone returns a duplicate of the UserQuery builder, including all associated steps. It can be -// used to prepare common query builders and use them differently after the clone is made. -func (_q *UserQuery) Clone() *UserQuery { - if _q == nil { - return nil - } - return &UserQuery{ - config: _q.config, - ctx: _q.ctx.Clone(), - order: append([]user.OrderOption{}, _q.order...), - inters: append([]Interceptor{}, _q.inters...), - predicates: append([]predicate.User{}, _q.predicates...), - // clone intermediate query. - sql: _q.sql.Clone(), - path: _q.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. -func (_q *UserQuery) GroupBy(field string, fields ...string) *UserGroupBy { - _q.ctx.Fields = append([]string{field}, fields...) - grbuild := &UserGroupBy{build: _q} - grbuild.flds = &_q.ctx.Fields - grbuild.label = user.Label - grbuild.scan = grbuild.Scan - return grbuild -} - -// Select allows the selection one or more fields/columns for the given query, -// instead of selecting all fields in the entity. -func (_q *UserQuery) Select(fields ...string) *UserSelect { - _q.ctx.Fields = append(_q.ctx.Fields, fields...) - sbuild := &UserSelect{UserQuery: _q} - sbuild.label = user.Label - sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan - return sbuild -} - -// Aggregate returns a UserSelect configured with the given aggregations. -func (_q *UserQuery) Aggregate(fns ...AggregateFunc) *UserSelect { - return _q.Select().Aggregate(fns...) -} - -func (_q *UserQuery) prepareQuery(ctx context.Context) error { - for _, inter := range _q.inters { - if inter == nil { - return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") - } - if trv, ok := inter.(Traverser); ok { - if err := trv.Traverse(ctx, _q); err != nil { - return err - } - } - } - for _, f := range _q.ctx.Fields { - if !user.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} - } - } - if _q.path != nil { - prev, err := _q.path(ctx) - if err != nil { - return err - } - _q.sql = prev - } - return nil -} - -func (_q *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, error) { - var ( - nodes = []*User{} - _spec = _q.querySpec() - ) - _spec.ScanValues = func(columns []string) ([]any, error) { - return (*User).scanValues(nil, columns) - } - _spec.Assign = func(columns []string, values []any) error { - node := &User{config: _q.config} - nodes = append(nodes, node) - return node.assignValues(columns, values) - } - for i := range hooks { - hooks[i](ctx, _spec) - } - if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { - return nil, err - } - if len(nodes) == 0 { - return nodes, nil - } - return nodes, nil -} - -func (_q *UserQuery) sqlCount(ctx context.Context) (int, error) { - _spec := _q.querySpec() - _spec.Node.Columns = _q.ctx.Fields - if len(_q.ctx.Fields) > 0 { - _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique - } - return sqlgraph.CountNodes(ctx, _q.driver, _spec) -} - -func (_q *UserQuery) querySpec() *sqlgraph.QuerySpec { - _spec := sqlgraph.NewQuerySpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt)) - _spec.From = _q.sql - if unique := _q.ctx.Unique; unique != nil { - _spec.Unique = *unique - } else if _q.path != nil { - _spec.Unique = true - } - if fields := _q.ctx.Fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, user.FieldID) - for i := range fields { - if fields[i] != user.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) - } - } - } - if ps := _q.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if limit := _q.ctx.Limit; limit != nil { - _spec.Limit = *limit - } - if offset := _q.ctx.Offset; offset != nil { - _spec.Offset = *offset - } - if ps := _q.order; len(ps) > 0 { - _spec.Order = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return _spec -} - -func (_q *UserQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(_q.driver.Dialect()) - t1 := builder.Table(user.Table) - columns := _q.ctx.Fields - if len(columns) == 0 { - columns = user.Columns - } - selector := builder.Select(t1.Columns(columns...)...).From(t1) - if _q.sql != nil { - selector = _q.sql - selector.Select(selector.Columns(columns...)...) - } - if _q.ctx.Unique != nil && *_q.ctx.Unique { - selector.Distinct() - } - for _, p := range _q.predicates { - p(selector) - } - for _, p := range _q.order { - p(selector) - } - if offset := _q.ctx.Offset; offset != nil { - // limit is mandatory for offset clause. We start - // with default value, and override it below if needed. - selector.Offset(*offset).Limit(math.MaxInt32) - } - if limit := _q.ctx.Limit; limit != nil { - selector.Limit(*limit) - } - return selector -} - -// UserGroupBy is the group-by builder for User entities. -type UserGroupBy struct { - selector - build *UserQuery -} - -// Aggregate adds the given aggregation functions to the group-by query. -func (_g *UserGroupBy) Aggregate(fns ...AggregateFunc) *UserGroupBy { - _g.fns = append(_g.fns, fns...) - return _g -} - -// Scan applies the selector query and scans the result into the given value. -func (_g *UserGroupBy) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) - if err := _g.build.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*UserQuery, *UserGroupBy](ctx, _g.build, _g, _g.build.inters, v) -} - -func (_g *UserGroupBy) sqlScan(ctx context.Context, root *UserQuery, v any) error { - selector := root.sqlQuery(ctx).Select() - aggregation := make([]string, 0, len(_g.fns)) - for _, fn := range _g.fns { - aggregation = append(aggregation, fn(selector)) - } - if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) - for _, f := range *_g.flds { - columns = append(columns, selector.C(f)) - } - columns = append(columns, aggregation...) - selector.Select(columns...) - } - selector.GroupBy(selector.Columns(*_g.flds...)...) - if err := selector.Err(); err != nil { - return err - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} - -// UserSelect is the builder for selecting fields of User entities. -type UserSelect struct { - *UserQuery - selector -} - -// Aggregate adds the given aggregation functions to the selector query. -func (_s *UserSelect) Aggregate(fns ...AggregateFunc) *UserSelect { - _s.fns = append(_s.fns, fns...) - return _s -} - -// Scan applies the selector query and scans the result into the given value. -func (_s *UserSelect) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) - if err := _s.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*UserQuery, *UserSelect](ctx, _s.UserQuery, _s, _s.inters, v) -} - -func (_s *UserSelect) sqlScan(ctx context.Context, root *UserQuery, v any) error { - selector := root.sqlQuery(ctx) - aggregation := make([]string, 0, len(_s.fns)) - for _, fn := range _s.fns { - aggregation = append(aggregation, fn(selector)) - } - switch n := len(*_s.selector.flds); { - case n == 0 && len(aggregation) > 0: - selector.Select(aggregation...) - case n != 0 && len(aggregation) > 0: - selector.AppendSelect(aggregation...) - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := _s.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} diff --git a/ent/user_update.go b/ent/user_update.go deleted file mode 100644 index 7f02561..0000000 --- a/ent/user_update.go +++ /dev/null @@ -1,175 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "errors" - "fmt" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/ent/predicate" - "git.dcentral.systems/toolz/goplt/ent/user" -) - -// UserUpdate is the builder for updating User entities. -type UserUpdate struct { - config - hooks []Hook - mutation *UserMutation -} - -// Where appends a list predicates to the UserUpdate builder. -func (_u *UserUpdate) Where(ps ...predicate.User) *UserUpdate { - _u.mutation.Where(ps...) - return _u -} - -// Mutation returns the UserMutation object of the builder. -func (_u *UserUpdate) Mutation() *UserMutation { - return _u.mutation -} - -// Save executes the query and returns the number of nodes affected by the update operation. -func (_u *UserUpdate) Save(ctx context.Context) (int, error) { - return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (_u *UserUpdate) SaveX(ctx context.Context) int { - affected, err := _u.Save(ctx) - if err != nil { - panic(err) - } - return affected -} - -// Exec executes the query. -func (_u *UserUpdate) Exec(ctx context.Context) error { - _, err := _u.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_u *UserUpdate) ExecX(ctx context.Context) { - if err := _u.Exec(ctx); err != nil { - panic(err) - } -} - -func (_u *UserUpdate) sqlSave(ctx context.Context) (_node int, err error) { - _spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt)) - if ps := _u.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{user.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return 0, err - } - _u.mutation.done = true - return _node, nil -} - -// UserUpdateOne is the builder for updating a single User entity. -type UserUpdateOne struct { - config - fields []string - hooks []Hook - mutation *UserMutation -} - -// Mutation returns the UserMutation object of the builder. -func (_u *UserUpdateOne) Mutation() *UserMutation { - return _u.mutation -} - -// Where appends a list predicates to the UserUpdate builder. -func (_u *UserUpdateOne) Where(ps ...predicate.User) *UserUpdateOne { - _u.mutation.Where(ps...) - return _u -} - -// Select allows selecting one or more fields (columns) of the returned entity. -// The default is selecting all fields defined in the entity schema. -func (_u *UserUpdateOne) Select(field string, fields ...string) *UserUpdateOne { - _u.fields = append([]string{field}, fields...) - return _u -} - -// Save executes the query and returns the updated User entity. -func (_u *UserUpdateOne) Save(ctx context.Context) (*User, error) { - return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (_u *UserUpdateOne) SaveX(ctx context.Context) *User { - node, err := _u.Save(ctx) - if err != nil { - panic(err) - } - return node -} - -// Exec executes the query on the entity. -func (_u *UserUpdateOne) Exec(ctx context.Context) error { - _, err := _u.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_u *UserUpdateOne) ExecX(ctx context.Context) { - if err := _u.Exec(ctx); err != nil { - panic(err) - } -} - -func (_u *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) { - _spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt)) - id, ok := _u.mutation.ID() - if !ok { - return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "User.id" for update`)} - } - _spec.Node.ID.Value = id - if fields := _u.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, user.FieldID) - for _, f := range fields { - if !user.ValidColumn(f) { - return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} - } - if f != user.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, f) - } - } - } - if ps := _u.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - _node = &User{config: _u.config} - _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{user.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - _u.mutation.done = true - return _node, nil -} diff --git a/internal/ent/auditlog.go b/internal/ent/auditlog.go deleted file mode 100644 index 3e50ce2..0000000 --- a/internal/ent/auditlog.go +++ /dev/null @@ -1,186 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "encoding/json" - "fmt" - "strings" - "time" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "git.dcentral.systems/toolz/goplt/internal/ent/auditlog" -) - -// AuditLog is the model entity for the AuditLog schema. -type AuditLog struct { - config `json:"-"` - // ID of the ent. - ID string `json:"id,omitempty"` - // ID of the user/actor performing the action - UserID string `json:"user_id,omitempty"` - // Action performed (e.g., user.create, user.update) - Action string `json:"action,omitempty"` - // Resource type (e.g., user, role) - Resource string `json:"resource,omitempty"` - // ID of the target resource - ResourceID string `json:"resource_id,omitempty"` - // IP address of the client - IPAddress string `json:"ip_address,omitempty"` - // User agent of the client - UserAgent string `json:"user_agent,omitempty"` - // Additional metadata as JSON - Metadata map[string]interface{} `json:"metadata,omitempty"` - // Timestamp holds the value of the "timestamp" field. - Timestamp time.Time `json:"timestamp,omitempty"` - selectValues sql.SelectValues -} - -// scanValues returns the types for scanning values from sql.Rows. -func (*AuditLog) scanValues(columns []string) ([]any, error) { - values := make([]any, len(columns)) - for i := range columns { - switch columns[i] { - case auditlog.FieldMetadata: - values[i] = new([]byte) - case auditlog.FieldID, auditlog.FieldUserID, auditlog.FieldAction, auditlog.FieldResource, auditlog.FieldResourceID, auditlog.FieldIPAddress, auditlog.FieldUserAgent: - values[i] = new(sql.NullString) - case auditlog.FieldTimestamp: - values[i] = new(sql.NullTime) - default: - values[i] = new(sql.UnknownType) - } - } - return values, nil -} - -// assignValues assigns the values that were returned from sql.Rows (after scanning) -// to the AuditLog fields. -func (_m *AuditLog) assignValues(columns []string, values []any) error { - if m, n := len(values), len(columns); m < n { - return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) - } - for i := range columns { - switch columns[i] { - case auditlog.FieldID: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field id", values[i]) - } else if value.Valid { - _m.ID = value.String - } - case auditlog.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 { - _m.UserID = value.String - } - case auditlog.FieldAction: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field action", values[i]) - } else if value.Valid { - _m.Action = value.String - } - case auditlog.FieldResource: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field resource", values[i]) - } else if value.Valid { - _m.Resource = value.String - } - case auditlog.FieldResourceID: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field resource_id", values[i]) - } else if value.Valid { - _m.ResourceID = value.String - } - case auditlog.FieldIPAddress: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field ip_address", values[i]) - } else if value.Valid { - _m.IPAddress = value.String - } - case auditlog.FieldUserAgent: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field user_agent", values[i]) - } else if value.Valid { - _m.UserAgent = value.String - } - case auditlog.FieldMetadata: - if value, ok := values[i].(*[]byte); !ok { - return fmt.Errorf("unexpected type %T for field metadata", values[i]) - } else if value != nil && len(*value) > 0 { - if err := json.Unmarshal(*value, &_m.Metadata); err != nil { - return fmt.Errorf("unmarshal field metadata: %w", err) - } - } - case auditlog.FieldTimestamp: - if value, ok := values[i].(*sql.NullTime); !ok { - return fmt.Errorf("unexpected type %T for field timestamp", values[i]) - } else if value.Valid { - _m.Timestamp = value.Time - } - default: - _m.selectValues.Set(columns[i], values[i]) - } - } - return nil -} - -// Value returns the ent.Value that was dynamically selected and assigned to the AuditLog. -// This includes values selected through modifiers, order, etc. -func (_m *AuditLog) Value(name string) (ent.Value, error) { - return _m.selectValues.Get(name) -} - -// Update returns a builder for updating this AuditLog. -// Note that you need to call AuditLog.Unwrap() before calling this method if this AuditLog -// was returned from a transaction, and the transaction was committed or rolled back. -func (_m *AuditLog) Update() *AuditLogUpdateOne { - return NewAuditLogClient(_m.config).UpdateOne(_m) -} - -// Unwrap unwraps the AuditLog entity that was returned from a transaction after it was closed, -// so that all future queries will be executed through the driver which created the transaction. -func (_m *AuditLog) Unwrap() *AuditLog { - _tx, ok := _m.config.driver.(*txDriver) - if !ok { - panic("ent: AuditLog is not a transactional entity") - } - _m.config.driver = _tx.drv - return _m -} - -// String implements the fmt.Stringer. -func (_m *AuditLog) String() string { - var builder strings.Builder - builder.WriteString("AuditLog(") - builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) - builder.WriteString("user_id=") - builder.WriteString(_m.UserID) - builder.WriteString(", ") - builder.WriteString("action=") - builder.WriteString(_m.Action) - builder.WriteString(", ") - builder.WriteString("resource=") - builder.WriteString(_m.Resource) - builder.WriteString(", ") - builder.WriteString("resource_id=") - builder.WriteString(_m.ResourceID) - builder.WriteString(", ") - builder.WriteString("ip_address=") - builder.WriteString(_m.IPAddress) - builder.WriteString(", ") - builder.WriteString("user_agent=") - builder.WriteString(_m.UserAgent) - builder.WriteString(", ") - builder.WriteString("metadata=") - builder.WriteString(fmt.Sprintf("%v", _m.Metadata)) - builder.WriteString(", ") - builder.WriteString("timestamp=") - builder.WriteString(_m.Timestamp.Format(time.ANSIC)) - builder.WriteByte(')') - return builder.String() -} - -// AuditLogs is a parsable slice of AuditLog. -type AuditLogs []*AuditLog diff --git a/internal/ent/auditlog/auditlog.go b/internal/ent/auditlog/auditlog.go deleted file mode 100644 index a178843..0000000 --- a/internal/ent/auditlog/auditlog.go +++ /dev/null @@ -1,109 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package auditlog - -import ( - "time" - - "entgo.io/ent/dialect/sql" -) - -const ( - // Label holds the string label denoting the auditlog type in the database. - Label = "audit_log" - // 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" - // FieldAction holds the string denoting the action field in the database. - FieldAction = "action" - // FieldResource holds the string denoting the resource field in the database. - FieldResource = "resource" - // FieldResourceID holds the string denoting the resource_id field in the database. - FieldResourceID = "resource_id" - // FieldIPAddress holds the string denoting the ip_address field in the database. - FieldIPAddress = "ip_address" - // FieldUserAgent holds the string denoting the user_agent field in the database. - FieldUserAgent = "user_agent" - // FieldMetadata holds the string denoting the metadata field in the database. - FieldMetadata = "metadata" - // FieldTimestamp holds the string denoting the timestamp field in the database. - FieldTimestamp = "timestamp" - // Table holds the table name of the auditlog in the database. - Table = "audit_logs" -) - -// Columns holds all SQL columns for auditlog fields. -var Columns = []string{ - FieldID, - FieldUserID, - FieldAction, - FieldResource, - FieldResourceID, - FieldIPAddress, - FieldUserAgent, - FieldMetadata, - FieldTimestamp, -} - -// 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 - // ActionValidator is a validator for the "action" field. It is called by the builders before save. - ActionValidator func(string) error - // DefaultTimestamp holds the default value on creation for the "timestamp" field. - DefaultTimestamp func() time.Time -) - -// OrderOption defines the ordering options for the AuditLog queries. -type OrderOption func(*sql.Selector) - -// ByID orders the results by the id field. -func ByID(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldID, opts...).ToFunc() -} - -// ByUserID orders the results by the user_id field. -func ByUserID(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldUserID, opts...).ToFunc() -} - -// ByAction orders the results by the action field. -func ByAction(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldAction, opts...).ToFunc() -} - -// ByResource orders the results by the resource field. -func ByResource(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldResource, opts...).ToFunc() -} - -// ByResourceID orders the results by the resource_id field. -func ByResourceID(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldResourceID, opts...).ToFunc() -} - -// ByIPAddress orders the results by the ip_address field. -func ByIPAddress(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldIPAddress, opts...).ToFunc() -} - -// ByUserAgent orders the results by the user_agent field. -func ByUserAgent(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldUserAgent, opts...).ToFunc() -} - -// ByTimestamp orders the results by the timestamp field. -func ByTimestamp(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldTimestamp, opts...).ToFunc() -} diff --git a/internal/ent/auditlog/where.go b/internal/ent/auditlog/where.go deleted file mode 100644 index 62aa279..0000000 --- a/internal/ent/auditlog/where.go +++ /dev/null @@ -1,595 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package auditlog - -import ( - "time" - - "entgo.io/ent/dialect/sql" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" -) - -// ID filters vertices based on their ID field. -func ID(id string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldEQ(FieldID, id)) -} - -// IDEQ applies the EQ predicate on the ID field. -func IDEQ(id string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldEQ(FieldID, id)) -} - -// IDNEQ applies the NEQ predicate on the ID field. -func IDNEQ(id string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldNEQ(FieldID, id)) -} - -// IDIn applies the In predicate on the ID field. -func IDIn(ids ...string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldIn(FieldID, ids...)) -} - -// IDNotIn applies the NotIn predicate on the ID field. -func IDNotIn(ids ...string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldNotIn(FieldID, ids...)) -} - -// IDGT applies the GT predicate on the ID field. -func IDGT(id string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldGT(FieldID, id)) -} - -// IDGTE applies the GTE predicate on the ID field. -func IDGTE(id string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldGTE(FieldID, id)) -} - -// IDLT applies the LT predicate on the ID field. -func IDLT(id string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldLT(FieldID, id)) -} - -// IDLTE applies the LTE predicate on the ID field. -func IDLTE(id string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldLTE(FieldID, id)) -} - -// IDEqualFold applies the EqualFold predicate on the ID field. -func IDEqualFold(id string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldEqualFold(FieldID, id)) -} - -// IDContainsFold applies the ContainsFold predicate on the ID field. -func IDContainsFold(id string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldContainsFold(FieldID, id)) -} - -// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. -func UserID(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldEQ(FieldUserID, v)) -} - -// Action applies equality check predicate on the "action" field. It's identical to ActionEQ. -func Action(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldEQ(FieldAction, v)) -} - -// Resource applies equality check predicate on the "resource" field. It's identical to ResourceEQ. -func Resource(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldEQ(FieldResource, v)) -} - -// ResourceID applies equality check predicate on the "resource_id" field. It's identical to ResourceIDEQ. -func ResourceID(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldEQ(FieldResourceID, v)) -} - -// IPAddress applies equality check predicate on the "ip_address" field. It's identical to IPAddressEQ. -func IPAddress(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldEQ(FieldIPAddress, v)) -} - -// UserAgent applies equality check predicate on the "user_agent" field. It's identical to UserAgentEQ. -func UserAgent(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldEQ(FieldUserAgent, v)) -} - -// Timestamp applies equality check predicate on the "timestamp" field. It's identical to TimestampEQ. -func Timestamp(v time.Time) predicate.AuditLog { - return predicate.AuditLog(sql.FieldEQ(FieldTimestamp, v)) -} - -// UserIDEQ applies the EQ predicate on the "user_id" field. -func UserIDEQ(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldEQ(FieldUserID, v)) -} - -// UserIDNEQ applies the NEQ predicate on the "user_id" field. -func UserIDNEQ(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldNEQ(FieldUserID, v)) -} - -// UserIDIn applies the In predicate on the "user_id" field. -func UserIDIn(vs ...string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldIn(FieldUserID, vs...)) -} - -// UserIDNotIn applies the NotIn predicate on the "user_id" field. -func UserIDNotIn(vs ...string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldNotIn(FieldUserID, vs...)) -} - -// UserIDGT applies the GT predicate on the "user_id" field. -func UserIDGT(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldGT(FieldUserID, v)) -} - -// UserIDGTE applies the GTE predicate on the "user_id" field. -func UserIDGTE(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldGTE(FieldUserID, v)) -} - -// UserIDLT applies the LT predicate on the "user_id" field. -func UserIDLT(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldLT(FieldUserID, v)) -} - -// UserIDLTE applies the LTE predicate on the "user_id" field. -func UserIDLTE(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldLTE(FieldUserID, v)) -} - -// UserIDContains applies the Contains predicate on the "user_id" field. -func UserIDContains(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldContains(FieldUserID, v)) -} - -// UserIDHasPrefix applies the HasPrefix predicate on the "user_id" field. -func UserIDHasPrefix(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldHasPrefix(FieldUserID, v)) -} - -// UserIDHasSuffix applies the HasSuffix predicate on the "user_id" field. -func UserIDHasSuffix(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldHasSuffix(FieldUserID, v)) -} - -// UserIDEqualFold applies the EqualFold predicate on the "user_id" field. -func UserIDEqualFold(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldEqualFold(FieldUserID, v)) -} - -// UserIDContainsFold applies the ContainsFold predicate on the "user_id" field. -func UserIDContainsFold(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldContainsFold(FieldUserID, v)) -} - -// ActionEQ applies the EQ predicate on the "action" field. -func ActionEQ(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldEQ(FieldAction, v)) -} - -// ActionNEQ applies the NEQ predicate on the "action" field. -func ActionNEQ(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldNEQ(FieldAction, v)) -} - -// ActionIn applies the In predicate on the "action" field. -func ActionIn(vs ...string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldIn(FieldAction, vs...)) -} - -// ActionNotIn applies the NotIn predicate on the "action" field. -func ActionNotIn(vs ...string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldNotIn(FieldAction, vs...)) -} - -// ActionGT applies the GT predicate on the "action" field. -func ActionGT(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldGT(FieldAction, v)) -} - -// ActionGTE applies the GTE predicate on the "action" field. -func ActionGTE(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldGTE(FieldAction, v)) -} - -// ActionLT applies the LT predicate on the "action" field. -func ActionLT(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldLT(FieldAction, v)) -} - -// ActionLTE applies the LTE predicate on the "action" field. -func ActionLTE(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldLTE(FieldAction, v)) -} - -// ActionContains applies the Contains predicate on the "action" field. -func ActionContains(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldContains(FieldAction, v)) -} - -// ActionHasPrefix applies the HasPrefix predicate on the "action" field. -func ActionHasPrefix(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldHasPrefix(FieldAction, v)) -} - -// ActionHasSuffix applies the HasSuffix predicate on the "action" field. -func ActionHasSuffix(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldHasSuffix(FieldAction, v)) -} - -// ActionEqualFold applies the EqualFold predicate on the "action" field. -func ActionEqualFold(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldEqualFold(FieldAction, v)) -} - -// ActionContainsFold applies the ContainsFold predicate on the "action" field. -func ActionContainsFold(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldContainsFold(FieldAction, v)) -} - -// ResourceEQ applies the EQ predicate on the "resource" field. -func ResourceEQ(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldEQ(FieldResource, v)) -} - -// ResourceNEQ applies the NEQ predicate on the "resource" field. -func ResourceNEQ(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldNEQ(FieldResource, v)) -} - -// ResourceIn applies the In predicate on the "resource" field. -func ResourceIn(vs ...string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldIn(FieldResource, vs...)) -} - -// ResourceNotIn applies the NotIn predicate on the "resource" field. -func ResourceNotIn(vs ...string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldNotIn(FieldResource, vs...)) -} - -// ResourceGT applies the GT predicate on the "resource" field. -func ResourceGT(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldGT(FieldResource, v)) -} - -// ResourceGTE applies the GTE predicate on the "resource" field. -func ResourceGTE(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldGTE(FieldResource, v)) -} - -// ResourceLT applies the LT predicate on the "resource" field. -func ResourceLT(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldLT(FieldResource, v)) -} - -// ResourceLTE applies the LTE predicate on the "resource" field. -func ResourceLTE(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldLTE(FieldResource, v)) -} - -// ResourceContains applies the Contains predicate on the "resource" field. -func ResourceContains(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldContains(FieldResource, v)) -} - -// ResourceHasPrefix applies the HasPrefix predicate on the "resource" field. -func ResourceHasPrefix(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldHasPrefix(FieldResource, v)) -} - -// ResourceHasSuffix applies the HasSuffix predicate on the "resource" field. -func ResourceHasSuffix(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldHasSuffix(FieldResource, v)) -} - -// ResourceIsNil applies the IsNil predicate on the "resource" field. -func ResourceIsNil() predicate.AuditLog { - return predicate.AuditLog(sql.FieldIsNull(FieldResource)) -} - -// ResourceNotNil applies the NotNil predicate on the "resource" field. -func ResourceNotNil() predicate.AuditLog { - return predicate.AuditLog(sql.FieldNotNull(FieldResource)) -} - -// ResourceEqualFold applies the EqualFold predicate on the "resource" field. -func ResourceEqualFold(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldEqualFold(FieldResource, v)) -} - -// ResourceContainsFold applies the ContainsFold predicate on the "resource" field. -func ResourceContainsFold(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldContainsFold(FieldResource, v)) -} - -// ResourceIDEQ applies the EQ predicate on the "resource_id" field. -func ResourceIDEQ(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldEQ(FieldResourceID, v)) -} - -// ResourceIDNEQ applies the NEQ predicate on the "resource_id" field. -func ResourceIDNEQ(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldNEQ(FieldResourceID, v)) -} - -// ResourceIDIn applies the In predicate on the "resource_id" field. -func ResourceIDIn(vs ...string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldIn(FieldResourceID, vs...)) -} - -// ResourceIDNotIn applies the NotIn predicate on the "resource_id" field. -func ResourceIDNotIn(vs ...string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldNotIn(FieldResourceID, vs...)) -} - -// ResourceIDGT applies the GT predicate on the "resource_id" field. -func ResourceIDGT(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldGT(FieldResourceID, v)) -} - -// ResourceIDGTE applies the GTE predicate on the "resource_id" field. -func ResourceIDGTE(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldGTE(FieldResourceID, v)) -} - -// ResourceIDLT applies the LT predicate on the "resource_id" field. -func ResourceIDLT(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldLT(FieldResourceID, v)) -} - -// ResourceIDLTE applies the LTE predicate on the "resource_id" field. -func ResourceIDLTE(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldLTE(FieldResourceID, v)) -} - -// ResourceIDContains applies the Contains predicate on the "resource_id" field. -func ResourceIDContains(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldContains(FieldResourceID, v)) -} - -// ResourceIDHasPrefix applies the HasPrefix predicate on the "resource_id" field. -func ResourceIDHasPrefix(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldHasPrefix(FieldResourceID, v)) -} - -// ResourceIDHasSuffix applies the HasSuffix predicate on the "resource_id" field. -func ResourceIDHasSuffix(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldHasSuffix(FieldResourceID, v)) -} - -// ResourceIDIsNil applies the IsNil predicate on the "resource_id" field. -func ResourceIDIsNil() predicate.AuditLog { - return predicate.AuditLog(sql.FieldIsNull(FieldResourceID)) -} - -// ResourceIDNotNil applies the NotNil predicate on the "resource_id" field. -func ResourceIDNotNil() predicate.AuditLog { - return predicate.AuditLog(sql.FieldNotNull(FieldResourceID)) -} - -// ResourceIDEqualFold applies the EqualFold predicate on the "resource_id" field. -func ResourceIDEqualFold(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldEqualFold(FieldResourceID, v)) -} - -// ResourceIDContainsFold applies the ContainsFold predicate on the "resource_id" field. -func ResourceIDContainsFold(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldContainsFold(FieldResourceID, v)) -} - -// IPAddressEQ applies the EQ predicate on the "ip_address" field. -func IPAddressEQ(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldEQ(FieldIPAddress, v)) -} - -// IPAddressNEQ applies the NEQ predicate on the "ip_address" field. -func IPAddressNEQ(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldNEQ(FieldIPAddress, v)) -} - -// IPAddressIn applies the In predicate on the "ip_address" field. -func IPAddressIn(vs ...string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldIn(FieldIPAddress, vs...)) -} - -// IPAddressNotIn applies the NotIn predicate on the "ip_address" field. -func IPAddressNotIn(vs ...string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldNotIn(FieldIPAddress, vs...)) -} - -// IPAddressGT applies the GT predicate on the "ip_address" field. -func IPAddressGT(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldGT(FieldIPAddress, v)) -} - -// IPAddressGTE applies the GTE predicate on the "ip_address" field. -func IPAddressGTE(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldGTE(FieldIPAddress, v)) -} - -// IPAddressLT applies the LT predicate on the "ip_address" field. -func IPAddressLT(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldLT(FieldIPAddress, v)) -} - -// IPAddressLTE applies the LTE predicate on the "ip_address" field. -func IPAddressLTE(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldLTE(FieldIPAddress, v)) -} - -// IPAddressContains applies the Contains predicate on the "ip_address" field. -func IPAddressContains(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldContains(FieldIPAddress, v)) -} - -// IPAddressHasPrefix applies the HasPrefix predicate on the "ip_address" field. -func IPAddressHasPrefix(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldHasPrefix(FieldIPAddress, v)) -} - -// IPAddressHasSuffix applies the HasSuffix predicate on the "ip_address" field. -func IPAddressHasSuffix(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldHasSuffix(FieldIPAddress, v)) -} - -// IPAddressIsNil applies the IsNil predicate on the "ip_address" field. -func IPAddressIsNil() predicate.AuditLog { - return predicate.AuditLog(sql.FieldIsNull(FieldIPAddress)) -} - -// IPAddressNotNil applies the NotNil predicate on the "ip_address" field. -func IPAddressNotNil() predicate.AuditLog { - return predicate.AuditLog(sql.FieldNotNull(FieldIPAddress)) -} - -// IPAddressEqualFold applies the EqualFold predicate on the "ip_address" field. -func IPAddressEqualFold(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldEqualFold(FieldIPAddress, v)) -} - -// IPAddressContainsFold applies the ContainsFold predicate on the "ip_address" field. -func IPAddressContainsFold(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldContainsFold(FieldIPAddress, v)) -} - -// UserAgentEQ applies the EQ predicate on the "user_agent" field. -func UserAgentEQ(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldEQ(FieldUserAgent, v)) -} - -// UserAgentNEQ applies the NEQ predicate on the "user_agent" field. -func UserAgentNEQ(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldNEQ(FieldUserAgent, v)) -} - -// UserAgentIn applies the In predicate on the "user_agent" field. -func UserAgentIn(vs ...string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldIn(FieldUserAgent, vs...)) -} - -// UserAgentNotIn applies the NotIn predicate on the "user_agent" field. -func UserAgentNotIn(vs ...string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldNotIn(FieldUserAgent, vs...)) -} - -// UserAgentGT applies the GT predicate on the "user_agent" field. -func UserAgentGT(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldGT(FieldUserAgent, v)) -} - -// UserAgentGTE applies the GTE predicate on the "user_agent" field. -func UserAgentGTE(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldGTE(FieldUserAgent, v)) -} - -// UserAgentLT applies the LT predicate on the "user_agent" field. -func UserAgentLT(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldLT(FieldUserAgent, v)) -} - -// UserAgentLTE applies the LTE predicate on the "user_agent" field. -func UserAgentLTE(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldLTE(FieldUserAgent, v)) -} - -// UserAgentContains applies the Contains predicate on the "user_agent" field. -func UserAgentContains(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldContains(FieldUserAgent, v)) -} - -// UserAgentHasPrefix applies the HasPrefix predicate on the "user_agent" field. -func UserAgentHasPrefix(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldHasPrefix(FieldUserAgent, v)) -} - -// UserAgentHasSuffix applies the HasSuffix predicate on the "user_agent" field. -func UserAgentHasSuffix(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldHasSuffix(FieldUserAgent, v)) -} - -// UserAgentIsNil applies the IsNil predicate on the "user_agent" field. -func UserAgentIsNil() predicate.AuditLog { - return predicate.AuditLog(sql.FieldIsNull(FieldUserAgent)) -} - -// UserAgentNotNil applies the NotNil predicate on the "user_agent" field. -func UserAgentNotNil() predicate.AuditLog { - return predicate.AuditLog(sql.FieldNotNull(FieldUserAgent)) -} - -// UserAgentEqualFold applies the EqualFold predicate on the "user_agent" field. -func UserAgentEqualFold(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldEqualFold(FieldUserAgent, v)) -} - -// UserAgentContainsFold applies the ContainsFold predicate on the "user_agent" field. -func UserAgentContainsFold(v string) predicate.AuditLog { - return predicate.AuditLog(sql.FieldContainsFold(FieldUserAgent, v)) -} - -// MetadataIsNil applies the IsNil predicate on the "metadata" field. -func MetadataIsNil() predicate.AuditLog { - return predicate.AuditLog(sql.FieldIsNull(FieldMetadata)) -} - -// MetadataNotNil applies the NotNil predicate on the "metadata" field. -func MetadataNotNil() predicate.AuditLog { - return predicate.AuditLog(sql.FieldNotNull(FieldMetadata)) -} - -// TimestampEQ applies the EQ predicate on the "timestamp" field. -func TimestampEQ(v time.Time) predicate.AuditLog { - return predicate.AuditLog(sql.FieldEQ(FieldTimestamp, v)) -} - -// TimestampNEQ applies the NEQ predicate on the "timestamp" field. -func TimestampNEQ(v time.Time) predicate.AuditLog { - return predicate.AuditLog(sql.FieldNEQ(FieldTimestamp, v)) -} - -// TimestampIn applies the In predicate on the "timestamp" field. -func TimestampIn(vs ...time.Time) predicate.AuditLog { - return predicate.AuditLog(sql.FieldIn(FieldTimestamp, vs...)) -} - -// TimestampNotIn applies the NotIn predicate on the "timestamp" field. -func TimestampNotIn(vs ...time.Time) predicate.AuditLog { - return predicate.AuditLog(sql.FieldNotIn(FieldTimestamp, vs...)) -} - -// TimestampGT applies the GT predicate on the "timestamp" field. -func TimestampGT(v time.Time) predicate.AuditLog { - return predicate.AuditLog(sql.FieldGT(FieldTimestamp, v)) -} - -// TimestampGTE applies the GTE predicate on the "timestamp" field. -func TimestampGTE(v time.Time) predicate.AuditLog { - return predicate.AuditLog(sql.FieldGTE(FieldTimestamp, v)) -} - -// TimestampLT applies the LT predicate on the "timestamp" field. -func TimestampLT(v time.Time) predicate.AuditLog { - return predicate.AuditLog(sql.FieldLT(FieldTimestamp, v)) -} - -// TimestampLTE applies the LTE predicate on the "timestamp" field. -func TimestampLTE(v time.Time) predicate.AuditLog { - return predicate.AuditLog(sql.FieldLTE(FieldTimestamp, v)) -} - -// And groups predicates with the AND operator between them. -func And(predicates ...predicate.AuditLog) predicate.AuditLog { - return predicate.AuditLog(sql.AndPredicates(predicates...)) -} - -// Or groups predicates with the OR operator between them. -func Or(predicates ...predicate.AuditLog) predicate.AuditLog { - return predicate.AuditLog(sql.OrPredicates(predicates...)) -} - -// Not applies the not operator on the given predicate. -func Not(p predicate.AuditLog) predicate.AuditLog { - return predicate.AuditLog(sql.NotPredicates(p)) -} diff --git a/internal/ent/auditlog_create.go b/internal/ent/auditlog_create.go deleted file mode 100644 index 283a5b1..0000000 --- a/internal/ent/auditlog_create.go +++ /dev/null @@ -1,331 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "errors" - "fmt" - "time" - - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/internal/ent/auditlog" -) - -// AuditLogCreate is the builder for creating a AuditLog entity. -type AuditLogCreate struct { - config - mutation *AuditLogMutation - hooks []Hook -} - -// SetUserID sets the "user_id" field. -func (_c *AuditLogCreate) SetUserID(v string) *AuditLogCreate { - _c.mutation.SetUserID(v) - return _c -} - -// SetAction sets the "action" field. -func (_c *AuditLogCreate) SetAction(v string) *AuditLogCreate { - _c.mutation.SetAction(v) - return _c -} - -// SetResource sets the "resource" field. -func (_c *AuditLogCreate) SetResource(v string) *AuditLogCreate { - _c.mutation.SetResource(v) - return _c -} - -// SetNillableResource sets the "resource" field if the given value is not nil. -func (_c *AuditLogCreate) SetNillableResource(v *string) *AuditLogCreate { - if v != nil { - _c.SetResource(*v) - } - return _c -} - -// SetResourceID sets the "resource_id" field. -func (_c *AuditLogCreate) SetResourceID(v string) *AuditLogCreate { - _c.mutation.SetResourceID(v) - return _c -} - -// SetNillableResourceID sets the "resource_id" field if the given value is not nil. -func (_c *AuditLogCreate) SetNillableResourceID(v *string) *AuditLogCreate { - if v != nil { - _c.SetResourceID(*v) - } - return _c -} - -// SetIPAddress sets the "ip_address" field. -func (_c *AuditLogCreate) SetIPAddress(v string) *AuditLogCreate { - _c.mutation.SetIPAddress(v) - return _c -} - -// SetNillableIPAddress sets the "ip_address" field if the given value is not nil. -func (_c *AuditLogCreate) SetNillableIPAddress(v *string) *AuditLogCreate { - if v != nil { - _c.SetIPAddress(*v) - } - return _c -} - -// SetUserAgent sets the "user_agent" field. -func (_c *AuditLogCreate) SetUserAgent(v string) *AuditLogCreate { - _c.mutation.SetUserAgent(v) - return _c -} - -// SetNillableUserAgent sets the "user_agent" field if the given value is not nil. -func (_c *AuditLogCreate) SetNillableUserAgent(v *string) *AuditLogCreate { - if v != nil { - _c.SetUserAgent(*v) - } - return _c -} - -// SetMetadata sets the "metadata" field. -func (_c *AuditLogCreate) SetMetadata(v map[string]interface{}) *AuditLogCreate { - _c.mutation.SetMetadata(v) - return _c -} - -// SetTimestamp sets the "timestamp" field. -func (_c *AuditLogCreate) SetTimestamp(v time.Time) *AuditLogCreate { - _c.mutation.SetTimestamp(v) - return _c -} - -// SetNillableTimestamp sets the "timestamp" field if the given value is not nil. -func (_c *AuditLogCreate) SetNillableTimestamp(v *time.Time) *AuditLogCreate { - if v != nil { - _c.SetTimestamp(*v) - } - return _c -} - -// SetID sets the "id" field. -func (_c *AuditLogCreate) SetID(v string) *AuditLogCreate { - _c.mutation.SetID(v) - return _c -} - -// Mutation returns the AuditLogMutation object of the builder. -func (_c *AuditLogCreate) Mutation() *AuditLogMutation { - return _c.mutation -} - -// Save creates the AuditLog in the database. -func (_c *AuditLogCreate) Save(ctx context.Context) (*AuditLog, error) { - _c.defaults() - return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) -} - -// SaveX calls Save and panics if Save returns an error. -func (_c *AuditLogCreate) SaveX(ctx context.Context) *AuditLog { - v, err := _c.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (_c *AuditLogCreate) Exec(ctx context.Context) error { - _, err := _c.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_c *AuditLogCreate) ExecX(ctx context.Context) { - if err := _c.Exec(ctx); err != nil { - panic(err) - } -} - -// defaults sets the default values of the builder before save. -func (_c *AuditLogCreate) defaults() { - if _, ok := _c.mutation.Timestamp(); !ok { - v := auditlog.DefaultTimestamp() - _c.mutation.SetTimestamp(v) - } -} - -// check runs all checks and user-defined validators on the builder. -func (_c *AuditLogCreate) check() error { - if _, ok := _c.mutation.UserID(); !ok { - return &ValidationError{Name: "user_id", err: errors.New(`ent: missing required field "AuditLog.user_id"`)} - } - if v, ok := _c.mutation.UserID(); ok { - if err := auditlog.UserIDValidator(v); err != nil { - return &ValidationError{Name: "user_id", err: fmt.Errorf(`ent: validator failed for field "AuditLog.user_id": %w`, err)} - } - } - if _, ok := _c.mutation.Action(); !ok { - return &ValidationError{Name: "action", err: errors.New(`ent: missing required field "AuditLog.action"`)} - } - if v, ok := _c.mutation.Action(); ok { - if err := auditlog.ActionValidator(v); err != nil { - return &ValidationError{Name: "action", err: fmt.Errorf(`ent: validator failed for field "AuditLog.action": %w`, err)} - } - } - if _, ok := _c.mutation.Timestamp(); !ok { - return &ValidationError{Name: "timestamp", err: errors.New(`ent: missing required field "AuditLog.timestamp"`)} - } - return nil -} - -func (_c *AuditLogCreate) sqlSave(ctx context.Context) (*AuditLog, error) { - if err := _c.check(); err != nil { - return nil, err - } - _node, _spec := _c.createSpec() - if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - if _spec.ID.Value != nil { - if id, ok := _spec.ID.Value.(string); ok { - _node.ID = id - } else { - return nil, fmt.Errorf("unexpected AuditLog.ID type: %T", _spec.ID.Value) - } - } - _c.mutation.id = &_node.ID - _c.mutation.done = true - return _node, nil -} - -func (_c *AuditLogCreate) createSpec() (*AuditLog, *sqlgraph.CreateSpec) { - var ( - _node = &AuditLog{config: _c.config} - _spec = sqlgraph.NewCreateSpec(auditlog.Table, sqlgraph.NewFieldSpec(auditlog.FieldID, field.TypeString)) - ) - if id, ok := _c.mutation.ID(); ok { - _node.ID = id - _spec.ID.Value = id - } - if value, ok := _c.mutation.UserID(); ok { - _spec.SetField(auditlog.FieldUserID, field.TypeString, value) - _node.UserID = value - } - if value, ok := _c.mutation.Action(); ok { - _spec.SetField(auditlog.FieldAction, field.TypeString, value) - _node.Action = value - } - if value, ok := _c.mutation.Resource(); ok { - _spec.SetField(auditlog.FieldResource, field.TypeString, value) - _node.Resource = value - } - if value, ok := _c.mutation.ResourceID(); ok { - _spec.SetField(auditlog.FieldResourceID, field.TypeString, value) - _node.ResourceID = value - } - if value, ok := _c.mutation.IPAddress(); ok { - _spec.SetField(auditlog.FieldIPAddress, field.TypeString, value) - _node.IPAddress = value - } - if value, ok := _c.mutation.UserAgent(); ok { - _spec.SetField(auditlog.FieldUserAgent, field.TypeString, value) - _node.UserAgent = value - } - if value, ok := _c.mutation.Metadata(); ok { - _spec.SetField(auditlog.FieldMetadata, field.TypeJSON, value) - _node.Metadata = value - } - if value, ok := _c.mutation.Timestamp(); ok { - _spec.SetField(auditlog.FieldTimestamp, field.TypeTime, value) - _node.Timestamp = value - } - return _node, _spec -} - -// AuditLogCreateBulk is the builder for creating many AuditLog entities in bulk. -type AuditLogCreateBulk struct { - config - err error - builders []*AuditLogCreate -} - -// Save creates the AuditLog entities in the database. -func (_c *AuditLogCreateBulk) Save(ctx context.Context) ([]*AuditLog, error) { - if _c.err != nil { - return nil, _c.err - } - specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) - nodes := make([]*AuditLog, len(_c.builders)) - mutators := make([]Mutator, len(_c.builders)) - for i := range _c.builders { - func(i int, root context.Context) { - builder := _c.builders[i] - builder.defaults() - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*AuditLogMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err := builder.check(); err != nil { - return nil, err - } - builder.mutation = mutation - var err error - nodes[i], specs[i] = builder.createSpec() - if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) - } else { - spec := &sqlgraph.BatchCreateSpec{Nodes: specs} - // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - } - } - if err != nil { - return nil, err - } - mutation.id = &nodes[i].ID - mutation.done = true - return nodes[i], nil - }) - for i := len(builder.hooks) - 1; i >= 0; i-- { - mut = builder.hooks[i](mut) - } - mutators[i] = mut - }(i, ctx) - } - if len(mutators) > 0 { - if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { - return nil, err - } - } - return nodes, nil -} - -// SaveX is like Save, but panics if an error occurs. -func (_c *AuditLogCreateBulk) SaveX(ctx context.Context) []*AuditLog { - v, err := _c.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (_c *AuditLogCreateBulk) Exec(ctx context.Context) error { - _, err := _c.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_c *AuditLogCreateBulk) ExecX(ctx context.Context) { - if err := _c.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/internal/ent/auditlog_delete.go b/internal/ent/auditlog_delete.go deleted file mode 100644 index 47a913b..0000000 --- a/internal/ent/auditlog_delete.go +++ /dev/null @@ -1,88 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/internal/ent/auditlog" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" -) - -// AuditLogDelete is the builder for deleting a AuditLog entity. -type AuditLogDelete struct { - config - hooks []Hook - mutation *AuditLogMutation -} - -// Where appends a list predicates to the AuditLogDelete builder. -func (_d *AuditLogDelete) Where(ps ...predicate.AuditLog) *AuditLogDelete { - _d.mutation.Where(ps...) - return _d -} - -// Exec executes the deletion query and returns how many vertices were deleted. -func (_d *AuditLogDelete) Exec(ctx context.Context) (int, error) { - return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) -} - -// ExecX is like Exec, but panics if an error occurs. -func (_d *AuditLogDelete) ExecX(ctx context.Context) int { - n, err := _d.Exec(ctx) - if err != nil { - panic(err) - } - return n -} - -func (_d *AuditLogDelete) sqlExec(ctx context.Context) (int, error) { - _spec := sqlgraph.NewDeleteSpec(auditlog.Table, sqlgraph.NewFieldSpec(auditlog.FieldID, field.TypeString)) - if ps := _d.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) - if err != nil && sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - _d.mutation.done = true - return affected, err -} - -// AuditLogDeleteOne is the builder for deleting a single AuditLog entity. -type AuditLogDeleteOne struct { - _d *AuditLogDelete -} - -// Where appends a list predicates to the AuditLogDelete builder. -func (_d *AuditLogDeleteOne) Where(ps ...predicate.AuditLog) *AuditLogDeleteOne { - _d._d.mutation.Where(ps...) - return _d -} - -// Exec executes the deletion query. -func (_d *AuditLogDeleteOne) Exec(ctx context.Context) error { - n, err := _d._d.Exec(ctx) - switch { - case err != nil: - return err - case n == 0: - return &NotFoundError{auditlog.Label} - default: - return nil - } -} - -// ExecX is like Exec, but panics if an error occurs. -func (_d *AuditLogDeleteOne) ExecX(ctx context.Context) { - if err := _d.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/internal/ent/auditlog_query.go b/internal/ent/auditlog_query.go deleted file mode 100644 index 116c6b8..0000000 --- a/internal/ent/auditlog_query.go +++ /dev/null @@ -1,527 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "fmt" - "math" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/internal/ent/auditlog" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" -) - -// AuditLogQuery is the builder for querying AuditLog entities. -type AuditLogQuery struct { - config - ctx *QueryContext - order []auditlog.OrderOption - inters []Interceptor - predicates []predicate.AuditLog - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Where adds a new predicate for the AuditLogQuery builder. -func (_q *AuditLogQuery) Where(ps ...predicate.AuditLog) *AuditLogQuery { - _q.predicates = append(_q.predicates, ps...) - return _q -} - -// Limit the number of records to be returned by this query. -func (_q *AuditLogQuery) Limit(limit int) *AuditLogQuery { - _q.ctx.Limit = &limit - return _q -} - -// Offset to start from. -func (_q *AuditLogQuery) Offset(offset int) *AuditLogQuery { - _q.ctx.Offset = &offset - return _q -} - -// Unique configures the query builder to filter duplicate records on query. -// By default, unique is set to true, and can be disabled using this method. -func (_q *AuditLogQuery) Unique(unique bool) *AuditLogQuery { - _q.ctx.Unique = &unique - return _q -} - -// Order specifies how the records should be ordered. -func (_q *AuditLogQuery) Order(o ...auditlog.OrderOption) *AuditLogQuery { - _q.order = append(_q.order, o...) - return _q -} - -// First returns the first AuditLog entity from the query. -// Returns a *NotFoundError when no AuditLog was found. -func (_q *AuditLogQuery) First(ctx context.Context) (*AuditLog, error) { - nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{auditlog.Label} - } - return nodes[0], nil -} - -// FirstX is like First, but panics if an error occurs. -func (_q *AuditLogQuery) FirstX(ctx context.Context) *AuditLog { - node, err := _q.First(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// FirstID returns the first AuditLog ID from the query. -// Returns a *NotFoundError when no AuditLog ID was found. -func (_q *AuditLogQuery) FirstID(ctx context.Context) (id string, err error) { - var ids []string - if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{auditlog.Label} - return - } - return ids[0], nil -} - -// FirstIDX is like FirstID, but panics if an error occurs. -func (_q *AuditLogQuery) FirstIDX(ctx context.Context) string { - id, err := _q.FirstID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Only returns a single AuditLog entity found by the query, ensuring it only returns one. -// Returns a *NotSingularError when more than one AuditLog entity is found. -// Returns a *NotFoundError when no AuditLog entities are found. -func (_q *AuditLogQuery) Only(ctx context.Context) (*AuditLog, error) { - nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) - if err != nil { - return nil, err - } - switch len(nodes) { - case 1: - return nodes[0], nil - case 0: - return nil, &NotFoundError{auditlog.Label} - default: - return nil, &NotSingularError{auditlog.Label} - } -} - -// OnlyX is like Only, but panics if an error occurs. -func (_q *AuditLogQuery) OnlyX(ctx context.Context) *AuditLog { - node, err := _q.Only(ctx) - if err != nil { - panic(err) - } - return node -} - -// OnlyID is like Only, but returns the only AuditLog ID in the query. -// Returns a *NotSingularError when more than one AuditLog ID is found. -// Returns a *NotFoundError when no entities are found. -func (_q *AuditLogQuery) OnlyID(ctx context.Context) (id string, err error) { - var ids []string - if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { - return - } - switch len(ids) { - case 1: - id = ids[0] - case 0: - err = &NotFoundError{auditlog.Label} - default: - err = &NotSingularError{auditlog.Label} - } - return -} - -// OnlyIDX is like OnlyID, but panics if an error occurs. -func (_q *AuditLogQuery) OnlyIDX(ctx context.Context) string { - id, err := _q.OnlyID(ctx) - if err != nil { - panic(err) - } - return id -} - -// All executes the query and returns a list of AuditLogs. -func (_q *AuditLogQuery) All(ctx context.Context) ([]*AuditLog, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) - if err := _q.prepareQuery(ctx); err != nil { - return nil, err - } - qr := querierAll[[]*AuditLog, *AuditLogQuery]() - return withInterceptors[[]*AuditLog](ctx, _q, qr, _q.inters) -} - -// AllX is like All, but panics if an error occurs. -func (_q *AuditLogQuery) AllX(ctx context.Context) []*AuditLog { - nodes, err := _q.All(ctx) - if err != nil { - panic(err) - } - return nodes -} - -// IDs executes the query and returns a list of AuditLog IDs. -func (_q *AuditLogQuery) IDs(ctx context.Context) (ids []string, err error) { - if _q.ctx.Unique == nil && _q.path != nil { - _q.Unique(true) - } - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) - if err = _q.Select(auditlog.FieldID).Scan(ctx, &ids); err != nil { - return nil, err - } - return ids, nil -} - -// IDsX is like IDs, but panics if an error occurs. -func (_q *AuditLogQuery) IDsX(ctx context.Context) []string { - ids, err := _q.IDs(ctx) - if err != nil { - panic(err) - } - return ids -} - -// Count returns the count of the given query. -func (_q *AuditLogQuery) Count(ctx context.Context) (int, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) - if err := _q.prepareQuery(ctx); err != nil { - return 0, err - } - return withInterceptors[int](ctx, _q, querierCount[*AuditLogQuery](), _q.inters) -} - -// CountX is like Count, but panics if an error occurs. -func (_q *AuditLogQuery) CountX(ctx context.Context) int { - count, err := _q.Count(ctx) - if err != nil { - panic(err) - } - return count -} - -// Exist returns true if the query has elements in the graph. -func (_q *AuditLogQuery) Exist(ctx context.Context) (bool, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) - switch _, err := _q.FirstID(ctx); { - case IsNotFound(err): - return false, nil - case err != nil: - return false, fmt.Errorf("ent: check existence: %w", err) - default: - return true, nil - } -} - -// ExistX is like Exist, but panics if an error occurs. -func (_q *AuditLogQuery) ExistX(ctx context.Context) bool { - exist, err := _q.Exist(ctx) - if err != nil { - panic(err) - } - return exist -} - -// Clone returns a duplicate of the AuditLogQuery builder, including all associated steps. It can be -// used to prepare common query builders and use them differently after the clone is made. -func (_q *AuditLogQuery) Clone() *AuditLogQuery { - if _q == nil { - return nil - } - return &AuditLogQuery{ - config: _q.config, - ctx: _q.ctx.Clone(), - order: append([]auditlog.OrderOption{}, _q.order...), - inters: append([]Interceptor{}, _q.inters...), - predicates: append([]predicate.AuditLog{}, _q.predicates...), - // clone intermediate query. - sql: _q.sql.Clone(), - path: _q.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.AuditLog.Query(). -// GroupBy(auditlog.FieldUserID). -// Aggregate(ent.Count()). -// Scan(ctx, &v) -func (_q *AuditLogQuery) GroupBy(field string, fields ...string) *AuditLogGroupBy { - _q.ctx.Fields = append([]string{field}, fields...) - grbuild := &AuditLogGroupBy{build: _q} - grbuild.flds = &_q.ctx.Fields - grbuild.label = auditlog.Label - grbuild.scan = grbuild.Scan - return grbuild -} - -// Select allows the selection one or more fields/columns for the given query, -// instead of selecting all fields in the entity. -// -// Example: -// -// var v []struct { -// UserID string `json:"user_id,omitempty"` -// } -// -// client.AuditLog.Query(). -// Select(auditlog.FieldUserID). -// Scan(ctx, &v) -func (_q *AuditLogQuery) Select(fields ...string) *AuditLogSelect { - _q.ctx.Fields = append(_q.ctx.Fields, fields...) - sbuild := &AuditLogSelect{AuditLogQuery: _q} - sbuild.label = auditlog.Label - sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan - return sbuild -} - -// Aggregate returns a AuditLogSelect configured with the given aggregations. -func (_q *AuditLogQuery) Aggregate(fns ...AggregateFunc) *AuditLogSelect { - return _q.Select().Aggregate(fns...) -} - -func (_q *AuditLogQuery) prepareQuery(ctx context.Context) error { - for _, inter := range _q.inters { - if inter == nil { - return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") - } - if trv, ok := inter.(Traverser); ok { - if err := trv.Traverse(ctx, _q); err != nil { - return err - } - } - } - for _, f := range _q.ctx.Fields { - if !auditlog.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} - } - } - if _q.path != nil { - prev, err := _q.path(ctx) - if err != nil { - return err - } - _q.sql = prev - } - return nil -} - -func (_q *AuditLogQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AuditLog, error) { - var ( - nodes = []*AuditLog{} - _spec = _q.querySpec() - ) - _spec.ScanValues = func(columns []string) ([]any, error) { - return (*AuditLog).scanValues(nil, columns) - } - _spec.Assign = func(columns []string, values []any) error { - node := &AuditLog{config: _q.config} - nodes = append(nodes, node) - return node.assignValues(columns, values) - } - for i := range hooks { - hooks[i](ctx, _spec) - } - if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { - return nil, err - } - if len(nodes) == 0 { - return nodes, nil - } - return nodes, nil -} - -func (_q *AuditLogQuery) sqlCount(ctx context.Context) (int, error) { - _spec := _q.querySpec() - _spec.Node.Columns = _q.ctx.Fields - if len(_q.ctx.Fields) > 0 { - _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique - } - return sqlgraph.CountNodes(ctx, _q.driver, _spec) -} - -func (_q *AuditLogQuery) querySpec() *sqlgraph.QuerySpec { - _spec := sqlgraph.NewQuerySpec(auditlog.Table, auditlog.Columns, sqlgraph.NewFieldSpec(auditlog.FieldID, field.TypeString)) - _spec.From = _q.sql - if unique := _q.ctx.Unique; unique != nil { - _spec.Unique = *unique - } else if _q.path != nil { - _spec.Unique = true - } - if fields := _q.ctx.Fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, auditlog.FieldID) - for i := range fields { - if fields[i] != auditlog.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) - } - } - } - if ps := _q.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if limit := _q.ctx.Limit; limit != nil { - _spec.Limit = *limit - } - if offset := _q.ctx.Offset; offset != nil { - _spec.Offset = *offset - } - if ps := _q.order; len(ps) > 0 { - _spec.Order = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return _spec -} - -func (_q *AuditLogQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(_q.driver.Dialect()) - t1 := builder.Table(auditlog.Table) - columns := _q.ctx.Fields - if len(columns) == 0 { - columns = auditlog.Columns - } - selector := builder.Select(t1.Columns(columns...)...).From(t1) - if _q.sql != nil { - selector = _q.sql - selector.Select(selector.Columns(columns...)...) - } - if _q.ctx.Unique != nil && *_q.ctx.Unique { - selector.Distinct() - } - for _, p := range _q.predicates { - p(selector) - } - for _, p := range _q.order { - p(selector) - } - if offset := _q.ctx.Offset; offset != nil { - // limit is mandatory for offset clause. We start - // with default value, and override it below if needed. - selector.Offset(*offset).Limit(math.MaxInt32) - } - if limit := _q.ctx.Limit; limit != nil { - selector.Limit(*limit) - } - return selector -} - -// AuditLogGroupBy is the group-by builder for AuditLog entities. -type AuditLogGroupBy struct { - selector - build *AuditLogQuery -} - -// Aggregate adds the given aggregation functions to the group-by query. -func (_g *AuditLogGroupBy) Aggregate(fns ...AggregateFunc) *AuditLogGroupBy { - _g.fns = append(_g.fns, fns...) - return _g -} - -// Scan applies the selector query and scans the result into the given value. -func (_g *AuditLogGroupBy) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) - if err := _g.build.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*AuditLogQuery, *AuditLogGroupBy](ctx, _g.build, _g, _g.build.inters, v) -} - -func (_g *AuditLogGroupBy) sqlScan(ctx context.Context, root *AuditLogQuery, v any) error { - selector := root.sqlQuery(ctx).Select() - aggregation := make([]string, 0, len(_g.fns)) - for _, fn := range _g.fns { - aggregation = append(aggregation, fn(selector)) - } - if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) - for _, f := range *_g.flds { - columns = append(columns, selector.C(f)) - } - columns = append(columns, aggregation...) - selector.Select(columns...) - } - selector.GroupBy(selector.Columns(*_g.flds...)...) - if err := selector.Err(); err != nil { - return err - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} - -// AuditLogSelect is the builder for selecting fields of AuditLog entities. -type AuditLogSelect struct { - *AuditLogQuery - selector -} - -// Aggregate adds the given aggregation functions to the selector query. -func (_s *AuditLogSelect) Aggregate(fns ...AggregateFunc) *AuditLogSelect { - _s.fns = append(_s.fns, fns...) - return _s -} - -// Scan applies the selector query and scans the result into the given value. -func (_s *AuditLogSelect) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) - if err := _s.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*AuditLogQuery, *AuditLogSelect](ctx, _s.AuditLogQuery, _s, _s.inters, v) -} - -func (_s *AuditLogSelect) sqlScan(ctx context.Context, root *AuditLogQuery, v any) error { - selector := root.sqlQuery(ctx) - aggregation := make([]string, 0, len(_s.fns)) - for _, fn := range _s.fns { - aggregation = append(aggregation, fn(selector)) - } - switch n := len(*_s.selector.flds); { - case n == 0 && len(aggregation) > 0: - selector.Select(aggregation...) - case n != 0 && len(aggregation) > 0: - selector.AppendSelect(aggregation...) - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := _s.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} diff --git a/internal/ent/auditlog_update.go b/internal/ent/auditlog_update.go deleted file mode 100644 index 439beaa..0000000 --- a/internal/ent/auditlog_update.go +++ /dev/null @@ -1,523 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "errors" - "fmt" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/internal/ent/auditlog" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" -) - -// AuditLogUpdate is the builder for updating AuditLog entities. -type AuditLogUpdate struct { - config - hooks []Hook - mutation *AuditLogMutation -} - -// Where appends a list predicates to the AuditLogUpdate builder. -func (_u *AuditLogUpdate) Where(ps ...predicate.AuditLog) *AuditLogUpdate { - _u.mutation.Where(ps...) - return _u -} - -// SetUserID sets the "user_id" field. -func (_u *AuditLogUpdate) SetUserID(v string) *AuditLogUpdate { - _u.mutation.SetUserID(v) - return _u -} - -// SetNillableUserID sets the "user_id" field if the given value is not nil. -func (_u *AuditLogUpdate) SetNillableUserID(v *string) *AuditLogUpdate { - if v != nil { - _u.SetUserID(*v) - } - return _u -} - -// SetAction sets the "action" field. -func (_u *AuditLogUpdate) SetAction(v string) *AuditLogUpdate { - _u.mutation.SetAction(v) - return _u -} - -// SetNillableAction sets the "action" field if the given value is not nil. -func (_u *AuditLogUpdate) SetNillableAction(v *string) *AuditLogUpdate { - if v != nil { - _u.SetAction(*v) - } - return _u -} - -// SetResource sets the "resource" field. -func (_u *AuditLogUpdate) SetResource(v string) *AuditLogUpdate { - _u.mutation.SetResource(v) - return _u -} - -// SetNillableResource sets the "resource" field if the given value is not nil. -func (_u *AuditLogUpdate) SetNillableResource(v *string) *AuditLogUpdate { - if v != nil { - _u.SetResource(*v) - } - return _u -} - -// ClearResource clears the value of the "resource" field. -func (_u *AuditLogUpdate) ClearResource() *AuditLogUpdate { - _u.mutation.ClearResource() - return _u -} - -// SetResourceID sets the "resource_id" field. -func (_u *AuditLogUpdate) SetResourceID(v string) *AuditLogUpdate { - _u.mutation.SetResourceID(v) - return _u -} - -// SetNillableResourceID sets the "resource_id" field if the given value is not nil. -func (_u *AuditLogUpdate) SetNillableResourceID(v *string) *AuditLogUpdate { - if v != nil { - _u.SetResourceID(*v) - } - return _u -} - -// ClearResourceID clears the value of the "resource_id" field. -func (_u *AuditLogUpdate) ClearResourceID() *AuditLogUpdate { - _u.mutation.ClearResourceID() - return _u -} - -// SetIPAddress sets the "ip_address" field. -func (_u *AuditLogUpdate) SetIPAddress(v string) *AuditLogUpdate { - _u.mutation.SetIPAddress(v) - return _u -} - -// SetNillableIPAddress sets the "ip_address" field if the given value is not nil. -func (_u *AuditLogUpdate) SetNillableIPAddress(v *string) *AuditLogUpdate { - if v != nil { - _u.SetIPAddress(*v) - } - return _u -} - -// ClearIPAddress clears the value of the "ip_address" field. -func (_u *AuditLogUpdate) ClearIPAddress() *AuditLogUpdate { - _u.mutation.ClearIPAddress() - return _u -} - -// SetUserAgent sets the "user_agent" field. -func (_u *AuditLogUpdate) SetUserAgent(v string) *AuditLogUpdate { - _u.mutation.SetUserAgent(v) - return _u -} - -// SetNillableUserAgent sets the "user_agent" field if the given value is not nil. -func (_u *AuditLogUpdate) SetNillableUserAgent(v *string) *AuditLogUpdate { - if v != nil { - _u.SetUserAgent(*v) - } - return _u -} - -// ClearUserAgent clears the value of the "user_agent" field. -func (_u *AuditLogUpdate) ClearUserAgent() *AuditLogUpdate { - _u.mutation.ClearUserAgent() - return _u -} - -// SetMetadata sets the "metadata" field. -func (_u *AuditLogUpdate) SetMetadata(v map[string]interface{}) *AuditLogUpdate { - _u.mutation.SetMetadata(v) - return _u -} - -// ClearMetadata clears the value of the "metadata" field. -func (_u *AuditLogUpdate) ClearMetadata() *AuditLogUpdate { - _u.mutation.ClearMetadata() - return _u -} - -// Mutation returns the AuditLogMutation object of the builder. -func (_u *AuditLogUpdate) Mutation() *AuditLogMutation { - return _u.mutation -} - -// Save executes the query and returns the number of nodes affected by the update operation. -func (_u *AuditLogUpdate) Save(ctx context.Context) (int, error) { - return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (_u *AuditLogUpdate) SaveX(ctx context.Context) int { - affected, err := _u.Save(ctx) - if err != nil { - panic(err) - } - return affected -} - -// Exec executes the query. -func (_u *AuditLogUpdate) Exec(ctx context.Context) error { - _, err := _u.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_u *AuditLogUpdate) ExecX(ctx context.Context) { - if err := _u.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (_u *AuditLogUpdate) check() error { - if v, ok := _u.mutation.UserID(); ok { - if err := auditlog.UserIDValidator(v); err != nil { - return &ValidationError{Name: "user_id", err: fmt.Errorf(`ent: validator failed for field "AuditLog.user_id": %w`, err)} - } - } - if v, ok := _u.mutation.Action(); ok { - if err := auditlog.ActionValidator(v); err != nil { - return &ValidationError{Name: "action", err: fmt.Errorf(`ent: validator failed for field "AuditLog.action": %w`, err)} - } - } - return nil -} - -func (_u *AuditLogUpdate) sqlSave(ctx context.Context) (_node int, err error) { - if err := _u.check(); err != nil { - return _node, err - } - _spec := sqlgraph.NewUpdateSpec(auditlog.Table, auditlog.Columns, sqlgraph.NewFieldSpec(auditlog.FieldID, field.TypeString)) - if ps := _u.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := _u.mutation.UserID(); ok { - _spec.SetField(auditlog.FieldUserID, field.TypeString, value) - } - if value, ok := _u.mutation.Action(); ok { - _spec.SetField(auditlog.FieldAction, field.TypeString, value) - } - if value, ok := _u.mutation.Resource(); ok { - _spec.SetField(auditlog.FieldResource, field.TypeString, value) - } - if _u.mutation.ResourceCleared() { - _spec.ClearField(auditlog.FieldResource, field.TypeString) - } - if value, ok := _u.mutation.ResourceID(); ok { - _spec.SetField(auditlog.FieldResourceID, field.TypeString, value) - } - if _u.mutation.ResourceIDCleared() { - _spec.ClearField(auditlog.FieldResourceID, field.TypeString) - } - if value, ok := _u.mutation.IPAddress(); ok { - _spec.SetField(auditlog.FieldIPAddress, field.TypeString, value) - } - if _u.mutation.IPAddressCleared() { - _spec.ClearField(auditlog.FieldIPAddress, field.TypeString) - } - if value, ok := _u.mutation.UserAgent(); ok { - _spec.SetField(auditlog.FieldUserAgent, field.TypeString, value) - } - if _u.mutation.UserAgentCleared() { - _spec.ClearField(auditlog.FieldUserAgent, field.TypeString) - } - if value, ok := _u.mutation.Metadata(); ok { - _spec.SetField(auditlog.FieldMetadata, field.TypeJSON, value) - } - if _u.mutation.MetadataCleared() { - _spec.ClearField(auditlog.FieldMetadata, field.TypeJSON) - } - if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{auditlog.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return 0, err - } - _u.mutation.done = true - return _node, nil -} - -// AuditLogUpdateOne is the builder for updating a single AuditLog entity. -type AuditLogUpdateOne struct { - config - fields []string - hooks []Hook - mutation *AuditLogMutation -} - -// SetUserID sets the "user_id" field. -func (_u *AuditLogUpdateOne) SetUserID(v string) *AuditLogUpdateOne { - _u.mutation.SetUserID(v) - return _u -} - -// SetNillableUserID sets the "user_id" field if the given value is not nil. -func (_u *AuditLogUpdateOne) SetNillableUserID(v *string) *AuditLogUpdateOne { - if v != nil { - _u.SetUserID(*v) - } - return _u -} - -// SetAction sets the "action" field. -func (_u *AuditLogUpdateOne) SetAction(v string) *AuditLogUpdateOne { - _u.mutation.SetAction(v) - return _u -} - -// SetNillableAction sets the "action" field if the given value is not nil. -func (_u *AuditLogUpdateOne) SetNillableAction(v *string) *AuditLogUpdateOne { - if v != nil { - _u.SetAction(*v) - } - return _u -} - -// SetResource sets the "resource" field. -func (_u *AuditLogUpdateOne) SetResource(v string) *AuditLogUpdateOne { - _u.mutation.SetResource(v) - return _u -} - -// SetNillableResource sets the "resource" field if the given value is not nil. -func (_u *AuditLogUpdateOne) SetNillableResource(v *string) *AuditLogUpdateOne { - if v != nil { - _u.SetResource(*v) - } - return _u -} - -// ClearResource clears the value of the "resource" field. -func (_u *AuditLogUpdateOne) ClearResource() *AuditLogUpdateOne { - _u.mutation.ClearResource() - return _u -} - -// SetResourceID sets the "resource_id" field. -func (_u *AuditLogUpdateOne) SetResourceID(v string) *AuditLogUpdateOne { - _u.mutation.SetResourceID(v) - return _u -} - -// SetNillableResourceID sets the "resource_id" field if the given value is not nil. -func (_u *AuditLogUpdateOne) SetNillableResourceID(v *string) *AuditLogUpdateOne { - if v != nil { - _u.SetResourceID(*v) - } - return _u -} - -// ClearResourceID clears the value of the "resource_id" field. -func (_u *AuditLogUpdateOne) ClearResourceID() *AuditLogUpdateOne { - _u.mutation.ClearResourceID() - return _u -} - -// SetIPAddress sets the "ip_address" field. -func (_u *AuditLogUpdateOne) SetIPAddress(v string) *AuditLogUpdateOne { - _u.mutation.SetIPAddress(v) - return _u -} - -// SetNillableIPAddress sets the "ip_address" field if the given value is not nil. -func (_u *AuditLogUpdateOne) SetNillableIPAddress(v *string) *AuditLogUpdateOne { - if v != nil { - _u.SetIPAddress(*v) - } - return _u -} - -// ClearIPAddress clears the value of the "ip_address" field. -func (_u *AuditLogUpdateOne) ClearIPAddress() *AuditLogUpdateOne { - _u.mutation.ClearIPAddress() - return _u -} - -// SetUserAgent sets the "user_agent" field. -func (_u *AuditLogUpdateOne) SetUserAgent(v string) *AuditLogUpdateOne { - _u.mutation.SetUserAgent(v) - return _u -} - -// SetNillableUserAgent sets the "user_agent" field if the given value is not nil. -func (_u *AuditLogUpdateOne) SetNillableUserAgent(v *string) *AuditLogUpdateOne { - if v != nil { - _u.SetUserAgent(*v) - } - return _u -} - -// ClearUserAgent clears the value of the "user_agent" field. -func (_u *AuditLogUpdateOne) ClearUserAgent() *AuditLogUpdateOne { - _u.mutation.ClearUserAgent() - return _u -} - -// SetMetadata sets the "metadata" field. -func (_u *AuditLogUpdateOne) SetMetadata(v map[string]interface{}) *AuditLogUpdateOne { - _u.mutation.SetMetadata(v) - return _u -} - -// ClearMetadata clears the value of the "metadata" field. -func (_u *AuditLogUpdateOne) ClearMetadata() *AuditLogUpdateOne { - _u.mutation.ClearMetadata() - return _u -} - -// Mutation returns the AuditLogMutation object of the builder. -func (_u *AuditLogUpdateOne) Mutation() *AuditLogMutation { - return _u.mutation -} - -// Where appends a list predicates to the AuditLogUpdate builder. -func (_u *AuditLogUpdateOne) Where(ps ...predicate.AuditLog) *AuditLogUpdateOne { - _u.mutation.Where(ps...) - return _u -} - -// Select allows selecting one or more fields (columns) of the returned entity. -// The default is selecting all fields defined in the entity schema. -func (_u *AuditLogUpdateOne) Select(field string, fields ...string) *AuditLogUpdateOne { - _u.fields = append([]string{field}, fields...) - return _u -} - -// Save executes the query and returns the updated AuditLog entity. -func (_u *AuditLogUpdateOne) Save(ctx context.Context) (*AuditLog, error) { - return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (_u *AuditLogUpdateOne) SaveX(ctx context.Context) *AuditLog { - node, err := _u.Save(ctx) - if err != nil { - panic(err) - } - return node -} - -// Exec executes the query on the entity. -func (_u *AuditLogUpdateOne) Exec(ctx context.Context) error { - _, err := _u.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_u *AuditLogUpdateOne) ExecX(ctx context.Context) { - if err := _u.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (_u *AuditLogUpdateOne) check() error { - if v, ok := _u.mutation.UserID(); ok { - if err := auditlog.UserIDValidator(v); err != nil { - return &ValidationError{Name: "user_id", err: fmt.Errorf(`ent: validator failed for field "AuditLog.user_id": %w`, err)} - } - } - if v, ok := _u.mutation.Action(); ok { - if err := auditlog.ActionValidator(v); err != nil { - return &ValidationError{Name: "action", err: fmt.Errorf(`ent: validator failed for field "AuditLog.action": %w`, err)} - } - } - return nil -} - -func (_u *AuditLogUpdateOne) sqlSave(ctx context.Context) (_node *AuditLog, err error) { - if err := _u.check(); err != nil { - return _node, err - } - _spec := sqlgraph.NewUpdateSpec(auditlog.Table, auditlog.Columns, sqlgraph.NewFieldSpec(auditlog.FieldID, field.TypeString)) - id, ok := _u.mutation.ID() - if !ok { - return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "AuditLog.id" for update`)} - } - _spec.Node.ID.Value = id - if fields := _u.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, auditlog.FieldID) - for _, f := range fields { - if !auditlog.ValidColumn(f) { - return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} - } - if f != auditlog.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, f) - } - } - } - if ps := _u.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := _u.mutation.UserID(); ok { - _spec.SetField(auditlog.FieldUserID, field.TypeString, value) - } - if value, ok := _u.mutation.Action(); ok { - _spec.SetField(auditlog.FieldAction, field.TypeString, value) - } - if value, ok := _u.mutation.Resource(); ok { - _spec.SetField(auditlog.FieldResource, field.TypeString, value) - } - if _u.mutation.ResourceCleared() { - _spec.ClearField(auditlog.FieldResource, field.TypeString) - } - if value, ok := _u.mutation.ResourceID(); ok { - _spec.SetField(auditlog.FieldResourceID, field.TypeString, value) - } - if _u.mutation.ResourceIDCleared() { - _spec.ClearField(auditlog.FieldResourceID, field.TypeString) - } - if value, ok := _u.mutation.IPAddress(); ok { - _spec.SetField(auditlog.FieldIPAddress, field.TypeString, value) - } - if _u.mutation.IPAddressCleared() { - _spec.ClearField(auditlog.FieldIPAddress, field.TypeString) - } - if value, ok := _u.mutation.UserAgent(); ok { - _spec.SetField(auditlog.FieldUserAgent, field.TypeString, value) - } - if _u.mutation.UserAgentCleared() { - _spec.ClearField(auditlog.FieldUserAgent, field.TypeString) - } - if value, ok := _u.mutation.Metadata(); ok { - _spec.SetField(auditlog.FieldMetadata, field.TypeJSON, value) - } - if _u.mutation.MetadataCleared() { - _spec.ClearField(auditlog.FieldMetadata, field.TypeJSON) - } - _node = &AuditLog{config: _u.config} - _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{auditlog.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - _u.mutation.done = true - return _node, nil -} diff --git a/internal/ent/client.go b/internal/ent/client.go deleted file mode 100644 index e1416a2..0000000 --- a/internal/ent/client.go +++ /dev/null @@ -1,1327 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "errors" - "fmt" - "log" - "reflect" - - "git.dcentral.systems/toolz/goplt/internal/ent/migrate" - - "entgo.io/ent" - "entgo.io/ent/dialect" - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "git.dcentral.systems/toolz/goplt/internal/ent/auditlog" - "git.dcentral.systems/toolz/goplt/internal/ent/permission" - "git.dcentral.systems/toolz/goplt/internal/ent/refreshtoken" - "git.dcentral.systems/toolz/goplt/internal/ent/role" - "git.dcentral.systems/toolz/goplt/internal/ent/rolepermission" - "git.dcentral.systems/toolz/goplt/internal/ent/user" - "git.dcentral.systems/toolz/goplt/internal/ent/userrole" -) - -// Client is the client that holds all ent builders. -type Client struct { - config - // Schema is the client for creating, migrating and dropping schema. - Schema *migrate.Schema - // AuditLog is the client for interacting with the AuditLog builders. - AuditLog *AuditLogClient - // Permission is the client for interacting with the Permission builders. - Permission *PermissionClient - // RefreshToken is the client for interacting with the RefreshToken builders. - RefreshToken *RefreshTokenClient - // Role is the client for interacting with the Role builders. - Role *RoleClient - // RolePermission is the client for interacting with the RolePermission builders. - RolePermission *RolePermissionClient - // User is the client for interacting with the User builders. - User *UserClient - // UserRole is the client for interacting with the UserRole builders. - UserRole *UserRoleClient -} - -// NewClient creates a new client configured with the given options. -func NewClient(opts ...Option) *Client { - client := &Client{config: newConfig(opts...)} - client.init() - return client -} - -func (c *Client) init() { - c.Schema = migrate.NewSchema(c.driver) - c.AuditLog = NewAuditLogClient(c.config) - c.Permission = NewPermissionClient(c.config) - c.RefreshToken = NewRefreshTokenClient(c.config) - c.Role = NewRoleClient(c.config) - c.RolePermission = NewRolePermissionClient(c.config) - c.User = NewUserClient(c.config) - c.UserRole = NewUserRoleClient(c.config) -} - -type ( - // config is the configuration for the client and its builder. - config struct { - // driver used for executing database requests. - driver dialect.Driver - // debug enable a debug logging. - debug bool - // log used for logging on debug mode. - log func(...any) - // hooks to execute on mutations. - hooks *hooks - // interceptors to execute on queries. - inters *inters - } - // Option function to configure the client. - Option func(*config) -) - -// newConfig creates a new config for the client. -func newConfig(opts ...Option) config { - cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}} - cfg.options(opts...) - return cfg -} - -// options applies the options on the config object. -func (c *config) options(opts ...Option) { - for _, opt := range opts { - opt(c) - } - if c.debug { - c.driver = dialect.Debug(c.driver, c.log) - } -} - -// Debug enables debug logging on the ent.Driver. -func Debug() Option { - return func(c *config) { - c.debug = true - } -} - -// Log sets the logging function for debug mode. -func Log(fn func(...any)) Option { - return func(c *config) { - c.log = fn - } -} - -// Driver configures the client driver. -func Driver(driver dialect.Driver) Option { - return func(c *config) { - c.driver = driver - } -} - -// Open opens a database/sql.DB specified by the driver name and -// the data source name, and returns a new client attached to it. -// Optional parameters can be added for configuring the client. -func Open(driverName, dataSourceName string, options ...Option) (*Client, error) { - switch driverName { - case dialect.MySQL, dialect.Postgres, dialect.SQLite: - drv, err := sql.Open(driverName, dataSourceName) - if err != nil { - return nil, err - } - return NewClient(append(options, Driver(drv))...), nil - default: - return nil, fmt.Errorf("unsupported driver: %q", driverName) - } -} - -// ErrTxStarted is returned when trying to start a new transaction from a transactional client. -var ErrTxStarted = errors.New("ent: cannot start a transaction within a transaction") - -// Tx returns a new transactional client. The provided context -// is used until the transaction is committed or rolled back. -func (c *Client) Tx(ctx context.Context) (*Tx, error) { - if _, ok := c.driver.(*txDriver); ok { - return nil, ErrTxStarted - } - tx, err := newTx(ctx, c.driver) - if err != nil { - return nil, fmt.Errorf("ent: starting a transaction: %w", err) - } - cfg := c.config - cfg.driver = tx - return &Tx{ - ctx: ctx, - config: cfg, - AuditLog: NewAuditLogClient(cfg), - Permission: NewPermissionClient(cfg), - RefreshToken: NewRefreshTokenClient(cfg), - Role: NewRoleClient(cfg), - RolePermission: NewRolePermissionClient(cfg), - User: NewUserClient(cfg), - UserRole: NewUserRoleClient(cfg), - }, nil -} - -// BeginTx returns a transactional client with specified options. -func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) { - if _, ok := c.driver.(*txDriver); ok { - return nil, errors.New("ent: cannot start a transaction within a transaction") - } - tx, err := c.driver.(interface { - BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error) - }).BeginTx(ctx, opts) - if err != nil { - return nil, fmt.Errorf("ent: starting a transaction: %w", err) - } - cfg := c.config - cfg.driver = &txDriver{tx: tx, drv: c.driver} - return &Tx{ - ctx: ctx, - config: cfg, - AuditLog: NewAuditLogClient(cfg), - Permission: NewPermissionClient(cfg), - RefreshToken: NewRefreshTokenClient(cfg), - Role: NewRoleClient(cfg), - RolePermission: NewRolePermissionClient(cfg), - User: NewUserClient(cfg), - UserRole: NewUserRoleClient(cfg), - }, nil -} - -// Debug returns a new debug-client. It's used to get verbose logging on specific operations. -// -// client.Debug(). -// AuditLog. -// Query(). -// Count(ctx) -func (c *Client) Debug() *Client { - if c.debug { - return c - } - cfg := c.config - cfg.driver = dialect.Debug(c.driver, c.log) - client := &Client{config: cfg} - client.init() - return client -} - -// Close closes the database connection and prevents new queries from starting. -func (c *Client) Close() error { - return c.driver.Close() -} - -// Use adds the mutation hooks to all the entity clients. -// In order to add hooks to a specific client, call: `client.Node.Use(...)`. -func (c *Client) Use(hooks ...Hook) { - for _, n := range []interface{ Use(...Hook) }{ - c.AuditLog, c.Permission, c.RefreshToken, c.Role, c.RolePermission, c.User, - c.UserRole, - } { - n.Use(hooks...) - } -} - -// Intercept adds the query interceptors to all the entity clients. -// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. -func (c *Client) Intercept(interceptors ...Interceptor) { - for _, n := range []interface{ Intercept(...Interceptor) }{ - c.AuditLog, c.Permission, c.RefreshToken, c.Role, c.RolePermission, c.User, - c.UserRole, - } { - n.Intercept(interceptors...) - } -} - -// Mutate implements the ent.Mutator interface. -func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { - switch m := m.(type) { - case *AuditLogMutation: - return c.AuditLog.mutate(ctx, m) - case *PermissionMutation: - return c.Permission.mutate(ctx, m) - case *RefreshTokenMutation: - return c.RefreshToken.mutate(ctx, m) - case *RoleMutation: - return c.Role.mutate(ctx, m) - case *RolePermissionMutation: - return c.RolePermission.mutate(ctx, m) - case *UserMutation: - return c.User.mutate(ctx, m) - case *UserRoleMutation: - return c.UserRole.mutate(ctx, m) - default: - return nil, fmt.Errorf("ent: unknown mutation type %T", m) - } -} - -// AuditLogClient is a client for the AuditLog schema. -type AuditLogClient struct { - config -} - -// NewAuditLogClient returns a client for the AuditLog from the given config. -func NewAuditLogClient(c config) *AuditLogClient { - return &AuditLogClient{config: c} -} - -// Use adds a list of mutation hooks to the hooks stack. -// A call to `Use(f, g, h)` equals to `auditlog.Hooks(f(g(h())))`. -func (c *AuditLogClient) Use(hooks ...Hook) { - c.hooks.AuditLog = append(c.hooks.AuditLog, hooks...) -} - -// Intercept adds a list of query interceptors to the interceptors stack. -// A call to `Intercept(f, g, h)` equals to `auditlog.Intercept(f(g(h())))`. -func (c *AuditLogClient) Intercept(interceptors ...Interceptor) { - c.inters.AuditLog = append(c.inters.AuditLog, interceptors...) -} - -// Create returns a builder for creating a AuditLog entity. -func (c *AuditLogClient) Create() *AuditLogCreate { - mutation := newAuditLogMutation(c.config, OpCreate) - return &AuditLogCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// CreateBulk returns a builder for creating a bulk of AuditLog entities. -func (c *AuditLogClient) CreateBulk(builders ...*AuditLogCreate) *AuditLogCreateBulk { - return &AuditLogCreateBulk{config: c.config, builders: builders} -} - -// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates -// a builder and applies setFunc on it. -func (c *AuditLogClient) MapCreateBulk(slice any, setFunc func(*AuditLogCreate, int)) *AuditLogCreateBulk { - rv := reflect.ValueOf(slice) - if rv.Kind() != reflect.Slice { - return &AuditLogCreateBulk{err: fmt.Errorf("calling to AuditLogClient.MapCreateBulk with wrong type %T, need slice", slice)} - } - builders := make([]*AuditLogCreate, rv.Len()) - for i := 0; i < rv.Len(); i++ { - builders[i] = c.Create() - setFunc(builders[i], i) - } - return &AuditLogCreateBulk{config: c.config, builders: builders} -} - -// Update returns an update builder for AuditLog. -func (c *AuditLogClient) Update() *AuditLogUpdate { - mutation := newAuditLogMutation(c.config, OpUpdate) - return &AuditLogUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOne returns an update builder for the given entity. -func (c *AuditLogClient) UpdateOne(_m *AuditLog) *AuditLogUpdateOne { - mutation := newAuditLogMutation(c.config, OpUpdateOne, withAuditLog(_m)) - return &AuditLogUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOneID returns an update builder for the given id. -func (c *AuditLogClient) UpdateOneID(id string) *AuditLogUpdateOne { - mutation := newAuditLogMutation(c.config, OpUpdateOne, withAuditLogID(id)) - return &AuditLogUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// Delete returns a delete builder for AuditLog. -func (c *AuditLogClient) Delete() *AuditLogDelete { - mutation := newAuditLogMutation(c.config, OpDelete) - return &AuditLogDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// DeleteOne returns a builder for deleting the given entity. -func (c *AuditLogClient) DeleteOne(_m *AuditLog) *AuditLogDeleteOne { - return c.DeleteOneID(_m.ID) -} - -// DeleteOneID returns a builder for deleting the given entity by its id. -func (c *AuditLogClient) DeleteOneID(id string) *AuditLogDeleteOne { - builder := c.Delete().Where(auditlog.ID(id)) - builder.mutation.id = &id - builder.mutation.op = OpDeleteOne - return &AuditLogDeleteOne{builder} -} - -// Query returns a query builder for AuditLog. -func (c *AuditLogClient) Query() *AuditLogQuery { - return &AuditLogQuery{ - config: c.config, - ctx: &QueryContext{Type: TypeAuditLog}, - inters: c.Interceptors(), - } -} - -// Get returns a AuditLog entity by its id. -func (c *AuditLogClient) Get(ctx context.Context, id string) (*AuditLog, error) { - return c.Query().Where(auditlog.ID(id)).Only(ctx) -} - -// GetX is like Get, but panics if an error occurs. -func (c *AuditLogClient) GetX(ctx context.Context, id string) *AuditLog { - obj, err := c.Get(ctx, id) - if err != nil { - panic(err) - } - return obj -} - -// Hooks returns the client hooks. -func (c *AuditLogClient) Hooks() []Hook { - return c.hooks.AuditLog -} - -// Interceptors returns the client interceptors. -func (c *AuditLogClient) Interceptors() []Interceptor { - return c.inters.AuditLog -} - -func (c *AuditLogClient) mutate(ctx context.Context, m *AuditLogMutation) (Value, error) { - switch m.Op() { - case OpCreate: - return (&AuditLogCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdate: - return (&AuditLogUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdateOne: - return (&AuditLogUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpDelete, OpDeleteOne: - return (&AuditLogDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) - default: - return nil, fmt.Errorf("ent: unknown AuditLog mutation op: %q", m.Op()) - } -} - -// PermissionClient is a client for the Permission schema. -type PermissionClient struct { - config -} - -// NewPermissionClient returns a client for the Permission from the given config. -func NewPermissionClient(c config) *PermissionClient { - return &PermissionClient{config: c} -} - -// Use adds a list of mutation hooks to the hooks stack. -// A call to `Use(f, g, h)` equals to `permission.Hooks(f(g(h())))`. -func (c *PermissionClient) Use(hooks ...Hook) { - c.hooks.Permission = append(c.hooks.Permission, hooks...) -} - -// Intercept adds a list of query interceptors to the interceptors stack. -// A call to `Intercept(f, g, h)` equals to `permission.Intercept(f(g(h())))`. -func (c *PermissionClient) Intercept(interceptors ...Interceptor) { - c.inters.Permission = append(c.inters.Permission, interceptors...) -} - -// Create returns a builder for creating a Permission entity. -func (c *PermissionClient) Create() *PermissionCreate { - mutation := newPermissionMutation(c.config, OpCreate) - return &PermissionCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// CreateBulk returns a builder for creating a bulk of Permission entities. -func (c *PermissionClient) CreateBulk(builders ...*PermissionCreate) *PermissionCreateBulk { - return &PermissionCreateBulk{config: c.config, builders: builders} -} - -// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates -// a builder and applies setFunc on it. -func (c *PermissionClient) MapCreateBulk(slice any, setFunc func(*PermissionCreate, int)) *PermissionCreateBulk { - rv := reflect.ValueOf(slice) - if rv.Kind() != reflect.Slice { - return &PermissionCreateBulk{err: fmt.Errorf("calling to PermissionClient.MapCreateBulk with wrong type %T, need slice", slice)} - } - builders := make([]*PermissionCreate, rv.Len()) - for i := 0; i < rv.Len(); i++ { - builders[i] = c.Create() - setFunc(builders[i], i) - } - return &PermissionCreateBulk{config: c.config, builders: builders} -} - -// Update returns an update builder for Permission. -func (c *PermissionClient) Update() *PermissionUpdate { - mutation := newPermissionMutation(c.config, OpUpdate) - return &PermissionUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOne returns an update builder for the given entity. -func (c *PermissionClient) UpdateOne(_m *Permission) *PermissionUpdateOne { - mutation := newPermissionMutation(c.config, OpUpdateOne, withPermission(_m)) - return &PermissionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOneID returns an update builder for the given id. -func (c *PermissionClient) UpdateOneID(id string) *PermissionUpdateOne { - mutation := newPermissionMutation(c.config, OpUpdateOne, withPermissionID(id)) - return &PermissionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// Delete returns a delete builder for Permission. -func (c *PermissionClient) Delete() *PermissionDelete { - mutation := newPermissionMutation(c.config, OpDelete) - return &PermissionDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// DeleteOne returns a builder for deleting the given entity. -func (c *PermissionClient) DeleteOne(_m *Permission) *PermissionDeleteOne { - return c.DeleteOneID(_m.ID) -} - -// DeleteOneID returns a builder for deleting the given entity by its id. -func (c *PermissionClient) DeleteOneID(id string) *PermissionDeleteOne { - builder := c.Delete().Where(permission.ID(id)) - builder.mutation.id = &id - builder.mutation.op = OpDeleteOne - return &PermissionDeleteOne{builder} -} - -// Query returns a query builder for Permission. -func (c *PermissionClient) Query() *PermissionQuery { - return &PermissionQuery{ - config: c.config, - ctx: &QueryContext{Type: TypePermission}, - inters: c.Interceptors(), - } -} - -// Get returns a Permission entity by its id. -func (c *PermissionClient) Get(ctx context.Context, id string) (*Permission, error) { - return c.Query().Where(permission.ID(id)).Only(ctx) -} - -// GetX is like Get, but panics if an error occurs. -func (c *PermissionClient) GetX(ctx context.Context, id string) *Permission { - obj, err := c.Get(ctx, id) - if err != nil { - panic(err) - } - return obj -} - -// QueryRolePermissions queries the role_permissions edge of a Permission. -func (c *PermissionClient) QueryRolePermissions(_m *Permission) *RolePermissionQuery { - query := (&RolePermissionClient{config: c.config}).Query() - query.path = func(context.Context) (fromV *sql.Selector, _ error) { - id := _m.ID - step := sqlgraph.NewStep( - sqlgraph.From(permission.Table, permission.FieldID, id), - sqlgraph.To(rolepermission.Table, rolepermission.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, permission.RolePermissionsTable, permission.RolePermissionsColumn), - ) - fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) - return fromV, nil - } - return query -} - -// Hooks returns the client hooks. -func (c *PermissionClient) Hooks() []Hook { - return c.hooks.Permission -} - -// Interceptors returns the client interceptors. -func (c *PermissionClient) Interceptors() []Interceptor { - return c.inters.Permission -} - -func (c *PermissionClient) mutate(ctx context.Context, m *PermissionMutation) (Value, error) { - switch m.Op() { - case OpCreate: - return (&PermissionCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdate: - return (&PermissionUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdateOne: - return (&PermissionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpDelete, OpDeleteOne: - return (&PermissionDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) - default: - return nil, fmt.Errorf("ent: unknown Permission mutation op: %q", m.Op()) - } -} - -// RefreshTokenClient is a client for the RefreshToken schema. -type RefreshTokenClient struct { - config -} - -// NewRefreshTokenClient returns a client for the RefreshToken from the given config. -func NewRefreshTokenClient(c config) *RefreshTokenClient { - return &RefreshTokenClient{config: c} -} - -// Use adds a list of mutation hooks to the hooks stack. -// A call to `Use(f, g, h)` equals to `refreshtoken.Hooks(f(g(h())))`. -func (c *RefreshTokenClient) Use(hooks ...Hook) { - c.hooks.RefreshToken = append(c.hooks.RefreshToken, hooks...) -} - -// Intercept adds a list of query interceptors to the interceptors stack. -// A call to `Intercept(f, g, h)` equals to `refreshtoken.Intercept(f(g(h())))`. -func (c *RefreshTokenClient) Intercept(interceptors ...Interceptor) { - c.inters.RefreshToken = append(c.inters.RefreshToken, interceptors...) -} - -// Create returns a builder for creating a RefreshToken entity. -func (c *RefreshTokenClient) Create() *RefreshTokenCreate { - mutation := newRefreshTokenMutation(c.config, OpCreate) - return &RefreshTokenCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// CreateBulk returns a builder for creating a bulk of RefreshToken entities. -func (c *RefreshTokenClient) CreateBulk(builders ...*RefreshTokenCreate) *RefreshTokenCreateBulk { - return &RefreshTokenCreateBulk{config: c.config, builders: builders} -} - -// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates -// a builder and applies setFunc on it. -func (c *RefreshTokenClient) MapCreateBulk(slice any, setFunc func(*RefreshTokenCreate, int)) *RefreshTokenCreateBulk { - rv := reflect.ValueOf(slice) - if rv.Kind() != reflect.Slice { - return &RefreshTokenCreateBulk{err: fmt.Errorf("calling to RefreshTokenClient.MapCreateBulk with wrong type %T, need slice", slice)} - } - builders := make([]*RefreshTokenCreate, rv.Len()) - for i := 0; i < rv.Len(); i++ { - builders[i] = c.Create() - setFunc(builders[i], i) - } - return &RefreshTokenCreateBulk{config: c.config, builders: builders} -} - -// Update returns an update builder for RefreshToken. -func (c *RefreshTokenClient) Update() *RefreshTokenUpdate { - mutation := newRefreshTokenMutation(c.config, OpUpdate) - return &RefreshTokenUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOne returns an update builder for the given entity. -func (c *RefreshTokenClient) UpdateOne(_m *RefreshToken) *RefreshTokenUpdateOne { - mutation := newRefreshTokenMutation(c.config, OpUpdateOne, withRefreshToken(_m)) - return &RefreshTokenUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOneID returns an update builder for the given id. -func (c *RefreshTokenClient) UpdateOneID(id string) *RefreshTokenUpdateOne { - mutation := newRefreshTokenMutation(c.config, OpUpdateOne, withRefreshTokenID(id)) - return &RefreshTokenUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// Delete returns a delete builder for RefreshToken. -func (c *RefreshTokenClient) Delete() *RefreshTokenDelete { - mutation := newRefreshTokenMutation(c.config, OpDelete) - return &RefreshTokenDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// DeleteOne returns a builder for deleting the given entity. -func (c *RefreshTokenClient) DeleteOne(_m *RefreshToken) *RefreshTokenDeleteOne { - return c.DeleteOneID(_m.ID) -} - -// DeleteOneID returns a builder for deleting the given entity by its id. -func (c *RefreshTokenClient) DeleteOneID(id string) *RefreshTokenDeleteOne { - builder := c.Delete().Where(refreshtoken.ID(id)) - builder.mutation.id = &id - builder.mutation.op = OpDeleteOne - return &RefreshTokenDeleteOne{builder} -} - -// Query returns a query builder for RefreshToken. -func (c *RefreshTokenClient) Query() *RefreshTokenQuery { - return &RefreshTokenQuery{ - config: c.config, - ctx: &QueryContext{Type: TypeRefreshToken}, - inters: c.Interceptors(), - } -} - -// Get returns a RefreshToken entity by its id. -func (c *RefreshTokenClient) Get(ctx context.Context, id string) (*RefreshToken, error) { - return c.Query().Where(refreshtoken.ID(id)).Only(ctx) -} - -// GetX is like Get, but panics if an error occurs. -func (c *RefreshTokenClient) GetX(ctx context.Context, id string) *RefreshToken { - obj, err := c.Get(ctx, id) - if err != nil { - panic(err) - } - return obj -} - -// Hooks returns the client hooks. -func (c *RefreshTokenClient) Hooks() []Hook { - return c.hooks.RefreshToken -} - -// Interceptors returns the client interceptors. -func (c *RefreshTokenClient) Interceptors() []Interceptor { - return c.inters.RefreshToken -} - -func (c *RefreshTokenClient) mutate(ctx context.Context, m *RefreshTokenMutation) (Value, error) { - switch m.Op() { - case OpCreate: - return (&RefreshTokenCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdate: - return (&RefreshTokenUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdateOne: - return (&RefreshTokenUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpDelete, OpDeleteOne: - return (&RefreshTokenDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) - default: - return nil, fmt.Errorf("ent: unknown RefreshToken mutation op: %q", m.Op()) - } -} - -// RoleClient is a client for the Role schema. -type RoleClient struct { - config -} - -// NewRoleClient returns a client for the Role from the given config. -func NewRoleClient(c config) *RoleClient { - return &RoleClient{config: c} -} - -// Use adds a list of mutation hooks to the hooks stack. -// A call to `Use(f, g, h)` equals to `role.Hooks(f(g(h())))`. -func (c *RoleClient) Use(hooks ...Hook) { - c.hooks.Role = append(c.hooks.Role, hooks...) -} - -// Intercept adds a list of query interceptors to the interceptors stack. -// A call to `Intercept(f, g, h)` equals to `role.Intercept(f(g(h())))`. -func (c *RoleClient) Intercept(interceptors ...Interceptor) { - c.inters.Role = append(c.inters.Role, interceptors...) -} - -// Create returns a builder for creating a Role entity. -func (c *RoleClient) Create() *RoleCreate { - mutation := newRoleMutation(c.config, OpCreate) - return &RoleCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// CreateBulk returns a builder for creating a bulk of Role entities. -func (c *RoleClient) CreateBulk(builders ...*RoleCreate) *RoleCreateBulk { - return &RoleCreateBulk{config: c.config, builders: builders} -} - -// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates -// a builder and applies setFunc on it. -func (c *RoleClient) MapCreateBulk(slice any, setFunc func(*RoleCreate, int)) *RoleCreateBulk { - rv := reflect.ValueOf(slice) - if rv.Kind() != reflect.Slice { - return &RoleCreateBulk{err: fmt.Errorf("calling to RoleClient.MapCreateBulk with wrong type %T, need slice", slice)} - } - builders := make([]*RoleCreate, rv.Len()) - for i := 0; i < rv.Len(); i++ { - builders[i] = c.Create() - setFunc(builders[i], i) - } - return &RoleCreateBulk{config: c.config, builders: builders} -} - -// Update returns an update builder for Role. -func (c *RoleClient) Update() *RoleUpdate { - mutation := newRoleMutation(c.config, OpUpdate) - return &RoleUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOne returns an update builder for the given entity. -func (c *RoleClient) UpdateOne(_m *Role) *RoleUpdateOne { - mutation := newRoleMutation(c.config, OpUpdateOne, withRole(_m)) - return &RoleUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOneID returns an update builder for the given id. -func (c *RoleClient) UpdateOneID(id string) *RoleUpdateOne { - mutation := newRoleMutation(c.config, OpUpdateOne, withRoleID(id)) - return &RoleUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// Delete returns a delete builder for Role. -func (c *RoleClient) Delete() *RoleDelete { - mutation := newRoleMutation(c.config, OpDelete) - return &RoleDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// DeleteOne returns a builder for deleting the given entity. -func (c *RoleClient) DeleteOne(_m *Role) *RoleDeleteOne { - return c.DeleteOneID(_m.ID) -} - -// DeleteOneID returns a builder for deleting the given entity by its id. -func (c *RoleClient) DeleteOneID(id string) *RoleDeleteOne { - builder := c.Delete().Where(role.ID(id)) - builder.mutation.id = &id - builder.mutation.op = OpDeleteOne - return &RoleDeleteOne{builder} -} - -// Query returns a query builder for Role. -func (c *RoleClient) Query() *RoleQuery { - return &RoleQuery{ - config: c.config, - ctx: &QueryContext{Type: TypeRole}, - inters: c.Interceptors(), - } -} - -// Get returns a Role entity by its id. -func (c *RoleClient) Get(ctx context.Context, id string) (*Role, error) { - return c.Query().Where(role.ID(id)).Only(ctx) -} - -// GetX is like Get, but panics if an error occurs. -func (c *RoleClient) GetX(ctx context.Context, id string) *Role { - obj, err := c.Get(ctx, id) - if err != nil { - panic(err) - } - return obj -} - -// QueryRolePermissions queries the role_permissions edge of a Role. -func (c *RoleClient) QueryRolePermissions(_m *Role) *RolePermissionQuery { - query := (&RolePermissionClient{config: c.config}).Query() - query.path = func(context.Context) (fromV *sql.Selector, _ error) { - id := _m.ID - step := sqlgraph.NewStep( - sqlgraph.From(role.Table, role.FieldID, id), - sqlgraph.To(rolepermission.Table, rolepermission.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, role.RolePermissionsTable, role.RolePermissionsColumn), - ) - fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) - return fromV, nil - } - return query -} - -// QueryUserRoles queries the user_roles edge of a Role. -func (c *RoleClient) QueryUserRoles(_m *Role) *UserRoleQuery { - query := (&UserRoleClient{config: c.config}).Query() - query.path = func(context.Context) (fromV *sql.Selector, _ error) { - id := _m.ID - step := sqlgraph.NewStep( - sqlgraph.From(role.Table, role.FieldID, id), - sqlgraph.To(userrole.Table, userrole.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, role.UserRolesTable, role.UserRolesColumn), - ) - fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) - return fromV, nil - } - return query -} - -// Hooks returns the client hooks. -func (c *RoleClient) Hooks() []Hook { - return c.hooks.Role -} - -// Interceptors returns the client interceptors. -func (c *RoleClient) Interceptors() []Interceptor { - return c.inters.Role -} - -func (c *RoleClient) mutate(ctx context.Context, m *RoleMutation) (Value, error) { - switch m.Op() { - case OpCreate: - return (&RoleCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdate: - return (&RoleUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdateOne: - return (&RoleUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpDelete, OpDeleteOne: - return (&RoleDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) - default: - return nil, fmt.Errorf("ent: unknown Role mutation op: %q", m.Op()) - } -} - -// RolePermissionClient is a client for the RolePermission schema. -type RolePermissionClient struct { - config -} - -// NewRolePermissionClient returns a client for the RolePermission from the given config. -func NewRolePermissionClient(c config) *RolePermissionClient { - return &RolePermissionClient{config: c} -} - -// Use adds a list of mutation hooks to the hooks stack. -// A call to `Use(f, g, h)` equals to `rolepermission.Hooks(f(g(h())))`. -func (c *RolePermissionClient) Use(hooks ...Hook) { - c.hooks.RolePermission = append(c.hooks.RolePermission, hooks...) -} - -// Intercept adds a list of query interceptors to the interceptors stack. -// A call to `Intercept(f, g, h)` equals to `rolepermission.Intercept(f(g(h())))`. -func (c *RolePermissionClient) Intercept(interceptors ...Interceptor) { - c.inters.RolePermission = append(c.inters.RolePermission, interceptors...) -} - -// Create returns a builder for creating a RolePermission entity. -func (c *RolePermissionClient) Create() *RolePermissionCreate { - mutation := newRolePermissionMutation(c.config, OpCreate) - return &RolePermissionCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// CreateBulk returns a builder for creating a bulk of RolePermission entities. -func (c *RolePermissionClient) CreateBulk(builders ...*RolePermissionCreate) *RolePermissionCreateBulk { - return &RolePermissionCreateBulk{config: c.config, builders: builders} -} - -// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates -// a builder and applies setFunc on it. -func (c *RolePermissionClient) MapCreateBulk(slice any, setFunc func(*RolePermissionCreate, int)) *RolePermissionCreateBulk { - rv := reflect.ValueOf(slice) - if rv.Kind() != reflect.Slice { - return &RolePermissionCreateBulk{err: fmt.Errorf("calling to RolePermissionClient.MapCreateBulk with wrong type %T, need slice", slice)} - } - builders := make([]*RolePermissionCreate, rv.Len()) - for i := 0; i < rv.Len(); i++ { - builders[i] = c.Create() - setFunc(builders[i], i) - } - return &RolePermissionCreateBulk{config: c.config, builders: builders} -} - -// Update returns an update builder for RolePermission. -func (c *RolePermissionClient) Update() *RolePermissionUpdate { - mutation := newRolePermissionMutation(c.config, OpUpdate) - return &RolePermissionUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOne returns an update builder for the given entity. -func (c *RolePermissionClient) UpdateOne(_m *RolePermission) *RolePermissionUpdateOne { - mutation := newRolePermissionMutation(c.config, OpUpdateOne, withRolePermission(_m)) - return &RolePermissionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOneID returns an update builder for the given id. -func (c *RolePermissionClient) UpdateOneID(id int) *RolePermissionUpdateOne { - mutation := newRolePermissionMutation(c.config, OpUpdateOne, withRolePermissionID(id)) - return &RolePermissionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// Delete returns a delete builder for RolePermission. -func (c *RolePermissionClient) Delete() *RolePermissionDelete { - mutation := newRolePermissionMutation(c.config, OpDelete) - return &RolePermissionDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// DeleteOne returns a builder for deleting the given entity. -func (c *RolePermissionClient) DeleteOne(_m *RolePermission) *RolePermissionDeleteOne { - return c.DeleteOneID(_m.ID) -} - -// DeleteOneID returns a builder for deleting the given entity by its id. -func (c *RolePermissionClient) DeleteOneID(id int) *RolePermissionDeleteOne { - builder := c.Delete().Where(rolepermission.ID(id)) - builder.mutation.id = &id - builder.mutation.op = OpDeleteOne - return &RolePermissionDeleteOne{builder} -} - -// Query returns a query builder for RolePermission. -func (c *RolePermissionClient) Query() *RolePermissionQuery { - return &RolePermissionQuery{ - config: c.config, - ctx: &QueryContext{Type: TypeRolePermission}, - inters: c.Interceptors(), - } -} - -// Get returns a RolePermission entity by its id. -func (c *RolePermissionClient) Get(ctx context.Context, id int) (*RolePermission, error) { - return c.Query().Where(rolepermission.ID(id)).Only(ctx) -} - -// GetX is like Get, but panics if an error occurs. -func (c *RolePermissionClient) GetX(ctx context.Context, id int) *RolePermission { - obj, err := c.Get(ctx, id) - if err != nil { - panic(err) - } - return obj -} - -// QueryRole queries the role edge of a RolePermission. -func (c *RolePermissionClient) QueryRole(_m *RolePermission) *RoleQuery { - query := (&RoleClient{config: c.config}).Query() - query.path = func(context.Context) (fromV *sql.Selector, _ error) { - id := _m.ID - step := sqlgraph.NewStep( - sqlgraph.From(rolepermission.Table, rolepermission.FieldID, id), - sqlgraph.To(role.Table, role.FieldID), - sqlgraph.Edge(sqlgraph.M2O, false, rolepermission.RoleTable, rolepermission.RoleColumn), - ) - fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) - return fromV, nil - } - return query -} - -// QueryPermission queries the permission edge of a RolePermission. -func (c *RolePermissionClient) QueryPermission(_m *RolePermission) *PermissionQuery { - query := (&PermissionClient{config: c.config}).Query() - query.path = func(context.Context) (fromV *sql.Selector, _ error) { - id := _m.ID - step := sqlgraph.NewStep( - sqlgraph.From(rolepermission.Table, rolepermission.FieldID, id), - sqlgraph.To(permission.Table, permission.FieldID), - sqlgraph.Edge(sqlgraph.M2O, false, rolepermission.PermissionTable, rolepermission.PermissionColumn), - ) - fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) - return fromV, nil - } - return query -} - -// Hooks returns the client hooks. -func (c *RolePermissionClient) Hooks() []Hook { - return c.hooks.RolePermission -} - -// Interceptors returns the client interceptors. -func (c *RolePermissionClient) Interceptors() []Interceptor { - return c.inters.RolePermission -} - -func (c *RolePermissionClient) mutate(ctx context.Context, m *RolePermissionMutation) (Value, error) { - switch m.Op() { - case OpCreate: - return (&RolePermissionCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdate: - return (&RolePermissionUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdateOne: - return (&RolePermissionUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpDelete, OpDeleteOne: - return (&RolePermissionDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) - default: - return nil, fmt.Errorf("ent: unknown RolePermission mutation op: %q", m.Op()) - } -} - -// UserClient is a client for the User schema. -type UserClient struct { - config -} - -// NewUserClient returns a client for the User from the given config. -func NewUserClient(c config) *UserClient { - return &UserClient{config: c} -} - -// Use adds a list of mutation hooks to the hooks stack. -// A call to `Use(f, g, h)` equals to `user.Hooks(f(g(h())))`. -func (c *UserClient) Use(hooks ...Hook) { - c.hooks.User = append(c.hooks.User, hooks...) -} - -// Intercept adds a list of query interceptors to the interceptors stack. -// A call to `Intercept(f, g, h)` equals to `user.Intercept(f(g(h())))`. -func (c *UserClient) Intercept(interceptors ...Interceptor) { - c.inters.User = append(c.inters.User, interceptors...) -} - -// Create returns a builder for creating a User entity. -func (c *UserClient) Create() *UserCreate { - mutation := newUserMutation(c.config, OpCreate) - return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// CreateBulk returns a builder for creating a bulk of User entities. -func (c *UserClient) CreateBulk(builders ...*UserCreate) *UserCreateBulk { - return &UserCreateBulk{config: c.config, builders: builders} -} - -// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates -// a builder and applies setFunc on it. -func (c *UserClient) MapCreateBulk(slice any, setFunc func(*UserCreate, int)) *UserCreateBulk { - rv := reflect.ValueOf(slice) - if rv.Kind() != reflect.Slice { - return &UserCreateBulk{err: fmt.Errorf("calling to UserClient.MapCreateBulk with wrong type %T, need slice", slice)} - } - builders := make([]*UserCreate, rv.Len()) - for i := 0; i < rv.Len(); i++ { - builders[i] = c.Create() - setFunc(builders[i], i) - } - return &UserCreateBulk{config: c.config, builders: builders} -} - -// Update returns an update builder for User. -func (c *UserClient) Update() *UserUpdate { - mutation := newUserMutation(c.config, OpUpdate) - return &UserUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOne returns an update builder for the given entity. -func (c *UserClient) UpdateOne(_m *User) *UserUpdateOne { - mutation := newUserMutation(c.config, OpUpdateOne, withUser(_m)) - return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOneID returns an update builder for the given id. -func (c *UserClient) UpdateOneID(id string) *UserUpdateOne { - mutation := newUserMutation(c.config, OpUpdateOne, withUserID(id)) - return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// Delete returns a delete builder for User. -func (c *UserClient) Delete() *UserDelete { - mutation := newUserMutation(c.config, OpDelete) - return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// DeleteOne returns a builder for deleting the given entity. -func (c *UserClient) DeleteOne(_m *User) *UserDeleteOne { - return c.DeleteOneID(_m.ID) -} - -// DeleteOneID returns a builder for deleting the given entity by its id. -func (c *UserClient) DeleteOneID(id string) *UserDeleteOne { - builder := c.Delete().Where(user.ID(id)) - builder.mutation.id = &id - builder.mutation.op = OpDeleteOne - return &UserDeleteOne{builder} -} - -// Query returns a query builder for User. -func (c *UserClient) Query() *UserQuery { - return &UserQuery{ - config: c.config, - ctx: &QueryContext{Type: TypeUser}, - inters: c.Interceptors(), - } -} - -// Get returns a User entity by its id. -func (c *UserClient) Get(ctx context.Context, id string) (*User, error) { - return c.Query().Where(user.ID(id)).Only(ctx) -} - -// GetX is like Get, but panics if an error occurs. -func (c *UserClient) GetX(ctx context.Context, id string) *User { - obj, err := c.Get(ctx, id) - if err != nil { - panic(err) - } - return obj -} - -// QueryUserRoles queries the user_roles edge of a User. -func (c *UserClient) QueryUserRoles(_m *User) *UserRoleQuery { - query := (&UserRoleClient{config: c.config}).Query() - query.path = func(context.Context) (fromV *sql.Selector, _ error) { - id := _m.ID - step := sqlgraph.NewStep( - sqlgraph.From(user.Table, user.FieldID, id), - sqlgraph.To(userrole.Table, userrole.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, user.UserRolesTable, user.UserRolesColumn), - ) - fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) - return fromV, nil - } - return query -} - -// Hooks returns the client hooks. -func (c *UserClient) Hooks() []Hook { - return c.hooks.User -} - -// Interceptors returns the client interceptors. -func (c *UserClient) Interceptors() []Interceptor { - return c.inters.User -} - -func (c *UserClient) mutate(ctx context.Context, m *UserMutation) (Value, error) { - switch m.Op() { - case OpCreate: - return (&UserCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdate: - return (&UserUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdateOne: - return (&UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpDelete, OpDeleteOne: - return (&UserDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) - default: - return nil, fmt.Errorf("ent: unknown User mutation op: %q", m.Op()) - } -} - -// UserRoleClient is a client for the UserRole schema. -type UserRoleClient struct { - config -} - -// NewUserRoleClient returns a client for the UserRole from the given config. -func NewUserRoleClient(c config) *UserRoleClient { - return &UserRoleClient{config: c} -} - -// Use adds a list of mutation hooks to the hooks stack. -// A call to `Use(f, g, h)` equals to `userrole.Hooks(f(g(h())))`. -func (c *UserRoleClient) Use(hooks ...Hook) { - c.hooks.UserRole = append(c.hooks.UserRole, hooks...) -} - -// Intercept adds a list of query interceptors to the interceptors stack. -// A call to `Intercept(f, g, h)` equals to `userrole.Intercept(f(g(h())))`. -func (c *UserRoleClient) Intercept(interceptors ...Interceptor) { - c.inters.UserRole = append(c.inters.UserRole, interceptors...) -} - -// Create returns a builder for creating a UserRole entity. -func (c *UserRoleClient) Create() *UserRoleCreate { - mutation := newUserRoleMutation(c.config, OpCreate) - return &UserRoleCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// CreateBulk returns a builder for creating a bulk of UserRole entities. -func (c *UserRoleClient) CreateBulk(builders ...*UserRoleCreate) *UserRoleCreateBulk { - return &UserRoleCreateBulk{config: c.config, builders: builders} -} - -// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates -// a builder and applies setFunc on it. -func (c *UserRoleClient) MapCreateBulk(slice any, setFunc func(*UserRoleCreate, int)) *UserRoleCreateBulk { - rv := reflect.ValueOf(slice) - if rv.Kind() != reflect.Slice { - return &UserRoleCreateBulk{err: fmt.Errorf("calling to UserRoleClient.MapCreateBulk with wrong type %T, need slice", slice)} - } - builders := make([]*UserRoleCreate, rv.Len()) - for i := 0; i < rv.Len(); i++ { - builders[i] = c.Create() - setFunc(builders[i], i) - } - return &UserRoleCreateBulk{config: c.config, builders: builders} -} - -// Update returns an update builder for UserRole. -func (c *UserRoleClient) Update() *UserRoleUpdate { - mutation := newUserRoleMutation(c.config, OpUpdate) - return &UserRoleUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOne returns an update builder for the given entity. -func (c *UserRoleClient) UpdateOne(_m *UserRole) *UserRoleUpdateOne { - mutation := newUserRoleMutation(c.config, OpUpdateOne, withUserRole(_m)) - return &UserRoleUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// UpdateOneID returns an update builder for the given id. -func (c *UserRoleClient) UpdateOneID(id int) *UserRoleUpdateOne { - mutation := newUserRoleMutation(c.config, OpUpdateOne, withUserRoleID(id)) - return &UserRoleUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// Delete returns a delete builder for UserRole. -func (c *UserRoleClient) Delete() *UserRoleDelete { - mutation := newUserRoleMutation(c.config, OpDelete) - return &UserRoleDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} -} - -// DeleteOne returns a builder for deleting the given entity. -func (c *UserRoleClient) DeleteOne(_m *UserRole) *UserRoleDeleteOne { - return c.DeleteOneID(_m.ID) -} - -// DeleteOneID returns a builder for deleting the given entity by its id. -func (c *UserRoleClient) DeleteOneID(id int) *UserRoleDeleteOne { - builder := c.Delete().Where(userrole.ID(id)) - builder.mutation.id = &id - builder.mutation.op = OpDeleteOne - return &UserRoleDeleteOne{builder} -} - -// Query returns a query builder for UserRole. -func (c *UserRoleClient) Query() *UserRoleQuery { - return &UserRoleQuery{ - config: c.config, - ctx: &QueryContext{Type: TypeUserRole}, - inters: c.Interceptors(), - } -} - -// Get returns a UserRole entity by its id. -func (c *UserRoleClient) Get(ctx context.Context, id int) (*UserRole, error) { - return c.Query().Where(userrole.ID(id)).Only(ctx) -} - -// GetX is like Get, but panics if an error occurs. -func (c *UserRoleClient) GetX(ctx context.Context, id int) *UserRole { - obj, err := c.Get(ctx, id) - if err != nil { - panic(err) - } - return obj -} - -// QueryUser queries the user edge of a UserRole. -func (c *UserRoleClient) QueryUser(_m *UserRole) *UserQuery { - query := (&UserClient{config: c.config}).Query() - query.path = func(context.Context) (fromV *sql.Selector, _ error) { - id := _m.ID - step := sqlgraph.NewStep( - sqlgraph.From(userrole.Table, userrole.FieldID, id), - sqlgraph.To(user.Table, user.FieldID), - sqlgraph.Edge(sqlgraph.M2O, false, userrole.UserTable, userrole.UserColumn), - ) - fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) - return fromV, nil - } - return query -} - -// QueryRole queries the role edge of a UserRole. -func (c *UserRoleClient) QueryRole(_m *UserRole) *RoleQuery { - query := (&RoleClient{config: c.config}).Query() - query.path = func(context.Context) (fromV *sql.Selector, _ error) { - id := _m.ID - step := sqlgraph.NewStep( - sqlgraph.From(userrole.Table, userrole.FieldID, id), - sqlgraph.To(role.Table, role.FieldID), - sqlgraph.Edge(sqlgraph.M2O, false, userrole.RoleTable, userrole.RoleColumn), - ) - fromV = sqlgraph.Neighbors(_m.driver.Dialect(), step) - return fromV, nil - } - return query -} - -// Hooks returns the client hooks. -func (c *UserRoleClient) Hooks() []Hook { - return c.hooks.UserRole -} - -// Interceptors returns the client interceptors. -func (c *UserRoleClient) Interceptors() []Interceptor { - return c.inters.UserRole -} - -func (c *UserRoleClient) mutate(ctx context.Context, m *UserRoleMutation) (Value, error) { - switch m.Op() { - case OpCreate: - return (&UserRoleCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdate: - return (&UserRoleUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpUpdateOne: - return (&UserRoleUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) - case OpDelete, OpDeleteOne: - return (&UserRoleDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) - default: - return nil, fmt.Errorf("ent: unknown UserRole mutation op: %q", m.Op()) - } -} - -// hooks and interceptors per client, for fast access. -type ( - hooks struct { - AuditLog, Permission, RefreshToken, Role, RolePermission, User, - UserRole []ent.Hook - } - inters struct { - AuditLog, Permission, RefreshToken, Role, RolePermission, User, - UserRole []ent.Interceptor - } -) diff --git a/internal/ent/ent.go b/internal/ent/ent.go deleted file mode 100644 index 06a26ec..0000000 --- a/internal/ent/ent.go +++ /dev/null @@ -1,620 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "errors" - "fmt" - "reflect" - "sync" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "git.dcentral.systems/toolz/goplt/internal/ent/auditlog" - "git.dcentral.systems/toolz/goplt/internal/ent/permission" - "git.dcentral.systems/toolz/goplt/internal/ent/refreshtoken" - "git.dcentral.systems/toolz/goplt/internal/ent/role" - "git.dcentral.systems/toolz/goplt/internal/ent/rolepermission" - "git.dcentral.systems/toolz/goplt/internal/ent/user" - "git.dcentral.systems/toolz/goplt/internal/ent/userrole" -) - -// ent aliases to avoid import conflicts in user's code. -type ( - Op = ent.Op - Hook = ent.Hook - Value = ent.Value - Query = ent.Query - QueryContext = ent.QueryContext - Querier = ent.Querier - QuerierFunc = ent.QuerierFunc - Interceptor = ent.Interceptor - InterceptFunc = ent.InterceptFunc - Traverser = ent.Traverser - TraverseFunc = ent.TraverseFunc - Policy = ent.Policy - Mutator = ent.Mutator - Mutation = ent.Mutation - MutateFunc = ent.MutateFunc -) - -type clientCtxKey struct{} - -// FromContext returns a Client stored inside a context, or nil if there isn't one. -func FromContext(ctx context.Context) *Client { - c, _ := ctx.Value(clientCtxKey{}).(*Client) - return c -} - -// NewContext returns a new context with the given Client attached. -func NewContext(parent context.Context, c *Client) context.Context { - return context.WithValue(parent, clientCtxKey{}, c) -} - -type txCtxKey struct{} - -// TxFromContext returns a Tx stored inside a context, or nil if there isn't one. -func TxFromContext(ctx context.Context) *Tx { - tx, _ := ctx.Value(txCtxKey{}).(*Tx) - return tx -} - -// NewTxContext returns a new context with the given Tx attached. -func NewTxContext(parent context.Context, tx *Tx) context.Context { - return context.WithValue(parent, txCtxKey{}, tx) -} - -// OrderFunc applies an ordering on the sql selector. -// Deprecated: Use Asc/Desc functions or the package builders instead. -type OrderFunc func(*sql.Selector) - -var ( - initCheck sync.Once - columnCheck sql.ColumnCheck -) - -// checkColumn checks if the column exists in the given table. -func checkColumn(t, c string) error { - initCheck.Do(func() { - columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ - auditlog.Table: auditlog.ValidColumn, - permission.Table: permission.ValidColumn, - refreshtoken.Table: refreshtoken.ValidColumn, - role.Table: role.ValidColumn, - rolepermission.Table: rolepermission.ValidColumn, - user.Table: user.ValidColumn, - userrole.Table: userrole.ValidColumn, - }) - }) - return columnCheck(t, c) -} - -// Asc applies the given fields in ASC order. -func Asc(fields ...string) func(*sql.Selector) { - return func(s *sql.Selector) { - for _, f := range fields { - if err := checkColumn(s.TableName(), f); err != nil { - s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)}) - } - s.OrderBy(sql.Asc(s.C(f))) - } - } -} - -// Desc applies the given fields in DESC order. -func Desc(fields ...string) func(*sql.Selector) { - return func(s *sql.Selector) { - for _, f := range fields { - if err := checkColumn(s.TableName(), f); err != nil { - s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)}) - } - s.OrderBy(sql.Desc(s.C(f))) - } - } -} - -// AggregateFunc applies an aggregation step on the group-by traversal/selector. -type AggregateFunc func(*sql.Selector) string - -// As is a pseudo aggregation function for renaming another other functions with custom names. For example: -// -// GroupBy(field1, field2). -// Aggregate(ent.As(ent.Sum(field1), "sum_field1"), (ent.As(ent.Sum(field2), "sum_field2")). -// Scan(ctx, &v) -func As(fn AggregateFunc, end string) AggregateFunc { - return func(s *sql.Selector) string { - return sql.As(fn(s), end) - } -} - -// Count applies the "count" aggregation function on each group. -func Count() AggregateFunc { - return func(s *sql.Selector) string { - return sql.Count("*") - } -} - -// Max applies the "max" aggregation function on the given field of each group. -func Max(field string) AggregateFunc { - return func(s *sql.Selector) string { - if err := checkColumn(s.TableName(), field); err != nil { - s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) - return "" - } - return sql.Max(s.C(field)) - } -} - -// Mean applies the "mean" aggregation function on the given field of each group. -func Mean(field string) AggregateFunc { - return func(s *sql.Selector) string { - if err := checkColumn(s.TableName(), field); err != nil { - s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) - return "" - } - return sql.Avg(s.C(field)) - } -} - -// Min applies the "min" aggregation function on the given field of each group. -func Min(field string) AggregateFunc { - return func(s *sql.Selector) string { - if err := checkColumn(s.TableName(), field); err != nil { - s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) - return "" - } - return sql.Min(s.C(field)) - } -} - -// Sum applies the "sum" aggregation function on the given field of each group. -func Sum(field string) AggregateFunc { - return func(s *sql.Selector) string { - if err := checkColumn(s.TableName(), field); err != nil { - s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) - return "" - } - return sql.Sum(s.C(field)) - } -} - -// ValidationError returns when validating a field or edge fails. -type ValidationError struct { - Name string // Field or edge name. - err error -} - -// Error implements the error interface. -func (e *ValidationError) Error() string { - return e.err.Error() -} - -// Unwrap implements the errors.Wrapper interface. -func (e *ValidationError) Unwrap() error { - return e.err -} - -// IsValidationError returns a boolean indicating whether the error is a validation error. -func IsValidationError(err error) bool { - if err == nil { - return false - } - var e *ValidationError - return errors.As(err, &e) -} - -// NotFoundError returns when trying to fetch a specific entity and it was not found in the database. -type NotFoundError struct { - label string -} - -// Error implements the error interface. -func (e *NotFoundError) Error() string { - return "ent: " + e.label + " not found" -} - -// IsNotFound returns a boolean indicating whether the error is a not found error. -func IsNotFound(err error) bool { - if err == nil { - return false - } - var e *NotFoundError - return errors.As(err, &e) -} - -// MaskNotFound masks not found error. -func MaskNotFound(err error) error { - if IsNotFound(err) { - return nil - } - return err -} - -// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database. -type NotSingularError struct { - label string -} - -// Error implements the error interface. -func (e *NotSingularError) Error() string { - return "ent: " + e.label + " not singular" -} - -// IsNotSingular returns a boolean indicating whether the error is a not singular error. -func IsNotSingular(err error) bool { - if err == nil { - return false - } - var e *NotSingularError - return errors.As(err, &e) -} - -// NotLoadedError returns when trying to get a node that was not loaded by the query. -type NotLoadedError struct { - edge string -} - -// Error implements the error interface. -func (e *NotLoadedError) Error() string { - return "ent: " + e.edge + " edge was not loaded" -} - -// IsNotLoaded returns a boolean indicating whether the error is a not loaded error. -func IsNotLoaded(err error) bool { - if err == nil { - return false - } - var e *NotLoadedError - return errors.As(err, &e) -} - -// ConstraintError returns when trying to create/update one or more entities and -// one or more of their constraints failed. For example, violation of edge or -// field uniqueness. -type ConstraintError struct { - msg string - wrap error -} - -// Error implements the error interface. -func (e ConstraintError) Error() string { - return "ent: constraint failed: " + e.msg -} - -// Unwrap implements the errors.Wrapper interface. -func (e *ConstraintError) Unwrap() error { - return e.wrap -} - -// IsConstraintError returns a boolean indicating whether the error is a constraint failure. -func IsConstraintError(err error) bool { - if err == nil { - return false - } - var e *ConstraintError - return errors.As(err, &e) -} - -// selector embedded by the different Select/GroupBy builders. -type selector struct { - label string - flds *[]string - fns []AggregateFunc - scan func(context.Context, any) error -} - -// ScanX is like Scan, but panics if an error occurs. -func (s *selector) ScanX(ctx context.Context, v any) { - if err := s.scan(ctx, v); err != nil { - panic(err) - } -} - -// Strings returns list of strings from a selector. It is only allowed when selecting one field. -func (s *selector) Strings(ctx context.Context) ([]string, error) { - if len(*s.flds) > 1 { - return nil, errors.New("ent: Strings is not achievable when selecting more than 1 field") - } - var v []string - if err := s.scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// StringsX is like Strings, but panics if an error occurs. -func (s *selector) StringsX(ctx context.Context) []string { - v, err := s.Strings(ctx) - if err != nil { - panic(err) - } - return v -} - -// String returns a single string from a selector. It is only allowed when selecting one field. -func (s *selector) String(ctx context.Context) (_ string, err error) { - var v []string - if v, err = s.Strings(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{s.label} - default: - err = fmt.Errorf("ent: Strings returned %d results when one was expected", len(v)) - } - return -} - -// StringX is like String, but panics if an error occurs. -func (s *selector) StringX(ctx context.Context) string { - v, err := s.String(ctx) - if err != nil { - panic(err) - } - return v -} - -// Ints returns list of ints from a selector. It is only allowed when selecting one field. -func (s *selector) Ints(ctx context.Context) ([]int, error) { - if len(*s.flds) > 1 { - return nil, errors.New("ent: Ints is not achievable when selecting more than 1 field") - } - var v []int - if err := s.scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// IntsX is like Ints, but panics if an error occurs. -func (s *selector) IntsX(ctx context.Context) []int { - v, err := s.Ints(ctx) - if err != nil { - panic(err) - } - return v -} - -// Int returns a single int from a selector. It is only allowed when selecting one field. -func (s *selector) Int(ctx context.Context) (_ int, err error) { - var v []int - if v, err = s.Ints(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{s.label} - default: - err = fmt.Errorf("ent: Ints returned %d results when one was expected", len(v)) - } - return -} - -// IntX is like Int, but panics if an error occurs. -func (s *selector) IntX(ctx context.Context) int { - v, err := s.Int(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64s returns list of float64s from a selector. It is only allowed when selecting one field. -func (s *selector) Float64s(ctx context.Context) ([]float64, error) { - if len(*s.flds) > 1 { - return nil, errors.New("ent: Float64s is not achievable when selecting more than 1 field") - } - var v []float64 - if err := s.scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// Float64sX is like Float64s, but panics if an error occurs. -func (s *selector) Float64sX(ctx context.Context) []float64 { - v, err := s.Float64s(ctx) - if err != nil { - panic(err) - } - return v -} - -// Float64 returns a single float64 from a selector. It is only allowed when selecting one field. -func (s *selector) Float64(ctx context.Context) (_ float64, err error) { - var v []float64 - if v, err = s.Float64s(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{s.label} - default: - err = fmt.Errorf("ent: Float64s returned %d results when one was expected", len(v)) - } - return -} - -// Float64X is like Float64, but panics if an error occurs. -func (s *selector) Float64X(ctx context.Context) float64 { - v, err := s.Float64(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bools returns list of bools from a selector. It is only allowed when selecting one field. -func (s *selector) Bools(ctx context.Context) ([]bool, error) { - if len(*s.flds) > 1 { - return nil, errors.New("ent: Bools is not achievable when selecting more than 1 field") - } - var v []bool - if err := s.scan(ctx, &v); err != nil { - return nil, err - } - return v, nil -} - -// BoolsX is like Bools, but panics if an error occurs. -func (s *selector) BoolsX(ctx context.Context) []bool { - v, err := s.Bools(ctx) - if err != nil { - panic(err) - } - return v -} - -// Bool returns a single bool from a selector. It is only allowed when selecting one field. -func (s *selector) Bool(ctx context.Context) (_ bool, err error) { - var v []bool - if v, err = s.Bools(ctx); err != nil { - return - } - switch len(v) { - case 1: - return v[0], nil - case 0: - err = &NotFoundError{s.label} - default: - err = fmt.Errorf("ent: Bools returned %d results when one was expected", len(v)) - } - return -} - -// BoolX is like Bool, but panics if an error occurs. -func (s *selector) BoolX(ctx context.Context) bool { - v, err := s.Bool(ctx) - if err != nil { - panic(err) - } - return v -} - -// withHooks invokes the builder operation with the given hooks, if any. -func withHooks[V Value, M any, PM interface { - *M - Mutation -}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) { - if len(hooks) == 0 { - return exec(ctx) - } - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutationT, ok := any(m).(PM) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - // Set the mutation to the builder. - *mutation = *mutationT - return exec(ctx) - }) - for i := len(hooks) - 1; i >= 0; i-- { - if hooks[i] == nil { - return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") - } - mut = hooks[i](mut) - } - v, err := mut.Mutate(ctx, mutation) - if err != nil { - return value, err - } - nv, ok := v.(V) - if !ok { - return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation) - } - return nv, nil -} - -// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist. -func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context { - if ent.QueryFromContext(ctx) == nil { - qc.Op = op - ctx = ent.NewQueryContext(ctx, qc) - } - return ctx -} - -func querierAll[V Value, Q interface { - sqlAll(context.Context, ...queryHook) (V, error) -}]() Querier { - return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { - query, ok := q.(Q) - if !ok { - return nil, fmt.Errorf("unexpected query type %T", q) - } - return query.sqlAll(ctx) - }) -} - -func querierCount[Q interface { - sqlCount(context.Context) (int, error) -}]() Querier { - return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { - query, ok := q.(Q) - if !ok { - return nil, fmt.Errorf("unexpected query type %T", q) - } - return query.sqlCount(ctx) - }) -} - -func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) { - for i := len(inters) - 1; i >= 0; i-- { - qr = inters[i].Intercept(qr) - } - rv, err := qr.Query(ctx, q) - if err != nil { - return v, err - } - vt, ok := rv.(V) - if !ok { - return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v) - } - return vt, nil -} - -func scanWithInterceptors[Q1 ent.Query, Q2 interface { - sqlScan(context.Context, Q1, any) error -}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error { - rv := reflect.ValueOf(v) - var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) { - query, ok := q.(Q1) - if !ok { - return nil, fmt.Errorf("unexpected query type %T", q) - } - if err := selectOrGroup.sqlScan(ctx, query, v); err != nil { - return nil, err - } - if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() { - return rv.Elem().Interface(), nil - } - return v, nil - }) - for i := len(inters) - 1; i >= 0; i-- { - qr = inters[i].Intercept(qr) - } - vv, err := qr.Query(ctx, rootQuery) - if err != nil { - return err - } - switch rv2 := reflect.ValueOf(vv); { - case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer: - case rv.Type() == rv2.Type(): - rv.Elem().Set(rv2.Elem()) - case rv.Elem().Type() == rv2.Type(): - rv.Elem().Set(rv2) - } - return nil -} - -// queryHook describes an internal hook for the different sqlAll methods. -type queryHook func(context.Context, *sqlgraph.QuerySpec) diff --git a/internal/ent/enttest/enttest.go b/internal/ent/enttest/enttest.go deleted file mode 100644 index 7e3c6e6..0000000 --- a/internal/ent/enttest/enttest.go +++ /dev/null @@ -1,84 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package enttest - -import ( - "context" - - "git.dcentral.systems/toolz/goplt/internal/ent" - // required by schema hooks. - _ "git.dcentral.systems/toolz/goplt/internal/ent/runtime" - - "entgo.io/ent/dialect/sql/schema" - "git.dcentral.systems/toolz/goplt/internal/ent/migrate" -) - -type ( - // TestingT is the interface that is shared between - // testing.T and testing.B and used by enttest. - TestingT interface { - FailNow() - Error(...any) - } - - // Option configures client creation. - Option func(*options) - - options struct { - opts []ent.Option - migrateOpts []schema.MigrateOption - } -) - -// WithOptions forwards options to client creation. -func WithOptions(opts ...ent.Option) Option { - return func(o *options) { - o.opts = append(o.opts, opts...) - } -} - -// WithMigrateOptions forwards options to auto migration. -func WithMigrateOptions(opts ...schema.MigrateOption) Option { - return func(o *options) { - o.migrateOpts = append(o.migrateOpts, opts...) - } -} - -func newOptions(opts []Option) *options { - o := &options{} - for _, opt := range opts { - opt(o) - } - return o -} - -// Open calls ent.Open and auto-run migration. -func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *ent.Client { - o := newOptions(opts) - c, err := ent.Open(driverName, dataSourceName, o.opts...) - if err != nil { - t.Error(err) - t.FailNow() - } - migrateSchema(t, c, o) - return c -} - -// NewClient calls ent.NewClient and auto-run migration. -func NewClient(t TestingT, opts ...Option) *ent.Client { - o := newOptions(opts) - c := ent.NewClient(o.opts...) - migrateSchema(t, c, o) - return c -} -func migrateSchema(t TestingT, c *ent.Client, o *options) { - tables, err := schema.CopyTables(migrate.Tables) - if err != nil { - t.Error(err) - t.FailNow() - } - if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil { - t.Error(err) - t.FailNow() - } -} diff --git a/internal/ent/hook/hook.go b/internal/ent/hook/hook.go deleted file mode 100644 index c534315..0000000 --- a/internal/ent/hook/hook.go +++ /dev/null @@ -1,271 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package hook - -import ( - "context" - "fmt" - - "git.dcentral.systems/toolz/goplt/internal/ent" -) - -// The AuditLogFunc type is an adapter to allow the use of ordinary -// function as AuditLog mutator. -type AuditLogFunc func(context.Context, *ent.AuditLogMutation) (ent.Value, error) - -// Mutate calls f(ctx, m). -func (f AuditLogFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { - if mv, ok := m.(*ent.AuditLogMutation); ok { - return f(ctx, mv) - } - return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.AuditLogMutation", m) -} - -// The PermissionFunc type is an adapter to allow the use of ordinary -// function as Permission mutator. -type PermissionFunc func(context.Context, *ent.PermissionMutation) (ent.Value, error) - -// Mutate calls f(ctx, m). -func (f PermissionFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { - if mv, ok := m.(*ent.PermissionMutation); ok { - return f(ctx, mv) - } - return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.PermissionMutation", m) -} - -// The RefreshTokenFunc type is an adapter to allow the use of ordinary -// function as RefreshToken mutator. -type RefreshTokenFunc func(context.Context, *ent.RefreshTokenMutation) (ent.Value, error) - -// Mutate calls f(ctx, m). -func (f RefreshTokenFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { - if mv, ok := m.(*ent.RefreshTokenMutation); ok { - return f(ctx, mv) - } - return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.RefreshTokenMutation", m) -} - -// The RoleFunc type is an adapter to allow the use of ordinary -// function as Role mutator. -type RoleFunc func(context.Context, *ent.RoleMutation) (ent.Value, error) - -// Mutate calls f(ctx, m). -func (f RoleFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { - if mv, ok := m.(*ent.RoleMutation); ok { - return f(ctx, mv) - } - return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.RoleMutation", m) -} - -// The RolePermissionFunc type is an adapter to allow the use of ordinary -// function as RolePermission mutator. -type RolePermissionFunc func(context.Context, *ent.RolePermissionMutation) (ent.Value, error) - -// Mutate calls f(ctx, m). -func (f RolePermissionFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { - if mv, ok := m.(*ent.RolePermissionMutation); ok { - return f(ctx, mv) - } - return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.RolePermissionMutation", m) -} - -// The UserFunc type is an adapter to allow the use of ordinary -// function as User mutator. -type UserFunc func(context.Context, *ent.UserMutation) (ent.Value, error) - -// Mutate calls f(ctx, m). -func (f UserFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { - if mv, ok := m.(*ent.UserMutation); ok { - return f(ctx, mv) - } - return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserMutation", m) -} - -// The UserRoleFunc type is an adapter to allow the use of ordinary -// function as UserRole mutator. -type UserRoleFunc func(context.Context, *ent.UserRoleMutation) (ent.Value, error) - -// Mutate calls f(ctx, m). -func (f UserRoleFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { - if mv, ok := m.(*ent.UserRoleMutation); ok { - return f(ctx, mv) - } - return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserRoleMutation", m) -} - -// Condition is a hook condition function. -type Condition func(context.Context, ent.Mutation) bool - -// And groups conditions with the AND operator. -func And(first, second Condition, rest ...Condition) Condition { - return func(ctx context.Context, m ent.Mutation) bool { - if !first(ctx, m) || !second(ctx, m) { - return false - } - for _, cond := range rest { - if !cond(ctx, m) { - return false - } - } - return true - } -} - -// Or groups conditions with the OR operator. -func Or(first, second Condition, rest ...Condition) Condition { - return func(ctx context.Context, m ent.Mutation) bool { - if first(ctx, m) || second(ctx, m) { - return true - } - for _, cond := range rest { - if cond(ctx, m) { - return true - } - } - return false - } -} - -// Not negates a given condition. -func Not(cond Condition) Condition { - return func(ctx context.Context, m ent.Mutation) bool { - return !cond(ctx, m) - } -} - -// HasOp is a condition testing mutation operation. -func HasOp(op ent.Op) Condition { - return func(_ context.Context, m ent.Mutation) bool { - return m.Op().Is(op) - } -} - -// HasAddedFields is a condition validating `.AddedField` on fields. -func HasAddedFields(field string, fields ...string) Condition { - return func(_ context.Context, m ent.Mutation) bool { - if _, exists := m.AddedField(field); !exists { - return false - } - for _, field := range fields { - if _, exists := m.AddedField(field); !exists { - return false - } - } - return true - } -} - -// HasClearedFields is a condition validating `.FieldCleared` on fields. -func HasClearedFields(field string, fields ...string) Condition { - return func(_ context.Context, m ent.Mutation) bool { - if exists := m.FieldCleared(field); !exists { - return false - } - for _, field := range fields { - if exists := m.FieldCleared(field); !exists { - return false - } - } - return true - } -} - -// HasFields is a condition validating `.Field` on fields. -func HasFields(field string, fields ...string) Condition { - return func(_ context.Context, m ent.Mutation) bool { - if _, exists := m.Field(field); !exists { - return false - } - for _, field := range fields { - if _, exists := m.Field(field); !exists { - return false - } - } - return true - } -} - -// If executes the given hook under condition. -// -// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...))) -func If(hk ent.Hook, cond Condition) ent.Hook { - return func(next ent.Mutator) ent.Mutator { - return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) { - if cond(ctx, m) { - return hk(next).Mutate(ctx, m) - } - return next.Mutate(ctx, m) - }) - } -} - -// On executes the given hook only for the given operation. -// -// hook.On(Log, ent.Delete|ent.Create) -func On(hk ent.Hook, op ent.Op) ent.Hook { - return If(hk, HasOp(op)) -} - -// Unless skips the given hook only for the given operation. -// -// hook.Unless(Log, ent.Update|ent.UpdateOne) -func Unless(hk ent.Hook, op ent.Op) ent.Hook { - return If(hk, Not(HasOp(op))) -} - -// FixedError is a hook returning a fixed error. -func FixedError(err error) ent.Hook { - return func(ent.Mutator) ent.Mutator { - return ent.MutateFunc(func(context.Context, ent.Mutation) (ent.Value, error) { - return nil, err - }) - } -} - -// Reject returns a hook that rejects all operations that match op. -// -// func (T) Hooks() []ent.Hook { -// return []ent.Hook{ -// Reject(ent.Delete|ent.Update), -// } -// } -func Reject(op ent.Op) ent.Hook { - hk := FixedError(fmt.Errorf("%s operation is not allowed", op)) - return On(hk, op) -} - -// Chain acts as a list of hooks and is effectively immutable. -// Once created, it will always hold the same set of hooks in the same order. -type Chain struct { - hooks []ent.Hook -} - -// NewChain creates a new chain of hooks. -func NewChain(hooks ...ent.Hook) Chain { - return Chain{append([]ent.Hook(nil), hooks...)} -} - -// Hook chains the list of hooks and returns the final hook. -func (c Chain) Hook() ent.Hook { - return func(mutator ent.Mutator) ent.Mutator { - for i := len(c.hooks) - 1; i >= 0; i-- { - mutator = c.hooks[i](mutator) - } - return mutator - } -} - -// Append extends a chain, adding the specified hook -// as the last ones in the mutation flow. -func (c Chain) Append(hooks ...ent.Hook) Chain { - newHooks := make([]ent.Hook, 0, len(c.hooks)+len(hooks)) - newHooks = append(newHooks, c.hooks...) - newHooks = append(newHooks, hooks...) - return Chain{newHooks} -} - -// Extend extends a chain, adding the specified chain -// as the last ones in the mutation flow. -func (c Chain) Extend(chain Chain) Chain { - return c.Append(chain.hooks...) -} diff --git a/internal/ent/migrate/migrate.go b/internal/ent/migrate/migrate.go deleted file mode 100644 index 1956a6b..0000000 --- a/internal/ent/migrate/migrate.go +++ /dev/null @@ -1,64 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package migrate - -import ( - "context" - "fmt" - "io" - - "entgo.io/ent/dialect" - "entgo.io/ent/dialect/sql/schema" -) - -var ( - // WithGlobalUniqueID sets the universal ids options to the migration. - // If this option is enabled, ent migration will allocate a 1<<32 range - // for the ids of each entity (table). - // Note that this option cannot be applied on tables that already exist. - WithGlobalUniqueID = schema.WithGlobalUniqueID - // WithDropColumn sets the drop column option to the migration. - // If this option is enabled, ent migration will drop old columns - // that were used for both fields and edges. This defaults to false. - WithDropColumn = schema.WithDropColumn - // WithDropIndex sets the drop index option to the migration. - // If this option is enabled, ent migration will drop old indexes - // that were defined in the schema. This defaults to false. - // Note that unique constraints are defined using `UNIQUE INDEX`, - // and therefore, it's recommended to enable this option to get more - // flexibility in the schema changes. - WithDropIndex = schema.WithDropIndex - // WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true. - WithForeignKeys = schema.WithForeignKeys -) - -// Schema is the API for creating, migrating and dropping a schema. -type Schema struct { - drv dialect.Driver -} - -// NewSchema creates a new schema client. -func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} } - -// Create creates all schema resources. -func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error { - return Create(ctx, s, Tables, opts...) -} - -// Create creates all table resources using the given schema driver. -func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error { - migrate, err := schema.NewMigrate(s.drv, opts...) - if err != nil { - return fmt.Errorf("ent/migrate: %w", err) - } - return migrate.Create(ctx, tables...) -} - -// WriteTo writes the schema changes to w instead of running them against the database. -// -// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil { -// log.Fatal(err) -// } -func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error { - return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...) -} diff --git a/internal/ent/migrate/schema.go b/internal/ent/migrate/schema.go deleted file mode 100644 index 69fb041..0000000 --- a/internal/ent/migrate/schema.go +++ /dev/null @@ -1,233 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package migrate - -import ( - "entgo.io/ent/dialect/sql/schema" - "entgo.io/ent/schema/field" -) - -var ( - // AuditLogsColumns holds the columns for the "audit_logs" table. - AuditLogsColumns = []*schema.Column{ - {Name: "id", Type: field.TypeString, Unique: true}, - {Name: "user_id", Type: field.TypeString}, - {Name: "action", Type: field.TypeString}, - {Name: "resource", Type: field.TypeString, Nullable: true}, - {Name: "resource_id", Type: field.TypeString, Nullable: true}, - {Name: "ip_address", Type: field.TypeString, Nullable: true}, - {Name: "user_agent", Type: field.TypeString, Nullable: true}, - {Name: "metadata", Type: field.TypeJSON, Nullable: true}, - {Name: "timestamp", Type: field.TypeTime}, - } - // AuditLogsTable holds the schema information for the "audit_logs" table. - AuditLogsTable = &schema.Table{ - Name: "audit_logs", - Columns: AuditLogsColumns, - PrimaryKey: []*schema.Column{AuditLogsColumns[0]}, - Indexes: []*schema.Index{ - { - Name: "auditlog_user_id", - Unique: false, - Columns: []*schema.Column{AuditLogsColumns[1]}, - }, - { - Name: "auditlog_resource_id", - Unique: false, - Columns: []*schema.Column{AuditLogsColumns[4]}, - }, - { - Name: "auditlog_timestamp", - Unique: false, - Columns: []*schema.Column{AuditLogsColumns[8]}, - }, - { - Name: "auditlog_action", - Unique: false, - Columns: []*schema.Column{AuditLogsColumns[2]}, - }, - { - Name: "auditlog_resource", - Unique: false, - Columns: []*schema.Column{AuditLogsColumns[3]}, - }, - }, - } - // PermissionsColumns holds the columns for the "permissions" table. - PermissionsColumns = []*schema.Column{ - {Name: "id", Type: field.TypeString, Unique: true}, - {Name: "name", Type: field.TypeString, Unique: true}, - } - // PermissionsTable holds the schema information for the "permissions" table. - PermissionsTable = &schema.Table{ - Name: "permissions", - Columns: PermissionsColumns, - PrimaryKey: []*schema.Column{PermissionsColumns[0]}, - } - // RefreshTokensColumns holds the columns for the "refresh_tokens" table. - RefreshTokensColumns = []*schema.Column{ - {Name: "id", Type: field.TypeString, Unique: true}, - {Name: "user_id", Type: field.TypeString}, - {Name: "token_hash", Type: field.TypeString}, - {Name: "expires_at", Type: field.TypeTime}, - {Name: "created_at", 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]}, - Indexes: []*schema.Index{ - { - Name: "refreshtoken_user_id", - Unique: false, - Columns: []*schema.Column{RefreshTokensColumns[1]}, - }, - { - Name: "refreshtoken_token_hash", - Unique: false, - Columns: []*schema.Column{RefreshTokensColumns[2]}, - }, - { - Name: "refreshtoken_expires_at", - Unique: false, - Columns: []*schema.Column{RefreshTokensColumns[3]}, - }, - }, - } - // RolesColumns holds the columns for the "roles" table. - RolesColumns = []*schema.Column{ - {Name: "id", Type: field.TypeString, Unique: true}, - {Name: "name", Type: field.TypeString, Unique: true}, - {Name: "description", Type: field.TypeString, Nullable: true}, - {Name: "created_at", Type: field.TypeTime}, - } - // RolesTable holds the schema information for the "roles" table. - RolesTable = &schema.Table{ - Name: "roles", - Columns: RolesColumns, - PrimaryKey: []*schema.Column{RolesColumns[0]}, - } - // RolePermissionsColumns holds the columns for the "role_permissions" table. - RolePermissionsColumns = []*schema.Column{ - {Name: "id", Type: field.TypeInt, Increment: true}, - {Name: "permission_role_permissions", Type: field.TypeString, Nullable: true}, - {Name: "role_role_permissions", Type: field.TypeString, Nullable: true}, - {Name: "role_id", Type: field.TypeString}, - {Name: "permission_id", Type: field.TypeString}, - } - // RolePermissionsTable holds the schema information for the "role_permissions" table. - RolePermissionsTable = &schema.Table{ - Name: "role_permissions", - Columns: RolePermissionsColumns, - PrimaryKey: []*schema.Column{RolePermissionsColumns[0]}, - ForeignKeys: []*schema.ForeignKey{ - { - Symbol: "role_permissions_permissions_role_permissions", - Columns: []*schema.Column{RolePermissionsColumns[1]}, - RefColumns: []*schema.Column{PermissionsColumns[0]}, - OnDelete: schema.SetNull, - }, - { - Symbol: "role_permissions_roles_role_permissions", - Columns: []*schema.Column{RolePermissionsColumns[2]}, - RefColumns: []*schema.Column{RolesColumns[0]}, - OnDelete: schema.SetNull, - }, - { - Symbol: "role_permissions_roles_role", - Columns: []*schema.Column{RolePermissionsColumns[3]}, - RefColumns: []*schema.Column{RolesColumns[0]}, - OnDelete: schema.NoAction, - }, - { - Symbol: "role_permissions_permissions_permission", - Columns: []*schema.Column{RolePermissionsColumns[4]}, - RefColumns: []*schema.Column{PermissionsColumns[0]}, - OnDelete: schema.NoAction, - }, - }, - } - // UsersColumns holds the columns for the "users" table. - UsersColumns = []*schema.Column{ - {Name: "id", Type: field.TypeString, Unique: true}, - {Name: "email", Type: field.TypeString, Unique: true}, - {Name: "username", Type: field.TypeString, Nullable: true}, - {Name: "first_name", Type: field.TypeString, Nullable: true}, - {Name: "last_name", Type: field.TypeString, Nullable: true}, - {Name: "password_hash", Type: field.TypeString}, - {Name: "verified", Type: field.TypeBool, Default: false}, - {Name: "email_verification_token", Type: field.TypeString, Nullable: true}, - {Name: "password_reset_token", Type: field.TypeString, Nullable: true}, - {Name: "password_reset_expires_at", Type: field.TypeTime, Nullable: true}, - {Name: "created_at", Type: field.TypeTime}, - {Name: "updated_at", Type: field.TypeTime}, - } - // UsersTable holds the schema information for the "users" table. - UsersTable = &schema.Table{ - Name: "users", - Columns: UsersColumns, - PrimaryKey: []*schema.Column{UsersColumns[0]}, - } - // UserRolesColumns holds the columns for the "user_roles" table. - UserRolesColumns = []*schema.Column{ - {Name: "id", Type: field.TypeInt, Increment: true}, - {Name: "role_user_roles", Type: field.TypeString, Nullable: true}, - {Name: "user_user_roles", Type: field.TypeString, Nullable: true}, - {Name: "user_id", Type: field.TypeString}, - {Name: "role_id", Type: field.TypeString}, - } - // UserRolesTable holds the schema information for the "user_roles" table. - UserRolesTable = &schema.Table{ - Name: "user_roles", - Columns: UserRolesColumns, - PrimaryKey: []*schema.Column{UserRolesColumns[0]}, - ForeignKeys: []*schema.ForeignKey{ - { - Symbol: "user_roles_roles_user_roles", - Columns: []*schema.Column{UserRolesColumns[1]}, - RefColumns: []*schema.Column{RolesColumns[0]}, - OnDelete: schema.SetNull, - }, - { - Symbol: "user_roles_users_user_roles", - Columns: []*schema.Column{UserRolesColumns[2]}, - RefColumns: []*schema.Column{UsersColumns[0]}, - OnDelete: schema.SetNull, - }, - { - Symbol: "user_roles_users_user", - Columns: []*schema.Column{UserRolesColumns[3]}, - RefColumns: []*schema.Column{UsersColumns[0]}, - OnDelete: schema.NoAction, - }, - { - Symbol: "user_roles_roles_role", - Columns: []*schema.Column{UserRolesColumns[4]}, - RefColumns: []*schema.Column{RolesColumns[0]}, - OnDelete: schema.NoAction, - }, - }, - } - // Tables holds all the tables in the schema. - Tables = []*schema.Table{ - AuditLogsTable, - PermissionsTable, - RefreshTokensTable, - RolesTable, - RolePermissionsTable, - UsersTable, - UserRolesTable, - } -) - -func init() { - RolePermissionsTable.ForeignKeys[0].RefTable = PermissionsTable - RolePermissionsTable.ForeignKeys[1].RefTable = RolesTable - RolePermissionsTable.ForeignKeys[2].RefTable = RolesTable - RolePermissionsTable.ForeignKeys[3].RefTable = PermissionsTable - UserRolesTable.ForeignKeys[0].RefTable = RolesTable - UserRolesTable.ForeignKeys[1].RefTable = UsersTable - UserRolesTable.ForeignKeys[2].RefTable = UsersTable - UserRolesTable.ForeignKeys[3].RefTable = RolesTable -} diff --git a/internal/ent/mutation.go b/internal/ent/mutation.go deleted file mode 100644 index 9c88d27..0000000 --- a/internal/ent/mutation.go +++ /dev/null @@ -1,4447 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "errors" - "fmt" - "sync" - "time" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "git.dcentral.systems/toolz/goplt/internal/ent/auditlog" - "git.dcentral.systems/toolz/goplt/internal/ent/permission" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" - "git.dcentral.systems/toolz/goplt/internal/ent/refreshtoken" - "git.dcentral.systems/toolz/goplt/internal/ent/role" - "git.dcentral.systems/toolz/goplt/internal/ent/rolepermission" - "git.dcentral.systems/toolz/goplt/internal/ent/user" - "git.dcentral.systems/toolz/goplt/internal/ent/userrole" -) - -const ( - // Operation types. - OpCreate = ent.OpCreate - OpDelete = ent.OpDelete - OpDeleteOne = ent.OpDeleteOne - OpUpdate = ent.OpUpdate - OpUpdateOne = ent.OpUpdateOne - - // Node types. - TypeAuditLog = "AuditLog" - TypePermission = "Permission" - TypeRefreshToken = "RefreshToken" - TypeRole = "Role" - TypeRolePermission = "RolePermission" - TypeUser = "User" - TypeUserRole = "UserRole" -) - -// AuditLogMutation represents an operation that mutates the AuditLog nodes in the graph. -type AuditLogMutation struct { - config - op Op - typ string - id *string - user_id *string - action *string - resource *string - resource_id *string - ip_address *string - user_agent *string - metadata *map[string]interface{} - timestamp *time.Time - clearedFields map[string]struct{} - done bool - oldValue func(context.Context) (*AuditLog, error) - predicates []predicate.AuditLog -} - -var _ ent.Mutation = (*AuditLogMutation)(nil) - -// auditlogOption allows management of the mutation configuration using functional options. -type auditlogOption func(*AuditLogMutation) - -// newAuditLogMutation creates new mutation for the AuditLog entity. -func newAuditLogMutation(c config, op Op, opts ...auditlogOption) *AuditLogMutation { - m := &AuditLogMutation{ - config: c, - op: op, - typ: TypeAuditLog, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m -} - -// withAuditLogID sets the ID field of the mutation. -func withAuditLogID(id string) auditlogOption { - return func(m *AuditLogMutation) { - var ( - err error - once sync.Once - value *AuditLog - ) - m.oldValue = func(ctx context.Context) (*AuditLog, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().AuditLog.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } -} - -// withAuditLog sets the old AuditLog of the mutation. -func withAuditLog(node *AuditLog) auditlogOption { - return func(m *AuditLogMutation) { - m.oldValue = func(context.Context) (*AuditLog, error) { - return node, nil - } - m.id = &node.ID - } -} - -// Client returns a new `ent.Client` from the mutation. If the mutation was -// executed in a transaction (ent.Tx), a transactional client is returned. -func (m AuditLogMutation) Client() *Client { - client := &Client{config: m.config} - client.init() - return client -} - -// Tx returns an `ent.Tx` for mutations that were executed in transactions; -// it returns an error otherwise. -func (m AuditLogMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("ent: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil -} - -// SetID sets the value of the id field. Note that this -// operation is only accepted on creation of AuditLog entities. -func (m *AuditLogMutation) SetID(id string) { - m.id = &id -} - -// ID returns the ID value in the mutation. Note that the ID is only available -// if it was provided to the builder or after it was returned from the database. -func (m *AuditLogMutation) ID() (id string, exists bool) { - if m.id == nil { - return - } - return *m.id, true -} - -// IDs queries the database and returns the entity ids that match the mutation's predicate. -// That means, if the mutation is applied within a transaction with an isolation level such -// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated -// or updated by the mutation. -func (m *AuditLogMutation) IDs(ctx context.Context) ([]string, error) { - switch { - case m.op.Is(OpUpdateOne | OpDeleteOne): - id, exists := m.ID() - if exists { - return []string{id}, nil - } - fallthrough - case m.op.Is(OpUpdate | OpDelete): - return m.Client().AuditLog.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) - } -} - -// SetUserID sets the "user_id" field. -func (m *AuditLogMutation) SetUserID(s string) { - m.user_id = &s -} - -// UserID returns the value of the "user_id" field in the mutation. -func (m *AuditLogMutation) UserID() (r string, exists bool) { - v := m.user_id - if v == nil { - return - } - return *v, true -} - -// OldUserID returns the old "user_id" field's value of the AuditLog entity. -// If the AuditLog object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *AuditLogMutation) OldUserID(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUserID is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUserID requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldUserID: %w", err) - } - return oldValue.UserID, nil -} - -// ResetUserID resets all changes to the "user_id" field. -func (m *AuditLogMutation) ResetUserID() { - m.user_id = nil -} - -// SetAction sets the "action" field. -func (m *AuditLogMutation) SetAction(s string) { - m.action = &s -} - -// Action returns the value of the "action" field in the mutation. -func (m *AuditLogMutation) Action() (r string, exists bool) { - v := m.action - if v == nil { - return - } - return *v, true -} - -// OldAction returns the old "action" field's value of the AuditLog entity. -// If the AuditLog object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *AuditLogMutation) OldAction(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldAction is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldAction requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldAction: %w", err) - } - return oldValue.Action, nil -} - -// ResetAction resets all changes to the "action" field. -func (m *AuditLogMutation) ResetAction() { - m.action = nil -} - -// SetResource sets the "resource" field. -func (m *AuditLogMutation) SetResource(s string) { - m.resource = &s -} - -// Resource returns the value of the "resource" field in the mutation. -func (m *AuditLogMutation) Resource() (r string, exists bool) { - v := m.resource - if v == nil { - return - } - return *v, true -} - -// OldResource returns the old "resource" field's value of the AuditLog entity. -// If the AuditLog object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *AuditLogMutation) OldResource(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldResource is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldResource requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldResource: %w", err) - } - return oldValue.Resource, nil -} - -// ClearResource clears the value of the "resource" field. -func (m *AuditLogMutation) ClearResource() { - m.resource = nil - m.clearedFields[auditlog.FieldResource] = struct{}{} -} - -// ResourceCleared returns if the "resource" field was cleared in this mutation. -func (m *AuditLogMutation) ResourceCleared() bool { - _, ok := m.clearedFields[auditlog.FieldResource] - return ok -} - -// ResetResource resets all changes to the "resource" field. -func (m *AuditLogMutation) ResetResource() { - m.resource = nil - delete(m.clearedFields, auditlog.FieldResource) -} - -// SetResourceID sets the "resource_id" field. -func (m *AuditLogMutation) SetResourceID(s string) { - m.resource_id = &s -} - -// ResourceID returns the value of the "resource_id" field in the mutation. -func (m *AuditLogMutation) ResourceID() (r string, exists bool) { - v := m.resource_id - if v == nil { - return - } - return *v, true -} - -// OldResourceID returns the old "resource_id" field's value of the AuditLog entity. -// If the AuditLog object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *AuditLogMutation) OldResourceID(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldResourceID is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldResourceID requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldResourceID: %w", err) - } - return oldValue.ResourceID, nil -} - -// ClearResourceID clears the value of the "resource_id" field. -func (m *AuditLogMutation) ClearResourceID() { - m.resource_id = nil - m.clearedFields[auditlog.FieldResourceID] = struct{}{} -} - -// ResourceIDCleared returns if the "resource_id" field was cleared in this mutation. -func (m *AuditLogMutation) ResourceIDCleared() bool { - _, ok := m.clearedFields[auditlog.FieldResourceID] - return ok -} - -// ResetResourceID resets all changes to the "resource_id" field. -func (m *AuditLogMutation) ResetResourceID() { - m.resource_id = nil - delete(m.clearedFields, auditlog.FieldResourceID) -} - -// SetIPAddress sets the "ip_address" field. -func (m *AuditLogMutation) SetIPAddress(s string) { - m.ip_address = &s -} - -// IPAddress returns the value of the "ip_address" field in the mutation. -func (m *AuditLogMutation) IPAddress() (r string, exists bool) { - v := m.ip_address - if v == nil { - return - } - return *v, true -} - -// OldIPAddress returns the old "ip_address" field's value of the AuditLog entity. -// If the AuditLog object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *AuditLogMutation) OldIPAddress(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldIPAddress is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldIPAddress requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldIPAddress: %w", err) - } - return oldValue.IPAddress, nil -} - -// ClearIPAddress clears the value of the "ip_address" field. -func (m *AuditLogMutation) ClearIPAddress() { - m.ip_address = nil - m.clearedFields[auditlog.FieldIPAddress] = struct{}{} -} - -// IPAddressCleared returns if the "ip_address" field was cleared in this mutation. -func (m *AuditLogMutation) IPAddressCleared() bool { - _, ok := m.clearedFields[auditlog.FieldIPAddress] - return ok -} - -// ResetIPAddress resets all changes to the "ip_address" field. -func (m *AuditLogMutation) ResetIPAddress() { - m.ip_address = nil - delete(m.clearedFields, auditlog.FieldIPAddress) -} - -// SetUserAgent sets the "user_agent" field. -func (m *AuditLogMutation) SetUserAgent(s string) { - m.user_agent = &s -} - -// UserAgent returns the value of the "user_agent" field in the mutation. -func (m *AuditLogMutation) UserAgent() (r string, exists bool) { - v := m.user_agent - if v == nil { - return - } - return *v, true -} - -// OldUserAgent returns the old "user_agent" field's value of the AuditLog entity. -// If the AuditLog object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *AuditLogMutation) OldUserAgent(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUserAgent is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUserAgent requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldUserAgent: %w", err) - } - return oldValue.UserAgent, nil -} - -// ClearUserAgent clears the value of the "user_agent" field. -func (m *AuditLogMutation) ClearUserAgent() { - m.user_agent = nil - m.clearedFields[auditlog.FieldUserAgent] = struct{}{} -} - -// UserAgentCleared returns if the "user_agent" field was cleared in this mutation. -func (m *AuditLogMutation) UserAgentCleared() bool { - _, ok := m.clearedFields[auditlog.FieldUserAgent] - return ok -} - -// ResetUserAgent resets all changes to the "user_agent" field. -func (m *AuditLogMutation) ResetUserAgent() { - m.user_agent = nil - delete(m.clearedFields, auditlog.FieldUserAgent) -} - -// SetMetadata sets the "metadata" field. -func (m *AuditLogMutation) SetMetadata(value map[string]interface{}) { - m.metadata = &value -} - -// Metadata returns the value of the "metadata" field in the mutation. -func (m *AuditLogMutation) Metadata() (r map[string]interface{}, exists bool) { - v := m.metadata - if v == nil { - return - } - return *v, true -} - -// OldMetadata returns the old "metadata" field's value of the AuditLog entity. -// If the AuditLog object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *AuditLogMutation) OldMetadata(ctx context.Context) (v map[string]interface{}, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldMetadata is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldMetadata requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldMetadata: %w", err) - } - return oldValue.Metadata, nil -} - -// ClearMetadata clears the value of the "metadata" field. -func (m *AuditLogMutation) ClearMetadata() { - m.metadata = nil - m.clearedFields[auditlog.FieldMetadata] = struct{}{} -} - -// MetadataCleared returns if the "metadata" field was cleared in this mutation. -func (m *AuditLogMutation) MetadataCleared() bool { - _, ok := m.clearedFields[auditlog.FieldMetadata] - return ok -} - -// ResetMetadata resets all changes to the "metadata" field. -func (m *AuditLogMutation) ResetMetadata() { - m.metadata = nil - delete(m.clearedFields, auditlog.FieldMetadata) -} - -// SetTimestamp sets the "timestamp" field. -func (m *AuditLogMutation) SetTimestamp(t time.Time) { - m.timestamp = &t -} - -// Timestamp returns the value of the "timestamp" field in the mutation. -func (m *AuditLogMutation) Timestamp() (r time.Time, exists bool) { - v := m.timestamp - if v == nil { - return - } - return *v, true -} - -// OldTimestamp returns the old "timestamp" field's value of the AuditLog entity. -// If the AuditLog object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *AuditLogMutation) OldTimestamp(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldTimestamp is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldTimestamp requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldTimestamp: %w", err) - } - return oldValue.Timestamp, nil -} - -// ResetTimestamp resets all changes to the "timestamp" field. -func (m *AuditLogMutation) ResetTimestamp() { - m.timestamp = nil -} - -// Where appends a list predicates to the AuditLogMutation builder. -func (m *AuditLogMutation) Where(ps ...predicate.AuditLog) { - m.predicates = append(m.predicates, ps...) -} - -// WhereP appends storage-level predicates to the AuditLogMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *AuditLogMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.AuditLog, len(ps)) - for i := range ps { - p[i] = ps[i] - } - m.Where(p...) -} - -// Op returns the operation name. -func (m *AuditLogMutation) Op() Op { - return m.op -} - -// SetOp allows setting the mutation operation. -func (m *AuditLogMutation) SetOp(op Op) { - m.op = op -} - -// Type returns the node type of this mutation (AuditLog). -func (m *AuditLogMutation) Type() string { - return m.typ -} - -// Fields returns all fields that were changed during this mutation. Note that in -// order to get all numeric fields that were incremented/decremented, call -// AddedFields(). -func (m *AuditLogMutation) Fields() []string { - fields := make([]string, 0, 8) - if m.user_id != nil { - fields = append(fields, auditlog.FieldUserID) - } - if m.action != nil { - fields = append(fields, auditlog.FieldAction) - } - if m.resource != nil { - fields = append(fields, auditlog.FieldResource) - } - if m.resource_id != nil { - fields = append(fields, auditlog.FieldResourceID) - } - if m.ip_address != nil { - fields = append(fields, auditlog.FieldIPAddress) - } - if m.user_agent != nil { - fields = append(fields, auditlog.FieldUserAgent) - } - if m.metadata != nil { - fields = append(fields, auditlog.FieldMetadata) - } - if m.timestamp != nil { - fields = append(fields, auditlog.FieldTimestamp) - } - return fields -} - -// Field returns the value of a field with the given name. The second boolean -// return value indicates that this field was not set, or was not defined in the -// schema. -func (m *AuditLogMutation) Field(name string) (ent.Value, bool) { - switch name { - case auditlog.FieldUserID: - return m.UserID() - case auditlog.FieldAction: - return m.Action() - case auditlog.FieldResource: - return m.Resource() - case auditlog.FieldResourceID: - return m.ResourceID() - case auditlog.FieldIPAddress: - return m.IPAddress() - case auditlog.FieldUserAgent: - return m.UserAgent() - case auditlog.FieldMetadata: - return m.Metadata() - case auditlog.FieldTimestamp: - return m.Timestamp() - } - return nil, false -} - -// OldField returns the old value of the field from the database. An error is -// returned if the mutation operation is not UpdateOne, or the query to the -// database failed. -func (m *AuditLogMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case auditlog.FieldUserID: - return m.OldUserID(ctx) - case auditlog.FieldAction: - return m.OldAction(ctx) - case auditlog.FieldResource: - return m.OldResource(ctx) - case auditlog.FieldResourceID: - return m.OldResourceID(ctx) - case auditlog.FieldIPAddress: - return m.OldIPAddress(ctx) - case auditlog.FieldUserAgent: - return m.OldUserAgent(ctx) - case auditlog.FieldMetadata: - return m.OldMetadata(ctx) - case auditlog.FieldTimestamp: - return m.OldTimestamp(ctx) - } - return nil, fmt.Errorf("unknown AuditLog field %s", name) -} - -// SetField sets the value of a field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *AuditLogMutation) SetField(name string, value ent.Value) error { - switch name { - case auditlog.FieldUserID: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUserID(v) - return nil - case auditlog.FieldAction: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetAction(v) - return nil - case auditlog.FieldResource: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetResource(v) - return nil - case auditlog.FieldResourceID: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetResourceID(v) - return nil - case auditlog.FieldIPAddress: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetIPAddress(v) - return nil - case auditlog.FieldUserAgent: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUserAgent(v) - return nil - case auditlog.FieldMetadata: - v, ok := value.(map[string]interface{}) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetMetadata(v) - return nil - case auditlog.FieldTimestamp: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetTimestamp(v) - return nil - } - return fmt.Errorf("unknown AuditLog field %s", name) -} - -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *AuditLogMutation) AddedFields() []string { - return nil -} - -// AddedField returns the numeric value that was incremented/decremented on a field -// with the given name. The second boolean return value indicates that this field -// was not set, or was not defined in the schema. -func (m *AuditLogMutation) AddedField(name string) (ent.Value, bool) { - return nil, false -} - -// AddField adds the value to the field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *AuditLogMutation) AddField(name string, value ent.Value) error { - switch name { - } - return fmt.Errorf("unknown AuditLog numeric field %s", name) -} - -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *AuditLogMutation) ClearedFields() []string { - var fields []string - if m.FieldCleared(auditlog.FieldResource) { - fields = append(fields, auditlog.FieldResource) - } - if m.FieldCleared(auditlog.FieldResourceID) { - fields = append(fields, auditlog.FieldResourceID) - } - if m.FieldCleared(auditlog.FieldIPAddress) { - fields = append(fields, auditlog.FieldIPAddress) - } - if m.FieldCleared(auditlog.FieldUserAgent) { - fields = append(fields, auditlog.FieldUserAgent) - } - if m.FieldCleared(auditlog.FieldMetadata) { - fields = append(fields, auditlog.FieldMetadata) - } - return fields -} - -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *AuditLogMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok -} - -// ClearField clears the value of the field with the given name. It returns an -// error if the field is not defined in the schema. -func (m *AuditLogMutation) ClearField(name string) error { - switch name { - case auditlog.FieldResource: - m.ClearResource() - return nil - case auditlog.FieldResourceID: - m.ClearResourceID() - return nil - case auditlog.FieldIPAddress: - m.ClearIPAddress() - return nil - case auditlog.FieldUserAgent: - m.ClearUserAgent() - return nil - case auditlog.FieldMetadata: - m.ClearMetadata() - return nil - } - return fmt.Errorf("unknown AuditLog nullable field %s", name) -} - -// ResetField resets all changes in the mutation for the field with the given name. -// It returns an error if the field is not defined in the schema. -func (m *AuditLogMutation) ResetField(name string) error { - switch name { - case auditlog.FieldUserID: - m.ResetUserID() - return nil - case auditlog.FieldAction: - m.ResetAction() - return nil - case auditlog.FieldResource: - m.ResetResource() - return nil - case auditlog.FieldResourceID: - m.ResetResourceID() - return nil - case auditlog.FieldIPAddress: - m.ResetIPAddress() - return nil - case auditlog.FieldUserAgent: - m.ResetUserAgent() - return nil - case auditlog.FieldMetadata: - m.ResetMetadata() - return nil - case auditlog.FieldTimestamp: - m.ResetTimestamp() - return nil - } - return fmt.Errorf("unknown AuditLog field %s", name) -} - -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *AuditLogMutation) AddedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *AuditLogMutation) AddedIDs(name string) []ent.Value { - return nil -} - -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *AuditLogMutation) RemovedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *AuditLogMutation) RemovedIDs(name string) []ent.Value { - return nil -} - -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *AuditLogMutation) ClearedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *AuditLogMutation) EdgeCleared(name string) bool { - return false -} - -// ClearEdge clears the value of the edge with the given name. It returns an error -// if that edge is not defined in the schema. -func (m *AuditLogMutation) ClearEdge(name string) error { - return fmt.Errorf("unknown AuditLog unique edge %s", name) -} - -// ResetEdge resets all changes to the edge with the given name in this mutation. -// It returns an error if the edge is not defined in the schema. -func (m *AuditLogMutation) ResetEdge(name string) error { - return fmt.Errorf("unknown AuditLog edge %s", name) -} - -// PermissionMutation represents an operation that mutates the Permission nodes in the graph. -type PermissionMutation struct { - config - op Op - typ string - id *string - name *string - clearedFields map[string]struct{} - role_permissions map[int]struct{} - removedrole_permissions map[int]struct{} - clearedrole_permissions bool - done bool - oldValue func(context.Context) (*Permission, error) - predicates []predicate.Permission -} - -var _ ent.Mutation = (*PermissionMutation)(nil) - -// permissionOption allows management of the mutation configuration using functional options. -type permissionOption func(*PermissionMutation) - -// newPermissionMutation creates new mutation for the Permission entity. -func newPermissionMutation(c config, op Op, opts ...permissionOption) *PermissionMutation { - m := &PermissionMutation{ - config: c, - op: op, - typ: TypePermission, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m -} - -// withPermissionID sets the ID field of the mutation. -func withPermissionID(id string) permissionOption { - return func(m *PermissionMutation) { - var ( - err error - once sync.Once - value *Permission - ) - m.oldValue = func(ctx context.Context) (*Permission, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().Permission.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } -} - -// withPermission sets the old Permission of the mutation. -func withPermission(node *Permission) permissionOption { - return func(m *PermissionMutation) { - m.oldValue = func(context.Context) (*Permission, error) { - return node, nil - } - m.id = &node.ID - } -} - -// Client returns a new `ent.Client` from the mutation. If the mutation was -// executed in a transaction (ent.Tx), a transactional client is returned. -func (m PermissionMutation) Client() *Client { - client := &Client{config: m.config} - client.init() - return client -} - -// Tx returns an `ent.Tx` for mutations that were executed in transactions; -// it returns an error otherwise. -func (m PermissionMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("ent: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil -} - -// SetID sets the value of the id field. Note that this -// operation is only accepted on creation of Permission entities. -func (m *PermissionMutation) SetID(id string) { - m.id = &id -} - -// ID returns the ID value in the mutation. Note that the ID is only available -// if it was provided to the builder or after it was returned from the database. -func (m *PermissionMutation) ID() (id string, exists bool) { - if m.id == nil { - return - } - return *m.id, true -} - -// IDs queries the database and returns the entity ids that match the mutation's predicate. -// That means, if the mutation is applied within a transaction with an isolation level such -// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated -// or updated by the mutation. -func (m *PermissionMutation) IDs(ctx context.Context) ([]string, error) { - switch { - case m.op.Is(OpUpdateOne | OpDeleteOne): - id, exists := m.ID() - if exists { - return []string{id}, nil - } - fallthrough - case m.op.Is(OpUpdate | OpDelete): - return m.Client().Permission.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) - } -} - -// SetName sets the "name" field. -func (m *PermissionMutation) SetName(s string) { - m.name = &s -} - -// Name returns the value of the "name" field in the mutation. -func (m *PermissionMutation) Name() (r string, exists bool) { - v := m.name - if v == nil { - return - } - return *v, true -} - -// OldName returns the old "name" field's value of the Permission entity. -// If the Permission object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *PermissionMutation) OldName(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldName is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldName requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldName: %w", err) - } - return oldValue.Name, nil -} - -// ResetName resets all changes to the "name" field. -func (m *PermissionMutation) ResetName() { - m.name = nil -} - -// AddRolePermissionIDs adds the "role_permissions" edge to the RolePermission entity by ids. -func (m *PermissionMutation) AddRolePermissionIDs(ids ...int) { - if m.role_permissions == nil { - m.role_permissions = make(map[int]struct{}) - } - for i := range ids { - m.role_permissions[ids[i]] = struct{}{} - } -} - -// ClearRolePermissions clears the "role_permissions" edge to the RolePermission entity. -func (m *PermissionMutation) ClearRolePermissions() { - m.clearedrole_permissions = true -} - -// RolePermissionsCleared reports if the "role_permissions" edge to the RolePermission entity was cleared. -func (m *PermissionMutation) RolePermissionsCleared() bool { - return m.clearedrole_permissions -} - -// RemoveRolePermissionIDs removes the "role_permissions" edge to the RolePermission entity by IDs. -func (m *PermissionMutation) RemoveRolePermissionIDs(ids ...int) { - if m.removedrole_permissions == nil { - m.removedrole_permissions = make(map[int]struct{}) - } - for i := range ids { - delete(m.role_permissions, ids[i]) - m.removedrole_permissions[ids[i]] = struct{}{} - } -} - -// RemovedRolePermissions returns the removed IDs of the "role_permissions" edge to the RolePermission entity. -func (m *PermissionMutation) RemovedRolePermissionsIDs() (ids []int) { - for id := range m.removedrole_permissions { - ids = append(ids, id) - } - return -} - -// RolePermissionsIDs returns the "role_permissions" edge IDs in the mutation. -func (m *PermissionMutation) RolePermissionsIDs() (ids []int) { - for id := range m.role_permissions { - ids = append(ids, id) - } - return -} - -// ResetRolePermissions resets all changes to the "role_permissions" edge. -func (m *PermissionMutation) ResetRolePermissions() { - m.role_permissions = nil - m.clearedrole_permissions = false - m.removedrole_permissions = nil -} - -// Where appends a list predicates to the PermissionMutation builder. -func (m *PermissionMutation) Where(ps ...predicate.Permission) { - m.predicates = append(m.predicates, ps...) -} - -// WhereP appends storage-level predicates to the PermissionMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *PermissionMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.Permission, len(ps)) - for i := range ps { - p[i] = ps[i] - } - m.Where(p...) -} - -// Op returns the operation name. -func (m *PermissionMutation) Op() Op { - return m.op -} - -// SetOp allows setting the mutation operation. -func (m *PermissionMutation) SetOp(op Op) { - m.op = op -} - -// Type returns the node type of this mutation (Permission). -func (m *PermissionMutation) Type() string { - return m.typ -} - -// Fields returns all fields that were changed during this mutation. Note that in -// order to get all numeric fields that were incremented/decremented, call -// AddedFields(). -func (m *PermissionMutation) Fields() []string { - fields := make([]string, 0, 1) - if m.name != nil { - fields = append(fields, permission.FieldName) - } - return fields -} - -// Field returns the value of a field with the given name. The second boolean -// return value indicates that this field was not set, or was not defined in the -// schema. -func (m *PermissionMutation) Field(name string) (ent.Value, bool) { - switch name { - case permission.FieldName: - return m.Name() - } - return nil, false -} - -// OldField returns the old value of the field from the database. An error is -// returned if the mutation operation is not UpdateOne, or the query to the -// database failed. -func (m *PermissionMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case permission.FieldName: - return m.OldName(ctx) - } - return nil, fmt.Errorf("unknown Permission field %s", name) -} - -// SetField sets the value of a field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *PermissionMutation) SetField(name string, value ent.Value) error { - switch name { - case permission.FieldName: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetName(v) - return nil - } - return fmt.Errorf("unknown Permission field %s", name) -} - -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *PermissionMutation) AddedFields() []string { - return nil -} - -// AddedField returns the numeric value that was incremented/decremented on a field -// with the given name. The second boolean return value indicates that this field -// was not set, or was not defined in the schema. -func (m *PermissionMutation) AddedField(name string) (ent.Value, bool) { - return nil, false -} - -// AddField adds the value to the field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *PermissionMutation) AddField(name string, value ent.Value) error { - switch name { - } - return fmt.Errorf("unknown Permission numeric field %s", name) -} - -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *PermissionMutation) ClearedFields() []string { - return nil -} - -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *PermissionMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok -} - -// ClearField clears the value of the field with the given name. It returns an -// error if the field is not defined in the schema. -func (m *PermissionMutation) ClearField(name string) error { - return fmt.Errorf("unknown Permission nullable field %s", name) -} - -// ResetField resets all changes in the mutation for the field with the given name. -// It returns an error if the field is not defined in the schema. -func (m *PermissionMutation) ResetField(name string) error { - switch name { - case permission.FieldName: - m.ResetName() - return nil - } - return fmt.Errorf("unknown Permission field %s", name) -} - -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *PermissionMutation) AddedEdges() []string { - edges := make([]string, 0, 1) - if m.role_permissions != nil { - edges = append(edges, permission.EdgeRolePermissions) - } - return edges -} - -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *PermissionMutation) AddedIDs(name string) []ent.Value { - switch name { - case permission.EdgeRolePermissions: - ids := make([]ent.Value, 0, len(m.role_permissions)) - for id := range m.role_permissions { - ids = append(ids, id) - } - return ids - } - return nil -} - -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *PermissionMutation) RemovedEdges() []string { - edges := make([]string, 0, 1) - if m.removedrole_permissions != nil { - edges = append(edges, permission.EdgeRolePermissions) - } - return edges -} - -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *PermissionMutation) RemovedIDs(name string) []ent.Value { - switch name { - case permission.EdgeRolePermissions: - ids := make([]ent.Value, 0, len(m.removedrole_permissions)) - for id := range m.removedrole_permissions { - ids = append(ids, id) - } - return ids - } - return nil -} - -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *PermissionMutation) ClearedEdges() []string { - edges := make([]string, 0, 1) - if m.clearedrole_permissions { - edges = append(edges, permission.EdgeRolePermissions) - } - return edges -} - -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *PermissionMutation) EdgeCleared(name string) bool { - switch name { - case permission.EdgeRolePermissions: - return m.clearedrole_permissions - } - return false -} - -// ClearEdge clears the value of the edge with the given name. It returns an error -// if that edge is not defined in the schema. -func (m *PermissionMutation) ClearEdge(name string) error { - switch name { - } - return fmt.Errorf("unknown Permission unique edge %s", name) -} - -// ResetEdge resets all changes to the edge with the given name in this mutation. -// It returns an error if the edge is not defined in the schema. -func (m *PermissionMutation) ResetEdge(name string) error { - switch name { - case permission.EdgeRolePermissions: - m.ResetRolePermissions() - return nil - } - return fmt.Errorf("unknown Permission edge %s", name) -} - -// RefreshTokenMutation represents an operation that mutates the RefreshToken nodes in the graph. -type RefreshTokenMutation struct { - config - op Op - typ string - id *string - user_id *string - token_hash *string - expires_at *time.Time - created_at *time.Time - clearedFields map[string]struct{} - done bool - oldValue func(context.Context) (*RefreshToken, error) - predicates []predicate.RefreshToken -} - -var _ ent.Mutation = (*RefreshTokenMutation)(nil) - -// refreshtokenOption allows management of the mutation configuration using functional options. -type refreshtokenOption func(*RefreshTokenMutation) - -// newRefreshTokenMutation creates new mutation for the RefreshToken entity. -func newRefreshTokenMutation(c config, op Op, opts ...refreshtokenOption) *RefreshTokenMutation { - m := &RefreshTokenMutation{ - config: c, - op: op, - typ: TypeRefreshToken, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m -} - -// withRefreshTokenID sets the ID field of the mutation. -func withRefreshTokenID(id string) refreshtokenOption { - return func(m *RefreshTokenMutation) { - var ( - err error - once sync.Once - value *RefreshToken - ) - m.oldValue = func(ctx context.Context) (*RefreshToken, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().RefreshToken.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } -} - -// withRefreshToken sets the old RefreshToken of the mutation. -func withRefreshToken(node *RefreshToken) refreshtokenOption { - return func(m *RefreshTokenMutation) { - m.oldValue = func(context.Context) (*RefreshToken, error) { - return node, nil - } - m.id = &node.ID - } -} - -// Client returns a new `ent.Client` from the mutation. If the mutation was -// executed in a transaction (ent.Tx), a transactional client is returned. -func (m RefreshTokenMutation) Client() *Client { - client := &Client{config: m.config} - client.init() - return client -} - -// Tx returns an `ent.Tx` for mutations that were executed in transactions; -// it returns an error otherwise. -func (m RefreshTokenMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("ent: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil -} - -// SetID sets the value of the id field. Note that this -// operation is only accepted on creation of RefreshToken entities. -func (m *RefreshTokenMutation) SetID(id string) { - m.id = &id -} - -// ID returns the ID value in the mutation. Note that the ID is only available -// if it was provided to the builder or after it was returned from the database. -func (m *RefreshTokenMutation) ID() (id string, exists bool) { - if m.id == nil { - return - } - return *m.id, true -} - -// IDs queries the database and returns the entity ids that match the mutation's predicate. -// That means, if the mutation is applied within a transaction with an isolation level such -// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated -// or updated by the mutation. -func (m *RefreshTokenMutation) IDs(ctx context.Context) ([]string, error) { - switch { - case m.op.Is(OpUpdateOne | OpDeleteOne): - id, exists := m.ID() - if exists { - return []string{id}, nil - } - fallthrough - case m.op.Is(OpUpdate | OpDelete): - return m.Client().RefreshToken.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) - } -} - -// SetUserID sets the "user_id" field. -func (m *RefreshTokenMutation) SetUserID(s string) { - m.user_id = &s -} - -// UserID returns the value of the "user_id" field in the mutation. -func (m *RefreshTokenMutation) UserID() (r string, exists bool) { - v := m.user_id - if v == nil { - return - } - return *v, true -} - -// OldUserID returns the old "user_id" field's value of the RefreshToken entity. -// If the RefreshToken object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *RefreshTokenMutation) OldUserID(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUserID is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUserID requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldUserID: %w", err) - } - return oldValue.UserID, nil -} - -// ResetUserID resets all changes to the "user_id" field. -func (m *RefreshTokenMutation) ResetUserID() { - m.user_id = nil -} - -// SetTokenHash sets the "token_hash" field. -func (m *RefreshTokenMutation) SetTokenHash(s string) { - m.token_hash = &s -} - -// TokenHash returns the value of the "token_hash" field in the mutation. -func (m *RefreshTokenMutation) TokenHash() (r string, exists bool) { - v := m.token_hash - if v == nil { - return - } - return *v, true -} - -// OldTokenHash returns the old "token_hash" field's value of the RefreshToken entity. -// If the RefreshToken object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *RefreshTokenMutation) OldTokenHash(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldTokenHash is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldTokenHash requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldTokenHash: %w", err) - } - return oldValue.TokenHash, nil -} - -// ResetTokenHash resets all changes to the "token_hash" field. -func (m *RefreshTokenMutation) ResetTokenHash() { - m.token_hash = nil -} - -// SetExpiresAt sets the "expires_at" field. -func (m *RefreshTokenMutation) SetExpiresAt(t time.Time) { - m.expires_at = &t -} - -// ExpiresAt returns the value of the "expires_at" field in the mutation. -func (m *RefreshTokenMutation) ExpiresAt() (r time.Time, exists bool) { - v := m.expires_at - if v == nil { - return - } - return *v, true -} - -// OldExpiresAt returns the old "expires_at" field's value of the RefreshToken entity. -// If the RefreshToken object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *RefreshTokenMutation) OldExpiresAt(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldExpiresAt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldExpiresAt requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldExpiresAt: %w", err) - } - return oldValue.ExpiresAt, nil -} - -// ResetExpiresAt resets all changes to the "expires_at" field. -func (m *RefreshTokenMutation) ResetExpiresAt() { - m.expires_at = nil -} - -// SetCreatedAt sets the "created_at" field. -func (m *RefreshTokenMutation) SetCreatedAt(t time.Time) { - m.created_at = &t -} - -// CreatedAt returns the value of the "created_at" field in the mutation. -func (m *RefreshTokenMutation) CreatedAt() (r time.Time, exists bool) { - v := m.created_at - if v == nil { - return - } - return *v, true -} - -// OldCreatedAt returns the old "created_at" field's value of the RefreshToken entity. -// If the RefreshToken object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *RefreshTokenMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCreatedAt requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) - } - return oldValue.CreatedAt, nil -} - -// ResetCreatedAt resets all changes to the "created_at" field. -func (m *RefreshTokenMutation) ResetCreatedAt() { - m.created_at = nil -} - -// Where appends a list predicates to the RefreshTokenMutation builder. -func (m *RefreshTokenMutation) Where(ps ...predicate.RefreshToken) { - m.predicates = append(m.predicates, ps...) -} - -// WhereP appends storage-level predicates to the RefreshTokenMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *RefreshTokenMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.RefreshToken, len(ps)) - for i := range ps { - p[i] = ps[i] - } - m.Where(p...) -} - -// Op returns the operation name. -func (m *RefreshTokenMutation) Op() Op { - return m.op -} - -// SetOp allows setting the mutation operation. -func (m *RefreshTokenMutation) SetOp(op Op) { - m.op = op -} - -// Type returns the node type of this mutation (RefreshToken). -func (m *RefreshTokenMutation) Type() string { - return m.typ -} - -// Fields returns all fields that were changed during this mutation. Note that in -// order to get all numeric fields that were incremented/decremented, call -// AddedFields(). -func (m *RefreshTokenMutation) Fields() []string { - fields := make([]string, 0, 4) - if m.user_id != nil { - fields = append(fields, refreshtoken.FieldUserID) - } - if m.token_hash != nil { - fields = append(fields, refreshtoken.FieldTokenHash) - } - if m.expires_at != nil { - fields = append(fields, refreshtoken.FieldExpiresAt) - } - if m.created_at != nil { - fields = append(fields, refreshtoken.FieldCreatedAt) - } - return fields -} - -// Field returns the value of a field with the given name. The second boolean -// return value indicates that this field was not set, or was not defined in the -// schema. -func (m *RefreshTokenMutation) Field(name string) (ent.Value, bool) { - switch name { - case refreshtoken.FieldUserID: - return m.UserID() - case refreshtoken.FieldTokenHash: - return m.TokenHash() - case refreshtoken.FieldExpiresAt: - return m.ExpiresAt() - case refreshtoken.FieldCreatedAt: - return m.CreatedAt() - } - return nil, false -} - -// OldField returns the old value of the field from the database. An error is -// returned if the mutation operation is not UpdateOne, or the query to the -// database failed. -func (m *RefreshTokenMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case refreshtoken.FieldUserID: - return m.OldUserID(ctx) - case refreshtoken.FieldTokenHash: - return m.OldTokenHash(ctx) - case refreshtoken.FieldExpiresAt: - return m.OldExpiresAt(ctx) - case refreshtoken.FieldCreatedAt: - return m.OldCreatedAt(ctx) - } - return nil, fmt.Errorf("unknown RefreshToken field %s", name) -} - -// SetField sets the value of a field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *RefreshTokenMutation) SetField(name string, value ent.Value) error { - switch name { - case refreshtoken.FieldUserID: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUserID(v) - return nil - case refreshtoken.FieldTokenHash: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetTokenHash(v) - return nil - case refreshtoken.FieldExpiresAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetExpiresAt(v) - return nil - case refreshtoken.FieldCreatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCreatedAt(v) - return nil - } - return fmt.Errorf("unknown RefreshToken field %s", name) -} - -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *RefreshTokenMutation) AddedFields() []string { - return nil -} - -// AddedField returns the numeric value that was incremented/decremented on a field -// with the given name. The second boolean return value indicates that this field -// was not set, or was not defined in the schema. -func (m *RefreshTokenMutation) AddedField(name string) (ent.Value, bool) { - return nil, false -} - -// AddField adds the value to the field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *RefreshTokenMutation) AddField(name string, value ent.Value) error { - switch name { - } - return fmt.Errorf("unknown RefreshToken numeric field %s", name) -} - -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *RefreshTokenMutation) ClearedFields() []string { - return nil -} - -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *RefreshTokenMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok -} - -// ClearField clears the value of the field with the given name. It returns an -// error if the field is not defined in the schema. -func (m *RefreshTokenMutation) ClearField(name string) error { - return fmt.Errorf("unknown RefreshToken nullable field %s", name) -} - -// ResetField resets all changes in the mutation for the field with the given name. -// It returns an error if the field is not defined in the schema. -func (m *RefreshTokenMutation) ResetField(name string) error { - switch name { - case refreshtoken.FieldUserID: - m.ResetUserID() - return nil - case refreshtoken.FieldTokenHash: - m.ResetTokenHash() - return nil - case refreshtoken.FieldExpiresAt: - m.ResetExpiresAt() - return nil - case refreshtoken.FieldCreatedAt: - m.ResetCreatedAt() - return nil - } - return fmt.Errorf("unknown RefreshToken field %s", name) -} - -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *RefreshTokenMutation) AddedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *RefreshTokenMutation) AddedIDs(name string) []ent.Value { - return nil -} - -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *RefreshTokenMutation) RemovedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *RefreshTokenMutation) RemovedIDs(name string) []ent.Value { - return nil -} - -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *RefreshTokenMutation) ClearedEdges() []string { - edges := make([]string, 0, 0) - return edges -} - -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *RefreshTokenMutation) EdgeCleared(name string) bool { - return false -} - -// ClearEdge clears the value of the edge with the given name. It returns an error -// if that edge is not defined in the schema. -func (m *RefreshTokenMutation) ClearEdge(name string) error { - return fmt.Errorf("unknown RefreshToken unique edge %s", name) -} - -// ResetEdge resets all changes to the edge with the given name in this mutation. -// It returns an error if the edge is not defined in the schema. -func (m *RefreshTokenMutation) ResetEdge(name string) error { - return fmt.Errorf("unknown RefreshToken edge %s", name) -} - -// RoleMutation represents an operation that mutates the Role nodes in the graph. -type RoleMutation struct { - config - op Op - typ string - id *string - name *string - description *string - created_at *time.Time - clearedFields map[string]struct{} - role_permissions map[int]struct{} - removedrole_permissions map[int]struct{} - clearedrole_permissions bool - user_roles map[int]struct{} - removeduser_roles map[int]struct{} - cleareduser_roles bool - done bool - oldValue func(context.Context) (*Role, error) - predicates []predicate.Role -} - -var _ ent.Mutation = (*RoleMutation)(nil) - -// roleOption allows management of the mutation configuration using functional options. -type roleOption func(*RoleMutation) - -// newRoleMutation creates new mutation for the Role entity. -func newRoleMutation(c config, op Op, opts ...roleOption) *RoleMutation { - m := &RoleMutation{ - config: c, - op: op, - typ: TypeRole, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m -} - -// withRoleID sets the ID field of the mutation. -func withRoleID(id string) roleOption { - return func(m *RoleMutation) { - var ( - err error - once sync.Once - value *Role - ) - m.oldValue = func(ctx context.Context) (*Role, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().Role.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } -} - -// withRole sets the old Role of the mutation. -func withRole(node *Role) roleOption { - return func(m *RoleMutation) { - m.oldValue = func(context.Context) (*Role, error) { - return node, nil - } - m.id = &node.ID - } -} - -// Client returns a new `ent.Client` from the mutation. If the mutation was -// executed in a transaction (ent.Tx), a transactional client is returned. -func (m RoleMutation) Client() *Client { - client := &Client{config: m.config} - client.init() - return client -} - -// Tx returns an `ent.Tx` for mutations that were executed in transactions; -// it returns an error otherwise. -func (m RoleMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("ent: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil -} - -// SetID sets the value of the id field. Note that this -// operation is only accepted on creation of Role entities. -func (m *RoleMutation) SetID(id string) { - m.id = &id -} - -// ID returns the ID value in the mutation. Note that the ID is only available -// if it was provided to the builder or after it was returned from the database. -func (m *RoleMutation) ID() (id string, exists bool) { - if m.id == nil { - return - } - return *m.id, true -} - -// IDs queries the database and returns the entity ids that match the mutation's predicate. -// That means, if the mutation is applied within a transaction with an isolation level such -// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated -// or updated by the mutation. -func (m *RoleMutation) IDs(ctx context.Context) ([]string, error) { - switch { - case m.op.Is(OpUpdateOne | OpDeleteOne): - id, exists := m.ID() - if exists { - return []string{id}, nil - } - fallthrough - case m.op.Is(OpUpdate | OpDelete): - return m.Client().Role.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) - } -} - -// SetName sets the "name" field. -func (m *RoleMutation) SetName(s string) { - m.name = &s -} - -// Name returns the value of the "name" field in the mutation. -func (m *RoleMutation) Name() (r string, exists bool) { - v := m.name - if v == nil { - return - } - return *v, true -} - -// OldName returns the old "name" field's value of the Role entity. -// If the Role object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *RoleMutation) OldName(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldName is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldName requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldName: %w", err) - } - return oldValue.Name, nil -} - -// ResetName resets all changes to the "name" field. -func (m *RoleMutation) ResetName() { - m.name = nil -} - -// SetDescription sets the "description" field. -func (m *RoleMutation) SetDescription(s string) { - m.description = &s -} - -// Description returns the value of the "description" field in the mutation. -func (m *RoleMutation) Description() (r string, exists bool) { - v := m.description - if v == nil { - return - } - return *v, true -} - -// OldDescription returns the old "description" field's value of the Role entity. -// If the Role object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *RoleMutation) OldDescription(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldDescription is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldDescription requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldDescription: %w", err) - } - return oldValue.Description, nil -} - -// ClearDescription clears the value of the "description" field. -func (m *RoleMutation) ClearDescription() { - m.description = nil - m.clearedFields[role.FieldDescription] = struct{}{} -} - -// DescriptionCleared returns if the "description" field was cleared in this mutation. -func (m *RoleMutation) DescriptionCleared() bool { - _, ok := m.clearedFields[role.FieldDescription] - return ok -} - -// ResetDescription resets all changes to the "description" field. -func (m *RoleMutation) ResetDescription() { - m.description = nil - delete(m.clearedFields, role.FieldDescription) -} - -// SetCreatedAt sets the "created_at" field. -func (m *RoleMutation) SetCreatedAt(t time.Time) { - m.created_at = &t -} - -// CreatedAt returns the value of the "created_at" field in the mutation. -func (m *RoleMutation) CreatedAt() (r time.Time, exists bool) { - v := m.created_at - if v == nil { - return - } - return *v, true -} - -// OldCreatedAt returns the old "created_at" field's value of the Role entity. -// If the Role object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *RoleMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCreatedAt requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) - } - return oldValue.CreatedAt, nil -} - -// ResetCreatedAt resets all changes to the "created_at" field. -func (m *RoleMutation) ResetCreatedAt() { - m.created_at = nil -} - -// AddRolePermissionIDs adds the "role_permissions" edge to the RolePermission entity by ids. -func (m *RoleMutation) AddRolePermissionIDs(ids ...int) { - if m.role_permissions == nil { - m.role_permissions = make(map[int]struct{}) - } - for i := range ids { - m.role_permissions[ids[i]] = struct{}{} - } -} - -// ClearRolePermissions clears the "role_permissions" edge to the RolePermission entity. -func (m *RoleMutation) ClearRolePermissions() { - m.clearedrole_permissions = true -} - -// RolePermissionsCleared reports if the "role_permissions" edge to the RolePermission entity was cleared. -func (m *RoleMutation) RolePermissionsCleared() bool { - return m.clearedrole_permissions -} - -// RemoveRolePermissionIDs removes the "role_permissions" edge to the RolePermission entity by IDs. -func (m *RoleMutation) RemoveRolePermissionIDs(ids ...int) { - if m.removedrole_permissions == nil { - m.removedrole_permissions = make(map[int]struct{}) - } - for i := range ids { - delete(m.role_permissions, ids[i]) - m.removedrole_permissions[ids[i]] = struct{}{} - } -} - -// RemovedRolePermissions returns the removed IDs of the "role_permissions" edge to the RolePermission entity. -func (m *RoleMutation) RemovedRolePermissionsIDs() (ids []int) { - for id := range m.removedrole_permissions { - ids = append(ids, id) - } - return -} - -// RolePermissionsIDs returns the "role_permissions" edge IDs in the mutation. -func (m *RoleMutation) RolePermissionsIDs() (ids []int) { - for id := range m.role_permissions { - ids = append(ids, id) - } - return -} - -// ResetRolePermissions resets all changes to the "role_permissions" edge. -func (m *RoleMutation) ResetRolePermissions() { - m.role_permissions = nil - m.clearedrole_permissions = false - m.removedrole_permissions = nil -} - -// AddUserRoleIDs adds the "user_roles" edge to the UserRole entity by ids. -func (m *RoleMutation) AddUserRoleIDs(ids ...int) { - if m.user_roles == nil { - m.user_roles = make(map[int]struct{}) - } - for i := range ids { - m.user_roles[ids[i]] = struct{}{} - } -} - -// ClearUserRoles clears the "user_roles" edge to the UserRole entity. -func (m *RoleMutation) ClearUserRoles() { - m.cleareduser_roles = true -} - -// UserRolesCleared reports if the "user_roles" edge to the UserRole entity was cleared. -func (m *RoleMutation) UserRolesCleared() bool { - return m.cleareduser_roles -} - -// RemoveUserRoleIDs removes the "user_roles" edge to the UserRole entity by IDs. -func (m *RoleMutation) RemoveUserRoleIDs(ids ...int) { - if m.removeduser_roles == nil { - m.removeduser_roles = make(map[int]struct{}) - } - for i := range ids { - delete(m.user_roles, ids[i]) - m.removeduser_roles[ids[i]] = struct{}{} - } -} - -// RemovedUserRoles returns the removed IDs of the "user_roles" edge to the UserRole entity. -func (m *RoleMutation) RemovedUserRolesIDs() (ids []int) { - for id := range m.removeduser_roles { - ids = append(ids, id) - } - return -} - -// UserRolesIDs returns the "user_roles" edge IDs in the mutation. -func (m *RoleMutation) UserRolesIDs() (ids []int) { - for id := range m.user_roles { - ids = append(ids, id) - } - return -} - -// ResetUserRoles resets all changes to the "user_roles" edge. -func (m *RoleMutation) ResetUserRoles() { - m.user_roles = nil - m.cleareduser_roles = false - m.removeduser_roles = nil -} - -// Where appends a list predicates to the RoleMutation builder. -func (m *RoleMutation) Where(ps ...predicate.Role) { - m.predicates = append(m.predicates, ps...) -} - -// WhereP appends storage-level predicates to the RoleMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *RoleMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.Role, len(ps)) - for i := range ps { - p[i] = ps[i] - } - m.Where(p...) -} - -// Op returns the operation name. -func (m *RoleMutation) Op() Op { - return m.op -} - -// SetOp allows setting the mutation operation. -func (m *RoleMutation) SetOp(op Op) { - m.op = op -} - -// Type returns the node type of this mutation (Role). -func (m *RoleMutation) Type() string { - return m.typ -} - -// Fields returns all fields that were changed during this mutation. Note that in -// order to get all numeric fields that were incremented/decremented, call -// AddedFields(). -func (m *RoleMutation) Fields() []string { - fields := make([]string, 0, 3) - if m.name != nil { - fields = append(fields, role.FieldName) - } - if m.description != nil { - fields = append(fields, role.FieldDescription) - } - if m.created_at != nil { - fields = append(fields, role.FieldCreatedAt) - } - return fields -} - -// Field returns the value of a field with the given name. The second boolean -// return value indicates that this field was not set, or was not defined in the -// schema. -func (m *RoleMutation) Field(name string) (ent.Value, bool) { - switch name { - case role.FieldName: - return m.Name() - case role.FieldDescription: - return m.Description() - case role.FieldCreatedAt: - return m.CreatedAt() - } - return nil, false -} - -// OldField returns the old value of the field from the database. An error is -// returned if the mutation operation is not UpdateOne, or the query to the -// database failed. -func (m *RoleMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case role.FieldName: - return m.OldName(ctx) - case role.FieldDescription: - return m.OldDescription(ctx) - case role.FieldCreatedAt: - return m.OldCreatedAt(ctx) - } - return nil, fmt.Errorf("unknown Role field %s", name) -} - -// SetField sets the value of a field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *RoleMutation) SetField(name string, value ent.Value) error { - switch name { - case role.FieldName: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetName(v) - return nil - case role.FieldDescription: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetDescription(v) - return nil - case role.FieldCreatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCreatedAt(v) - return nil - } - return fmt.Errorf("unknown Role field %s", name) -} - -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *RoleMutation) AddedFields() []string { - return nil -} - -// AddedField returns the numeric value that was incremented/decremented on a field -// with the given name. The second boolean return value indicates that this field -// was not set, or was not defined in the schema. -func (m *RoleMutation) AddedField(name string) (ent.Value, bool) { - return nil, false -} - -// AddField adds the value to the field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *RoleMutation) AddField(name string, value ent.Value) error { - switch name { - } - return fmt.Errorf("unknown Role numeric field %s", name) -} - -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *RoleMutation) ClearedFields() []string { - var fields []string - if m.FieldCleared(role.FieldDescription) { - fields = append(fields, role.FieldDescription) - } - return fields -} - -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *RoleMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok -} - -// ClearField clears the value of the field with the given name. It returns an -// error if the field is not defined in the schema. -func (m *RoleMutation) ClearField(name string) error { - switch name { - case role.FieldDescription: - m.ClearDescription() - return nil - } - return fmt.Errorf("unknown Role nullable field %s", name) -} - -// ResetField resets all changes in the mutation for the field with the given name. -// It returns an error if the field is not defined in the schema. -func (m *RoleMutation) ResetField(name string) error { - switch name { - case role.FieldName: - m.ResetName() - return nil - case role.FieldDescription: - m.ResetDescription() - return nil - case role.FieldCreatedAt: - m.ResetCreatedAt() - return nil - } - return fmt.Errorf("unknown Role field %s", name) -} - -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *RoleMutation) AddedEdges() []string { - edges := make([]string, 0, 2) - if m.role_permissions != nil { - edges = append(edges, role.EdgeRolePermissions) - } - if m.user_roles != nil { - edges = append(edges, role.EdgeUserRoles) - } - return edges -} - -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *RoleMutation) AddedIDs(name string) []ent.Value { - switch name { - case role.EdgeRolePermissions: - ids := make([]ent.Value, 0, len(m.role_permissions)) - for id := range m.role_permissions { - ids = append(ids, id) - } - return ids - case role.EdgeUserRoles: - ids := make([]ent.Value, 0, len(m.user_roles)) - for id := range m.user_roles { - ids = append(ids, id) - } - return ids - } - return nil -} - -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *RoleMutation) RemovedEdges() []string { - edges := make([]string, 0, 2) - if m.removedrole_permissions != nil { - edges = append(edges, role.EdgeRolePermissions) - } - if m.removeduser_roles != nil { - edges = append(edges, role.EdgeUserRoles) - } - return edges -} - -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *RoleMutation) RemovedIDs(name string) []ent.Value { - switch name { - case role.EdgeRolePermissions: - ids := make([]ent.Value, 0, len(m.removedrole_permissions)) - for id := range m.removedrole_permissions { - ids = append(ids, id) - } - return ids - case role.EdgeUserRoles: - ids := make([]ent.Value, 0, len(m.removeduser_roles)) - for id := range m.removeduser_roles { - ids = append(ids, id) - } - return ids - } - return nil -} - -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *RoleMutation) ClearedEdges() []string { - edges := make([]string, 0, 2) - if m.clearedrole_permissions { - edges = append(edges, role.EdgeRolePermissions) - } - if m.cleareduser_roles { - edges = append(edges, role.EdgeUserRoles) - } - return edges -} - -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *RoleMutation) EdgeCleared(name string) bool { - switch name { - case role.EdgeRolePermissions: - return m.clearedrole_permissions - case role.EdgeUserRoles: - return m.cleareduser_roles - } - return false -} - -// ClearEdge clears the value of the edge with the given name. It returns an error -// if that edge is not defined in the schema. -func (m *RoleMutation) ClearEdge(name string) error { - switch name { - } - return fmt.Errorf("unknown Role unique edge %s", name) -} - -// ResetEdge resets all changes to the edge with the given name in this mutation. -// It returns an error if the edge is not defined in the schema. -func (m *RoleMutation) ResetEdge(name string) error { - switch name { - case role.EdgeRolePermissions: - m.ResetRolePermissions() - return nil - case role.EdgeUserRoles: - m.ResetUserRoles() - return nil - } - return fmt.Errorf("unknown Role edge %s", name) -} - -// RolePermissionMutation represents an operation that mutates the RolePermission nodes in the graph. -type RolePermissionMutation struct { - config - op Op - typ string - id *int - clearedFields map[string]struct{} - role *string - clearedrole bool - permission *string - clearedpermission bool - done bool - oldValue func(context.Context) (*RolePermission, error) - predicates []predicate.RolePermission -} - -var _ ent.Mutation = (*RolePermissionMutation)(nil) - -// rolepermissionOption allows management of the mutation configuration using functional options. -type rolepermissionOption func(*RolePermissionMutation) - -// newRolePermissionMutation creates new mutation for the RolePermission entity. -func newRolePermissionMutation(c config, op Op, opts ...rolepermissionOption) *RolePermissionMutation { - m := &RolePermissionMutation{ - config: c, - op: op, - typ: TypeRolePermission, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m -} - -// withRolePermissionID sets the ID field of the mutation. -func withRolePermissionID(id int) rolepermissionOption { - return func(m *RolePermissionMutation) { - var ( - err error - once sync.Once - value *RolePermission - ) - m.oldValue = func(ctx context.Context) (*RolePermission, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().RolePermission.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } -} - -// withRolePermission sets the old RolePermission of the mutation. -func withRolePermission(node *RolePermission) rolepermissionOption { - return func(m *RolePermissionMutation) { - m.oldValue = func(context.Context) (*RolePermission, error) { - return node, nil - } - m.id = &node.ID - } -} - -// Client returns a new `ent.Client` from the mutation. If the mutation was -// executed in a transaction (ent.Tx), a transactional client is returned. -func (m RolePermissionMutation) Client() *Client { - client := &Client{config: m.config} - client.init() - return client -} - -// Tx returns an `ent.Tx` for mutations that were executed in transactions; -// it returns an error otherwise. -func (m RolePermissionMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("ent: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil -} - -// ID returns the ID value in the mutation. Note that the ID is only available -// if it was provided to the builder or after it was returned from the database. -func (m *RolePermissionMutation) ID() (id int, exists bool) { - if m.id == nil { - return - } - return *m.id, true -} - -// IDs queries the database and returns the entity ids that match the mutation's predicate. -// That means, if the mutation is applied within a transaction with an isolation level such -// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated -// or updated by the mutation. -func (m *RolePermissionMutation) IDs(ctx context.Context) ([]int, error) { - switch { - case m.op.Is(OpUpdateOne | OpDeleteOne): - id, exists := m.ID() - if exists { - return []int{id}, nil - } - fallthrough - case m.op.Is(OpUpdate | OpDelete): - return m.Client().RolePermission.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) - } -} - -// SetRoleID sets the "role_id" field. -func (m *RolePermissionMutation) SetRoleID(s string) { - m.role = &s -} - -// RoleID returns the value of the "role_id" field in the mutation. -func (m *RolePermissionMutation) RoleID() (r string, exists bool) { - v := m.role - if v == nil { - return - } - return *v, true -} - -// OldRoleID returns the old "role_id" field's value of the RolePermission entity. -// If the RolePermission object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *RolePermissionMutation) OldRoleID(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldRoleID is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldRoleID requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldRoleID: %w", err) - } - return oldValue.RoleID, nil -} - -// ResetRoleID resets all changes to the "role_id" field. -func (m *RolePermissionMutation) ResetRoleID() { - m.role = nil -} - -// SetPermissionID sets the "permission_id" field. -func (m *RolePermissionMutation) SetPermissionID(s string) { - m.permission = &s -} - -// PermissionID returns the value of the "permission_id" field in the mutation. -func (m *RolePermissionMutation) PermissionID() (r string, exists bool) { - v := m.permission - if v == nil { - return - } - return *v, true -} - -// OldPermissionID returns the old "permission_id" field's value of the RolePermission entity. -// If the RolePermission object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *RolePermissionMutation) OldPermissionID(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldPermissionID is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldPermissionID requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldPermissionID: %w", err) - } - return oldValue.PermissionID, nil -} - -// ResetPermissionID resets all changes to the "permission_id" field. -func (m *RolePermissionMutation) ResetPermissionID() { - m.permission = nil -} - -// ClearRole clears the "role" edge to the Role entity. -func (m *RolePermissionMutation) ClearRole() { - m.clearedrole = true - m.clearedFields[rolepermission.FieldRoleID] = struct{}{} -} - -// RoleCleared reports if the "role" edge to the Role entity was cleared. -func (m *RolePermissionMutation) RoleCleared() bool { - return m.clearedrole -} - -// RoleIDs returns the "role" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// RoleID instead. It exists only for internal usage by the builders. -func (m *RolePermissionMutation) RoleIDs() (ids []string) { - if id := m.role; id != nil { - ids = append(ids, *id) - } - return -} - -// ResetRole resets all changes to the "role" edge. -func (m *RolePermissionMutation) ResetRole() { - m.role = nil - m.clearedrole = false -} - -// ClearPermission clears the "permission" edge to the Permission entity. -func (m *RolePermissionMutation) ClearPermission() { - m.clearedpermission = true - m.clearedFields[rolepermission.FieldPermissionID] = struct{}{} -} - -// PermissionCleared reports if the "permission" edge to the Permission entity was cleared. -func (m *RolePermissionMutation) PermissionCleared() bool { - return m.clearedpermission -} - -// PermissionIDs returns the "permission" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// PermissionID instead. It exists only for internal usage by the builders. -func (m *RolePermissionMutation) PermissionIDs() (ids []string) { - if id := m.permission; id != nil { - ids = append(ids, *id) - } - return -} - -// ResetPermission resets all changes to the "permission" edge. -func (m *RolePermissionMutation) ResetPermission() { - m.permission = nil - m.clearedpermission = false -} - -// Where appends a list predicates to the RolePermissionMutation builder. -func (m *RolePermissionMutation) Where(ps ...predicate.RolePermission) { - m.predicates = append(m.predicates, ps...) -} - -// WhereP appends storage-level predicates to the RolePermissionMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *RolePermissionMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.RolePermission, len(ps)) - for i := range ps { - p[i] = ps[i] - } - m.Where(p...) -} - -// Op returns the operation name. -func (m *RolePermissionMutation) Op() Op { - return m.op -} - -// SetOp allows setting the mutation operation. -func (m *RolePermissionMutation) SetOp(op Op) { - m.op = op -} - -// Type returns the node type of this mutation (RolePermission). -func (m *RolePermissionMutation) Type() string { - return m.typ -} - -// Fields returns all fields that were changed during this mutation. Note that in -// order to get all numeric fields that were incremented/decremented, call -// AddedFields(). -func (m *RolePermissionMutation) Fields() []string { - fields := make([]string, 0, 2) - if m.role != nil { - fields = append(fields, rolepermission.FieldRoleID) - } - if m.permission != nil { - fields = append(fields, rolepermission.FieldPermissionID) - } - return fields -} - -// Field returns the value of a field with the given name. The second boolean -// return value indicates that this field was not set, or was not defined in the -// schema. -func (m *RolePermissionMutation) Field(name string) (ent.Value, bool) { - switch name { - case rolepermission.FieldRoleID: - return m.RoleID() - case rolepermission.FieldPermissionID: - return m.PermissionID() - } - return nil, false -} - -// OldField returns the old value of the field from the database. An error is -// returned if the mutation operation is not UpdateOne, or the query to the -// database failed. -func (m *RolePermissionMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case rolepermission.FieldRoleID: - return m.OldRoleID(ctx) - case rolepermission.FieldPermissionID: - return m.OldPermissionID(ctx) - } - return nil, fmt.Errorf("unknown RolePermission field %s", name) -} - -// SetField sets the value of a field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *RolePermissionMutation) SetField(name string, value ent.Value) error { - switch name { - case rolepermission.FieldRoleID: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetRoleID(v) - return nil - case rolepermission.FieldPermissionID: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetPermissionID(v) - return nil - } - return fmt.Errorf("unknown RolePermission field %s", name) -} - -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *RolePermissionMutation) AddedFields() []string { - return nil -} - -// AddedField returns the numeric value that was incremented/decremented on a field -// with the given name. The second boolean return value indicates that this field -// was not set, or was not defined in the schema. -func (m *RolePermissionMutation) AddedField(name string) (ent.Value, bool) { - return nil, false -} - -// AddField adds the value to the field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *RolePermissionMutation) AddField(name string, value ent.Value) error { - switch name { - } - return fmt.Errorf("unknown RolePermission numeric field %s", name) -} - -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *RolePermissionMutation) ClearedFields() []string { - return nil -} - -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *RolePermissionMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok -} - -// ClearField clears the value of the field with the given name. It returns an -// error if the field is not defined in the schema. -func (m *RolePermissionMutation) ClearField(name string) error { - return fmt.Errorf("unknown RolePermission nullable field %s", name) -} - -// ResetField resets all changes in the mutation for the field with the given name. -// It returns an error if the field is not defined in the schema. -func (m *RolePermissionMutation) ResetField(name string) error { - switch name { - case rolepermission.FieldRoleID: - m.ResetRoleID() - return nil - case rolepermission.FieldPermissionID: - m.ResetPermissionID() - return nil - } - return fmt.Errorf("unknown RolePermission field %s", name) -} - -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *RolePermissionMutation) AddedEdges() []string { - edges := make([]string, 0, 2) - if m.role != nil { - edges = append(edges, rolepermission.EdgeRole) - } - if m.permission != nil { - edges = append(edges, rolepermission.EdgePermission) - } - return edges -} - -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *RolePermissionMutation) AddedIDs(name string) []ent.Value { - switch name { - case rolepermission.EdgeRole: - if id := m.role; id != nil { - return []ent.Value{*id} - } - case rolepermission.EdgePermission: - if id := m.permission; id != nil { - return []ent.Value{*id} - } - } - return nil -} - -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *RolePermissionMutation) RemovedEdges() []string { - edges := make([]string, 0, 2) - return edges -} - -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *RolePermissionMutation) RemovedIDs(name string) []ent.Value { - return nil -} - -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *RolePermissionMutation) ClearedEdges() []string { - edges := make([]string, 0, 2) - if m.clearedrole { - edges = append(edges, rolepermission.EdgeRole) - } - if m.clearedpermission { - edges = append(edges, rolepermission.EdgePermission) - } - return edges -} - -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *RolePermissionMutation) EdgeCleared(name string) bool { - switch name { - case rolepermission.EdgeRole: - return m.clearedrole - case rolepermission.EdgePermission: - return m.clearedpermission - } - return false -} - -// ClearEdge clears the value of the edge with the given name. It returns an error -// if that edge is not defined in the schema. -func (m *RolePermissionMutation) ClearEdge(name string) error { - switch name { - case rolepermission.EdgeRole: - m.ClearRole() - return nil - case rolepermission.EdgePermission: - m.ClearPermission() - return nil - } - return fmt.Errorf("unknown RolePermission unique edge %s", name) -} - -// ResetEdge resets all changes to the edge with the given name in this mutation. -// It returns an error if the edge is not defined in the schema. -func (m *RolePermissionMutation) ResetEdge(name string) error { - switch name { - case rolepermission.EdgeRole: - m.ResetRole() - return nil - case rolepermission.EdgePermission: - m.ResetPermission() - return nil - } - return fmt.Errorf("unknown RolePermission edge %s", name) -} - -// UserMutation represents an operation that mutates the User nodes in the graph. -type UserMutation struct { - config - op Op - typ string - id *string - email *string - username *string - first_name *string - last_name *string - password_hash *string - verified *bool - email_verification_token *string - password_reset_token *string - password_reset_expires_at *time.Time - created_at *time.Time - updated_at *time.Time - clearedFields map[string]struct{} - user_roles map[int]struct{} - removeduser_roles map[int]struct{} - cleareduser_roles bool - done bool - oldValue func(context.Context) (*User, error) - predicates []predicate.User -} - -var _ ent.Mutation = (*UserMutation)(nil) - -// userOption allows management of the mutation configuration using functional options. -type userOption func(*UserMutation) - -// newUserMutation creates new mutation for the User entity. -func newUserMutation(c config, op Op, opts ...userOption) *UserMutation { - m := &UserMutation{ - config: c, - op: op, - typ: TypeUser, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m -} - -// withUserID sets the ID field of the mutation. -func withUserID(id string) userOption { - return func(m *UserMutation) { - var ( - err error - once sync.Once - value *User - ) - m.oldValue = func(ctx context.Context) (*User, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().User.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } -} - -// withUser sets the old User of the mutation. -func withUser(node *User) userOption { - return func(m *UserMutation) { - m.oldValue = func(context.Context) (*User, error) { - return node, nil - } - m.id = &node.ID - } -} - -// Client returns a new `ent.Client` from the mutation. If the mutation was -// executed in a transaction (ent.Tx), a transactional client is returned. -func (m UserMutation) Client() *Client { - client := &Client{config: m.config} - client.init() - return client -} - -// Tx returns an `ent.Tx` for mutations that were executed in transactions; -// it returns an error otherwise. -func (m UserMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("ent: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil -} - -// SetID sets the value of the id field. Note that this -// operation is only accepted on creation of User entities. -func (m *UserMutation) SetID(id string) { - m.id = &id -} - -// ID returns the ID value in the mutation. Note that the ID is only available -// if it was provided to the builder or after it was returned from the database. -func (m *UserMutation) ID() (id string, exists bool) { - if m.id == nil { - return - } - return *m.id, true -} - -// IDs queries the database and returns the entity ids that match the mutation's predicate. -// That means, if the mutation is applied within a transaction with an isolation level such -// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated -// or updated by the mutation. -func (m *UserMutation) IDs(ctx context.Context) ([]string, error) { - switch { - case m.op.Is(OpUpdateOne | OpDeleteOne): - id, exists := m.ID() - if exists { - return []string{id}, nil - } - fallthrough - case m.op.Is(OpUpdate | OpDelete): - return m.Client().User.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) - } -} - -// SetEmail sets the "email" field. -func (m *UserMutation) SetEmail(s string) { - m.email = &s -} - -// Email returns the value of the "email" field in the mutation. -func (m *UserMutation) Email() (r string, exists bool) { - v := m.email - if v == nil { - return - } - return *v, true -} - -// OldEmail returns the old "email" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserMutation) OldEmail(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldEmail is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldEmail requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldEmail: %w", err) - } - return oldValue.Email, nil -} - -// ResetEmail resets all changes to the "email" field. -func (m *UserMutation) ResetEmail() { - m.email = nil -} - -// SetUsername sets the "username" field. -func (m *UserMutation) SetUsername(s string) { - m.username = &s -} - -// Username returns the value of the "username" field in the mutation. -func (m *UserMutation) Username() (r string, exists bool) { - v := m.username - if v == nil { - return - } - return *v, true -} - -// OldUsername returns the old "username" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserMutation) OldUsername(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUsername is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUsername requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldUsername: %w", err) - } - return oldValue.Username, nil -} - -// ClearUsername clears the value of the "username" field. -func (m *UserMutation) ClearUsername() { - m.username = nil - m.clearedFields[user.FieldUsername] = struct{}{} -} - -// UsernameCleared returns if the "username" field was cleared in this mutation. -func (m *UserMutation) UsernameCleared() bool { - _, ok := m.clearedFields[user.FieldUsername] - return ok -} - -// ResetUsername resets all changes to the "username" field. -func (m *UserMutation) ResetUsername() { - m.username = nil - delete(m.clearedFields, user.FieldUsername) -} - -// SetFirstName sets the "first_name" field. -func (m *UserMutation) SetFirstName(s string) { - m.first_name = &s -} - -// FirstName returns the value of the "first_name" field in the mutation. -func (m *UserMutation) FirstName() (r string, exists bool) { - v := m.first_name - if v == nil { - return - } - return *v, true -} - -// OldFirstName returns the old "first_name" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserMutation) OldFirstName(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldFirstName is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldFirstName requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldFirstName: %w", err) - } - return oldValue.FirstName, nil -} - -// ClearFirstName clears the value of the "first_name" field. -func (m *UserMutation) ClearFirstName() { - m.first_name = nil - m.clearedFields[user.FieldFirstName] = struct{}{} -} - -// FirstNameCleared returns if the "first_name" field was cleared in this mutation. -func (m *UserMutation) FirstNameCleared() bool { - _, ok := m.clearedFields[user.FieldFirstName] - return ok -} - -// ResetFirstName resets all changes to the "first_name" field. -func (m *UserMutation) ResetFirstName() { - m.first_name = nil - delete(m.clearedFields, user.FieldFirstName) -} - -// SetLastName sets the "last_name" field. -func (m *UserMutation) SetLastName(s string) { - m.last_name = &s -} - -// LastName returns the value of the "last_name" field in the mutation. -func (m *UserMutation) LastName() (r string, exists bool) { - v := m.last_name - if v == nil { - return - } - return *v, true -} - -// OldLastName returns the old "last_name" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserMutation) OldLastName(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldLastName is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldLastName requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldLastName: %w", err) - } - return oldValue.LastName, nil -} - -// ClearLastName clears the value of the "last_name" field. -func (m *UserMutation) ClearLastName() { - m.last_name = nil - m.clearedFields[user.FieldLastName] = struct{}{} -} - -// LastNameCleared returns if the "last_name" field was cleared in this mutation. -func (m *UserMutation) LastNameCleared() bool { - _, ok := m.clearedFields[user.FieldLastName] - return ok -} - -// ResetLastName resets all changes to the "last_name" field. -func (m *UserMutation) ResetLastName() { - m.last_name = nil - delete(m.clearedFields, user.FieldLastName) -} - -// SetPasswordHash sets the "password_hash" field. -func (m *UserMutation) SetPasswordHash(s string) { - m.password_hash = &s -} - -// PasswordHash returns the value of the "password_hash" field in the mutation. -func (m *UserMutation) PasswordHash() (r string, exists bool) { - v := m.password_hash - if v == nil { - return - } - return *v, true -} - -// OldPasswordHash returns the old "password_hash" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserMutation) OldPasswordHash(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldPasswordHash is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldPasswordHash requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldPasswordHash: %w", err) - } - return oldValue.PasswordHash, nil -} - -// ResetPasswordHash resets all changes to the "password_hash" field. -func (m *UserMutation) ResetPasswordHash() { - m.password_hash = nil -} - -// SetVerified sets the "verified" field. -func (m *UserMutation) SetVerified(b bool) { - m.verified = &b -} - -// Verified returns the value of the "verified" field in the mutation. -func (m *UserMutation) Verified() (r bool, exists bool) { - v := m.verified - if v == nil { - return - } - return *v, true -} - -// OldVerified returns the old "verified" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserMutation) OldVerified(ctx context.Context) (v bool, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldVerified is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldVerified requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldVerified: %w", err) - } - return oldValue.Verified, nil -} - -// ResetVerified resets all changes to the "verified" field. -func (m *UserMutation) ResetVerified() { - m.verified = nil -} - -// SetEmailVerificationToken sets the "email_verification_token" field. -func (m *UserMutation) SetEmailVerificationToken(s string) { - m.email_verification_token = &s -} - -// EmailVerificationToken returns the value of the "email_verification_token" field in the mutation. -func (m *UserMutation) EmailVerificationToken() (r string, exists bool) { - v := m.email_verification_token - if v == nil { - return - } - return *v, true -} - -// OldEmailVerificationToken returns the old "email_verification_token" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserMutation) OldEmailVerificationToken(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldEmailVerificationToken is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldEmailVerificationToken requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldEmailVerificationToken: %w", err) - } - return oldValue.EmailVerificationToken, nil -} - -// ClearEmailVerificationToken clears the value of the "email_verification_token" field. -func (m *UserMutation) ClearEmailVerificationToken() { - m.email_verification_token = nil - m.clearedFields[user.FieldEmailVerificationToken] = struct{}{} -} - -// EmailVerificationTokenCleared returns if the "email_verification_token" field was cleared in this mutation. -func (m *UserMutation) EmailVerificationTokenCleared() bool { - _, ok := m.clearedFields[user.FieldEmailVerificationToken] - return ok -} - -// ResetEmailVerificationToken resets all changes to the "email_verification_token" field. -func (m *UserMutation) ResetEmailVerificationToken() { - m.email_verification_token = nil - delete(m.clearedFields, user.FieldEmailVerificationToken) -} - -// SetPasswordResetToken sets the "password_reset_token" field. -func (m *UserMutation) SetPasswordResetToken(s string) { - m.password_reset_token = &s -} - -// PasswordResetToken returns the value of the "password_reset_token" field in the mutation. -func (m *UserMutation) PasswordResetToken() (r string, exists bool) { - v := m.password_reset_token - if v == nil { - return - } - return *v, true -} - -// OldPasswordResetToken returns the old "password_reset_token" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserMutation) OldPasswordResetToken(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldPasswordResetToken is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldPasswordResetToken requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldPasswordResetToken: %w", err) - } - return oldValue.PasswordResetToken, nil -} - -// ClearPasswordResetToken clears the value of the "password_reset_token" field. -func (m *UserMutation) ClearPasswordResetToken() { - m.password_reset_token = nil - m.clearedFields[user.FieldPasswordResetToken] = struct{}{} -} - -// PasswordResetTokenCleared returns if the "password_reset_token" field was cleared in this mutation. -func (m *UserMutation) PasswordResetTokenCleared() bool { - _, ok := m.clearedFields[user.FieldPasswordResetToken] - return ok -} - -// ResetPasswordResetToken resets all changes to the "password_reset_token" field. -func (m *UserMutation) ResetPasswordResetToken() { - m.password_reset_token = nil - delete(m.clearedFields, user.FieldPasswordResetToken) -} - -// SetPasswordResetExpiresAt sets the "password_reset_expires_at" field. -func (m *UserMutation) SetPasswordResetExpiresAt(t time.Time) { - m.password_reset_expires_at = &t -} - -// PasswordResetExpiresAt returns the value of the "password_reset_expires_at" field in the mutation. -func (m *UserMutation) PasswordResetExpiresAt() (r time.Time, exists bool) { - v := m.password_reset_expires_at - if v == nil { - return - } - return *v, true -} - -// OldPasswordResetExpiresAt returns the old "password_reset_expires_at" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserMutation) OldPasswordResetExpiresAt(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldPasswordResetExpiresAt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldPasswordResetExpiresAt requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldPasswordResetExpiresAt: %w", err) - } - return oldValue.PasswordResetExpiresAt, nil -} - -// ClearPasswordResetExpiresAt clears the value of the "password_reset_expires_at" field. -func (m *UserMutation) ClearPasswordResetExpiresAt() { - m.password_reset_expires_at = nil - m.clearedFields[user.FieldPasswordResetExpiresAt] = struct{}{} -} - -// PasswordResetExpiresAtCleared returns if the "password_reset_expires_at" field was cleared in this mutation. -func (m *UserMutation) PasswordResetExpiresAtCleared() bool { - _, ok := m.clearedFields[user.FieldPasswordResetExpiresAt] - return ok -} - -// ResetPasswordResetExpiresAt resets all changes to the "password_reset_expires_at" field. -func (m *UserMutation) ResetPasswordResetExpiresAt() { - m.password_reset_expires_at = nil - delete(m.clearedFields, user.FieldPasswordResetExpiresAt) -} - -// SetCreatedAt sets the "created_at" field. -func (m *UserMutation) SetCreatedAt(t time.Time) { - m.created_at = &t -} - -// CreatedAt returns the value of the "created_at" field in the mutation. -func (m *UserMutation) CreatedAt() (r time.Time, exists bool) { - v := m.created_at - if v == nil { - return - } - return *v, true -} - -// OldCreatedAt returns the old "created_at" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldCreatedAt requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) - } - return oldValue.CreatedAt, nil -} - -// ResetCreatedAt resets all changes to the "created_at" field. -func (m *UserMutation) ResetCreatedAt() { - m.created_at = nil -} - -// SetUpdatedAt sets the "updated_at" field. -func (m *UserMutation) SetUpdatedAt(t time.Time) { - m.updated_at = &t -} - -// UpdatedAt returns the value of the "updated_at" field in the mutation. -func (m *UserMutation) UpdatedAt() (r time.Time, exists bool) { - v := m.updated_at - if v == nil { - return - } - return *v, true -} - -// OldUpdatedAt returns the old "updated_at" field's value of the User entity. -// If the User object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUpdatedAt requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) - } - return oldValue.UpdatedAt, nil -} - -// ResetUpdatedAt resets all changes to the "updated_at" field. -func (m *UserMutation) ResetUpdatedAt() { - m.updated_at = nil -} - -// AddUserRoleIDs adds the "user_roles" edge to the UserRole entity by ids. -func (m *UserMutation) AddUserRoleIDs(ids ...int) { - if m.user_roles == nil { - m.user_roles = make(map[int]struct{}) - } - for i := range ids { - m.user_roles[ids[i]] = struct{}{} - } -} - -// ClearUserRoles clears the "user_roles" edge to the UserRole entity. -func (m *UserMutation) ClearUserRoles() { - m.cleareduser_roles = true -} - -// UserRolesCleared reports if the "user_roles" edge to the UserRole entity was cleared. -func (m *UserMutation) UserRolesCleared() bool { - return m.cleareduser_roles -} - -// RemoveUserRoleIDs removes the "user_roles" edge to the UserRole entity by IDs. -func (m *UserMutation) RemoveUserRoleIDs(ids ...int) { - if m.removeduser_roles == nil { - m.removeduser_roles = make(map[int]struct{}) - } - for i := range ids { - delete(m.user_roles, ids[i]) - m.removeduser_roles[ids[i]] = struct{}{} - } -} - -// RemovedUserRoles returns the removed IDs of the "user_roles" edge to the UserRole entity. -func (m *UserMutation) RemovedUserRolesIDs() (ids []int) { - for id := range m.removeduser_roles { - ids = append(ids, id) - } - return -} - -// UserRolesIDs returns the "user_roles" edge IDs in the mutation. -func (m *UserMutation) UserRolesIDs() (ids []int) { - for id := range m.user_roles { - ids = append(ids, id) - } - return -} - -// ResetUserRoles resets all changes to the "user_roles" edge. -func (m *UserMutation) ResetUserRoles() { - m.user_roles = nil - m.cleareduser_roles = false - m.removeduser_roles = nil -} - -// Where appends a list predicates to the UserMutation builder. -func (m *UserMutation) Where(ps ...predicate.User) { - m.predicates = append(m.predicates, ps...) -} - -// WhereP appends storage-level predicates to the UserMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *UserMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.User, len(ps)) - for i := range ps { - p[i] = ps[i] - } - m.Where(p...) -} - -// Op returns the operation name. -func (m *UserMutation) Op() Op { - return m.op -} - -// SetOp allows setting the mutation operation. -func (m *UserMutation) SetOp(op Op) { - m.op = op -} - -// Type returns the node type of this mutation (User). -func (m *UserMutation) Type() string { - return m.typ -} - -// Fields returns all fields that were changed during this mutation. Note that in -// order to get all numeric fields that were incremented/decremented, call -// AddedFields(). -func (m *UserMutation) Fields() []string { - fields := make([]string, 0, 11) - if m.email != nil { - fields = append(fields, user.FieldEmail) - } - if m.username != nil { - fields = append(fields, user.FieldUsername) - } - if m.first_name != nil { - fields = append(fields, user.FieldFirstName) - } - if m.last_name != nil { - fields = append(fields, user.FieldLastName) - } - if m.password_hash != nil { - fields = append(fields, user.FieldPasswordHash) - } - if m.verified != nil { - fields = append(fields, user.FieldVerified) - } - if m.email_verification_token != nil { - fields = append(fields, user.FieldEmailVerificationToken) - } - if m.password_reset_token != nil { - fields = append(fields, user.FieldPasswordResetToken) - } - if m.password_reset_expires_at != nil { - fields = append(fields, user.FieldPasswordResetExpiresAt) - } - if m.created_at != nil { - fields = append(fields, user.FieldCreatedAt) - } - if m.updated_at != nil { - fields = append(fields, user.FieldUpdatedAt) - } - return fields -} - -// Field returns the value of a field with the given name. The second boolean -// return value indicates that this field was not set, or was not defined in the -// schema. -func (m *UserMutation) Field(name string) (ent.Value, bool) { - switch name { - case user.FieldEmail: - return m.Email() - case user.FieldUsername: - return m.Username() - case user.FieldFirstName: - return m.FirstName() - case user.FieldLastName: - return m.LastName() - case user.FieldPasswordHash: - return m.PasswordHash() - case user.FieldVerified: - return m.Verified() - case user.FieldEmailVerificationToken: - return m.EmailVerificationToken() - case user.FieldPasswordResetToken: - return m.PasswordResetToken() - case user.FieldPasswordResetExpiresAt: - return m.PasswordResetExpiresAt() - case user.FieldCreatedAt: - return m.CreatedAt() - case user.FieldUpdatedAt: - return m.UpdatedAt() - } - return nil, false -} - -// OldField returns the old value of the field from the database. An error is -// returned if the mutation operation is not UpdateOne, or the query to the -// database failed. -func (m *UserMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case user.FieldEmail: - return m.OldEmail(ctx) - case user.FieldUsername: - return m.OldUsername(ctx) - case user.FieldFirstName: - return m.OldFirstName(ctx) - case user.FieldLastName: - return m.OldLastName(ctx) - case user.FieldPasswordHash: - return m.OldPasswordHash(ctx) - case user.FieldVerified: - return m.OldVerified(ctx) - case user.FieldEmailVerificationToken: - return m.OldEmailVerificationToken(ctx) - case user.FieldPasswordResetToken: - return m.OldPasswordResetToken(ctx) - case user.FieldPasswordResetExpiresAt: - return m.OldPasswordResetExpiresAt(ctx) - case user.FieldCreatedAt: - return m.OldCreatedAt(ctx) - case user.FieldUpdatedAt: - return m.OldUpdatedAt(ctx) - } - return nil, fmt.Errorf("unknown User field %s", name) -} - -// SetField sets the value of a field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *UserMutation) SetField(name string, value ent.Value) error { - switch name { - case user.FieldEmail: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetEmail(v) - return nil - case user.FieldUsername: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUsername(v) - return nil - case user.FieldFirstName: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetFirstName(v) - return nil - case user.FieldLastName: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetLastName(v) - return nil - case user.FieldPasswordHash: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetPasswordHash(v) - return nil - case user.FieldVerified: - v, ok := value.(bool) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetVerified(v) - return nil - case user.FieldEmailVerificationToken: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetEmailVerificationToken(v) - return nil - case user.FieldPasswordResetToken: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetPasswordResetToken(v) - return nil - case user.FieldPasswordResetExpiresAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetPasswordResetExpiresAt(v) - return nil - case user.FieldCreatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetCreatedAt(v) - return nil - case user.FieldUpdatedAt: - v, ok := value.(time.Time) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUpdatedAt(v) - return nil - } - return fmt.Errorf("unknown User field %s", name) -} - -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *UserMutation) AddedFields() []string { - return nil -} - -// AddedField returns the numeric value that was incremented/decremented on a field -// with the given name. The second boolean return value indicates that this field -// was not set, or was not defined in the schema. -func (m *UserMutation) AddedField(name string) (ent.Value, bool) { - return nil, false -} - -// AddField adds the value to the field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *UserMutation) AddField(name string, value ent.Value) error { - switch name { - } - return fmt.Errorf("unknown User numeric field %s", name) -} - -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *UserMutation) ClearedFields() []string { - var fields []string - if m.FieldCleared(user.FieldUsername) { - fields = append(fields, user.FieldUsername) - } - if m.FieldCleared(user.FieldFirstName) { - fields = append(fields, user.FieldFirstName) - } - if m.FieldCleared(user.FieldLastName) { - fields = append(fields, user.FieldLastName) - } - if m.FieldCleared(user.FieldEmailVerificationToken) { - fields = append(fields, user.FieldEmailVerificationToken) - } - if m.FieldCleared(user.FieldPasswordResetToken) { - fields = append(fields, user.FieldPasswordResetToken) - } - if m.FieldCleared(user.FieldPasswordResetExpiresAt) { - fields = append(fields, user.FieldPasswordResetExpiresAt) - } - return fields -} - -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *UserMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok -} - -// ClearField clears the value of the field with the given name. It returns an -// error if the field is not defined in the schema. -func (m *UserMutation) ClearField(name string) error { - switch name { - case user.FieldUsername: - m.ClearUsername() - return nil - case user.FieldFirstName: - m.ClearFirstName() - return nil - case user.FieldLastName: - m.ClearLastName() - return nil - case user.FieldEmailVerificationToken: - m.ClearEmailVerificationToken() - return nil - case user.FieldPasswordResetToken: - m.ClearPasswordResetToken() - return nil - case user.FieldPasswordResetExpiresAt: - m.ClearPasswordResetExpiresAt() - return nil - } - return fmt.Errorf("unknown User nullable field %s", name) -} - -// ResetField resets all changes in the mutation for the field with the given name. -// It returns an error if the field is not defined in the schema. -func (m *UserMutation) ResetField(name string) error { - switch name { - case user.FieldEmail: - m.ResetEmail() - return nil - case user.FieldUsername: - m.ResetUsername() - return nil - case user.FieldFirstName: - m.ResetFirstName() - return nil - case user.FieldLastName: - m.ResetLastName() - return nil - case user.FieldPasswordHash: - m.ResetPasswordHash() - return nil - case user.FieldVerified: - m.ResetVerified() - return nil - case user.FieldEmailVerificationToken: - m.ResetEmailVerificationToken() - return nil - case user.FieldPasswordResetToken: - m.ResetPasswordResetToken() - return nil - case user.FieldPasswordResetExpiresAt: - m.ResetPasswordResetExpiresAt() - return nil - case user.FieldCreatedAt: - m.ResetCreatedAt() - return nil - case user.FieldUpdatedAt: - m.ResetUpdatedAt() - return nil - } - return fmt.Errorf("unknown User field %s", name) -} - -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *UserMutation) AddedEdges() []string { - edges := make([]string, 0, 1) - if m.user_roles != nil { - edges = append(edges, user.EdgeUserRoles) - } - return edges -} - -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *UserMutation) AddedIDs(name string) []ent.Value { - switch name { - case user.EdgeUserRoles: - ids := make([]ent.Value, 0, len(m.user_roles)) - for id := range m.user_roles { - ids = append(ids, id) - } - return ids - } - return nil -} - -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *UserMutation) RemovedEdges() []string { - edges := make([]string, 0, 1) - if m.removeduser_roles != nil { - edges = append(edges, user.EdgeUserRoles) - } - return edges -} - -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *UserMutation) RemovedIDs(name string) []ent.Value { - switch name { - case user.EdgeUserRoles: - ids := make([]ent.Value, 0, len(m.removeduser_roles)) - for id := range m.removeduser_roles { - ids = append(ids, id) - } - return ids - } - return nil -} - -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *UserMutation) ClearedEdges() []string { - edges := make([]string, 0, 1) - if m.cleareduser_roles { - edges = append(edges, user.EdgeUserRoles) - } - return edges -} - -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *UserMutation) EdgeCleared(name string) bool { - switch name { - case user.EdgeUserRoles: - return m.cleareduser_roles - } - return false -} - -// ClearEdge clears the value of the edge with the given name. It returns an error -// if that edge is not defined in the schema. -func (m *UserMutation) ClearEdge(name string) error { - switch name { - } - return fmt.Errorf("unknown User unique edge %s", name) -} - -// ResetEdge resets all changes to the edge with the given name in this mutation. -// It returns an error if the edge is not defined in the schema. -func (m *UserMutation) ResetEdge(name string) error { - switch name { - case user.EdgeUserRoles: - m.ResetUserRoles() - return nil - } - return fmt.Errorf("unknown User edge %s", name) -} - -// UserRoleMutation represents an operation that mutates the UserRole nodes in the graph. -type UserRoleMutation struct { - config - op Op - typ string - id *int - clearedFields map[string]struct{} - user *string - cleareduser bool - role *string - clearedrole bool - done bool - oldValue func(context.Context) (*UserRole, error) - predicates []predicate.UserRole -} - -var _ ent.Mutation = (*UserRoleMutation)(nil) - -// userroleOption allows management of the mutation configuration using functional options. -type userroleOption func(*UserRoleMutation) - -// newUserRoleMutation creates new mutation for the UserRole entity. -func newUserRoleMutation(c config, op Op, opts ...userroleOption) *UserRoleMutation { - m := &UserRoleMutation{ - config: c, - op: op, - typ: TypeUserRole, - clearedFields: make(map[string]struct{}), - } - for _, opt := range opts { - opt(m) - } - return m -} - -// withUserRoleID sets the ID field of the mutation. -func withUserRoleID(id int) userroleOption { - return func(m *UserRoleMutation) { - var ( - err error - once sync.Once - value *UserRole - ) - m.oldValue = func(ctx context.Context) (*UserRole, error) { - once.Do(func() { - if m.done { - err = errors.New("querying old values post mutation is not allowed") - } else { - value, err = m.Client().UserRole.Get(ctx, id) - } - }) - return value, err - } - m.id = &id - } -} - -// withUserRole sets the old UserRole of the mutation. -func withUserRole(node *UserRole) userroleOption { - return func(m *UserRoleMutation) { - m.oldValue = func(context.Context) (*UserRole, error) { - return node, nil - } - m.id = &node.ID - } -} - -// Client returns a new `ent.Client` from the mutation. If the mutation was -// executed in a transaction (ent.Tx), a transactional client is returned. -func (m UserRoleMutation) Client() *Client { - client := &Client{config: m.config} - client.init() - return client -} - -// Tx returns an `ent.Tx` for mutations that were executed in transactions; -// it returns an error otherwise. -func (m UserRoleMutation) Tx() (*Tx, error) { - if _, ok := m.driver.(*txDriver); !ok { - return nil, errors.New("ent: mutation is not running in a transaction") - } - tx := &Tx{config: m.config} - tx.init() - return tx, nil -} - -// ID returns the ID value in the mutation. Note that the ID is only available -// if it was provided to the builder or after it was returned from the database. -func (m *UserRoleMutation) ID() (id int, exists bool) { - if m.id == nil { - return - } - return *m.id, true -} - -// IDs queries the database and returns the entity ids that match the mutation's predicate. -// That means, if the mutation is applied within a transaction with an isolation level such -// as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated -// or updated by the mutation. -func (m *UserRoleMutation) IDs(ctx context.Context) ([]int, error) { - switch { - case m.op.Is(OpUpdateOne | OpDeleteOne): - id, exists := m.ID() - if exists { - return []int{id}, nil - } - fallthrough - case m.op.Is(OpUpdate | OpDelete): - return m.Client().UserRole.Query().Where(m.predicates...).IDs(ctx) - default: - return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) - } -} - -// SetUserID sets the "user_id" field. -func (m *UserRoleMutation) SetUserID(s string) { - m.user = &s -} - -// UserID returns the value of the "user_id" field in the mutation. -func (m *UserRoleMutation) UserID() (r string, exists bool) { - v := m.user - if v == nil { - return - } - return *v, true -} - -// OldUserID returns the old "user_id" field's value of the UserRole entity. -// If the UserRole object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserRoleMutation) OldUserID(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldUserID is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldUserID requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldUserID: %w", err) - } - return oldValue.UserID, nil -} - -// ResetUserID resets all changes to the "user_id" field. -func (m *UserRoleMutation) ResetUserID() { - m.user = nil -} - -// SetRoleID sets the "role_id" field. -func (m *UserRoleMutation) SetRoleID(s string) { - m.role = &s -} - -// RoleID returns the value of the "role_id" field in the mutation. -func (m *UserRoleMutation) RoleID() (r string, exists bool) { - v := m.role - if v == nil { - return - } - return *v, true -} - -// OldRoleID returns the old "role_id" field's value of the UserRole entity. -// If the UserRole object wasn't provided to the builder, the object is fetched from the database. -// An error is returned if the mutation operation is not UpdateOne, or the database query fails. -func (m *UserRoleMutation) OldRoleID(ctx context.Context) (v string, err error) { - if !m.op.Is(OpUpdateOne) { - return v, errors.New("OldRoleID is only allowed on UpdateOne operations") - } - if m.id == nil || m.oldValue == nil { - return v, errors.New("OldRoleID requires an ID field in the mutation") - } - oldValue, err := m.oldValue(ctx) - if err != nil { - return v, fmt.Errorf("querying old value for OldRoleID: %w", err) - } - return oldValue.RoleID, nil -} - -// ResetRoleID resets all changes to the "role_id" field. -func (m *UserRoleMutation) ResetRoleID() { - m.role = nil -} - -// ClearUser clears the "user" edge to the User entity. -func (m *UserRoleMutation) ClearUser() { - m.cleareduser = true - m.clearedFields[userrole.FieldUserID] = struct{}{} -} - -// UserCleared reports if the "user" edge to the User entity was cleared. -func (m *UserRoleMutation) UserCleared() bool { - return m.cleareduser -} - -// UserIDs returns the "user" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// UserID instead. It exists only for internal usage by the builders. -func (m *UserRoleMutation) UserIDs() (ids []string) { - if id := m.user; id != nil { - ids = append(ids, *id) - } - return -} - -// ResetUser resets all changes to the "user" edge. -func (m *UserRoleMutation) ResetUser() { - m.user = nil - m.cleareduser = false -} - -// ClearRole clears the "role" edge to the Role entity. -func (m *UserRoleMutation) ClearRole() { - m.clearedrole = true - m.clearedFields[userrole.FieldRoleID] = struct{}{} -} - -// RoleCleared reports if the "role" edge to the Role entity was cleared. -func (m *UserRoleMutation) RoleCleared() bool { - return m.clearedrole -} - -// RoleIDs returns the "role" edge IDs in the mutation. -// Note that IDs always returns len(IDs) <= 1 for unique edges, and you should use -// RoleID instead. It exists only for internal usage by the builders. -func (m *UserRoleMutation) RoleIDs() (ids []string) { - if id := m.role; id != nil { - ids = append(ids, *id) - } - return -} - -// ResetRole resets all changes to the "role" edge. -func (m *UserRoleMutation) ResetRole() { - m.role = nil - m.clearedrole = false -} - -// Where appends a list predicates to the UserRoleMutation builder. -func (m *UserRoleMutation) Where(ps ...predicate.UserRole) { - m.predicates = append(m.predicates, ps...) -} - -// WhereP appends storage-level predicates to the UserRoleMutation builder. Using this method, -// users can use type-assertion to append predicates that do not depend on any generated package. -func (m *UserRoleMutation) WhereP(ps ...func(*sql.Selector)) { - p := make([]predicate.UserRole, len(ps)) - for i := range ps { - p[i] = ps[i] - } - m.Where(p...) -} - -// Op returns the operation name. -func (m *UserRoleMutation) Op() Op { - return m.op -} - -// SetOp allows setting the mutation operation. -func (m *UserRoleMutation) SetOp(op Op) { - m.op = op -} - -// Type returns the node type of this mutation (UserRole). -func (m *UserRoleMutation) Type() string { - return m.typ -} - -// Fields returns all fields that were changed during this mutation. Note that in -// order to get all numeric fields that were incremented/decremented, call -// AddedFields(). -func (m *UserRoleMutation) Fields() []string { - fields := make([]string, 0, 2) - if m.user != nil { - fields = append(fields, userrole.FieldUserID) - } - if m.role != nil { - fields = append(fields, userrole.FieldRoleID) - } - return fields -} - -// Field returns the value of a field with the given name. The second boolean -// return value indicates that this field was not set, or was not defined in the -// schema. -func (m *UserRoleMutation) Field(name string) (ent.Value, bool) { - switch name { - case userrole.FieldUserID: - return m.UserID() - case userrole.FieldRoleID: - return m.RoleID() - } - return nil, false -} - -// OldField returns the old value of the field from the database. An error is -// returned if the mutation operation is not UpdateOne, or the query to the -// database failed. -func (m *UserRoleMutation) OldField(ctx context.Context, name string) (ent.Value, error) { - switch name { - case userrole.FieldUserID: - return m.OldUserID(ctx) - case userrole.FieldRoleID: - return m.OldRoleID(ctx) - } - return nil, fmt.Errorf("unknown UserRole field %s", name) -} - -// SetField sets the value of a field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *UserRoleMutation) SetField(name string, value ent.Value) error { - switch name { - case userrole.FieldUserID: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetUserID(v) - return nil - case userrole.FieldRoleID: - v, ok := value.(string) - if !ok { - return fmt.Errorf("unexpected type %T for field %s", value, name) - } - m.SetRoleID(v) - return nil - } - return fmt.Errorf("unknown UserRole field %s", name) -} - -// AddedFields returns all numeric fields that were incremented/decremented during -// this mutation. -func (m *UserRoleMutation) AddedFields() []string { - return nil -} - -// AddedField returns the numeric value that was incremented/decremented on a field -// with the given name. The second boolean return value indicates that this field -// was not set, or was not defined in the schema. -func (m *UserRoleMutation) AddedField(name string) (ent.Value, bool) { - return nil, false -} - -// AddField adds the value to the field with the given name. It returns an error if -// the field is not defined in the schema, or if the type mismatched the field -// type. -func (m *UserRoleMutation) AddField(name string, value ent.Value) error { - switch name { - } - return fmt.Errorf("unknown UserRole numeric field %s", name) -} - -// ClearedFields returns all nullable fields that were cleared during this -// mutation. -func (m *UserRoleMutation) ClearedFields() []string { - return nil -} - -// FieldCleared returns a boolean indicating if a field with the given name was -// cleared in this mutation. -func (m *UserRoleMutation) FieldCleared(name string) bool { - _, ok := m.clearedFields[name] - return ok -} - -// ClearField clears the value of the field with the given name. It returns an -// error if the field is not defined in the schema. -func (m *UserRoleMutation) ClearField(name string) error { - return fmt.Errorf("unknown UserRole nullable field %s", name) -} - -// ResetField resets all changes in the mutation for the field with the given name. -// It returns an error if the field is not defined in the schema. -func (m *UserRoleMutation) ResetField(name string) error { - switch name { - case userrole.FieldUserID: - m.ResetUserID() - return nil - case userrole.FieldRoleID: - m.ResetRoleID() - return nil - } - return fmt.Errorf("unknown UserRole field %s", name) -} - -// AddedEdges returns all edge names that were set/added in this mutation. -func (m *UserRoleMutation) AddedEdges() []string { - edges := make([]string, 0, 2) - if m.user != nil { - edges = append(edges, userrole.EdgeUser) - } - if m.role != nil { - edges = append(edges, userrole.EdgeRole) - } - return edges -} - -// AddedIDs returns all IDs (to other nodes) that were added for the given edge -// name in this mutation. -func (m *UserRoleMutation) AddedIDs(name string) []ent.Value { - switch name { - case userrole.EdgeUser: - if id := m.user; id != nil { - return []ent.Value{*id} - } - case userrole.EdgeRole: - if id := m.role; id != nil { - return []ent.Value{*id} - } - } - return nil -} - -// RemovedEdges returns all edge names that were removed in this mutation. -func (m *UserRoleMutation) RemovedEdges() []string { - edges := make([]string, 0, 2) - return edges -} - -// RemovedIDs returns all IDs (to other nodes) that were removed for the edge with -// the given name in this mutation. -func (m *UserRoleMutation) RemovedIDs(name string) []ent.Value { - return nil -} - -// ClearedEdges returns all edge names that were cleared in this mutation. -func (m *UserRoleMutation) ClearedEdges() []string { - edges := make([]string, 0, 2) - if m.cleareduser { - edges = append(edges, userrole.EdgeUser) - } - if m.clearedrole { - edges = append(edges, userrole.EdgeRole) - } - return edges -} - -// EdgeCleared returns a boolean which indicates if the edge with the given name -// was cleared in this mutation. -func (m *UserRoleMutation) EdgeCleared(name string) bool { - switch name { - case userrole.EdgeUser: - return m.cleareduser - case userrole.EdgeRole: - return m.clearedrole - } - return false -} - -// ClearEdge clears the value of the edge with the given name. It returns an error -// if that edge is not defined in the schema. -func (m *UserRoleMutation) ClearEdge(name string) error { - switch name { - case userrole.EdgeUser: - m.ClearUser() - return nil - case userrole.EdgeRole: - m.ClearRole() - return nil - } - return fmt.Errorf("unknown UserRole unique edge %s", name) -} - -// ResetEdge resets all changes to the edge with the given name in this mutation. -// It returns an error if the edge is not defined in the schema. -func (m *UserRoleMutation) ResetEdge(name string) error { - switch name { - case userrole.EdgeUser: - m.ResetUser() - return nil - case userrole.EdgeRole: - m.ResetRole() - return nil - } - return fmt.Errorf("unknown UserRole edge %s", name) -} diff --git a/internal/ent/permission.go b/internal/ent/permission.go deleted file mode 100644 index aced3d0..0000000 --- a/internal/ent/permission.go +++ /dev/null @@ -1,127 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "fmt" - "strings" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "git.dcentral.systems/toolz/goplt/internal/ent/permission" -) - -// Permission is the model entity for the Permission schema. -type Permission struct { - config `json:"-"` - // ID of the ent. - ID string `json:"id,omitempty"` - // Format: module.resource.action - Name string `json:"name,omitempty"` - // Edges holds the relations/edges for other nodes in the graph. - // The values are being populated by the PermissionQuery when eager-loading is set. - Edges PermissionEdges `json:"edges"` - selectValues sql.SelectValues -} - -// PermissionEdges holds the relations/edges for other nodes in the graph. -type PermissionEdges struct { - // RolePermissions holds the value of the role_permissions edge. - RolePermissions []*RolePermission `json:"role_permissions,omitempty"` - // loadedTypes holds the information for reporting if a - // type was loaded (or requested) in eager-loading or not. - loadedTypes [1]bool -} - -// RolePermissionsOrErr returns the RolePermissions value or an error if the edge -// was not loaded in eager-loading. -func (e PermissionEdges) RolePermissionsOrErr() ([]*RolePermission, error) { - if e.loadedTypes[0] { - return e.RolePermissions, nil - } - return nil, &NotLoadedError{edge: "role_permissions"} -} - -// scanValues returns the types for scanning values from sql.Rows. -func (*Permission) scanValues(columns []string) ([]any, error) { - values := make([]any, len(columns)) - for i := range columns { - switch columns[i] { - case permission.FieldID, permission.FieldName: - values[i] = new(sql.NullString) - default: - values[i] = new(sql.UnknownType) - } - } - return values, nil -} - -// assignValues assigns the values that were returned from sql.Rows (after scanning) -// to the Permission fields. -func (_m *Permission) assignValues(columns []string, values []any) error { - if m, n := len(values), len(columns); m < n { - return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) - } - for i := range columns { - switch columns[i] { - case permission.FieldID: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field id", values[i]) - } else if value.Valid { - _m.ID = value.String - } - case permission.FieldName: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field name", values[i]) - } else if value.Valid { - _m.Name = value.String - } - default: - _m.selectValues.Set(columns[i], values[i]) - } - } - return nil -} - -// Value returns the ent.Value that was dynamically selected and assigned to the Permission. -// This includes values selected through modifiers, order, etc. -func (_m *Permission) Value(name string) (ent.Value, error) { - return _m.selectValues.Get(name) -} - -// QueryRolePermissions queries the "role_permissions" edge of the Permission entity. -func (_m *Permission) QueryRolePermissions() *RolePermissionQuery { - return NewPermissionClient(_m.config).QueryRolePermissions(_m) -} - -// Update returns a builder for updating this Permission. -// Note that you need to call Permission.Unwrap() before calling this method if this Permission -// was returned from a transaction, and the transaction was committed or rolled back. -func (_m *Permission) Update() *PermissionUpdateOne { - return NewPermissionClient(_m.config).UpdateOne(_m) -} - -// Unwrap unwraps the Permission entity that was returned from a transaction after it was closed, -// so that all future queries will be executed through the driver which created the transaction. -func (_m *Permission) Unwrap() *Permission { - _tx, ok := _m.config.driver.(*txDriver) - if !ok { - panic("ent: Permission is not a transactional entity") - } - _m.config.driver = _tx.drv - return _m -} - -// String implements the fmt.Stringer. -func (_m *Permission) String() string { - var builder strings.Builder - builder.WriteString("Permission(") - builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) - builder.WriteString("name=") - builder.WriteString(_m.Name) - builder.WriteByte(')') - return builder.String() -} - -// Permissions is a parsable slice of Permission. -type Permissions []*Permission diff --git a/internal/ent/permission/permission.go b/internal/ent/permission/permission.go deleted file mode 100644 index 2350fa4..0000000 --- a/internal/ent/permission/permission.go +++ /dev/null @@ -1,83 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package permission - -import ( - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" -) - -const ( - // Label holds the string label denoting the permission type in the database. - Label = "permission" - // FieldID holds the string denoting the id field in the database. - FieldID = "id" - // FieldName holds the string denoting the name field in the database. - FieldName = "name" - // EdgeRolePermissions holds the string denoting the role_permissions edge name in mutations. - EdgeRolePermissions = "role_permissions" - // Table holds the table name of the permission in the database. - Table = "permissions" - // RolePermissionsTable is the table that holds the role_permissions relation/edge. - RolePermissionsTable = "role_permissions" - // RolePermissionsInverseTable is the table name for the RolePermission entity. - // It exists in this package in order to avoid circular dependency with the "rolepermission" package. - RolePermissionsInverseTable = "role_permissions" - // RolePermissionsColumn is the table column denoting the role_permissions relation/edge. - RolePermissionsColumn = "permission_role_permissions" -) - -// Columns holds all SQL columns for permission fields. -var Columns = []string{ - FieldID, - FieldName, -} - -// ValidColumn reports if the column name is valid (part of the table columns). -func ValidColumn(column string) bool { - for i := range Columns { - if column == Columns[i] { - return true - } - } - return false -} - -var ( - // NameValidator is a validator for the "name" field. It is called by the builders before save. - NameValidator func(string) error -) - -// OrderOption defines the ordering options for the Permission queries. -type OrderOption func(*sql.Selector) - -// ByID orders the results by the id field. -func ByID(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldID, opts...).ToFunc() -} - -// ByName orders the results by the name field. -func ByName(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldName, opts...).ToFunc() -} - -// ByRolePermissionsCount orders the results by role_permissions count. -func ByRolePermissionsCount(opts ...sql.OrderTermOption) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborsCount(s, newRolePermissionsStep(), opts...) - } -} - -// ByRolePermissions orders the results by role_permissions terms. -func ByRolePermissions(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborTerms(s, newRolePermissionsStep(), append([]sql.OrderTerm{term}, terms...)...) - } -} -func newRolePermissionsStep() *sqlgraph.Step { - return sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(RolePermissionsInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, RolePermissionsTable, RolePermissionsColumn), - ) -} diff --git a/internal/ent/permission/where.go b/internal/ent/permission/where.go deleted file mode 100644 index 35d0594..0000000 --- a/internal/ent/permission/where.go +++ /dev/null @@ -1,172 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package permission - -import ( - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" -) - -// ID filters vertices based on their ID field. -func ID(id string) predicate.Permission { - return predicate.Permission(sql.FieldEQ(FieldID, id)) -} - -// IDEQ applies the EQ predicate on the ID field. -func IDEQ(id string) predicate.Permission { - return predicate.Permission(sql.FieldEQ(FieldID, id)) -} - -// IDNEQ applies the NEQ predicate on the ID field. -func IDNEQ(id string) predicate.Permission { - return predicate.Permission(sql.FieldNEQ(FieldID, id)) -} - -// IDIn applies the In predicate on the ID field. -func IDIn(ids ...string) predicate.Permission { - return predicate.Permission(sql.FieldIn(FieldID, ids...)) -} - -// IDNotIn applies the NotIn predicate on the ID field. -func IDNotIn(ids ...string) predicate.Permission { - return predicate.Permission(sql.FieldNotIn(FieldID, ids...)) -} - -// IDGT applies the GT predicate on the ID field. -func IDGT(id string) predicate.Permission { - return predicate.Permission(sql.FieldGT(FieldID, id)) -} - -// IDGTE applies the GTE predicate on the ID field. -func IDGTE(id string) predicate.Permission { - return predicate.Permission(sql.FieldGTE(FieldID, id)) -} - -// IDLT applies the LT predicate on the ID field. -func IDLT(id string) predicate.Permission { - return predicate.Permission(sql.FieldLT(FieldID, id)) -} - -// IDLTE applies the LTE predicate on the ID field. -func IDLTE(id string) predicate.Permission { - return predicate.Permission(sql.FieldLTE(FieldID, id)) -} - -// IDEqualFold applies the EqualFold predicate on the ID field. -func IDEqualFold(id string) predicate.Permission { - return predicate.Permission(sql.FieldEqualFold(FieldID, id)) -} - -// IDContainsFold applies the ContainsFold predicate on the ID field. -func IDContainsFold(id string) predicate.Permission { - return predicate.Permission(sql.FieldContainsFold(FieldID, id)) -} - -// Name applies equality check predicate on the "name" field. It's identical to NameEQ. -func Name(v string) predicate.Permission { - return predicate.Permission(sql.FieldEQ(FieldName, v)) -} - -// NameEQ applies the EQ predicate on the "name" field. -func NameEQ(v string) predicate.Permission { - return predicate.Permission(sql.FieldEQ(FieldName, v)) -} - -// NameNEQ applies the NEQ predicate on the "name" field. -func NameNEQ(v string) predicate.Permission { - return predicate.Permission(sql.FieldNEQ(FieldName, v)) -} - -// NameIn applies the In predicate on the "name" field. -func NameIn(vs ...string) predicate.Permission { - return predicate.Permission(sql.FieldIn(FieldName, vs...)) -} - -// NameNotIn applies the NotIn predicate on the "name" field. -func NameNotIn(vs ...string) predicate.Permission { - return predicate.Permission(sql.FieldNotIn(FieldName, vs...)) -} - -// NameGT applies the GT predicate on the "name" field. -func NameGT(v string) predicate.Permission { - return predicate.Permission(sql.FieldGT(FieldName, v)) -} - -// NameGTE applies the GTE predicate on the "name" field. -func NameGTE(v string) predicate.Permission { - return predicate.Permission(sql.FieldGTE(FieldName, v)) -} - -// NameLT applies the LT predicate on the "name" field. -func NameLT(v string) predicate.Permission { - return predicate.Permission(sql.FieldLT(FieldName, v)) -} - -// NameLTE applies the LTE predicate on the "name" field. -func NameLTE(v string) predicate.Permission { - return predicate.Permission(sql.FieldLTE(FieldName, v)) -} - -// NameContains applies the Contains predicate on the "name" field. -func NameContains(v string) predicate.Permission { - return predicate.Permission(sql.FieldContains(FieldName, v)) -} - -// NameHasPrefix applies the HasPrefix predicate on the "name" field. -func NameHasPrefix(v string) predicate.Permission { - return predicate.Permission(sql.FieldHasPrefix(FieldName, v)) -} - -// NameHasSuffix applies the HasSuffix predicate on the "name" field. -func NameHasSuffix(v string) predicate.Permission { - return predicate.Permission(sql.FieldHasSuffix(FieldName, v)) -} - -// NameEqualFold applies the EqualFold predicate on the "name" field. -func NameEqualFold(v string) predicate.Permission { - return predicate.Permission(sql.FieldEqualFold(FieldName, v)) -} - -// NameContainsFold applies the ContainsFold predicate on the "name" field. -func NameContainsFold(v string) predicate.Permission { - return predicate.Permission(sql.FieldContainsFold(FieldName, v)) -} - -// HasRolePermissions applies the HasEdge predicate on the "role_permissions" edge. -func HasRolePermissions() predicate.Permission { - return predicate.Permission(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, RolePermissionsTable, RolePermissionsColumn), - ) - sqlgraph.HasNeighbors(s, step) - }) -} - -// HasRolePermissionsWith applies the HasEdge predicate on the "role_permissions" edge with a given conditions (other predicates). -func HasRolePermissionsWith(preds ...predicate.RolePermission) predicate.Permission { - return predicate.Permission(func(s *sql.Selector) { - step := newRolePermissionsStep() - sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { - for _, p := range preds { - p(s) - } - }) - }) -} - -// And groups predicates with the AND operator between them. -func And(predicates ...predicate.Permission) predicate.Permission { - return predicate.Permission(sql.AndPredicates(predicates...)) -} - -// Or groups predicates with the OR operator between them. -func Or(predicates ...predicate.Permission) predicate.Permission { - return predicate.Permission(sql.OrPredicates(predicates...)) -} - -// Not applies the not operator on the given predicate. -func Not(p predicate.Permission) predicate.Permission { - return predicate.Permission(sql.NotPredicates(p)) -} diff --git a/internal/ent/permission_create.go b/internal/ent/permission_create.go deleted file mode 100644 index db05dc1..0000000 --- a/internal/ent/permission_create.go +++ /dev/null @@ -1,231 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "errors" - "fmt" - - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/internal/ent/permission" - "git.dcentral.systems/toolz/goplt/internal/ent/rolepermission" -) - -// PermissionCreate is the builder for creating a Permission entity. -type PermissionCreate struct { - config - mutation *PermissionMutation - hooks []Hook -} - -// SetName sets the "name" field. -func (_c *PermissionCreate) SetName(v string) *PermissionCreate { - _c.mutation.SetName(v) - return _c -} - -// SetID sets the "id" field. -func (_c *PermissionCreate) SetID(v string) *PermissionCreate { - _c.mutation.SetID(v) - return _c -} - -// AddRolePermissionIDs adds the "role_permissions" edge to the RolePermission entity by IDs. -func (_c *PermissionCreate) AddRolePermissionIDs(ids ...int) *PermissionCreate { - _c.mutation.AddRolePermissionIDs(ids...) - return _c -} - -// AddRolePermissions adds the "role_permissions" edges to the RolePermission entity. -func (_c *PermissionCreate) AddRolePermissions(v ...*RolePermission) *PermissionCreate { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _c.AddRolePermissionIDs(ids...) -} - -// Mutation returns the PermissionMutation object of the builder. -func (_c *PermissionCreate) Mutation() *PermissionMutation { - return _c.mutation -} - -// Save creates the Permission in the database. -func (_c *PermissionCreate) Save(ctx context.Context) (*Permission, error) { - return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) -} - -// SaveX calls Save and panics if Save returns an error. -func (_c *PermissionCreate) SaveX(ctx context.Context) *Permission { - v, err := _c.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (_c *PermissionCreate) Exec(ctx context.Context) error { - _, err := _c.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_c *PermissionCreate) ExecX(ctx context.Context) { - if err := _c.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (_c *PermissionCreate) check() error { - if _, ok := _c.mutation.Name(); !ok { - return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Permission.name"`)} - } - if v, ok := _c.mutation.Name(); ok { - if err := permission.NameValidator(v); err != nil { - return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Permission.name": %w`, err)} - } - } - return nil -} - -func (_c *PermissionCreate) sqlSave(ctx context.Context) (*Permission, error) { - if err := _c.check(); err != nil { - return nil, err - } - _node, _spec := _c.createSpec() - if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - if _spec.ID.Value != nil { - if id, ok := _spec.ID.Value.(string); ok { - _node.ID = id - } else { - return nil, fmt.Errorf("unexpected Permission.ID type: %T", _spec.ID.Value) - } - } - _c.mutation.id = &_node.ID - _c.mutation.done = true - return _node, nil -} - -func (_c *PermissionCreate) createSpec() (*Permission, *sqlgraph.CreateSpec) { - var ( - _node = &Permission{config: _c.config} - _spec = sqlgraph.NewCreateSpec(permission.Table, sqlgraph.NewFieldSpec(permission.FieldID, field.TypeString)) - ) - if id, ok := _c.mutation.ID(); ok { - _node.ID = id - _spec.ID.Value = id - } - if value, ok := _c.mutation.Name(); ok { - _spec.SetField(permission.FieldName, field.TypeString, value) - _node.Name = value - } - if nodes := _c.mutation.RolePermissionsIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: permission.RolePermissionsTable, - Columns: []string{permission.RolePermissionsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges = append(_spec.Edges, edge) - } - return _node, _spec -} - -// PermissionCreateBulk is the builder for creating many Permission entities in bulk. -type PermissionCreateBulk struct { - config - err error - builders []*PermissionCreate -} - -// Save creates the Permission entities in the database. -func (_c *PermissionCreateBulk) Save(ctx context.Context) ([]*Permission, error) { - if _c.err != nil { - return nil, _c.err - } - specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) - nodes := make([]*Permission, len(_c.builders)) - mutators := make([]Mutator, len(_c.builders)) - for i := range _c.builders { - func(i int, root context.Context) { - builder := _c.builders[i] - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*PermissionMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err := builder.check(); err != nil { - return nil, err - } - builder.mutation = mutation - var err error - nodes[i], specs[i] = builder.createSpec() - if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) - } else { - spec := &sqlgraph.BatchCreateSpec{Nodes: specs} - // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - } - } - if err != nil { - return nil, err - } - mutation.id = &nodes[i].ID - mutation.done = true - return nodes[i], nil - }) - for i := len(builder.hooks) - 1; i >= 0; i-- { - mut = builder.hooks[i](mut) - } - mutators[i] = mut - }(i, ctx) - } - if len(mutators) > 0 { - if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { - return nil, err - } - } - return nodes, nil -} - -// SaveX is like Save, but panics if an error occurs. -func (_c *PermissionCreateBulk) SaveX(ctx context.Context) []*Permission { - v, err := _c.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (_c *PermissionCreateBulk) Exec(ctx context.Context) error { - _, err := _c.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_c *PermissionCreateBulk) ExecX(ctx context.Context) { - if err := _c.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/internal/ent/permission_delete.go b/internal/ent/permission_delete.go deleted file mode 100644 index efb3360..0000000 --- a/internal/ent/permission_delete.go +++ /dev/null @@ -1,88 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/internal/ent/permission" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" -) - -// PermissionDelete is the builder for deleting a Permission entity. -type PermissionDelete struct { - config - hooks []Hook - mutation *PermissionMutation -} - -// Where appends a list predicates to the PermissionDelete builder. -func (_d *PermissionDelete) Where(ps ...predicate.Permission) *PermissionDelete { - _d.mutation.Where(ps...) - return _d -} - -// Exec executes the deletion query and returns how many vertices were deleted. -func (_d *PermissionDelete) Exec(ctx context.Context) (int, error) { - return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) -} - -// ExecX is like Exec, but panics if an error occurs. -func (_d *PermissionDelete) ExecX(ctx context.Context) int { - n, err := _d.Exec(ctx) - if err != nil { - panic(err) - } - return n -} - -func (_d *PermissionDelete) sqlExec(ctx context.Context) (int, error) { - _spec := sqlgraph.NewDeleteSpec(permission.Table, sqlgraph.NewFieldSpec(permission.FieldID, field.TypeString)) - if ps := _d.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) - if err != nil && sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - _d.mutation.done = true - return affected, err -} - -// PermissionDeleteOne is the builder for deleting a single Permission entity. -type PermissionDeleteOne struct { - _d *PermissionDelete -} - -// Where appends a list predicates to the PermissionDelete builder. -func (_d *PermissionDeleteOne) Where(ps ...predicate.Permission) *PermissionDeleteOne { - _d._d.mutation.Where(ps...) - return _d -} - -// Exec executes the deletion query. -func (_d *PermissionDeleteOne) Exec(ctx context.Context) error { - n, err := _d._d.Exec(ctx) - switch { - case err != nil: - return err - case n == 0: - return &NotFoundError{permission.Label} - default: - return nil - } -} - -// ExecX is like Exec, but panics if an error occurs. -func (_d *PermissionDeleteOne) ExecX(ctx context.Context) { - if err := _d.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/internal/ent/permission_query.go b/internal/ent/permission_query.go deleted file mode 100644 index 8e13ee1..0000000 --- a/internal/ent/permission_query.go +++ /dev/null @@ -1,607 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "database/sql/driver" - "fmt" - "math" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/internal/ent/permission" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" - "git.dcentral.systems/toolz/goplt/internal/ent/rolepermission" -) - -// PermissionQuery is the builder for querying Permission entities. -type PermissionQuery struct { - config - ctx *QueryContext - order []permission.OrderOption - inters []Interceptor - predicates []predicate.Permission - withRolePermissions *RolePermissionQuery - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Where adds a new predicate for the PermissionQuery builder. -func (_q *PermissionQuery) Where(ps ...predicate.Permission) *PermissionQuery { - _q.predicates = append(_q.predicates, ps...) - return _q -} - -// Limit the number of records to be returned by this query. -func (_q *PermissionQuery) Limit(limit int) *PermissionQuery { - _q.ctx.Limit = &limit - return _q -} - -// Offset to start from. -func (_q *PermissionQuery) Offset(offset int) *PermissionQuery { - _q.ctx.Offset = &offset - return _q -} - -// Unique configures the query builder to filter duplicate records on query. -// By default, unique is set to true, and can be disabled using this method. -func (_q *PermissionQuery) Unique(unique bool) *PermissionQuery { - _q.ctx.Unique = &unique - return _q -} - -// Order specifies how the records should be ordered. -func (_q *PermissionQuery) Order(o ...permission.OrderOption) *PermissionQuery { - _q.order = append(_q.order, o...) - return _q -} - -// QueryRolePermissions chains the current query on the "role_permissions" edge. -func (_q *PermissionQuery) QueryRolePermissions() *RolePermissionQuery { - query := (&RolePermissionClient{config: _q.config}).Query() - query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { - if err := _q.prepareQuery(ctx); err != nil { - return nil, err - } - selector := _q.sqlQuery(ctx) - if err := selector.Err(); err != nil { - return nil, err - } - step := sqlgraph.NewStep( - sqlgraph.From(permission.Table, permission.FieldID, selector), - sqlgraph.To(rolepermission.Table, rolepermission.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, permission.RolePermissionsTable, permission.RolePermissionsColumn), - ) - fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) - return fromU, nil - } - return query -} - -// First returns the first Permission entity from the query. -// Returns a *NotFoundError when no Permission was found. -func (_q *PermissionQuery) First(ctx context.Context) (*Permission, error) { - nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{permission.Label} - } - return nodes[0], nil -} - -// FirstX is like First, but panics if an error occurs. -func (_q *PermissionQuery) FirstX(ctx context.Context) *Permission { - node, err := _q.First(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// FirstID returns the first Permission ID from the query. -// Returns a *NotFoundError when no Permission ID was found. -func (_q *PermissionQuery) FirstID(ctx context.Context) (id string, err error) { - var ids []string - if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{permission.Label} - return - } - return ids[0], nil -} - -// FirstIDX is like FirstID, but panics if an error occurs. -func (_q *PermissionQuery) FirstIDX(ctx context.Context) string { - id, err := _q.FirstID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Only returns a single Permission entity found by the query, ensuring it only returns one. -// Returns a *NotSingularError when more than one Permission entity is found. -// Returns a *NotFoundError when no Permission entities are found. -func (_q *PermissionQuery) Only(ctx context.Context) (*Permission, error) { - nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) - if err != nil { - return nil, err - } - switch len(nodes) { - case 1: - return nodes[0], nil - case 0: - return nil, &NotFoundError{permission.Label} - default: - return nil, &NotSingularError{permission.Label} - } -} - -// OnlyX is like Only, but panics if an error occurs. -func (_q *PermissionQuery) OnlyX(ctx context.Context) *Permission { - node, err := _q.Only(ctx) - if err != nil { - panic(err) - } - return node -} - -// OnlyID is like Only, but returns the only Permission ID in the query. -// Returns a *NotSingularError when more than one Permission ID is found. -// Returns a *NotFoundError when no entities are found. -func (_q *PermissionQuery) OnlyID(ctx context.Context) (id string, err error) { - var ids []string - if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { - return - } - switch len(ids) { - case 1: - id = ids[0] - case 0: - err = &NotFoundError{permission.Label} - default: - err = &NotSingularError{permission.Label} - } - return -} - -// OnlyIDX is like OnlyID, but panics if an error occurs. -func (_q *PermissionQuery) OnlyIDX(ctx context.Context) string { - id, err := _q.OnlyID(ctx) - if err != nil { - panic(err) - } - return id -} - -// All executes the query and returns a list of Permissions. -func (_q *PermissionQuery) All(ctx context.Context) ([]*Permission, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) - if err := _q.prepareQuery(ctx); err != nil { - return nil, err - } - qr := querierAll[[]*Permission, *PermissionQuery]() - return withInterceptors[[]*Permission](ctx, _q, qr, _q.inters) -} - -// AllX is like All, but panics if an error occurs. -func (_q *PermissionQuery) AllX(ctx context.Context) []*Permission { - nodes, err := _q.All(ctx) - if err != nil { - panic(err) - } - return nodes -} - -// IDs executes the query and returns a list of Permission IDs. -func (_q *PermissionQuery) IDs(ctx context.Context) (ids []string, err error) { - if _q.ctx.Unique == nil && _q.path != nil { - _q.Unique(true) - } - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) - if err = _q.Select(permission.FieldID).Scan(ctx, &ids); err != nil { - return nil, err - } - return ids, nil -} - -// IDsX is like IDs, but panics if an error occurs. -func (_q *PermissionQuery) IDsX(ctx context.Context) []string { - ids, err := _q.IDs(ctx) - if err != nil { - panic(err) - } - return ids -} - -// Count returns the count of the given query. -func (_q *PermissionQuery) Count(ctx context.Context) (int, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) - if err := _q.prepareQuery(ctx); err != nil { - return 0, err - } - return withInterceptors[int](ctx, _q, querierCount[*PermissionQuery](), _q.inters) -} - -// CountX is like Count, but panics if an error occurs. -func (_q *PermissionQuery) CountX(ctx context.Context) int { - count, err := _q.Count(ctx) - if err != nil { - panic(err) - } - return count -} - -// Exist returns true if the query has elements in the graph. -func (_q *PermissionQuery) Exist(ctx context.Context) (bool, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) - switch _, err := _q.FirstID(ctx); { - case IsNotFound(err): - return false, nil - case err != nil: - return false, fmt.Errorf("ent: check existence: %w", err) - default: - return true, nil - } -} - -// ExistX is like Exist, but panics if an error occurs. -func (_q *PermissionQuery) ExistX(ctx context.Context) bool { - exist, err := _q.Exist(ctx) - if err != nil { - panic(err) - } - return exist -} - -// Clone returns a duplicate of the PermissionQuery builder, including all associated steps. It can be -// used to prepare common query builders and use them differently after the clone is made. -func (_q *PermissionQuery) Clone() *PermissionQuery { - if _q == nil { - return nil - } - return &PermissionQuery{ - config: _q.config, - ctx: _q.ctx.Clone(), - order: append([]permission.OrderOption{}, _q.order...), - inters: append([]Interceptor{}, _q.inters...), - predicates: append([]predicate.Permission{}, _q.predicates...), - withRolePermissions: _q.withRolePermissions.Clone(), - // clone intermediate query. - sql: _q.sql.Clone(), - path: _q.path, - } -} - -// WithRolePermissions tells the query-builder to eager-load the nodes that are connected to -// the "role_permissions" edge. The optional arguments are used to configure the query builder of the edge. -func (_q *PermissionQuery) WithRolePermissions(opts ...func(*RolePermissionQuery)) *PermissionQuery { - query := (&RolePermissionClient{config: _q.config}).Query() - for _, opt := range opts { - opt(query) - } - _q.withRolePermissions = query - return _q -} - -// GroupBy is used to group vertices by one or more fields/columns. -// It is often used with aggregate functions, like: count, max, mean, min, sum. -// -// Example: -// -// var v []struct { -// Name string `json:"name,omitempty"` -// Count int `json:"count,omitempty"` -// } -// -// client.Permission.Query(). -// GroupBy(permission.FieldName). -// Aggregate(ent.Count()). -// Scan(ctx, &v) -func (_q *PermissionQuery) GroupBy(field string, fields ...string) *PermissionGroupBy { - _q.ctx.Fields = append([]string{field}, fields...) - grbuild := &PermissionGroupBy{build: _q} - grbuild.flds = &_q.ctx.Fields - grbuild.label = permission.Label - grbuild.scan = grbuild.Scan - return grbuild -} - -// Select allows the selection one or more fields/columns for the given query, -// instead of selecting all fields in the entity. -// -// Example: -// -// var v []struct { -// Name string `json:"name,omitempty"` -// } -// -// client.Permission.Query(). -// Select(permission.FieldName). -// Scan(ctx, &v) -func (_q *PermissionQuery) Select(fields ...string) *PermissionSelect { - _q.ctx.Fields = append(_q.ctx.Fields, fields...) - sbuild := &PermissionSelect{PermissionQuery: _q} - sbuild.label = permission.Label - sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan - return sbuild -} - -// Aggregate returns a PermissionSelect configured with the given aggregations. -func (_q *PermissionQuery) Aggregate(fns ...AggregateFunc) *PermissionSelect { - return _q.Select().Aggregate(fns...) -} - -func (_q *PermissionQuery) prepareQuery(ctx context.Context) error { - for _, inter := range _q.inters { - if inter == nil { - return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") - } - if trv, ok := inter.(Traverser); ok { - if err := trv.Traverse(ctx, _q); err != nil { - return err - } - } - } - for _, f := range _q.ctx.Fields { - if !permission.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} - } - } - if _q.path != nil { - prev, err := _q.path(ctx) - if err != nil { - return err - } - _q.sql = prev - } - return nil -} - -func (_q *PermissionQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Permission, error) { - var ( - nodes = []*Permission{} - _spec = _q.querySpec() - loadedTypes = [1]bool{ - _q.withRolePermissions != nil, - } - ) - _spec.ScanValues = func(columns []string) ([]any, error) { - return (*Permission).scanValues(nil, columns) - } - _spec.Assign = func(columns []string, values []any) error { - node := &Permission{config: _q.config} - nodes = append(nodes, node) - node.Edges.loadedTypes = loadedTypes - return node.assignValues(columns, values) - } - for i := range hooks { - hooks[i](ctx, _spec) - } - if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { - return nil, err - } - if len(nodes) == 0 { - return nodes, nil - } - if query := _q.withRolePermissions; query != nil { - if err := _q.loadRolePermissions(ctx, query, nodes, - func(n *Permission) { n.Edges.RolePermissions = []*RolePermission{} }, - func(n *Permission, e *RolePermission) { n.Edges.RolePermissions = append(n.Edges.RolePermissions, e) }); err != nil { - return nil, err - } - } - return nodes, nil -} - -func (_q *PermissionQuery) loadRolePermissions(ctx context.Context, query *RolePermissionQuery, nodes []*Permission, init func(*Permission), assign func(*Permission, *RolePermission)) error { - fks := make([]driver.Value, 0, len(nodes)) - nodeids := make(map[string]*Permission) - for i := range nodes { - fks = append(fks, nodes[i].ID) - nodeids[nodes[i].ID] = nodes[i] - if init != nil { - init(nodes[i]) - } - } - query.withFKs = true - query.Where(predicate.RolePermission(func(s *sql.Selector) { - s.Where(sql.InValues(s.C(permission.RolePermissionsColumn), fks...)) - })) - neighbors, err := query.All(ctx) - if err != nil { - return err - } - for _, n := range neighbors { - fk := n.permission_role_permissions - if fk == nil { - return fmt.Errorf(`foreign-key "permission_role_permissions" is nil for node %v`, n.ID) - } - node, ok := nodeids[*fk] - if !ok { - return fmt.Errorf(`unexpected referenced foreign-key "permission_role_permissions" returned %v for node %v`, *fk, n.ID) - } - assign(node, n) - } - return nil -} - -func (_q *PermissionQuery) sqlCount(ctx context.Context) (int, error) { - _spec := _q.querySpec() - _spec.Node.Columns = _q.ctx.Fields - if len(_q.ctx.Fields) > 0 { - _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique - } - return sqlgraph.CountNodes(ctx, _q.driver, _spec) -} - -func (_q *PermissionQuery) querySpec() *sqlgraph.QuerySpec { - _spec := sqlgraph.NewQuerySpec(permission.Table, permission.Columns, sqlgraph.NewFieldSpec(permission.FieldID, field.TypeString)) - _spec.From = _q.sql - if unique := _q.ctx.Unique; unique != nil { - _spec.Unique = *unique - } else if _q.path != nil { - _spec.Unique = true - } - if fields := _q.ctx.Fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, permission.FieldID) - for i := range fields { - if fields[i] != permission.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) - } - } - } - if ps := _q.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if limit := _q.ctx.Limit; limit != nil { - _spec.Limit = *limit - } - if offset := _q.ctx.Offset; offset != nil { - _spec.Offset = *offset - } - if ps := _q.order; len(ps) > 0 { - _spec.Order = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return _spec -} - -func (_q *PermissionQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(_q.driver.Dialect()) - t1 := builder.Table(permission.Table) - columns := _q.ctx.Fields - if len(columns) == 0 { - columns = permission.Columns - } - selector := builder.Select(t1.Columns(columns...)...).From(t1) - if _q.sql != nil { - selector = _q.sql - selector.Select(selector.Columns(columns...)...) - } - if _q.ctx.Unique != nil && *_q.ctx.Unique { - selector.Distinct() - } - for _, p := range _q.predicates { - p(selector) - } - for _, p := range _q.order { - p(selector) - } - if offset := _q.ctx.Offset; offset != nil { - // limit is mandatory for offset clause. We start - // with default value, and override it below if needed. - selector.Offset(*offset).Limit(math.MaxInt32) - } - if limit := _q.ctx.Limit; limit != nil { - selector.Limit(*limit) - } - return selector -} - -// PermissionGroupBy is the group-by builder for Permission entities. -type PermissionGroupBy struct { - selector - build *PermissionQuery -} - -// Aggregate adds the given aggregation functions to the group-by query. -func (_g *PermissionGroupBy) Aggregate(fns ...AggregateFunc) *PermissionGroupBy { - _g.fns = append(_g.fns, fns...) - return _g -} - -// Scan applies the selector query and scans the result into the given value. -func (_g *PermissionGroupBy) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) - if err := _g.build.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*PermissionQuery, *PermissionGroupBy](ctx, _g.build, _g, _g.build.inters, v) -} - -func (_g *PermissionGroupBy) sqlScan(ctx context.Context, root *PermissionQuery, v any) error { - selector := root.sqlQuery(ctx).Select() - aggregation := make([]string, 0, len(_g.fns)) - for _, fn := range _g.fns { - aggregation = append(aggregation, fn(selector)) - } - if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) - for _, f := range *_g.flds { - columns = append(columns, selector.C(f)) - } - columns = append(columns, aggregation...) - selector.Select(columns...) - } - selector.GroupBy(selector.Columns(*_g.flds...)...) - if err := selector.Err(); err != nil { - return err - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} - -// PermissionSelect is the builder for selecting fields of Permission entities. -type PermissionSelect struct { - *PermissionQuery - selector -} - -// Aggregate adds the given aggregation functions to the selector query. -func (_s *PermissionSelect) Aggregate(fns ...AggregateFunc) *PermissionSelect { - _s.fns = append(_s.fns, fns...) - return _s -} - -// Scan applies the selector query and scans the result into the given value. -func (_s *PermissionSelect) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) - if err := _s.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*PermissionQuery, *PermissionSelect](ctx, _s.PermissionQuery, _s, _s.inters, v) -} - -func (_s *PermissionSelect) sqlScan(ctx context.Context, root *PermissionQuery, v any) error { - selector := root.sqlQuery(ctx) - aggregation := make([]string, 0, len(_s.fns)) - for _, fn := range _s.fns { - aggregation = append(aggregation, fn(selector)) - } - switch n := len(*_s.selector.flds); { - case n == 0 && len(aggregation) > 0: - selector.Select(aggregation...) - case n != 0 && len(aggregation) > 0: - selector.AppendSelect(aggregation...) - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := _s.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} diff --git a/internal/ent/permission_update.go b/internal/ent/permission_update.go deleted file mode 100644 index b61d452..0000000 --- a/internal/ent/permission_update.go +++ /dev/null @@ -1,398 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "errors" - "fmt" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/internal/ent/permission" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" - "git.dcentral.systems/toolz/goplt/internal/ent/rolepermission" -) - -// PermissionUpdate is the builder for updating Permission entities. -type PermissionUpdate struct { - config - hooks []Hook - mutation *PermissionMutation -} - -// Where appends a list predicates to the PermissionUpdate builder. -func (_u *PermissionUpdate) Where(ps ...predicate.Permission) *PermissionUpdate { - _u.mutation.Where(ps...) - return _u -} - -// SetName sets the "name" field. -func (_u *PermissionUpdate) SetName(v string) *PermissionUpdate { - _u.mutation.SetName(v) - return _u -} - -// SetNillableName sets the "name" field if the given value is not nil. -func (_u *PermissionUpdate) SetNillableName(v *string) *PermissionUpdate { - if v != nil { - _u.SetName(*v) - } - return _u -} - -// AddRolePermissionIDs adds the "role_permissions" edge to the RolePermission entity by IDs. -func (_u *PermissionUpdate) AddRolePermissionIDs(ids ...int) *PermissionUpdate { - _u.mutation.AddRolePermissionIDs(ids...) - return _u -} - -// AddRolePermissions adds the "role_permissions" edges to the RolePermission entity. -func (_u *PermissionUpdate) AddRolePermissions(v ...*RolePermission) *PermissionUpdate { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.AddRolePermissionIDs(ids...) -} - -// Mutation returns the PermissionMutation object of the builder. -func (_u *PermissionUpdate) Mutation() *PermissionMutation { - return _u.mutation -} - -// ClearRolePermissions clears all "role_permissions" edges to the RolePermission entity. -func (_u *PermissionUpdate) ClearRolePermissions() *PermissionUpdate { - _u.mutation.ClearRolePermissions() - return _u -} - -// RemoveRolePermissionIDs removes the "role_permissions" edge to RolePermission entities by IDs. -func (_u *PermissionUpdate) RemoveRolePermissionIDs(ids ...int) *PermissionUpdate { - _u.mutation.RemoveRolePermissionIDs(ids...) - return _u -} - -// RemoveRolePermissions removes "role_permissions" edges to RolePermission entities. -func (_u *PermissionUpdate) RemoveRolePermissions(v ...*RolePermission) *PermissionUpdate { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.RemoveRolePermissionIDs(ids...) -} - -// Save executes the query and returns the number of nodes affected by the update operation. -func (_u *PermissionUpdate) Save(ctx context.Context) (int, error) { - return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (_u *PermissionUpdate) SaveX(ctx context.Context) int { - affected, err := _u.Save(ctx) - if err != nil { - panic(err) - } - return affected -} - -// Exec executes the query. -func (_u *PermissionUpdate) Exec(ctx context.Context) error { - _, err := _u.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_u *PermissionUpdate) ExecX(ctx context.Context) { - if err := _u.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (_u *PermissionUpdate) check() error { - if v, ok := _u.mutation.Name(); ok { - if err := permission.NameValidator(v); err != nil { - return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Permission.name": %w`, err)} - } - } - return nil -} - -func (_u *PermissionUpdate) sqlSave(ctx context.Context) (_node int, err error) { - if err := _u.check(); err != nil { - return _node, err - } - _spec := sqlgraph.NewUpdateSpec(permission.Table, permission.Columns, sqlgraph.NewFieldSpec(permission.FieldID, field.TypeString)) - if ps := _u.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := _u.mutation.Name(); ok { - _spec.SetField(permission.FieldName, field.TypeString, value) - } - if _u.mutation.RolePermissionsCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: permission.RolePermissionsTable, - Columns: []string{permission.RolePermissionsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.RemovedRolePermissionsIDs(); len(nodes) > 0 && !_u.mutation.RolePermissionsCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: permission.RolePermissionsTable, - Columns: []string{permission.RolePermissionsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.RolePermissionsIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: permission.RolePermissionsTable, - Columns: []string{permission.RolePermissionsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{permission.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return 0, err - } - _u.mutation.done = true - return _node, nil -} - -// PermissionUpdateOne is the builder for updating a single Permission entity. -type PermissionUpdateOne struct { - config - fields []string - hooks []Hook - mutation *PermissionMutation -} - -// SetName sets the "name" field. -func (_u *PermissionUpdateOne) SetName(v string) *PermissionUpdateOne { - _u.mutation.SetName(v) - return _u -} - -// SetNillableName sets the "name" field if the given value is not nil. -func (_u *PermissionUpdateOne) SetNillableName(v *string) *PermissionUpdateOne { - if v != nil { - _u.SetName(*v) - } - return _u -} - -// AddRolePermissionIDs adds the "role_permissions" edge to the RolePermission entity by IDs. -func (_u *PermissionUpdateOne) AddRolePermissionIDs(ids ...int) *PermissionUpdateOne { - _u.mutation.AddRolePermissionIDs(ids...) - return _u -} - -// AddRolePermissions adds the "role_permissions" edges to the RolePermission entity. -func (_u *PermissionUpdateOne) AddRolePermissions(v ...*RolePermission) *PermissionUpdateOne { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.AddRolePermissionIDs(ids...) -} - -// Mutation returns the PermissionMutation object of the builder. -func (_u *PermissionUpdateOne) Mutation() *PermissionMutation { - return _u.mutation -} - -// ClearRolePermissions clears all "role_permissions" edges to the RolePermission entity. -func (_u *PermissionUpdateOne) ClearRolePermissions() *PermissionUpdateOne { - _u.mutation.ClearRolePermissions() - return _u -} - -// RemoveRolePermissionIDs removes the "role_permissions" edge to RolePermission entities by IDs. -func (_u *PermissionUpdateOne) RemoveRolePermissionIDs(ids ...int) *PermissionUpdateOne { - _u.mutation.RemoveRolePermissionIDs(ids...) - return _u -} - -// RemoveRolePermissions removes "role_permissions" edges to RolePermission entities. -func (_u *PermissionUpdateOne) RemoveRolePermissions(v ...*RolePermission) *PermissionUpdateOne { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.RemoveRolePermissionIDs(ids...) -} - -// Where appends a list predicates to the PermissionUpdate builder. -func (_u *PermissionUpdateOne) Where(ps ...predicate.Permission) *PermissionUpdateOne { - _u.mutation.Where(ps...) - return _u -} - -// Select allows selecting one or more fields (columns) of the returned entity. -// The default is selecting all fields defined in the entity schema. -func (_u *PermissionUpdateOne) Select(field string, fields ...string) *PermissionUpdateOne { - _u.fields = append([]string{field}, fields...) - return _u -} - -// Save executes the query and returns the updated Permission entity. -func (_u *PermissionUpdateOne) Save(ctx context.Context) (*Permission, error) { - return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (_u *PermissionUpdateOne) SaveX(ctx context.Context) *Permission { - node, err := _u.Save(ctx) - if err != nil { - panic(err) - } - return node -} - -// Exec executes the query on the entity. -func (_u *PermissionUpdateOne) Exec(ctx context.Context) error { - _, err := _u.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_u *PermissionUpdateOne) ExecX(ctx context.Context) { - if err := _u.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (_u *PermissionUpdateOne) check() error { - if v, ok := _u.mutation.Name(); ok { - if err := permission.NameValidator(v); err != nil { - return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Permission.name": %w`, err)} - } - } - return nil -} - -func (_u *PermissionUpdateOne) sqlSave(ctx context.Context) (_node *Permission, err error) { - if err := _u.check(); err != nil { - return _node, err - } - _spec := sqlgraph.NewUpdateSpec(permission.Table, permission.Columns, sqlgraph.NewFieldSpec(permission.FieldID, field.TypeString)) - id, ok := _u.mutation.ID() - if !ok { - return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Permission.id" for update`)} - } - _spec.Node.ID.Value = id - if fields := _u.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, permission.FieldID) - for _, f := range fields { - if !permission.ValidColumn(f) { - return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} - } - if f != permission.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, f) - } - } - } - if ps := _u.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := _u.mutation.Name(); ok { - _spec.SetField(permission.FieldName, field.TypeString, value) - } - if _u.mutation.RolePermissionsCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: permission.RolePermissionsTable, - Columns: []string{permission.RolePermissionsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.RemovedRolePermissionsIDs(); len(nodes) > 0 && !_u.mutation.RolePermissionsCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: permission.RolePermissionsTable, - Columns: []string{permission.RolePermissionsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.RolePermissionsIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: permission.RolePermissionsTable, - Columns: []string{permission.RolePermissionsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - _node = &Permission{config: _u.config} - _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{permission.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - _u.mutation.done = true - return _node, nil -} diff --git a/internal/ent/predicate/predicate.go b/internal/ent/predicate/predicate.go deleted file mode 100644 index 51a5c9c..0000000 --- a/internal/ent/predicate/predicate.go +++ /dev/null @@ -1,28 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package predicate - -import ( - "entgo.io/ent/dialect/sql" -) - -// AuditLog is the predicate function for auditlog builders. -type AuditLog func(*sql.Selector) - -// Permission is the predicate function for permission builders. -type Permission func(*sql.Selector) - -// RefreshToken is the predicate function for refreshtoken builders. -type RefreshToken func(*sql.Selector) - -// Role is the predicate function for role builders. -type Role func(*sql.Selector) - -// RolePermission is the predicate function for rolepermission builders. -type RolePermission func(*sql.Selector) - -// User is the predicate function for user builders. -type User func(*sql.Selector) - -// UserRole is the predicate function for userrole builders. -type UserRole func(*sql.Selector) diff --git a/internal/ent/refreshtoken.go b/internal/ent/refreshtoken.go deleted file mode 100644 index 08b841d..0000000 --- a/internal/ent/refreshtoken.go +++ /dev/null @@ -1,136 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "fmt" - "strings" - "time" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "git.dcentral.systems/toolz/goplt/internal/ent/refreshtoken" -) - -// RefreshToken is the model entity for the RefreshToken schema. -type RefreshToken struct { - config `json:"-"` - // ID of the ent. - ID string `json:"id,omitempty"` - // ID of the user who owns this refresh token - UserID string `json:"user_id,omitempty"` - // SHA256 hash of the refresh token - TokenHash string `json:"-"` - // When the refresh token expires - ExpiresAt time.Time `json:"expires_at,omitempty"` - // CreatedAt holds the value of the "created_at" field. - CreatedAt time.Time `json:"created_at,omitempty"` - selectValues sql.SelectValues -} - -// scanValues returns the types for scanning values from sql.Rows. -func (*RefreshToken) scanValues(columns []string) ([]any, error) { - values := make([]any, len(columns)) - for i := range columns { - switch columns[i] { - case refreshtoken.FieldID, refreshtoken.FieldUserID, refreshtoken.FieldTokenHash: - values[i] = new(sql.NullString) - case refreshtoken.FieldExpiresAt, refreshtoken.FieldCreatedAt: - values[i] = new(sql.NullTime) - default: - values[i] = new(sql.UnknownType) - } - } - return values, nil -} - -// assignValues assigns the values that were returned from sql.Rows (after scanning) -// to the RefreshToken fields. -func (_m *RefreshToken) assignValues(columns []string, values []any) error { - if m, n := len(values), len(columns); m < n { - return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) - } - 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 { - _m.ID = value.String - } - case refreshtoken.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 { - _m.UserID = value.String - } - case refreshtoken.FieldTokenHash: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field token_hash", values[i]) - } else if value.Valid { - _m.TokenHash = value.String - } - case refreshtoken.FieldExpiresAt: - if value, ok := values[i].(*sql.NullTime); !ok { - return fmt.Errorf("unexpected type %T for field expires_at", values[i]) - } else if value.Valid { - _m.ExpiresAt = value.Time - } - 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 { - _m.CreatedAt = value.Time - } - default: - _m.selectValues.Set(columns[i], values[i]) - } - } - return nil -} - -// Value returns the ent.Value that was dynamically selected and assigned to the RefreshToken. -// This includes values selected through modifiers, order, etc. -func (_m *RefreshToken) Value(name string) (ent.Value, error) { - return _m.selectValues.Get(name) -} - -// Update returns a builder for updating this RefreshToken. -// Note that you need to call RefreshToken.Unwrap() before calling this method if this RefreshToken -// was returned from a transaction, and the transaction was committed or rolled back. -func (_m *RefreshToken) Update() *RefreshTokenUpdateOne { - return NewRefreshTokenClient(_m.config).UpdateOne(_m) -} - -// Unwrap unwraps the RefreshToken entity that was returned from a transaction after it was closed, -// so that all future queries will be executed through the driver which created the transaction. -func (_m *RefreshToken) Unwrap() *RefreshToken { - _tx, ok := _m.config.driver.(*txDriver) - if !ok { - panic("ent: RefreshToken is not a transactional entity") - } - _m.config.driver = _tx.drv - return _m -} - -// String implements the fmt.Stringer. -func (_m *RefreshToken) String() string { - var builder strings.Builder - builder.WriteString("RefreshToken(") - builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) - builder.WriteString("user_id=") - builder.WriteString(_m.UserID) - builder.WriteString(", ") - builder.WriteString("token_hash=") - builder.WriteString(", ") - builder.WriteString("expires_at=") - builder.WriteString(_m.ExpiresAt.Format(time.ANSIC)) - builder.WriteString(", ") - builder.WriteString("created_at=") - builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) - builder.WriteByte(')') - return builder.String() -} - -// RefreshTokens is a parsable slice of RefreshToken. -type RefreshTokens []*RefreshToken diff --git a/internal/ent/refreshtoken/refreshtoken.go b/internal/ent/refreshtoken/refreshtoken.go deleted file mode 100644 index b373279..0000000 --- a/internal/ent/refreshtoken/refreshtoken.go +++ /dev/null @@ -1,82 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package refreshtoken - -import ( - "time" - - "entgo.io/ent/dialect/sql" -) - -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" - // FieldUserID holds the string denoting the user_id field in the database. - FieldUserID = "user_id" - // FieldTokenHash holds the string denoting the token_hash field in the database. - FieldTokenHash = "token_hash" - // FieldExpiresAt holds the string denoting the expires_at field in the database. - FieldExpiresAt = "expires_at" - // FieldCreatedAt holds the string denoting the created_at field in the database. - FieldCreatedAt = "created_at" - // 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, - FieldUserID, - FieldTokenHash, - FieldExpiresAt, - FieldCreatedAt, -} - -// ValidColumn reports if the column name is valid (part of the table columns). -func ValidColumn(column string) bool { - for i := range Columns { - if column == Columns[i] { - return true - } - } - return false -} - -var ( - // UserIDValidator is a validator for the "user_id" field. It is called by the builders before save. - UserIDValidator func(string) error - // TokenHashValidator is a validator for the "token_hash" field. It is called by the builders before save. - TokenHashValidator func(string) error - // DefaultCreatedAt holds the default value on creation for the "created_at" field. - DefaultCreatedAt func() time.Time -) - -// OrderOption defines the ordering options for the RefreshToken queries. -type OrderOption func(*sql.Selector) - -// ByID orders the results by the id field. -func ByID(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldID, opts...).ToFunc() -} - -// ByUserID orders the results by the user_id field. -func ByUserID(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldUserID, opts...).ToFunc() -} - -// ByTokenHash orders the results by the token_hash field. -func ByTokenHash(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldTokenHash, opts...).ToFunc() -} - -// ByExpiresAt orders the results by the expires_at field. -func ByExpiresAt(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldExpiresAt, opts...).ToFunc() -} - -// ByCreatedAt orders the results by the created_at field. -func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() -} diff --git a/internal/ent/refreshtoken/where.go b/internal/ent/refreshtoken/where.go deleted file mode 100644 index f6f02d7..0000000 --- a/internal/ent/refreshtoken/where.go +++ /dev/null @@ -1,310 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package refreshtoken - -import ( - "time" - - "entgo.io/ent/dialect/sql" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" -) - -// ID filters vertices based on their ID field. -func ID(id string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldEQ(FieldID, id)) -} - -// IDEQ applies the EQ predicate on the ID field. -func IDEQ(id string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldEQ(FieldID, id)) -} - -// IDNEQ applies the NEQ predicate on the ID field. -func IDNEQ(id string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldNEQ(FieldID, id)) -} - -// IDIn applies the In predicate on the ID field. -func IDIn(ids ...string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldIn(FieldID, ids...)) -} - -// IDNotIn applies the NotIn predicate on the ID field. -func IDNotIn(ids ...string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldNotIn(FieldID, ids...)) -} - -// IDGT applies the GT predicate on the ID field. -func IDGT(id string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldGT(FieldID, id)) -} - -// IDGTE applies the GTE predicate on the ID field. -func IDGTE(id string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldGTE(FieldID, id)) -} - -// IDLT applies the LT predicate on the ID field. -func IDLT(id string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldLT(FieldID, id)) -} - -// IDLTE applies the LTE predicate on the ID field. -func IDLTE(id string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldLTE(FieldID, id)) -} - -// IDEqualFold applies the EqualFold predicate on the ID field. -func IDEqualFold(id string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldEqualFold(FieldID, id)) -} - -// IDContainsFold applies the ContainsFold predicate on the ID field. -func IDContainsFold(id string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldContainsFold(FieldID, id)) -} - -// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. -func UserID(v string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldEQ(FieldUserID, v)) -} - -// TokenHash applies equality check predicate on the "token_hash" field. It's identical to TokenHashEQ. -func TokenHash(v string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldEQ(FieldTokenHash, v)) -} - -// ExpiresAt applies equality check predicate on the "expires_at" field. It's identical to ExpiresAtEQ. -func ExpiresAt(v time.Time) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldEQ(FieldExpiresAt, v)) -} - -// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. -func CreatedAt(v time.Time) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldEQ(FieldCreatedAt, v)) -} - -// UserIDEQ applies the EQ predicate on the "user_id" field. -func UserIDEQ(v string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldEQ(FieldUserID, v)) -} - -// UserIDNEQ applies the NEQ predicate on the "user_id" field. -func UserIDNEQ(v string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldNEQ(FieldUserID, v)) -} - -// UserIDIn applies the In predicate on the "user_id" field. -func UserIDIn(vs ...string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldIn(FieldUserID, vs...)) -} - -// UserIDNotIn applies the NotIn predicate on the "user_id" field. -func UserIDNotIn(vs ...string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldNotIn(FieldUserID, vs...)) -} - -// UserIDGT applies the GT predicate on the "user_id" field. -func UserIDGT(v string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldGT(FieldUserID, v)) -} - -// UserIDGTE applies the GTE predicate on the "user_id" field. -func UserIDGTE(v string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldGTE(FieldUserID, v)) -} - -// UserIDLT applies the LT predicate on the "user_id" field. -func UserIDLT(v string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldLT(FieldUserID, v)) -} - -// UserIDLTE applies the LTE predicate on the "user_id" field. -func UserIDLTE(v string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldLTE(FieldUserID, v)) -} - -// UserIDContains applies the Contains predicate on the "user_id" field. -func UserIDContains(v string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldContains(FieldUserID, v)) -} - -// UserIDHasPrefix applies the HasPrefix predicate on the "user_id" field. -func UserIDHasPrefix(v string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldHasPrefix(FieldUserID, v)) -} - -// UserIDHasSuffix applies the HasSuffix predicate on the "user_id" field. -func UserIDHasSuffix(v string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldHasSuffix(FieldUserID, v)) -} - -// UserIDEqualFold applies the EqualFold predicate on the "user_id" field. -func UserIDEqualFold(v string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldEqualFold(FieldUserID, v)) -} - -// UserIDContainsFold applies the ContainsFold predicate on the "user_id" field. -func UserIDContainsFold(v string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldContainsFold(FieldUserID, v)) -} - -// TokenHashEQ applies the EQ predicate on the "token_hash" field. -func TokenHashEQ(v string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldEQ(FieldTokenHash, v)) -} - -// TokenHashNEQ applies the NEQ predicate on the "token_hash" field. -func TokenHashNEQ(v string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldNEQ(FieldTokenHash, v)) -} - -// TokenHashIn applies the In predicate on the "token_hash" field. -func TokenHashIn(vs ...string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldIn(FieldTokenHash, vs...)) -} - -// TokenHashNotIn applies the NotIn predicate on the "token_hash" field. -func TokenHashNotIn(vs ...string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldNotIn(FieldTokenHash, vs...)) -} - -// TokenHashGT applies the GT predicate on the "token_hash" field. -func TokenHashGT(v string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldGT(FieldTokenHash, v)) -} - -// TokenHashGTE applies the GTE predicate on the "token_hash" field. -func TokenHashGTE(v string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldGTE(FieldTokenHash, v)) -} - -// TokenHashLT applies the LT predicate on the "token_hash" field. -func TokenHashLT(v string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldLT(FieldTokenHash, v)) -} - -// TokenHashLTE applies the LTE predicate on the "token_hash" field. -func TokenHashLTE(v string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldLTE(FieldTokenHash, v)) -} - -// TokenHashContains applies the Contains predicate on the "token_hash" field. -func TokenHashContains(v string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldContains(FieldTokenHash, v)) -} - -// TokenHashHasPrefix applies the HasPrefix predicate on the "token_hash" field. -func TokenHashHasPrefix(v string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldHasPrefix(FieldTokenHash, v)) -} - -// TokenHashHasSuffix applies the HasSuffix predicate on the "token_hash" field. -func TokenHashHasSuffix(v string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldHasSuffix(FieldTokenHash, v)) -} - -// TokenHashEqualFold applies the EqualFold predicate on the "token_hash" field. -func TokenHashEqualFold(v string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldEqualFold(FieldTokenHash, v)) -} - -// TokenHashContainsFold applies the ContainsFold predicate on the "token_hash" field. -func TokenHashContainsFold(v string) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldContainsFold(FieldTokenHash, v)) -} - -// ExpiresAtEQ applies the EQ predicate on the "expires_at" field. -func ExpiresAtEQ(v time.Time) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldEQ(FieldExpiresAt, v)) -} - -// ExpiresAtNEQ applies the NEQ predicate on the "expires_at" field. -func ExpiresAtNEQ(v time.Time) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldNEQ(FieldExpiresAt, v)) -} - -// ExpiresAtIn applies the In predicate on the "expires_at" field. -func ExpiresAtIn(vs ...time.Time) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldIn(FieldExpiresAt, vs...)) -} - -// ExpiresAtNotIn applies the NotIn predicate on the "expires_at" field. -func ExpiresAtNotIn(vs ...time.Time) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldNotIn(FieldExpiresAt, vs...)) -} - -// ExpiresAtGT applies the GT predicate on the "expires_at" field. -func ExpiresAtGT(v time.Time) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldGT(FieldExpiresAt, v)) -} - -// ExpiresAtGTE applies the GTE predicate on the "expires_at" field. -func ExpiresAtGTE(v time.Time) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldGTE(FieldExpiresAt, v)) -} - -// ExpiresAtLT applies the LT predicate on the "expires_at" field. -func ExpiresAtLT(v time.Time) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldLT(FieldExpiresAt, v)) -} - -// ExpiresAtLTE applies the LTE predicate on the "expires_at" field. -func ExpiresAtLTE(v time.Time) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldLTE(FieldExpiresAt, v)) -} - -// CreatedAtEQ applies the EQ predicate on the "created_at" field. -func CreatedAtEQ(v time.Time) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldEQ(FieldCreatedAt, v)) -} - -// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. -func CreatedAtNEQ(v time.Time) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldNEQ(FieldCreatedAt, v)) -} - -// CreatedAtIn applies the In predicate on the "created_at" field. -func CreatedAtIn(vs ...time.Time) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldIn(FieldCreatedAt, vs...)) -} - -// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. -func CreatedAtNotIn(vs ...time.Time) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldNotIn(FieldCreatedAt, vs...)) -} - -// CreatedAtGT applies the GT predicate on the "created_at" field. -func CreatedAtGT(v time.Time) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldGT(FieldCreatedAt, v)) -} - -// CreatedAtGTE applies the GTE predicate on the "created_at" field. -func CreatedAtGTE(v time.Time) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldGTE(FieldCreatedAt, v)) -} - -// CreatedAtLT applies the LT predicate on the "created_at" field. -func CreatedAtLT(v time.Time) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldLT(FieldCreatedAt, v)) -} - -// CreatedAtLTE applies the LTE predicate on the "created_at" field. -func CreatedAtLTE(v time.Time) predicate.RefreshToken { - return predicate.RefreshToken(sql.FieldLTE(FieldCreatedAt, v)) -} - -// And groups predicates with the AND operator between them. -func And(predicates ...predicate.RefreshToken) predicate.RefreshToken { - return predicate.RefreshToken(sql.AndPredicates(predicates...)) -} - -// Or groups predicates with the OR operator between them. -func Or(predicates ...predicate.RefreshToken) predicate.RefreshToken { - return predicate.RefreshToken(sql.OrPredicates(predicates...)) -} - -// Not applies the not operator on the given predicate. -func Not(p predicate.RefreshToken) predicate.RefreshToken { - return predicate.RefreshToken(sql.NotPredicates(p)) -} diff --git a/internal/ent/refreshtoken_create.go b/internal/ent/refreshtoken_create.go deleted file mode 100644 index 690127e..0000000 --- a/internal/ent/refreshtoken_create.go +++ /dev/null @@ -1,262 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "errors" - "fmt" - "time" - - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/internal/ent/refreshtoken" -) - -// RefreshTokenCreate is the builder for creating a RefreshToken entity. -type RefreshTokenCreate struct { - config - mutation *RefreshTokenMutation - hooks []Hook -} - -// SetUserID sets the "user_id" field. -func (_c *RefreshTokenCreate) SetUserID(v string) *RefreshTokenCreate { - _c.mutation.SetUserID(v) - return _c -} - -// SetTokenHash sets the "token_hash" field. -func (_c *RefreshTokenCreate) SetTokenHash(v string) *RefreshTokenCreate { - _c.mutation.SetTokenHash(v) - return _c -} - -// SetExpiresAt sets the "expires_at" field. -func (_c *RefreshTokenCreate) SetExpiresAt(v time.Time) *RefreshTokenCreate { - _c.mutation.SetExpiresAt(v) - return _c -} - -// SetCreatedAt sets the "created_at" field. -func (_c *RefreshTokenCreate) SetCreatedAt(v time.Time) *RefreshTokenCreate { - _c.mutation.SetCreatedAt(v) - return _c -} - -// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. -func (_c *RefreshTokenCreate) SetNillableCreatedAt(v *time.Time) *RefreshTokenCreate { - if v != nil { - _c.SetCreatedAt(*v) - } - return _c -} - -// SetID sets the "id" field. -func (_c *RefreshTokenCreate) SetID(v string) *RefreshTokenCreate { - _c.mutation.SetID(v) - return _c -} - -// Mutation returns the RefreshTokenMutation object of the builder. -func (_c *RefreshTokenCreate) Mutation() *RefreshTokenMutation { - return _c.mutation -} - -// Save creates the RefreshToken in the database. -func (_c *RefreshTokenCreate) Save(ctx context.Context) (*RefreshToken, error) { - _c.defaults() - return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) -} - -// SaveX calls Save and panics if Save returns an error. -func (_c *RefreshTokenCreate) SaveX(ctx context.Context) *RefreshToken { - v, err := _c.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (_c *RefreshTokenCreate) Exec(ctx context.Context) error { - _, err := _c.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_c *RefreshTokenCreate) ExecX(ctx context.Context) { - if err := _c.Exec(ctx); err != nil { - panic(err) - } -} - -// defaults sets the default values of the builder before save. -func (_c *RefreshTokenCreate) defaults() { - if _, ok := _c.mutation.CreatedAt(); !ok { - v := refreshtoken.DefaultCreatedAt() - _c.mutation.SetCreatedAt(v) - } -} - -// check runs all checks and user-defined validators on the builder. -func (_c *RefreshTokenCreate) check() error { - if _, ok := _c.mutation.UserID(); !ok { - return &ValidationError{Name: "user_id", err: errors.New(`ent: missing required field "RefreshToken.user_id"`)} - } - if v, ok := _c.mutation.UserID(); ok { - if err := refreshtoken.UserIDValidator(v); err != nil { - return &ValidationError{Name: "user_id", err: fmt.Errorf(`ent: validator failed for field "RefreshToken.user_id": %w`, err)} - } - } - if _, ok := _c.mutation.TokenHash(); !ok { - return &ValidationError{Name: "token_hash", err: errors.New(`ent: missing required field "RefreshToken.token_hash"`)} - } - if v, ok := _c.mutation.TokenHash(); ok { - if err := refreshtoken.TokenHashValidator(v); err != nil { - return &ValidationError{Name: "token_hash", err: fmt.Errorf(`ent: validator failed for field "RefreshToken.token_hash": %w`, err)} - } - } - if _, ok := _c.mutation.ExpiresAt(); !ok { - return &ValidationError{Name: "expires_at", err: errors.New(`ent: missing required field "RefreshToken.expires_at"`)} - } - if _, ok := _c.mutation.CreatedAt(); !ok { - return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "RefreshToken.created_at"`)} - } - return nil -} - -func (_c *RefreshTokenCreate) sqlSave(ctx context.Context) (*RefreshToken, error) { - if err := _c.check(); err != nil { - return nil, err - } - _node, _spec := _c.createSpec() - if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - if _spec.ID.Value != nil { - if id, ok := _spec.ID.Value.(string); ok { - _node.ID = id - } else { - return nil, fmt.Errorf("unexpected RefreshToken.ID type: %T", _spec.ID.Value) - } - } - _c.mutation.id = &_node.ID - _c.mutation.done = true - return _node, nil -} - -func (_c *RefreshTokenCreate) createSpec() (*RefreshToken, *sqlgraph.CreateSpec) { - var ( - _node = &RefreshToken{config: _c.config} - _spec = sqlgraph.NewCreateSpec(refreshtoken.Table, sqlgraph.NewFieldSpec(refreshtoken.FieldID, field.TypeString)) - ) - if id, ok := _c.mutation.ID(); ok { - _node.ID = id - _spec.ID.Value = id - } - if value, ok := _c.mutation.UserID(); ok { - _spec.SetField(refreshtoken.FieldUserID, field.TypeString, value) - _node.UserID = value - } - if value, ok := _c.mutation.TokenHash(); ok { - _spec.SetField(refreshtoken.FieldTokenHash, field.TypeString, value) - _node.TokenHash = value - } - if value, ok := _c.mutation.ExpiresAt(); ok { - _spec.SetField(refreshtoken.FieldExpiresAt, field.TypeTime, value) - _node.ExpiresAt = value - } - if value, ok := _c.mutation.CreatedAt(); ok { - _spec.SetField(refreshtoken.FieldCreatedAt, field.TypeTime, value) - _node.CreatedAt = value - } - return _node, _spec -} - -// RefreshTokenCreateBulk is the builder for creating many RefreshToken entities in bulk. -type RefreshTokenCreateBulk struct { - config - err error - builders []*RefreshTokenCreate -} - -// Save creates the RefreshToken entities in the database. -func (_c *RefreshTokenCreateBulk) Save(ctx context.Context) ([]*RefreshToken, error) { - if _c.err != nil { - return nil, _c.err - } - specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) - nodes := make([]*RefreshToken, len(_c.builders)) - mutators := make([]Mutator, len(_c.builders)) - for i := range _c.builders { - func(i int, root context.Context) { - builder := _c.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 - var err error - nodes[i], specs[i] = builder.createSpec() - if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) - } else { - spec := &sqlgraph.BatchCreateSpec{Nodes: specs} - // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - } - } - if err != nil { - return nil, err - } - mutation.id = &nodes[i].ID - mutation.done = true - return nodes[i], nil - }) - for i := len(builder.hooks) - 1; i >= 0; i-- { - mut = builder.hooks[i](mut) - } - mutators[i] = mut - }(i, ctx) - } - if len(mutators) > 0 { - if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { - return nil, err - } - } - return nodes, nil -} - -// SaveX is like Save, but panics if an error occurs. -func (_c *RefreshTokenCreateBulk) SaveX(ctx context.Context) []*RefreshToken { - v, err := _c.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (_c *RefreshTokenCreateBulk) Exec(ctx context.Context) error { - _, err := _c.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_c *RefreshTokenCreateBulk) ExecX(ctx context.Context) { - if err := _c.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/internal/ent/refreshtoken_delete.go b/internal/ent/refreshtoken_delete.go deleted file mode 100644 index 0e7adf9..0000000 --- a/internal/ent/refreshtoken_delete.go +++ /dev/null @@ -1,88 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" - "git.dcentral.systems/toolz/goplt/internal/ent/refreshtoken" -) - -// RefreshTokenDelete is the builder for deleting a RefreshToken entity. -type RefreshTokenDelete struct { - config - hooks []Hook - mutation *RefreshTokenMutation -} - -// Where appends a list predicates to the RefreshTokenDelete builder. -func (_d *RefreshTokenDelete) Where(ps ...predicate.RefreshToken) *RefreshTokenDelete { - _d.mutation.Where(ps...) - return _d -} - -// Exec executes the deletion query and returns how many vertices were deleted. -func (_d *RefreshTokenDelete) Exec(ctx context.Context) (int, error) { - return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) -} - -// ExecX is like Exec, but panics if an error occurs. -func (_d *RefreshTokenDelete) ExecX(ctx context.Context) int { - n, err := _d.Exec(ctx) - if err != nil { - panic(err) - } - return n -} - -func (_d *RefreshTokenDelete) sqlExec(ctx context.Context) (int, error) { - _spec := sqlgraph.NewDeleteSpec(refreshtoken.Table, sqlgraph.NewFieldSpec(refreshtoken.FieldID, field.TypeString)) - if ps := _d.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) - if err != nil && sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - _d.mutation.done = true - return affected, err -} - -// RefreshTokenDeleteOne is the builder for deleting a single RefreshToken entity. -type RefreshTokenDeleteOne struct { - _d *RefreshTokenDelete -} - -// Where appends a list predicates to the RefreshTokenDelete builder. -func (_d *RefreshTokenDeleteOne) Where(ps ...predicate.RefreshToken) *RefreshTokenDeleteOne { - _d._d.mutation.Where(ps...) - return _d -} - -// Exec executes the deletion query. -func (_d *RefreshTokenDeleteOne) Exec(ctx context.Context) error { - n, err := _d._d.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 (_d *RefreshTokenDeleteOne) ExecX(ctx context.Context) { - if err := _d.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/internal/ent/refreshtoken_query.go b/internal/ent/refreshtoken_query.go deleted file mode 100644 index 0359d60..0000000 --- a/internal/ent/refreshtoken_query.go +++ /dev/null @@ -1,527 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "fmt" - "math" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" - "git.dcentral.systems/toolz/goplt/internal/ent/refreshtoken" -) - -// RefreshTokenQuery is the builder for querying RefreshToken entities. -type RefreshTokenQuery struct { - config - ctx *QueryContext - order []refreshtoken.OrderOption - inters []Interceptor - 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 (_q *RefreshTokenQuery) Where(ps ...predicate.RefreshToken) *RefreshTokenQuery { - _q.predicates = append(_q.predicates, ps...) - return _q -} - -// Limit the number of records to be returned by this query. -func (_q *RefreshTokenQuery) Limit(limit int) *RefreshTokenQuery { - _q.ctx.Limit = &limit - return _q -} - -// Offset to start from. -func (_q *RefreshTokenQuery) Offset(offset int) *RefreshTokenQuery { - _q.ctx.Offset = &offset - return _q -} - -// Unique configures the query builder to filter duplicate records on query. -// By default, unique is set to true, and can be disabled using this method. -func (_q *RefreshTokenQuery) Unique(unique bool) *RefreshTokenQuery { - _q.ctx.Unique = &unique - return _q -} - -// Order specifies how the records should be ordered. -func (_q *RefreshTokenQuery) Order(o ...refreshtoken.OrderOption) *RefreshTokenQuery { - _q.order = append(_q.order, o...) - return _q -} - -// First returns the first RefreshToken entity from the query. -// Returns a *NotFoundError when no RefreshToken was found. -func (_q *RefreshTokenQuery) First(ctx context.Context) (*RefreshToken, error) { - nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{refreshtoken.Label} - } - return nodes[0], nil -} - -// FirstX is like First, but panics if an error occurs. -func (_q *RefreshTokenQuery) FirstX(ctx context.Context) *RefreshToken { - node, err := _q.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 (_q *RefreshTokenQuery) FirstID(ctx context.Context) (id string, err error) { - var ids []string - if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{refreshtoken.Label} - return - } - return ids[0], nil -} - -// FirstIDX is like FirstID, but panics if an error occurs. -func (_q *RefreshTokenQuery) FirstIDX(ctx context.Context) string { - id, err := _q.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 more than one RefreshToken entity is found. -// Returns a *NotFoundError when no RefreshToken entities are found. -func (_q *RefreshTokenQuery) Only(ctx context.Context) (*RefreshToken, error) { - nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) - if err != nil { - return nil, err - } - 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 (_q *RefreshTokenQuery) OnlyX(ctx context.Context) *RefreshToken { - node, err := _q.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 more than one RefreshToken ID is found. -// Returns a *NotFoundError when no entities are found. -func (_q *RefreshTokenQuery) OnlyID(ctx context.Context) (id string, err error) { - var ids []string - if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { - return - } - switch len(ids) { - case 1: - id = ids[0] - case 0: - err = &NotFoundError{refreshtoken.Label} - default: - err = &NotSingularError{refreshtoken.Label} - } - return -} - -// OnlyIDX is like OnlyID, but panics if an error occurs. -func (_q *RefreshTokenQuery) OnlyIDX(ctx context.Context) string { - id, err := _q.OnlyID(ctx) - if err != nil { - panic(err) - } - return id -} - -// All executes the query and returns a list of RefreshTokens. -func (_q *RefreshTokenQuery) All(ctx context.Context) ([]*RefreshToken, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) - if err := _q.prepareQuery(ctx); err != nil { - return nil, err - } - qr := querierAll[[]*RefreshToken, *RefreshTokenQuery]() - return withInterceptors[[]*RefreshToken](ctx, _q, qr, _q.inters) -} - -// AllX is like All, but panics if an error occurs. -func (_q *RefreshTokenQuery) AllX(ctx context.Context) []*RefreshToken { - nodes, err := _q.All(ctx) - if err != nil { - panic(err) - } - return nodes -} - -// IDs executes the query and returns a list of RefreshToken IDs. -func (_q *RefreshTokenQuery) IDs(ctx context.Context) (ids []string, err error) { - if _q.ctx.Unique == nil && _q.path != nil { - _q.Unique(true) - } - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) - if err = _q.Select(refreshtoken.FieldID).Scan(ctx, &ids); err != nil { - return nil, err - } - return ids, nil -} - -// IDsX is like IDs, but panics if an error occurs. -func (_q *RefreshTokenQuery) IDsX(ctx context.Context) []string { - ids, err := _q.IDs(ctx) - if err != nil { - panic(err) - } - return ids -} - -// Count returns the count of the given query. -func (_q *RefreshTokenQuery) Count(ctx context.Context) (int, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) - if err := _q.prepareQuery(ctx); err != nil { - return 0, err - } - return withInterceptors[int](ctx, _q, querierCount[*RefreshTokenQuery](), _q.inters) -} - -// CountX is like Count, but panics if an error occurs. -func (_q *RefreshTokenQuery) CountX(ctx context.Context) int { - count, err := _q.Count(ctx) - if err != nil { - panic(err) - } - return count -} - -// Exist returns true if the query has elements in the graph. -func (_q *RefreshTokenQuery) Exist(ctx context.Context) (bool, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) - switch _, err := _q.FirstID(ctx); { - case IsNotFound(err): - return false, nil - case err != nil: - return false, fmt.Errorf("ent: check existence: %w", err) - default: - return true, nil - } -} - -// ExistX is like Exist, but panics if an error occurs. -func (_q *RefreshTokenQuery) ExistX(ctx context.Context) bool { - exist, err := _q.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 (_q *RefreshTokenQuery) Clone() *RefreshTokenQuery { - if _q == nil { - return nil - } - return &RefreshTokenQuery{ - config: _q.config, - ctx: _q.ctx.Clone(), - order: append([]refreshtoken.OrderOption{}, _q.order...), - inters: append([]Interceptor{}, _q.inters...), - predicates: append([]predicate.RefreshToken{}, _q.predicates...), - // clone intermediate query. - sql: _q.sql.Clone(), - path: _q.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.RefreshToken.Query(). -// GroupBy(refreshtoken.FieldUserID). -// Aggregate(ent.Count()). -// Scan(ctx, &v) -func (_q *RefreshTokenQuery) GroupBy(field string, fields ...string) *RefreshTokenGroupBy { - _q.ctx.Fields = append([]string{field}, fields...) - grbuild := &RefreshTokenGroupBy{build: _q} - grbuild.flds = &_q.ctx.Fields - grbuild.label = refreshtoken.Label - grbuild.scan = grbuild.Scan - return grbuild -} - -// 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.RefreshToken.Query(). -// Select(refreshtoken.FieldUserID). -// Scan(ctx, &v) -func (_q *RefreshTokenQuery) Select(fields ...string) *RefreshTokenSelect { - _q.ctx.Fields = append(_q.ctx.Fields, fields...) - sbuild := &RefreshTokenSelect{RefreshTokenQuery: _q} - sbuild.label = refreshtoken.Label - sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan - return sbuild -} - -// Aggregate returns a RefreshTokenSelect configured with the given aggregations. -func (_q *RefreshTokenQuery) Aggregate(fns ...AggregateFunc) *RefreshTokenSelect { - return _q.Select().Aggregate(fns...) -} - -func (_q *RefreshTokenQuery) prepareQuery(ctx context.Context) error { - for _, inter := range _q.inters { - if inter == nil { - return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") - } - if trv, ok := inter.(Traverser); ok { - if err := trv.Traverse(ctx, _q); err != nil { - return err - } - } - } - for _, f := range _q.ctx.Fields { - if !refreshtoken.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} - } - } - if _q.path != nil { - prev, err := _q.path(ctx) - if err != nil { - return err - } - _q.sql = prev - } - return nil -} - -func (_q *RefreshTokenQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*RefreshToken, error) { - var ( - nodes = []*RefreshToken{} - _spec = _q.querySpec() - ) - _spec.ScanValues = func(columns []string) ([]any, error) { - return (*RefreshToken).scanValues(nil, columns) - } - _spec.Assign = func(columns []string, values []any) error { - node := &RefreshToken{config: _q.config} - nodes = append(nodes, node) - return node.assignValues(columns, values) - } - for i := range hooks { - hooks[i](ctx, _spec) - } - if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { - return nil, err - } - if len(nodes) == 0 { - return nodes, nil - } - return nodes, nil -} - -func (_q *RefreshTokenQuery) sqlCount(ctx context.Context) (int, error) { - _spec := _q.querySpec() - _spec.Node.Columns = _q.ctx.Fields - if len(_q.ctx.Fields) > 0 { - _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique - } - return sqlgraph.CountNodes(ctx, _q.driver, _spec) -} - -func (_q *RefreshTokenQuery) querySpec() *sqlgraph.QuerySpec { - _spec := sqlgraph.NewQuerySpec(refreshtoken.Table, refreshtoken.Columns, sqlgraph.NewFieldSpec(refreshtoken.FieldID, field.TypeString)) - _spec.From = _q.sql - if unique := _q.ctx.Unique; unique != nil { - _spec.Unique = *unique - } else if _q.path != nil { - _spec.Unique = true - } - if fields := _q.ctx.Fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, refreshtoken.FieldID) - for i := range fields { - if fields[i] != refreshtoken.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) - } - } - } - if ps := _q.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if limit := _q.ctx.Limit; limit != nil { - _spec.Limit = *limit - } - if offset := _q.ctx.Offset; offset != nil { - _spec.Offset = *offset - } - if ps := _q.order; len(ps) > 0 { - _spec.Order = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return _spec -} - -func (_q *RefreshTokenQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(_q.driver.Dialect()) - t1 := builder.Table(refreshtoken.Table) - columns := _q.ctx.Fields - if len(columns) == 0 { - columns = refreshtoken.Columns - } - selector := builder.Select(t1.Columns(columns...)...).From(t1) - if _q.sql != nil { - selector = _q.sql - selector.Select(selector.Columns(columns...)...) - } - if _q.ctx.Unique != nil && *_q.ctx.Unique { - selector.Distinct() - } - for _, p := range _q.predicates { - p(selector) - } - for _, p := range _q.order { - p(selector) - } - if offset := _q.ctx.Offset; offset != nil { - // limit is mandatory for offset clause. We start - // with default value, and override it below if needed. - selector.Offset(*offset).Limit(math.MaxInt32) - } - if limit := _q.ctx.Limit; limit != nil { - selector.Limit(*limit) - } - return selector -} - -// RefreshTokenGroupBy is the group-by builder for RefreshToken entities. -type RefreshTokenGroupBy struct { - selector - build *RefreshTokenQuery -} - -// Aggregate adds the given aggregation functions to the group-by query. -func (_g *RefreshTokenGroupBy) Aggregate(fns ...AggregateFunc) *RefreshTokenGroupBy { - _g.fns = append(_g.fns, fns...) - return _g -} - -// Scan applies the selector query and scans the result into the given value. -func (_g *RefreshTokenGroupBy) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) - if err := _g.build.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*RefreshTokenQuery, *RefreshTokenGroupBy](ctx, _g.build, _g, _g.build.inters, v) -} - -func (_g *RefreshTokenGroupBy) sqlScan(ctx context.Context, root *RefreshTokenQuery, v any) error { - selector := root.sqlQuery(ctx).Select() - aggregation := make([]string, 0, len(_g.fns)) - for _, fn := range _g.fns { - aggregation = append(aggregation, fn(selector)) - } - if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) - for _, f := range *_g.flds { - columns = append(columns, selector.C(f)) - } - columns = append(columns, aggregation...) - selector.Select(columns...) - } - selector.GroupBy(selector.Columns(*_g.flds...)...) - if err := selector.Err(); err != nil { - return err - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} - -// RefreshTokenSelect is the builder for selecting fields of RefreshToken entities. -type RefreshTokenSelect struct { - *RefreshTokenQuery - selector -} - -// Aggregate adds the given aggregation functions to the selector query. -func (_s *RefreshTokenSelect) Aggregate(fns ...AggregateFunc) *RefreshTokenSelect { - _s.fns = append(_s.fns, fns...) - return _s -} - -// Scan applies the selector query and scans the result into the given value. -func (_s *RefreshTokenSelect) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) - if err := _s.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*RefreshTokenQuery, *RefreshTokenSelect](ctx, _s.RefreshTokenQuery, _s, _s.inters, v) -} - -func (_s *RefreshTokenSelect) sqlScan(ctx context.Context, root *RefreshTokenQuery, v any) error { - selector := root.sqlQuery(ctx) - aggregation := make([]string, 0, len(_s.fns)) - for _, fn := range _s.fns { - aggregation = append(aggregation, fn(selector)) - } - switch n := len(*_s.selector.flds); { - case n == 0 && len(aggregation) > 0: - selector.Select(aggregation...) - case n != 0 && len(aggregation) > 0: - selector.AppendSelect(aggregation...) - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := _s.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} diff --git a/internal/ent/refreshtoken_update.go b/internal/ent/refreshtoken_update.go deleted file mode 100644 index 32281f7..0000000 --- a/internal/ent/refreshtoken_update.go +++ /dev/null @@ -1,314 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "errors" - "fmt" - "time" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" - "git.dcentral.systems/toolz/goplt/internal/ent/refreshtoken" -) - -// RefreshTokenUpdate is the builder for updating RefreshToken entities. -type RefreshTokenUpdate struct { - config - hooks []Hook - mutation *RefreshTokenMutation -} - -// Where appends a list predicates to the RefreshTokenUpdate builder. -func (_u *RefreshTokenUpdate) Where(ps ...predicate.RefreshToken) *RefreshTokenUpdate { - _u.mutation.Where(ps...) - return _u -} - -// SetUserID sets the "user_id" field. -func (_u *RefreshTokenUpdate) SetUserID(v string) *RefreshTokenUpdate { - _u.mutation.SetUserID(v) - return _u -} - -// SetNillableUserID sets the "user_id" field if the given value is not nil. -func (_u *RefreshTokenUpdate) SetNillableUserID(v *string) *RefreshTokenUpdate { - if v != nil { - _u.SetUserID(*v) - } - return _u -} - -// SetTokenHash sets the "token_hash" field. -func (_u *RefreshTokenUpdate) SetTokenHash(v string) *RefreshTokenUpdate { - _u.mutation.SetTokenHash(v) - return _u -} - -// SetNillableTokenHash sets the "token_hash" field if the given value is not nil. -func (_u *RefreshTokenUpdate) SetNillableTokenHash(v *string) *RefreshTokenUpdate { - if v != nil { - _u.SetTokenHash(*v) - } - return _u -} - -// SetExpiresAt sets the "expires_at" field. -func (_u *RefreshTokenUpdate) SetExpiresAt(v time.Time) *RefreshTokenUpdate { - _u.mutation.SetExpiresAt(v) - return _u -} - -// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil. -func (_u *RefreshTokenUpdate) SetNillableExpiresAt(v *time.Time) *RefreshTokenUpdate { - if v != nil { - _u.SetExpiresAt(*v) - } - return _u -} - -// Mutation returns the RefreshTokenMutation object of the builder. -func (_u *RefreshTokenUpdate) Mutation() *RefreshTokenMutation { - return _u.mutation -} - -// Save executes the query and returns the number of nodes affected by the update operation. -func (_u *RefreshTokenUpdate) Save(ctx context.Context) (int, error) { - return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (_u *RefreshTokenUpdate) SaveX(ctx context.Context) int { - affected, err := _u.Save(ctx) - if err != nil { - panic(err) - } - return affected -} - -// Exec executes the query. -func (_u *RefreshTokenUpdate) Exec(ctx context.Context) error { - _, err := _u.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_u *RefreshTokenUpdate) ExecX(ctx context.Context) { - if err := _u.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (_u *RefreshTokenUpdate) check() error { - if v, ok := _u.mutation.UserID(); ok { - if err := refreshtoken.UserIDValidator(v); err != nil { - return &ValidationError{Name: "user_id", err: fmt.Errorf(`ent: validator failed for field "RefreshToken.user_id": %w`, err)} - } - } - if v, ok := _u.mutation.TokenHash(); ok { - if err := refreshtoken.TokenHashValidator(v); err != nil { - return &ValidationError{Name: "token_hash", err: fmt.Errorf(`ent: validator failed for field "RefreshToken.token_hash": %w`, err)} - } - } - return nil -} - -func (_u *RefreshTokenUpdate) sqlSave(ctx context.Context) (_node int, err error) { - if err := _u.check(); err != nil { - return _node, err - } - _spec := sqlgraph.NewUpdateSpec(refreshtoken.Table, refreshtoken.Columns, sqlgraph.NewFieldSpec(refreshtoken.FieldID, field.TypeString)) - if ps := _u.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := _u.mutation.UserID(); ok { - _spec.SetField(refreshtoken.FieldUserID, field.TypeString, value) - } - if value, ok := _u.mutation.TokenHash(); ok { - _spec.SetField(refreshtoken.FieldTokenHash, field.TypeString, value) - } - if value, ok := _u.mutation.ExpiresAt(); ok { - _spec.SetField(refreshtoken.FieldExpiresAt, field.TypeTime, value) - } - if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{refreshtoken.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return 0, err - } - _u.mutation.done = true - return _node, nil -} - -// RefreshTokenUpdateOne is the builder for updating a single RefreshToken entity. -type RefreshTokenUpdateOne struct { - config - fields []string - hooks []Hook - mutation *RefreshTokenMutation -} - -// SetUserID sets the "user_id" field. -func (_u *RefreshTokenUpdateOne) SetUserID(v string) *RefreshTokenUpdateOne { - _u.mutation.SetUserID(v) - return _u -} - -// SetNillableUserID sets the "user_id" field if the given value is not nil. -func (_u *RefreshTokenUpdateOne) SetNillableUserID(v *string) *RefreshTokenUpdateOne { - if v != nil { - _u.SetUserID(*v) - } - return _u -} - -// SetTokenHash sets the "token_hash" field. -func (_u *RefreshTokenUpdateOne) SetTokenHash(v string) *RefreshTokenUpdateOne { - _u.mutation.SetTokenHash(v) - return _u -} - -// SetNillableTokenHash sets the "token_hash" field if the given value is not nil. -func (_u *RefreshTokenUpdateOne) SetNillableTokenHash(v *string) *RefreshTokenUpdateOne { - if v != nil { - _u.SetTokenHash(*v) - } - return _u -} - -// SetExpiresAt sets the "expires_at" field. -func (_u *RefreshTokenUpdateOne) SetExpiresAt(v time.Time) *RefreshTokenUpdateOne { - _u.mutation.SetExpiresAt(v) - return _u -} - -// SetNillableExpiresAt sets the "expires_at" field if the given value is not nil. -func (_u *RefreshTokenUpdateOne) SetNillableExpiresAt(v *time.Time) *RefreshTokenUpdateOne { - if v != nil { - _u.SetExpiresAt(*v) - } - return _u -} - -// Mutation returns the RefreshTokenMutation object of the builder. -func (_u *RefreshTokenUpdateOne) Mutation() *RefreshTokenMutation { - return _u.mutation -} - -// Where appends a list predicates to the RefreshTokenUpdate builder. -func (_u *RefreshTokenUpdateOne) Where(ps ...predicate.RefreshToken) *RefreshTokenUpdateOne { - _u.mutation.Where(ps...) - return _u -} - -// Select allows selecting one or more fields (columns) of the returned entity. -// The default is selecting all fields defined in the entity schema. -func (_u *RefreshTokenUpdateOne) Select(field string, fields ...string) *RefreshTokenUpdateOne { - _u.fields = append([]string{field}, fields...) - return _u -} - -// Save executes the query and returns the updated RefreshToken entity. -func (_u *RefreshTokenUpdateOne) Save(ctx context.Context) (*RefreshToken, error) { - return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (_u *RefreshTokenUpdateOne) SaveX(ctx context.Context) *RefreshToken { - node, err := _u.Save(ctx) - if err != nil { - panic(err) - } - return node -} - -// Exec executes the query on the entity. -func (_u *RefreshTokenUpdateOne) Exec(ctx context.Context) error { - _, err := _u.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_u *RefreshTokenUpdateOne) ExecX(ctx context.Context) { - if err := _u.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (_u *RefreshTokenUpdateOne) check() error { - if v, ok := _u.mutation.UserID(); ok { - if err := refreshtoken.UserIDValidator(v); err != nil { - return &ValidationError{Name: "user_id", err: fmt.Errorf(`ent: validator failed for field "RefreshToken.user_id": %w`, err)} - } - } - if v, ok := _u.mutation.TokenHash(); ok { - if err := refreshtoken.TokenHashValidator(v); err != nil { - return &ValidationError{Name: "token_hash", err: fmt.Errorf(`ent: validator failed for field "RefreshToken.token_hash": %w`, err)} - } - } - return nil -} - -func (_u *RefreshTokenUpdateOne) sqlSave(ctx context.Context) (_node *RefreshToken, err error) { - if err := _u.check(); err != nil { - return _node, err - } - _spec := sqlgraph.NewUpdateSpec(refreshtoken.Table, refreshtoken.Columns, sqlgraph.NewFieldSpec(refreshtoken.FieldID, field.TypeString)) - id, ok := _u.mutation.ID() - if !ok { - return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "RefreshToken.id" for update`)} - } - _spec.Node.ID.Value = id - if fields := _u.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, refreshtoken.FieldID) - for _, f := range fields { - if !refreshtoken.ValidColumn(f) { - return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} - } - if f != refreshtoken.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, f) - } - } - } - if ps := _u.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := _u.mutation.UserID(); ok { - _spec.SetField(refreshtoken.FieldUserID, field.TypeString, value) - } - if value, ok := _u.mutation.TokenHash(); ok { - _spec.SetField(refreshtoken.FieldTokenHash, field.TypeString, value) - } - if value, ok := _u.mutation.ExpiresAt(); ok { - _spec.SetField(refreshtoken.FieldExpiresAt, field.TypeTime, value) - } - _node = &RefreshToken{config: _u.config} - _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{refreshtoken.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - _u.mutation.done = true - return _node, nil -} diff --git a/internal/ent/role.go b/internal/ent/role.go deleted file mode 100644 index 46d7e71..0000000 --- a/internal/ent/role.go +++ /dev/null @@ -1,168 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "fmt" - "strings" - "time" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "git.dcentral.systems/toolz/goplt/internal/ent/role" -) - -// Role is the model entity for the Role schema. -type Role struct { - config `json:"-"` - // ID of the ent. - ID string `json:"id,omitempty"` - // Name holds the value of the "name" field. - Name string `json:"name,omitempty"` - // Description holds the value of the "description" field. - Description string `json:"description,omitempty"` - // CreatedAt holds the value of the "created_at" field. - CreatedAt time.Time `json:"created_at,omitempty"` - // Edges holds the relations/edges for other nodes in the graph. - // The values are being populated by the RoleQuery when eager-loading is set. - Edges RoleEdges `json:"edges"` - selectValues sql.SelectValues -} - -// RoleEdges holds the relations/edges for other nodes in the graph. -type RoleEdges struct { - // RolePermissions holds the value of the role_permissions edge. - RolePermissions []*RolePermission `json:"role_permissions,omitempty"` - // UserRoles holds the value of the user_roles edge. - UserRoles []*UserRole `json:"user_roles,omitempty"` - // loadedTypes holds the information for reporting if a - // type was loaded (or requested) in eager-loading or not. - loadedTypes [2]bool -} - -// RolePermissionsOrErr returns the RolePermissions value or an error if the edge -// was not loaded in eager-loading. -func (e RoleEdges) RolePermissionsOrErr() ([]*RolePermission, error) { - if e.loadedTypes[0] { - return e.RolePermissions, nil - } - return nil, &NotLoadedError{edge: "role_permissions"} -} - -// UserRolesOrErr returns the UserRoles value or an error if the edge -// was not loaded in eager-loading. -func (e RoleEdges) UserRolesOrErr() ([]*UserRole, error) { - if e.loadedTypes[1] { - return e.UserRoles, nil - } - return nil, &NotLoadedError{edge: "user_roles"} -} - -// scanValues returns the types for scanning values from sql.Rows. -func (*Role) scanValues(columns []string) ([]any, error) { - values := make([]any, len(columns)) - for i := range columns { - switch columns[i] { - case role.FieldID, role.FieldName, role.FieldDescription: - values[i] = new(sql.NullString) - case role.FieldCreatedAt: - values[i] = new(sql.NullTime) - default: - values[i] = new(sql.UnknownType) - } - } - return values, nil -} - -// assignValues assigns the values that were returned from sql.Rows (after scanning) -// to the Role fields. -func (_m *Role) assignValues(columns []string, values []any) error { - if m, n := len(values), len(columns); m < n { - return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) - } - for i := range columns { - switch columns[i] { - case role.FieldID: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field id", values[i]) - } else if value.Valid { - _m.ID = value.String - } - case role.FieldName: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field name", values[i]) - } else if value.Valid { - _m.Name = value.String - } - case role.FieldDescription: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field description", values[i]) - } else if value.Valid { - _m.Description = value.String - } - case role.FieldCreatedAt: - if value, ok := values[i].(*sql.NullTime); !ok { - return fmt.Errorf("unexpected type %T for field created_at", values[i]) - } else if value.Valid { - _m.CreatedAt = value.Time - } - default: - _m.selectValues.Set(columns[i], values[i]) - } - } - return nil -} - -// Value returns the ent.Value that was dynamically selected and assigned to the Role. -// This includes values selected through modifiers, order, etc. -func (_m *Role) Value(name string) (ent.Value, error) { - return _m.selectValues.Get(name) -} - -// QueryRolePermissions queries the "role_permissions" edge of the Role entity. -func (_m *Role) QueryRolePermissions() *RolePermissionQuery { - return NewRoleClient(_m.config).QueryRolePermissions(_m) -} - -// QueryUserRoles queries the "user_roles" edge of the Role entity. -func (_m *Role) QueryUserRoles() *UserRoleQuery { - return NewRoleClient(_m.config).QueryUserRoles(_m) -} - -// Update returns a builder for updating this Role. -// Note that you need to call Role.Unwrap() before calling this method if this Role -// was returned from a transaction, and the transaction was committed or rolled back. -func (_m *Role) Update() *RoleUpdateOne { - return NewRoleClient(_m.config).UpdateOne(_m) -} - -// Unwrap unwraps the Role entity that was returned from a transaction after it was closed, -// so that all future queries will be executed through the driver which created the transaction. -func (_m *Role) Unwrap() *Role { - _tx, ok := _m.config.driver.(*txDriver) - if !ok { - panic("ent: Role is not a transactional entity") - } - _m.config.driver = _tx.drv - return _m -} - -// String implements the fmt.Stringer. -func (_m *Role) String() string { - var builder strings.Builder - builder.WriteString("Role(") - builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) - builder.WriteString("name=") - builder.WriteString(_m.Name) - builder.WriteString(", ") - builder.WriteString("description=") - builder.WriteString(_m.Description) - builder.WriteString(", ") - builder.WriteString("created_at=") - builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) - builder.WriteByte(')') - return builder.String() -} - -// Roles is a parsable slice of Role. -type Roles []*Role diff --git a/internal/ent/role/role.go b/internal/ent/role/role.go deleted file mode 100644 index 6f62145..0000000 --- a/internal/ent/role/role.go +++ /dev/null @@ -1,133 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package role - -import ( - "time" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" -) - -const ( - // Label holds the string label denoting the role type in the database. - Label = "role" - // FieldID holds the string denoting the id field in the database. - FieldID = "id" - // FieldName holds the string denoting the name field in the database. - FieldName = "name" - // FieldDescription holds the string denoting the description field in the database. - FieldDescription = "description" - // FieldCreatedAt holds the string denoting the created_at field in the database. - FieldCreatedAt = "created_at" - // EdgeRolePermissions holds the string denoting the role_permissions edge name in mutations. - EdgeRolePermissions = "role_permissions" - // EdgeUserRoles holds the string denoting the user_roles edge name in mutations. - EdgeUserRoles = "user_roles" - // Table holds the table name of the role in the database. - Table = "roles" - // RolePermissionsTable is the table that holds the role_permissions relation/edge. - RolePermissionsTable = "role_permissions" - // RolePermissionsInverseTable is the table name for the RolePermission entity. - // It exists in this package in order to avoid circular dependency with the "rolepermission" package. - RolePermissionsInverseTable = "role_permissions" - // RolePermissionsColumn is the table column denoting the role_permissions relation/edge. - RolePermissionsColumn = "role_role_permissions" - // UserRolesTable is the table that holds the user_roles relation/edge. - UserRolesTable = "user_roles" - // UserRolesInverseTable is the table name for the UserRole entity. - // It exists in this package in order to avoid circular dependency with the "userrole" package. - UserRolesInverseTable = "user_roles" - // UserRolesColumn is the table column denoting the user_roles relation/edge. - UserRolesColumn = "role_user_roles" -) - -// Columns holds all SQL columns for role fields. -var Columns = []string{ - FieldID, - FieldName, - FieldDescription, - FieldCreatedAt, -} - -// ValidColumn reports if the column name is valid (part of the table columns). -func ValidColumn(column string) bool { - for i := range Columns { - if column == Columns[i] { - return true - } - } - return false -} - -var ( - // NameValidator is a validator for the "name" field. It is called by the builders before save. - NameValidator func(string) error - // DefaultCreatedAt holds the default value on creation for the "created_at" field. - DefaultCreatedAt func() time.Time -) - -// OrderOption defines the ordering options for the Role queries. -type OrderOption func(*sql.Selector) - -// ByID orders the results by the id field. -func ByID(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldID, opts...).ToFunc() -} - -// ByName orders the results by the name field. -func ByName(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldName, opts...).ToFunc() -} - -// ByDescription orders the results by the description field. -func ByDescription(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldDescription, opts...).ToFunc() -} - -// ByCreatedAt orders the results by the created_at field. -func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() -} - -// ByRolePermissionsCount orders the results by role_permissions count. -func ByRolePermissionsCount(opts ...sql.OrderTermOption) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborsCount(s, newRolePermissionsStep(), opts...) - } -} - -// ByRolePermissions orders the results by role_permissions terms. -func ByRolePermissions(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborTerms(s, newRolePermissionsStep(), append([]sql.OrderTerm{term}, terms...)...) - } -} - -// ByUserRolesCount orders the results by user_roles count. -func ByUserRolesCount(opts ...sql.OrderTermOption) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborsCount(s, newUserRolesStep(), opts...) - } -} - -// ByUserRoles orders the results by user_roles terms. -func ByUserRoles(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborTerms(s, newUserRolesStep(), append([]sql.OrderTerm{term}, terms...)...) - } -} -func newRolePermissionsStep() *sqlgraph.Step { - return sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(RolePermissionsInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, RolePermissionsTable, RolePermissionsColumn), - ) -} -func newUserRolesStep() *sqlgraph.Step { - return sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(UserRolesInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, UserRolesTable, UserRolesColumn), - ) -} diff --git a/internal/ent/role/where.go b/internal/ent/role/where.go deleted file mode 100644 index 086045c..0000000 --- a/internal/ent/role/where.go +++ /dev/null @@ -1,322 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package role - -import ( - "time" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" -) - -// ID filters vertices based on their ID field. -func ID(id string) predicate.Role { - return predicate.Role(sql.FieldEQ(FieldID, id)) -} - -// IDEQ applies the EQ predicate on the ID field. -func IDEQ(id string) predicate.Role { - return predicate.Role(sql.FieldEQ(FieldID, id)) -} - -// IDNEQ applies the NEQ predicate on the ID field. -func IDNEQ(id string) predicate.Role { - return predicate.Role(sql.FieldNEQ(FieldID, id)) -} - -// IDIn applies the In predicate on the ID field. -func IDIn(ids ...string) predicate.Role { - return predicate.Role(sql.FieldIn(FieldID, ids...)) -} - -// IDNotIn applies the NotIn predicate on the ID field. -func IDNotIn(ids ...string) predicate.Role { - return predicate.Role(sql.FieldNotIn(FieldID, ids...)) -} - -// IDGT applies the GT predicate on the ID field. -func IDGT(id string) predicate.Role { - return predicate.Role(sql.FieldGT(FieldID, id)) -} - -// IDGTE applies the GTE predicate on the ID field. -func IDGTE(id string) predicate.Role { - return predicate.Role(sql.FieldGTE(FieldID, id)) -} - -// IDLT applies the LT predicate on the ID field. -func IDLT(id string) predicate.Role { - return predicate.Role(sql.FieldLT(FieldID, id)) -} - -// IDLTE applies the LTE predicate on the ID field. -func IDLTE(id string) predicate.Role { - return predicate.Role(sql.FieldLTE(FieldID, id)) -} - -// IDEqualFold applies the EqualFold predicate on the ID field. -func IDEqualFold(id string) predicate.Role { - return predicate.Role(sql.FieldEqualFold(FieldID, id)) -} - -// IDContainsFold applies the ContainsFold predicate on the ID field. -func IDContainsFold(id string) predicate.Role { - return predicate.Role(sql.FieldContainsFold(FieldID, id)) -} - -// Name applies equality check predicate on the "name" field. It's identical to NameEQ. -func Name(v string) predicate.Role { - return predicate.Role(sql.FieldEQ(FieldName, v)) -} - -// Description applies equality check predicate on the "description" field. It's identical to DescriptionEQ. -func Description(v string) predicate.Role { - return predicate.Role(sql.FieldEQ(FieldDescription, v)) -} - -// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. -func CreatedAt(v time.Time) predicate.Role { - return predicate.Role(sql.FieldEQ(FieldCreatedAt, v)) -} - -// NameEQ applies the EQ predicate on the "name" field. -func NameEQ(v string) predicate.Role { - return predicate.Role(sql.FieldEQ(FieldName, v)) -} - -// NameNEQ applies the NEQ predicate on the "name" field. -func NameNEQ(v string) predicate.Role { - return predicate.Role(sql.FieldNEQ(FieldName, v)) -} - -// NameIn applies the In predicate on the "name" field. -func NameIn(vs ...string) predicate.Role { - return predicate.Role(sql.FieldIn(FieldName, vs...)) -} - -// NameNotIn applies the NotIn predicate on the "name" field. -func NameNotIn(vs ...string) predicate.Role { - return predicate.Role(sql.FieldNotIn(FieldName, vs...)) -} - -// NameGT applies the GT predicate on the "name" field. -func NameGT(v string) predicate.Role { - return predicate.Role(sql.FieldGT(FieldName, v)) -} - -// NameGTE applies the GTE predicate on the "name" field. -func NameGTE(v string) predicate.Role { - return predicate.Role(sql.FieldGTE(FieldName, v)) -} - -// NameLT applies the LT predicate on the "name" field. -func NameLT(v string) predicate.Role { - return predicate.Role(sql.FieldLT(FieldName, v)) -} - -// NameLTE applies the LTE predicate on the "name" field. -func NameLTE(v string) predicate.Role { - return predicate.Role(sql.FieldLTE(FieldName, v)) -} - -// NameContains applies the Contains predicate on the "name" field. -func NameContains(v string) predicate.Role { - return predicate.Role(sql.FieldContains(FieldName, v)) -} - -// NameHasPrefix applies the HasPrefix predicate on the "name" field. -func NameHasPrefix(v string) predicate.Role { - return predicate.Role(sql.FieldHasPrefix(FieldName, v)) -} - -// NameHasSuffix applies the HasSuffix predicate on the "name" field. -func NameHasSuffix(v string) predicate.Role { - return predicate.Role(sql.FieldHasSuffix(FieldName, v)) -} - -// NameEqualFold applies the EqualFold predicate on the "name" field. -func NameEqualFold(v string) predicate.Role { - return predicate.Role(sql.FieldEqualFold(FieldName, v)) -} - -// NameContainsFold applies the ContainsFold predicate on the "name" field. -func NameContainsFold(v string) predicate.Role { - return predicate.Role(sql.FieldContainsFold(FieldName, v)) -} - -// DescriptionEQ applies the EQ predicate on the "description" field. -func DescriptionEQ(v string) predicate.Role { - return predicate.Role(sql.FieldEQ(FieldDescription, v)) -} - -// DescriptionNEQ applies the NEQ predicate on the "description" field. -func DescriptionNEQ(v string) predicate.Role { - return predicate.Role(sql.FieldNEQ(FieldDescription, v)) -} - -// DescriptionIn applies the In predicate on the "description" field. -func DescriptionIn(vs ...string) predicate.Role { - return predicate.Role(sql.FieldIn(FieldDescription, vs...)) -} - -// DescriptionNotIn applies the NotIn predicate on the "description" field. -func DescriptionNotIn(vs ...string) predicate.Role { - return predicate.Role(sql.FieldNotIn(FieldDescription, vs...)) -} - -// DescriptionGT applies the GT predicate on the "description" field. -func DescriptionGT(v string) predicate.Role { - return predicate.Role(sql.FieldGT(FieldDescription, v)) -} - -// DescriptionGTE applies the GTE predicate on the "description" field. -func DescriptionGTE(v string) predicate.Role { - return predicate.Role(sql.FieldGTE(FieldDescription, v)) -} - -// DescriptionLT applies the LT predicate on the "description" field. -func DescriptionLT(v string) predicate.Role { - return predicate.Role(sql.FieldLT(FieldDescription, v)) -} - -// DescriptionLTE applies the LTE predicate on the "description" field. -func DescriptionLTE(v string) predicate.Role { - return predicate.Role(sql.FieldLTE(FieldDescription, v)) -} - -// DescriptionContains applies the Contains predicate on the "description" field. -func DescriptionContains(v string) predicate.Role { - return predicate.Role(sql.FieldContains(FieldDescription, v)) -} - -// DescriptionHasPrefix applies the HasPrefix predicate on the "description" field. -func DescriptionHasPrefix(v string) predicate.Role { - return predicate.Role(sql.FieldHasPrefix(FieldDescription, v)) -} - -// DescriptionHasSuffix applies the HasSuffix predicate on the "description" field. -func DescriptionHasSuffix(v string) predicate.Role { - return predicate.Role(sql.FieldHasSuffix(FieldDescription, v)) -} - -// DescriptionIsNil applies the IsNil predicate on the "description" field. -func DescriptionIsNil() predicate.Role { - return predicate.Role(sql.FieldIsNull(FieldDescription)) -} - -// DescriptionNotNil applies the NotNil predicate on the "description" field. -func DescriptionNotNil() predicate.Role { - return predicate.Role(sql.FieldNotNull(FieldDescription)) -} - -// DescriptionEqualFold applies the EqualFold predicate on the "description" field. -func DescriptionEqualFold(v string) predicate.Role { - return predicate.Role(sql.FieldEqualFold(FieldDescription, v)) -} - -// DescriptionContainsFold applies the ContainsFold predicate on the "description" field. -func DescriptionContainsFold(v string) predicate.Role { - return predicate.Role(sql.FieldContainsFold(FieldDescription, v)) -} - -// CreatedAtEQ applies the EQ predicate on the "created_at" field. -func CreatedAtEQ(v time.Time) predicate.Role { - return predicate.Role(sql.FieldEQ(FieldCreatedAt, v)) -} - -// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. -func CreatedAtNEQ(v time.Time) predicate.Role { - return predicate.Role(sql.FieldNEQ(FieldCreatedAt, v)) -} - -// CreatedAtIn applies the In predicate on the "created_at" field. -func CreatedAtIn(vs ...time.Time) predicate.Role { - return predicate.Role(sql.FieldIn(FieldCreatedAt, vs...)) -} - -// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. -func CreatedAtNotIn(vs ...time.Time) predicate.Role { - return predicate.Role(sql.FieldNotIn(FieldCreatedAt, vs...)) -} - -// CreatedAtGT applies the GT predicate on the "created_at" field. -func CreatedAtGT(v time.Time) predicate.Role { - return predicate.Role(sql.FieldGT(FieldCreatedAt, v)) -} - -// CreatedAtGTE applies the GTE predicate on the "created_at" field. -func CreatedAtGTE(v time.Time) predicate.Role { - return predicate.Role(sql.FieldGTE(FieldCreatedAt, v)) -} - -// CreatedAtLT applies the LT predicate on the "created_at" field. -func CreatedAtLT(v time.Time) predicate.Role { - return predicate.Role(sql.FieldLT(FieldCreatedAt, v)) -} - -// CreatedAtLTE applies the LTE predicate on the "created_at" field. -func CreatedAtLTE(v time.Time) predicate.Role { - return predicate.Role(sql.FieldLTE(FieldCreatedAt, v)) -} - -// HasRolePermissions applies the HasEdge predicate on the "role_permissions" edge. -func HasRolePermissions() predicate.Role { - return predicate.Role(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, RolePermissionsTable, RolePermissionsColumn), - ) - sqlgraph.HasNeighbors(s, step) - }) -} - -// HasRolePermissionsWith applies the HasEdge predicate on the "role_permissions" edge with a given conditions (other predicates). -func HasRolePermissionsWith(preds ...predicate.RolePermission) predicate.Role { - return predicate.Role(func(s *sql.Selector) { - step := newRolePermissionsStep() - sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { - for _, p := range preds { - p(s) - } - }) - }) -} - -// HasUserRoles applies the HasEdge predicate on the "user_roles" edge. -func HasUserRoles() predicate.Role { - return predicate.Role(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, UserRolesTable, UserRolesColumn), - ) - sqlgraph.HasNeighbors(s, step) - }) -} - -// HasUserRolesWith applies the HasEdge predicate on the "user_roles" edge with a given conditions (other predicates). -func HasUserRolesWith(preds ...predicate.UserRole) predicate.Role { - return predicate.Role(func(s *sql.Selector) { - step := newUserRolesStep() - sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { - for _, p := range preds { - p(s) - } - }) - }) -} - -// And groups predicates with the AND operator between them. -func And(predicates ...predicate.Role) predicate.Role { - return predicate.Role(sql.AndPredicates(predicates...)) -} - -// Or groups predicates with the OR operator between them. -func Or(predicates ...predicate.Role) predicate.Role { - return predicate.Role(sql.OrPredicates(predicates...)) -} - -// Not applies the not operator on the given predicate. -func Not(p predicate.Role) predicate.Role { - return predicate.Role(sql.NotPredicates(p)) -} diff --git a/internal/ent/role_create.go b/internal/ent/role_create.go deleted file mode 100644 index 221dadc..0000000 --- a/internal/ent/role_create.go +++ /dev/null @@ -1,313 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "errors" - "fmt" - "time" - - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/internal/ent/role" - "git.dcentral.systems/toolz/goplt/internal/ent/rolepermission" - "git.dcentral.systems/toolz/goplt/internal/ent/userrole" -) - -// RoleCreate is the builder for creating a Role entity. -type RoleCreate struct { - config - mutation *RoleMutation - hooks []Hook -} - -// SetName sets the "name" field. -func (_c *RoleCreate) SetName(v string) *RoleCreate { - _c.mutation.SetName(v) - return _c -} - -// SetDescription sets the "description" field. -func (_c *RoleCreate) SetDescription(v string) *RoleCreate { - _c.mutation.SetDescription(v) - return _c -} - -// SetNillableDescription sets the "description" field if the given value is not nil. -func (_c *RoleCreate) SetNillableDescription(v *string) *RoleCreate { - if v != nil { - _c.SetDescription(*v) - } - return _c -} - -// SetCreatedAt sets the "created_at" field. -func (_c *RoleCreate) SetCreatedAt(v time.Time) *RoleCreate { - _c.mutation.SetCreatedAt(v) - return _c -} - -// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. -func (_c *RoleCreate) SetNillableCreatedAt(v *time.Time) *RoleCreate { - if v != nil { - _c.SetCreatedAt(*v) - } - return _c -} - -// SetID sets the "id" field. -func (_c *RoleCreate) SetID(v string) *RoleCreate { - _c.mutation.SetID(v) - return _c -} - -// AddRolePermissionIDs adds the "role_permissions" edge to the RolePermission entity by IDs. -func (_c *RoleCreate) AddRolePermissionIDs(ids ...int) *RoleCreate { - _c.mutation.AddRolePermissionIDs(ids...) - return _c -} - -// AddRolePermissions adds the "role_permissions" edges to the RolePermission entity. -func (_c *RoleCreate) AddRolePermissions(v ...*RolePermission) *RoleCreate { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _c.AddRolePermissionIDs(ids...) -} - -// AddUserRoleIDs adds the "user_roles" edge to the UserRole entity by IDs. -func (_c *RoleCreate) AddUserRoleIDs(ids ...int) *RoleCreate { - _c.mutation.AddUserRoleIDs(ids...) - return _c -} - -// AddUserRoles adds the "user_roles" edges to the UserRole entity. -func (_c *RoleCreate) AddUserRoles(v ...*UserRole) *RoleCreate { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _c.AddUserRoleIDs(ids...) -} - -// Mutation returns the RoleMutation object of the builder. -func (_c *RoleCreate) Mutation() *RoleMutation { - return _c.mutation -} - -// Save creates the Role in the database. -func (_c *RoleCreate) Save(ctx context.Context) (*Role, error) { - _c.defaults() - return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) -} - -// SaveX calls Save and panics if Save returns an error. -func (_c *RoleCreate) SaveX(ctx context.Context) *Role { - v, err := _c.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (_c *RoleCreate) Exec(ctx context.Context) error { - _, err := _c.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_c *RoleCreate) ExecX(ctx context.Context) { - if err := _c.Exec(ctx); err != nil { - panic(err) - } -} - -// defaults sets the default values of the builder before save. -func (_c *RoleCreate) defaults() { - if _, ok := _c.mutation.CreatedAt(); !ok { - v := role.DefaultCreatedAt() - _c.mutation.SetCreatedAt(v) - } -} - -// check runs all checks and user-defined validators on the builder. -func (_c *RoleCreate) check() error { - if _, ok := _c.mutation.Name(); !ok { - return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Role.name"`)} - } - if v, ok := _c.mutation.Name(); ok { - if err := role.NameValidator(v); err != nil { - return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Role.name": %w`, err)} - } - } - if _, ok := _c.mutation.CreatedAt(); !ok { - return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Role.created_at"`)} - } - return nil -} - -func (_c *RoleCreate) sqlSave(ctx context.Context) (*Role, error) { - if err := _c.check(); err != nil { - return nil, err - } - _node, _spec := _c.createSpec() - if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - if _spec.ID.Value != nil { - if id, ok := _spec.ID.Value.(string); ok { - _node.ID = id - } else { - return nil, fmt.Errorf("unexpected Role.ID type: %T", _spec.ID.Value) - } - } - _c.mutation.id = &_node.ID - _c.mutation.done = true - return _node, nil -} - -func (_c *RoleCreate) createSpec() (*Role, *sqlgraph.CreateSpec) { - var ( - _node = &Role{config: _c.config} - _spec = sqlgraph.NewCreateSpec(role.Table, sqlgraph.NewFieldSpec(role.FieldID, field.TypeString)) - ) - if id, ok := _c.mutation.ID(); ok { - _node.ID = id - _spec.ID.Value = id - } - if value, ok := _c.mutation.Name(); ok { - _spec.SetField(role.FieldName, field.TypeString, value) - _node.Name = value - } - if value, ok := _c.mutation.Description(); ok { - _spec.SetField(role.FieldDescription, field.TypeString, value) - _node.Description = value - } - if value, ok := _c.mutation.CreatedAt(); ok { - _spec.SetField(role.FieldCreatedAt, field.TypeTime, value) - _node.CreatedAt = value - } - if nodes := _c.mutation.RolePermissionsIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: role.RolePermissionsTable, - Columns: []string{role.RolePermissionsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges = append(_spec.Edges, edge) - } - if nodes := _c.mutation.UserRolesIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: role.UserRolesTable, - Columns: []string{role.UserRolesColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges = append(_spec.Edges, edge) - } - return _node, _spec -} - -// RoleCreateBulk is the builder for creating many Role entities in bulk. -type RoleCreateBulk struct { - config - err error - builders []*RoleCreate -} - -// Save creates the Role entities in the database. -func (_c *RoleCreateBulk) Save(ctx context.Context) ([]*Role, error) { - if _c.err != nil { - return nil, _c.err - } - specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) - nodes := make([]*Role, len(_c.builders)) - mutators := make([]Mutator, len(_c.builders)) - for i := range _c.builders { - func(i int, root context.Context) { - builder := _c.builders[i] - builder.defaults() - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*RoleMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err := builder.check(); err != nil { - return nil, err - } - builder.mutation = mutation - var err error - nodes[i], specs[i] = builder.createSpec() - if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) - } else { - spec := &sqlgraph.BatchCreateSpec{Nodes: specs} - // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - } - } - if err != nil { - return nil, err - } - mutation.id = &nodes[i].ID - mutation.done = true - return nodes[i], nil - }) - for i := len(builder.hooks) - 1; i >= 0; i-- { - mut = builder.hooks[i](mut) - } - mutators[i] = mut - }(i, ctx) - } - if len(mutators) > 0 { - if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { - return nil, err - } - } - return nodes, nil -} - -// SaveX is like Save, but panics if an error occurs. -func (_c *RoleCreateBulk) SaveX(ctx context.Context) []*Role { - v, err := _c.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (_c *RoleCreateBulk) Exec(ctx context.Context) error { - _, err := _c.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_c *RoleCreateBulk) ExecX(ctx context.Context) { - if err := _c.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/internal/ent/role_delete.go b/internal/ent/role_delete.go deleted file mode 100644 index 3688b06..0000000 --- a/internal/ent/role_delete.go +++ /dev/null @@ -1,88 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" - "git.dcentral.systems/toolz/goplt/internal/ent/role" -) - -// RoleDelete is the builder for deleting a Role entity. -type RoleDelete struct { - config - hooks []Hook - mutation *RoleMutation -} - -// Where appends a list predicates to the RoleDelete builder. -func (_d *RoleDelete) Where(ps ...predicate.Role) *RoleDelete { - _d.mutation.Where(ps...) - return _d -} - -// Exec executes the deletion query and returns how many vertices were deleted. -func (_d *RoleDelete) Exec(ctx context.Context) (int, error) { - return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) -} - -// ExecX is like Exec, but panics if an error occurs. -func (_d *RoleDelete) ExecX(ctx context.Context) int { - n, err := _d.Exec(ctx) - if err != nil { - panic(err) - } - return n -} - -func (_d *RoleDelete) sqlExec(ctx context.Context) (int, error) { - _spec := sqlgraph.NewDeleteSpec(role.Table, sqlgraph.NewFieldSpec(role.FieldID, field.TypeString)) - if ps := _d.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) - if err != nil && sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - _d.mutation.done = true - return affected, err -} - -// RoleDeleteOne is the builder for deleting a single Role entity. -type RoleDeleteOne struct { - _d *RoleDelete -} - -// Where appends a list predicates to the RoleDelete builder. -func (_d *RoleDeleteOne) Where(ps ...predicate.Role) *RoleDeleteOne { - _d._d.mutation.Where(ps...) - return _d -} - -// Exec executes the deletion query. -func (_d *RoleDeleteOne) Exec(ctx context.Context) error { - n, err := _d._d.Exec(ctx) - switch { - case err != nil: - return err - case n == 0: - return &NotFoundError{role.Label} - default: - return nil - } -} - -// ExecX is like Exec, but panics if an error occurs. -func (_d *RoleDeleteOne) ExecX(ctx context.Context) { - if err := _d.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/internal/ent/role_query.go b/internal/ent/role_query.go deleted file mode 100644 index c4e8e42..0000000 --- a/internal/ent/role_query.go +++ /dev/null @@ -1,682 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "database/sql/driver" - "fmt" - "math" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" - "git.dcentral.systems/toolz/goplt/internal/ent/role" - "git.dcentral.systems/toolz/goplt/internal/ent/rolepermission" - "git.dcentral.systems/toolz/goplt/internal/ent/userrole" -) - -// RoleQuery is the builder for querying Role entities. -type RoleQuery struct { - config - ctx *QueryContext - order []role.OrderOption - inters []Interceptor - predicates []predicate.Role - withRolePermissions *RolePermissionQuery - withUserRoles *UserRoleQuery - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Where adds a new predicate for the RoleQuery builder. -func (_q *RoleQuery) Where(ps ...predicate.Role) *RoleQuery { - _q.predicates = append(_q.predicates, ps...) - return _q -} - -// Limit the number of records to be returned by this query. -func (_q *RoleQuery) Limit(limit int) *RoleQuery { - _q.ctx.Limit = &limit - return _q -} - -// Offset to start from. -func (_q *RoleQuery) Offset(offset int) *RoleQuery { - _q.ctx.Offset = &offset - return _q -} - -// Unique configures the query builder to filter duplicate records on query. -// By default, unique is set to true, and can be disabled using this method. -func (_q *RoleQuery) Unique(unique bool) *RoleQuery { - _q.ctx.Unique = &unique - return _q -} - -// Order specifies how the records should be ordered. -func (_q *RoleQuery) Order(o ...role.OrderOption) *RoleQuery { - _q.order = append(_q.order, o...) - return _q -} - -// QueryRolePermissions chains the current query on the "role_permissions" edge. -func (_q *RoleQuery) QueryRolePermissions() *RolePermissionQuery { - query := (&RolePermissionClient{config: _q.config}).Query() - query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { - if err := _q.prepareQuery(ctx); err != nil { - return nil, err - } - selector := _q.sqlQuery(ctx) - if err := selector.Err(); err != nil { - return nil, err - } - step := sqlgraph.NewStep( - sqlgraph.From(role.Table, role.FieldID, selector), - sqlgraph.To(rolepermission.Table, rolepermission.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, role.RolePermissionsTable, role.RolePermissionsColumn), - ) - fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) - return fromU, nil - } - return query -} - -// QueryUserRoles chains the current query on the "user_roles" edge. -func (_q *RoleQuery) QueryUserRoles() *UserRoleQuery { - query := (&UserRoleClient{config: _q.config}).Query() - query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { - if err := _q.prepareQuery(ctx); err != nil { - return nil, err - } - selector := _q.sqlQuery(ctx) - if err := selector.Err(); err != nil { - return nil, err - } - step := sqlgraph.NewStep( - sqlgraph.From(role.Table, role.FieldID, selector), - sqlgraph.To(userrole.Table, userrole.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, role.UserRolesTable, role.UserRolesColumn), - ) - fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) - return fromU, nil - } - return query -} - -// First returns the first Role entity from the query. -// Returns a *NotFoundError when no Role was found. -func (_q *RoleQuery) First(ctx context.Context) (*Role, error) { - nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{role.Label} - } - return nodes[0], nil -} - -// FirstX is like First, but panics if an error occurs. -func (_q *RoleQuery) FirstX(ctx context.Context) *Role { - node, err := _q.First(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// FirstID returns the first Role ID from the query. -// Returns a *NotFoundError when no Role ID was found. -func (_q *RoleQuery) FirstID(ctx context.Context) (id string, err error) { - var ids []string - if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{role.Label} - return - } - return ids[0], nil -} - -// FirstIDX is like FirstID, but panics if an error occurs. -func (_q *RoleQuery) FirstIDX(ctx context.Context) string { - id, err := _q.FirstID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Only returns a single Role entity found by the query, ensuring it only returns one. -// Returns a *NotSingularError when more than one Role entity is found. -// Returns a *NotFoundError when no Role entities are found. -func (_q *RoleQuery) Only(ctx context.Context) (*Role, error) { - nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) - if err != nil { - return nil, err - } - switch len(nodes) { - case 1: - return nodes[0], nil - case 0: - return nil, &NotFoundError{role.Label} - default: - return nil, &NotSingularError{role.Label} - } -} - -// OnlyX is like Only, but panics if an error occurs. -func (_q *RoleQuery) OnlyX(ctx context.Context) *Role { - node, err := _q.Only(ctx) - if err != nil { - panic(err) - } - return node -} - -// OnlyID is like Only, but returns the only Role ID in the query. -// Returns a *NotSingularError when more than one Role ID is found. -// Returns a *NotFoundError when no entities are found. -func (_q *RoleQuery) OnlyID(ctx context.Context) (id string, err error) { - var ids []string - if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { - return - } - switch len(ids) { - case 1: - id = ids[0] - case 0: - err = &NotFoundError{role.Label} - default: - err = &NotSingularError{role.Label} - } - return -} - -// OnlyIDX is like OnlyID, but panics if an error occurs. -func (_q *RoleQuery) OnlyIDX(ctx context.Context) string { - id, err := _q.OnlyID(ctx) - if err != nil { - panic(err) - } - return id -} - -// All executes the query and returns a list of Roles. -func (_q *RoleQuery) All(ctx context.Context) ([]*Role, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) - if err := _q.prepareQuery(ctx); err != nil { - return nil, err - } - qr := querierAll[[]*Role, *RoleQuery]() - return withInterceptors[[]*Role](ctx, _q, qr, _q.inters) -} - -// AllX is like All, but panics if an error occurs. -func (_q *RoleQuery) AllX(ctx context.Context) []*Role { - nodes, err := _q.All(ctx) - if err != nil { - panic(err) - } - return nodes -} - -// IDs executes the query and returns a list of Role IDs. -func (_q *RoleQuery) IDs(ctx context.Context) (ids []string, err error) { - if _q.ctx.Unique == nil && _q.path != nil { - _q.Unique(true) - } - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) - if err = _q.Select(role.FieldID).Scan(ctx, &ids); err != nil { - return nil, err - } - return ids, nil -} - -// IDsX is like IDs, but panics if an error occurs. -func (_q *RoleQuery) IDsX(ctx context.Context) []string { - ids, err := _q.IDs(ctx) - if err != nil { - panic(err) - } - return ids -} - -// Count returns the count of the given query. -func (_q *RoleQuery) Count(ctx context.Context) (int, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) - if err := _q.prepareQuery(ctx); err != nil { - return 0, err - } - return withInterceptors[int](ctx, _q, querierCount[*RoleQuery](), _q.inters) -} - -// CountX is like Count, but panics if an error occurs. -func (_q *RoleQuery) CountX(ctx context.Context) int { - count, err := _q.Count(ctx) - if err != nil { - panic(err) - } - return count -} - -// Exist returns true if the query has elements in the graph. -func (_q *RoleQuery) Exist(ctx context.Context) (bool, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) - switch _, err := _q.FirstID(ctx); { - case IsNotFound(err): - return false, nil - case err != nil: - return false, fmt.Errorf("ent: check existence: %w", err) - default: - return true, nil - } -} - -// ExistX is like Exist, but panics if an error occurs. -func (_q *RoleQuery) ExistX(ctx context.Context) bool { - exist, err := _q.Exist(ctx) - if err != nil { - panic(err) - } - return exist -} - -// Clone returns a duplicate of the RoleQuery builder, including all associated steps. It can be -// used to prepare common query builders and use them differently after the clone is made. -func (_q *RoleQuery) Clone() *RoleQuery { - if _q == nil { - return nil - } - return &RoleQuery{ - config: _q.config, - ctx: _q.ctx.Clone(), - order: append([]role.OrderOption{}, _q.order...), - inters: append([]Interceptor{}, _q.inters...), - predicates: append([]predicate.Role{}, _q.predicates...), - withRolePermissions: _q.withRolePermissions.Clone(), - withUserRoles: _q.withUserRoles.Clone(), - // clone intermediate query. - sql: _q.sql.Clone(), - path: _q.path, - } -} - -// WithRolePermissions tells the query-builder to eager-load the nodes that are connected to -// the "role_permissions" edge. The optional arguments are used to configure the query builder of the edge. -func (_q *RoleQuery) WithRolePermissions(opts ...func(*RolePermissionQuery)) *RoleQuery { - query := (&RolePermissionClient{config: _q.config}).Query() - for _, opt := range opts { - opt(query) - } - _q.withRolePermissions = query - return _q -} - -// WithUserRoles tells the query-builder to eager-load the nodes that are connected to -// the "user_roles" edge. The optional arguments are used to configure the query builder of the edge. -func (_q *RoleQuery) WithUserRoles(opts ...func(*UserRoleQuery)) *RoleQuery { - query := (&UserRoleClient{config: _q.config}).Query() - for _, opt := range opts { - opt(query) - } - _q.withUserRoles = query - return _q -} - -// GroupBy is used to group vertices by one or more fields/columns. -// It is often used with aggregate functions, like: count, max, mean, min, sum. -// -// Example: -// -// var v []struct { -// Name string `json:"name,omitempty"` -// Count int `json:"count,omitempty"` -// } -// -// client.Role.Query(). -// GroupBy(role.FieldName). -// Aggregate(ent.Count()). -// Scan(ctx, &v) -func (_q *RoleQuery) GroupBy(field string, fields ...string) *RoleGroupBy { - _q.ctx.Fields = append([]string{field}, fields...) - grbuild := &RoleGroupBy{build: _q} - grbuild.flds = &_q.ctx.Fields - grbuild.label = role.Label - grbuild.scan = grbuild.Scan - return grbuild -} - -// Select allows the selection one or more fields/columns for the given query, -// instead of selecting all fields in the entity. -// -// Example: -// -// var v []struct { -// Name string `json:"name,omitempty"` -// } -// -// client.Role.Query(). -// Select(role.FieldName). -// Scan(ctx, &v) -func (_q *RoleQuery) Select(fields ...string) *RoleSelect { - _q.ctx.Fields = append(_q.ctx.Fields, fields...) - sbuild := &RoleSelect{RoleQuery: _q} - sbuild.label = role.Label - sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan - return sbuild -} - -// Aggregate returns a RoleSelect configured with the given aggregations. -func (_q *RoleQuery) Aggregate(fns ...AggregateFunc) *RoleSelect { - return _q.Select().Aggregate(fns...) -} - -func (_q *RoleQuery) prepareQuery(ctx context.Context) error { - for _, inter := range _q.inters { - if inter == nil { - return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") - } - if trv, ok := inter.(Traverser); ok { - if err := trv.Traverse(ctx, _q); err != nil { - return err - } - } - } - for _, f := range _q.ctx.Fields { - if !role.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} - } - } - if _q.path != nil { - prev, err := _q.path(ctx) - if err != nil { - return err - } - _q.sql = prev - } - return nil -} - -func (_q *RoleQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Role, error) { - var ( - nodes = []*Role{} - _spec = _q.querySpec() - loadedTypes = [2]bool{ - _q.withRolePermissions != nil, - _q.withUserRoles != nil, - } - ) - _spec.ScanValues = func(columns []string) ([]any, error) { - return (*Role).scanValues(nil, columns) - } - _spec.Assign = func(columns []string, values []any) error { - node := &Role{config: _q.config} - nodes = append(nodes, node) - node.Edges.loadedTypes = loadedTypes - return node.assignValues(columns, values) - } - for i := range hooks { - hooks[i](ctx, _spec) - } - if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { - return nil, err - } - if len(nodes) == 0 { - return nodes, nil - } - if query := _q.withRolePermissions; query != nil { - if err := _q.loadRolePermissions(ctx, query, nodes, - func(n *Role) { n.Edges.RolePermissions = []*RolePermission{} }, - func(n *Role, e *RolePermission) { n.Edges.RolePermissions = append(n.Edges.RolePermissions, e) }); err != nil { - return nil, err - } - } - if query := _q.withUserRoles; query != nil { - if err := _q.loadUserRoles(ctx, query, nodes, - func(n *Role) { n.Edges.UserRoles = []*UserRole{} }, - func(n *Role, e *UserRole) { n.Edges.UserRoles = append(n.Edges.UserRoles, e) }); err != nil { - return nil, err - } - } - return nodes, nil -} - -func (_q *RoleQuery) loadRolePermissions(ctx context.Context, query *RolePermissionQuery, nodes []*Role, init func(*Role), assign func(*Role, *RolePermission)) error { - fks := make([]driver.Value, 0, len(nodes)) - nodeids := make(map[string]*Role) - for i := range nodes { - fks = append(fks, nodes[i].ID) - nodeids[nodes[i].ID] = nodes[i] - if init != nil { - init(nodes[i]) - } - } - query.withFKs = true - query.Where(predicate.RolePermission(func(s *sql.Selector) { - s.Where(sql.InValues(s.C(role.RolePermissionsColumn), fks...)) - })) - neighbors, err := query.All(ctx) - if err != nil { - return err - } - for _, n := range neighbors { - fk := n.role_role_permissions - if fk == nil { - return fmt.Errorf(`foreign-key "role_role_permissions" is nil for node %v`, n.ID) - } - node, ok := nodeids[*fk] - if !ok { - return fmt.Errorf(`unexpected referenced foreign-key "role_role_permissions" returned %v for node %v`, *fk, n.ID) - } - assign(node, n) - } - return nil -} -func (_q *RoleQuery) loadUserRoles(ctx context.Context, query *UserRoleQuery, nodes []*Role, init func(*Role), assign func(*Role, *UserRole)) error { - fks := make([]driver.Value, 0, len(nodes)) - nodeids := make(map[string]*Role) - for i := range nodes { - fks = append(fks, nodes[i].ID) - nodeids[nodes[i].ID] = nodes[i] - if init != nil { - init(nodes[i]) - } - } - query.withFKs = true - query.Where(predicate.UserRole(func(s *sql.Selector) { - s.Where(sql.InValues(s.C(role.UserRolesColumn), fks...)) - })) - neighbors, err := query.All(ctx) - if err != nil { - return err - } - for _, n := range neighbors { - fk := n.role_user_roles - if fk == nil { - return fmt.Errorf(`foreign-key "role_user_roles" is nil for node %v`, n.ID) - } - node, ok := nodeids[*fk] - if !ok { - return fmt.Errorf(`unexpected referenced foreign-key "role_user_roles" returned %v for node %v`, *fk, n.ID) - } - assign(node, n) - } - return nil -} - -func (_q *RoleQuery) sqlCount(ctx context.Context) (int, error) { - _spec := _q.querySpec() - _spec.Node.Columns = _q.ctx.Fields - if len(_q.ctx.Fields) > 0 { - _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique - } - return sqlgraph.CountNodes(ctx, _q.driver, _spec) -} - -func (_q *RoleQuery) querySpec() *sqlgraph.QuerySpec { - _spec := sqlgraph.NewQuerySpec(role.Table, role.Columns, sqlgraph.NewFieldSpec(role.FieldID, field.TypeString)) - _spec.From = _q.sql - if unique := _q.ctx.Unique; unique != nil { - _spec.Unique = *unique - } else if _q.path != nil { - _spec.Unique = true - } - if fields := _q.ctx.Fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, role.FieldID) - for i := range fields { - if fields[i] != role.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) - } - } - } - if ps := _q.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if limit := _q.ctx.Limit; limit != nil { - _spec.Limit = *limit - } - if offset := _q.ctx.Offset; offset != nil { - _spec.Offset = *offset - } - if ps := _q.order; len(ps) > 0 { - _spec.Order = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return _spec -} - -func (_q *RoleQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(_q.driver.Dialect()) - t1 := builder.Table(role.Table) - columns := _q.ctx.Fields - if len(columns) == 0 { - columns = role.Columns - } - selector := builder.Select(t1.Columns(columns...)...).From(t1) - if _q.sql != nil { - selector = _q.sql - selector.Select(selector.Columns(columns...)...) - } - if _q.ctx.Unique != nil && *_q.ctx.Unique { - selector.Distinct() - } - for _, p := range _q.predicates { - p(selector) - } - for _, p := range _q.order { - p(selector) - } - if offset := _q.ctx.Offset; offset != nil { - // limit is mandatory for offset clause. We start - // with default value, and override it below if needed. - selector.Offset(*offset).Limit(math.MaxInt32) - } - if limit := _q.ctx.Limit; limit != nil { - selector.Limit(*limit) - } - return selector -} - -// RoleGroupBy is the group-by builder for Role entities. -type RoleGroupBy struct { - selector - build *RoleQuery -} - -// Aggregate adds the given aggregation functions to the group-by query. -func (_g *RoleGroupBy) Aggregate(fns ...AggregateFunc) *RoleGroupBy { - _g.fns = append(_g.fns, fns...) - return _g -} - -// Scan applies the selector query and scans the result into the given value. -func (_g *RoleGroupBy) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) - if err := _g.build.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*RoleQuery, *RoleGroupBy](ctx, _g.build, _g, _g.build.inters, v) -} - -func (_g *RoleGroupBy) sqlScan(ctx context.Context, root *RoleQuery, v any) error { - selector := root.sqlQuery(ctx).Select() - aggregation := make([]string, 0, len(_g.fns)) - for _, fn := range _g.fns { - aggregation = append(aggregation, fn(selector)) - } - if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) - for _, f := range *_g.flds { - columns = append(columns, selector.C(f)) - } - columns = append(columns, aggregation...) - selector.Select(columns...) - } - selector.GroupBy(selector.Columns(*_g.flds...)...) - if err := selector.Err(); err != nil { - return err - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} - -// RoleSelect is the builder for selecting fields of Role entities. -type RoleSelect struct { - *RoleQuery - selector -} - -// Aggregate adds the given aggregation functions to the selector query. -func (_s *RoleSelect) Aggregate(fns ...AggregateFunc) *RoleSelect { - _s.fns = append(_s.fns, fns...) - return _s -} - -// Scan applies the selector query and scans the result into the given value. -func (_s *RoleSelect) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) - if err := _s.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*RoleQuery, *RoleSelect](ctx, _s.RoleQuery, _s, _s.inters, v) -} - -func (_s *RoleSelect) sqlScan(ctx context.Context, root *RoleQuery, v any) error { - selector := root.sqlQuery(ctx) - aggregation := make([]string, 0, len(_s.fns)) - for _, fn := range _s.fns { - aggregation = append(aggregation, fn(selector)) - } - switch n := len(*_s.selector.flds); { - case n == 0 && len(aggregation) > 0: - selector.Select(aggregation...) - case n != 0 && len(aggregation) > 0: - selector.AppendSelect(aggregation...) - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := _s.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} diff --git a/internal/ent/role_update.go b/internal/ent/role_update.go deleted file mode 100644 index c100bcf..0000000 --- a/internal/ent/role_update.go +++ /dev/null @@ -1,613 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "errors" - "fmt" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" - "git.dcentral.systems/toolz/goplt/internal/ent/role" - "git.dcentral.systems/toolz/goplt/internal/ent/rolepermission" - "git.dcentral.systems/toolz/goplt/internal/ent/userrole" -) - -// RoleUpdate is the builder for updating Role entities. -type RoleUpdate struct { - config - hooks []Hook - mutation *RoleMutation -} - -// Where appends a list predicates to the RoleUpdate builder. -func (_u *RoleUpdate) Where(ps ...predicate.Role) *RoleUpdate { - _u.mutation.Where(ps...) - return _u -} - -// SetName sets the "name" field. -func (_u *RoleUpdate) SetName(v string) *RoleUpdate { - _u.mutation.SetName(v) - return _u -} - -// SetNillableName sets the "name" field if the given value is not nil. -func (_u *RoleUpdate) SetNillableName(v *string) *RoleUpdate { - if v != nil { - _u.SetName(*v) - } - return _u -} - -// SetDescription sets the "description" field. -func (_u *RoleUpdate) SetDescription(v string) *RoleUpdate { - _u.mutation.SetDescription(v) - return _u -} - -// SetNillableDescription sets the "description" field if the given value is not nil. -func (_u *RoleUpdate) SetNillableDescription(v *string) *RoleUpdate { - if v != nil { - _u.SetDescription(*v) - } - return _u -} - -// ClearDescription clears the value of the "description" field. -func (_u *RoleUpdate) ClearDescription() *RoleUpdate { - _u.mutation.ClearDescription() - return _u -} - -// AddRolePermissionIDs adds the "role_permissions" edge to the RolePermission entity by IDs. -func (_u *RoleUpdate) AddRolePermissionIDs(ids ...int) *RoleUpdate { - _u.mutation.AddRolePermissionIDs(ids...) - return _u -} - -// AddRolePermissions adds the "role_permissions" edges to the RolePermission entity. -func (_u *RoleUpdate) AddRolePermissions(v ...*RolePermission) *RoleUpdate { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.AddRolePermissionIDs(ids...) -} - -// AddUserRoleIDs adds the "user_roles" edge to the UserRole entity by IDs. -func (_u *RoleUpdate) AddUserRoleIDs(ids ...int) *RoleUpdate { - _u.mutation.AddUserRoleIDs(ids...) - return _u -} - -// AddUserRoles adds the "user_roles" edges to the UserRole entity. -func (_u *RoleUpdate) AddUserRoles(v ...*UserRole) *RoleUpdate { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.AddUserRoleIDs(ids...) -} - -// Mutation returns the RoleMutation object of the builder. -func (_u *RoleUpdate) Mutation() *RoleMutation { - return _u.mutation -} - -// ClearRolePermissions clears all "role_permissions" edges to the RolePermission entity. -func (_u *RoleUpdate) ClearRolePermissions() *RoleUpdate { - _u.mutation.ClearRolePermissions() - return _u -} - -// RemoveRolePermissionIDs removes the "role_permissions" edge to RolePermission entities by IDs. -func (_u *RoleUpdate) RemoveRolePermissionIDs(ids ...int) *RoleUpdate { - _u.mutation.RemoveRolePermissionIDs(ids...) - return _u -} - -// RemoveRolePermissions removes "role_permissions" edges to RolePermission entities. -func (_u *RoleUpdate) RemoveRolePermissions(v ...*RolePermission) *RoleUpdate { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.RemoveRolePermissionIDs(ids...) -} - -// ClearUserRoles clears all "user_roles" edges to the UserRole entity. -func (_u *RoleUpdate) ClearUserRoles() *RoleUpdate { - _u.mutation.ClearUserRoles() - return _u -} - -// RemoveUserRoleIDs removes the "user_roles" edge to UserRole entities by IDs. -func (_u *RoleUpdate) RemoveUserRoleIDs(ids ...int) *RoleUpdate { - _u.mutation.RemoveUserRoleIDs(ids...) - return _u -} - -// RemoveUserRoles removes "user_roles" edges to UserRole entities. -func (_u *RoleUpdate) RemoveUserRoles(v ...*UserRole) *RoleUpdate { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.RemoveUserRoleIDs(ids...) -} - -// Save executes the query and returns the number of nodes affected by the update operation. -func (_u *RoleUpdate) Save(ctx context.Context) (int, error) { - return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (_u *RoleUpdate) SaveX(ctx context.Context) int { - affected, err := _u.Save(ctx) - if err != nil { - panic(err) - } - return affected -} - -// Exec executes the query. -func (_u *RoleUpdate) Exec(ctx context.Context) error { - _, err := _u.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_u *RoleUpdate) ExecX(ctx context.Context) { - if err := _u.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (_u *RoleUpdate) check() error { - if v, ok := _u.mutation.Name(); ok { - if err := role.NameValidator(v); err != nil { - return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Role.name": %w`, err)} - } - } - return nil -} - -func (_u *RoleUpdate) sqlSave(ctx context.Context) (_node int, err error) { - if err := _u.check(); err != nil { - return _node, err - } - _spec := sqlgraph.NewUpdateSpec(role.Table, role.Columns, sqlgraph.NewFieldSpec(role.FieldID, field.TypeString)) - if ps := _u.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := _u.mutation.Name(); ok { - _spec.SetField(role.FieldName, field.TypeString, value) - } - if value, ok := _u.mutation.Description(); ok { - _spec.SetField(role.FieldDescription, field.TypeString, value) - } - if _u.mutation.DescriptionCleared() { - _spec.ClearField(role.FieldDescription, field.TypeString) - } - if _u.mutation.RolePermissionsCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: role.RolePermissionsTable, - Columns: []string{role.RolePermissionsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.RemovedRolePermissionsIDs(); len(nodes) > 0 && !_u.mutation.RolePermissionsCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: role.RolePermissionsTable, - Columns: []string{role.RolePermissionsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.RolePermissionsIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: role.RolePermissionsTable, - Columns: []string{role.RolePermissionsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - if _u.mutation.UserRolesCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: role.UserRolesTable, - Columns: []string{role.UserRolesColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.RemovedUserRolesIDs(); len(nodes) > 0 && !_u.mutation.UserRolesCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: role.UserRolesTable, - Columns: []string{role.UserRolesColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.UserRolesIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: role.UserRolesTable, - Columns: []string{role.UserRolesColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{role.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return 0, err - } - _u.mutation.done = true - return _node, nil -} - -// RoleUpdateOne is the builder for updating a single Role entity. -type RoleUpdateOne struct { - config - fields []string - hooks []Hook - mutation *RoleMutation -} - -// SetName sets the "name" field. -func (_u *RoleUpdateOne) SetName(v string) *RoleUpdateOne { - _u.mutation.SetName(v) - return _u -} - -// SetNillableName sets the "name" field if the given value is not nil. -func (_u *RoleUpdateOne) SetNillableName(v *string) *RoleUpdateOne { - if v != nil { - _u.SetName(*v) - } - return _u -} - -// SetDescription sets the "description" field. -func (_u *RoleUpdateOne) SetDescription(v string) *RoleUpdateOne { - _u.mutation.SetDescription(v) - return _u -} - -// SetNillableDescription sets the "description" field if the given value is not nil. -func (_u *RoleUpdateOne) SetNillableDescription(v *string) *RoleUpdateOne { - if v != nil { - _u.SetDescription(*v) - } - return _u -} - -// ClearDescription clears the value of the "description" field. -func (_u *RoleUpdateOne) ClearDescription() *RoleUpdateOne { - _u.mutation.ClearDescription() - return _u -} - -// AddRolePermissionIDs adds the "role_permissions" edge to the RolePermission entity by IDs. -func (_u *RoleUpdateOne) AddRolePermissionIDs(ids ...int) *RoleUpdateOne { - _u.mutation.AddRolePermissionIDs(ids...) - return _u -} - -// AddRolePermissions adds the "role_permissions" edges to the RolePermission entity. -func (_u *RoleUpdateOne) AddRolePermissions(v ...*RolePermission) *RoleUpdateOne { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.AddRolePermissionIDs(ids...) -} - -// AddUserRoleIDs adds the "user_roles" edge to the UserRole entity by IDs. -func (_u *RoleUpdateOne) AddUserRoleIDs(ids ...int) *RoleUpdateOne { - _u.mutation.AddUserRoleIDs(ids...) - return _u -} - -// AddUserRoles adds the "user_roles" edges to the UserRole entity. -func (_u *RoleUpdateOne) AddUserRoles(v ...*UserRole) *RoleUpdateOne { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.AddUserRoleIDs(ids...) -} - -// Mutation returns the RoleMutation object of the builder. -func (_u *RoleUpdateOne) Mutation() *RoleMutation { - return _u.mutation -} - -// ClearRolePermissions clears all "role_permissions" edges to the RolePermission entity. -func (_u *RoleUpdateOne) ClearRolePermissions() *RoleUpdateOne { - _u.mutation.ClearRolePermissions() - return _u -} - -// RemoveRolePermissionIDs removes the "role_permissions" edge to RolePermission entities by IDs. -func (_u *RoleUpdateOne) RemoveRolePermissionIDs(ids ...int) *RoleUpdateOne { - _u.mutation.RemoveRolePermissionIDs(ids...) - return _u -} - -// RemoveRolePermissions removes "role_permissions" edges to RolePermission entities. -func (_u *RoleUpdateOne) RemoveRolePermissions(v ...*RolePermission) *RoleUpdateOne { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.RemoveRolePermissionIDs(ids...) -} - -// ClearUserRoles clears all "user_roles" edges to the UserRole entity. -func (_u *RoleUpdateOne) ClearUserRoles() *RoleUpdateOne { - _u.mutation.ClearUserRoles() - return _u -} - -// RemoveUserRoleIDs removes the "user_roles" edge to UserRole entities by IDs. -func (_u *RoleUpdateOne) RemoveUserRoleIDs(ids ...int) *RoleUpdateOne { - _u.mutation.RemoveUserRoleIDs(ids...) - return _u -} - -// RemoveUserRoles removes "user_roles" edges to UserRole entities. -func (_u *RoleUpdateOne) RemoveUserRoles(v ...*UserRole) *RoleUpdateOne { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.RemoveUserRoleIDs(ids...) -} - -// Where appends a list predicates to the RoleUpdate builder. -func (_u *RoleUpdateOne) Where(ps ...predicate.Role) *RoleUpdateOne { - _u.mutation.Where(ps...) - return _u -} - -// Select allows selecting one or more fields (columns) of the returned entity. -// The default is selecting all fields defined in the entity schema. -func (_u *RoleUpdateOne) Select(field string, fields ...string) *RoleUpdateOne { - _u.fields = append([]string{field}, fields...) - return _u -} - -// Save executes the query and returns the updated Role entity. -func (_u *RoleUpdateOne) Save(ctx context.Context) (*Role, error) { - return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (_u *RoleUpdateOne) SaveX(ctx context.Context) *Role { - node, err := _u.Save(ctx) - if err != nil { - panic(err) - } - return node -} - -// Exec executes the query on the entity. -func (_u *RoleUpdateOne) Exec(ctx context.Context) error { - _, err := _u.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_u *RoleUpdateOne) ExecX(ctx context.Context) { - if err := _u.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (_u *RoleUpdateOne) check() error { - if v, ok := _u.mutation.Name(); ok { - if err := role.NameValidator(v); err != nil { - return &ValidationError{Name: "name", err: fmt.Errorf(`ent: validator failed for field "Role.name": %w`, err)} - } - } - return nil -} - -func (_u *RoleUpdateOne) sqlSave(ctx context.Context) (_node *Role, err error) { - if err := _u.check(); err != nil { - return _node, err - } - _spec := sqlgraph.NewUpdateSpec(role.Table, role.Columns, sqlgraph.NewFieldSpec(role.FieldID, field.TypeString)) - id, ok := _u.mutation.ID() - if !ok { - return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Role.id" for update`)} - } - _spec.Node.ID.Value = id - if fields := _u.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, role.FieldID) - for _, f := range fields { - if !role.ValidColumn(f) { - return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} - } - if f != role.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, f) - } - } - } - if ps := _u.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := _u.mutation.Name(); ok { - _spec.SetField(role.FieldName, field.TypeString, value) - } - if value, ok := _u.mutation.Description(); ok { - _spec.SetField(role.FieldDescription, field.TypeString, value) - } - if _u.mutation.DescriptionCleared() { - _spec.ClearField(role.FieldDescription, field.TypeString) - } - if _u.mutation.RolePermissionsCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: role.RolePermissionsTable, - Columns: []string{role.RolePermissionsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.RemovedRolePermissionsIDs(); len(nodes) > 0 && !_u.mutation.RolePermissionsCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: role.RolePermissionsTable, - Columns: []string{role.RolePermissionsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.RolePermissionsIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: role.RolePermissionsTable, - Columns: []string{role.RolePermissionsColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - if _u.mutation.UserRolesCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: role.UserRolesTable, - Columns: []string{role.UserRolesColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.RemovedUserRolesIDs(); len(nodes) > 0 && !_u.mutation.UserRolesCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: role.UserRolesTable, - Columns: []string{role.UserRolesColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.UserRolesIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: role.UserRolesTable, - Columns: []string{role.UserRolesColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - _node = &Role{config: _u.config} - _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{role.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - _u.mutation.done = true - return _node, nil -} diff --git a/internal/ent/rolepermission.go b/internal/ent/rolepermission.go deleted file mode 100644 index c92e26a..0000000 --- a/internal/ent/rolepermission.go +++ /dev/null @@ -1,182 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "fmt" - "strings" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "git.dcentral.systems/toolz/goplt/internal/ent/permission" - "git.dcentral.systems/toolz/goplt/internal/ent/role" - "git.dcentral.systems/toolz/goplt/internal/ent/rolepermission" -) - -// RolePermission is the model entity for the RolePermission schema. -type RolePermission struct { - config `json:"-"` - // ID of the ent. - ID int `json:"id,omitempty"` - // RoleID holds the value of the "role_id" field. - RoleID string `json:"role_id,omitempty"` - // PermissionID holds the value of the "permission_id" field. - PermissionID string `json:"permission_id,omitempty"` - // Edges holds the relations/edges for other nodes in the graph. - // The values are being populated by the RolePermissionQuery when eager-loading is set. - Edges RolePermissionEdges `json:"edges"` - permission_role_permissions *string - role_role_permissions *string - selectValues sql.SelectValues -} - -// RolePermissionEdges holds the relations/edges for other nodes in the graph. -type RolePermissionEdges struct { - // Role holds the value of the role edge. - Role *Role `json:"role,omitempty"` - // Permission holds the value of the permission edge. - Permission *Permission `json:"permission,omitempty"` - // loadedTypes holds the information for reporting if a - // type was loaded (or requested) in eager-loading or not. - loadedTypes [2]bool -} - -// RoleOrErr returns the Role value or an error if the edge -// was not loaded in eager-loading, or loaded but was not found. -func (e RolePermissionEdges) RoleOrErr() (*Role, error) { - if e.Role != nil { - return e.Role, nil - } else if e.loadedTypes[0] { - return nil, &NotFoundError{label: role.Label} - } - return nil, &NotLoadedError{edge: "role"} -} - -// PermissionOrErr returns the Permission value or an error if the edge -// was not loaded in eager-loading, or loaded but was not found. -func (e RolePermissionEdges) PermissionOrErr() (*Permission, error) { - if e.Permission != nil { - return e.Permission, nil - } else if e.loadedTypes[1] { - return nil, &NotFoundError{label: permission.Label} - } - return nil, &NotLoadedError{edge: "permission"} -} - -// scanValues returns the types for scanning values from sql.Rows. -func (*RolePermission) scanValues(columns []string) ([]any, error) { - values := make([]any, len(columns)) - for i := range columns { - switch columns[i] { - case rolepermission.FieldID: - values[i] = new(sql.NullInt64) - case rolepermission.FieldRoleID, rolepermission.FieldPermissionID: - values[i] = new(sql.NullString) - case rolepermission.ForeignKeys[0]: // permission_role_permissions - values[i] = new(sql.NullString) - case rolepermission.ForeignKeys[1]: // role_role_permissions - values[i] = new(sql.NullString) - default: - values[i] = new(sql.UnknownType) - } - } - return values, nil -} - -// assignValues assigns the values that were returned from sql.Rows (after scanning) -// to the RolePermission fields. -func (_m *RolePermission) assignValues(columns []string, values []any) error { - if m, n := len(values), len(columns); m < n { - return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) - } - for i := range columns { - switch columns[i] { - case rolepermission.FieldID: - value, ok := values[i].(*sql.NullInt64) - if !ok { - return fmt.Errorf("unexpected type %T for field id", value) - } - _m.ID = int(value.Int64) - case rolepermission.FieldRoleID: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field role_id", values[i]) - } else if value.Valid { - _m.RoleID = value.String - } - case rolepermission.FieldPermissionID: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field permission_id", values[i]) - } else if value.Valid { - _m.PermissionID = value.String - } - case rolepermission.ForeignKeys[0]: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field permission_role_permissions", values[i]) - } else if value.Valid { - _m.permission_role_permissions = new(string) - *_m.permission_role_permissions = value.String - } - case rolepermission.ForeignKeys[1]: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field role_role_permissions", values[i]) - } else if value.Valid { - _m.role_role_permissions = new(string) - *_m.role_role_permissions = value.String - } - default: - _m.selectValues.Set(columns[i], values[i]) - } - } - return nil -} - -// Value returns the ent.Value that was dynamically selected and assigned to the RolePermission. -// This includes values selected through modifiers, order, etc. -func (_m *RolePermission) Value(name string) (ent.Value, error) { - return _m.selectValues.Get(name) -} - -// QueryRole queries the "role" edge of the RolePermission entity. -func (_m *RolePermission) QueryRole() *RoleQuery { - return NewRolePermissionClient(_m.config).QueryRole(_m) -} - -// QueryPermission queries the "permission" edge of the RolePermission entity. -func (_m *RolePermission) QueryPermission() *PermissionQuery { - return NewRolePermissionClient(_m.config).QueryPermission(_m) -} - -// Update returns a builder for updating this RolePermission. -// Note that you need to call RolePermission.Unwrap() before calling this method if this RolePermission -// was returned from a transaction, and the transaction was committed or rolled back. -func (_m *RolePermission) Update() *RolePermissionUpdateOne { - return NewRolePermissionClient(_m.config).UpdateOne(_m) -} - -// Unwrap unwraps the RolePermission entity that was returned from a transaction after it was closed, -// so that all future queries will be executed through the driver which created the transaction. -func (_m *RolePermission) Unwrap() *RolePermission { - _tx, ok := _m.config.driver.(*txDriver) - if !ok { - panic("ent: RolePermission is not a transactional entity") - } - _m.config.driver = _tx.drv - return _m -} - -// String implements the fmt.Stringer. -func (_m *RolePermission) String() string { - var builder strings.Builder - builder.WriteString("RolePermission(") - builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) - builder.WriteString("role_id=") - builder.WriteString(_m.RoleID) - builder.WriteString(", ") - builder.WriteString("permission_id=") - builder.WriteString(_m.PermissionID) - builder.WriteByte(')') - return builder.String() -} - -// RolePermissions is a parsable slice of RolePermission. -type RolePermissions []*RolePermission diff --git a/internal/ent/rolepermission/rolepermission.go b/internal/ent/rolepermission/rolepermission.go deleted file mode 100644 index 74260d3..0000000 --- a/internal/ent/rolepermission/rolepermission.go +++ /dev/null @@ -1,114 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package rolepermission - -import ( - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" -) - -const ( - // Label holds the string label denoting the rolepermission type in the database. - Label = "role_permission" - // FieldID holds the string denoting the id field in the database. - FieldID = "id" - // FieldRoleID holds the string denoting the role_id field in the database. - FieldRoleID = "role_id" - // FieldPermissionID holds the string denoting the permission_id field in the database. - FieldPermissionID = "permission_id" - // EdgeRole holds the string denoting the role edge name in mutations. - EdgeRole = "role" - // EdgePermission holds the string denoting the permission edge name in mutations. - EdgePermission = "permission" - // Table holds the table name of the rolepermission in the database. - Table = "role_permissions" - // RoleTable is the table that holds the role relation/edge. - RoleTable = "role_permissions" - // RoleInverseTable is the table name for the Role entity. - // It exists in this package in order to avoid circular dependency with the "role" package. - RoleInverseTable = "roles" - // RoleColumn is the table column denoting the role relation/edge. - RoleColumn = "role_id" - // PermissionTable is the table that holds the permission relation/edge. - PermissionTable = "role_permissions" - // PermissionInverseTable is the table name for the Permission entity. - // It exists in this package in order to avoid circular dependency with the "permission" package. - PermissionInverseTable = "permissions" - // PermissionColumn is the table column denoting the permission relation/edge. - PermissionColumn = "permission_id" -) - -// Columns holds all SQL columns for rolepermission fields. -var Columns = []string{ - FieldID, - FieldRoleID, - FieldPermissionID, -} - -// ForeignKeys holds the SQL foreign-keys that are owned by the "role_permissions" -// table and are not defined as standalone fields in the schema. -var ForeignKeys = []string{ - "permission_role_permissions", - "role_role_permissions", -} - -// ValidColumn reports if the column name is valid (part of the table columns). -func ValidColumn(column string) bool { - for i := range Columns { - if column == Columns[i] { - return true - } - } - for i := range ForeignKeys { - if column == ForeignKeys[i] { - return true - } - } - return false -} - -// OrderOption defines the ordering options for the RolePermission queries. -type OrderOption func(*sql.Selector) - -// ByID orders the results by the id field. -func ByID(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldID, opts...).ToFunc() -} - -// ByRoleID orders the results by the role_id field. -func ByRoleID(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldRoleID, opts...).ToFunc() -} - -// ByPermissionID orders the results by the permission_id field. -func ByPermissionID(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldPermissionID, opts...).ToFunc() -} - -// ByRoleField orders the results by role field. -func ByRoleField(field string, opts ...sql.OrderTermOption) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborTerms(s, newRoleStep(), sql.OrderByField(field, opts...)) - } -} - -// ByPermissionField orders the results by permission field. -func ByPermissionField(field string, opts ...sql.OrderTermOption) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborTerms(s, newPermissionStep(), sql.OrderByField(field, opts...)) - } -} -func newRoleStep() *sqlgraph.Step { - return sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(RoleInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.M2O, false, RoleTable, RoleColumn), - ) -} -func newPermissionStep() *sqlgraph.Step { - return sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(PermissionInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.M2O, false, PermissionTable, PermissionColumn), - ) -} diff --git a/internal/ent/rolepermission/where.go b/internal/ent/rolepermission/where.go deleted file mode 100644 index 70539b8..0000000 --- a/internal/ent/rolepermission/where.go +++ /dev/null @@ -1,255 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package rolepermission - -import ( - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" -) - -// ID filters vertices based on their ID field. -func ID(id int) predicate.RolePermission { - return predicate.RolePermission(sql.FieldEQ(FieldID, id)) -} - -// IDEQ applies the EQ predicate on the ID field. -func IDEQ(id int) predicate.RolePermission { - return predicate.RolePermission(sql.FieldEQ(FieldID, id)) -} - -// IDNEQ applies the NEQ predicate on the ID field. -func IDNEQ(id int) predicate.RolePermission { - return predicate.RolePermission(sql.FieldNEQ(FieldID, id)) -} - -// IDIn applies the In predicate on the ID field. -func IDIn(ids ...int) predicate.RolePermission { - return predicate.RolePermission(sql.FieldIn(FieldID, ids...)) -} - -// IDNotIn applies the NotIn predicate on the ID field. -func IDNotIn(ids ...int) predicate.RolePermission { - return predicate.RolePermission(sql.FieldNotIn(FieldID, ids...)) -} - -// IDGT applies the GT predicate on the ID field. -func IDGT(id int) predicate.RolePermission { - return predicate.RolePermission(sql.FieldGT(FieldID, id)) -} - -// IDGTE applies the GTE predicate on the ID field. -func IDGTE(id int) predicate.RolePermission { - return predicate.RolePermission(sql.FieldGTE(FieldID, id)) -} - -// IDLT applies the LT predicate on the ID field. -func IDLT(id int) predicate.RolePermission { - return predicate.RolePermission(sql.FieldLT(FieldID, id)) -} - -// IDLTE applies the LTE predicate on the ID field. -func IDLTE(id int) predicate.RolePermission { - return predicate.RolePermission(sql.FieldLTE(FieldID, id)) -} - -// RoleID applies equality check predicate on the "role_id" field. It's identical to RoleIDEQ. -func RoleID(v string) predicate.RolePermission { - return predicate.RolePermission(sql.FieldEQ(FieldRoleID, v)) -} - -// PermissionID applies equality check predicate on the "permission_id" field. It's identical to PermissionIDEQ. -func PermissionID(v string) predicate.RolePermission { - return predicate.RolePermission(sql.FieldEQ(FieldPermissionID, v)) -} - -// RoleIDEQ applies the EQ predicate on the "role_id" field. -func RoleIDEQ(v string) predicate.RolePermission { - return predicate.RolePermission(sql.FieldEQ(FieldRoleID, v)) -} - -// RoleIDNEQ applies the NEQ predicate on the "role_id" field. -func RoleIDNEQ(v string) predicate.RolePermission { - return predicate.RolePermission(sql.FieldNEQ(FieldRoleID, v)) -} - -// RoleIDIn applies the In predicate on the "role_id" field. -func RoleIDIn(vs ...string) predicate.RolePermission { - return predicate.RolePermission(sql.FieldIn(FieldRoleID, vs...)) -} - -// RoleIDNotIn applies the NotIn predicate on the "role_id" field. -func RoleIDNotIn(vs ...string) predicate.RolePermission { - return predicate.RolePermission(sql.FieldNotIn(FieldRoleID, vs...)) -} - -// RoleIDGT applies the GT predicate on the "role_id" field. -func RoleIDGT(v string) predicate.RolePermission { - return predicate.RolePermission(sql.FieldGT(FieldRoleID, v)) -} - -// RoleIDGTE applies the GTE predicate on the "role_id" field. -func RoleIDGTE(v string) predicate.RolePermission { - return predicate.RolePermission(sql.FieldGTE(FieldRoleID, v)) -} - -// RoleIDLT applies the LT predicate on the "role_id" field. -func RoleIDLT(v string) predicate.RolePermission { - return predicate.RolePermission(sql.FieldLT(FieldRoleID, v)) -} - -// RoleIDLTE applies the LTE predicate on the "role_id" field. -func RoleIDLTE(v string) predicate.RolePermission { - return predicate.RolePermission(sql.FieldLTE(FieldRoleID, v)) -} - -// RoleIDContains applies the Contains predicate on the "role_id" field. -func RoleIDContains(v string) predicate.RolePermission { - return predicate.RolePermission(sql.FieldContains(FieldRoleID, v)) -} - -// RoleIDHasPrefix applies the HasPrefix predicate on the "role_id" field. -func RoleIDHasPrefix(v string) predicate.RolePermission { - return predicate.RolePermission(sql.FieldHasPrefix(FieldRoleID, v)) -} - -// RoleIDHasSuffix applies the HasSuffix predicate on the "role_id" field. -func RoleIDHasSuffix(v string) predicate.RolePermission { - return predicate.RolePermission(sql.FieldHasSuffix(FieldRoleID, v)) -} - -// RoleIDEqualFold applies the EqualFold predicate on the "role_id" field. -func RoleIDEqualFold(v string) predicate.RolePermission { - return predicate.RolePermission(sql.FieldEqualFold(FieldRoleID, v)) -} - -// RoleIDContainsFold applies the ContainsFold predicate on the "role_id" field. -func RoleIDContainsFold(v string) predicate.RolePermission { - return predicate.RolePermission(sql.FieldContainsFold(FieldRoleID, v)) -} - -// PermissionIDEQ applies the EQ predicate on the "permission_id" field. -func PermissionIDEQ(v string) predicate.RolePermission { - return predicate.RolePermission(sql.FieldEQ(FieldPermissionID, v)) -} - -// PermissionIDNEQ applies the NEQ predicate on the "permission_id" field. -func PermissionIDNEQ(v string) predicate.RolePermission { - return predicate.RolePermission(sql.FieldNEQ(FieldPermissionID, v)) -} - -// PermissionIDIn applies the In predicate on the "permission_id" field. -func PermissionIDIn(vs ...string) predicate.RolePermission { - return predicate.RolePermission(sql.FieldIn(FieldPermissionID, vs...)) -} - -// PermissionIDNotIn applies the NotIn predicate on the "permission_id" field. -func PermissionIDNotIn(vs ...string) predicate.RolePermission { - return predicate.RolePermission(sql.FieldNotIn(FieldPermissionID, vs...)) -} - -// PermissionIDGT applies the GT predicate on the "permission_id" field. -func PermissionIDGT(v string) predicate.RolePermission { - return predicate.RolePermission(sql.FieldGT(FieldPermissionID, v)) -} - -// PermissionIDGTE applies the GTE predicate on the "permission_id" field. -func PermissionIDGTE(v string) predicate.RolePermission { - return predicate.RolePermission(sql.FieldGTE(FieldPermissionID, v)) -} - -// PermissionIDLT applies the LT predicate on the "permission_id" field. -func PermissionIDLT(v string) predicate.RolePermission { - return predicate.RolePermission(sql.FieldLT(FieldPermissionID, v)) -} - -// PermissionIDLTE applies the LTE predicate on the "permission_id" field. -func PermissionIDLTE(v string) predicate.RolePermission { - return predicate.RolePermission(sql.FieldLTE(FieldPermissionID, v)) -} - -// PermissionIDContains applies the Contains predicate on the "permission_id" field. -func PermissionIDContains(v string) predicate.RolePermission { - return predicate.RolePermission(sql.FieldContains(FieldPermissionID, v)) -} - -// PermissionIDHasPrefix applies the HasPrefix predicate on the "permission_id" field. -func PermissionIDHasPrefix(v string) predicate.RolePermission { - return predicate.RolePermission(sql.FieldHasPrefix(FieldPermissionID, v)) -} - -// PermissionIDHasSuffix applies the HasSuffix predicate on the "permission_id" field. -func PermissionIDHasSuffix(v string) predicate.RolePermission { - return predicate.RolePermission(sql.FieldHasSuffix(FieldPermissionID, v)) -} - -// PermissionIDEqualFold applies the EqualFold predicate on the "permission_id" field. -func PermissionIDEqualFold(v string) predicate.RolePermission { - return predicate.RolePermission(sql.FieldEqualFold(FieldPermissionID, v)) -} - -// PermissionIDContainsFold applies the ContainsFold predicate on the "permission_id" field. -func PermissionIDContainsFold(v string) predicate.RolePermission { - return predicate.RolePermission(sql.FieldContainsFold(FieldPermissionID, v)) -} - -// HasRole applies the HasEdge predicate on the "role" edge. -func HasRole() predicate.RolePermission { - return predicate.RolePermission(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.Edge(sqlgraph.M2O, false, RoleTable, RoleColumn), - ) - sqlgraph.HasNeighbors(s, step) - }) -} - -// HasRoleWith applies the HasEdge predicate on the "role" edge with a given conditions (other predicates). -func HasRoleWith(preds ...predicate.Role) predicate.RolePermission { - return predicate.RolePermission(func(s *sql.Selector) { - step := newRoleStep() - sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { - for _, p := range preds { - p(s) - } - }) - }) -} - -// HasPermission applies the HasEdge predicate on the "permission" edge. -func HasPermission() predicate.RolePermission { - return predicate.RolePermission(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.Edge(sqlgraph.M2O, false, PermissionTable, PermissionColumn), - ) - sqlgraph.HasNeighbors(s, step) - }) -} - -// HasPermissionWith applies the HasEdge predicate on the "permission" edge with a given conditions (other predicates). -func HasPermissionWith(preds ...predicate.Permission) predicate.RolePermission { - return predicate.RolePermission(func(s *sql.Selector) { - step := newPermissionStep() - sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { - for _, p := range preds { - p(s) - } - }) - }) -} - -// And groups predicates with the AND operator between them. -func And(predicates ...predicate.RolePermission) predicate.RolePermission { - return predicate.RolePermission(sql.AndPredicates(predicates...)) -} - -// Or groups predicates with the OR operator between them. -func Or(predicates ...predicate.RolePermission) predicate.RolePermission { - return predicate.RolePermission(sql.OrPredicates(predicates...)) -} - -// Not applies the not operator on the given predicate. -func Not(p predicate.RolePermission) predicate.RolePermission { - return predicate.RolePermission(sql.NotPredicates(p)) -} diff --git a/internal/ent/rolepermission_create.go b/internal/ent/rolepermission_create.go deleted file mode 100644 index dbc1ba3..0000000 --- a/internal/ent/rolepermission_create.go +++ /dev/null @@ -1,240 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "errors" - "fmt" - - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/internal/ent/permission" - "git.dcentral.systems/toolz/goplt/internal/ent/role" - "git.dcentral.systems/toolz/goplt/internal/ent/rolepermission" -) - -// RolePermissionCreate is the builder for creating a RolePermission entity. -type RolePermissionCreate struct { - config - mutation *RolePermissionMutation - hooks []Hook -} - -// SetRoleID sets the "role_id" field. -func (_c *RolePermissionCreate) SetRoleID(v string) *RolePermissionCreate { - _c.mutation.SetRoleID(v) - return _c -} - -// SetPermissionID sets the "permission_id" field. -func (_c *RolePermissionCreate) SetPermissionID(v string) *RolePermissionCreate { - _c.mutation.SetPermissionID(v) - return _c -} - -// SetRole sets the "role" edge to the Role entity. -func (_c *RolePermissionCreate) SetRole(v *Role) *RolePermissionCreate { - return _c.SetRoleID(v.ID) -} - -// SetPermission sets the "permission" edge to the Permission entity. -func (_c *RolePermissionCreate) SetPermission(v *Permission) *RolePermissionCreate { - return _c.SetPermissionID(v.ID) -} - -// Mutation returns the RolePermissionMutation object of the builder. -func (_c *RolePermissionCreate) Mutation() *RolePermissionMutation { - return _c.mutation -} - -// Save creates the RolePermission in the database. -func (_c *RolePermissionCreate) Save(ctx context.Context) (*RolePermission, error) { - return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) -} - -// SaveX calls Save and panics if Save returns an error. -func (_c *RolePermissionCreate) SaveX(ctx context.Context) *RolePermission { - v, err := _c.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (_c *RolePermissionCreate) Exec(ctx context.Context) error { - _, err := _c.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_c *RolePermissionCreate) ExecX(ctx context.Context) { - if err := _c.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (_c *RolePermissionCreate) check() error { - if _, ok := _c.mutation.RoleID(); !ok { - return &ValidationError{Name: "role_id", err: errors.New(`ent: missing required field "RolePermission.role_id"`)} - } - if _, ok := _c.mutation.PermissionID(); !ok { - return &ValidationError{Name: "permission_id", err: errors.New(`ent: missing required field "RolePermission.permission_id"`)} - } - if len(_c.mutation.RoleIDs()) == 0 { - return &ValidationError{Name: "role", err: errors.New(`ent: missing required edge "RolePermission.role"`)} - } - if len(_c.mutation.PermissionIDs()) == 0 { - return &ValidationError{Name: "permission", err: errors.New(`ent: missing required edge "RolePermission.permission"`)} - } - return nil -} - -func (_c *RolePermissionCreate) sqlSave(ctx context.Context) (*RolePermission, error) { - if err := _c.check(); err != nil { - return nil, err - } - _node, _spec := _c.createSpec() - if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - id := _spec.ID.Value.(int64) - _node.ID = int(id) - _c.mutation.id = &_node.ID - _c.mutation.done = true - return _node, nil -} - -func (_c *RolePermissionCreate) createSpec() (*RolePermission, *sqlgraph.CreateSpec) { - var ( - _node = &RolePermission{config: _c.config} - _spec = sqlgraph.NewCreateSpec(rolepermission.Table, sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt)) - ) - if nodes := _c.mutation.RoleIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: false, - Table: rolepermission.RoleTable, - Columns: []string{rolepermission.RoleColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeString), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _node.RoleID = nodes[0] - _spec.Edges = append(_spec.Edges, edge) - } - if nodes := _c.mutation.PermissionIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: false, - Table: rolepermission.PermissionTable, - Columns: []string{rolepermission.PermissionColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(permission.FieldID, field.TypeString), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _node.PermissionID = nodes[0] - _spec.Edges = append(_spec.Edges, edge) - } - return _node, _spec -} - -// RolePermissionCreateBulk is the builder for creating many RolePermission entities in bulk. -type RolePermissionCreateBulk struct { - config - err error - builders []*RolePermissionCreate -} - -// Save creates the RolePermission entities in the database. -func (_c *RolePermissionCreateBulk) Save(ctx context.Context) ([]*RolePermission, error) { - if _c.err != nil { - return nil, _c.err - } - specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) - nodes := make([]*RolePermission, len(_c.builders)) - mutators := make([]Mutator, len(_c.builders)) - for i := range _c.builders { - func(i int, root context.Context) { - builder := _c.builders[i] - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*RolePermissionMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err := builder.check(); err != nil { - return nil, err - } - builder.mutation = mutation - var err error - nodes[i], specs[i] = builder.createSpec() - if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) - } else { - spec := &sqlgraph.BatchCreateSpec{Nodes: specs} - // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - } - } - if err != nil { - return nil, err - } - mutation.id = &nodes[i].ID - if specs[i].ID.Value != nil { - id := specs[i].ID.Value.(int64) - nodes[i].ID = int(id) - } - mutation.done = true - return nodes[i], nil - }) - for i := len(builder.hooks) - 1; i >= 0; i-- { - mut = builder.hooks[i](mut) - } - mutators[i] = mut - }(i, ctx) - } - if len(mutators) > 0 { - if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { - return nil, err - } - } - return nodes, nil -} - -// SaveX is like Save, but panics if an error occurs. -func (_c *RolePermissionCreateBulk) SaveX(ctx context.Context) []*RolePermission { - v, err := _c.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (_c *RolePermissionCreateBulk) Exec(ctx context.Context) error { - _, err := _c.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_c *RolePermissionCreateBulk) ExecX(ctx context.Context) { - if err := _c.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/internal/ent/rolepermission_delete.go b/internal/ent/rolepermission_delete.go deleted file mode 100644 index 7ac0014..0000000 --- a/internal/ent/rolepermission_delete.go +++ /dev/null @@ -1,88 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" - "git.dcentral.systems/toolz/goplt/internal/ent/rolepermission" -) - -// RolePermissionDelete is the builder for deleting a RolePermission entity. -type RolePermissionDelete struct { - config - hooks []Hook - mutation *RolePermissionMutation -} - -// Where appends a list predicates to the RolePermissionDelete builder. -func (_d *RolePermissionDelete) Where(ps ...predicate.RolePermission) *RolePermissionDelete { - _d.mutation.Where(ps...) - return _d -} - -// Exec executes the deletion query and returns how many vertices were deleted. -func (_d *RolePermissionDelete) Exec(ctx context.Context) (int, error) { - return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) -} - -// ExecX is like Exec, but panics if an error occurs. -func (_d *RolePermissionDelete) ExecX(ctx context.Context) int { - n, err := _d.Exec(ctx) - if err != nil { - panic(err) - } - return n -} - -func (_d *RolePermissionDelete) sqlExec(ctx context.Context) (int, error) { - _spec := sqlgraph.NewDeleteSpec(rolepermission.Table, sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt)) - if ps := _d.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) - if err != nil && sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - _d.mutation.done = true - return affected, err -} - -// RolePermissionDeleteOne is the builder for deleting a single RolePermission entity. -type RolePermissionDeleteOne struct { - _d *RolePermissionDelete -} - -// Where appends a list predicates to the RolePermissionDelete builder. -func (_d *RolePermissionDeleteOne) Where(ps ...predicate.RolePermission) *RolePermissionDeleteOne { - _d._d.mutation.Where(ps...) - return _d -} - -// Exec executes the deletion query. -func (_d *RolePermissionDeleteOne) Exec(ctx context.Context) error { - n, err := _d._d.Exec(ctx) - switch { - case err != nil: - return err - case n == 0: - return &NotFoundError{rolepermission.Label} - default: - return nil - } -} - -// ExecX is like Exec, but panics if an error occurs. -func (_d *RolePermissionDeleteOne) ExecX(ctx context.Context) { - if err := _d.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/internal/ent/rolepermission_query.go b/internal/ent/rolepermission_query.go deleted file mode 100644 index da6d6aa..0000000 --- a/internal/ent/rolepermission_query.go +++ /dev/null @@ -1,686 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "fmt" - "math" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/internal/ent/permission" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" - "git.dcentral.systems/toolz/goplt/internal/ent/role" - "git.dcentral.systems/toolz/goplt/internal/ent/rolepermission" -) - -// RolePermissionQuery is the builder for querying RolePermission entities. -type RolePermissionQuery struct { - config - ctx *QueryContext - order []rolepermission.OrderOption - inters []Interceptor - predicates []predicate.RolePermission - withRole *RoleQuery - withPermission *PermissionQuery - withFKs bool - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Where adds a new predicate for the RolePermissionQuery builder. -func (_q *RolePermissionQuery) Where(ps ...predicate.RolePermission) *RolePermissionQuery { - _q.predicates = append(_q.predicates, ps...) - return _q -} - -// Limit the number of records to be returned by this query. -func (_q *RolePermissionQuery) Limit(limit int) *RolePermissionQuery { - _q.ctx.Limit = &limit - return _q -} - -// Offset to start from. -func (_q *RolePermissionQuery) Offset(offset int) *RolePermissionQuery { - _q.ctx.Offset = &offset - return _q -} - -// Unique configures the query builder to filter duplicate records on query. -// By default, unique is set to true, and can be disabled using this method. -func (_q *RolePermissionQuery) Unique(unique bool) *RolePermissionQuery { - _q.ctx.Unique = &unique - return _q -} - -// Order specifies how the records should be ordered. -func (_q *RolePermissionQuery) Order(o ...rolepermission.OrderOption) *RolePermissionQuery { - _q.order = append(_q.order, o...) - return _q -} - -// QueryRole chains the current query on the "role" edge. -func (_q *RolePermissionQuery) QueryRole() *RoleQuery { - query := (&RoleClient{config: _q.config}).Query() - query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { - if err := _q.prepareQuery(ctx); err != nil { - return nil, err - } - selector := _q.sqlQuery(ctx) - if err := selector.Err(); err != nil { - return nil, err - } - step := sqlgraph.NewStep( - sqlgraph.From(rolepermission.Table, rolepermission.FieldID, selector), - sqlgraph.To(role.Table, role.FieldID), - sqlgraph.Edge(sqlgraph.M2O, false, rolepermission.RoleTable, rolepermission.RoleColumn), - ) - fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) - return fromU, nil - } - return query -} - -// QueryPermission chains the current query on the "permission" edge. -func (_q *RolePermissionQuery) QueryPermission() *PermissionQuery { - query := (&PermissionClient{config: _q.config}).Query() - query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { - if err := _q.prepareQuery(ctx); err != nil { - return nil, err - } - selector := _q.sqlQuery(ctx) - if err := selector.Err(); err != nil { - return nil, err - } - step := sqlgraph.NewStep( - sqlgraph.From(rolepermission.Table, rolepermission.FieldID, selector), - sqlgraph.To(permission.Table, permission.FieldID), - sqlgraph.Edge(sqlgraph.M2O, false, rolepermission.PermissionTable, rolepermission.PermissionColumn), - ) - fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) - return fromU, nil - } - return query -} - -// First returns the first RolePermission entity from the query. -// Returns a *NotFoundError when no RolePermission was found. -func (_q *RolePermissionQuery) First(ctx context.Context) (*RolePermission, error) { - nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{rolepermission.Label} - } - return nodes[0], nil -} - -// FirstX is like First, but panics if an error occurs. -func (_q *RolePermissionQuery) FirstX(ctx context.Context) *RolePermission { - node, err := _q.First(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// FirstID returns the first RolePermission ID from the query. -// Returns a *NotFoundError when no RolePermission ID was found. -func (_q *RolePermissionQuery) FirstID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{rolepermission.Label} - return - } - return ids[0], nil -} - -// FirstIDX is like FirstID, but panics if an error occurs. -func (_q *RolePermissionQuery) FirstIDX(ctx context.Context) int { - id, err := _q.FirstID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Only returns a single RolePermission entity found by the query, ensuring it only returns one. -// Returns a *NotSingularError when more than one RolePermission entity is found. -// Returns a *NotFoundError when no RolePermission entities are found. -func (_q *RolePermissionQuery) Only(ctx context.Context) (*RolePermission, error) { - nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) - if err != nil { - return nil, err - } - switch len(nodes) { - case 1: - return nodes[0], nil - case 0: - return nil, &NotFoundError{rolepermission.Label} - default: - return nil, &NotSingularError{rolepermission.Label} - } -} - -// OnlyX is like Only, but panics if an error occurs. -func (_q *RolePermissionQuery) OnlyX(ctx context.Context) *RolePermission { - node, err := _q.Only(ctx) - if err != nil { - panic(err) - } - return node -} - -// OnlyID is like Only, but returns the only RolePermission ID in the query. -// Returns a *NotSingularError when more than one RolePermission ID is found. -// Returns a *NotFoundError when no entities are found. -func (_q *RolePermissionQuery) OnlyID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { - return - } - switch len(ids) { - case 1: - id = ids[0] - case 0: - err = &NotFoundError{rolepermission.Label} - default: - err = &NotSingularError{rolepermission.Label} - } - return -} - -// OnlyIDX is like OnlyID, but panics if an error occurs. -func (_q *RolePermissionQuery) OnlyIDX(ctx context.Context) int { - id, err := _q.OnlyID(ctx) - if err != nil { - panic(err) - } - return id -} - -// All executes the query and returns a list of RolePermissions. -func (_q *RolePermissionQuery) All(ctx context.Context) ([]*RolePermission, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) - if err := _q.prepareQuery(ctx); err != nil { - return nil, err - } - qr := querierAll[[]*RolePermission, *RolePermissionQuery]() - return withInterceptors[[]*RolePermission](ctx, _q, qr, _q.inters) -} - -// AllX is like All, but panics if an error occurs. -func (_q *RolePermissionQuery) AllX(ctx context.Context) []*RolePermission { - nodes, err := _q.All(ctx) - if err != nil { - panic(err) - } - return nodes -} - -// IDs executes the query and returns a list of RolePermission IDs. -func (_q *RolePermissionQuery) IDs(ctx context.Context) (ids []int, err error) { - if _q.ctx.Unique == nil && _q.path != nil { - _q.Unique(true) - } - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) - if err = _q.Select(rolepermission.FieldID).Scan(ctx, &ids); err != nil { - return nil, err - } - return ids, nil -} - -// IDsX is like IDs, but panics if an error occurs. -func (_q *RolePermissionQuery) IDsX(ctx context.Context) []int { - ids, err := _q.IDs(ctx) - if err != nil { - panic(err) - } - return ids -} - -// Count returns the count of the given query. -func (_q *RolePermissionQuery) Count(ctx context.Context) (int, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) - if err := _q.prepareQuery(ctx); err != nil { - return 0, err - } - return withInterceptors[int](ctx, _q, querierCount[*RolePermissionQuery](), _q.inters) -} - -// CountX is like Count, but panics if an error occurs. -func (_q *RolePermissionQuery) CountX(ctx context.Context) int { - count, err := _q.Count(ctx) - if err != nil { - panic(err) - } - return count -} - -// Exist returns true if the query has elements in the graph. -func (_q *RolePermissionQuery) Exist(ctx context.Context) (bool, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) - switch _, err := _q.FirstID(ctx); { - case IsNotFound(err): - return false, nil - case err != nil: - return false, fmt.Errorf("ent: check existence: %w", err) - default: - return true, nil - } -} - -// ExistX is like Exist, but panics if an error occurs. -func (_q *RolePermissionQuery) ExistX(ctx context.Context) bool { - exist, err := _q.Exist(ctx) - if err != nil { - panic(err) - } - return exist -} - -// Clone returns a duplicate of the RolePermissionQuery builder, including all associated steps. It can be -// used to prepare common query builders and use them differently after the clone is made. -func (_q *RolePermissionQuery) Clone() *RolePermissionQuery { - if _q == nil { - return nil - } - return &RolePermissionQuery{ - config: _q.config, - ctx: _q.ctx.Clone(), - order: append([]rolepermission.OrderOption{}, _q.order...), - inters: append([]Interceptor{}, _q.inters...), - predicates: append([]predicate.RolePermission{}, _q.predicates...), - withRole: _q.withRole.Clone(), - withPermission: _q.withPermission.Clone(), - // clone intermediate query. - sql: _q.sql.Clone(), - path: _q.path, - } -} - -// WithRole tells the query-builder to eager-load the nodes that are connected to -// the "role" edge. The optional arguments are used to configure the query builder of the edge. -func (_q *RolePermissionQuery) WithRole(opts ...func(*RoleQuery)) *RolePermissionQuery { - query := (&RoleClient{config: _q.config}).Query() - for _, opt := range opts { - opt(query) - } - _q.withRole = query - return _q -} - -// WithPermission tells the query-builder to eager-load the nodes that are connected to -// the "permission" edge. The optional arguments are used to configure the query builder of the edge. -func (_q *RolePermissionQuery) WithPermission(opts ...func(*PermissionQuery)) *RolePermissionQuery { - query := (&PermissionClient{config: _q.config}).Query() - for _, opt := range opts { - opt(query) - } - _q.withPermission = query - return _q -} - -// GroupBy is used to group vertices by one or more fields/columns. -// It is often used with aggregate functions, like: count, max, mean, min, sum. -// -// Example: -// -// var v []struct { -// RoleID string `json:"role_id,omitempty"` -// Count int `json:"count,omitempty"` -// } -// -// client.RolePermission.Query(). -// GroupBy(rolepermission.FieldRoleID). -// Aggregate(ent.Count()). -// Scan(ctx, &v) -func (_q *RolePermissionQuery) GroupBy(field string, fields ...string) *RolePermissionGroupBy { - _q.ctx.Fields = append([]string{field}, fields...) - grbuild := &RolePermissionGroupBy{build: _q} - grbuild.flds = &_q.ctx.Fields - grbuild.label = rolepermission.Label - grbuild.scan = grbuild.Scan - return grbuild -} - -// Select allows the selection one or more fields/columns for the given query, -// instead of selecting all fields in the entity. -// -// Example: -// -// var v []struct { -// RoleID string `json:"role_id,omitempty"` -// } -// -// client.RolePermission.Query(). -// Select(rolepermission.FieldRoleID). -// Scan(ctx, &v) -func (_q *RolePermissionQuery) Select(fields ...string) *RolePermissionSelect { - _q.ctx.Fields = append(_q.ctx.Fields, fields...) - sbuild := &RolePermissionSelect{RolePermissionQuery: _q} - sbuild.label = rolepermission.Label - sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan - return sbuild -} - -// Aggregate returns a RolePermissionSelect configured with the given aggregations. -func (_q *RolePermissionQuery) Aggregate(fns ...AggregateFunc) *RolePermissionSelect { - return _q.Select().Aggregate(fns...) -} - -func (_q *RolePermissionQuery) prepareQuery(ctx context.Context) error { - for _, inter := range _q.inters { - if inter == nil { - return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") - } - if trv, ok := inter.(Traverser); ok { - if err := trv.Traverse(ctx, _q); err != nil { - return err - } - } - } - for _, f := range _q.ctx.Fields { - if !rolepermission.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} - } - } - if _q.path != nil { - prev, err := _q.path(ctx) - if err != nil { - return err - } - _q.sql = prev - } - return nil -} - -func (_q *RolePermissionQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*RolePermission, error) { - var ( - nodes = []*RolePermission{} - withFKs = _q.withFKs - _spec = _q.querySpec() - loadedTypes = [2]bool{ - _q.withRole != nil, - _q.withPermission != nil, - } - ) - if withFKs { - _spec.Node.Columns = append(_spec.Node.Columns, rolepermission.ForeignKeys...) - } - _spec.ScanValues = func(columns []string) ([]any, error) { - return (*RolePermission).scanValues(nil, columns) - } - _spec.Assign = func(columns []string, values []any) error { - node := &RolePermission{config: _q.config} - nodes = append(nodes, node) - node.Edges.loadedTypes = loadedTypes - return node.assignValues(columns, values) - } - for i := range hooks { - hooks[i](ctx, _spec) - } - if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { - return nil, err - } - if len(nodes) == 0 { - return nodes, nil - } - if query := _q.withRole; query != nil { - if err := _q.loadRole(ctx, query, nodes, nil, - func(n *RolePermission, e *Role) { n.Edges.Role = e }); err != nil { - return nil, err - } - } - if query := _q.withPermission; query != nil { - if err := _q.loadPermission(ctx, query, nodes, nil, - func(n *RolePermission, e *Permission) { n.Edges.Permission = e }); err != nil { - return nil, err - } - } - return nodes, nil -} - -func (_q *RolePermissionQuery) loadRole(ctx context.Context, query *RoleQuery, nodes []*RolePermission, init func(*RolePermission), assign func(*RolePermission, *Role)) error { - ids := make([]string, 0, len(nodes)) - nodeids := make(map[string][]*RolePermission) - for i := range nodes { - fk := nodes[i].RoleID - if _, ok := nodeids[fk]; !ok { - ids = append(ids, fk) - } - nodeids[fk] = append(nodeids[fk], nodes[i]) - } - if len(ids) == 0 { - return nil - } - query.Where(role.IDIn(ids...)) - neighbors, err := query.All(ctx) - if err != nil { - return err - } - for _, n := range neighbors { - nodes, ok := nodeids[n.ID] - if !ok { - return fmt.Errorf(`unexpected foreign-key "role_id" returned %v`, n.ID) - } - for i := range nodes { - assign(nodes[i], n) - } - } - return nil -} -func (_q *RolePermissionQuery) loadPermission(ctx context.Context, query *PermissionQuery, nodes []*RolePermission, init func(*RolePermission), assign func(*RolePermission, *Permission)) error { - ids := make([]string, 0, len(nodes)) - nodeids := make(map[string][]*RolePermission) - for i := range nodes { - fk := nodes[i].PermissionID - if _, ok := nodeids[fk]; !ok { - ids = append(ids, fk) - } - nodeids[fk] = append(nodeids[fk], nodes[i]) - } - if len(ids) == 0 { - return nil - } - query.Where(permission.IDIn(ids...)) - neighbors, err := query.All(ctx) - if err != nil { - return err - } - for _, n := range neighbors { - nodes, ok := nodeids[n.ID] - if !ok { - return fmt.Errorf(`unexpected foreign-key "permission_id" returned %v`, n.ID) - } - for i := range nodes { - assign(nodes[i], n) - } - } - return nil -} - -func (_q *RolePermissionQuery) sqlCount(ctx context.Context) (int, error) { - _spec := _q.querySpec() - _spec.Node.Columns = _q.ctx.Fields - if len(_q.ctx.Fields) > 0 { - _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique - } - return sqlgraph.CountNodes(ctx, _q.driver, _spec) -} - -func (_q *RolePermissionQuery) querySpec() *sqlgraph.QuerySpec { - _spec := sqlgraph.NewQuerySpec(rolepermission.Table, rolepermission.Columns, sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt)) - _spec.From = _q.sql - if unique := _q.ctx.Unique; unique != nil { - _spec.Unique = *unique - } else if _q.path != nil { - _spec.Unique = true - } - if fields := _q.ctx.Fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, rolepermission.FieldID) - for i := range fields { - if fields[i] != rolepermission.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) - } - } - if _q.withRole != nil { - _spec.Node.AddColumnOnce(rolepermission.FieldRoleID) - } - if _q.withPermission != nil { - _spec.Node.AddColumnOnce(rolepermission.FieldPermissionID) - } - } - if ps := _q.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if limit := _q.ctx.Limit; limit != nil { - _spec.Limit = *limit - } - if offset := _q.ctx.Offset; offset != nil { - _spec.Offset = *offset - } - if ps := _q.order; len(ps) > 0 { - _spec.Order = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return _spec -} - -func (_q *RolePermissionQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(_q.driver.Dialect()) - t1 := builder.Table(rolepermission.Table) - columns := _q.ctx.Fields - if len(columns) == 0 { - columns = rolepermission.Columns - } - selector := builder.Select(t1.Columns(columns...)...).From(t1) - if _q.sql != nil { - selector = _q.sql - selector.Select(selector.Columns(columns...)...) - } - if _q.ctx.Unique != nil && *_q.ctx.Unique { - selector.Distinct() - } - for _, p := range _q.predicates { - p(selector) - } - for _, p := range _q.order { - p(selector) - } - if offset := _q.ctx.Offset; offset != nil { - // limit is mandatory for offset clause. We start - // with default value, and override it below if needed. - selector.Offset(*offset).Limit(math.MaxInt32) - } - if limit := _q.ctx.Limit; limit != nil { - selector.Limit(*limit) - } - return selector -} - -// RolePermissionGroupBy is the group-by builder for RolePermission entities. -type RolePermissionGroupBy struct { - selector - build *RolePermissionQuery -} - -// Aggregate adds the given aggregation functions to the group-by query. -func (_g *RolePermissionGroupBy) Aggregate(fns ...AggregateFunc) *RolePermissionGroupBy { - _g.fns = append(_g.fns, fns...) - return _g -} - -// Scan applies the selector query and scans the result into the given value. -func (_g *RolePermissionGroupBy) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) - if err := _g.build.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*RolePermissionQuery, *RolePermissionGroupBy](ctx, _g.build, _g, _g.build.inters, v) -} - -func (_g *RolePermissionGroupBy) sqlScan(ctx context.Context, root *RolePermissionQuery, v any) error { - selector := root.sqlQuery(ctx).Select() - aggregation := make([]string, 0, len(_g.fns)) - for _, fn := range _g.fns { - aggregation = append(aggregation, fn(selector)) - } - if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) - for _, f := range *_g.flds { - columns = append(columns, selector.C(f)) - } - columns = append(columns, aggregation...) - selector.Select(columns...) - } - selector.GroupBy(selector.Columns(*_g.flds...)...) - if err := selector.Err(); err != nil { - return err - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} - -// RolePermissionSelect is the builder for selecting fields of RolePermission entities. -type RolePermissionSelect struct { - *RolePermissionQuery - selector -} - -// Aggregate adds the given aggregation functions to the selector query. -func (_s *RolePermissionSelect) Aggregate(fns ...AggregateFunc) *RolePermissionSelect { - _s.fns = append(_s.fns, fns...) - return _s -} - -// Scan applies the selector query and scans the result into the given value. -func (_s *RolePermissionSelect) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) - if err := _s.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*RolePermissionQuery, *RolePermissionSelect](ctx, _s.RolePermissionQuery, _s, _s.inters, v) -} - -func (_s *RolePermissionSelect) sqlScan(ctx context.Context, root *RolePermissionQuery, v any) error { - selector := root.sqlQuery(ctx) - aggregation := make([]string, 0, len(_s.fns)) - for _, fn := range _s.fns { - aggregation = append(aggregation, fn(selector)) - } - switch n := len(*_s.selector.flds); { - case n == 0 && len(aggregation) > 0: - selector.Select(aggregation...) - case n != 0 && len(aggregation) > 0: - selector.AppendSelect(aggregation...) - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := _s.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} diff --git a/internal/ent/rolepermission_update.go b/internal/ent/rolepermission_update.go deleted file mode 100644 index e240158..0000000 --- a/internal/ent/rolepermission_update.go +++ /dev/null @@ -1,421 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "errors" - "fmt" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/internal/ent/permission" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" - "git.dcentral.systems/toolz/goplt/internal/ent/role" - "git.dcentral.systems/toolz/goplt/internal/ent/rolepermission" -) - -// RolePermissionUpdate is the builder for updating RolePermission entities. -type RolePermissionUpdate struct { - config - hooks []Hook - mutation *RolePermissionMutation -} - -// Where appends a list predicates to the RolePermissionUpdate builder. -func (_u *RolePermissionUpdate) Where(ps ...predicate.RolePermission) *RolePermissionUpdate { - _u.mutation.Where(ps...) - return _u -} - -// SetRoleID sets the "role_id" field. -func (_u *RolePermissionUpdate) SetRoleID(v string) *RolePermissionUpdate { - _u.mutation.SetRoleID(v) - return _u -} - -// SetNillableRoleID sets the "role_id" field if the given value is not nil. -func (_u *RolePermissionUpdate) SetNillableRoleID(v *string) *RolePermissionUpdate { - if v != nil { - _u.SetRoleID(*v) - } - return _u -} - -// SetPermissionID sets the "permission_id" field. -func (_u *RolePermissionUpdate) SetPermissionID(v string) *RolePermissionUpdate { - _u.mutation.SetPermissionID(v) - return _u -} - -// SetNillablePermissionID sets the "permission_id" field if the given value is not nil. -func (_u *RolePermissionUpdate) SetNillablePermissionID(v *string) *RolePermissionUpdate { - if v != nil { - _u.SetPermissionID(*v) - } - return _u -} - -// SetRole sets the "role" edge to the Role entity. -func (_u *RolePermissionUpdate) SetRole(v *Role) *RolePermissionUpdate { - return _u.SetRoleID(v.ID) -} - -// SetPermission sets the "permission" edge to the Permission entity. -func (_u *RolePermissionUpdate) SetPermission(v *Permission) *RolePermissionUpdate { - return _u.SetPermissionID(v.ID) -} - -// Mutation returns the RolePermissionMutation object of the builder. -func (_u *RolePermissionUpdate) Mutation() *RolePermissionMutation { - return _u.mutation -} - -// ClearRole clears the "role" edge to the Role entity. -func (_u *RolePermissionUpdate) ClearRole() *RolePermissionUpdate { - _u.mutation.ClearRole() - return _u -} - -// ClearPermission clears the "permission" edge to the Permission entity. -func (_u *RolePermissionUpdate) ClearPermission() *RolePermissionUpdate { - _u.mutation.ClearPermission() - return _u -} - -// Save executes the query and returns the number of nodes affected by the update operation. -func (_u *RolePermissionUpdate) Save(ctx context.Context) (int, error) { - return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (_u *RolePermissionUpdate) SaveX(ctx context.Context) int { - affected, err := _u.Save(ctx) - if err != nil { - panic(err) - } - return affected -} - -// Exec executes the query. -func (_u *RolePermissionUpdate) Exec(ctx context.Context) error { - _, err := _u.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_u *RolePermissionUpdate) ExecX(ctx context.Context) { - if err := _u.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (_u *RolePermissionUpdate) check() error { - if _u.mutation.RoleCleared() && len(_u.mutation.RoleIDs()) > 0 { - return errors.New(`ent: clearing a required unique edge "RolePermission.role"`) - } - if _u.mutation.PermissionCleared() && len(_u.mutation.PermissionIDs()) > 0 { - return errors.New(`ent: clearing a required unique edge "RolePermission.permission"`) - } - return nil -} - -func (_u *RolePermissionUpdate) sqlSave(ctx context.Context) (_node int, err error) { - if err := _u.check(); err != nil { - return _node, err - } - _spec := sqlgraph.NewUpdateSpec(rolepermission.Table, rolepermission.Columns, sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt)) - if ps := _u.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if _u.mutation.RoleCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: false, - Table: rolepermission.RoleTable, - Columns: []string{rolepermission.RoleColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeString), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.RoleIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: false, - Table: rolepermission.RoleTable, - Columns: []string{rolepermission.RoleColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeString), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - if _u.mutation.PermissionCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: false, - Table: rolepermission.PermissionTable, - Columns: []string{rolepermission.PermissionColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(permission.FieldID, field.TypeString), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.PermissionIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: false, - Table: rolepermission.PermissionTable, - Columns: []string{rolepermission.PermissionColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(permission.FieldID, field.TypeString), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{rolepermission.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return 0, err - } - _u.mutation.done = true - return _node, nil -} - -// RolePermissionUpdateOne is the builder for updating a single RolePermission entity. -type RolePermissionUpdateOne struct { - config - fields []string - hooks []Hook - mutation *RolePermissionMutation -} - -// SetRoleID sets the "role_id" field. -func (_u *RolePermissionUpdateOne) SetRoleID(v string) *RolePermissionUpdateOne { - _u.mutation.SetRoleID(v) - return _u -} - -// SetNillableRoleID sets the "role_id" field if the given value is not nil. -func (_u *RolePermissionUpdateOne) SetNillableRoleID(v *string) *RolePermissionUpdateOne { - if v != nil { - _u.SetRoleID(*v) - } - return _u -} - -// SetPermissionID sets the "permission_id" field. -func (_u *RolePermissionUpdateOne) SetPermissionID(v string) *RolePermissionUpdateOne { - _u.mutation.SetPermissionID(v) - return _u -} - -// SetNillablePermissionID sets the "permission_id" field if the given value is not nil. -func (_u *RolePermissionUpdateOne) SetNillablePermissionID(v *string) *RolePermissionUpdateOne { - if v != nil { - _u.SetPermissionID(*v) - } - return _u -} - -// SetRole sets the "role" edge to the Role entity. -func (_u *RolePermissionUpdateOne) SetRole(v *Role) *RolePermissionUpdateOne { - return _u.SetRoleID(v.ID) -} - -// SetPermission sets the "permission" edge to the Permission entity. -func (_u *RolePermissionUpdateOne) SetPermission(v *Permission) *RolePermissionUpdateOne { - return _u.SetPermissionID(v.ID) -} - -// Mutation returns the RolePermissionMutation object of the builder. -func (_u *RolePermissionUpdateOne) Mutation() *RolePermissionMutation { - return _u.mutation -} - -// ClearRole clears the "role" edge to the Role entity. -func (_u *RolePermissionUpdateOne) ClearRole() *RolePermissionUpdateOne { - _u.mutation.ClearRole() - return _u -} - -// ClearPermission clears the "permission" edge to the Permission entity. -func (_u *RolePermissionUpdateOne) ClearPermission() *RolePermissionUpdateOne { - _u.mutation.ClearPermission() - return _u -} - -// Where appends a list predicates to the RolePermissionUpdate builder. -func (_u *RolePermissionUpdateOne) Where(ps ...predicate.RolePermission) *RolePermissionUpdateOne { - _u.mutation.Where(ps...) - return _u -} - -// Select allows selecting one or more fields (columns) of the returned entity. -// The default is selecting all fields defined in the entity schema. -func (_u *RolePermissionUpdateOne) Select(field string, fields ...string) *RolePermissionUpdateOne { - _u.fields = append([]string{field}, fields...) - return _u -} - -// Save executes the query and returns the updated RolePermission entity. -func (_u *RolePermissionUpdateOne) Save(ctx context.Context) (*RolePermission, error) { - return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (_u *RolePermissionUpdateOne) SaveX(ctx context.Context) *RolePermission { - node, err := _u.Save(ctx) - if err != nil { - panic(err) - } - return node -} - -// Exec executes the query on the entity. -func (_u *RolePermissionUpdateOne) Exec(ctx context.Context) error { - _, err := _u.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_u *RolePermissionUpdateOne) ExecX(ctx context.Context) { - if err := _u.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (_u *RolePermissionUpdateOne) check() error { - if _u.mutation.RoleCleared() && len(_u.mutation.RoleIDs()) > 0 { - return errors.New(`ent: clearing a required unique edge "RolePermission.role"`) - } - if _u.mutation.PermissionCleared() && len(_u.mutation.PermissionIDs()) > 0 { - return errors.New(`ent: clearing a required unique edge "RolePermission.permission"`) - } - return nil -} - -func (_u *RolePermissionUpdateOne) sqlSave(ctx context.Context) (_node *RolePermission, err error) { - if err := _u.check(); err != nil { - return _node, err - } - _spec := sqlgraph.NewUpdateSpec(rolepermission.Table, rolepermission.Columns, sqlgraph.NewFieldSpec(rolepermission.FieldID, field.TypeInt)) - id, ok := _u.mutation.ID() - if !ok { - return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "RolePermission.id" for update`)} - } - _spec.Node.ID.Value = id - if fields := _u.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, rolepermission.FieldID) - for _, f := range fields { - if !rolepermission.ValidColumn(f) { - return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} - } - if f != rolepermission.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, f) - } - } - } - if ps := _u.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if _u.mutation.RoleCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: false, - Table: rolepermission.RoleTable, - Columns: []string{rolepermission.RoleColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeString), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.RoleIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: false, - Table: rolepermission.RoleTable, - Columns: []string{rolepermission.RoleColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeString), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - if _u.mutation.PermissionCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: false, - Table: rolepermission.PermissionTable, - Columns: []string{rolepermission.PermissionColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(permission.FieldID, field.TypeString), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.PermissionIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: false, - Table: rolepermission.PermissionTable, - Columns: []string{rolepermission.PermissionColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(permission.FieldID, field.TypeString), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - _node = &RolePermission{config: _u.config} - _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{rolepermission.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - _u.mutation.done = true - return _node, nil -} diff --git a/internal/ent/runtime.go b/internal/ent/runtime.go deleted file mode 100644 index 82264c3..0000000 --- a/internal/ent/runtime.go +++ /dev/null @@ -1,88 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "time" - - "git.dcentral.systems/toolz/goplt/internal/ent/auditlog" - "git.dcentral.systems/toolz/goplt/internal/ent/permission" - "git.dcentral.systems/toolz/goplt/internal/ent/refreshtoken" - "git.dcentral.systems/toolz/goplt/internal/ent/role" - "git.dcentral.systems/toolz/goplt/internal/ent/schema" - "git.dcentral.systems/toolz/goplt/internal/ent/user" -) - -// 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() { - auditlogFields := schema.AuditLog{}.Fields() - _ = auditlogFields - // auditlogDescUserID is the schema descriptor for user_id field. - auditlogDescUserID := auditlogFields[1].Descriptor() - // auditlog.UserIDValidator is a validator for the "user_id" field. It is called by the builders before save. - auditlog.UserIDValidator = auditlogDescUserID.Validators[0].(func(string) error) - // auditlogDescAction is the schema descriptor for action field. - auditlogDescAction := auditlogFields[2].Descriptor() - // auditlog.ActionValidator is a validator for the "action" field. It is called by the builders before save. - auditlog.ActionValidator = auditlogDescAction.Validators[0].(func(string) error) - // auditlogDescTimestamp is the schema descriptor for timestamp field. - auditlogDescTimestamp := auditlogFields[8].Descriptor() - // auditlog.DefaultTimestamp holds the default value on creation for the timestamp field. - auditlog.DefaultTimestamp = auditlogDescTimestamp.Default.(func() time.Time) - permissionFields := schema.Permission{}.Fields() - _ = permissionFields - // permissionDescName is the schema descriptor for name field. - permissionDescName := permissionFields[1].Descriptor() - // permission.NameValidator is a validator for the "name" field. It is called by the builders before save. - permission.NameValidator = permissionDescName.Validators[0].(func(string) error) - refreshtokenFields := schema.RefreshToken{}.Fields() - _ = refreshtokenFields - // refreshtokenDescUserID is the schema descriptor for user_id field. - refreshtokenDescUserID := refreshtokenFields[1].Descriptor() - // refreshtoken.UserIDValidator is a validator for the "user_id" field. It is called by the builders before save. - refreshtoken.UserIDValidator = refreshtokenDescUserID.Validators[0].(func(string) error) - // refreshtokenDescTokenHash is the schema descriptor for token_hash field. - refreshtokenDescTokenHash := refreshtokenFields[2].Descriptor() - // refreshtoken.TokenHashValidator is a validator for the "token_hash" field. It is called by the builders before save. - refreshtoken.TokenHashValidator = refreshtokenDescTokenHash.Validators[0].(func(string) error) - // refreshtokenDescCreatedAt is the schema descriptor for created_at field. - refreshtokenDescCreatedAt := refreshtokenFields[4].Descriptor() - // refreshtoken.DefaultCreatedAt holds the default value on creation for the created_at field. - refreshtoken.DefaultCreatedAt = refreshtokenDescCreatedAt.Default.(func() time.Time) - roleFields := schema.Role{}.Fields() - _ = roleFields - // roleDescName is the schema descriptor for name field. - roleDescName := roleFields[1].Descriptor() - // role.NameValidator is a validator for the "name" field. It is called by the builders before save. - role.NameValidator = roleDescName.Validators[0].(func(string) error) - // roleDescCreatedAt is the schema descriptor for created_at field. - roleDescCreatedAt := roleFields[3].Descriptor() - // role.DefaultCreatedAt holds the default value on creation for the created_at field. - role.DefaultCreatedAt = roleDescCreatedAt.Default.(func() time.Time) - userFields := schema.User{}.Fields() - _ = userFields - // userDescEmail is the schema descriptor for email field. - userDescEmail := userFields[1].Descriptor() - // user.EmailValidator is a validator for the "email" field. It is called by the builders before save. - user.EmailValidator = userDescEmail.Validators[0].(func(string) error) - // userDescPasswordHash is the schema descriptor for password_hash field. - userDescPasswordHash := userFields[5].Descriptor() - // user.PasswordHashValidator is a validator for the "password_hash" field. It is called by the builders before save. - user.PasswordHashValidator = userDescPasswordHash.Validators[0].(func(string) error) - // userDescVerified is the schema descriptor for verified field. - userDescVerified := userFields[6].Descriptor() - // user.DefaultVerified holds the default value on creation for the verified field. - user.DefaultVerified = userDescVerified.Default.(bool) - // userDescCreatedAt is the schema descriptor for created_at field. - userDescCreatedAt := userFields[10].Descriptor() - // user.DefaultCreatedAt holds the default value on creation for the created_at field. - user.DefaultCreatedAt = userDescCreatedAt.Default.(func() time.Time) - // userDescUpdatedAt is the schema descriptor for updated_at field. - userDescUpdatedAt := userFields[11].Descriptor() - // user.DefaultUpdatedAt holds the default value on creation for the updated_at field. - user.DefaultUpdatedAt = userDescUpdatedAt.Default.(func() time.Time) - // user.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. - user.UpdateDefaultUpdatedAt = userDescUpdatedAt.UpdateDefault.(func() time.Time) -} diff --git a/internal/ent/runtime/runtime.go b/internal/ent/runtime/runtime.go deleted file mode 100644 index 0dd9113..0000000 --- a/internal/ent/runtime/runtime.go +++ /dev/null @@ -1,10 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package runtime - -// The schema-stitching logic is generated in git.dcentral.systems/toolz/goplt/internal/ent/runtime.go - -const ( - Version = "v0.14.5" // Version of ent codegen. - Sum = "h1:Rj2WOYJtCkWyFo6a+5wB3EfBRP0rnx1fMk6gGA0UUe4=" // Sum of ent codegen. -) diff --git a/internal/ent/schema/audit_log.go b/internal/ent/schema/audit_log.go deleted file mode 100644 index a58ecb8..0000000 --- a/internal/ent/schema/audit_log.go +++ /dev/null @@ -1,59 +0,0 @@ -// Package schema defines the Ent schema for domain entities. -package schema - -import ( - "time" - - "entgo.io/ent" - "entgo.io/ent/schema/field" - "entgo.io/ent/schema/index" -) - -// AuditLog holds the schema definition for the AuditLog entity. -type AuditLog struct { - ent.Schema -} - -// Fields of the AuditLog. -func (AuditLog) Fields() []ent.Field { - return []ent.Field{ - field.String("id"). - Unique(). - Immutable(), - field.String("user_id"). - NotEmpty(). - Comment("ID of the user/actor performing the action"), - field.String("action"). - NotEmpty(). - Comment("Action performed (e.g., user.create, user.update)"), - field.String("resource"). - Optional(). - Comment("Resource type (e.g., user, role)"), - field.String("resource_id"). - Optional(). - Comment("ID of the target resource"), - field.String("ip_address"). - Optional(). - Comment("IP address of the client"), - field.String("user_agent"). - Optional(). - Comment("User agent of the client"), - field.JSON("metadata", map[string]interface{}{}). - Optional(). - Comment("Additional metadata as JSON"), - field.Time("timestamp"). - Default(time.Now). - Immutable(), - } -} - -// Indexes of the AuditLog. -func (AuditLog) Indexes() []ent.Index { - return []ent.Index{ - index.Fields("user_id"), - index.Fields("resource_id"), - index.Fields("timestamp"), - index.Fields("action"), - index.Fields("resource"), - } -} diff --git a/internal/ent/schema/permission.go b/internal/ent/schema/permission.go deleted file mode 100644 index 8bfd7a3..0000000 --- a/internal/ent/schema/permission.go +++ /dev/null @@ -1,32 +0,0 @@ -package schema - -import ( - "entgo.io/ent" - "entgo.io/ent/schema/edge" - "entgo.io/ent/schema/field" -) - -// Permission holds the schema definition for the Permission entity. -type Permission struct { - ent.Schema -} - -// Fields of the Permission. -func (Permission) Fields() []ent.Field { - return []ent.Field{ - field.String("id"). - Unique(). - Immutable(), - field.String("name"). - Unique(). - NotEmpty(). - Comment("Format: module.resource.action"), - } -} - -// Edges of the Permission. -func (Permission) Edges() []ent.Edge { - return []ent.Edge{ - edge.To("role_permissions", RolePermission.Type), - } -} diff --git a/internal/ent/schema/refresh_token.go b/internal/ent/schema/refresh_token.go deleted file mode 100644 index b49ed75..0000000 --- a/internal/ent/schema/refresh_token.go +++ /dev/null @@ -1,44 +0,0 @@ -package schema - -import ( - "time" - - "entgo.io/ent" - "entgo.io/ent/schema/field" - "entgo.io/ent/schema/index" -) - -// RefreshToken holds the schema definition for the RefreshToken entity. -type RefreshToken struct { - ent.Schema -} - -// Fields of the RefreshToken. -func (RefreshToken) Fields() []ent.Field { - return []ent.Field{ - field.String("id"). - Unique(). - Immutable(), - field.String("user_id"). - NotEmpty(). - Comment("ID of the user who owns this refresh token"), - field.String("token_hash"). - NotEmpty(). - Sensitive(). - Comment("SHA256 hash of the refresh token"), - field.Time("expires_at"). - Comment("When the refresh token expires"), - field.Time("created_at"). - Default(time.Now). - Immutable(), - } -} - -// Indexes of the RefreshToken. -func (RefreshToken) Indexes() []ent.Index { - return []ent.Index{ - index.Fields("user_id"), - index.Fields("token_hash"), - index.Fields("expires_at"), - } -} diff --git a/internal/ent/schema/role.go b/internal/ent/schema/role.go deleted file mode 100644 index 689fa37..0000000 --- a/internal/ent/schema/role.go +++ /dev/null @@ -1,39 +0,0 @@ -package schema - -import ( - "time" - - "entgo.io/ent" - "entgo.io/ent/schema/edge" - "entgo.io/ent/schema/field" -) - -// Role holds the schema definition for the Role entity. -type Role struct { - ent.Schema -} - -// Fields of the Role. -func (Role) Fields() []ent.Field { - return []ent.Field{ - field.String("id"). - Unique(). - Immutable(), - field.String("name"). - Unique(). - NotEmpty(), - field.String("description"). - Optional(), - field.Time("created_at"). - Default(time.Now). - Immutable(), - } -} - -// Edges of the Role. -func (Role) Edges() []ent.Edge { - return []ent.Edge{ - edge.To("role_permissions", RolePermission.Type), - edge.To("user_roles", UserRole.Type), - } -} diff --git a/internal/ent/schema/role_permission.go b/internal/ent/schema/role_permission.go deleted file mode 100644 index 255c9b2..0000000 --- a/internal/ent/schema/role_permission.go +++ /dev/null @@ -1,34 +0,0 @@ -package schema - -import ( - "entgo.io/ent" - "entgo.io/ent/schema/edge" - "entgo.io/ent/schema/field" -) - -// RolePermission holds the schema definition for the RolePermission entity (many-to-many relationship). -type RolePermission struct { - ent.Schema -} - -// Fields of the RolePermission. -func (RolePermission) Fields() []ent.Field { - return []ent.Field{ - field.String("role_id"), - field.String("permission_id"), - } -} - -// Edges of the RolePermission. -func (RolePermission) Edges() []ent.Edge { - return []ent.Edge{ - edge.To("role", Role.Type). - Unique(). - Required(). - Field("role_id"), - edge.To("permission", Permission.Type). - Unique(). - Required(). - Field("permission_id"), - } -} diff --git a/internal/ent/schema/user.go b/internal/ent/schema/user.go deleted file mode 100644 index 086a074..0000000 --- a/internal/ent/schema/user.go +++ /dev/null @@ -1,57 +0,0 @@ -package schema - -import ( - "time" - - "entgo.io/ent" - "entgo.io/ent/schema/edge" - "entgo.io/ent/schema/field" -) - -// User holds the schema definition for the User entity. -type User struct { - ent.Schema -} - -// Fields of the User. -func (User) Fields() []ent.Field { - return []ent.Field{ - field.String("id"). - Unique(). - Immutable(), - field.String("email"). - Unique(). - NotEmpty(), - field.String("username"). - Optional(), - field.String("first_name"). - Optional(), - field.String("last_name"). - Optional(), - field.String("password_hash"). - NotEmpty(), - field.Bool("verified"). - Default(false), - field.String("email_verification_token"). - Optional(). - Sensitive(), - field.String("password_reset_token"). - Optional(). - Sensitive(), - field.Time("password_reset_expires_at"). - Optional(), - field.Time("created_at"). - Default(time.Now). - Immutable(), - field.Time("updated_at"). - Default(time.Now). - UpdateDefault(time.Now), - } -} - -// Edges of the User. -func (User) Edges() []ent.Edge { - return []ent.Edge{ - edge.To("user_roles", UserRole.Type), - } -} diff --git a/internal/ent/schema/user_role.go b/internal/ent/schema/user_role.go deleted file mode 100644 index bcfc366..0000000 --- a/internal/ent/schema/user_role.go +++ /dev/null @@ -1,34 +0,0 @@ -package schema - -import ( - "entgo.io/ent" - "entgo.io/ent/schema/edge" - "entgo.io/ent/schema/field" -) - -// UserRole holds the schema definition for the UserRole entity (many-to-many relationship). -type UserRole struct { - ent.Schema -} - -// Fields of the UserRole. -func (UserRole) Fields() []ent.Field { - return []ent.Field{ - field.String("user_id"), - field.String("role_id"), - } -} - -// Edges of the UserRole. -func (UserRole) Edges() []ent.Edge { - return []ent.Edge{ - edge.To("user", User.Type). - Unique(). - Required(). - Field("user_id"), - edge.To("role", Role.Type). - Unique(). - Required(). - Field("role_id"), - } -} diff --git a/internal/ent/tx.go b/internal/ent/tx.go deleted file mode 100644 index 6ad3b25..0000000 --- a/internal/ent/tx.go +++ /dev/null @@ -1,228 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "sync" - - "entgo.io/ent/dialect" -) - -// Tx is a transactional client that is created by calling Client.Tx(). -type Tx struct { - config - // AuditLog is the client for interacting with the AuditLog builders. - AuditLog *AuditLogClient - // Permission is the client for interacting with the Permission builders. - Permission *PermissionClient - // RefreshToken is the client for interacting with the RefreshToken builders. - RefreshToken *RefreshTokenClient - // Role is the client for interacting with the Role builders. - Role *RoleClient - // RolePermission is the client for interacting with the RolePermission builders. - RolePermission *RolePermissionClient - // User is the client for interacting with the User builders. - User *UserClient - // UserRole is the client for interacting with the UserRole builders. - UserRole *UserRoleClient - - // lazily loaded. - client *Client - clientOnce sync.Once - // ctx lives for the life of the transaction. It is - // the same context used by the underlying connection. - ctx context.Context -} - -type ( - // Committer is the interface that wraps the Commit method. - Committer interface { - Commit(context.Context, *Tx) error - } - - // The CommitFunc type is an adapter to allow the use of ordinary - // function as a Committer. If f is a function with the appropriate - // signature, CommitFunc(f) is a Committer that calls f. - CommitFunc func(context.Context, *Tx) error - - // CommitHook defines the "commit middleware". A function that gets a Committer - // and returns a Committer. For example: - // - // hook := func(next ent.Committer) ent.Committer { - // return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error { - // // Do some stuff before. - // if err := next.Commit(ctx, tx); err != nil { - // return err - // } - // // Do some stuff after. - // return nil - // }) - // } - // - CommitHook func(Committer) Committer -) - -// Commit calls f(ctx, m). -func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error { - return f(ctx, tx) -} - -// Commit commits the transaction. -func (tx *Tx) Commit() error { - txDriver := tx.config.driver.(*txDriver) - var fn Committer = CommitFunc(func(context.Context, *Tx) error { - return txDriver.tx.Commit() - }) - txDriver.mu.Lock() - hooks := append([]CommitHook(nil), txDriver.onCommit...) - txDriver.mu.Unlock() - for i := len(hooks) - 1; i >= 0; i-- { - fn = hooks[i](fn) - } - return fn.Commit(tx.ctx, tx) -} - -// OnCommit adds a hook to call on commit. -func (tx *Tx) OnCommit(f CommitHook) { - txDriver := tx.config.driver.(*txDriver) - txDriver.mu.Lock() - txDriver.onCommit = append(txDriver.onCommit, f) - txDriver.mu.Unlock() -} - -type ( - // Rollbacker is the interface that wraps the Rollback method. - Rollbacker interface { - Rollback(context.Context, *Tx) error - } - - // The RollbackFunc type is an adapter to allow the use of ordinary - // function as a Rollbacker. If f is a function with the appropriate - // signature, RollbackFunc(f) is a Rollbacker that calls f. - RollbackFunc func(context.Context, *Tx) error - - // RollbackHook defines the "rollback middleware". A function that gets a Rollbacker - // and returns a Rollbacker. For example: - // - // hook := func(next ent.Rollbacker) ent.Rollbacker { - // return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error { - // // Do some stuff before. - // if err := next.Rollback(ctx, tx); err != nil { - // return err - // } - // // Do some stuff after. - // return nil - // }) - // } - // - RollbackHook func(Rollbacker) Rollbacker -) - -// Rollback calls f(ctx, m). -func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error { - return f(ctx, tx) -} - -// Rollback rollbacks the transaction. -func (tx *Tx) Rollback() error { - txDriver := tx.config.driver.(*txDriver) - var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error { - return txDriver.tx.Rollback() - }) - txDriver.mu.Lock() - hooks := append([]RollbackHook(nil), txDriver.onRollback...) - txDriver.mu.Unlock() - for i := len(hooks) - 1; i >= 0; i-- { - fn = hooks[i](fn) - } - return fn.Rollback(tx.ctx, tx) -} - -// OnRollback adds a hook to call on rollback. -func (tx *Tx) OnRollback(f RollbackHook) { - txDriver := tx.config.driver.(*txDriver) - txDriver.mu.Lock() - txDriver.onRollback = append(txDriver.onRollback, f) - txDriver.mu.Unlock() -} - -// Client returns a Client that binds to current transaction. -func (tx *Tx) Client() *Client { - tx.clientOnce.Do(func() { - tx.client = &Client{config: tx.config} - tx.client.init() - }) - return tx.client -} - -func (tx *Tx) init() { - tx.AuditLog = NewAuditLogClient(tx.config) - tx.Permission = NewPermissionClient(tx.config) - tx.RefreshToken = NewRefreshTokenClient(tx.config) - tx.Role = NewRoleClient(tx.config) - tx.RolePermission = NewRolePermissionClient(tx.config) - tx.User = NewUserClient(tx.config) - tx.UserRole = NewUserRoleClient(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: AuditLog.QueryXXX(), the query will be executed -// through the driver which created this transaction. -// -// Note that txDriver is not goroutine safe. -type txDriver struct { - // the driver we started the transaction from. - drv dialect.Driver - // tx is the underlying transaction. - tx dialect.Tx - // completion hooks. - mu sync.Mutex - onCommit []CommitHook - onRollback []RollbackHook -} - -// newTx creates a new transactional driver. -func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) { - tx, err := drv.Tx(ctx) - if err != nil { - return nil, err - } - return &txDriver{tx: tx, drv: drv}, nil -} - -// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls -// from the internal builders. Should be called only by the internal builders. -func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil } - -// Dialect returns the dialect of the driver we started the transaction from. -func (tx *txDriver) Dialect() string { return tx.drv.Dialect() } - -// Close is a nop close. -func (*txDriver) Close() error { return nil } - -// Commit is a nop commit for the internal builders. -// User must call `Tx.Commit` in order to commit the transaction. -func (*txDriver) Commit() error { return nil } - -// Rollback is a nop rollback for the internal builders. -// User must call `Tx.Rollback` in order to rollback the transaction. -func (*txDriver) Rollback() error { return nil } - -// Exec calls tx.Exec. -func (tx *txDriver) Exec(ctx context.Context, query string, args, v any) error { - return tx.tx.Exec(ctx, query, args, v) -} - -// Query calls tx.Query. -func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error { - return tx.tx.Query(ctx, query, args, v) -} - -var _ dialect.Driver = (*txDriver)(nil) diff --git a/internal/ent/user.go b/internal/ent/user.go deleted file mode 100644 index 19557c3..0000000 --- a/internal/ent/user.go +++ /dev/null @@ -1,240 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "fmt" - "strings" - "time" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "git.dcentral.systems/toolz/goplt/internal/ent/user" -) - -// User is the model entity for the User schema. -type User struct { - config `json:"-"` - // ID of the ent. - ID string `json:"id,omitempty"` - // Email holds the value of the "email" field. - Email string `json:"email,omitempty"` - // Username holds the value of the "username" field. - Username string `json:"username,omitempty"` - // FirstName holds the value of the "first_name" field. - FirstName string `json:"first_name,omitempty"` - // LastName holds the value of the "last_name" field. - LastName string `json:"last_name,omitempty"` - // PasswordHash holds the value of the "password_hash" field. - PasswordHash string `json:"password_hash,omitempty"` - // Verified holds the value of the "verified" field. - Verified bool `json:"verified,omitempty"` - // EmailVerificationToken holds the value of the "email_verification_token" field. - EmailVerificationToken string `json:"-"` - // PasswordResetToken holds the value of the "password_reset_token" field. - PasswordResetToken string `json:"-"` - // PasswordResetExpiresAt holds the value of the "password_reset_expires_at" field. - PasswordResetExpiresAt time.Time `json:"password_reset_expires_at,omitempty"` - // CreatedAt holds the value of the "created_at" field. - CreatedAt time.Time `json:"created_at,omitempty"` - // UpdatedAt holds the value of the "updated_at" field. - UpdatedAt time.Time `json:"updated_at,omitempty"` - // Edges holds the relations/edges for other nodes in the graph. - // The values are being populated by the UserQuery when eager-loading is set. - Edges UserEdges `json:"edges"` - selectValues sql.SelectValues -} - -// UserEdges holds the relations/edges for other nodes in the graph. -type UserEdges struct { - // UserRoles holds the value of the user_roles edge. - UserRoles []*UserRole `json:"user_roles,omitempty"` - // loadedTypes holds the information for reporting if a - // type was loaded (or requested) in eager-loading or not. - loadedTypes [1]bool -} - -// UserRolesOrErr returns the UserRoles value or an error if the edge -// was not loaded in eager-loading. -func (e UserEdges) UserRolesOrErr() ([]*UserRole, error) { - if e.loadedTypes[0] { - return e.UserRoles, nil - } - return nil, &NotLoadedError{edge: "user_roles"} -} - -// scanValues returns the types for scanning values from sql.Rows. -func (*User) scanValues(columns []string) ([]any, error) { - values := make([]any, len(columns)) - for i := range columns { - switch columns[i] { - case user.FieldVerified: - values[i] = new(sql.NullBool) - case user.FieldID, user.FieldEmail, user.FieldUsername, user.FieldFirstName, user.FieldLastName, user.FieldPasswordHash, user.FieldEmailVerificationToken, user.FieldPasswordResetToken: - values[i] = new(sql.NullString) - case user.FieldPasswordResetExpiresAt, user.FieldCreatedAt, user.FieldUpdatedAt: - values[i] = new(sql.NullTime) - default: - values[i] = new(sql.UnknownType) - } - } - return values, nil -} - -// assignValues assigns the values that were returned from sql.Rows (after scanning) -// to the User fields. -func (_m *User) assignValues(columns []string, values []any) error { - if m, n := len(values), len(columns); m < n { - return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) - } - for i := range columns { - switch columns[i] { - case user.FieldID: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field id", values[i]) - } else if value.Valid { - _m.ID = value.String - } - case user.FieldEmail: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field email", values[i]) - } else if value.Valid { - _m.Email = value.String - } - case user.FieldUsername: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field username", values[i]) - } else if value.Valid { - _m.Username = value.String - } - case user.FieldFirstName: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field first_name", values[i]) - } else if value.Valid { - _m.FirstName = value.String - } - case user.FieldLastName: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field last_name", values[i]) - } else if value.Valid { - _m.LastName = value.String - } - case user.FieldPasswordHash: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field password_hash", values[i]) - } else if value.Valid { - _m.PasswordHash = value.String - } - case user.FieldVerified: - if value, ok := values[i].(*sql.NullBool); !ok { - return fmt.Errorf("unexpected type %T for field verified", values[i]) - } else if value.Valid { - _m.Verified = value.Bool - } - case user.FieldEmailVerificationToken: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field email_verification_token", values[i]) - } else if value.Valid { - _m.EmailVerificationToken = value.String - } - case user.FieldPasswordResetToken: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field password_reset_token", values[i]) - } else if value.Valid { - _m.PasswordResetToken = value.String - } - case user.FieldPasswordResetExpiresAt: - if value, ok := values[i].(*sql.NullTime); !ok { - return fmt.Errorf("unexpected type %T for field password_reset_expires_at", values[i]) - } else if value.Valid { - _m.PasswordResetExpiresAt = value.Time - } - case user.FieldCreatedAt: - if value, ok := values[i].(*sql.NullTime); !ok { - return fmt.Errorf("unexpected type %T for field created_at", values[i]) - } else if value.Valid { - _m.CreatedAt = value.Time - } - case user.FieldUpdatedAt: - if value, ok := values[i].(*sql.NullTime); !ok { - return fmt.Errorf("unexpected type %T for field updated_at", values[i]) - } else if value.Valid { - _m.UpdatedAt = value.Time - } - default: - _m.selectValues.Set(columns[i], values[i]) - } - } - return nil -} - -// Value returns the ent.Value that was dynamically selected and assigned to the User. -// This includes values selected through modifiers, order, etc. -func (_m *User) Value(name string) (ent.Value, error) { - return _m.selectValues.Get(name) -} - -// QueryUserRoles queries the "user_roles" edge of the User entity. -func (_m *User) QueryUserRoles() *UserRoleQuery { - return NewUserClient(_m.config).QueryUserRoles(_m) -} - -// Update returns a builder for updating this User. -// Note that you need to call User.Unwrap() before calling this method if this User -// was returned from a transaction, and the transaction was committed or rolled back. -func (_m *User) Update() *UserUpdateOne { - return NewUserClient(_m.config).UpdateOne(_m) -} - -// Unwrap unwraps the User entity that was returned from a transaction after it was closed, -// so that all future queries will be executed through the driver which created the transaction. -func (_m *User) Unwrap() *User { - _tx, ok := _m.config.driver.(*txDriver) - if !ok { - panic("ent: User is not a transactional entity") - } - _m.config.driver = _tx.drv - return _m -} - -// String implements the fmt.Stringer. -func (_m *User) String() string { - var builder strings.Builder - builder.WriteString("User(") - builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) - builder.WriteString("email=") - builder.WriteString(_m.Email) - builder.WriteString(", ") - builder.WriteString("username=") - builder.WriteString(_m.Username) - builder.WriteString(", ") - builder.WriteString("first_name=") - builder.WriteString(_m.FirstName) - builder.WriteString(", ") - builder.WriteString("last_name=") - builder.WriteString(_m.LastName) - builder.WriteString(", ") - builder.WriteString("password_hash=") - builder.WriteString(_m.PasswordHash) - builder.WriteString(", ") - builder.WriteString("verified=") - builder.WriteString(fmt.Sprintf("%v", _m.Verified)) - builder.WriteString(", ") - builder.WriteString("email_verification_token=") - builder.WriteString(", ") - builder.WriteString("password_reset_token=") - builder.WriteString(", ") - builder.WriteString("password_reset_expires_at=") - builder.WriteString(_m.PasswordResetExpiresAt.Format(time.ANSIC)) - builder.WriteString(", ") - builder.WriteString("created_at=") - builder.WriteString(_m.CreatedAt.Format(time.ANSIC)) - builder.WriteString(", ") - builder.WriteString("updated_at=") - builder.WriteString(_m.UpdatedAt.Format(time.ANSIC)) - builder.WriteByte(')') - return builder.String() -} - -// Users is a parsable slice of User. -type Users []*User diff --git a/internal/ent/user/user.go b/internal/ent/user/user.go deleted file mode 100644 index 50257b4..0000000 --- a/internal/ent/user/user.go +++ /dev/null @@ -1,175 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package user - -import ( - "time" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" -) - -const ( - // Label holds the string label denoting the user type in the database. - Label = "user" - // FieldID holds the string denoting the id field in the database. - FieldID = "id" - // FieldEmail holds the string denoting the email field in the database. - FieldEmail = "email" - // FieldUsername holds the string denoting the username field in the database. - FieldUsername = "username" - // FieldFirstName holds the string denoting the first_name field in the database. - FieldFirstName = "first_name" - // FieldLastName holds the string denoting the last_name field in the database. - FieldLastName = "last_name" - // FieldPasswordHash holds the string denoting the password_hash field in the database. - FieldPasswordHash = "password_hash" - // FieldVerified holds the string denoting the verified field in the database. - FieldVerified = "verified" - // FieldEmailVerificationToken holds the string denoting the email_verification_token field in the database. - FieldEmailVerificationToken = "email_verification_token" - // FieldPasswordResetToken holds the string denoting the password_reset_token field in the database. - FieldPasswordResetToken = "password_reset_token" - // FieldPasswordResetExpiresAt holds the string denoting the password_reset_expires_at field in the database. - FieldPasswordResetExpiresAt = "password_reset_expires_at" - // FieldCreatedAt holds the string denoting the created_at field in the database. - FieldCreatedAt = "created_at" - // FieldUpdatedAt holds the string denoting the updated_at field in the database. - FieldUpdatedAt = "updated_at" - // EdgeUserRoles holds the string denoting the user_roles edge name in mutations. - EdgeUserRoles = "user_roles" - // Table holds the table name of the user in the database. - Table = "users" - // UserRolesTable is the table that holds the user_roles relation/edge. - UserRolesTable = "user_roles" - // UserRolesInverseTable is the table name for the UserRole entity. - // It exists in this package in order to avoid circular dependency with the "userrole" package. - UserRolesInverseTable = "user_roles" - // UserRolesColumn is the table column denoting the user_roles relation/edge. - UserRolesColumn = "user_user_roles" -) - -// Columns holds all SQL columns for user fields. -var Columns = []string{ - FieldID, - FieldEmail, - FieldUsername, - FieldFirstName, - FieldLastName, - FieldPasswordHash, - FieldVerified, - FieldEmailVerificationToken, - FieldPasswordResetToken, - FieldPasswordResetExpiresAt, - FieldCreatedAt, - FieldUpdatedAt, -} - -// ValidColumn reports if the column name is valid (part of the table columns). -func ValidColumn(column string) bool { - for i := range Columns { - if column == Columns[i] { - return true - } - } - return false -} - -var ( - // EmailValidator is a validator for the "email" field. It is called by the builders before save. - EmailValidator func(string) error - // PasswordHashValidator is a validator for the "password_hash" field. It is called by the builders before save. - PasswordHashValidator func(string) error - // DefaultVerified holds the default value on creation for the "verified" field. - DefaultVerified bool - // DefaultCreatedAt holds the default value on creation for the "created_at" field. - DefaultCreatedAt func() time.Time - // DefaultUpdatedAt holds the default value on creation for the "updated_at" field. - DefaultUpdatedAt func() time.Time - // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field. - UpdateDefaultUpdatedAt func() time.Time -) - -// OrderOption defines the ordering options for the User queries. -type OrderOption func(*sql.Selector) - -// ByID orders the results by the id field. -func ByID(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldID, opts...).ToFunc() -} - -// ByEmail orders the results by the email field. -func ByEmail(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldEmail, opts...).ToFunc() -} - -// ByUsername orders the results by the username field. -func ByUsername(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldUsername, opts...).ToFunc() -} - -// ByFirstName orders the results by the first_name field. -func ByFirstName(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldFirstName, opts...).ToFunc() -} - -// ByLastName orders the results by the last_name field. -func ByLastName(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldLastName, opts...).ToFunc() -} - -// ByPasswordHash orders the results by the password_hash field. -func ByPasswordHash(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldPasswordHash, opts...).ToFunc() -} - -// ByVerified orders the results by the verified field. -func ByVerified(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldVerified, opts...).ToFunc() -} - -// ByEmailVerificationToken orders the results by the email_verification_token field. -func ByEmailVerificationToken(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldEmailVerificationToken, opts...).ToFunc() -} - -// ByPasswordResetToken orders the results by the password_reset_token field. -func ByPasswordResetToken(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldPasswordResetToken, opts...).ToFunc() -} - -// ByPasswordResetExpiresAt orders the results by the password_reset_expires_at field. -func ByPasswordResetExpiresAt(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldPasswordResetExpiresAt, opts...).ToFunc() -} - -// ByCreatedAt orders the results by the created_at field. -func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() -} - -// ByUpdatedAt orders the results by the updated_at field. -func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() -} - -// ByUserRolesCount orders the results by user_roles count. -func ByUserRolesCount(opts ...sql.OrderTermOption) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborsCount(s, newUserRolesStep(), opts...) - } -} - -// ByUserRoles orders the results by user_roles terms. -func ByUserRoles(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborTerms(s, newUserRolesStep(), append([]sql.OrderTerm{term}, terms...)...) - } -} -func newUserRolesStep() *sqlgraph.Step { - return sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(UserRolesInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, UserRolesTable, UserRolesColumn), - ) -} diff --git a/internal/ent/user/where.go b/internal/ent/user/where.go deleted file mode 100644 index fe45520..0000000 --- a/internal/ent/user/where.go +++ /dev/null @@ -1,804 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package user - -import ( - "time" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" -) - -// ID filters vertices based on their ID field. -func ID(id string) predicate.User { - return predicate.User(sql.FieldEQ(FieldID, id)) -} - -// IDEQ applies the EQ predicate on the ID field. -func IDEQ(id string) predicate.User { - return predicate.User(sql.FieldEQ(FieldID, id)) -} - -// IDNEQ applies the NEQ predicate on the ID field. -func IDNEQ(id string) predicate.User { - return predicate.User(sql.FieldNEQ(FieldID, id)) -} - -// IDIn applies the In predicate on the ID field. -func IDIn(ids ...string) predicate.User { - return predicate.User(sql.FieldIn(FieldID, ids...)) -} - -// IDNotIn applies the NotIn predicate on the ID field. -func IDNotIn(ids ...string) predicate.User { - return predicate.User(sql.FieldNotIn(FieldID, ids...)) -} - -// IDGT applies the GT predicate on the ID field. -func IDGT(id string) predicate.User { - return predicate.User(sql.FieldGT(FieldID, id)) -} - -// IDGTE applies the GTE predicate on the ID field. -func IDGTE(id string) predicate.User { - return predicate.User(sql.FieldGTE(FieldID, id)) -} - -// IDLT applies the LT predicate on the ID field. -func IDLT(id string) predicate.User { - return predicate.User(sql.FieldLT(FieldID, id)) -} - -// IDLTE applies the LTE predicate on the ID field. -func IDLTE(id string) predicate.User { - return predicate.User(sql.FieldLTE(FieldID, id)) -} - -// IDEqualFold applies the EqualFold predicate on the ID field. -func IDEqualFold(id string) predicate.User { - return predicate.User(sql.FieldEqualFold(FieldID, id)) -} - -// IDContainsFold applies the ContainsFold predicate on the ID field. -func IDContainsFold(id string) predicate.User { - return predicate.User(sql.FieldContainsFold(FieldID, id)) -} - -// Email applies equality check predicate on the "email" field. It's identical to EmailEQ. -func Email(v string) predicate.User { - return predicate.User(sql.FieldEQ(FieldEmail, v)) -} - -// Username applies equality check predicate on the "username" field. It's identical to UsernameEQ. -func Username(v string) predicate.User { - return predicate.User(sql.FieldEQ(FieldUsername, v)) -} - -// FirstName applies equality check predicate on the "first_name" field. It's identical to FirstNameEQ. -func FirstName(v string) predicate.User { - return predicate.User(sql.FieldEQ(FieldFirstName, v)) -} - -// LastName applies equality check predicate on the "last_name" field. It's identical to LastNameEQ. -func LastName(v string) predicate.User { - return predicate.User(sql.FieldEQ(FieldLastName, v)) -} - -// PasswordHash applies equality check predicate on the "password_hash" field. It's identical to PasswordHashEQ. -func PasswordHash(v string) predicate.User { - return predicate.User(sql.FieldEQ(FieldPasswordHash, v)) -} - -// Verified applies equality check predicate on the "verified" field. It's identical to VerifiedEQ. -func Verified(v bool) predicate.User { - return predicate.User(sql.FieldEQ(FieldVerified, v)) -} - -// EmailVerificationToken applies equality check predicate on the "email_verification_token" field. It's identical to EmailVerificationTokenEQ. -func EmailVerificationToken(v string) predicate.User { - return predicate.User(sql.FieldEQ(FieldEmailVerificationToken, v)) -} - -// PasswordResetToken applies equality check predicate on the "password_reset_token" field. It's identical to PasswordResetTokenEQ. -func PasswordResetToken(v string) predicate.User { - return predicate.User(sql.FieldEQ(FieldPasswordResetToken, v)) -} - -// PasswordResetExpiresAt applies equality check predicate on the "password_reset_expires_at" field. It's identical to PasswordResetExpiresAtEQ. -func PasswordResetExpiresAt(v time.Time) predicate.User { - return predicate.User(sql.FieldEQ(FieldPasswordResetExpiresAt, v)) -} - -// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. -func CreatedAt(v time.Time) predicate.User { - return predicate.User(sql.FieldEQ(FieldCreatedAt, v)) -} - -// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. -func UpdatedAt(v time.Time) predicate.User { - return predicate.User(sql.FieldEQ(FieldUpdatedAt, v)) -} - -// EmailEQ applies the EQ predicate on the "email" field. -func EmailEQ(v string) predicate.User { - return predicate.User(sql.FieldEQ(FieldEmail, v)) -} - -// EmailNEQ applies the NEQ predicate on the "email" field. -func EmailNEQ(v string) predicate.User { - return predicate.User(sql.FieldNEQ(FieldEmail, v)) -} - -// EmailIn applies the In predicate on the "email" field. -func EmailIn(vs ...string) predicate.User { - return predicate.User(sql.FieldIn(FieldEmail, vs...)) -} - -// EmailNotIn applies the NotIn predicate on the "email" field. -func EmailNotIn(vs ...string) predicate.User { - return predicate.User(sql.FieldNotIn(FieldEmail, vs...)) -} - -// EmailGT applies the GT predicate on the "email" field. -func EmailGT(v string) predicate.User { - return predicate.User(sql.FieldGT(FieldEmail, v)) -} - -// EmailGTE applies the GTE predicate on the "email" field. -func EmailGTE(v string) predicate.User { - return predicate.User(sql.FieldGTE(FieldEmail, v)) -} - -// EmailLT applies the LT predicate on the "email" field. -func EmailLT(v string) predicate.User { - return predicate.User(sql.FieldLT(FieldEmail, v)) -} - -// EmailLTE applies the LTE predicate on the "email" field. -func EmailLTE(v string) predicate.User { - return predicate.User(sql.FieldLTE(FieldEmail, v)) -} - -// EmailContains applies the Contains predicate on the "email" field. -func EmailContains(v string) predicate.User { - return predicate.User(sql.FieldContains(FieldEmail, v)) -} - -// EmailHasPrefix applies the HasPrefix predicate on the "email" field. -func EmailHasPrefix(v string) predicate.User { - return predicate.User(sql.FieldHasPrefix(FieldEmail, v)) -} - -// EmailHasSuffix applies the HasSuffix predicate on the "email" field. -func EmailHasSuffix(v string) predicate.User { - return predicate.User(sql.FieldHasSuffix(FieldEmail, v)) -} - -// EmailEqualFold applies the EqualFold predicate on the "email" field. -func EmailEqualFold(v string) predicate.User { - return predicate.User(sql.FieldEqualFold(FieldEmail, v)) -} - -// EmailContainsFold applies the ContainsFold predicate on the "email" field. -func EmailContainsFold(v string) predicate.User { - return predicate.User(sql.FieldContainsFold(FieldEmail, v)) -} - -// UsernameEQ applies the EQ predicate on the "username" field. -func UsernameEQ(v string) predicate.User { - return predicate.User(sql.FieldEQ(FieldUsername, v)) -} - -// UsernameNEQ applies the NEQ predicate on the "username" field. -func UsernameNEQ(v string) predicate.User { - return predicate.User(sql.FieldNEQ(FieldUsername, v)) -} - -// UsernameIn applies the In predicate on the "username" field. -func UsernameIn(vs ...string) predicate.User { - return predicate.User(sql.FieldIn(FieldUsername, vs...)) -} - -// UsernameNotIn applies the NotIn predicate on the "username" field. -func UsernameNotIn(vs ...string) predicate.User { - return predicate.User(sql.FieldNotIn(FieldUsername, vs...)) -} - -// UsernameGT applies the GT predicate on the "username" field. -func UsernameGT(v string) predicate.User { - return predicate.User(sql.FieldGT(FieldUsername, v)) -} - -// UsernameGTE applies the GTE predicate on the "username" field. -func UsernameGTE(v string) predicate.User { - return predicate.User(sql.FieldGTE(FieldUsername, v)) -} - -// UsernameLT applies the LT predicate on the "username" field. -func UsernameLT(v string) predicate.User { - return predicate.User(sql.FieldLT(FieldUsername, v)) -} - -// UsernameLTE applies the LTE predicate on the "username" field. -func UsernameLTE(v string) predicate.User { - return predicate.User(sql.FieldLTE(FieldUsername, v)) -} - -// UsernameContains applies the Contains predicate on the "username" field. -func UsernameContains(v string) predicate.User { - return predicate.User(sql.FieldContains(FieldUsername, v)) -} - -// UsernameHasPrefix applies the HasPrefix predicate on the "username" field. -func UsernameHasPrefix(v string) predicate.User { - return predicate.User(sql.FieldHasPrefix(FieldUsername, v)) -} - -// UsernameHasSuffix applies the HasSuffix predicate on the "username" field. -func UsernameHasSuffix(v string) predicate.User { - return predicate.User(sql.FieldHasSuffix(FieldUsername, v)) -} - -// UsernameIsNil applies the IsNil predicate on the "username" field. -func UsernameIsNil() predicate.User { - return predicate.User(sql.FieldIsNull(FieldUsername)) -} - -// UsernameNotNil applies the NotNil predicate on the "username" field. -func UsernameNotNil() predicate.User { - return predicate.User(sql.FieldNotNull(FieldUsername)) -} - -// UsernameEqualFold applies the EqualFold predicate on the "username" field. -func UsernameEqualFold(v string) predicate.User { - return predicate.User(sql.FieldEqualFold(FieldUsername, v)) -} - -// UsernameContainsFold applies the ContainsFold predicate on the "username" field. -func UsernameContainsFold(v string) predicate.User { - return predicate.User(sql.FieldContainsFold(FieldUsername, v)) -} - -// FirstNameEQ applies the EQ predicate on the "first_name" field. -func FirstNameEQ(v string) predicate.User { - return predicate.User(sql.FieldEQ(FieldFirstName, v)) -} - -// FirstNameNEQ applies the NEQ predicate on the "first_name" field. -func FirstNameNEQ(v string) predicate.User { - return predicate.User(sql.FieldNEQ(FieldFirstName, v)) -} - -// FirstNameIn applies the In predicate on the "first_name" field. -func FirstNameIn(vs ...string) predicate.User { - return predicate.User(sql.FieldIn(FieldFirstName, vs...)) -} - -// FirstNameNotIn applies the NotIn predicate on the "first_name" field. -func FirstNameNotIn(vs ...string) predicate.User { - return predicate.User(sql.FieldNotIn(FieldFirstName, vs...)) -} - -// FirstNameGT applies the GT predicate on the "first_name" field. -func FirstNameGT(v string) predicate.User { - return predicate.User(sql.FieldGT(FieldFirstName, v)) -} - -// FirstNameGTE applies the GTE predicate on the "first_name" field. -func FirstNameGTE(v string) predicate.User { - return predicate.User(sql.FieldGTE(FieldFirstName, v)) -} - -// FirstNameLT applies the LT predicate on the "first_name" field. -func FirstNameLT(v string) predicate.User { - return predicate.User(sql.FieldLT(FieldFirstName, v)) -} - -// FirstNameLTE applies the LTE predicate on the "first_name" field. -func FirstNameLTE(v string) predicate.User { - return predicate.User(sql.FieldLTE(FieldFirstName, v)) -} - -// FirstNameContains applies the Contains predicate on the "first_name" field. -func FirstNameContains(v string) predicate.User { - return predicate.User(sql.FieldContains(FieldFirstName, v)) -} - -// FirstNameHasPrefix applies the HasPrefix predicate on the "first_name" field. -func FirstNameHasPrefix(v string) predicate.User { - return predicate.User(sql.FieldHasPrefix(FieldFirstName, v)) -} - -// FirstNameHasSuffix applies the HasSuffix predicate on the "first_name" field. -func FirstNameHasSuffix(v string) predicate.User { - return predicate.User(sql.FieldHasSuffix(FieldFirstName, v)) -} - -// FirstNameIsNil applies the IsNil predicate on the "first_name" field. -func FirstNameIsNil() predicate.User { - return predicate.User(sql.FieldIsNull(FieldFirstName)) -} - -// FirstNameNotNil applies the NotNil predicate on the "first_name" field. -func FirstNameNotNil() predicate.User { - return predicate.User(sql.FieldNotNull(FieldFirstName)) -} - -// FirstNameEqualFold applies the EqualFold predicate on the "first_name" field. -func FirstNameEqualFold(v string) predicate.User { - return predicate.User(sql.FieldEqualFold(FieldFirstName, v)) -} - -// FirstNameContainsFold applies the ContainsFold predicate on the "first_name" field. -func FirstNameContainsFold(v string) predicate.User { - return predicate.User(sql.FieldContainsFold(FieldFirstName, v)) -} - -// LastNameEQ applies the EQ predicate on the "last_name" field. -func LastNameEQ(v string) predicate.User { - return predicate.User(sql.FieldEQ(FieldLastName, v)) -} - -// LastNameNEQ applies the NEQ predicate on the "last_name" field. -func LastNameNEQ(v string) predicate.User { - return predicate.User(sql.FieldNEQ(FieldLastName, v)) -} - -// LastNameIn applies the In predicate on the "last_name" field. -func LastNameIn(vs ...string) predicate.User { - return predicate.User(sql.FieldIn(FieldLastName, vs...)) -} - -// LastNameNotIn applies the NotIn predicate on the "last_name" field. -func LastNameNotIn(vs ...string) predicate.User { - return predicate.User(sql.FieldNotIn(FieldLastName, vs...)) -} - -// LastNameGT applies the GT predicate on the "last_name" field. -func LastNameGT(v string) predicate.User { - return predicate.User(sql.FieldGT(FieldLastName, v)) -} - -// LastNameGTE applies the GTE predicate on the "last_name" field. -func LastNameGTE(v string) predicate.User { - return predicate.User(sql.FieldGTE(FieldLastName, v)) -} - -// LastNameLT applies the LT predicate on the "last_name" field. -func LastNameLT(v string) predicate.User { - return predicate.User(sql.FieldLT(FieldLastName, v)) -} - -// LastNameLTE applies the LTE predicate on the "last_name" field. -func LastNameLTE(v string) predicate.User { - return predicate.User(sql.FieldLTE(FieldLastName, v)) -} - -// LastNameContains applies the Contains predicate on the "last_name" field. -func LastNameContains(v string) predicate.User { - return predicate.User(sql.FieldContains(FieldLastName, v)) -} - -// LastNameHasPrefix applies the HasPrefix predicate on the "last_name" field. -func LastNameHasPrefix(v string) predicate.User { - return predicate.User(sql.FieldHasPrefix(FieldLastName, v)) -} - -// LastNameHasSuffix applies the HasSuffix predicate on the "last_name" field. -func LastNameHasSuffix(v string) predicate.User { - return predicate.User(sql.FieldHasSuffix(FieldLastName, v)) -} - -// LastNameIsNil applies the IsNil predicate on the "last_name" field. -func LastNameIsNil() predicate.User { - return predicate.User(sql.FieldIsNull(FieldLastName)) -} - -// LastNameNotNil applies the NotNil predicate on the "last_name" field. -func LastNameNotNil() predicate.User { - return predicate.User(sql.FieldNotNull(FieldLastName)) -} - -// LastNameEqualFold applies the EqualFold predicate on the "last_name" field. -func LastNameEqualFold(v string) predicate.User { - return predicate.User(sql.FieldEqualFold(FieldLastName, v)) -} - -// LastNameContainsFold applies the ContainsFold predicate on the "last_name" field. -func LastNameContainsFold(v string) predicate.User { - return predicate.User(sql.FieldContainsFold(FieldLastName, v)) -} - -// PasswordHashEQ applies the EQ predicate on the "password_hash" field. -func PasswordHashEQ(v string) predicate.User { - return predicate.User(sql.FieldEQ(FieldPasswordHash, v)) -} - -// PasswordHashNEQ applies the NEQ predicate on the "password_hash" field. -func PasswordHashNEQ(v string) predicate.User { - return predicate.User(sql.FieldNEQ(FieldPasswordHash, v)) -} - -// PasswordHashIn applies the In predicate on the "password_hash" field. -func PasswordHashIn(vs ...string) predicate.User { - return predicate.User(sql.FieldIn(FieldPasswordHash, vs...)) -} - -// PasswordHashNotIn applies the NotIn predicate on the "password_hash" field. -func PasswordHashNotIn(vs ...string) predicate.User { - return predicate.User(sql.FieldNotIn(FieldPasswordHash, vs...)) -} - -// PasswordHashGT applies the GT predicate on the "password_hash" field. -func PasswordHashGT(v string) predicate.User { - return predicate.User(sql.FieldGT(FieldPasswordHash, v)) -} - -// PasswordHashGTE applies the GTE predicate on the "password_hash" field. -func PasswordHashGTE(v string) predicate.User { - return predicate.User(sql.FieldGTE(FieldPasswordHash, v)) -} - -// PasswordHashLT applies the LT predicate on the "password_hash" field. -func PasswordHashLT(v string) predicate.User { - return predicate.User(sql.FieldLT(FieldPasswordHash, v)) -} - -// PasswordHashLTE applies the LTE predicate on the "password_hash" field. -func PasswordHashLTE(v string) predicate.User { - return predicate.User(sql.FieldLTE(FieldPasswordHash, v)) -} - -// PasswordHashContains applies the Contains predicate on the "password_hash" field. -func PasswordHashContains(v string) predicate.User { - return predicate.User(sql.FieldContains(FieldPasswordHash, v)) -} - -// PasswordHashHasPrefix applies the HasPrefix predicate on the "password_hash" field. -func PasswordHashHasPrefix(v string) predicate.User { - return predicate.User(sql.FieldHasPrefix(FieldPasswordHash, v)) -} - -// PasswordHashHasSuffix applies the HasSuffix predicate on the "password_hash" field. -func PasswordHashHasSuffix(v string) predicate.User { - return predicate.User(sql.FieldHasSuffix(FieldPasswordHash, v)) -} - -// PasswordHashEqualFold applies the EqualFold predicate on the "password_hash" field. -func PasswordHashEqualFold(v string) predicate.User { - return predicate.User(sql.FieldEqualFold(FieldPasswordHash, v)) -} - -// PasswordHashContainsFold applies the ContainsFold predicate on the "password_hash" field. -func PasswordHashContainsFold(v string) predicate.User { - return predicate.User(sql.FieldContainsFold(FieldPasswordHash, v)) -} - -// VerifiedEQ applies the EQ predicate on the "verified" field. -func VerifiedEQ(v bool) predicate.User { - return predicate.User(sql.FieldEQ(FieldVerified, v)) -} - -// VerifiedNEQ applies the NEQ predicate on the "verified" field. -func VerifiedNEQ(v bool) predicate.User { - return predicate.User(sql.FieldNEQ(FieldVerified, v)) -} - -// EmailVerificationTokenEQ applies the EQ predicate on the "email_verification_token" field. -func EmailVerificationTokenEQ(v string) predicate.User { - return predicate.User(sql.FieldEQ(FieldEmailVerificationToken, v)) -} - -// EmailVerificationTokenNEQ applies the NEQ predicate on the "email_verification_token" field. -func EmailVerificationTokenNEQ(v string) predicate.User { - return predicate.User(sql.FieldNEQ(FieldEmailVerificationToken, v)) -} - -// EmailVerificationTokenIn applies the In predicate on the "email_verification_token" field. -func EmailVerificationTokenIn(vs ...string) predicate.User { - return predicate.User(sql.FieldIn(FieldEmailVerificationToken, vs...)) -} - -// EmailVerificationTokenNotIn applies the NotIn predicate on the "email_verification_token" field. -func EmailVerificationTokenNotIn(vs ...string) predicate.User { - return predicate.User(sql.FieldNotIn(FieldEmailVerificationToken, vs...)) -} - -// EmailVerificationTokenGT applies the GT predicate on the "email_verification_token" field. -func EmailVerificationTokenGT(v string) predicate.User { - return predicate.User(sql.FieldGT(FieldEmailVerificationToken, v)) -} - -// EmailVerificationTokenGTE applies the GTE predicate on the "email_verification_token" field. -func EmailVerificationTokenGTE(v string) predicate.User { - return predicate.User(sql.FieldGTE(FieldEmailVerificationToken, v)) -} - -// EmailVerificationTokenLT applies the LT predicate on the "email_verification_token" field. -func EmailVerificationTokenLT(v string) predicate.User { - return predicate.User(sql.FieldLT(FieldEmailVerificationToken, v)) -} - -// EmailVerificationTokenLTE applies the LTE predicate on the "email_verification_token" field. -func EmailVerificationTokenLTE(v string) predicate.User { - return predicate.User(sql.FieldLTE(FieldEmailVerificationToken, v)) -} - -// EmailVerificationTokenContains applies the Contains predicate on the "email_verification_token" field. -func EmailVerificationTokenContains(v string) predicate.User { - return predicate.User(sql.FieldContains(FieldEmailVerificationToken, v)) -} - -// EmailVerificationTokenHasPrefix applies the HasPrefix predicate on the "email_verification_token" field. -func EmailVerificationTokenHasPrefix(v string) predicate.User { - return predicate.User(sql.FieldHasPrefix(FieldEmailVerificationToken, v)) -} - -// EmailVerificationTokenHasSuffix applies the HasSuffix predicate on the "email_verification_token" field. -func EmailVerificationTokenHasSuffix(v string) predicate.User { - return predicate.User(sql.FieldHasSuffix(FieldEmailVerificationToken, v)) -} - -// EmailVerificationTokenIsNil applies the IsNil predicate on the "email_verification_token" field. -func EmailVerificationTokenIsNil() predicate.User { - return predicate.User(sql.FieldIsNull(FieldEmailVerificationToken)) -} - -// EmailVerificationTokenNotNil applies the NotNil predicate on the "email_verification_token" field. -func EmailVerificationTokenNotNil() predicate.User { - return predicate.User(sql.FieldNotNull(FieldEmailVerificationToken)) -} - -// EmailVerificationTokenEqualFold applies the EqualFold predicate on the "email_verification_token" field. -func EmailVerificationTokenEqualFold(v string) predicate.User { - return predicate.User(sql.FieldEqualFold(FieldEmailVerificationToken, v)) -} - -// EmailVerificationTokenContainsFold applies the ContainsFold predicate on the "email_verification_token" field. -func EmailVerificationTokenContainsFold(v string) predicate.User { - return predicate.User(sql.FieldContainsFold(FieldEmailVerificationToken, v)) -} - -// PasswordResetTokenEQ applies the EQ predicate on the "password_reset_token" field. -func PasswordResetTokenEQ(v string) predicate.User { - return predicate.User(sql.FieldEQ(FieldPasswordResetToken, v)) -} - -// PasswordResetTokenNEQ applies the NEQ predicate on the "password_reset_token" field. -func PasswordResetTokenNEQ(v string) predicate.User { - return predicate.User(sql.FieldNEQ(FieldPasswordResetToken, v)) -} - -// PasswordResetTokenIn applies the In predicate on the "password_reset_token" field. -func PasswordResetTokenIn(vs ...string) predicate.User { - return predicate.User(sql.FieldIn(FieldPasswordResetToken, vs...)) -} - -// PasswordResetTokenNotIn applies the NotIn predicate on the "password_reset_token" field. -func PasswordResetTokenNotIn(vs ...string) predicate.User { - return predicate.User(sql.FieldNotIn(FieldPasswordResetToken, vs...)) -} - -// PasswordResetTokenGT applies the GT predicate on the "password_reset_token" field. -func PasswordResetTokenGT(v string) predicate.User { - return predicate.User(sql.FieldGT(FieldPasswordResetToken, v)) -} - -// PasswordResetTokenGTE applies the GTE predicate on the "password_reset_token" field. -func PasswordResetTokenGTE(v string) predicate.User { - return predicate.User(sql.FieldGTE(FieldPasswordResetToken, v)) -} - -// PasswordResetTokenLT applies the LT predicate on the "password_reset_token" field. -func PasswordResetTokenLT(v string) predicate.User { - return predicate.User(sql.FieldLT(FieldPasswordResetToken, v)) -} - -// PasswordResetTokenLTE applies the LTE predicate on the "password_reset_token" field. -func PasswordResetTokenLTE(v string) predicate.User { - return predicate.User(sql.FieldLTE(FieldPasswordResetToken, v)) -} - -// PasswordResetTokenContains applies the Contains predicate on the "password_reset_token" field. -func PasswordResetTokenContains(v string) predicate.User { - return predicate.User(sql.FieldContains(FieldPasswordResetToken, v)) -} - -// PasswordResetTokenHasPrefix applies the HasPrefix predicate on the "password_reset_token" field. -func PasswordResetTokenHasPrefix(v string) predicate.User { - return predicate.User(sql.FieldHasPrefix(FieldPasswordResetToken, v)) -} - -// PasswordResetTokenHasSuffix applies the HasSuffix predicate on the "password_reset_token" field. -func PasswordResetTokenHasSuffix(v string) predicate.User { - return predicate.User(sql.FieldHasSuffix(FieldPasswordResetToken, v)) -} - -// PasswordResetTokenIsNil applies the IsNil predicate on the "password_reset_token" field. -func PasswordResetTokenIsNil() predicate.User { - return predicate.User(sql.FieldIsNull(FieldPasswordResetToken)) -} - -// PasswordResetTokenNotNil applies the NotNil predicate on the "password_reset_token" field. -func PasswordResetTokenNotNil() predicate.User { - return predicate.User(sql.FieldNotNull(FieldPasswordResetToken)) -} - -// PasswordResetTokenEqualFold applies the EqualFold predicate on the "password_reset_token" field. -func PasswordResetTokenEqualFold(v string) predicate.User { - return predicate.User(sql.FieldEqualFold(FieldPasswordResetToken, v)) -} - -// PasswordResetTokenContainsFold applies the ContainsFold predicate on the "password_reset_token" field. -func PasswordResetTokenContainsFold(v string) predicate.User { - return predicate.User(sql.FieldContainsFold(FieldPasswordResetToken, v)) -} - -// PasswordResetExpiresAtEQ applies the EQ predicate on the "password_reset_expires_at" field. -func PasswordResetExpiresAtEQ(v time.Time) predicate.User { - return predicate.User(sql.FieldEQ(FieldPasswordResetExpiresAt, v)) -} - -// PasswordResetExpiresAtNEQ applies the NEQ predicate on the "password_reset_expires_at" field. -func PasswordResetExpiresAtNEQ(v time.Time) predicate.User { - return predicate.User(sql.FieldNEQ(FieldPasswordResetExpiresAt, v)) -} - -// PasswordResetExpiresAtIn applies the In predicate on the "password_reset_expires_at" field. -func PasswordResetExpiresAtIn(vs ...time.Time) predicate.User { - return predicate.User(sql.FieldIn(FieldPasswordResetExpiresAt, vs...)) -} - -// PasswordResetExpiresAtNotIn applies the NotIn predicate on the "password_reset_expires_at" field. -func PasswordResetExpiresAtNotIn(vs ...time.Time) predicate.User { - return predicate.User(sql.FieldNotIn(FieldPasswordResetExpiresAt, vs...)) -} - -// PasswordResetExpiresAtGT applies the GT predicate on the "password_reset_expires_at" field. -func PasswordResetExpiresAtGT(v time.Time) predicate.User { - return predicate.User(sql.FieldGT(FieldPasswordResetExpiresAt, v)) -} - -// PasswordResetExpiresAtGTE applies the GTE predicate on the "password_reset_expires_at" field. -func PasswordResetExpiresAtGTE(v time.Time) predicate.User { - return predicate.User(sql.FieldGTE(FieldPasswordResetExpiresAt, v)) -} - -// PasswordResetExpiresAtLT applies the LT predicate on the "password_reset_expires_at" field. -func PasswordResetExpiresAtLT(v time.Time) predicate.User { - return predicate.User(sql.FieldLT(FieldPasswordResetExpiresAt, v)) -} - -// PasswordResetExpiresAtLTE applies the LTE predicate on the "password_reset_expires_at" field. -func PasswordResetExpiresAtLTE(v time.Time) predicate.User { - return predicate.User(sql.FieldLTE(FieldPasswordResetExpiresAt, v)) -} - -// PasswordResetExpiresAtIsNil applies the IsNil predicate on the "password_reset_expires_at" field. -func PasswordResetExpiresAtIsNil() predicate.User { - return predicate.User(sql.FieldIsNull(FieldPasswordResetExpiresAt)) -} - -// PasswordResetExpiresAtNotNil applies the NotNil predicate on the "password_reset_expires_at" field. -func PasswordResetExpiresAtNotNil() predicate.User { - return predicate.User(sql.FieldNotNull(FieldPasswordResetExpiresAt)) -} - -// CreatedAtEQ applies the EQ predicate on the "created_at" field. -func CreatedAtEQ(v time.Time) predicate.User { - return predicate.User(sql.FieldEQ(FieldCreatedAt, v)) -} - -// CreatedAtNEQ applies the NEQ predicate on the "created_at" field. -func CreatedAtNEQ(v time.Time) predicate.User { - return predicate.User(sql.FieldNEQ(FieldCreatedAt, v)) -} - -// CreatedAtIn applies the In predicate on the "created_at" field. -func CreatedAtIn(vs ...time.Time) predicate.User { - return predicate.User(sql.FieldIn(FieldCreatedAt, vs...)) -} - -// CreatedAtNotIn applies the NotIn predicate on the "created_at" field. -func CreatedAtNotIn(vs ...time.Time) predicate.User { - return predicate.User(sql.FieldNotIn(FieldCreatedAt, vs...)) -} - -// CreatedAtGT applies the GT predicate on the "created_at" field. -func CreatedAtGT(v time.Time) predicate.User { - return predicate.User(sql.FieldGT(FieldCreatedAt, v)) -} - -// CreatedAtGTE applies the GTE predicate on the "created_at" field. -func CreatedAtGTE(v time.Time) predicate.User { - return predicate.User(sql.FieldGTE(FieldCreatedAt, v)) -} - -// CreatedAtLT applies the LT predicate on the "created_at" field. -func CreatedAtLT(v time.Time) predicate.User { - return predicate.User(sql.FieldLT(FieldCreatedAt, v)) -} - -// CreatedAtLTE applies the LTE predicate on the "created_at" field. -func CreatedAtLTE(v time.Time) predicate.User { - return predicate.User(sql.FieldLTE(FieldCreatedAt, v)) -} - -// UpdatedAtEQ applies the EQ predicate on the "updated_at" field. -func UpdatedAtEQ(v time.Time) predicate.User { - return predicate.User(sql.FieldEQ(FieldUpdatedAt, v)) -} - -// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. -func UpdatedAtNEQ(v time.Time) predicate.User { - return predicate.User(sql.FieldNEQ(FieldUpdatedAt, v)) -} - -// UpdatedAtIn applies the In predicate on the "updated_at" field. -func UpdatedAtIn(vs ...time.Time) predicate.User { - return predicate.User(sql.FieldIn(FieldUpdatedAt, vs...)) -} - -// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. -func UpdatedAtNotIn(vs ...time.Time) predicate.User { - return predicate.User(sql.FieldNotIn(FieldUpdatedAt, vs...)) -} - -// UpdatedAtGT applies the GT predicate on the "updated_at" field. -func UpdatedAtGT(v time.Time) predicate.User { - return predicate.User(sql.FieldGT(FieldUpdatedAt, v)) -} - -// UpdatedAtGTE applies the GTE predicate on the "updated_at" field. -func UpdatedAtGTE(v time.Time) predicate.User { - return predicate.User(sql.FieldGTE(FieldUpdatedAt, v)) -} - -// UpdatedAtLT applies the LT predicate on the "updated_at" field. -func UpdatedAtLT(v time.Time) predicate.User { - return predicate.User(sql.FieldLT(FieldUpdatedAt, v)) -} - -// UpdatedAtLTE applies the LTE predicate on the "updated_at" field. -func UpdatedAtLTE(v time.Time) predicate.User { - return predicate.User(sql.FieldLTE(FieldUpdatedAt, v)) -} - -// HasUserRoles applies the HasEdge predicate on the "user_roles" edge. -func HasUserRoles() predicate.User { - return predicate.User(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, UserRolesTable, UserRolesColumn), - ) - sqlgraph.HasNeighbors(s, step) - }) -} - -// HasUserRolesWith applies the HasEdge predicate on the "user_roles" edge with a given conditions (other predicates). -func HasUserRolesWith(preds ...predicate.UserRole) predicate.User { - return predicate.User(func(s *sql.Selector) { - step := newUserRolesStep() - sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { - for _, p := range preds { - p(s) - } - }) - }) -} - -// And groups predicates with the AND operator between them. -func And(predicates ...predicate.User) predicate.User { - return predicate.User(sql.AndPredicates(predicates...)) -} - -// Or groups predicates with the OR operator between them. -func Or(predicates ...predicate.User) predicate.User { - return predicate.User(sql.OrPredicates(predicates...)) -} - -// Not applies the not operator on the given predicate. -func Not(p predicate.User) predicate.User { - return predicate.User(sql.NotPredicates(p)) -} diff --git a/internal/ent/user_create.go b/internal/ent/user_create.go deleted file mode 100644 index d0a6ea5..0000000 --- a/internal/ent/user_create.go +++ /dev/null @@ -1,439 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "errors" - "fmt" - "time" - - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/internal/ent/user" - "git.dcentral.systems/toolz/goplt/internal/ent/userrole" -) - -// UserCreate is the builder for creating a User entity. -type UserCreate struct { - config - mutation *UserMutation - hooks []Hook -} - -// SetEmail sets the "email" field. -func (_c *UserCreate) SetEmail(v string) *UserCreate { - _c.mutation.SetEmail(v) - return _c -} - -// SetUsername sets the "username" field. -func (_c *UserCreate) SetUsername(v string) *UserCreate { - _c.mutation.SetUsername(v) - return _c -} - -// SetNillableUsername sets the "username" field if the given value is not nil. -func (_c *UserCreate) SetNillableUsername(v *string) *UserCreate { - if v != nil { - _c.SetUsername(*v) - } - return _c -} - -// SetFirstName sets the "first_name" field. -func (_c *UserCreate) SetFirstName(v string) *UserCreate { - _c.mutation.SetFirstName(v) - return _c -} - -// SetNillableFirstName sets the "first_name" field if the given value is not nil. -func (_c *UserCreate) SetNillableFirstName(v *string) *UserCreate { - if v != nil { - _c.SetFirstName(*v) - } - return _c -} - -// SetLastName sets the "last_name" field. -func (_c *UserCreate) SetLastName(v string) *UserCreate { - _c.mutation.SetLastName(v) - return _c -} - -// SetNillableLastName sets the "last_name" field if the given value is not nil. -func (_c *UserCreate) SetNillableLastName(v *string) *UserCreate { - if v != nil { - _c.SetLastName(*v) - } - return _c -} - -// SetPasswordHash sets the "password_hash" field. -func (_c *UserCreate) SetPasswordHash(v string) *UserCreate { - _c.mutation.SetPasswordHash(v) - return _c -} - -// SetVerified sets the "verified" field. -func (_c *UserCreate) SetVerified(v bool) *UserCreate { - _c.mutation.SetVerified(v) - return _c -} - -// SetNillableVerified sets the "verified" field if the given value is not nil. -func (_c *UserCreate) SetNillableVerified(v *bool) *UserCreate { - if v != nil { - _c.SetVerified(*v) - } - return _c -} - -// SetEmailVerificationToken sets the "email_verification_token" field. -func (_c *UserCreate) SetEmailVerificationToken(v string) *UserCreate { - _c.mutation.SetEmailVerificationToken(v) - return _c -} - -// SetNillableEmailVerificationToken sets the "email_verification_token" field if the given value is not nil. -func (_c *UserCreate) SetNillableEmailVerificationToken(v *string) *UserCreate { - if v != nil { - _c.SetEmailVerificationToken(*v) - } - return _c -} - -// SetPasswordResetToken sets the "password_reset_token" field. -func (_c *UserCreate) SetPasswordResetToken(v string) *UserCreate { - _c.mutation.SetPasswordResetToken(v) - return _c -} - -// SetNillablePasswordResetToken sets the "password_reset_token" field if the given value is not nil. -func (_c *UserCreate) SetNillablePasswordResetToken(v *string) *UserCreate { - if v != nil { - _c.SetPasswordResetToken(*v) - } - return _c -} - -// SetPasswordResetExpiresAt sets the "password_reset_expires_at" field. -func (_c *UserCreate) SetPasswordResetExpiresAt(v time.Time) *UserCreate { - _c.mutation.SetPasswordResetExpiresAt(v) - return _c -} - -// SetNillablePasswordResetExpiresAt sets the "password_reset_expires_at" field if the given value is not nil. -func (_c *UserCreate) SetNillablePasswordResetExpiresAt(v *time.Time) *UserCreate { - if v != nil { - _c.SetPasswordResetExpiresAt(*v) - } - return _c -} - -// SetCreatedAt sets the "created_at" field. -func (_c *UserCreate) SetCreatedAt(v time.Time) *UserCreate { - _c.mutation.SetCreatedAt(v) - return _c -} - -// SetNillableCreatedAt sets the "created_at" field if the given value is not nil. -func (_c *UserCreate) SetNillableCreatedAt(v *time.Time) *UserCreate { - if v != nil { - _c.SetCreatedAt(*v) - } - return _c -} - -// SetUpdatedAt sets the "updated_at" field. -func (_c *UserCreate) SetUpdatedAt(v time.Time) *UserCreate { - _c.mutation.SetUpdatedAt(v) - return _c -} - -// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. -func (_c *UserCreate) SetNillableUpdatedAt(v *time.Time) *UserCreate { - if v != nil { - _c.SetUpdatedAt(*v) - } - return _c -} - -// SetID sets the "id" field. -func (_c *UserCreate) SetID(v string) *UserCreate { - _c.mutation.SetID(v) - return _c -} - -// AddUserRoleIDs adds the "user_roles" edge to the UserRole entity by IDs. -func (_c *UserCreate) AddUserRoleIDs(ids ...int) *UserCreate { - _c.mutation.AddUserRoleIDs(ids...) - return _c -} - -// AddUserRoles adds the "user_roles" edges to the UserRole entity. -func (_c *UserCreate) AddUserRoles(v ...*UserRole) *UserCreate { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _c.AddUserRoleIDs(ids...) -} - -// Mutation returns the UserMutation object of the builder. -func (_c *UserCreate) Mutation() *UserMutation { - return _c.mutation -} - -// Save creates the User in the database. -func (_c *UserCreate) Save(ctx context.Context) (*User, error) { - _c.defaults() - return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) -} - -// SaveX calls Save and panics if Save returns an error. -func (_c *UserCreate) SaveX(ctx context.Context) *User { - v, err := _c.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (_c *UserCreate) Exec(ctx context.Context) error { - _, err := _c.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_c *UserCreate) ExecX(ctx context.Context) { - if err := _c.Exec(ctx); err != nil { - panic(err) - } -} - -// defaults sets the default values of the builder before save. -func (_c *UserCreate) defaults() { - if _, ok := _c.mutation.Verified(); !ok { - v := user.DefaultVerified - _c.mutation.SetVerified(v) - } - if _, ok := _c.mutation.CreatedAt(); !ok { - v := user.DefaultCreatedAt() - _c.mutation.SetCreatedAt(v) - } - if _, ok := _c.mutation.UpdatedAt(); !ok { - v := user.DefaultUpdatedAt() - _c.mutation.SetUpdatedAt(v) - } -} - -// check runs all checks and user-defined validators on the builder. -func (_c *UserCreate) check() error { - if _, ok := _c.mutation.Email(); !ok { - return &ValidationError{Name: "email", err: errors.New(`ent: missing required field "User.email"`)} - } - if v, ok := _c.mutation.Email(); ok { - if err := user.EmailValidator(v); err != nil { - return &ValidationError{Name: "email", err: fmt.Errorf(`ent: validator failed for field "User.email": %w`, err)} - } - } - if _, ok := _c.mutation.PasswordHash(); !ok { - return &ValidationError{Name: "password_hash", err: errors.New(`ent: missing required field "User.password_hash"`)} - } - if v, ok := _c.mutation.PasswordHash(); ok { - if err := user.PasswordHashValidator(v); err != nil { - return &ValidationError{Name: "password_hash", err: fmt.Errorf(`ent: validator failed for field "User.password_hash": %w`, err)} - } - } - if _, ok := _c.mutation.Verified(); !ok { - return &ValidationError{Name: "verified", err: errors.New(`ent: missing required field "User.verified"`)} - } - if _, ok := _c.mutation.CreatedAt(); !ok { - return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "User.created_at"`)} - } - if _, ok := _c.mutation.UpdatedAt(); !ok { - return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "User.updated_at"`)} - } - return nil -} - -func (_c *UserCreate) sqlSave(ctx context.Context) (*User, error) { - if err := _c.check(); err != nil { - return nil, err - } - _node, _spec := _c.createSpec() - if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - if _spec.ID.Value != nil { - if id, ok := _spec.ID.Value.(string); ok { - _node.ID = id - } else { - return nil, fmt.Errorf("unexpected User.ID type: %T", _spec.ID.Value) - } - } - _c.mutation.id = &_node.ID - _c.mutation.done = true - return _node, nil -} - -func (_c *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) { - var ( - _node = &User{config: _c.config} - _spec = sqlgraph.NewCreateSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeString)) - ) - if id, ok := _c.mutation.ID(); ok { - _node.ID = id - _spec.ID.Value = id - } - if value, ok := _c.mutation.Email(); ok { - _spec.SetField(user.FieldEmail, field.TypeString, value) - _node.Email = value - } - if value, ok := _c.mutation.Username(); ok { - _spec.SetField(user.FieldUsername, field.TypeString, value) - _node.Username = value - } - if value, ok := _c.mutation.FirstName(); ok { - _spec.SetField(user.FieldFirstName, field.TypeString, value) - _node.FirstName = value - } - if value, ok := _c.mutation.LastName(); ok { - _spec.SetField(user.FieldLastName, field.TypeString, value) - _node.LastName = value - } - if value, ok := _c.mutation.PasswordHash(); ok { - _spec.SetField(user.FieldPasswordHash, field.TypeString, value) - _node.PasswordHash = value - } - if value, ok := _c.mutation.Verified(); ok { - _spec.SetField(user.FieldVerified, field.TypeBool, value) - _node.Verified = value - } - if value, ok := _c.mutation.EmailVerificationToken(); ok { - _spec.SetField(user.FieldEmailVerificationToken, field.TypeString, value) - _node.EmailVerificationToken = value - } - if value, ok := _c.mutation.PasswordResetToken(); ok { - _spec.SetField(user.FieldPasswordResetToken, field.TypeString, value) - _node.PasswordResetToken = value - } - if value, ok := _c.mutation.PasswordResetExpiresAt(); ok { - _spec.SetField(user.FieldPasswordResetExpiresAt, field.TypeTime, value) - _node.PasswordResetExpiresAt = value - } - if value, ok := _c.mutation.CreatedAt(); ok { - _spec.SetField(user.FieldCreatedAt, field.TypeTime, value) - _node.CreatedAt = value - } - if value, ok := _c.mutation.UpdatedAt(); ok { - _spec.SetField(user.FieldUpdatedAt, field.TypeTime, value) - _node.UpdatedAt = value - } - if nodes := _c.mutation.UserRolesIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: user.UserRolesTable, - Columns: []string{user.UserRolesColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges = append(_spec.Edges, edge) - } - return _node, _spec -} - -// UserCreateBulk is the builder for creating many User entities in bulk. -type UserCreateBulk struct { - config - err error - builders []*UserCreate -} - -// Save creates the User entities in the database. -func (_c *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { - if _c.err != nil { - return nil, _c.err - } - specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) - nodes := make([]*User, len(_c.builders)) - mutators := make([]Mutator, len(_c.builders)) - for i := range _c.builders { - func(i int, root context.Context) { - builder := _c.builders[i] - builder.defaults() - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*UserMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err := builder.check(); err != nil { - return nil, err - } - builder.mutation = mutation - var err error - nodes[i], specs[i] = builder.createSpec() - if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) - } else { - spec := &sqlgraph.BatchCreateSpec{Nodes: specs} - // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - } - } - if err != nil { - return nil, err - } - mutation.id = &nodes[i].ID - mutation.done = true - return nodes[i], nil - }) - for i := len(builder.hooks) - 1; i >= 0; i-- { - mut = builder.hooks[i](mut) - } - mutators[i] = mut - }(i, ctx) - } - if len(mutators) > 0 { - if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { - return nil, err - } - } - return nodes, nil -} - -// SaveX is like Save, but panics if an error occurs. -func (_c *UserCreateBulk) SaveX(ctx context.Context) []*User { - v, err := _c.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (_c *UserCreateBulk) Exec(ctx context.Context) error { - _, err := _c.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_c *UserCreateBulk) ExecX(ctx context.Context) { - if err := _c.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/internal/ent/user_delete.go b/internal/ent/user_delete.go deleted file mode 100644 index e264ee0..0000000 --- a/internal/ent/user_delete.go +++ /dev/null @@ -1,88 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" - "git.dcentral.systems/toolz/goplt/internal/ent/user" -) - -// UserDelete is the builder for deleting a User entity. -type UserDelete struct { - config - hooks []Hook - mutation *UserMutation -} - -// Where appends a list predicates to the UserDelete builder. -func (_d *UserDelete) Where(ps ...predicate.User) *UserDelete { - _d.mutation.Where(ps...) - return _d -} - -// Exec executes the deletion query and returns how many vertices were deleted. -func (_d *UserDelete) Exec(ctx context.Context) (int, error) { - return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) -} - -// ExecX is like Exec, but panics if an error occurs. -func (_d *UserDelete) ExecX(ctx context.Context) int { - n, err := _d.Exec(ctx) - if err != nil { - panic(err) - } - return n -} - -func (_d *UserDelete) sqlExec(ctx context.Context) (int, error) { - _spec := sqlgraph.NewDeleteSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeString)) - if ps := _d.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) - if err != nil && sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - _d.mutation.done = true - return affected, err -} - -// UserDeleteOne is the builder for deleting a single User entity. -type UserDeleteOne struct { - _d *UserDelete -} - -// Where appends a list predicates to the UserDelete builder. -func (_d *UserDeleteOne) Where(ps ...predicate.User) *UserDeleteOne { - _d._d.mutation.Where(ps...) - return _d -} - -// Exec executes the deletion query. -func (_d *UserDeleteOne) Exec(ctx context.Context) error { - n, err := _d._d.Exec(ctx) - switch { - case err != nil: - return err - case n == 0: - return &NotFoundError{user.Label} - default: - return nil - } -} - -// ExecX is like Exec, but panics if an error occurs. -func (_d *UserDeleteOne) ExecX(ctx context.Context) { - if err := _d.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/internal/ent/user_query.go b/internal/ent/user_query.go deleted file mode 100644 index 87cac0a..0000000 --- a/internal/ent/user_query.go +++ /dev/null @@ -1,607 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "database/sql/driver" - "fmt" - "math" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" - "git.dcentral.systems/toolz/goplt/internal/ent/user" - "git.dcentral.systems/toolz/goplt/internal/ent/userrole" -) - -// UserQuery is the builder for querying User entities. -type UserQuery struct { - config - ctx *QueryContext - order []user.OrderOption - inters []Interceptor - predicates []predicate.User - withUserRoles *UserRoleQuery - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Where adds a new predicate for the UserQuery builder. -func (_q *UserQuery) Where(ps ...predicate.User) *UserQuery { - _q.predicates = append(_q.predicates, ps...) - return _q -} - -// Limit the number of records to be returned by this query. -func (_q *UserQuery) Limit(limit int) *UserQuery { - _q.ctx.Limit = &limit - return _q -} - -// Offset to start from. -func (_q *UserQuery) Offset(offset int) *UserQuery { - _q.ctx.Offset = &offset - return _q -} - -// Unique configures the query builder to filter duplicate records on query. -// By default, unique is set to true, and can be disabled using this method. -func (_q *UserQuery) Unique(unique bool) *UserQuery { - _q.ctx.Unique = &unique - return _q -} - -// Order specifies how the records should be ordered. -func (_q *UserQuery) Order(o ...user.OrderOption) *UserQuery { - _q.order = append(_q.order, o...) - return _q -} - -// QueryUserRoles chains the current query on the "user_roles" edge. -func (_q *UserQuery) QueryUserRoles() *UserRoleQuery { - query := (&UserRoleClient{config: _q.config}).Query() - query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { - if err := _q.prepareQuery(ctx); err != nil { - return nil, err - } - selector := _q.sqlQuery(ctx) - if err := selector.Err(); err != nil { - return nil, err - } - step := sqlgraph.NewStep( - sqlgraph.From(user.Table, user.FieldID, selector), - sqlgraph.To(userrole.Table, userrole.FieldID), - sqlgraph.Edge(sqlgraph.O2M, false, user.UserRolesTable, user.UserRolesColumn), - ) - fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) - return fromU, nil - } - return query -} - -// First returns the first User entity from the query. -// Returns a *NotFoundError when no User was found. -func (_q *UserQuery) First(ctx context.Context) (*User, error) { - nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{user.Label} - } - return nodes[0], nil -} - -// FirstX is like First, but panics if an error occurs. -func (_q *UserQuery) FirstX(ctx context.Context) *User { - node, err := _q.First(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// FirstID returns the first User ID from the query. -// Returns a *NotFoundError when no User ID was found. -func (_q *UserQuery) FirstID(ctx context.Context) (id string, err error) { - var ids []string - if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{user.Label} - return - } - return ids[0], nil -} - -// FirstIDX is like FirstID, but panics if an error occurs. -func (_q *UserQuery) FirstIDX(ctx context.Context) string { - id, err := _q.FirstID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Only returns a single User entity found by the query, ensuring it only returns one. -// Returns a *NotSingularError when more than one User entity is found. -// Returns a *NotFoundError when no User entities are found. -func (_q *UserQuery) Only(ctx context.Context) (*User, error) { - nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) - if err != nil { - return nil, err - } - switch len(nodes) { - case 1: - return nodes[0], nil - case 0: - return nil, &NotFoundError{user.Label} - default: - return nil, &NotSingularError{user.Label} - } -} - -// OnlyX is like Only, but panics if an error occurs. -func (_q *UserQuery) OnlyX(ctx context.Context) *User { - node, err := _q.Only(ctx) - if err != nil { - panic(err) - } - return node -} - -// OnlyID is like Only, but returns the only User ID in the query. -// Returns a *NotSingularError when more than one User ID is found. -// Returns a *NotFoundError when no entities are found. -func (_q *UserQuery) OnlyID(ctx context.Context) (id string, err error) { - var ids []string - if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { - return - } - switch len(ids) { - case 1: - id = ids[0] - case 0: - err = &NotFoundError{user.Label} - default: - err = &NotSingularError{user.Label} - } - return -} - -// OnlyIDX is like OnlyID, but panics if an error occurs. -func (_q *UserQuery) OnlyIDX(ctx context.Context) string { - id, err := _q.OnlyID(ctx) - if err != nil { - panic(err) - } - return id -} - -// All executes the query and returns a list of Users. -func (_q *UserQuery) All(ctx context.Context) ([]*User, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) - if err := _q.prepareQuery(ctx); err != nil { - return nil, err - } - qr := querierAll[[]*User, *UserQuery]() - return withInterceptors[[]*User](ctx, _q, qr, _q.inters) -} - -// AllX is like All, but panics if an error occurs. -func (_q *UserQuery) AllX(ctx context.Context) []*User { - nodes, err := _q.All(ctx) - if err != nil { - panic(err) - } - return nodes -} - -// IDs executes the query and returns a list of User IDs. -func (_q *UserQuery) IDs(ctx context.Context) (ids []string, err error) { - if _q.ctx.Unique == nil && _q.path != nil { - _q.Unique(true) - } - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) - if err = _q.Select(user.FieldID).Scan(ctx, &ids); err != nil { - return nil, err - } - return ids, nil -} - -// IDsX is like IDs, but panics if an error occurs. -func (_q *UserQuery) IDsX(ctx context.Context) []string { - ids, err := _q.IDs(ctx) - if err != nil { - panic(err) - } - return ids -} - -// Count returns the count of the given query. -func (_q *UserQuery) Count(ctx context.Context) (int, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) - if err := _q.prepareQuery(ctx); err != nil { - return 0, err - } - return withInterceptors[int](ctx, _q, querierCount[*UserQuery](), _q.inters) -} - -// CountX is like Count, but panics if an error occurs. -func (_q *UserQuery) CountX(ctx context.Context) int { - count, err := _q.Count(ctx) - if err != nil { - panic(err) - } - return count -} - -// Exist returns true if the query has elements in the graph. -func (_q *UserQuery) Exist(ctx context.Context) (bool, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) - switch _, err := _q.FirstID(ctx); { - case IsNotFound(err): - return false, nil - case err != nil: - return false, fmt.Errorf("ent: check existence: %w", err) - default: - return true, nil - } -} - -// ExistX is like Exist, but panics if an error occurs. -func (_q *UserQuery) ExistX(ctx context.Context) bool { - exist, err := _q.Exist(ctx) - if err != nil { - panic(err) - } - return exist -} - -// Clone returns a duplicate of the UserQuery builder, including all associated steps. It can be -// used to prepare common query builders and use them differently after the clone is made. -func (_q *UserQuery) Clone() *UserQuery { - if _q == nil { - return nil - } - return &UserQuery{ - config: _q.config, - ctx: _q.ctx.Clone(), - order: append([]user.OrderOption{}, _q.order...), - inters: append([]Interceptor{}, _q.inters...), - predicates: append([]predicate.User{}, _q.predicates...), - withUserRoles: _q.withUserRoles.Clone(), - // clone intermediate query. - sql: _q.sql.Clone(), - path: _q.path, - } -} - -// WithUserRoles tells the query-builder to eager-load the nodes that are connected to -// the "user_roles" edge. The optional arguments are used to configure the query builder of the edge. -func (_q *UserQuery) WithUserRoles(opts ...func(*UserRoleQuery)) *UserQuery { - query := (&UserRoleClient{config: _q.config}).Query() - for _, opt := range opts { - opt(query) - } - _q.withUserRoles = query - return _q -} - -// GroupBy is used to group vertices by one or more fields/columns. -// It is often used with aggregate functions, like: count, max, mean, min, sum. -// -// Example: -// -// var v []struct { -// Email string `json:"email,omitempty"` -// Count int `json:"count,omitempty"` -// } -// -// client.User.Query(). -// GroupBy(user.FieldEmail). -// Aggregate(ent.Count()). -// Scan(ctx, &v) -func (_q *UserQuery) GroupBy(field string, fields ...string) *UserGroupBy { - _q.ctx.Fields = append([]string{field}, fields...) - grbuild := &UserGroupBy{build: _q} - grbuild.flds = &_q.ctx.Fields - grbuild.label = user.Label - grbuild.scan = grbuild.Scan - return grbuild -} - -// Select allows the selection one or more fields/columns for the given query, -// instead of selecting all fields in the entity. -// -// Example: -// -// var v []struct { -// Email string `json:"email,omitempty"` -// } -// -// client.User.Query(). -// Select(user.FieldEmail). -// Scan(ctx, &v) -func (_q *UserQuery) Select(fields ...string) *UserSelect { - _q.ctx.Fields = append(_q.ctx.Fields, fields...) - sbuild := &UserSelect{UserQuery: _q} - sbuild.label = user.Label - sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan - return sbuild -} - -// Aggregate returns a UserSelect configured with the given aggregations. -func (_q *UserQuery) Aggregate(fns ...AggregateFunc) *UserSelect { - return _q.Select().Aggregate(fns...) -} - -func (_q *UserQuery) prepareQuery(ctx context.Context) error { - for _, inter := range _q.inters { - if inter == nil { - return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") - } - if trv, ok := inter.(Traverser); ok { - if err := trv.Traverse(ctx, _q); err != nil { - return err - } - } - } - for _, f := range _q.ctx.Fields { - if !user.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} - } - } - if _q.path != nil { - prev, err := _q.path(ctx) - if err != nil { - return err - } - _q.sql = prev - } - return nil -} - -func (_q *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, error) { - var ( - nodes = []*User{} - _spec = _q.querySpec() - loadedTypes = [1]bool{ - _q.withUserRoles != nil, - } - ) - _spec.ScanValues = func(columns []string) ([]any, error) { - return (*User).scanValues(nil, columns) - } - _spec.Assign = func(columns []string, values []any) error { - node := &User{config: _q.config} - nodes = append(nodes, node) - node.Edges.loadedTypes = loadedTypes - return node.assignValues(columns, values) - } - for i := range hooks { - hooks[i](ctx, _spec) - } - if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { - return nil, err - } - if len(nodes) == 0 { - return nodes, nil - } - if query := _q.withUserRoles; query != nil { - if err := _q.loadUserRoles(ctx, query, nodes, - func(n *User) { n.Edges.UserRoles = []*UserRole{} }, - func(n *User, e *UserRole) { n.Edges.UserRoles = append(n.Edges.UserRoles, e) }); err != nil { - return nil, err - } - } - return nodes, nil -} - -func (_q *UserQuery) loadUserRoles(ctx context.Context, query *UserRoleQuery, nodes []*User, init func(*User), assign func(*User, *UserRole)) error { - fks := make([]driver.Value, 0, len(nodes)) - nodeids := make(map[string]*User) - for i := range nodes { - fks = append(fks, nodes[i].ID) - nodeids[nodes[i].ID] = nodes[i] - if init != nil { - init(nodes[i]) - } - } - query.withFKs = true - query.Where(predicate.UserRole(func(s *sql.Selector) { - s.Where(sql.InValues(s.C(user.UserRolesColumn), fks...)) - })) - neighbors, err := query.All(ctx) - if err != nil { - return err - } - for _, n := range neighbors { - fk := n.user_user_roles - if fk == nil { - return fmt.Errorf(`foreign-key "user_user_roles" is nil for node %v`, n.ID) - } - node, ok := nodeids[*fk] - if !ok { - return fmt.Errorf(`unexpected referenced foreign-key "user_user_roles" returned %v for node %v`, *fk, n.ID) - } - assign(node, n) - } - return nil -} - -func (_q *UserQuery) sqlCount(ctx context.Context) (int, error) { - _spec := _q.querySpec() - _spec.Node.Columns = _q.ctx.Fields - if len(_q.ctx.Fields) > 0 { - _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique - } - return sqlgraph.CountNodes(ctx, _q.driver, _spec) -} - -func (_q *UserQuery) querySpec() *sqlgraph.QuerySpec { - _spec := sqlgraph.NewQuerySpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeString)) - _spec.From = _q.sql - if unique := _q.ctx.Unique; unique != nil { - _spec.Unique = *unique - } else if _q.path != nil { - _spec.Unique = true - } - if fields := _q.ctx.Fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, user.FieldID) - for i := range fields { - if fields[i] != user.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) - } - } - } - if ps := _q.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if limit := _q.ctx.Limit; limit != nil { - _spec.Limit = *limit - } - if offset := _q.ctx.Offset; offset != nil { - _spec.Offset = *offset - } - if ps := _q.order; len(ps) > 0 { - _spec.Order = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return _spec -} - -func (_q *UserQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(_q.driver.Dialect()) - t1 := builder.Table(user.Table) - columns := _q.ctx.Fields - if len(columns) == 0 { - columns = user.Columns - } - selector := builder.Select(t1.Columns(columns...)...).From(t1) - if _q.sql != nil { - selector = _q.sql - selector.Select(selector.Columns(columns...)...) - } - if _q.ctx.Unique != nil && *_q.ctx.Unique { - selector.Distinct() - } - for _, p := range _q.predicates { - p(selector) - } - for _, p := range _q.order { - p(selector) - } - if offset := _q.ctx.Offset; offset != nil { - // limit is mandatory for offset clause. We start - // with default value, and override it below if needed. - selector.Offset(*offset).Limit(math.MaxInt32) - } - if limit := _q.ctx.Limit; limit != nil { - selector.Limit(*limit) - } - return selector -} - -// UserGroupBy is the group-by builder for User entities. -type UserGroupBy struct { - selector - build *UserQuery -} - -// Aggregate adds the given aggregation functions to the group-by query. -func (_g *UserGroupBy) Aggregate(fns ...AggregateFunc) *UserGroupBy { - _g.fns = append(_g.fns, fns...) - return _g -} - -// Scan applies the selector query and scans the result into the given value. -func (_g *UserGroupBy) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) - if err := _g.build.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*UserQuery, *UserGroupBy](ctx, _g.build, _g, _g.build.inters, v) -} - -func (_g *UserGroupBy) sqlScan(ctx context.Context, root *UserQuery, v any) error { - selector := root.sqlQuery(ctx).Select() - aggregation := make([]string, 0, len(_g.fns)) - for _, fn := range _g.fns { - aggregation = append(aggregation, fn(selector)) - } - if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) - for _, f := range *_g.flds { - columns = append(columns, selector.C(f)) - } - columns = append(columns, aggregation...) - selector.Select(columns...) - } - selector.GroupBy(selector.Columns(*_g.flds...)...) - if err := selector.Err(); err != nil { - return err - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} - -// UserSelect is the builder for selecting fields of User entities. -type UserSelect struct { - *UserQuery - selector -} - -// Aggregate adds the given aggregation functions to the selector query. -func (_s *UserSelect) Aggregate(fns ...AggregateFunc) *UserSelect { - _s.fns = append(_s.fns, fns...) - return _s -} - -// Scan applies the selector query and scans the result into the given value. -func (_s *UserSelect) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) - if err := _s.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*UserQuery, *UserSelect](ctx, _s.UserQuery, _s, _s.inters, v) -} - -func (_s *UserSelect) sqlScan(ctx context.Context, root *UserQuery, v any) error { - selector := root.sqlQuery(ctx) - aggregation := make([]string, 0, len(_s.fns)) - for _, fn := range _s.fns { - aggregation = append(aggregation, fn(selector)) - } - switch n := len(*_s.selector.flds); { - case n == 0 && len(aggregation) > 0: - selector.Select(aggregation...) - case n != 0 && len(aggregation) > 0: - selector.AppendSelect(aggregation...) - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := _s.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} diff --git a/internal/ent/user_update.go b/internal/ent/user_update.go deleted file mode 100644 index c83ccfb..0000000 --- a/internal/ent/user_update.go +++ /dev/null @@ -1,825 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "errors" - "fmt" - "time" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" - "git.dcentral.systems/toolz/goplt/internal/ent/user" - "git.dcentral.systems/toolz/goplt/internal/ent/userrole" -) - -// UserUpdate is the builder for updating User entities. -type UserUpdate struct { - config - hooks []Hook - mutation *UserMutation -} - -// Where appends a list predicates to the UserUpdate builder. -func (_u *UserUpdate) Where(ps ...predicate.User) *UserUpdate { - _u.mutation.Where(ps...) - return _u -} - -// SetEmail sets the "email" field. -func (_u *UserUpdate) SetEmail(v string) *UserUpdate { - _u.mutation.SetEmail(v) - return _u -} - -// SetNillableEmail sets the "email" field if the given value is not nil. -func (_u *UserUpdate) SetNillableEmail(v *string) *UserUpdate { - if v != nil { - _u.SetEmail(*v) - } - return _u -} - -// SetUsername sets the "username" field. -func (_u *UserUpdate) SetUsername(v string) *UserUpdate { - _u.mutation.SetUsername(v) - return _u -} - -// SetNillableUsername sets the "username" field if the given value is not nil. -func (_u *UserUpdate) SetNillableUsername(v *string) *UserUpdate { - if v != nil { - _u.SetUsername(*v) - } - return _u -} - -// ClearUsername clears the value of the "username" field. -func (_u *UserUpdate) ClearUsername() *UserUpdate { - _u.mutation.ClearUsername() - return _u -} - -// SetFirstName sets the "first_name" field. -func (_u *UserUpdate) SetFirstName(v string) *UserUpdate { - _u.mutation.SetFirstName(v) - return _u -} - -// SetNillableFirstName sets the "first_name" field if the given value is not nil. -func (_u *UserUpdate) SetNillableFirstName(v *string) *UserUpdate { - if v != nil { - _u.SetFirstName(*v) - } - return _u -} - -// ClearFirstName clears the value of the "first_name" field. -func (_u *UserUpdate) ClearFirstName() *UserUpdate { - _u.mutation.ClearFirstName() - return _u -} - -// SetLastName sets the "last_name" field. -func (_u *UserUpdate) SetLastName(v string) *UserUpdate { - _u.mutation.SetLastName(v) - return _u -} - -// SetNillableLastName sets the "last_name" field if the given value is not nil. -func (_u *UserUpdate) SetNillableLastName(v *string) *UserUpdate { - if v != nil { - _u.SetLastName(*v) - } - return _u -} - -// ClearLastName clears the value of the "last_name" field. -func (_u *UserUpdate) ClearLastName() *UserUpdate { - _u.mutation.ClearLastName() - return _u -} - -// SetPasswordHash sets the "password_hash" field. -func (_u *UserUpdate) SetPasswordHash(v string) *UserUpdate { - _u.mutation.SetPasswordHash(v) - return _u -} - -// SetNillablePasswordHash sets the "password_hash" field if the given value is not nil. -func (_u *UserUpdate) SetNillablePasswordHash(v *string) *UserUpdate { - if v != nil { - _u.SetPasswordHash(*v) - } - return _u -} - -// SetVerified sets the "verified" field. -func (_u *UserUpdate) SetVerified(v bool) *UserUpdate { - _u.mutation.SetVerified(v) - return _u -} - -// SetNillableVerified sets the "verified" field if the given value is not nil. -func (_u *UserUpdate) SetNillableVerified(v *bool) *UserUpdate { - if v != nil { - _u.SetVerified(*v) - } - return _u -} - -// SetEmailVerificationToken sets the "email_verification_token" field. -func (_u *UserUpdate) SetEmailVerificationToken(v string) *UserUpdate { - _u.mutation.SetEmailVerificationToken(v) - return _u -} - -// SetNillableEmailVerificationToken sets the "email_verification_token" field if the given value is not nil. -func (_u *UserUpdate) SetNillableEmailVerificationToken(v *string) *UserUpdate { - if v != nil { - _u.SetEmailVerificationToken(*v) - } - return _u -} - -// ClearEmailVerificationToken clears the value of the "email_verification_token" field. -func (_u *UserUpdate) ClearEmailVerificationToken() *UserUpdate { - _u.mutation.ClearEmailVerificationToken() - return _u -} - -// SetPasswordResetToken sets the "password_reset_token" field. -func (_u *UserUpdate) SetPasswordResetToken(v string) *UserUpdate { - _u.mutation.SetPasswordResetToken(v) - return _u -} - -// SetNillablePasswordResetToken sets the "password_reset_token" field if the given value is not nil. -func (_u *UserUpdate) SetNillablePasswordResetToken(v *string) *UserUpdate { - if v != nil { - _u.SetPasswordResetToken(*v) - } - return _u -} - -// ClearPasswordResetToken clears the value of the "password_reset_token" field. -func (_u *UserUpdate) ClearPasswordResetToken() *UserUpdate { - _u.mutation.ClearPasswordResetToken() - return _u -} - -// SetPasswordResetExpiresAt sets the "password_reset_expires_at" field. -func (_u *UserUpdate) SetPasswordResetExpiresAt(v time.Time) *UserUpdate { - _u.mutation.SetPasswordResetExpiresAt(v) - return _u -} - -// SetNillablePasswordResetExpiresAt sets the "password_reset_expires_at" field if the given value is not nil. -func (_u *UserUpdate) SetNillablePasswordResetExpiresAt(v *time.Time) *UserUpdate { - if v != nil { - _u.SetPasswordResetExpiresAt(*v) - } - return _u -} - -// ClearPasswordResetExpiresAt clears the value of the "password_reset_expires_at" field. -func (_u *UserUpdate) ClearPasswordResetExpiresAt() *UserUpdate { - _u.mutation.ClearPasswordResetExpiresAt() - return _u -} - -// SetUpdatedAt sets the "updated_at" field. -func (_u *UserUpdate) SetUpdatedAt(v time.Time) *UserUpdate { - _u.mutation.SetUpdatedAt(v) - return _u -} - -// AddUserRoleIDs adds the "user_roles" edge to the UserRole entity by IDs. -func (_u *UserUpdate) AddUserRoleIDs(ids ...int) *UserUpdate { - _u.mutation.AddUserRoleIDs(ids...) - return _u -} - -// AddUserRoles adds the "user_roles" edges to the UserRole entity. -func (_u *UserUpdate) AddUserRoles(v ...*UserRole) *UserUpdate { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.AddUserRoleIDs(ids...) -} - -// Mutation returns the UserMutation object of the builder. -func (_u *UserUpdate) Mutation() *UserMutation { - return _u.mutation -} - -// ClearUserRoles clears all "user_roles" edges to the UserRole entity. -func (_u *UserUpdate) ClearUserRoles() *UserUpdate { - _u.mutation.ClearUserRoles() - return _u -} - -// RemoveUserRoleIDs removes the "user_roles" edge to UserRole entities by IDs. -func (_u *UserUpdate) RemoveUserRoleIDs(ids ...int) *UserUpdate { - _u.mutation.RemoveUserRoleIDs(ids...) - return _u -} - -// RemoveUserRoles removes "user_roles" edges to UserRole entities. -func (_u *UserUpdate) RemoveUserRoles(v ...*UserRole) *UserUpdate { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.RemoveUserRoleIDs(ids...) -} - -// Save executes the query and returns the number of nodes affected by the update operation. -func (_u *UserUpdate) Save(ctx context.Context) (int, error) { - _u.defaults() - return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (_u *UserUpdate) SaveX(ctx context.Context) int { - affected, err := _u.Save(ctx) - if err != nil { - panic(err) - } - return affected -} - -// Exec executes the query. -func (_u *UserUpdate) Exec(ctx context.Context) error { - _, err := _u.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_u *UserUpdate) ExecX(ctx context.Context) { - if err := _u.Exec(ctx); err != nil { - panic(err) - } -} - -// defaults sets the default values of the builder before save. -func (_u *UserUpdate) defaults() { - if _, ok := _u.mutation.UpdatedAt(); !ok { - v := user.UpdateDefaultUpdatedAt() - _u.mutation.SetUpdatedAt(v) - } -} - -// check runs all checks and user-defined validators on the builder. -func (_u *UserUpdate) check() error { - if v, ok := _u.mutation.Email(); ok { - if err := user.EmailValidator(v); err != nil { - return &ValidationError{Name: "email", err: fmt.Errorf(`ent: validator failed for field "User.email": %w`, err)} - } - } - if v, ok := _u.mutation.PasswordHash(); ok { - if err := user.PasswordHashValidator(v); err != nil { - return &ValidationError{Name: "password_hash", err: fmt.Errorf(`ent: validator failed for field "User.password_hash": %w`, err)} - } - } - return nil -} - -func (_u *UserUpdate) sqlSave(ctx context.Context) (_node int, err error) { - if err := _u.check(); err != nil { - return _node, err - } - _spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeString)) - if ps := _u.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := _u.mutation.Email(); ok { - _spec.SetField(user.FieldEmail, field.TypeString, value) - } - if value, ok := _u.mutation.Username(); ok { - _spec.SetField(user.FieldUsername, field.TypeString, value) - } - if _u.mutation.UsernameCleared() { - _spec.ClearField(user.FieldUsername, field.TypeString) - } - if value, ok := _u.mutation.FirstName(); ok { - _spec.SetField(user.FieldFirstName, field.TypeString, value) - } - if _u.mutation.FirstNameCleared() { - _spec.ClearField(user.FieldFirstName, field.TypeString) - } - if value, ok := _u.mutation.LastName(); ok { - _spec.SetField(user.FieldLastName, field.TypeString, value) - } - if _u.mutation.LastNameCleared() { - _spec.ClearField(user.FieldLastName, field.TypeString) - } - if value, ok := _u.mutation.PasswordHash(); ok { - _spec.SetField(user.FieldPasswordHash, field.TypeString, value) - } - if value, ok := _u.mutation.Verified(); ok { - _spec.SetField(user.FieldVerified, field.TypeBool, value) - } - if value, ok := _u.mutation.EmailVerificationToken(); ok { - _spec.SetField(user.FieldEmailVerificationToken, field.TypeString, value) - } - if _u.mutation.EmailVerificationTokenCleared() { - _spec.ClearField(user.FieldEmailVerificationToken, field.TypeString) - } - if value, ok := _u.mutation.PasswordResetToken(); ok { - _spec.SetField(user.FieldPasswordResetToken, field.TypeString, value) - } - if _u.mutation.PasswordResetTokenCleared() { - _spec.ClearField(user.FieldPasswordResetToken, field.TypeString) - } - if value, ok := _u.mutation.PasswordResetExpiresAt(); ok { - _spec.SetField(user.FieldPasswordResetExpiresAt, field.TypeTime, value) - } - if _u.mutation.PasswordResetExpiresAtCleared() { - _spec.ClearField(user.FieldPasswordResetExpiresAt, field.TypeTime) - } - if value, ok := _u.mutation.UpdatedAt(); ok { - _spec.SetField(user.FieldUpdatedAt, field.TypeTime, value) - } - if _u.mutation.UserRolesCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: user.UserRolesTable, - Columns: []string{user.UserRolesColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.RemovedUserRolesIDs(); len(nodes) > 0 && !_u.mutation.UserRolesCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: user.UserRolesTable, - Columns: []string{user.UserRolesColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.UserRolesIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: user.UserRolesTable, - Columns: []string{user.UserRolesColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{user.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return 0, err - } - _u.mutation.done = true - return _node, nil -} - -// UserUpdateOne is the builder for updating a single User entity. -type UserUpdateOne struct { - config - fields []string - hooks []Hook - mutation *UserMutation -} - -// SetEmail sets the "email" field. -func (_u *UserUpdateOne) SetEmail(v string) *UserUpdateOne { - _u.mutation.SetEmail(v) - return _u -} - -// SetNillableEmail sets the "email" field if the given value is not nil. -func (_u *UserUpdateOne) SetNillableEmail(v *string) *UserUpdateOne { - if v != nil { - _u.SetEmail(*v) - } - return _u -} - -// SetUsername sets the "username" field. -func (_u *UserUpdateOne) SetUsername(v string) *UserUpdateOne { - _u.mutation.SetUsername(v) - return _u -} - -// SetNillableUsername sets the "username" field if the given value is not nil. -func (_u *UserUpdateOne) SetNillableUsername(v *string) *UserUpdateOne { - if v != nil { - _u.SetUsername(*v) - } - return _u -} - -// ClearUsername clears the value of the "username" field. -func (_u *UserUpdateOne) ClearUsername() *UserUpdateOne { - _u.mutation.ClearUsername() - return _u -} - -// SetFirstName sets the "first_name" field. -func (_u *UserUpdateOne) SetFirstName(v string) *UserUpdateOne { - _u.mutation.SetFirstName(v) - return _u -} - -// SetNillableFirstName sets the "first_name" field if the given value is not nil. -func (_u *UserUpdateOne) SetNillableFirstName(v *string) *UserUpdateOne { - if v != nil { - _u.SetFirstName(*v) - } - return _u -} - -// ClearFirstName clears the value of the "first_name" field. -func (_u *UserUpdateOne) ClearFirstName() *UserUpdateOne { - _u.mutation.ClearFirstName() - return _u -} - -// SetLastName sets the "last_name" field. -func (_u *UserUpdateOne) SetLastName(v string) *UserUpdateOne { - _u.mutation.SetLastName(v) - return _u -} - -// SetNillableLastName sets the "last_name" field if the given value is not nil. -func (_u *UserUpdateOne) SetNillableLastName(v *string) *UserUpdateOne { - if v != nil { - _u.SetLastName(*v) - } - return _u -} - -// ClearLastName clears the value of the "last_name" field. -func (_u *UserUpdateOne) ClearLastName() *UserUpdateOne { - _u.mutation.ClearLastName() - return _u -} - -// SetPasswordHash sets the "password_hash" field. -func (_u *UserUpdateOne) SetPasswordHash(v string) *UserUpdateOne { - _u.mutation.SetPasswordHash(v) - return _u -} - -// SetNillablePasswordHash sets the "password_hash" field if the given value is not nil. -func (_u *UserUpdateOne) SetNillablePasswordHash(v *string) *UserUpdateOne { - if v != nil { - _u.SetPasswordHash(*v) - } - return _u -} - -// SetVerified sets the "verified" field. -func (_u *UserUpdateOne) SetVerified(v bool) *UserUpdateOne { - _u.mutation.SetVerified(v) - return _u -} - -// SetNillableVerified sets the "verified" field if the given value is not nil. -func (_u *UserUpdateOne) SetNillableVerified(v *bool) *UserUpdateOne { - if v != nil { - _u.SetVerified(*v) - } - return _u -} - -// SetEmailVerificationToken sets the "email_verification_token" field. -func (_u *UserUpdateOne) SetEmailVerificationToken(v string) *UserUpdateOne { - _u.mutation.SetEmailVerificationToken(v) - return _u -} - -// SetNillableEmailVerificationToken sets the "email_verification_token" field if the given value is not nil. -func (_u *UserUpdateOne) SetNillableEmailVerificationToken(v *string) *UserUpdateOne { - if v != nil { - _u.SetEmailVerificationToken(*v) - } - return _u -} - -// ClearEmailVerificationToken clears the value of the "email_verification_token" field. -func (_u *UserUpdateOne) ClearEmailVerificationToken() *UserUpdateOne { - _u.mutation.ClearEmailVerificationToken() - return _u -} - -// SetPasswordResetToken sets the "password_reset_token" field. -func (_u *UserUpdateOne) SetPasswordResetToken(v string) *UserUpdateOne { - _u.mutation.SetPasswordResetToken(v) - return _u -} - -// SetNillablePasswordResetToken sets the "password_reset_token" field if the given value is not nil. -func (_u *UserUpdateOne) SetNillablePasswordResetToken(v *string) *UserUpdateOne { - if v != nil { - _u.SetPasswordResetToken(*v) - } - return _u -} - -// ClearPasswordResetToken clears the value of the "password_reset_token" field. -func (_u *UserUpdateOne) ClearPasswordResetToken() *UserUpdateOne { - _u.mutation.ClearPasswordResetToken() - return _u -} - -// SetPasswordResetExpiresAt sets the "password_reset_expires_at" field. -func (_u *UserUpdateOne) SetPasswordResetExpiresAt(v time.Time) *UserUpdateOne { - _u.mutation.SetPasswordResetExpiresAt(v) - return _u -} - -// SetNillablePasswordResetExpiresAt sets the "password_reset_expires_at" field if the given value is not nil. -func (_u *UserUpdateOne) SetNillablePasswordResetExpiresAt(v *time.Time) *UserUpdateOne { - if v != nil { - _u.SetPasswordResetExpiresAt(*v) - } - return _u -} - -// ClearPasswordResetExpiresAt clears the value of the "password_reset_expires_at" field. -func (_u *UserUpdateOne) ClearPasswordResetExpiresAt() *UserUpdateOne { - _u.mutation.ClearPasswordResetExpiresAt() - return _u -} - -// SetUpdatedAt sets the "updated_at" field. -func (_u *UserUpdateOne) SetUpdatedAt(v time.Time) *UserUpdateOne { - _u.mutation.SetUpdatedAt(v) - return _u -} - -// AddUserRoleIDs adds the "user_roles" edge to the UserRole entity by IDs. -func (_u *UserUpdateOne) AddUserRoleIDs(ids ...int) *UserUpdateOne { - _u.mutation.AddUserRoleIDs(ids...) - return _u -} - -// AddUserRoles adds the "user_roles" edges to the UserRole entity. -func (_u *UserUpdateOne) AddUserRoles(v ...*UserRole) *UserUpdateOne { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.AddUserRoleIDs(ids...) -} - -// Mutation returns the UserMutation object of the builder. -func (_u *UserUpdateOne) Mutation() *UserMutation { - return _u.mutation -} - -// ClearUserRoles clears all "user_roles" edges to the UserRole entity. -func (_u *UserUpdateOne) ClearUserRoles() *UserUpdateOne { - _u.mutation.ClearUserRoles() - return _u -} - -// RemoveUserRoleIDs removes the "user_roles" edge to UserRole entities by IDs. -func (_u *UserUpdateOne) RemoveUserRoleIDs(ids ...int) *UserUpdateOne { - _u.mutation.RemoveUserRoleIDs(ids...) - return _u -} - -// RemoveUserRoles removes "user_roles" edges to UserRole entities. -func (_u *UserUpdateOne) RemoveUserRoles(v ...*UserRole) *UserUpdateOne { - ids := make([]int, len(v)) - for i := range v { - ids[i] = v[i].ID - } - return _u.RemoveUserRoleIDs(ids...) -} - -// Where appends a list predicates to the UserUpdate builder. -func (_u *UserUpdateOne) Where(ps ...predicate.User) *UserUpdateOne { - _u.mutation.Where(ps...) - return _u -} - -// Select allows selecting one or more fields (columns) of the returned entity. -// The default is selecting all fields defined in the entity schema. -func (_u *UserUpdateOne) Select(field string, fields ...string) *UserUpdateOne { - _u.fields = append([]string{field}, fields...) - return _u -} - -// Save executes the query and returns the updated User entity. -func (_u *UserUpdateOne) Save(ctx context.Context) (*User, error) { - _u.defaults() - return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (_u *UserUpdateOne) SaveX(ctx context.Context) *User { - node, err := _u.Save(ctx) - if err != nil { - panic(err) - } - return node -} - -// Exec executes the query on the entity. -func (_u *UserUpdateOne) Exec(ctx context.Context) error { - _, err := _u.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_u *UserUpdateOne) ExecX(ctx context.Context) { - if err := _u.Exec(ctx); err != nil { - panic(err) - } -} - -// defaults sets the default values of the builder before save. -func (_u *UserUpdateOne) defaults() { - if _, ok := _u.mutation.UpdatedAt(); !ok { - v := user.UpdateDefaultUpdatedAt() - _u.mutation.SetUpdatedAt(v) - } -} - -// check runs all checks and user-defined validators on the builder. -func (_u *UserUpdateOne) check() error { - if v, ok := _u.mutation.Email(); ok { - if err := user.EmailValidator(v); err != nil { - return &ValidationError{Name: "email", err: fmt.Errorf(`ent: validator failed for field "User.email": %w`, err)} - } - } - if v, ok := _u.mutation.PasswordHash(); ok { - if err := user.PasswordHashValidator(v); err != nil { - return &ValidationError{Name: "password_hash", err: fmt.Errorf(`ent: validator failed for field "User.password_hash": %w`, err)} - } - } - return nil -} - -func (_u *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) { - if err := _u.check(); err != nil { - return _node, err - } - _spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeString)) - id, ok := _u.mutation.ID() - if !ok { - return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "User.id" for update`)} - } - _spec.Node.ID.Value = id - if fields := _u.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, user.FieldID) - for _, f := range fields { - if !user.ValidColumn(f) { - return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} - } - if f != user.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, f) - } - } - } - if ps := _u.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if value, ok := _u.mutation.Email(); ok { - _spec.SetField(user.FieldEmail, field.TypeString, value) - } - if value, ok := _u.mutation.Username(); ok { - _spec.SetField(user.FieldUsername, field.TypeString, value) - } - if _u.mutation.UsernameCleared() { - _spec.ClearField(user.FieldUsername, field.TypeString) - } - if value, ok := _u.mutation.FirstName(); ok { - _spec.SetField(user.FieldFirstName, field.TypeString, value) - } - if _u.mutation.FirstNameCleared() { - _spec.ClearField(user.FieldFirstName, field.TypeString) - } - if value, ok := _u.mutation.LastName(); ok { - _spec.SetField(user.FieldLastName, field.TypeString, value) - } - if _u.mutation.LastNameCleared() { - _spec.ClearField(user.FieldLastName, field.TypeString) - } - if value, ok := _u.mutation.PasswordHash(); ok { - _spec.SetField(user.FieldPasswordHash, field.TypeString, value) - } - if value, ok := _u.mutation.Verified(); ok { - _spec.SetField(user.FieldVerified, field.TypeBool, value) - } - if value, ok := _u.mutation.EmailVerificationToken(); ok { - _spec.SetField(user.FieldEmailVerificationToken, field.TypeString, value) - } - if _u.mutation.EmailVerificationTokenCleared() { - _spec.ClearField(user.FieldEmailVerificationToken, field.TypeString) - } - if value, ok := _u.mutation.PasswordResetToken(); ok { - _spec.SetField(user.FieldPasswordResetToken, field.TypeString, value) - } - if _u.mutation.PasswordResetTokenCleared() { - _spec.ClearField(user.FieldPasswordResetToken, field.TypeString) - } - if value, ok := _u.mutation.PasswordResetExpiresAt(); ok { - _spec.SetField(user.FieldPasswordResetExpiresAt, field.TypeTime, value) - } - if _u.mutation.PasswordResetExpiresAtCleared() { - _spec.ClearField(user.FieldPasswordResetExpiresAt, field.TypeTime) - } - if value, ok := _u.mutation.UpdatedAt(); ok { - _spec.SetField(user.FieldUpdatedAt, field.TypeTime, value) - } - if _u.mutation.UserRolesCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: user.UserRolesTable, - Columns: []string{user.UserRolesColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.RemovedUserRolesIDs(); len(nodes) > 0 && !_u.mutation.UserRolesCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: user.UserRolesTable, - Columns: []string{user.UserRolesColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.UserRolesIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.O2M, - Inverse: false, - Table: user.UserRolesTable, - Columns: []string{user.UserRolesColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - _node = &User{config: _u.config} - _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{user.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - _u.mutation.done = true - return _node, nil -} diff --git a/internal/ent/userrole.go b/internal/ent/userrole.go deleted file mode 100644 index 2bb026e..0000000 --- a/internal/ent/userrole.go +++ /dev/null @@ -1,182 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "fmt" - "strings" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "git.dcentral.systems/toolz/goplt/internal/ent/role" - "git.dcentral.systems/toolz/goplt/internal/ent/user" - "git.dcentral.systems/toolz/goplt/internal/ent/userrole" -) - -// UserRole is the model entity for the UserRole schema. -type UserRole struct { - config `json:"-"` - // ID of the ent. - ID int `json:"id,omitempty"` - // UserID holds the value of the "user_id" field. - UserID string `json:"user_id,omitempty"` - // RoleID holds the value of the "role_id" field. - RoleID string `json:"role_id,omitempty"` - // Edges holds the relations/edges for other nodes in the graph. - // The values are being populated by the UserRoleQuery when eager-loading is set. - Edges UserRoleEdges `json:"edges"` - role_user_roles *string - user_user_roles *string - selectValues sql.SelectValues -} - -// UserRoleEdges holds the relations/edges for other nodes in the graph. -type UserRoleEdges struct { - // User holds the value of the user edge. - User *User `json:"user,omitempty"` - // Role holds the value of the role edge. - Role *Role `json:"role,omitempty"` - // loadedTypes holds the information for reporting if a - // type was loaded (or requested) in eager-loading or not. - loadedTypes [2]bool -} - -// UserOrErr returns the User value or an error if the edge -// was not loaded in eager-loading, or loaded but was not found. -func (e UserRoleEdges) UserOrErr() (*User, error) { - if e.User != nil { - return e.User, nil - } else if e.loadedTypes[0] { - return nil, &NotFoundError{label: user.Label} - } - return nil, &NotLoadedError{edge: "user"} -} - -// RoleOrErr returns the Role value or an error if the edge -// was not loaded in eager-loading, or loaded but was not found. -func (e UserRoleEdges) RoleOrErr() (*Role, error) { - if e.Role != nil { - return e.Role, nil - } else if e.loadedTypes[1] { - return nil, &NotFoundError{label: role.Label} - } - return nil, &NotLoadedError{edge: "role"} -} - -// scanValues returns the types for scanning values from sql.Rows. -func (*UserRole) scanValues(columns []string) ([]any, error) { - values := make([]any, len(columns)) - for i := range columns { - switch columns[i] { - case userrole.FieldID: - values[i] = new(sql.NullInt64) - case userrole.FieldUserID, userrole.FieldRoleID: - values[i] = new(sql.NullString) - case userrole.ForeignKeys[0]: // role_user_roles - values[i] = new(sql.NullString) - case userrole.ForeignKeys[1]: // user_user_roles - values[i] = new(sql.NullString) - default: - values[i] = new(sql.UnknownType) - } - } - return values, nil -} - -// assignValues assigns the values that were returned from sql.Rows (after scanning) -// to the UserRole fields. -func (_m *UserRole) assignValues(columns []string, values []any) error { - if m, n := len(values), len(columns); m < n { - return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) - } - for i := range columns { - switch columns[i] { - case userrole.FieldID: - value, ok := values[i].(*sql.NullInt64) - if !ok { - return fmt.Errorf("unexpected type %T for field id", value) - } - _m.ID = int(value.Int64) - case userrole.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 { - _m.UserID = value.String - } - case userrole.FieldRoleID: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field role_id", values[i]) - } else if value.Valid { - _m.RoleID = value.String - } - case userrole.ForeignKeys[0]: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field role_user_roles", values[i]) - } else if value.Valid { - _m.role_user_roles = new(string) - *_m.role_user_roles = value.String - } - case userrole.ForeignKeys[1]: - if value, ok := values[i].(*sql.NullString); !ok { - return fmt.Errorf("unexpected type %T for field user_user_roles", values[i]) - } else if value.Valid { - _m.user_user_roles = new(string) - *_m.user_user_roles = value.String - } - default: - _m.selectValues.Set(columns[i], values[i]) - } - } - return nil -} - -// Value returns the ent.Value that was dynamically selected and assigned to the UserRole. -// This includes values selected through modifiers, order, etc. -func (_m *UserRole) Value(name string) (ent.Value, error) { - return _m.selectValues.Get(name) -} - -// QueryUser queries the "user" edge of the UserRole entity. -func (_m *UserRole) QueryUser() *UserQuery { - return NewUserRoleClient(_m.config).QueryUser(_m) -} - -// QueryRole queries the "role" edge of the UserRole entity. -func (_m *UserRole) QueryRole() *RoleQuery { - return NewUserRoleClient(_m.config).QueryRole(_m) -} - -// Update returns a builder for updating this UserRole. -// Note that you need to call UserRole.Unwrap() before calling this method if this UserRole -// was returned from a transaction, and the transaction was committed or rolled back. -func (_m *UserRole) Update() *UserRoleUpdateOne { - return NewUserRoleClient(_m.config).UpdateOne(_m) -} - -// Unwrap unwraps the UserRole entity that was returned from a transaction after it was closed, -// so that all future queries will be executed through the driver which created the transaction. -func (_m *UserRole) Unwrap() *UserRole { - _tx, ok := _m.config.driver.(*txDriver) - if !ok { - panic("ent: UserRole is not a transactional entity") - } - _m.config.driver = _tx.drv - return _m -} - -// String implements the fmt.Stringer. -func (_m *UserRole) String() string { - var builder strings.Builder - builder.WriteString("UserRole(") - builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) - builder.WriteString("user_id=") - builder.WriteString(_m.UserID) - builder.WriteString(", ") - builder.WriteString("role_id=") - builder.WriteString(_m.RoleID) - builder.WriteByte(')') - return builder.String() -} - -// UserRoles is a parsable slice of UserRole. -type UserRoles []*UserRole diff --git a/internal/ent/userrole/userrole.go b/internal/ent/userrole/userrole.go deleted file mode 100644 index 23b8734..0000000 --- a/internal/ent/userrole/userrole.go +++ /dev/null @@ -1,114 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package userrole - -import ( - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" -) - -const ( - // Label holds the string label denoting the userrole type in the database. - Label = "user_role" - // 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" - // FieldRoleID holds the string denoting the role_id field in the database. - FieldRoleID = "role_id" - // EdgeUser holds the string denoting the user edge name in mutations. - EdgeUser = "user" - // EdgeRole holds the string denoting the role edge name in mutations. - EdgeRole = "role" - // Table holds the table name of the userrole in the database. - Table = "user_roles" - // UserTable is the table that holds the user relation/edge. - UserTable = "user_roles" - // UserInverseTable is the table name for the User entity. - // It exists in this package in order to avoid circular dependency with the "user" package. - UserInverseTable = "users" - // UserColumn is the table column denoting the user relation/edge. - UserColumn = "user_id" - // RoleTable is the table that holds the role relation/edge. - RoleTable = "user_roles" - // RoleInverseTable is the table name for the Role entity. - // It exists in this package in order to avoid circular dependency with the "role" package. - RoleInverseTable = "roles" - // RoleColumn is the table column denoting the role relation/edge. - RoleColumn = "role_id" -) - -// Columns holds all SQL columns for userrole fields. -var Columns = []string{ - FieldID, - FieldUserID, - FieldRoleID, -} - -// ForeignKeys holds the SQL foreign-keys that are owned by the "user_roles" -// table and are not defined as standalone fields in the schema. -var ForeignKeys = []string{ - "role_user_roles", - "user_user_roles", -} - -// ValidColumn reports if the column name is valid (part of the table columns). -func ValidColumn(column string) bool { - for i := range Columns { - if column == Columns[i] { - return true - } - } - for i := range ForeignKeys { - if column == ForeignKeys[i] { - return true - } - } - return false -} - -// OrderOption defines the ordering options for the UserRole queries. -type OrderOption func(*sql.Selector) - -// ByID orders the results by the id field. -func ByID(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldID, opts...).ToFunc() -} - -// ByUserID orders the results by the user_id field. -func ByUserID(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldUserID, opts...).ToFunc() -} - -// ByRoleID orders the results by the role_id field. -func ByRoleID(opts ...sql.OrderTermOption) OrderOption { - return sql.OrderByField(FieldRoleID, opts...).ToFunc() -} - -// ByUserField orders the results by user field. -func ByUserField(field string, opts ...sql.OrderTermOption) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborTerms(s, newUserStep(), sql.OrderByField(field, opts...)) - } -} - -// ByRoleField orders the results by role field. -func ByRoleField(field string, opts ...sql.OrderTermOption) OrderOption { - return func(s *sql.Selector) { - sqlgraph.OrderByNeighborTerms(s, newRoleStep(), sql.OrderByField(field, opts...)) - } -} -func newUserStep() *sqlgraph.Step { - return sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(UserInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn), - ) -} -func newRoleStep() *sqlgraph.Step { - return sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.To(RoleInverseTable, FieldID), - sqlgraph.Edge(sqlgraph.M2O, false, RoleTable, RoleColumn), - ) -} diff --git a/internal/ent/userrole/where.go b/internal/ent/userrole/where.go deleted file mode 100644 index cc68d90..0000000 --- a/internal/ent/userrole/where.go +++ /dev/null @@ -1,255 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package userrole - -import ( - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" -) - -// ID filters vertices based on their ID field. -func ID(id int) predicate.UserRole { - return predicate.UserRole(sql.FieldEQ(FieldID, id)) -} - -// IDEQ applies the EQ predicate on the ID field. -func IDEQ(id int) predicate.UserRole { - return predicate.UserRole(sql.FieldEQ(FieldID, id)) -} - -// IDNEQ applies the NEQ predicate on the ID field. -func IDNEQ(id int) predicate.UserRole { - return predicate.UserRole(sql.FieldNEQ(FieldID, id)) -} - -// IDIn applies the In predicate on the ID field. -func IDIn(ids ...int) predicate.UserRole { - return predicate.UserRole(sql.FieldIn(FieldID, ids...)) -} - -// IDNotIn applies the NotIn predicate on the ID field. -func IDNotIn(ids ...int) predicate.UserRole { - return predicate.UserRole(sql.FieldNotIn(FieldID, ids...)) -} - -// IDGT applies the GT predicate on the ID field. -func IDGT(id int) predicate.UserRole { - return predicate.UserRole(sql.FieldGT(FieldID, id)) -} - -// IDGTE applies the GTE predicate on the ID field. -func IDGTE(id int) predicate.UserRole { - return predicate.UserRole(sql.FieldGTE(FieldID, id)) -} - -// IDLT applies the LT predicate on the ID field. -func IDLT(id int) predicate.UserRole { - return predicate.UserRole(sql.FieldLT(FieldID, id)) -} - -// IDLTE applies the LTE predicate on the ID field. -func IDLTE(id int) predicate.UserRole { - return predicate.UserRole(sql.FieldLTE(FieldID, id)) -} - -// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ. -func UserID(v string) predicate.UserRole { - return predicate.UserRole(sql.FieldEQ(FieldUserID, v)) -} - -// RoleID applies equality check predicate on the "role_id" field. It's identical to RoleIDEQ. -func RoleID(v string) predicate.UserRole { - return predicate.UserRole(sql.FieldEQ(FieldRoleID, v)) -} - -// UserIDEQ applies the EQ predicate on the "user_id" field. -func UserIDEQ(v string) predicate.UserRole { - return predicate.UserRole(sql.FieldEQ(FieldUserID, v)) -} - -// UserIDNEQ applies the NEQ predicate on the "user_id" field. -func UserIDNEQ(v string) predicate.UserRole { - return predicate.UserRole(sql.FieldNEQ(FieldUserID, v)) -} - -// UserIDIn applies the In predicate on the "user_id" field. -func UserIDIn(vs ...string) predicate.UserRole { - return predicate.UserRole(sql.FieldIn(FieldUserID, vs...)) -} - -// UserIDNotIn applies the NotIn predicate on the "user_id" field. -func UserIDNotIn(vs ...string) predicate.UserRole { - return predicate.UserRole(sql.FieldNotIn(FieldUserID, vs...)) -} - -// UserIDGT applies the GT predicate on the "user_id" field. -func UserIDGT(v string) predicate.UserRole { - return predicate.UserRole(sql.FieldGT(FieldUserID, v)) -} - -// UserIDGTE applies the GTE predicate on the "user_id" field. -func UserIDGTE(v string) predicate.UserRole { - return predicate.UserRole(sql.FieldGTE(FieldUserID, v)) -} - -// UserIDLT applies the LT predicate on the "user_id" field. -func UserIDLT(v string) predicate.UserRole { - return predicate.UserRole(sql.FieldLT(FieldUserID, v)) -} - -// UserIDLTE applies the LTE predicate on the "user_id" field. -func UserIDLTE(v string) predicate.UserRole { - return predicate.UserRole(sql.FieldLTE(FieldUserID, v)) -} - -// UserIDContains applies the Contains predicate on the "user_id" field. -func UserIDContains(v string) predicate.UserRole { - return predicate.UserRole(sql.FieldContains(FieldUserID, v)) -} - -// UserIDHasPrefix applies the HasPrefix predicate on the "user_id" field. -func UserIDHasPrefix(v string) predicate.UserRole { - return predicate.UserRole(sql.FieldHasPrefix(FieldUserID, v)) -} - -// UserIDHasSuffix applies the HasSuffix predicate on the "user_id" field. -func UserIDHasSuffix(v string) predicate.UserRole { - return predicate.UserRole(sql.FieldHasSuffix(FieldUserID, v)) -} - -// UserIDEqualFold applies the EqualFold predicate on the "user_id" field. -func UserIDEqualFold(v string) predicate.UserRole { - return predicate.UserRole(sql.FieldEqualFold(FieldUserID, v)) -} - -// UserIDContainsFold applies the ContainsFold predicate on the "user_id" field. -func UserIDContainsFold(v string) predicate.UserRole { - return predicate.UserRole(sql.FieldContainsFold(FieldUserID, v)) -} - -// RoleIDEQ applies the EQ predicate on the "role_id" field. -func RoleIDEQ(v string) predicate.UserRole { - return predicate.UserRole(sql.FieldEQ(FieldRoleID, v)) -} - -// RoleIDNEQ applies the NEQ predicate on the "role_id" field. -func RoleIDNEQ(v string) predicate.UserRole { - return predicate.UserRole(sql.FieldNEQ(FieldRoleID, v)) -} - -// RoleIDIn applies the In predicate on the "role_id" field. -func RoleIDIn(vs ...string) predicate.UserRole { - return predicate.UserRole(sql.FieldIn(FieldRoleID, vs...)) -} - -// RoleIDNotIn applies the NotIn predicate on the "role_id" field. -func RoleIDNotIn(vs ...string) predicate.UserRole { - return predicate.UserRole(sql.FieldNotIn(FieldRoleID, vs...)) -} - -// RoleIDGT applies the GT predicate on the "role_id" field. -func RoleIDGT(v string) predicate.UserRole { - return predicate.UserRole(sql.FieldGT(FieldRoleID, v)) -} - -// RoleIDGTE applies the GTE predicate on the "role_id" field. -func RoleIDGTE(v string) predicate.UserRole { - return predicate.UserRole(sql.FieldGTE(FieldRoleID, v)) -} - -// RoleIDLT applies the LT predicate on the "role_id" field. -func RoleIDLT(v string) predicate.UserRole { - return predicate.UserRole(sql.FieldLT(FieldRoleID, v)) -} - -// RoleIDLTE applies the LTE predicate on the "role_id" field. -func RoleIDLTE(v string) predicate.UserRole { - return predicate.UserRole(sql.FieldLTE(FieldRoleID, v)) -} - -// RoleIDContains applies the Contains predicate on the "role_id" field. -func RoleIDContains(v string) predicate.UserRole { - return predicate.UserRole(sql.FieldContains(FieldRoleID, v)) -} - -// RoleIDHasPrefix applies the HasPrefix predicate on the "role_id" field. -func RoleIDHasPrefix(v string) predicate.UserRole { - return predicate.UserRole(sql.FieldHasPrefix(FieldRoleID, v)) -} - -// RoleIDHasSuffix applies the HasSuffix predicate on the "role_id" field. -func RoleIDHasSuffix(v string) predicate.UserRole { - return predicate.UserRole(sql.FieldHasSuffix(FieldRoleID, v)) -} - -// RoleIDEqualFold applies the EqualFold predicate on the "role_id" field. -func RoleIDEqualFold(v string) predicate.UserRole { - return predicate.UserRole(sql.FieldEqualFold(FieldRoleID, v)) -} - -// RoleIDContainsFold applies the ContainsFold predicate on the "role_id" field. -func RoleIDContainsFold(v string) predicate.UserRole { - return predicate.UserRole(sql.FieldContainsFold(FieldRoleID, v)) -} - -// HasUser applies the HasEdge predicate on the "user" edge. -func HasUser() predicate.UserRole { - return predicate.UserRole(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.Edge(sqlgraph.M2O, false, UserTable, UserColumn), - ) - sqlgraph.HasNeighbors(s, step) - }) -} - -// HasUserWith applies the HasEdge predicate on the "user" edge with a given conditions (other predicates). -func HasUserWith(preds ...predicate.User) predicate.UserRole { - return predicate.UserRole(func(s *sql.Selector) { - step := newUserStep() - sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { - for _, p := range preds { - p(s) - } - }) - }) -} - -// HasRole applies the HasEdge predicate on the "role" edge. -func HasRole() predicate.UserRole { - return predicate.UserRole(func(s *sql.Selector) { - step := sqlgraph.NewStep( - sqlgraph.From(Table, FieldID), - sqlgraph.Edge(sqlgraph.M2O, false, RoleTable, RoleColumn), - ) - sqlgraph.HasNeighbors(s, step) - }) -} - -// HasRoleWith applies the HasEdge predicate on the "role" edge with a given conditions (other predicates). -func HasRoleWith(preds ...predicate.Role) predicate.UserRole { - return predicate.UserRole(func(s *sql.Selector) { - step := newRoleStep() - sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) { - for _, p := range preds { - p(s) - } - }) - }) -} - -// And groups predicates with the AND operator between them. -func And(predicates ...predicate.UserRole) predicate.UserRole { - return predicate.UserRole(sql.AndPredicates(predicates...)) -} - -// Or groups predicates with the OR operator between them. -func Or(predicates ...predicate.UserRole) predicate.UserRole { - return predicate.UserRole(sql.OrPredicates(predicates...)) -} - -// Not applies the not operator on the given predicate. -func Not(p predicate.UserRole) predicate.UserRole { - return predicate.UserRole(sql.NotPredicates(p)) -} diff --git a/internal/ent/userrole_create.go b/internal/ent/userrole_create.go deleted file mode 100644 index 5670f74..0000000 --- a/internal/ent/userrole_create.go +++ /dev/null @@ -1,240 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "errors" - "fmt" - - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/internal/ent/role" - "git.dcentral.systems/toolz/goplt/internal/ent/user" - "git.dcentral.systems/toolz/goplt/internal/ent/userrole" -) - -// UserRoleCreate is the builder for creating a UserRole entity. -type UserRoleCreate struct { - config - mutation *UserRoleMutation - hooks []Hook -} - -// SetUserID sets the "user_id" field. -func (_c *UserRoleCreate) SetUserID(v string) *UserRoleCreate { - _c.mutation.SetUserID(v) - return _c -} - -// SetRoleID sets the "role_id" field. -func (_c *UserRoleCreate) SetRoleID(v string) *UserRoleCreate { - _c.mutation.SetRoleID(v) - return _c -} - -// SetUser sets the "user" edge to the User entity. -func (_c *UserRoleCreate) SetUser(v *User) *UserRoleCreate { - return _c.SetUserID(v.ID) -} - -// SetRole sets the "role" edge to the Role entity. -func (_c *UserRoleCreate) SetRole(v *Role) *UserRoleCreate { - return _c.SetRoleID(v.ID) -} - -// Mutation returns the UserRoleMutation object of the builder. -func (_c *UserRoleCreate) Mutation() *UserRoleMutation { - return _c.mutation -} - -// Save creates the UserRole in the database. -func (_c *UserRoleCreate) Save(ctx context.Context) (*UserRole, error) { - return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks) -} - -// SaveX calls Save and panics if Save returns an error. -func (_c *UserRoleCreate) SaveX(ctx context.Context) *UserRole { - v, err := _c.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (_c *UserRoleCreate) Exec(ctx context.Context) error { - _, err := _c.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_c *UserRoleCreate) ExecX(ctx context.Context) { - if err := _c.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (_c *UserRoleCreate) check() error { - if _, ok := _c.mutation.UserID(); !ok { - return &ValidationError{Name: "user_id", err: errors.New(`ent: missing required field "UserRole.user_id"`)} - } - if _, ok := _c.mutation.RoleID(); !ok { - return &ValidationError{Name: "role_id", err: errors.New(`ent: missing required field "UserRole.role_id"`)} - } - if len(_c.mutation.UserIDs()) == 0 { - return &ValidationError{Name: "user", err: errors.New(`ent: missing required edge "UserRole.user"`)} - } - if len(_c.mutation.RoleIDs()) == 0 { - return &ValidationError{Name: "role", err: errors.New(`ent: missing required edge "UserRole.role"`)} - } - return nil -} - -func (_c *UserRoleCreate) sqlSave(ctx context.Context) (*UserRole, error) { - if err := _c.check(); err != nil { - return nil, err - } - _node, _spec := _c.createSpec() - if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - id := _spec.ID.Value.(int64) - _node.ID = int(id) - _c.mutation.id = &_node.ID - _c.mutation.done = true - return _node, nil -} - -func (_c *UserRoleCreate) createSpec() (*UserRole, *sqlgraph.CreateSpec) { - var ( - _node = &UserRole{config: _c.config} - _spec = sqlgraph.NewCreateSpec(userrole.Table, sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt)) - ) - if nodes := _c.mutation.UserIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: false, - Table: userrole.UserTable, - Columns: []string{userrole.UserColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeString), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _node.UserID = nodes[0] - _spec.Edges = append(_spec.Edges, edge) - } - if nodes := _c.mutation.RoleIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: false, - Table: userrole.RoleTable, - Columns: []string{userrole.RoleColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeString), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _node.RoleID = nodes[0] - _spec.Edges = append(_spec.Edges, edge) - } - return _node, _spec -} - -// UserRoleCreateBulk is the builder for creating many UserRole entities in bulk. -type UserRoleCreateBulk struct { - config - err error - builders []*UserRoleCreate -} - -// Save creates the UserRole entities in the database. -func (_c *UserRoleCreateBulk) Save(ctx context.Context) ([]*UserRole, error) { - if _c.err != nil { - return nil, _c.err - } - specs := make([]*sqlgraph.CreateSpec, len(_c.builders)) - nodes := make([]*UserRole, len(_c.builders)) - mutators := make([]Mutator, len(_c.builders)) - for i := range _c.builders { - func(i int, root context.Context) { - builder := _c.builders[i] - var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { - mutation, ok := m.(*UserRoleMutation) - if !ok { - return nil, fmt.Errorf("unexpected mutation type %T", m) - } - if err := builder.check(); err != nil { - return nil, err - } - builder.mutation = mutation - var err error - nodes[i], specs[i] = builder.createSpec() - if i < len(mutators)-1 { - _, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation) - } else { - spec := &sqlgraph.BatchCreateSpec{Nodes: specs} - // Invoke the actual operation on the latest mutation in the chain. - if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil { - if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - } - } - if err != nil { - return nil, err - } - mutation.id = &nodes[i].ID - if specs[i].ID.Value != nil { - id := specs[i].ID.Value.(int64) - nodes[i].ID = int(id) - } - mutation.done = true - return nodes[i], nil - }) - for i := len(builder.hooks) - 1; i >= 0; i-- { - mut = builder.hooks[i](mut) - } - mutators[i] = mut - }(i, ctx) - } - if len(mutators) > 0 { - if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil { - return nil, err - } - } - return nodes, nil -} - -// SaveX is like Save, but panics if an error occurs. -func (_c *UserRoleCreateBulk) SaveX(ctx context.Context) []*UserRole { - v, err := _c.Save(ctx) - if err != nil { - panic(err) - } - return v -} - -// Exec executes the query. -func (_c *UserRoleCreateBulk) Exec(ctx context.Context) error { - _, err := _c.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_c *UserRoleCreateBulk) ExecX(ctx context.Context) { - if err := _c.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/internal/ent/userrole_delete.go b/internal/ent/userrole_delete.go deleted file mode 100644 index f2828af..0000000 --- a/internal/ent/userrole_delete.go +++ /dev/null @@ -1,88 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" - "git.dcentral.systems/toolz/goplt/internal/ent/userrole" -) - -// UserRoleDelete is the builder for deleting a UserRole entity. -type UserRoleDelete struct { - config - hooks []Hook - mutation *UserRoleMutation -} - -// Where appends a list predicates to the UserRoleDelete builder. -func (_d *UserRoleDelete) Where(ps ...predicate.UserRole) *UserRoleDelete { - _d.mutation.Where(ps...) - return _d -} - -// Exec executes the deletion query and returns how many vertices were deleted. -func (_d *UserRoleDelete) Exec(ctx context.Context) (int, error) { - return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks) -} - -// ExecX is like Exec, but panics if an error occurs. -func (_d *UserRoleDelete) ExecX(ctx context.Context) int { - n, err := _d.Exec(ctx) - if err != nil { - panic(err) - } - return n -} - -func (_d *UserRoleDelete) sqlExec(ctx context.Context) (int, error) { - _spec := sqlgraph.NewDeleteSpec(userrole.Table, sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt)) - if ps := _d.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec) - if err != nil && sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - _d.mutation.done = true - return affected, err -} - -// UserRoleDeleteOne is the builder for deleting a single UserRole entity. -type UserRoleDeleteOne struct { - _d *UserRoleDelete -} - -// Where appends a list predicates to the UserRoleDelete builder. -func (_d *UserRoleDeleteOne) Where(ps ...predicate.UserRole) *UserRoleDeleteOne { - _d._d.mutation.Where(ps...) - return _d -} - -// Exec executes the deletion query. -func (_d *UserRoleDeleteOne) Exec(ctx context.Context) error { - n, err := _d._d.Exec(ctx) - switch { - case err != nil: - return err - case n == 0: - return &NotFoundError{userrole.Label} - default: - return nil - } -} - -// ExecX is like Exec, but panics if an error occurs. -func (_d *UserRoleDeleteOne) ExecX(ctx context.Context) { - if err := _d.Exec(ctx); err != nil { - panic(err) - } -} diff --git a/internal/ent/userrole_query.go b/internal/ent/userrole_query.go deleted file mode 100644 index 0327d3a..0000000 --- a/internal/ent/userrole_query.go +++ /dev/null @@ -1,686 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "fmt" - "math" - - "entgo.io/ent" - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" - "git.dcentral.systems/toolz/goplt/internal/ent/role" - "git.dcentral.systems/toolz/goplt/internal/ent/user" - "git.dcentral.systems/toolz/goplt/internal/ent/userrole" -) - -// UserRoleQuery is the builder for querying UserRole entities. -type UserRoleQuery struct { - config - ctx *QueryContext - order []userrole.OrderOption - inters []Interceptor - predicates []predicate.UserRole - withUser *UserQuery - withRole *RoleQuery - withFKs bool - // intermediate query (i.e. traversal path). - sql *sql.Selector - path func(context.Context) (*sql.Selector, error) -} - -// Where adds a new predicate for the UserRoleQuery builder. -func (_q *UserRoleQuery) Where(ps ...predicate.UserRole) *UserRoleQuery { - _q.predicates = append(_q.predicates, ps...) - return _q -} - -// Limit the number of records to be returned by this query. -func (_q *UserRoleQuery) Limit(limit int) *UserRoleQuery { - _q.ctx.Limit = &limit - return _q -} - -// Offset to start from. -func (_q *UserRoleQuery) Offset(offset int) *UserRoleQuery { - _q.ctx.Offset = &offset - return _q -} - -// Unique configures the query builder to filter duplicate records on query. -// By default, unique is set to true, and can be disabled using this method. -func (_q *UserRoleQuery) Unique(unique bool) *UserRoleQuery { - _q.ctx.Unique = &unique - return _q -} - -// Order specifies how the records should be ordered. -func (_q *UserRoleQuery) Order(o ...userrole.OrderOption) *UserRoleQuery { - _q.order = append(_q.order, o...) - return _q -} - -// QueryUser chains the current query on the "user" edge. -func (_q *UserRoleQuery) QueryUser() *UserQuery { - query := (&UserClient{config: _q.config}).Query() - query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { - if err := _q.prepareQuery(ctx); err != nil { - return nil, err - } - selector := _q.sqlQuery(ctx) - if err := selector.Err(); err != nil { - return nil, err - } - step := sqlgraph.NewStep( - sqlgraph.From(userrole.Table, userrole.FieldID, selector), - sqlgraph.To(user.Table, user.FieldID), - sqlgraph.Edge(sqlgraph.M2O, false, userrole.UserTable, userrole.UserColumn), - ) - fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) - return fromU, nil - } - return query -} - -// QueryRole chains the current query on the "role" edge. -func (_q *UserRoleQuery) QueryRole() *RoleQuery { - query := (&RoleClient{config: _q.config}).Query() - query.path = func(ctx context.Context) (fromU *sql.Selector, err error) { - if err := _q.prepareQuery(ctx); err != nil { - return nil, err - } - selector := _q.sqlQuery(ctx) - if err := selector.Err(); err != nil { - return nil, err - } - step := sqlgraph.NewStep( - sqlgraph.From(userrole.Table, userrole.FieldID, selector), - sqlgraph.To(role.Table, role.FieldID), - sqlgraph.Edge(sqlgraph.M2O, false, userrole.RoleTable, userrole.RoleColumn), - ) - fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step) - return fromU, nil - } - return query -} - -// First returns the first UserRole entity from the query. -// Returns a *NotFoundError when no UserRole was found. -func (_q *UserRoleQuery) First(ctx context.Context) (*UserRole, error) { - nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst)) - if err != nil { - return nil, err - } - if len(nodes) == 0 { - return nil, &NotFoundError{userrole.Label} - } - return nodes[0], nil -} - -// FirstX is like First, but panics if an error occurs. -func (_q *UserRoleQuery) FirstX(ctx context.Context) *UserRole { - node, err := _q.First(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return node -} - -// FirstID returns the first UserRole ID from the query. -// Returns a *NotFoundError when no UserRole ID was found. -func (_q *UserRoleQuery) FirstID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil { - return - } - if len(ids) == 0 { - err = &NotFoundError{userrole.Label} - return - } - return ids[0], nil -} - -// FirstIDX is like FirstID, but panics if an error occurs. -func (_q *UserRoleQuery) FirstIDX(ctx context.Context) int { - id, err := _q.FirstID(ctx) - if err != nil && !IsNotFound(err) { - panic(err) - } - return id -} - -// Only returns a single UserRole entity found by the query, ensuring it only returns one. -// Returns a *NotSingularError when more than one UserRole entity is found. -// Returns a *NotFoundError when no UserRole entities are found. -func (_q *UserRoleQuery) Only(ctx context.Context) (*UserRole, error) { - nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly)) - if err != nil { - return nil, err - } - switch len(nodes) { - case 1: - return nodes[0], nil - case 0: - return nil, &NotFoundError{userrole.Label} - default: - return nil, &NotSingularError{userrole.Label} - } -} - -// OnlyX is like Only, but panics if an error occurs. -func (_q *UserRoleQuery) OnlyX(ctx context.Context) *UserRole { - node, err := _q.Only(ctx) - if err != nil { - panic(err) - } - return node -} - -// OnlyID is like Only, but returns the only UserRole ID in the query. -// Returns a *NotSingularError when more than one UserRole ID is found. -// Returns a *NotFoundError when no entities are found. -func (_q *UserRoleQuery) OnlyID(ctx context.Context) (id int, err error) { - var ids []int - if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil { - return - } - switch len(ids) { - case 1: - id = ids[0] - case 0: - err = &NotFoundError{userrole.Label} - default: - err = &NotSingularError{userrole.Label} - } - return -} - -// OnlyIDX is like OnlyID, but panics if an error occurs. -func (_q *UserRoleQuery) OnlyIDX(ctx context.Context) int { - id, err := _q.OnlyID(ctx) - if err != nil { - panic(err) - } - return id -} - -// All executes the query and returns a list of UserRoles. -func (_q *UserRoleQuery) All(ctx context.Context) ([]*UserRole, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll) - if err := _q.prepareQuery(ctx); err != nil { - return nil, err - } - qr := querierAll[[]*UserRole, *UserRoleQuery]() - return withInterceptors[[]*UserRole](ctx, _q, qr, _q.inters) -} - -// AllX is like All, but panics if an error occurs. -func (_q *UserRoleQuery) AllX(ctx context.Context) []*UserRole { - nodes, err := _q.All(ctx) - if err != nil { - panic(err) - } - return nodes -} - -// IDs executes the query and returns a list of UserRole IDs. -func (_q *UserRoleQuery) IDs(ctx context.Context) (ids []int, err error) { - if _q.ctx.Unique == nil && _q.path != nil { - _q.Unique(true) - } - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs) - if err = _q.Select(userrole.FieldID).Scan(ctx, &ids); err != nil { - return nil, err - } - return ids, nil -} - -// IDsX is like IDs, but panics if an error occurs. -func (_q *UserRoleQuery) IDsX(ctx context.Context) []int { - ids, err := _q.IDs(ctx) - if err != nil { - panic(err) - } - return ids -} - -// Count returns the count of the given query. -func (_q *UserRoleQuery) Count(ctx context.Context) (int, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount) - if err := _q.prepareQuery(ctx); err != nil { - return 0, err - } - return withInterceptors[int](ctx, _q, querierCount[*UserRoleQuery](), _q.inters) -} - -// CountX is like Count, but panics if an error occurs. -func (_q *UserRoleQuery) CountX(ctx context.Context) int { - count, err := _q.Count(ctx) - if err != nil { - panic(err) - } - return count -} - -// Exist returns true if the query has elements in the graph. -func (_q *UserRoleQuery) Exist(ctx context.Context) (bool, error) { - ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist) - switch _, err := _q.FirstID(ctx); { - case IsNotFound(err): - return false, nil - case err != nil: - return false, fmt.Errorf("ent: check existence: %w", err) - default: - return true, nil - } -} - -// ExistX is like Exist, but panics if an error occurs. -func (_q *UserRoleQuery) ExistX(ctx context.Context) bool { - exist, err := _q.Exist(ctx) - if err != nil { - panic(err) - } - return exist -} - -// Clone returns a duplicate of the UserRoleQuery builder, including all associated steps. It can be -// used to prepare common query builders and use them differently after the clone is made. -func (_q *UserRoleQuery) Clone() *UserRoleQuery { - if _q == nil { - return nil - } - return &UserRoleQuery{ - config: _q.config, - ctx: _q.ctx.Clone(), - order: append([]userrole.OrderOption{}, _q.order...), - inters: append([]Interceptor{}, _q.inters...), - predicates: append([]predicate.UserRole{}, _q.predicates...), - withUser: _q.withUser.Clone(), - withRole: _q.withRole.Clone(), - // clone intermediate query. - sql: _q.sql.Clone(), - path: _q.path, - } -} - -// WithUser tells the query-builder to eager-load the nodes that are connected to -// the "user" edge. The optional arguments are used to configure the query builder of the edge. -func (_q *UserRoleQuery) WithUser(opts ...func(*UserQuery)) *UserRoleQuery { - query := (&UserClient{config: _q.config}).Query() - for _, opt := range opts { - opt(query) - } - _q.withUser = query - return _q -} - -// WithRole tells the query-builder to eager-load the nodes that are connected to -// the "role" edge. The optional arguments are used to configure the query builder of the edge. -func (_q *UserRoleQuery) WithRole(opts ...func(*RoleQuery)) *UserRoleQuery { - query := (&RoleClient{config: _q.config}).Query() - for _, opt := range opts { - opt(query) - } - _q.withRole = query - return _q -} - -// GroupBy is used to group vertices by one or more fields/columns. -// It is often used with aggregate functions, like: count, max, mean, min, sum. -// -// Example: -// -// var v []struct { -// UserID string `json:"user_id,omitempty"` -// Count int `json:"count,omitempty"` -// } -// -// client.UserRole.Query(). -// GroupBy(userrole.FieldUserID). -// Aggregate(ent.Count()). -// Scan(ctx, &v) -func (_q *UserRoleQuery) GroupBy(field string, fields ...string) *UserRoleGroupBy { - _q.ctx.Fields = append([]string{field}, fields...) - grbuild := &UserRoleGroupBy{build: _q} - grbuild.flds = &_q.ctx.Fields - grbuild.label = userrole.Label - grbuild.scan = grbuild.Scan - return grbuild -} - -// Select allows the selection one or more fields/columns for the given query, -// instead of selecting all fields in the entity. -// -// Example: -// -// var v []struct { -// UserID string `json:"user_id,omitempty"` -// } -// -// client.UserRole.Query(). -// Select(userrole.FieldUserID). -// Scan(ctx, &v) -func (_q *UserRoleQuery) Select(fields ...string) *UserRoleSelect { - _q.ctx.Fields = append(_q.ctx.Fields, fields...) - sbuild := &UserRoleSelect{UserRoleQuery: _q} - sbuild.label = userrole.Label - sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan - return sbuild -} - -// Aggregate returns a UserRoleSelect configured with the given aggregations. -func (_q *UserRoleQuery) Aggregate(fns ...AggregateFunc) *UserRoleSelect { - return _q.Select().Aggregate(fns...) -} - -func (_q *UserRoleQuery) prepareQuery(ctx context.Context) error { - for _, inter := range _q.inters { - if inter == nil { - return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") - } - if trv, ok := inter.(Traverser); ok { - if err := trv.Traverse(ctx, _q); err != nil { - return err - } - } - } - for _, f := range _q.ctx.Fields { - if !userrole.ValidColumn(f) { - return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} - } - } - if _q.path != nil { - prev, err := _q.path(ctx) - if err != nil { - return err - } - _q.sql = prev - } - return nil -} - -func (_q *UserRoleQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*UserRole, error) { - var ( - nodes = []*UserRole{} - withFKs = _q.withFKs - _spec = _q.querySpec() - loadedTypes = [2]bool{ - _q.withUser != nil, - _q.withRole != nil, - } - ) - if withFKs { - _spec.Node.Columns = append(_spec.Node.Columns, userrole.ForeignKeys...) - } - _spec.ScanValues = func(columns []string) ([]any, error) { - return (*UserRole).scanValues(nil, columns) - } - _spec.Assign = func(columns []string, values []any) error { - node := &UserRole{config: _q.config} - nodes = append(nodes, node) - node.Edges.loadedTypes = loadedTypes - return node.assignValues(columns, values) - } - for i := range hooks { - hooks[i](ctx, _spec) - } - if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil { - return nil, err - } - if len(nodes) == 0 { - return nodes, nil - } - if query := _q.withUser; query != nil { - if err := _q.loadUser(ctx, query, nodes, nil, - func(n *UserRole, e *User) { n.Edges.User = e }); err != nil { - return nil, err - } - } - if query := _q.withRole; query != nil { - if err := _q.loadRole(ctx, query, nodes, nil, - func(n *UserRole, e *Role) { n.Edges.Role = e }); err != nil { - return nil, err - } - } - return nodes, nil -} - -func (_q *UserRoleQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*UserRole, init func(*UserRole), assign func(*UserRole, *User)) error { - ids := make([]string, 0, len(nodes)) - nodeids := make(map[string][]*UserRole) - for i := range nodes { - fk := nodes[i].UserID - if _, ok := nodeids[fk]; !ok { - ids = append(ids, fk) - } - nodeids[fk] = append(nodeids[fk], nodes[i]) - } - if len(ids) == 0 { - return nil - } - query.Where(user.IDIn(ids...)) - neighbors, err := query.All(ctx) - if err != nil { - return err - } - for _, n := range neighbors { - nodes, ok := nodeids[n.ID] - if !ok { - return fmt.Errorf(`unexpected foreign-key "user_id" returned %v`, n.ID) - } - for i := range nodes { - assign(nodes[i], n) - } - } - return nil -} -func (_q *UserRoleQuery) loadRole(ctx context.Context, query *RoleQuery, nodes []*UserRole, init func(*UserRole), assign func(*UserRole, *Role)) error { - ids := make([]string, 0, len(nodes)) - nodeids := make(map[string][]*UserRole) - for i := range nodes { - fk := nodes[i].RoleID - if _, ok := nodeids[fk]; !ok { - ids = append(ids, fk) - } - nodeids[fk] = append(nodeids[fk], nodes[i]) - } - if len(ids) == 0 { - return nil - } - query.Where(role.IDIn(ids...)) - neighbors, err := query.All(ctx) - if err != nil { - return err - } - for _, n := range neighbors { - nodes, ok := nodeids[n.ID] - if !ok { - return fmt.Errorf(`unexpected foreign-key "role_id" returned %v`, n.ID) - } - for i := range nodes { - assign(nodes[i], n) - } - } - return nil -} - -func (_q *UserRoleQuery) sqlCount(ctx context.Context) (int, error) { - _spec := _q.querySpec() - _spec.Node.Columns = _q.ctx.Fields - if len(_q.ctx.Fields) > 0 { - _spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique - } - return sqlgraph.CountNodes(ctx, _q.driver, _spec) -} - -func (_q *UserRoleQuery) querySpec() *sqlgraph.QuerySpec { - _spec := sqlgraph.NewQuerySpec(userrole.Table, userrole.Columns, sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt)) - _spec.From = _q.sql - if unique := _q.ctx.Unique; unique != nil { - _spec.Unique = *unique - } else if _q.path != nil { - _spec.Unique = true - } - if fields := _q.ctx.Fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, userrole.FieldID) - for i := range fields { - if fields[i] != userrole.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) - } - } - if _q.withUser != nil { - _spec.Node.AddColumnOnce(userrole.FieldUserID) - } - if _q.withRole != nil { - _spec.Node.AddColumnOnce(userrole.FieldRoleID) - } - } - if ps := _q.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if limit := _q.ctx.Limit; limit != nil { - _spec.Limit = *limit - } - if offset := _q.ctx.Offset; offset != nil { - _spec.Offset = *offset - } - if ps := _q.order; len(ps) > 0 { - _spec.Order = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - return _spec -} - -func (_q *UserRoleQuery) sqlQuery(ctx context.Context) *sql.Selector { - builder := sql.Dialect(_q.driver.Dialect()) - t1 := builder.Table(userrole.Table) - columns := _q.ctx.Fields - if len(columns) == 0 { - columns = userrole.Columns - } - selector := builder.Select(t1.Columns(columns...)...).From(t1) - if _q.sql != nil { - selector = _q.sql - selector.Select(selector.Columns(columns...)...) - } - if _q.ctx.Unique != nil && *_q.ctx.Unique { - selector.Distinct() - } - for _, p := range _q.predicates { - p(selector) - } - for _, p := range _q.order { - p(selector) - } - if offset := _q.ctx.Offset; offset != nil { - // limit is mandatory for offset clause. We start - // with default value, and override it below if needed. - selector.Offset(*offset).Limit(math.MaxInt32) - } - if limit := _q.ctx.Limit; limit != nil { - selector.Limit(*limit) - } - return selector -} - -// UserRoleGroupBy is the group-by builder for UserRole entities. -type UserRoleGroupBy struct { - selector - build *UserRoleQuery -} - -// Aggregate adds the given aggregation functions to the group-by query. -func (_g *UserRoleGroupBy) Aggregate(fns ...AggregateFunc) *UserRoleGroupBy { - _g.fns = append(_g.fns, fns...) - return _g -} - -// Scan applies the selector query and scans the result into the given value. -func (_g *UserRoleGroupBy) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy) - if err := _g.build.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*UserRoleQuery, *UserRoleGroupBy](ctx, _g.build, _g, _g.build.inters, v) -} - -func (_g *UserRoleGroupBy) sqlScan(ctx context.Context, root *UserRoleQuery, v any) error { - selector := root.sqlQuery(ctx).Select() - aggregation := make([]string, 0, len(_g.fns)) - for _, fn := range _g.fns { - aggregation = append(aggregation, fn(selector)) - } - if len(selector.SelectedColumns()) == 0 { - columns := make([]string, 0, len(*_g.flds)+len(_g.fns)) - for _, f := range *_g.flds { - columns = append(columns, selector.C(f)) - } - columns = append(columns, aggregation...) - selector.Select(columns...) - } - selector.GroupBy(selector.Columns(*_g.flds...)...) - if err := selector.Err(); err != nil { - return err - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := _g.build.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} - -// UserRoleSelect is the builder for selecting fields of UserRole entities. -type UserRoleSelect struct { - *UserRoleQuery - selector -} - -// Aggregate adds the given aggregation functions to the selector query. -func (_s *UserRoleSelect) Aggregate(fns ...AggregateFunc) *UserRoleSelect { - _s.fns = append(_s.fns, fns...) - return _s -} - -// Scan applies the selector query and scans the result into the given value. -func (_s *UserRoleSelect) Scan(ctx context.Context, v any) error { - ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect) - if err := _s.prepareQuery(ctx); err != nil { - return err - } - return scanWithInterceptors[*UserRoleQuery, *UserRoleSelect](ctx, _s.UserRoleQuery, _s, _s.inters, v) -} - -func (_s *UserRoleSelect) sqlScan(ctx context.Context, root *UserRoleQuery, v any) error { - selector := root.sqlQuery(ctx) - aggregation := make([]string, 0, len(_s.fns)) - for _, fn := range _s.fns { - aggregation = append(aggregation, fn(selector)) - } - switch n := len(*_s.selector.flds); { - case n == 0 && len(aggregation) > 0: - selector.Select(aggregation...) - case n != 0 && len(aggregation) > 0: - selector.AppendSelect(aggregation...) - } - rows := &sql.Rows{} - query, args := selector.Query() - if err := _s.driver.Query(ctx, query, args, rows); err != nil { - return err - } - defer rows.Close() - return sql.ScanSlice(rows, v) -} diff --git a/internal/ent/userrole_update.go b/internal/ent/userrole_update.go deleted file mode 100644 index ed4bf8f..0000000 --- a/internal/ent/userrole_update.go +++ /dev/null @@ -1,421 +0,0 @@ -// Code generated by ent, DO NOT EDIT. - -package ent - -import ( - "context" - "errors" - "fmt" - - "entgo.io/ent/dialect/sql" - "entgo.io/ent/dialect/sql/sqlgraph" - "entgo.io/ent/schema/field" - "git.dcentral.systems/toolz/goplt/internal/ent/predicate" - "git.dcentral.systems/toolz/goplt/internal/ent/role" - "git.dcentral.systems/toolz/goplt/internal/ent/user" - "git.dcentral.systems/toolz/goplt/internal/ent/userrole" -) - -// UserRoleUpdate is the builder for updating UserRole entities. -type UserRoleUpdate struct { - config - hooks []Hook - mutation *UserRoleMutation -} - -// Where appends a list predicates to the UserRoleUpdate builder. -func (_u *UserRoleUpdate) Where(ps ...predicate.UserRole) *UserRoleUpdate { - _u.mutation.Where(ps...) - return _u -} - -// SetUserID sets the "user_id" field. -func (_u *UserRoleUpdate) SetUserID(v string) *UserRoleUpdate { - _u.mutation.SetUserID(v) - return _u -} - -// SetNillableUserID sets the "user_id" field if the given value is not nil. -func (_u *UserRoleUpdate) SetNillableUserID(v *string) *UserRoleUpdate { - if v != nil { - _u.SetUserID(*v) - } - return _u -} - -// SetRoleID sets the "role_id" field. -func (_u *UserRoleUpdate) SetRoleID(v string) *UserRoleUpdate { - _u.mutation.SetRoleID(v) - return _u -} - -// SetNillableRoleID sets the "role_id" field if the given value is not nil. -func (_u *UserRoleUpdate) SetNillableRoleID(v *string) *UserRoleUpdate { - if v != nil { - _u.SetRoleID(*v) - } - return _u -} - -// SetUser sets the "user" edge to the User entity. -func (_u *UserRoleUpdate) SetUser(v *User) *UserRoleUpdate { - return _u.SetUserID(v.ID) -} - -// SetRole sets the "role" edge to the Role entity. -func (_u *UserRoleUpdate) SetRole(v *Role) *UserRoleUpdate { - return _u.SetRoleID(v.ID) -} - -// Mutation returns the UserRoleMutation object of the builder. -func (_u *UserRoleUpdate) Mutation() *UserRoleMutation { - return _u.mutation -} - -// ClearUser clears the "user" edge to the User entity. -func (_u *UserRoleUpdate) ClearUser() *UserRoleUpdate { - _u.mutation.ClearUser() - return _u -} - -// ClearRole clears the "role" edge to the Role entity. -func (_u *UserRoleUpdate) ClearRole() *UserRoleUpdate { - _u.mutation.ClearRole() - return _u -} - -// Save executes the query and returns the number of nodes affected by the update operation. -func (_u *UserRoleUpdate) Save(ctx context.Context) (int, error) { - return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (_u *UserRoleUpdate) SaveX(ctx context.Context) int { - affected, err := _u.Save(ctx) - if err != nil { - panic(err) - } - return affected -} - -// Exec executes the query. -func (_u *UserRoleUpdate) Exec(ctx context.Context) error { - _, err := _u.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_u *UserRoleUpdate) ExecX(ctx context.Context) { - if err := _u.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (_u *UserRoleUpdate) check() error { - if _u.mutation.UserCleared() && len(_u.mutation.UserIDs()) > 0 { - return errors.New(`ent: clearing a required unique edge "UserRole.user"`) - } - if _u.mutation.RoleCleared() && len(_u.mutation.RoleIDs()) > 0 { - return errors.New(`ent: clearing a required unique edge "UserRole.role"`) - } - return nil -} - -func (_u *UserRoleUpdate) sqlSave(ctx context.Context) (_node int, err error) { - if err := _u.check(); err != nil { - return _node, err - } - _spec := sqlgraph.NewUpdateSpec(userrole.Table, userrole.Columns, sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt)) - if ps := _u.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if _u.mutation.UserCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: false, - Table: userrole.UserTable, - Columns: []string{userrole.UserColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeString), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.UserIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: false, - Table: userrole.UserTable, - Columns: []string{userrole.UserColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeString), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - if _u.mutation.RoleCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: false, - Table: userrole.RoleTable, - Columns: []string{userrole.RoleColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeString), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.RoleIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: false, - Table: userrole.RoleTable, - Columns: []string{userrole.RoleColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeString), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{userrole.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return 0, err - } - _u.mutation.done = true - return _node, nil -} - -// UserRoleUpdateOne is the builder for updating a single UserRole entity. -type UserRoleUpdateOne struct { - config - fields []string - hooks []Hook - mutation *UserRoleMutation -} - -// SetUserID sets the "user_id" field. -func (_u *UserRoleUpdateOne) SetUserID(v string) *UserRoleUpdateOne { - _u.mutation.SetUserID(v) - return _u -} - -// SetNillableUserID sets the "user_id" field if the given value is not nil. -func (_u *UserRoleUpdateOne) SetNillableUserID(v *string) *UserRoleUpdateOne { - if v != nil { - _u.SetUserID(*v) - } - return _u -} - -// SetRoleID sets the "role_id" field. -func (_u *UserRoleUpdateOne) SetRoleID(v string) *UserRoleUpdateOne { - _u.mutation.SetRoleID(v) - return _u -} - -// SetNillableRoleID sets the "role_id" field if the given value is not nil. -func (_u *UserRoleUpdateOne) SetNillableRoleID(v *string) *UserRoleUpdateOne { - if v != nil { - _u.SetRoleID(*v) - } - return _u -} - -// SetUser sets the "user" edge to the User entity. -func (_u *UserRoleUpdateOne) SetUser(v *User) *UserRoleUpdateOne { - return _u.SetUserID(v.ID) -} - -// SetRole sets the "role" edge to the Role entity. -func (_u *UserRoleUpdateOne) SetRole(v *Role) *UserRoleUpdateOne { - return _u.SetRoleID(v.ID) -} - -// Mutation returns the UserRoleMutation object of the builder. -func (_u *UserRoleUpdateOne) Mutation() *UserRoleMutation { - return _u.mutation -} - -// ClearUser clears the "user" edge to the User entity. -func (_u *UserRoleUpdateOne) ClearUser() *UserRoleUpdateOne { - _u.mutation.ClearUser() - return _u -} - -// ClearRole clears the "role" edge to the Role entity. -func (_u *UserRoleUpdateOne) ClearRole() *UserRoleUpdateOne { - _u.mutation.ClearRole() - return _u -} - -// Where appends a list predicates to the UserRoleUpdate builder. -func (_u *UserRoleUpdateOne) Where(ps ...predicate.UserRole) *UserRoleUpdateOne { - _u.mutation.Where(ps...) - return _u -} - -// Select allows selecting one or more fields (columns) of the returned entity. -// The default is selecting all fields defined in the entity schema. -func (_u *UserRoleUpdateOne) Select(field string, fields ...string) *UserRoleUpdateOne { - _u.fields = append([]string{field}, fields...) - return _u -} - -// Save executes the query and returns the updated UserRole entity. -func (_u *UserRoleUpdateOne) Save(ctx context.Context) (*UserRole, error) { - return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks) -} - -// SaveX is like Save, but panics if an error occurs. -func (_u *UserRoleUpdateOne) SaveX(ctx context.Context) *UserRole { - node, err := _u.Save(ctx) - if err != nil { - panic(err) - } - return node -} - -// Exec executes the query on the entity. -func (_u *UserRoleUpdateOne) Exec(ctx context.Context) error { - _, err := _u.Save(ctx) - return err -} - -// ExecX is like Exec, but panics if an error occurs. -func (_u *UserRoleUpdateOne) ExecX(ctx context.Context) { - if err := _u.Exec(ctx); err != nil { - panic(err) - } -} - -// check runs all checks and user-defined validators on the builder. -func (_u *UserRoleUpdateOne) check() error { - if _u.mutation.UserCleared() && len(_u.mutation.UserIDs()) > 0 { - return errors.New(`ent: clearing a required unique edge "UserRole.user"`) - } - if _u.mutation.RoleCleared() && len(_u.mutation.RoleIDs()) > 0 { - return errors.New(`ent: clearing a required unique edge "UserRole.role"`) - } - return nil -} - -func (_u *UserRoleUpdateOne) sqlSave(ctx context.Context) (_node *UserRole, err error) { - if err := _u.check(); err != nil { - return _node, err - } - _spec := sqlgraph.NewUpdateSpec(userrole.Table, userrole.Columns, sqlgraph.NewFieldSpec(userrole.FieldID, field.TypeInt)) - id, ok := _u.mutation.ID() - if !ok { - return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "UserRole.id" for update`)} - } - _spec.Node.ID.Value = id - if fields := _u.fields; len(fields) > 0 { - _spec.Node.Columns = make([]string, 0, len(fields)) - _spec.Node.Columns = append(_spec.Node.Columns, userrole.FieldID) - for _, f := range fields { - if !userrole.ValidColumn(f) { - return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} - } - if f != userrole.FieldID { - _spec.Node.Columns = append(_spec.Node.Columns, f) - } - } - } - if ps := _u.mutation.predicates; len(ps) > 0 { - _spec.Predicate = func(selector *sql.Selector) { - for i := range ps { - ps[i](selector) - } - } - } - if _u.mutation.UserCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: false, - Table: userrole.UserTable, - Columns: []string{userrole.UserColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeString), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.UserIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: false, - Table: userrole.UserTable, - Columns: []string{userrole.UserColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeString), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - if _u.mutation.RoleCleared() { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: false, - Table: userrole.RoleTable, - Columns: []string{userrole.RoleColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeString), - }, - } - _spec.Edges.Clear = append(_spec.Edges.Clear, edge) - } - if nodes := _u.mutation.RoleIDs(); len(nodes) > 0 { - edge := &sqlgraph.EdgeSpec{ - Rel: sqlgraph.M2O, - Inverse: false, - Table: userrole.RoleTable, - Columns: []string{userrole.RoleColumn}, - Bidi: false, - Target: &sqlgraph.EdgeTarget{ - IDSpec: sqlgraph.NewFieldSpec(role.FieldID, field.TypeString), - }, - } - for _, k := range nodes { - edge.Target.Nodes = append(edge.Target.Nodes, k) - } - _spec.Edges.Add = append(_spec.Edges.Add, edge) - } - _node = &UserRole{config: _u.config} - _spec.Assign = _node.assignValues - _spec.ScanValues = _node.scanValues - if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil { - if _, ok := err.(*sqlgraph.NotFoundError); ok { - err = &NotFoundError{userrole.Label} - } else if sqlgraph.IsConstraintError(err) { - err = &ConstraintError{msg: err.Error(), wrap: err} - } - return nil, err - } - _u.mutation.done = true - return _node, nil -}