Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
04b4d7de3a | ||
|
|
b11cfdc11f | ||
|
|
cdddbec629 | ||
|
|
b3fe0506fb | ||
|
|
8ca0e2772e | ||
|
|
5f6e929d61 | ||
|
|
4caa3c2701 | ||
|
|
a9ecd7bcc6 | ||
|
|
f89465fb39 | ||
|
|
440c3f46a7 | ||
|
|
c746964936 | ||
|
|
b2d6879b3f | ||
|
|
ce4095904e | ||
|
|
0d2dcbff11 | ||
|
|
02dca78dbe | ||
|
|
8df299b767 | ||
|
|
95cf59b2f6 | ||
|
|
a0f643da0e | ||
|
|
99331a5285 | ||
|
|
9245e197a8 | ||
|
|
5fa1d0978f | ||
|
|
0bb683a6f1 | ||
|
|
cb3958bac3 | ||
|
|
91ebf95efa | ||
|
|
7895dd65b2 | ||
|
|
09f8894906 | ||
|
|
45fdef9da7 | ||
|
|
704f256bd7 | ||
|
|
a6026e7ac4 | ||
|
|
1e03b2974a | ||
|
|
daa7c783b9 | ||
|
|
8a82a2a648 | ||
|
|
c3ac68af2a | ||
|
|
ec3897b981 | ||
|
|
62486cee37 | ||
|
|
7c5746ffbc | ||
|
|
47f7b0213b | ||
|
|
8df42f7aab | ||
|
|
d666e05a6d | ||
|
|
c37edf2de5 | ||
|
|
bb9af2465e | ||
|
|
7af00864b3 | ||
|
|
81903e87e3 | ||
|
|
0b96c7a65e | ||
|
|
34ccfe45ea | ||
|
|
d4231150a9 | ||
|
|
2268e93aec | ||
|
|
c976916b6d | ||
|
|
0bbd003a18 | ||
|
|
336a844712 | ||
|
|
51e7f262bd | ||
|
|
99663a3f20 | ||
|
|
4d88248091 | ||
|
|
c143367e15 | ||
|
|
ca44389baa | ||
|
|
05c2a65ef0 | ||
|
|
3f21d204a7 | ||
|
|
c848f950ce | ||
|
|
87bd765a57 | ||
|
|
49325a769e | ||
|
|
238d86f502 | ||
|
|
7064063230 | ||
|
|
b1de4352a8 | ||
|
|
7bf5c1cbcb | ||
|
|
411e24146d | ||
|
|
c7392fc80b | ||
|
|
c37c68a341 | ||
|
|
9230d3cbc9 | ||
|
|
19925e22d9 | ||
|
|
65e0c1b258 | ||
|
|
94bdde32bb | ||
|
|
14c80d26c6 | ||
|
|
9555a99d1c | ||
|
|
0e69895603 | ||
|
|
cc3cf1d70a | ||
|
|
3382d496e3 | ||
|
|
e0b4b00dc1 | ||
|
|
81d896bf78 | ||
|
|
ec576fdbde | ||
|
|
741eae59bb | ||
|
|
505494b378 | ||
|
|
c1033c12bd | ||
|
|
b789333b68 | ||
|
|
61ef73cb12 | ||
|
|
e71be7e0f1 | ||
|
|
0302c03864 | ||
|
|
d21fe54d55 | ||
|
|
a70d3ff82d | ||
|
|
574359f1df | ||
|
|
6da2f54e50 | ||
|
|
886464b2e9 | ||
|
|
396044e354 | ||
|
|
3d15202124 | ||
|
|
756b09b6b8 | ||
|
|
f4d3fadd6f | ||
|
|
1fb6e9e830 | ||
|
|
78ac6a7a29 | ||
|
|
efe8810dff | ||
|
|
5c07e11473 | ||
|
|
d552ad7673 | ||
|
|
496173da1f | ||
|
|
1cdaf33272 | ||
|
|
e2b3969492 | ||
|
|
8661bf8837 | ||
|
|
292fa7a6d2 | ||
|
|
39d7300a8e | ||
|
|
0ad20c9489 | ||
|
|
7eb3b23ddf | ||
|
|
5b06542193 | ||
|
|
38dca4f787 | ||
|
|
737d1ecf5b | ||
|
|
f819cef6d5 | ||
|
|
facae2a6db | ||
|
|
8b021c099d | ||
|
|
8a625188ce | ||
|
|
c0cfa6acde | ||
|
|
0913cfc082 | ||
|
|
59e8465325 | ||
|
|
be6e8ff77b | ||
|
|
ebb85cf843 | ||
|
|
ef959bc3c6 | ||
|
|
8cb7356bbc | ||
|
|
496545188a | ||
|
|
739c80227a | ||
|
|
6218eefd61 | ||
|
|
5715587baf | ||
|
|
ae770a625b | ||
|
|
428ee065d3 | ||
|
|
320ca28f90 | ||
|
|
5e518f5fbd | ||
|
|
24dcba1d72 | ||
|
|
1abc688cad | ||
|
|
34936189d8 | ||
|
|
daf7bf3e8b | ||
|
|
3a9f1c5796 | ||
|
|
bb1e205516 | ||
|
|
9af4a55176 | ||
|
|
51e903c34e | ||
|
|
7f03319646 | ||
|
|
0c33d18a4d | ||
|
|
a747c63b8e | ||
|
|
a03c361b04 | ||
|
|
807d0018ef | ||
|
|
850e267763 | ||
|
|
c75ae56f10 | ||
|
|
caaed775aa | ||
|
|
d11b295729 | ||
|
|
91d0059f8d | ||
|
|
44693d0dfb | ||
|
|
c722212e12 | ||
|
|
f12da65962 | ||
|
|
92745f7534 | ||
|
|
f2917aeaf8 | ||
|
|
a1e2ffd586 | ||
|
|
78a9705fad | ||
|
|
5b6da04a02 | ||
|
|
4661c2f90f | ||
|
|
90e4328885 | ||
|
|
130112a84a | ||
|
|
b368bb6ea1 | ||
|
|
9ecb6211d6 | ||
|
|
79fba9c8d3 | ||
|
|
37c76a93ab | ||
|
|
86e600aa52 | ||
|
|
6a1c28b70e | ||
|
|
9375f1809c | ||
|
|
f176150c93 | ||
|
|
30d25084f0 | ||
|
|
91ad94d941 | ||
|
|
57a778dccf | ||
|
|
f702c66659 | ||
|
|
a095468850 | ||
|
|
f9b6a20995 | ||
|
|
f2770da880 | ||
|
|
d269659e61 | ||
|
|
c4d6715443 | ||
|
|
fc4a1c5433 | ||
|
|
6bdd580b3f | ||
|
|
9cf4882f4c | ||
|
|
406dad998d | ||
|
|
8b0db22c18 | ||
|
|
f06048eccf | ||
|
|
05f5a8b61d | ||
|
|
662625a091 | ||
|
|
6328e69441 | ||
|
|
425dfb80d9 | ||
|
|
4c1fd570f0 | ||
|
|
345f853b5d | ||
|
|
100a70f87c | ||
|
|
18b591bc3b | ||
|
|
6a52b24369 | ||
|
|
228aca9523 | ||
|
|
7e4637cd70 | ||
|
|
3e3c015efa | ||
|
|
30c30b1712 | ||
|
|
e666356483 | ||
|
|
3710bc883b | ||
|
|
64f60d15b0 | ||
|
|
bc4a044337 | ||
|
|
cb233bfa66 | ||
|
|
d46059a735 | ||
|
|
da2fbd9924 | ||
|
|
084e0adb34 | ||
|
|
3bddbb6afe |
@@ -11,11 +11,6 @@
|
||||
*.md
|
||||
!deploy/DOCKER.md
|
||||
docs/
|
||||
# admin-compliance gate (LegalDocumentView.vue) build-time imports
|
||||
# docs/legal/*.md?raw into the frontend bundle; keep that subtree in the
|
||||
# Docker build context even though docs/ is otherwise excluded.
|
||||
!docs/legal/
|
||||
!docs/legal/*.md
|
||||
|
||||
# IDE
|
||||
.idea/
|
||||
@@ -66,9 +61,6 @@ temp/
|
||||
deploy/install.sh
|
||||
deploy/sub2api.service
|
||||
deploy/sub2api-sudoers
|
||||
deploy/data/
|
||||
deploy/postgres_data/
|
||||
deploy/redis_data/
|
||||
|
||||
# GoReleaser
|
||||
.goreleaser.yaml
|
||||
|
||||
@@ -4,13 +4,6 @@ backend/migrations/*.sql text eol=lf
|
||||
# Go 源代码文件
|
||||
*.go text eol=lf
|
||||
|
||||
# 前端 源代码文件
|
||||
*.ts text eol=lf
|
||||
*.tsx text eol=lf
|
||||
*.js text eol=lf
|
||||
*.jsx text eol=lf
|
||||
*.vue text eol=lf
|
||||
|
||||
# Shell 脚本
|
||||
*.sh text eol=lf
|
||||
|
||||
|
||||
@@ -5,33 +5,12 @@ exceptions:
|
||||
severity: high
|
||||
reason: "Admin export only; switched to dynamic import to reduce exposure (CVE-2023-30533)"
|
||||
mitigation: "Load only on export; restrict export permissions and data scope"
|
||||
expires_on: "2026-10-06"
|
||||
expires_on: "2026-04-05"
|
||||
owner: "security@your-domain"
|
||||
- package: xlsx
|
||||
advisory: "GHSA-5pgg-2g8v-p4x9"
|
||||
severity: high
|
||||
reason: "Admin export only; switched to dynamic import to reduce exposure (CVE-2024-22363)"
|
||||
mitigation: "Load only on export; restrict export permissions and data scope"
|
||||
expires_on: "2026-10-06"
|
||||
owner: "security@your-domain"
|
||||
- package: lodash
|
||||
advisory: "GHSA-r5fr-rjxr-66jc"
|
||||
severity: high
|
||||
reason: "lodash _.template not used with untrusted input; only internal admin UI templates"
|
||||
mitigation: "No user-controlled template strings; plan to migrate to lodash-es tree-shaken imports"
|
||||
expires_on: "2026-07-02"
|
||||
owner: "security@your-domain"
|
||||
- package: lodash-es
|
||||
advisory: "GHSA-r5fr-rjxr-66jc"
|
||||
severity: high
|
||||
reason: "lodash-es _.template not used with untrusted input; only internal admin UI templates"
|
||||
mitigation: "No user-controlled template strings; plan to migrate to native JS alternatives"
|
||||
expires_on: "2026-07-02"
|
||||
owner: "security@your-domain"
|
||||
- package: axios
|
||||
advisory: "GHSA-3p68-rc4w-qgx5"
|
||||
severity: critical
|
||||
reason: "NO_PROXY bypass not exploitable; all API calls go to known endpoints via server-side proxy"
|
||||
mitigation: "Proxy configuration not user-controlled; upgrade when axios releases fix"
|
||||
expires_on: "2026-07-10"
|
||||
expires_on: "2026-04-05"
|
||||
owner: "security@your-domain"
|
||||
|
||||
@@ -8,18 +8,6 @@ permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
shell:
|
||||
runs-on: macos-15
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- name: Check deployment scripts
|
||||
run: |
|
||||
/bin/bash -n deploy/apple-container.sh
|
||||
/bin/bash deploy/tests/apple-container-test.sh
|
||||
/bin/sh deploy/tests/docker-compose-security-test.sh
|
||||
/bin/sh deploy/tests/docker-runtime-resources-test.sh
|
||||
/bin/sh deploy/test-caddyfile-cache.sh
|
||||
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
@@ -32,7 +20,7 @@ jobs:
|
||||
cache-dependency-path: backend/go.sum
|
||||
- name: Verify Go version
|
||||
run: |
|
||||
go version | grep -q 'go1.26.5'
|
||||
go version | grep -q 'go1.26.1'
|
||||
- name: Unit tests
|
||||
working-directory: backend
|
||||
run: make test-unit
|
||||
@@ -40,26 +28,6 @@ jobs:
|
||||
working-directory: backend
|
||||
run: make test-integration
|
||||
|
||||
frontend:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 9
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'pnpm'
|
||||
cache-dependency-path: frontend/pnpm-lock.yaml
|
||||
- name: Install frontend dependencies
|
||||
working-directory: frontend
|
||||
run: pnpm install --frozen-lockfile
|
||||
- name: Frontend typecheck and critical vitest
|
||||
run: make test-frontend
|
||||
|
||||
golangci-lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
@@ -72,10 +40,10 @@ jobs:
|
||||
cache-dependency-path: backend/go.sum
|
||||
- name: Verify Go version
|
||||
run: |
|
||||
go version | grep -q 'go1.26.5'
|
||||
go version | grep -q 'go1.26.1'
|
||||
- name: golangci-lint
|
||||
uses: golangci/golangci-lint-action@v9
|
||||
with:
|
||||
version: v2.9
|
||||
args: --timeout=30m
|
||||
working-directory: backend
|
||||
working-directory: backend
|
||||
@@ -1,69 +0,0 @@
|
||||
name: "CLA Assistant"
|
||||
|
||||
on:
|
||||
issue_comment:
|
||||
types: [created]
|
||||
pull_request_target:
|
||||
types: [opened, reopened, closed, synchronize]
|
||||
|
||||
permissions:
|
||||
actions: write
|
||||
contents: write
|
||||
pull-requests: write
|
||||
statuses: write
|
||||
|
||||
env:
|
||||
FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
|
||||
|
||||
jobs:
|
||||
cla-check:
|
||||
if: |
|
||||
github.repository == 'Wei-Shaw/sub2api' &&
|
||||
(
|
||||
github.event_name == 'issue_comment' ||
|
||||
(github.event_name == 'pull_request_target' && github.event.action != 'closed')
|
||||
)
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: "CLA Assistant"
|
||||
if: |
|
||||
(github.event.comment.body == 'recheck' ||
|
||||
github.event.comment.body == 'I have read the CLA Document and I hereby sign the CLA') ||
|
||||
github.event_name == 'pull_request_target'
|
||||
uses: contributor-assistant/github-action@v2.6.1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
path-to-signatures: "cla.json"
|
||||
path-to-document: "https://github.com/Wei-Shaw/sub2api/blob/main/CLA.md"
|
||||
branch: "cla-signatures"
|
||||
allowlist: "dependabot[bot],renovate[bot],bot*"
|
||||
lock-pullrequest-aftermerge: false
|
||||
custom-notsigned-prcomment: |
|
||||
Thank you for your contribution! Before we can merge this PR, we need $you to sign our [Contributor License Agreement (CLA)](https://github.com/Wei-Shaw/sub2api/blob/main/CLA.md).
|
||||
|
||||
**To sign**, please reply with the following comment:
|
||||
|
||||
> I have read the CLA Document and I hereby sign the CLA
|
||||
|
||||
You only need to sign once — it will be valid for all your future contributions to this project.
|
||||
custom-pr-sign-comment: "I have read the CLA Document and I hereby sign the CLA"
|
||||
custom-allsigned-prcomment: "All contributors have signed the CLA. ✅"
|
||||
|
||||
cla-lock:
|
||||
if: |
|
||||
github.repository == 'Wei-Shaw/sub2api' &&
|
||||
github.event_name == 'pull_request_target' &&
|
||||
github.event.action == 'closed' &&
|
||||
github.event.pull_request.merged == true
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: "Lock merged PR"
|
||||
uses: contributor-assistant/github-action@v2.6.1
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
with:
|
||||
path-to-signatures: "cla.json"
|
||||
path-to-document: "https://github.com/Wei-Shaw/sub2api/blob/main/CLA.md"
|
||||
branch: "cla-signatures"
|
||||
lock-pullrequest-aftermerge: true
|
||||
@@ -58,7 +58,7 @@ jobs:
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
|
||||
@@ -115,7 +115,7 @@ jobs:
|
||||
|
||||
- name: Verify Go version
|
||||
run: |
|
||||
go version | grep -q 'go1.26.5'
|
||||
go version | grep -q 'go1.26.1'
|
||||
|
||||
# Docker setup for GoReleaser
|
||||
- name: Set up QEMU
|
||||
@@ -246,10 +246,10 @@ jobs:
|
||||
if [ -n "$DOCKERHUB_USERNAME" ]; then
|
||||
DOCKER_IMAGE="${DOCKERHUB_USERNAME}/sub2api"
|
||||
MESSAGE+="# Docker Hub"$'\n'
|
||||
MESSAGE+="docker pull ${DOCKER_IMAGE}:${VERSION}"$'\n'
|
||||
MESSAGE+="docker pull ${DOCKER_IMAGE}:${TAG_NAME}"$'\n'
|
||||
MESSAGE+="# GitHub Container Registry"$'\n'
|
||||
fi
|
||||
MESSAGE+="docker pull ${GHCR_IMAGE}:${VERSION}"$'\n'
|
||||
MESSAGE+="docker pull ${GHCR_IMAGE}:${TAG_NAME}"$'\n'
|
||||
MESSAGE+="\`\`\`"$'\n'$'\n'
|
||||
MESSAGE+="🔗 *相关链接:*"$'\n'
|
||||
MESSAGE+="• [GitHub Release](https://github.com/${REPO}/releases/tag/${TAG_NAME})"$'\n'
|
||||
@@ -271,36 +271,3 @@ jobs:
|
||||
parse_mode: "Markdown",
|
||||
disable_web_page_preview: true
|
||||
}')"
|
||||
|
||||
sync-version-file:
|
||||
needs: [release]
|
||||
if: ${{ needs.release.result == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout default branch
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.event.repository.default_branch }}
|
||||
|
||||
- name: Sync VERSION file to released tag
|
||||
run: |
|
||||
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
|
||||
VERSION=${{ github.event.inputs.tag }}
|
||||
VERSION=${VERSION#v}
|
||||
else
|
||||
VERSION=${GITHUB_REF#refs/tags/v}
|
||||
fi
|
||||
|
||||
CURRENT_VERSION=$(tr -d '\r\n' < backend/cmd/server/VERSION || true)
|
||||
if [ "$CURRENT_VERSION" = "$VERSION" ]; then
|
||||
echo "VERSION file already matches $VERSION"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "$VERSION" > backend/cmd/server/VERSION
|
||||
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git add backend/cmd/server/VERSION
|
||||
git commit -m "chore: sync VERSION to ${VERSION} [skip ci]"
|
||||
git push origin HEAD:${{ github.event.repository.default_branch }}
|
||||
|
||||
@@ -23,7 +23,7 @@ jobs:
|
||||
cache-dependency-path: backend/go.sum
|
||||
- name: Verify Go version
|
||||
run: |
|
||||
go version | grep -q 'go1.26.5'
|
||||
go version | grep -q 'go1.26.1'
|
||||
- name: Run govulncheck
|
||||
working-directory: backend
|
||||
run: |
|
||||
@@ -35,7 +35,7 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
- name: Set up pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
- name: Set up Node.js
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
docs/claude-relay-service/
|
||||
.codex
|
||||
|
||||
# ===================
|
||||
# Go 后端
|
||||
@@ -79,6 +78,7 @@ Desktop.ini
|
||||
# ===================
|
||||
tmp/
|
||||
temp/
|
||||
logs/
|
||||
*.tmp
|
||||
*.temp
|
||||
*.log
|
||||
@@ -116,29 +116,27 @@ backend/.installed
|
||||
# 其他
|
||||
# ===================
|
||||
tests
|
||||
!deploy/tests/
|
||||
!deploy/tests/**
|
||||
CLAUDE.md
|
||||
.claude
|
||||
scripts
|
||||
!backend/scripts/
|
||||
!backend/scripts/resolve-version.sh
|
||||
.code-review-state
|
||||
#openspec/
|
||||
code-reviews/
|
||||
AGENTS.md
|
||||
#AGENTS.md
|
||||
backend/cmd/server/server
|
||||
deploy/docker-compose.override.yml
|
||||
.gocache/
|
||||
vite.config.js
|
||||
docs/*
|
||||
!docs/PAYMENT.md
|
||||
!docs/PAYMENT_CN.md
|
||||
!docs/ADMIN_PAYMENT_INTEGRATION_API.md
|
||||
!docs/ASYNC_IMAGE_TASKS.md
|
||||
!docs/legal/
|
||||
!docs/legal/*.md
|
||||
.serena/
|
||||
|
||||
# ===================
|
||||
# 压测工具
|
||||
# ===================
|
||||
tools/loadtest/
|
||||
# Antigravity Manager
|
||||
Antigravity-Manager/
|
||||
antigravity_projectid_fix.patch
|
||||
.codex/
|
||||
frontend/coverage/
|
||||
aicodex
|
||||
|
||||
@@ -47,9 +47,6 @@ dockers:
|
||||
- "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub2api:latest"
|
||||
dockerfile: Dockerfile.goreleaser
|
||||
use: buildx
|
||||
extra_files:
|
||||
- deploy/docker-entrypoint.sh
|
||||
- backend/resources
|
||||
build_flag_templates:
|
||||
- "--platform=linux/amd64"
|
||||
- "--label=org.opencontainers.image.version={{ .Version }}"
|
||||
|
||||
@@ -63,9 +63,6 @@ dockers:
|
||||
- "{{ .Env.DOCKERHUB_USERNAME }}/sub2api:{{ .Version }}-amd64"
|
||||
dockerfile: Dockerfile.goreleaser
|
||||
use: buildx
|
||||
extra_files:
|
||||
- deploy/docker-entrypoint.sh
|
||||
- backend/resources
|
||||
build_flag_templates:
|
||||
- "--platform=linux/amd64"
|
||||
- "--label=org.opencontainers.image.version={{ .Version }}"
|
||||
@@ -79,9 +76,6 @@ dockers:
|
||||
- "{{ .Env.DOCKERHUB_USERNAME }}/sub2api:{{ .Version }}-arm64"
|
||||
dockerfile: Dockerfile.goreleaser
|
||||
use: buildx
|
||||
extra_files:
|
||||
- deploy/docker-entrypoint.sh
|
||||
- backend/resources
|
||||
build_flag_templates:
|
||||
- "--platform=linux/arm64"
|
||||
- "--label=org.opencontainers.image.version={{ .Version }}"
|
||||
@@ -95,9 +89,6 @@ dockers:
|
||||
- "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub2api:{{ .Version }}-amd64"
|
||||
dockerfile: Dockerfile.goreleaser
|
||||
use: buildx
|
||||
extra_files:
|
||||
- deploy/docker-entrypoint.sh
|
||||
- backend/resources
|
||||
build_flag_templates:
|
||||
- "--platform=linux/amd64"
|
||||
- "--label=org.opencontainers.image.version={{ .Version }}"
|
||||
@@ -111,9 +102,6 @@ dockers:
|
||||
- "ghcr.io/{{ .Env.GITHUB_REPO_OWNER_LOWER }}/sub2api:{{ .Version }}-arm64"
|
||||
dockerfile: Dockerfile.goreleaser
|
||||
use: buildx
|
||||
extra_files:
|
||||
- deploy/docker-entrypoint.sh
|
||||
- backend/resources
|
||||
build_flag_templates:
|
||||
- "--platform=linux/arm64"
|
||||
- "--label=org.opencontainers.image.version={{ .Version }}"
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
# Sub2API Individual Contributor License Agreement (v1.0)
|
||||
|
||||
Thank you for your interest in contributing to Sub2API ("the Project"). This Contributor License Agreement ("Agreement") documents the rights granted by contributors to the Project.
|
||||
|
||||
By signing this Agreement, you accept and agree to the following terms and conditions for your present and future contributions submitted to the Project.
|
||||
|
||||
## 1. Definitions
|
||||
|
||||
- **"You" (or "Your")** means the copyright owner or legal entity authorized by the copyright owner that is making this Agreement.
|
||||
- **"Contribution"** means any original work of authorship, including any modifications or additions to an existing work, that is intentionally submitted by You to the Project for inclusion in, or documentation of, any of the products owned or managed by the Project. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Project or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of discussing and improving the Project, but excluding communication that is conspicuously marked or otherwise designated in writing by You as "Not a Contribution."
|
||||
- **"Project Owner"** means Wesley Liddick, or any individual or legal entity to whom Wesley Liddick has explicitly assigned or transferred ownership of the Project in writing, and their respective successors and assigns.
|
||||
|
||||
## 2. Grant of Copyright License
|
||||
|
||||
Subject to the terms and conditions of this Agreement, You hereby grant to the Project Owner a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense, and distribute Your Contributions and such derivative works. This license includes, without limitation, the right to sublicense, assign, and transfer these rights to any third party, including without limitation any successor, assignee, or acquiring entity of the Project or the Project Owner, and to use Your Contributions under any license, including proprietary or commercial licenses.
|
||||
|
||||
## 3. Moral Rights
|
||||
|
||||
To the fullest extent permitted by applicable law, You irrevocably waive and agree not to assert any moral rights (including rights of attribution and integrity) that You may have in Your Contributions, and agree that the Project Owner and its licensees may use, modify, and distribute Your Contributions without attribution or other obligations arising from moral rights.
|
||||
|
||||
## 4. Grant of Patent License
|
||||
|
||||
Subject to the terms and conditions of this Agreement, You hereby grant to the Project Owner a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer Your Contributions, where such license applies only to those patent claims licensable by You that are necessarily infringed by Your Contribution(s) alone or by combination of Your Contribution(s) with the Project to which such Contribution(s) was submitted.
|
||||
|
||||
## 5. Representations and Warranties
|
||||
|
||||
You represent and warrant that:
|
||||
|
||||
(a) You are legally entitled to grant the above licenses.
|
||||
|
||||
(b) If Your employer(s) has rights to intellectual property that You create that includes Your Contributions, You have received permission to make Contributions on behalf of that employer, or that Your employer has waived such rights for Your Contributions to the Project.
|
||||
|
||||
(c) Each of Your Contributions is Your original creation, or You have sufficient rights to submit it under the terms of this Agreement. You agree to provide, upon request, reasonable documentation or explanation of any third-party materials included in Your Contributions.
|
||||
|
||||
## 6. No Warranty
|
||||
|
||||
Your Contributions are provided on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are not expected to provide support for Your Contributions, except to the extent You desire to provide support.
|
||||
|
||||
## 7. No Obligation
|
||||
|
||||
You understand that the decision to include Your Contribution in any product or project is entirely at the discretion of the Project Owner, and this Agreement does not obligate the Project Owner to use Your Contribution.
|
||||
|
||||
## 8. Retention of Rights
|
||||
|
||||
You retain ownership of the copyright in Your Contributions. This Agreement does not transfer any copyright or other intellectual property rights from You to the Project Owner. This Agreement only grants the licenses described above.
|
||||
|
||||
## 9. Term and Termination
|
||||
|
||||
This Agreement shall remain in effect indefinitely. You may terminate this Agreement prospectively by providing written notice to the Project Owner, but such termination shall not affect the licenses granted for Contributions submitted prior to the effective date of termination. The licenses granted herein for Contributions submitted prior to termination are perpetual and irrevocable.
|
||||
|
||||
## 10. Electronic Signature
|
||||
|
||||
You agree that Your electronic signature (including but not limited to typing a specific phrase in a pull request, issue, or other electronic communication) is legally binding and has the same force and effect as a handwritten signature. You consent to the use of electronic means to enter into this Agreement and acknowledge that this Agreement is enforceable as if executed in a traditional written format.
|
||||
|
||||
## 11. General Provisions
|
||||
|
||||
**Entire Agreement.** This Agreement constitutes the entire agreement between You and the Project Owner with respect to Your Contributions and supersedes all prior or contemporaneous understandings regarding such subject matter.
|
||||
|
||||
**Severability.** If any provision of this Agreement is held to be unenforceable or invalid, that provision will be enforced to the maximum extent possible and the remaining provisions will remain in full force and effect.
|
||||
|
||||
**No Waiver.** The failure of the Project Owner to enforce any provision of this Agreement shall not constitute a waiver of that provision or any other provision.
|
||||
|
||||
**Amendment.** This Agreement may only be modified by a written instrument signed by both parties. Modifications to this Agreement apply only to Contributions submitted after the modified Agreement is published and accepted by You. Prior Contributions remain governed by the version of the Agreement in effect at the time of submission.
|
||||
|
||||
**Notification.** Notices under this Agreement shall be sent to the Project Owner via a GitHub issue on the Project repository. Notices are effective upon receipt.
|
||||
|
||||
---
|
||||
|
||||
**By signing this CLA, you acknowledge that you have read and understood this Agreement and agree to be bound by its terms.**
|
||||
|
||||
To sign, reply in the pull request with:
|
||||
|
||||
> I have read the CLA Document and I hereby sign the CLA
|
||||
@@ -1,4 +1,3 @@
|
||||
# syntax=docker/dockerfile:1.7
|
||||
# =============================================================================
|
||||
# Sub2API Multi-Stage Dockerfile
|
||||
# =============================================================================
|
||||
@@ -8,49 +7,33 @@
|
||||
# =============================================================================
|
||||
|
||||
ARG NODE_IMAGE=node:24-alpine
|
||||
ARG GOLANG_IMAGE=golang:1.26.5-alpine
|
||||
ARG GOLANG_IMAGE=golang:1.26.1-alpine
|
||||
ARG ALPINE_IMAGE=alpine:3.21
|
||||
ARG POSTGRES_IMAGE=postgres:18-alpine
|
||||
ARG GOPROXY=https://goproxy.cn,direct
|
||||
ARG GOSUMDB=sum.golang.google.cn
|
||||
ARG NPM_CONFIG_REGISTRY=
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Stage 1: Frontend Builder
|
||||
# -----------------------------------------------------------------------------
|
||||
# --platform=$BUILDPLATFORM: the frontend output is JS (arch-neutral), so build
|
||||
# it on the native host arch instead of under QEMU emulation for the target.
|
||||
FROM --platform=${BUILDPLATFORM} ${NODE_IMAGE} AS frontend-builder
|
||||
ARG NPM_CONFIG_REGISTRY
|
||||
FROM ${NODE_IMAGE} AS frontend-builder
|
||||
|
||||
WORKDIR /app/frontend
|
||||
|
||||
# Install pnpm (pinned to v9 to match CI and keep builds reproducible)
|
||||
RUN corepack enable && corepack prepare pnpm@9 --activate
|
||||
# Install pnpm
|
||||
RUN corepack enable && corepack prepare pnpm@latest --activate
|
||||
|
||||
# Install dependencies first (better caching)
|
||||
COPY frontend/package.json frontend/pnpm-lock.yaml ./
|
||||
RUN --mount=type=cache,id=sub2api-pnpm-store,target=/root/.local/share/pnpm/store \
|
||||
if [ -n "${NPM_CONFIG_REGISTRY}" ]; then pnpm config set registry "${NPM_CONFIG_REGISTRY}"; fi && \
|
||||
pnpm install --frozen-lockfile --prefer-offline
|
||||
RUN pnpm install --frozen-lockfile
|
||||
|
||||
# Copy frontend source and build.
|
||||
# LegalDocumentView.vue (admin-compliance gate) build-time imports
|
||||
# ../../../../docs/legal/*.md?raw, so docs/legal/ must sit beside frontend/
|
||||
# in the image (WORKDIR /app/frontend -> resolves to /app/docs/legal/*.md).
|
||||
# Copy only that subtree to keep the build dependency minimal.
|
||||
# Copy frontend source and build
|
||||
COPY frontend/ ./
|
||||
COPY docs/legal/ /app/docs/legal/
|
||||
RUN pnpm run build
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Stage 2: Backend Builder
|
||||
# -----------------------------------------------------------------------------
|
||||
# --platform=$BUILDPLATFORM: run the Go toolchain on the native host arch and
|
||||
# cross-compile to the target arch below. The binary is CGO_ENABLED=0, so this
|
||||
# is a clean pure-Go cross-compile — no QEMU emulation of go mod download / go
|
||||
# build (emulated networking here was dropping module fetches with EOF).
|
||||
FROM --platform=${BUILDPLATFORM} ${GOLANG_IMAGE} AS backend-builder
|
||||
FROM ${GOLANG_IMAGE} AS backend-builder
|
||||
|
||||
# Build arguments for version info (set by CI)
|
||||
ARG VERSION=
|
||||
@@ -58,9 +41,6 @@ ARG COMMIT=docker
|
||||
ARG DATE
|
||||
ARG GOPROXY
|
||||
ARG GOSUMDB
|
||||
# Populated by buildx from the --platform target (e.g. linux/amd64).
|
||||
ARG TARGETOS
|
||||
ARG TARGETARCH
|
||||
|
||||
ENV GOPROXY=${GOPROXY}
|
||||
ENV GOSUMDB=${GOSUMDB}
|
||||
@@ -72,10 +52,7 @@ WORKDIR /app/backend
|
||||
|
||||
# Copy go mod files first (better caching)
|
||||
COPY backend/go.mod backend/go.sum ./
|
||||
# Cache mount keeps the module cache across builds so a transient CDN blip on
|
||||
# retry resumes instead of re-fetching every zip from scratch.
|
||||
RUN --mount=type=cache,id=sub2api-gomod,target=/go/pkg/mod \
|
||||
go mod download
|
||||
RUN go mod download
|
||||
|
||||
# Copy backend source first
|
||||
COPY backend/ ./
|
||||
@@ -84,13 +61,11 @@ COPY backend/ ./
|
||||
COPY --from=frontend-builder /app/backend/internal/web/dist ./internal/web/dist
|
||||
|
||||
# Build the binary (BuildType=release for CI builds, embed frontend)
|
||||
# Version precedence: build arg VERSION > exact git tag > cmd/server/VERSION
|
||||
RUN --mount=type=cache,id=sub2api-gomod,target=/go/pkg/mod \
|
||||
--mount=type=cache,id=sub2api-gobuild,target=/root/.cache/go-build \
|
||||
VERSION_VALUE="${VERSION}" && \
|
||||
if [ -z "${VERSION_VALUE}" ]; then VERSION_VALUE="$(./scripts/resolve-version.sh)"; fi && \
|
||||
# Version precedence: build arg VERSION > cmd/server/VERSION
|
||||
RUN VERSION_VALUE="${VERSION}" && \
|
||||
if [ -z "${VERSION_VALUE}" ]; then VERSION_VALUE="$(tr -d '\r\n' < ./cmd/server/VERSION)"; fi && \
|
||||
DATE_VALUE="${DATE:-$(date -u +%Y-%m-%dT%H:%M:%SZ)}" && \
|
||||
CGO_ENABLED=0 GOOS=${TARGETOS:-linux} GOARCH=${TARGETARCH} go build \
|
||||
CGO_ENABLED=0 GOOS=linux go build \
|
||||
-tags embed \
|
||||
-ldflags="-s -w -X main.Version=${VERSION_VALUE} -X main.Commit=${COMMIT} -X main.Date=${DATE_VALUE} -X main.BuildType=release" \
|
||||
-trimpath \
|
||||
@@ -98,12 +73,7 @@ RUN --mount=type=cache,id=sub2api-gomod,target=/go/pkg/mod \
|
||||
./cmd/server
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Stage 3: PostgreSQL Client (version-matched with docker-compose)
|
||||
# -----------------------------------------------------------------------------
|
||||
FROM ${POSTGRES_IMAGE} AS pg-client
|
||||
|
||||
# -----------------------------------------------------------------------------
|
||||
# Stage 4: Final Runtime Image
|
||||
# Stage 3: Final Runtime Image
|
||||
# -----------------------------------------------------------------------------
|
||||
FROM ${ALPINE_IMAGE}
|
||||
|
||||
@@ -116,21 +86,8 @@ LABEL org.opencontainers.image.source="https://github.com/Wei-Shaw/sub2api"
|
||||
RUN apk add --no-cache \
|
||||
ca-certificates \
|
||||
tzdata \
|
||||
su-exec \
|
||||
libpq \
|
||||
zstd-libs \
|
||||
lz4-libs \
|
||||
krb5-libs \
|
||||
libldap \
|
||||
libedit \
|
||||
&& rm -rf /var/cache/apk/*
|
||||
|
||||
# Copy pg_dump and psql from the same postgres image used in docker-compose
|
||||
# This ensures version consistency between backup tools and the database server
|
||||
COPY --from=pg-client /usr/local/bin/pg_dump /usr/local/bin/pg_dump
|
||||
COPY --from=pg-client /usr/local/bin/psql /usr/local/bin/psql
|
||||
COPY --from=pg-client /usr/local/lib/libpq.so.5* /usr/local/lib/
|
||||
|
||||
# Create non-root user
|
||||
RUN addgroup -g 1000 sub2api && \
|
||||
adduser -u 1000 -G sub2api -s /bin/sh -D sub2api
|
||||
@@ -145,9 +102,8 @@ COPY --from=backend-builder --chown=sub2api:sub2api /app/backend/resources /app/
|
||||
# Create data directory
|
||||
RUN mkdir -p /app/data && chown sub2api:sub2api /app/data
|
||||
|
||||
# Copy entrypoint script (fixes volume permissions then drops to sub2api)
|
||||
COPY deploy/docker-entrypoint.sh /app/docker-entrypoint.sh
|
||||
RUN chmod +x /app/docker-entrypoint.sh
|
||||
# Switch to non-root user
|
||||
USER sub2api
|
||||
|
||||
# Expose port (can be overridden by SERVER_PORT env var)
|
||||
EXPOSE 8080
|
||||
@@ -156,6 +112,5 @@ EXPOSE 8080
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=10s --retries=3 \
|
||||
CMD wget -q -T 5 -O /dev/null http://localhost:${SERVER_PORT:-8080}/health || exit 1
|
||||
|
||||
# Run the application (entrypoint fixes /app/data ownership then execs as sub2api)
|
||||
ENTRYPOINT ["/app/docker-entrypoint.sh"]
|
||||
CMD ["/app/sub2api"]
|
||||
# Run the application
|
||||
ENTRYPOINT ["/app/sub2api"]
|
||||
|
||||
@@ -5,12 +5,7 @@
|
||||
# It only packages the pre-built binary, no compilation needed.
|
||||
# =============================================================================
|
||||
|
||||
ARG ALPINE_IMAGE=alpine:3.21
|
||||
ARG POSTGRES_IMAGE=postgres:18-alpine
|
||||
|
||||
FROM ${POSTGRES_IMAGE} AS pg-client
|
||||
|
||||
FROM ${ALPINE_IMAGE}
|
||||
FROM alpine:3.19
|
||||
|
||||
LABEL maintainer="Wei-Shaw <github.com/Wei-Shaw>"
|
||||
LABEL description="Sub2API - AI API Gateway Platform"
|
||||
@@ -21,43 +16,25 @@ RUN apk add --no-cache \
|
||||
ca-certificates \
|
||||
tzdata \
|
||||
curl \
|
||||
su-exec \
|
||||
libpq \
|
||||
zstd-libs \
|
||||
lz4-libs \
|
||||
krb5-libs \
|
||||
libldap \
|
||||
libedit \
|
||||
&& rm -rf /var/cache/apk/*
|
||||
|
||||
# Copy pg_dump and psql from a version-matched PostgreSQL image so backup and
|
||||
# restore work in the runtime container without requiring Docker socket access.
|
||||
COPY --from=pg-client /usr/local/bin/pg_dump /usr/local/bin/pg_dump
|
||||
COPY --from=pg-client /usr/local/bin/psql /usr/local/bin/psql
|
||||
COPY --from=pg-client /usr/local/lib/libpq.so.5* /usr/local/lib/
|
||||
|
||||
# Create non-root user
|
||||
RUN addgroup -g 1000 sub2api && \
|
||||
adduser -u 1000 -G sub2api -s /bin/sh -D sub2api
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Copy the pre-built binary and runtime fallback resources from GoReleaser
|
||||
# Copy pre-built binary from GoReleaser
|
||||
COPY sub2api /app/sub2api
|
||||
COPY --chown=sub2api:sub2api backend/resources /app/resources
|
||||
|
||||
# Create data directory
|
||||
RUN mkdir -p /app/data && chown -R sub2api:sub2api /app
|
||||
|
||||
# Copy entrypoint script (fixes volume permissions then drops to sub2api)
|
||||
COPY deploy/docker-entrypoint.sh /app/docker-entrypoint.sh
|
||||
RUN chmod +x /app/docker-entrypoint.sh
|
||||
USER sub2api
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=10s --start-period=10s --retries=3 \
|
||||
CMD curl -f http://localhost:${SERVER_PORT:-8080}/health || exit 1
|
||||
|
||||
# Run the application (entrypoint fixes /app/data ownership then execs as sub2api)
|
||||
ENTRYPOINT ["/app/docker-entrypoint.sh"]
|
||||
CMD ["/app/sub2api"]
|
||||
ENTRYPOINT ["/app/sub2api"]
|
||||
|
||||
@@ -1,165 +1,21 @@
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
MIT License
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
Copyright (c) 2025 Wesley Liddick
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
This version of the GNU Lesser General Public License incorporates
|
||||
the terms and conditions of version 3 of the GNU General Public
|
||||
License, supplemented by the additional permissions listed below.
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
0. Additional Definitions.
|
||||
|
||||
As used herein, "this License" refers to version 3 of the GNU Lesser
|
||||
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
||||
General Public License.
|
||||
|
||||
"The Library" refers to a covered work governed by this License,
|
||||
other than an Application or a Combined Work as defined below.
|
||||
|
||||
An "Application" is any work that makes use of an interface provided
|
||||
by the Library, but which is not otherwise based on the Library.
|
||||
Defining a subclass of a class defined by the Library is deemed a mode
|
||||
of using an interface provided by the Library.
|
||||
|
||||
A "Combined Work" is a work produced by combining or linking an
|
||||
Application with the Library. The particular version of the Library
|
||||
with which the Combined Work was made is also called the "Linked
|
||||
Version".
|
||||
|
||||
The "Minimal Corresponding Source" for a Combined Work means the
|
||||
Corresponding Source for the Combined Work, excluding any source code
|
||||
for portions of the Combined Work that, considered in isolation, are
|
||||
based on the Application, and not on the Linked Version.
|
||||
|
||||
The "Corresponding Application Code" for a Combined Work means the
|
||||
object code and/or source code for the Application, including any data
|
||||
and utility programs needed for reproducing the Combined Work from the
|
||||
Application, but excluding the System Libraries of the Combined Work.
|
||||
|
||||
1. Exception to Section 3 of the GNU GPL.
|
||||
|
||||
You may convey a covered work under sections 3 and 4 of this License
|
||||
without being bound by section 3 of the GNU GPL.
|
||||
|
||||
2. Conveying Modified Versions.
|
||||
|
||||
If you modify a copy of the Library, and, in your modifications, a
|
||||
facility refers to a function or data to be supplied by an Application
|
||||
that uses the facility (other than as an argument passed when the
|
||||
facility is invoked), then you may convey a copy of the modified
|
||||
version:
|
||||
|
||||
a) under this License, provided that you make a good faith effort to
|
||||
ensure that, in the event an Application does not supply the
|
||||
function or data, the facility still operates, and performs
|
||||
whatever part of its purpose remains meaningful, or
|
||||
|
||||
b) under the GNU GPL, with none of the additional permissions of
|
||||
this License applicable to that copy.
|
||||
|
||||
3. Object Code Incorporating Material from Library Header Files.
|
||||
|
||||
The object code form of an Application may incorporate material from
|
||||
a header file that is part of the Library. You may convey such object
|
||||
code under terms of your choice, provided that, if the incorporated
|
||||
material is not limited to numerical parameters, data structure
|
||||
layouts and accessors, or small macros, inline functions and templates
|
||||
(ten or fewer lines in length), you do both of the following:
|
||||
|
||||
a) Give prominent notice with each copy of the object code that the
|
||||
Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the object code with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
4. Combined Works.
|
||||
|
||||
You may convey a Combined Work under terms of your choice that,
|
||||
taken together, effectively do not restrict modification of the
|
||||
portions of the Library contained in the Combined Work and reverse
|
||||
engineering for debugging such modifications, if you also do each of
|
||||
the following:
|
||||
|
||||
a) Give prominent notice with each copy of the Combined Work that
|
||||
the Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
c) For a Combined Work that displays copyright notices during
|
||||
execution, include the copyright notice for the Library among
|
||||
these notices, as well as a reference directing the user to the
|
||||
copies of the GNU GPL and this license document.
|
||||
|
||||
d) Do one of the following:
|
||||
|
||||
0) Convey the Minimal Corresponding Source under the terms of this
|
||||
License, and the Corresponding Application Code in a form
|
||||
suitable for, and under terms that permit, the user to
|
||||
recombine or relink the Application with a modified version of
|
||||
the Linked Version to produce a modified Combined Work, in the
|
||||
manner specified by section 6 of the GNU GPL for conveying
|
||||
Corresponding Source.
|
||||
|
||||
1) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (a) uses at run time
|
||||
a copy of the Library already present on the user's computer
|
||||
system, and (b) will operate properly with a modified version
|
||||
of the Library that is interface-compatible with the Linked
|
||||
Version.
|
||||
|
||||
e) Provide Installation Information, but only if you would otherwise
|
||||
be required to provide such information under section 6 of the
|
||||
GNU GPL, and only to the extent that such information is
|
||||
necessary to install and execute a modified version of the
|
||||
Combined Work produced by recombining or relinking the
|
||||
Application with a modified version of the Linked Version. (If
|
||||
you use option 4d0, the Installation Information must accompany
|
||||
the Minimal Corresponding Source and Corresponding Application
|
||||
Code. If you use option 4d1, you must provide the Installation
|
||||
Information in the manner specified by section 6 of the GNU GPL
|
||||
for conveying Corresponding Source.)
|
||||
|
||||
5. Combined Libraries.
|
||||
|
||||
You may place library facilities that are a work based on the
|
||||
Library side by side in a single library together with other library
|
||||
facilities that are not Applications and are not covered by this
|
||||
License, and convey such a combined library under terms of your
|
||||
choice, if you do both of the following:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work based
|
||||
on the Library, uncombined with any other library facilities,
|
||||
conveyed under the terms of this License.
|
||||
|
||||
b) Give prominent notice with the combined library that part of it
|
||||
is a work based on the Library, and explaining where to find the
|
||||
accompanying uncombined form of the same work.
|
||||
|
||||
6. Revised Versions of the GNU Lesser General Public License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions
|
||||
of the GNU Lesser General Public License from time to time. Such new
|
||||
versions will be similar in spirit to the present version, but may
|
||||
differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Library as you received it specifies that a certain numbered version
|
||||
of the GNU Lesser General Public License "or any later version"
|
||||
applies to it, you have the option of following the terms and
|
||||
conditions either of that published version or of any later version
|
||||
published by the Free Software Foundation. If the Library as you
|
||||
received it does not specify a version number of the GNU Lesser
|
||||
General Public License, you may choose any version of the GNU Lesser
|
||||
General Public License ever published by the Free Software Foundation.
|
||||
|
||||
If the Library as you received it specifies that a proxy can decide
|
||||
whether future versions of the GNU Lesser General Public License shall
|
||||
apply, that proxy's public statement of acceptance of any version is
|
||||
permanent authorization for you to choose that version for the
|
||||
Library.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
@@ -1,14 +1,4 @@
|
||||
.PHONY: build build-backend build-frontend test test-backend test-frontend test-frontend-critical
|
||||
|
||||
FRONTEND_CRITICAL_VITEST := \
|
||||
src/api/__tests__/client.spec.ts \
|
||||
src/api/__tests__/tokenRefresh.spec.ts \
|
||||
src/views/auth/__tests__/LinuxDoCallbackView.spec.ts \
|
||||
src/views/auth/__tests__/WechatCallbackView.spec.ts \
|
||||
src/views/user/__tests__/PaymentView.spec.ts \
|
||||
src/views/user/__tests__/PaymentResultView.spec.ts \
|
||||
src/components/user/profile/__tests__/ProfileInfoCard.spec.ts \
|
||||
src/views/admin/__tests__/SettingsView.spec.ts
|
||||
.PHONY: build build-backend build-frontend build-datamanagementd test test-backend test-frontend test-datamanagementd secret-scan
|
||||
|
||||
# 一键编译前后端
|
||||
build: build-backend build-frontend
|
||||
@@ -21,6 +11,10 @@ build-backend:
|
||||
build-frontend:
|
||||
@pnpm --dir frontend run build
|
||||
|
||||
# 编译 datamanagementd(宿主机数据管理进程)
|
||||
build-datamanagementd:
|
||||
@cd datamanagement && go build -o datamanagementd ./cmd/datamanagementd
|
||||
|
||||
# 运行测试(后端 + 前端)
|
||||
test: test-backend test-frontend
|
||||
|
||||
@@ -30,7 +24,9 @@ test-backend:
|
||||
test-frontend:
|
||||
@pnpm --dir frontend run lint:check
|
||||
@pnpm --dir frontend run typecheck
|
||||
@$(MAKE) test-frontend-critical
|
||||
|
||||
test-frontend-critical:
|
||||
@pnpm --dir frontend exec vitest run $(FRONTEND_CRITICAL_VITEST)
|
||||
test-datamanagementd:
|
||||
@cd datamanagement && go test ./...
|
||||
|
||||
secret-scan:
|
||||
@python3 tools/secret_scan.py
|
||||
|
||||
@@ -1,174 +1,34 @@
|
||||
<div align="center">
|
||||
|
||||
<img src="assets/logo.svg" alt="Sub2API Logo" width="128" />
|
||||
|
||||
# Sub2API
|
||||
|
||||
<div align="center">
|
||||
|
||||
[](https://golang.org/)
|
||||
[](https://vuejs.org/)
|
||||
[](https://www.postgresql.org/)
|
||||
[](https://redis.io/)
|
||||
[](https://www.docker.com/)
|
||||
|
||||
<a href="https://trendshift.io/repositories/21823" target="_blank"><img src="https://trendshift.io/api/badge/repositories/21823" alt="Wei-Shaw%2Fsub2api | Trendshift" width="250" height="55"/></a>
|
||||
|
||||
**AI API Gateway Platform for Subscription Quota Distribution**
|
||||
|
||||
English | [中文](README_CN.md) | [日本語](README_JA.md)
|
||||
English | [中文](README_CN.md)
|
||||
|
||||
</div>
|
||||
|
||||
## ⚠️ Important Notice
|
||||
---
|
||||
|
||||
Please read the following carefully before using this project:
|
||||
## Demo
|
||||
|
||||
- **🚨 Terms of Service Risk**: Using this project may violate the terms of service of Anthropic and other upstream providers. Please review the relevant providers' user agreements before use; all risks arising from such use are borne solely by the user.
|
||||
- **⚖️ Compliant Use**: Use this project only in compliance with the laws and regulations of your country or region. Any unlawful use is strictly prohibited.
|
||||
- **📖 Disclaimer**: This project is provided for technical learning and research purposes only. The authors assume no liability for account bans, service interruptions, data loss, or any other direct or indirect damages resulting from the use of this project.
|
||||
- **🚫 No Commercial Authorization**: The developers of this project have never authorized any individual or organization to conduct any form of commercial operation based on this project. Any commercial activity conducted in the name of or based on this project is unrelated to this project and its developers, and all resulting disputes, losses, and legal liabilities shall be borne solely by the party conducting such activity.
|
||||
Try Sub2API online: **https://demo.sub2api.org/**
|
||||
|
||||
## ❤️ Sponsors
|
||||
Demo credentials (shared demo environment; **not** created automatically for self-hosted installs):
|
||||
|
||||
> [Want to appear here?](mailto:support@sub2api.org)
|
||||
|
||||
<table>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://cctk.ai/register?aff=SUB2API"><img src="assets/partners/logos/cctk.jpg" alt="CCTK.AI" width="150"></a></td>
|
||||
<td>Thanks to CCTK.AI for sponsoring this project! <a href="https://cctk.ai/register?aff=SUB2API">CCTK.AI</a> is an AI API gateway focused on stability and cost-effectiveness, offering fast relay services for Claude, OpenAI, Gemini, and other popular models. It works seamlessly with Claude Code, Codex, and other mainstream coding tools, delivering the same model capabilities at a fraction of the official cost. Register via <a href="https://cctk.ai/register?aff=SUB2API">this link</a> for faster, more stable, and more affordable AI API access.</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.openmodel.ai?ref=sub2api"><img src="assets/partners/logos/openmodel.jpg" alt="openmodel" width="150"></a></td>
|
||||
<td>One API, every top model! <a href="https://www.openmodel.ai?ref=sub2api">OpenModel</a> is a production-grade, high-availability AI API gateway that makes your applications truly fast and stable: automatic failover, smart routing to the best-performing channel, and a production-grade SLA. An SLA that far surpasses any single provider — making stability your core competitive advantage. Works directly with Claude Code, Codex, and Gemini CLI. Register via this link to get started.</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://etok.ai"><img src="assets/partners/logos/etok.png" alt="ETok" width="150"></a></td>
|
||||
<td>Thanks to ETok.ai for sponsoring this project! ETok.ai is dedicated to building a one-stop AI programming tool service platform. We offer professional Claude Code packages and technical community services, with support for Google Gemini and OpenAI Codex. Through carefully designed plans and a professional tech community, we provide developers with reliable service guarantees and continuous technical support, making AI-assisted programming a true productivity tool. Click <a href="https://etok.ai">here</a> to register!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://apikey.fun/register?aff=SUB2API"><img src="assets/partners/logos/apikey-fun.png" alt="APIKEY.FUN" width="150"></a></td>
|
||||
<td>Thanks to APIKEY.FUN for sponsoring this project! <a href="https://apikey.fun/register?aff=SUB2API">APIKEY.FUN</a> is one of the core contributors to the sub2api open-source project, dedicated to providing open, stable, and cost-effective AI API access. The platform supports API relay services for Claude, OpenAI, Gemini, and other popular models, with pricing starting from as low as 7% of the original rate. Register via the exclusive link: <a href="https://apikey.fun/register?aff=SUB2API">APIKEY</a> to enjoy up to 5% off on all recharges.</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://aigocode.com/invite/SUB2API"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></td>
|
||||
<td>Thanks to AIGoCode for sponsoring this project! AIGoCode is an all-in-one platform that integrates Claude Code, Codex, and the latest Gemini models, providing you with stable, efficient, and highly cost-effective AI coding services. The platform offers flexible subscription plans, zero risk of account suspension, direct access with no VPN required, and lightning-fast responses. AIGoCode has prepared a special benefit for sub2api users: if you register via <a href="https://aigocode.com/invite/SUB2API">this link</a>, you'll receive an extra 10% bonus credit on your first top-up!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://shop.bmoplus.com/?utm_source=github"><img src="assets/partners/logos/bmoplus.jpg" alt="bmoplus" width="150"></a></td>
|
||||
<td>Huge thanks to BmoPlus for sponsoring this project! BmoPlus is a highly reliable AI account provider built strictly for heavy AI users and developers. They offer rock-solid, ready-to-use accounts and official top-up services for ChatGPT Plus / ChatGPT Pro (Full Warranty) / Claude Pro / Super Grok / Gemini Pro. By registering and ordering through <a href="https://shop.bmoplus.com/?utm_source=github">BmoPlus - Premium AI Accounts & Top-ups</a>, users can unlock the mind-blowing rate of 10% of the official GPT subscription price (90% OFF)</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://bestproxy.com/?keyword=a2e8iuol"><img src="assets/partners/logos/bestproxy.png" alt="bestproxy" width="150"></a></td>
|
||||
<td>Thanks to Bestproxy for sponsoring this project! <a href="https://bestproxy.com/?keyword=a2e8iuol">Bestproxy</a> provides high-purity residential IPs with dedicated one-IP-per-account support. By combining real home networks with fingerprint isolation, it enables link environment isolation and reduces the probability of association-based risk control.</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://pateway.ai/?ch=1tsfr51"><img src="assets/partners/logos/pateway.png" alt="pateway" width="150"></a></td>
|
||||
<td>Thanks to PatewayAI for sponsoring this project! <a href="https://pateway.ai/?ch=1tsfr51">PatewayAI</a> is a premium API relay built for heavy AI developers, offering the full Claude and Codex series sourced 100% from official providers, with transparent token-level billing. Enterprise plans include high concurrency, dedicated management, contracts, and invoicing. Register now to get $3 in trial credits, top-ups from 60% off, and referral bonuses up to $150.</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://api.pptoken.cc/register?promo=SUB2API"><img src="assets/partners/logos/pptoken.png" alt="pptoken" width="150"></a></td>
|
||||
<td>Thanks to PPToken.cc for sponsoring this project! <a href="https://api.pptoken.cc/register?promo=SUB2API">PPToken.cc</a> specializes in GPT model API relay services, supporting Codex, Claude Code, OpenAI-compatible clients, and Gemini CLI integration. Top-ups are 1:1 (¥1 = $1 credit); GPT models start at 0.16x rate multiplier, with overall cost at roughly 2.2% of official pricing and first-token latency around 1 second — ideal for developers seeking low-cost, high-speed access to GPT model capabilities. Technical support: 24/7 real human responses (no bots), @tech in the group chat and get a reply within 10 minutes. Sponsor benefit: the first 200 users who register via the <a href="https://api.pptoken.cc/register?promo=SUB2API">exclusive registration link</a> and enter promo code `SUB2API` can claim free Codex / Claude Code trial credits — no minimum spend, no card required.
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://veilx.io/#/hello/SJRBRVDV"><img src="assets/partners/logos/veilx.png" alt="veilx" width="150"></a></td>
|
||||
<td>Thanks to Veilx for sponsoring this project! <a href="https://veilx.io/#/hello/SJRBRVDV">Veilx</a> CDN is purpose-built for large-scale AI API traffic, deeply optimized for relay services and call chains across OpenAI, Claude, Gemini, and scenarios like chat, image generation, embeddings, and streaming — delivering lower latency and higher stability under heavy concurrency. It also offers China three-network optimized return lines, making it ideal for global AI relay platforms, overseas AI SaaS, and cross-border high-concurrency deployments.
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://roxybrowser.com/invite/bgGKG7"><img src="assets/partners/logos/RoxyBrowser.png" alt="veilx" width="150"></a></td>
|
||||
<td>Thanks to RoxyBrowser for sponsoring this project! <a href="https://roxybrowser.com/invite/bgGKG7">RoxyBrowser</a> RoxyBrowser is the perfect partner for Sub2API: it features a built-in native Roxy AI Agent and high-quality native residential IPs, supports batch automation via simple commands, and significantly boosts security and efficiency for multi-account management! Click <a href="https://roxybrowser.com/invite/bgGKG7">this link</a> to sign up and receive a free residential IP package plus a 10% lifetime discount.
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://sui-xiang.com/"><img src="assets/partners/logos/sui-xiang.jpg" alt="sui-xiang" width="150"></a></td>
|
||||
<td>Thanks to Suixiang AI Gateway for sponsoring this project! <a href="https://sui-xiang.com/">Suixiang AI Gateway</a> is a reliable and efficient API relay service provider offering relay services for Claude, Codex, Gemini, and more. A privacy-focused relay — no data reselling, no model dilution; privacy, transparency, and lightning-fast after-sales support. New accounts get ¥0.5 in trial credit daily by signing in; top-ups are 1:1, no subscription required, pay-as-you-go. Multi-line redundancy, cross-region disaster recovery, automatic failover, and uninterrupted long-link SSE. 99.9% availability — critical calls never fall behind.
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.proxy4free.com/?keyword=4yjqecpc"><img src="assets/partners/logos/proxy4free.png" alt="proxy4free" width="150"></a></td>
|
||||
<td>Thanks to Proxy4Free for sponsoring this project! Proxy4Free is a data proxy service provider for developers and AI applications, offering residential proxies, static residential proxies, ISP proxies, and datacenter proxies for scenarios such as Web Scraping, Browser Automation, and AI Agents. With global IP resources, stable connections, and flexible switching, it helps developers improve data collection success rates and reduce the risk of IP bans. Register via <a href="https://www.proxy4free.com/?keyword=4yjqecpc">this link</a> to get started and easily build more stable and efficient automation workflows.
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="http://www.fastaitoken.com/register"><img src="assets/partners/logos/fastaitoken.jpg" alt="fastaitoken" width="150"></a></td>
|
||||
<td>🎉 Thanks to FastAIToken for sponsoring this project! <a href="http://www.fastaitoken.com/register">FastAIToken</a> is an AI API aggregation platform for developers, supporting mainstream large models such as OpenAI, Claude, and Gemini. Top-up at 1:1 — 1 CNY = 1 USD of API credit — letting developers use the world's leading large model services at lower cost and with greater convenience.<br>
|
||||
|
||||
🚀 The platform offers a variety of channels to choose from: an ultra-low-price 0.02x OpenAI promotional group (limited time), groups as low as 0.25x OpenAI, 0.7x Claude with 95% fixed cache, and a 1.2x Claude Max channel. It also provides a public status page showing real-time availability, latency, and operating status of each group for transparent and reliable service, plus 7×24 human technical support (not bots) with fast responses to developer needs.
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="http://aimzoon.com"><img src="assets/partners/logos/aimzoon.jpg" alt="aimzoon" width="150"></a></td>
|
||||
<td>Thanks to Aimzoon for sponsoring this project! <a href="http://aimzoon.com">Aimzoon</a> provides stable, cost-effective AI API access services, enabling developers to quickly connect popular AI services to coding tools such as Codex, Claude Code, and Gemini CLI. No complex configuration — faster onboarding, more stable calls, and lower costs. Ongoing promotions including discounted Codex rates and special pricing, with free trial credits upon registration, bringing AI coding into your daily workflow. <a href="http://aimzoon.com">Click here</a> to register and try it out!
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://console.claudeapi.com/agent/register/drTKjyn6wGLK061Z"><img src="assets/partners/logos/claudeapi.jpg" alt="claudeapi" width="150"></a></td>
|
||||
<td>Thanks to Claude API for sponsoring this project! <a href="https://console.claudeapi.com/agent/register/drTKjyn6wGLK061Z">Claude API</a> is an official-channel API provider focused on Claude models. Built on official Anthropic keys and the official AWS Bedrock channel, it delivers a stable integration experience for Claude Code and Agent applications, supports the full Claude model lineup, and retains official capabilities such as Tool Use and long context. The service involves no reverse engineering and no model degradation, making it a great fit for heavy Claude Code users, Agent engineers, and enterprise engineering teams. Register via the <a href="https://console.claudeapi.com/agent/register/drTKjyn6wGLK061Z">exclusive link</a> and contact customer support to receive free trial credits; invoicing and team onboarding are also supported.
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://code0.ai/agent/register/LgpIgl9JHtVG53V1?utm_source=zcf&utm_medium=partner&utm_campaign=zcf_2026&utm_content=default"><img src="assets/partners/logos/code0.jpg" alt="code0" width="150"></a></td>
|
||||
<td>Thanks to code0.ai for sponsoring this project! <a href="https://code0.ai/agent/register/LgpIgl9JHtVG53V1?utm_source=zcf&utm_medium=partner&utm_campaign=zcf_2026&utm_content=default">code0.ai</a> is an AI coding workbench for developers and engineering teams, aggregating mainstream agent coding capabilities such as Claude Code and Codex, and covering common development scenarios including code generation, project understanding, debugging and fixing, code review, and documentation generation. It suits independent developers, Agent engineers, open-source maintainers, and enterprise R&D teams, with invoicing and team onboarding supported. Register via the <a href="https://code0.ai/agent/register/LgpIgl9JHtVG53V1?utm_source=zcf&utm_medium=partner&utm_campaign=zcf_2026&utm_content=default">exclusive link</a> and contact customer support to receive free trial credits and experience a more efficient AI coding workflow.
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://nagora.ai/"><img src="assets/partners/logos/nagora.png" alt="Nagora" width="150"></a></td>
|
||||
<td><a href="https://nagora.ai/">Nagora</a> is a multi-model AI API gateway built for developers and teams. With a single account and API key, you can access more than 26 leading text and image models through one unified interface. It is compatible with OpenAI, Anthropic, and Gemini protocols and integrates seamlessly with development tools such as Claude Code, Codex, and Gemini CLI. The platform provides intelligent routing, automatic failover, transparent pricing, and consolidated billing, along with budget management, rate limiting, and concurrency controls. This makes AI usage more reliable and manageable across individual development, team collaboration, and production environments. No changes to your existing application are required. Simply replace the Base URL and API key to complete the integration in as little as one minute.</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.novada.com/?sub2api/"><img src="assets/partners/logos/novada.png" alt="Novada" width="150"></a></td>
|
||||
<td>Thanks to <a href="https://www.novada.com/?sub2api/">Novada</a> for sponsoring this project! Novada provides residential, ISP, datacenter, and mobile proxies, along with Web Unlocker and Scraper APIs for developers building AI applications and automation workflows. With global IP coverage, flexible rotating and sticky sessions, and precise geo-targeting, Novada helps teams access web data reliably for AI agent workflows, cross-region testing, web research, and browser automation. Explore Novada to build more stable and scalable AI workflows.</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://s.qiniu.com/u6rQrq"><img src="assets/partners/logos/qiniu.jpg" alt="Qiniu AI" width="150"></a></td>
|
||||
<td>Thanks to Qiniu AI for sponsoring this project! Qiniu AI is the enterprise-grade large-model MaaS platform under Qiniu Cloud (02567.HK), offering one-stop access to 150+ mainstream models worldwide, compatible with the protocols of major global model providers, and covering full-modality capabilities including text, image, audio, video, and file processing, serving over 1.69 million enterprises and developers. Qiniu AI offers an exclusive benefit for Sub2API users: register via <a href="https://s.qiniu.com/u6rQrq">this link</a> — enterprise users get 12 million tokens free, and developers get 3 million tokens free.</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://api.fenno.ai/s/dC4k"><img src="assets/partners/logos/fennoai.jpg" alt="FennoAI" width="150"></a></td>
|
||||
<td>Thanks to FennoAI for sponsoring this project! FennoAI is a high-stability, high-performance API relay provider for enterprise R&D teams and developers, compatible with the OpenAI and Anthropic protocols and seamlessly integrating with mainstream AI coding tools such as Codex, Claude Code, and OpenCode. The platform delivers enterprise-grade stability, supporting call volumes of 100 billion tokens per day, and supports business-to-business settlement and invoicing for both domestic and overseas entities to meet enterprise R&D and procurement needs. As an exclusive benefit for Sub2API users, purchase a subscription via the <a href="https://api.fenno.ai/s/dC4k">exclusive link</a> to get $50 worth of Coding Plan credit for only $1.99. Referral rewards are also available: invite friends to purchase and earn up to 20% commission — the more you invite, the more you earn.</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://lanox.ai/?c=6"><img src="assets/partners/logos/lanox.jpg" alt="LanoX AI" width="150"></a></td>
|
||||
<td>Thank you to LanoX AI for sponsoring this project! <a href="https://lanox.ai/?c=6">LanoX AI</a> provides stable, cost-effective global model access services for developers, teams, and enterprises. 🎁 New User Benefits — Claim millions of free tokens, plus 500+ free models for easier low-cost testing, validation, and deployment 🧠 Global Leading Models — GPT · Claude · Gemini · Qwen · Grok... 🎬 Multimodal Creation — Seedance 2.0 · GPT Image · Gemini Nano Banana 🛡️ Enterprise-Grade Reliability — High availability 💎 native capability output 💎 no intelligence degradation 💎 no model mixing 💎 transparent usage and billing 💎 💰 Lower API Costs — Top-tier models from as low as 10% of official pricing, with clear documentation, simple integration, invoicing support, and enterprise-scale batch usage 🏢 Enterprise Choice — Ideal for AI products, Agents, content platforms, and R&D teams with high-volume model usage</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.rapidproxy.io/?ref=sub2api"><img src="assets/partners/logos/rapidproxy.jpg" alt="RapidProxy" width="150"></a></td>
|
||||
<td><a href="https://www.rapidproxy.io/?ref=sub2api">RapidProxy</a> is a data collection proxy solution built for developers, providing stable and reliable residential proxy services. With 90M+ global residential IPs and 200+ country coverage, intelligent rotation, and precise geo-targeting, it helps projects such as web scraping, AI data training, SEO monitoring, and e-commerce data analysis break through access restrictions and improve data collection efficiency. It supports mainstream automation frameworks such as Playwright, Selenium, and Puppeteer, with prices as low as $0.65/GB — <a href="https://www.rapidproxy.io/?ref=sub2api">start your free test now</a>.</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://hao.ai"><img src="assets/partners/logos/haoai.png" alt="hao.ai" width="150"></a></td>
|
||||
<td><a href="https://hao.ai">hao.ai</a> is a high-speed, stable unified large-model API gateway for developers and teams. With a single API Key and a unified interface, you can access mainstream models such as GPT, Claude, and xAI Grok, with compatibility for common protocols and SDKs including OpenAI and Anthropic. The platform provides model routing, failover, team management, and complete request logs, with model prices as low as 15% of official reference pricing, helping users build AI applications more simply, more reliably, and at lower cost.</td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
| Email | Password |
|
||||
|-------|----------|
|
||||
| admin@sub2api.com | admin123 |
|
||||
|
||||
## Overview
|
||||
|
||||
Sub2API is an AI API gateway platform designed to distribute and manage API quotas from AI product subscriptions. Users can access upstream AI services through platform-generated API Keys, while the platform handles authentication, billing, load balancing, and request forwarding.
|
||||
Sub2API is an AI API gateway platform designed to distribute and manage API quotas from AI product subscriptions (like Claude Code $200/month). Users can access upstream AI services through platform-generated API Keys, while the platform handles authentication, billing, load balancing, and request forwarding.
|
||||
|
||||
## Features
|
||||
|
||||
@@ -178,19 +38,7 @@ Sub2API is an AI API gateway platform designed to distribute and manage API quot
|
||||
- **Smart Scheduling** - Intelligent account selection with sticky sessions
|
||||
- **Concurrency Control** - Per-user and per-account concurrency limits
|
||||
- **Rate Limiting** - Configurable request and token rate limits
|
||||
- **Built-in Payment System** - Supports EasyPay, Alipay, WeChat Pay, and Stripe for user self-service top-up, no separate payment service needed ([Configuration Guide](docs/PAYMENT.md))
|
||||
- **Admin Dashboard** - Web interface for monitoring and management
|
||||
- **Composite Groups** - Admin routing layer that resolves requested models to concrete providers for multi-provider groups ([Operator Guide](docs/COMPOSITE_GROUPS.md))
|
||||
- **External System Integration** - Embed external systems (e.g. ticketing) via iframe to extend the admin dashboard
|
||||
|
||||
## Ecosystem
|
||||
|
||||
Community projects that extend or integrate with Sub2API:
|
||||
|
||||
| Project | Description | Features |
|
||||
|---------|-------------|----------|
|
||||
| ~~[Sub2ApiPay](https://github.com/touwaeriol/sub2apipay)~~ | ~~Self-service payment system~~ | **Now Built-in** — Payment is now integrated into Sub2API, no separate deployment needed. See [Payment Configuration Guide](docs/PAYMENT.md) |
|
||||
| [sub2api-mobile](https://github.com/ckken/sub2api-mobile) | Mobile admin console | Cross-platform app (iOS/Android/Web) for user management, account management, monitoring dashboard, and multi-backend switching; built with Expo + React Native |
|
||||
|
||||
## Tech Stack
|
||||
|
||||
@@ -203,15 +51,10 @@ Community projects that extend or integrate with Sub2API:
|
||||
|
||||
---
|
||||
|
||||
## Nginx Reverse Proxy Note
|
||||
## Documentation
|
||||
|
||||
When using Nginx as a reverse proxy for Sub2API (or CRS) with Codex CLI, add the following to the `http` block in your Nginx configuration:
|
||||
|
||||
```nginx
|
||||
underscores_in_headers on;
|
||||
```
|
||||
|
||||
Nginx drops headers containing underscores by default (e.g. `session_id`), which breaks sticky session routing in multi-account setups.
|
||||
- Dependency Security: `docs/dependency-security.md`
|
||||
- Admin Payment Integration API: `docs/ADMIN_PAYMENT_INTEGRATION_API.md`
|
||||
|
||||
---
|
||||
|
||||
@@ -307,10 +150,10 @@ mkdir -p sub2api-deploy && cd sub2api-deploy
|
||||
curl -sSL https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/deploy/docker-deploy.sh | bash
|
||||
|
||||
# Start services
|
||||
docker compose up -d
|
||||
docker-compose up -d
|
||||
|
||||
# View logs
|
||||
docker compose logs -f sub2api
|
||||
docker-compose logs -f sub2api
|
||||
```
|
||||
|
||||
**What the script does:**
|
||||
@@ -331,7 +174,6 @@ cd sub2api/deploy
|
||||
|
||||
# 2. Copy environment configuration
|
||||
cp .env.example .env
|
||||
chmod 600 .env
|
||||
|
||||
# 3. Edit configuration (generate secure passwords)
|
||||
nano .env
|
||||
@@ -375,16 +217,16 @@ mkdir -p data postgres_data redis_data
|
||||
|
||||
# 5. Start all services
|
||||
# Option A: Local directory version (recommended - easy migration)
|
||||
docker compose -f docker-compose.local.yml up -d
|
||||
docker-compose -f docker-compose.local.yml up -d
|
||||
|
||||
# Option B: Named volumes version (simple setup)
|
||||
docker compose up -d
|
||||
docker-compose up -d
|
||||
|
||||
# 6. Check status
|
||||
docker compose -f docker-compose.local.yml ps
|
||||
docker-compose -f docker-compose.local.yml ps
|
||||
|
||||
# 7. View logs
|
||||
docker compose -f docker-compose.local.yml logs -f sub2api
|
||||
docker-compose -f docker-compose.local.yml logs -f sub2api
|
||||
```
|
||||
|
||||
#### Deployment Versions
|
||||
@@ -402,15 +244,15 @@ Open `http://YOUR_SERVER_IP:8080` in your browser.
|
||||
|
||||
If admin password was auto-generated, find it in logs:
|
||||
```bash
|
||||
docker compose -f docker-compose.local.yml logs sub2api | grep "admin password"
|
||||
docker-compose -f docker-compose.local.yml logs sub2api | grep "admin password"
|
||||
```
|
||||
|
||||
#### Upgrade
|
||||
|
||||
```bash
|
||||
# Pull latest image and recreate container
|
||||
docker compose -f docker-compose.local.yml pull
|
||||
docker compose -f docker-compose.local.yml up -d
|
||||
docker-compose -f docker-compose.local.yml pull
|
||||
docker-compose -f docker-compose.local.yml up -d
|
||||
```
|
||||
|
||||
#### Easy Migration (Local Directory Version)
|
||||
@@ -419,7 +261,7 @@ When using `docker-compose.local.yml`, migrate to a new server easily:
|
||||
|
||||
```bash
|
||||
# On source server
|
||||
docker compose -f docker-compose.local.yml down
|
||||
docker-compose -f docker-compose.local.yml down
|
||||
cd ..
|
||||
tar czf sub2api-complete.tar.gz sub2api-deploy/
|
||||
|
||||
@@ -429,45 +271,29 @@ scp sub2api-complete.tar.gz user@new-server:/path/
|
||||
# On new server
|
||||
tar xzf sub2api-complete.tar.gz
|
||||
cd sub2api-deploy/
|
||||
docker compose -f docker-compose.local.yml up -d
|
||||
docker-compose -f docker-compose.local.yml up -d
|
||||
```
|
||||
|
||||
#### Useful Commands
|
||||
|
||||
```bash
|
||||
# Stop all services
|
||||
docker compose -f docker-compose.local.yml down
|
||||
docker-compose -f docker-compose.local.yml down
|
||||
|
||||
# Restart
|
||||
docker compose -f docker-compose.local.yml restart
|
||||
docker-compose -f docker-compose.local.yml restart
|
||||
|
||||
# View all logs
|
||||
docker compose -f docker-compose.local.yml logs -f
|
||||
docker-compose -f docker-compose.local.yml logs -f
|
||||
|
||||
# Remove all data (caution!)
|
||||
docker compose -f docker-compose.local.yml down
|
||||
docker-compose -f docker-compose.local.yml down
|
||||
rm -rf data/ postgres_data/ redis_data/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Method 3: Apple container (macOS)
|
||||
|
||||
Apple-silicon Macs running macOS 26 can run the full Sub2API, PostgreSQL, and Redis stack with Apple `container` 1.1.0 or newer:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/Wei-Shaw/sub2api.git
|
||||
cd sub2api/deploy
|
||||
./apple-container.sh init
|
||||
./apple-container.sh up
|
||||
./apple-container.sh status
|
||||
```
|
||||
|
||||
This is an operator-managed local workflow; Docker Compose remains the recommended production path. See [deploy/APPLE_CONTAINER.md](deploy/APPLE_CONTAINER.md) for lifecycle commands, persistence, upgrades, and runtime limitations.
|
||||
|
||||
---
|
||||
|
||||
### Method 4: Build from Source
|
||||
### Method 3: Build from Source
|
||||
|
||||
Build and run from source code for development or customization.
|
||||
|
||||
@@ -496,8 +322,7 @@ pnpm run build
|
||||
|
||||
# 4. Build backend with embedded frontend
|
||||
cd ../backend
|
||||
VERSION="$(./scripts/resolve-version.sh)"
|
||||
go build -tags embed -ldflags="-X main.Version=${VERSION}" -o sub2api ./cmd/server
|
||||
go build -tags embed -o sub2api ./cmd/server
|
||||
|
||||
# 5. Create configuration file
|
||||
cp ../deploy/config.example.yaml ./config.yaml
|
||||
@@ -526,7 +351,6 @@ database:
|
||||
redis:
|
||||
host: "localhost"
|
||||
port: 6379
|
||||
username: ""
|
||||
password: ""
|
||||
|
||||
jwt:
|
||||
@@ -556,34 +380,25 @@ Additional security-related options are available in `config.yaml`:
|
||||
- `security.response_headers.enabled` to enable configurable response header filtering (disabled uses default allowlist)
|
||||
- `security.csp` to control Content-Security-Policy headers
|
||||
- `billing.circuit_breaker` to fail closed on billing errors
|
||||
- `security.trust_forwarded_ip_for_api_key_acl` enables legacy raw forwarded-header takeover (enabled by default for upgrade compatibility); disable it to enforce `server.trusted_proxies`, which should contain only the exact proxy CIDRs that connect directly to Sub2API
|
||||
- `security.forwarded_client_ip_headers` configures up to 16 third-party CDN client-IP header names; they are checked in order before the built-in headers only while legacy takeover is enabled
|
||||
- `server.trusted_proxies` to enable X-Forwarded-For parsing
|
||||
- `turnstile.required` to require Turnstile in release mode
|
||||
|
||||
Custom client-IP headers can be set in YAML or as a comma-separated environment variable:
|
||||
|
||||
```bash
|
||||
SECURITY_FORWARDED_CLIENT_IP_HEADERS=True-Client-IP,X-CDN-Client-IP
|
||||
```
|
||||
|
||||
Header names are validated, canonicalized, and de-duplicated. The admin security settings can update the list without a restart; new installations persist YAML/environment defaults and existing installations backfill a missing database value. When legacy takeover is disabled, all custom and built-in raw forwarding headers are ignored and Gin uses only `server.trusted_proxies`. While takeover is enabled, firewall the origin to CDN/proxy addresses and make the edge overwrite every trusted client-IP header. See [`deploy/EDGE_SECURITY.md`](deploy/EDGE_SECURITY.md) for the complete migration and trust-boundary rules.
|
||||
|
||||
**⚠️ Security Warning: HTTP URL Configuration**
|
||||
|
||||
When `security.url_allowlist.enabled=false`, the system performs minimal URL validation and **allows HTTP URLs by default** (dev-friendly mode; Docker Compose deployments use the same default). For production, explicitly tighten this to HTTPS-only:
|
||||
When `security.url_allowlist.enabled=false`, the system performs minimal URL validation by default, **rejecting HTTP URLs** and only allowing HTTPS. To allow HTTP URLs (e.g., for development or internal testing), you must explicitly set:
|
||||
|
||||
```yaml
|
||||
security:
|
||||
url_allowlist:
|
||||
enabled: false # Disable allowlist checks
|
||||
allow_insecure_http: false # HTTPS only (recommended for production)
|
||||
allow_insecure_http: true # Allow HTTP URLs (⚠️ INSECURE)
|
||||
```
|
||||
|
||||
**Or via environment variable:**
|
||||
|
||||
```bash
|
||||
SECURITY_URL_ALLOWLIST_ENABLED=false
|
||||
SECURITY_URL_ALLOWLIST_ALLOW_INSECURE_HTTP=false
|
||||
SECURITY_URL_ALLOWLIST_ALLOW_INSECURE_HTTP=true
|
||||
```
|
||||
|
||||
**Risks of allowing HTTP:**
|
||||
@@ -597,7 +412,7 @@ SECURITY_URL_ALLOWLIST_ALLOW_INSECURE_HTTP=false
|
||||
- ✅ Testing account connectivity before obtaining HTTPS
|
||||
- ❌ Production environments (use HTTPS only)
|
||||
|
||||
**Example error for HTTP URLs when `allow_insecure_http: false` is set:**
|
||||
**Example error without this setting:**
|
||||
```
|
||||
Invalid base URL: invalid url scheme: http
|
||||
```
|
||||
@@ -608,65 +423,6 @@ If you disable URL validation or response header filtering, harden your network
|
||||
- Enforce TLS-only outbound traffic
|
||||
- Strip sensitive upstream response headers at the proxy
|
||||
|
||||
#### OpenAI Responses WebSocket ingress limits
|
||||
|
||||
`gateway.openai_ws` bounds the lifetime and aggregate count of client-facing
|
||||
Responses WebSocket sessions. These safeguards apply independently from
|
||||
per-turn user and account concurrency slots, which are released between turns.
|
||||
|
||||
```yaml
|
||||
gateway:
|
||||
openai_ws:
|
||||
# Total time to receive and decompress the first client message.
|
||||
client_first_message_timeout_seconds: 30
|
||||
# Close a client socket idle between completed turns; 0 disables this safeguard.
|
||||
ingress_inter_turn_idle_timeout_seconds: 300
|
||||
# Distributed API-key limit for live client ingress sessions; 0 disables it.
|
||||
max_ingress_connections_per_api_key: 64
|
||||
```
|
||||
|
||||
The first-message timeout is a total read deadline. Deployments that accept
|
||||
large contexts or image-heavy requests over slower links can raise it to
|
||||
120-300 seconds. It expires before HTTP bridge routing, so bridge mode does not
|
||||
override this limit.
|
||||
|
||||
The connection cap is coordinated through Redis using a 60-second lease that
|
||||
is refreshed every 20 seconds. A process that cannot confirm a lease for a
|
||||
full lease lifetime closes its local WebSocket rather than continuing outside
|
||||
the global cap.
|
||||
|
||||
Enable the v2 mode router before selecting an account-level WS mode such as
|
||||
`http_bridge`:
|
||||
|
||||
```yaml
|
||||
gateway:
|
||||
openai_ws:
|
||||
mode_router_v2_enabled: true
|
||||
```
|
||||
|
||||
Or set `GATEWAY_OPENAI_WS_MODE_ROUTER_V2_ENABLED=true` in the environment.
|
||||
Use `http_bridge` for client-WebSocket/upstream-HTTP operation when rolling out
|
||||
or mitigating upstream WebSocket issues.
|
||||
|
||||
#### ⚠️ Important: Creating the Admin Account
|
||||
|
||||
The initial admin account is **only created via the setup wizard** (served at `http://<host>:8080` on first run). The `default.admin_email` / `default.admin_password` fields in `config.yaml` are **not used** to create it — they exist in the template for historical reasons.
|
||||
|
||||
Because step 5 above pre-creates `config.yaml`, the setup wizard will be **skipped on first run**: the server detects an existing config and boots straight into normal mode with an empty `users` table, so the first login attempt fails with `invalid email or password`.
|
||||
|
||||
**Two ways to create the admin account:**
|
||||
|
||||
1. **Recommended — let the wizard generate `config.yaml`:** Skip step 5 (do not run the `cp`). Start `./sub2api` directly; the setup wizard at `http://localhost:8080` walks you through database, Redis, and admin account setup, then writes `config.yaml` for you.
|
||||
|
||||
2. **If you already created `config.yaml`:** Temporarily move it aside so the wizard can trigger on first run, then restore it afterwards:
|
||||
```bash
|
||||
mv config.yaml config.yaml.bak
|
||||
./sub2api # wizard runs at http://localhost:8080 and writes a fresh config.yaml
|
||||
# stop the server (Ctrl+C) once the wizard completes, then restore your config:
|
||||
mv config.yaml.bak config.yaml
|
||||
./sub2api # restart in normal mode and log in with the admin you just created
|
||||
```
|
||||
|
||||
```bash
|
||||
# 6. Run the application
|
||||
./sub2api
|
||||
@@ -706,100 +462,6 @@ Simple Mode is designed for individual developers or internal teams who want qui
|
||||
|
||||
---
|
||||
|
||||
## Asynchronous Image Tasks
|
||||
|
||||
Long-running OpenAI/Grok image generation and editing can be submitted through `/v1/images/generations/async` or `/v1/images/edits/async`, then polled at `/v1/images/tasks/{task_id}` without holding a CDN connection open. See [Asynchronous Image Tasks](docs/ASYNC_IMAGE_TASKS.md) for request and response examples.
|
||||
|
||||
---
|
||||
|
||||
## Grok / xAI Support
|
||||
|
||||
Sub2API supports both Grok subscription accounts through xAI OAuth and standard xAI API-key accounts. Both account types forward OpenAI-compatible Responses traffic to xAI.
|
||||
|
||||
### Supported Scope
|
||||
|
||||
- Platform name: `grok`
|
||||
- Account types: OAuth subscription accounts and xAI API-key accounts
|
||||
- Public Responses targets: `/v1/responses`, `/responses`, and `/backend-api/codex/responses`, forwarded to the Grok subscription proxy for OAuth accounts or `https://api.x.ai/v1/responses` for API-key accounts
|
||||
- Public Claude-compatible target: `/v1/messages`, converted to xAI Responses and returned as Anthropic Messages output for Claude CLI style clients
|
||||
- Public Chat Completions targets: `/v1/chat/completions` and `/chat/completions`, forwarded to the account-type-specific xAI upstream
|
||||
- Codex CLI style Responses WebSocket ingress is accepted on the Responses targets and bridged to xAI HTTP/SSE Responses upstream
|
||||
- Text models: `grok-4.5`, `grok-4.3`, `grok-build-0.1`, `grok-composer-2.5-fast`, `grok-4.20-0309-reasoning`, `grok-4.20-0309-non-reasoning`, and `grok-4.20-multi-agent-0309`
|
||||
- Media targets for Grok groups: `/v1/images/generations`, `/images/generations`, `/v1/images/edits`, `/images/edits`, `/v1/videos/generations`, `/videos/generations`, `/v1/videos/edits`, `/videos/edits`, `/v1/videos/extensions`, `/videos/extensions`, `/v1/videos/{request_id}`, and `/videos/{request_id}`. Generation, editing, and extension requests require the group image-generation permission.
|
||||
- Media models: `grok-imagine`, `grok-imagine-image-quality`, `grok-imagine-image`, `grok-imagine-edit`, `grok-imagine-video`, and `grok-imagine-video-1.5`
|
||||
- JSON image-edit and video-generation requests accept image references in `image`, `images`, `reference_images`, and `mask` objects. Use `url` for xAI-compatible payloads; the legacy `image_url` field remains accepted and is normalized to `url` before forwarding.
|
||||
- Out of scope for this provider: TTS, transcription, browser automation, cookies, and Grok web scraping
|
||||
|
||||
### OAuth Configuration
|
||||
|
||||
The Grok OAuth flow uses PKCE and does not require committing private secrets. The default client details follow the public xAI OAuth flow used by compatible clients, and every value can be overridden by environment variable:
|
||||
|
||||
| Variable | Default |
|
||||
|----------|---------|
|
||||
| `XAI_OAUTH_CLIENT_ID` | Public xAI OAuth client ID |
|
||||
| `XAI_OAUTH_SCOPE` | `openid profile email offline_access grok-cli:access api:access` |
|
||||
| `XAI_OAUTH_REDIRECT_URI` | `http://127.0.0.1:56121/callback` |
|
||||
| `XAI_OAUTH_AUTHORIZE_URL` | `https://auth.x.ai/oauth2/authorize` |
|
||||
| `XAI_OAUTH_TOKEN_URL` | `https://auth.x.ai/oauth2/token` |
|
||||
| `XAI_BASE_URL` | `https://api.x.ai/v1`; runtime-diagnostics override (account `base_url` controls request forwarding) |
|
||||
| `XAI_GROK_CLI_VERSION` | `0.2.114`; optional override for the client identity sent to `cli-chat-proxy.grok.com`. The pinned value is also the floor: an override below it is dropped |
|
||||
|
||||
Administrators can create Grok OAuth or API-key accounts from the dashboard. OAuth authorization and reauthorization are also available through the admin API:
|
||||
|
||||
| Endpoint | Purpose |
|
||||
|----------|---------|
|
||||
| `POST /api/v1/admin/grok/oauth/auth-url` | Generate an xAI OAuth authorization URL |
|
||||
| `POST /api/v1/admin/grok/oauth/exchange-code` | Exchange a callback URL, query string, or code for OAuth credentials |
|
||||
| `POST /api/v1/admin/grok/oauth/refresh-token` | Validate or refresh a Grok refresh token |
|
||||
| `POST /api/v1/admin/grok/accounts/:id/refresh` | Refresh an existing Grok account |
|
||||
|
||||
OAuth credential storage reuses the existing account JSON fields: `access_token`, `refresh_token`, `token_type`, `expires_at`, `base_url`, optional `email`, optional `subscription_tier`, and `entitlement_status`. OAuth inference defaults to `https://cli-chat-proxy.grok.com/v1`; existing OAuth accounts that stored the old `https://api.x.ai/v1` default are redirected to the subscription proxy at runtime. Explicit custom upstreams remain unchanged.
|
||||
|
||||
For API-key accounts, select **Grok → API Key** in the create-account dialog. The official base URL defaults to `https://api.x.ai/v1`; credentials use the existing `base_url` and `api_key` account fields. OAuth accounts continue to use the subscription flow above.
|
||||
|
||||
### Grok Build CLI Configuration
|
||||
|
||||
1. In the Sub2API admin dashboard, add either a `grok` OAuth account and complete xAI authorization, or add a Grok API-key account.
|
||||
2. Create a Grok group, attach the account to it, then create a Sub2API API key assigned to that group.
|
||||
3. In the user API-key page, click **Use Key** and select **Grok CLI**. The modal generates the correct file and base URL for macOS/Linux or Windows. It also provides an OpenCode configuration on the **OpenCode** tab.
|
||||
4. If configuring manually, save the following as `~/.grok/config.toml` (Windows: `%USERPROFILE%\.grok\config.toml`):
|
||||
|
||||
```toml
|
||||
[models]
|
||||
default = "grok"
|
||||
web_search = "grok"
|
||||
|
||||
[model."grok"]
|
||||
model = "grok-4.5"
|
||||
base_url = "https://your-sub2api.example.com/v1"
|
||||
name = "Grok 4.5"
|
||||
api_key = "sk-your-sub2api-key"
|
||||
api_backend = "responses"
|
||||
context_window = 1000000
|
||||
supports_backend_search = true
|
||||
```
|
||||
|
||||
Back up an existing `config.toml` before merging the entry. The file contains a Sub2API API key, so keep it private and restrict its permissions where supported. Verify the effective configuration and make a smoke request:
|
||||
|
||||
```bash
|
||||
grok inspect
|
||||
grok -p "Reply with sub2api-ok" -m grok
|
||||
```
|
||||
|
||||
The `base_url` above is the public Sub2API URL ending in `/v1`, not `api.x.ai` or the internal xAI OAuth proxy URL.
|
||||
|
||||
### Usage And Quota Display
|
||||
|
||||
xAI quota is passive. Sub2API does not invent subscription quota values; it records whitelisted xAI rate-limit headers from successful or rate-limited upstream responses when xAI sends them. Before the first usable upstream response, the dashboard shows quota as unknown and still displays local Sub2API usage stats.
|
||||
|
||||
`401` responses temporarily remove accounts with invalid credentials from scheduling. `403` responses are treated as access or entitlement failures instead of token-refresh loops. `429` responses use `Retry-After` or a short cooldown to temporarily remove the account from scheduling.
|
||||
|
||||
New Grok image and video generation requests use a media-specific eligibility check. API-key accounts remain eligible. OAuth accounts require positive paid-entitlement evidence from the xAI billing probe; Free, forbidden, missing, malformed, and inconclusive billing observations are excluded from new media generation. Unobserved OAuth accounts are probed before the first media request is forwarded, and imports run the billing-first quota probe proactively. Chat requests and video status lookups are not affected by this media-only quarantine. If no eligible account remains, the media endpoint returns HTTP `503` with error type `grok_media_no_eligible_account`.
|
||||
|
||||
Administrators can override automatic media eligibility through the account create/update API by setting `extra.grok_media_eligible` to `false` (exclude) or `true` (force eligible). On update, set it to `null` to remove the override and return to automatic probe-based behavior; omitting the field preserves the current override. A weekly allowance period alone is not treated as a paid tier signal. Successful image responses must contain at least one actual image output; empty HTTP `200` responses trigger account failover instead of being counted and returned as successful generations.
|
||||
|
||||
---
|
||||
|
||||
## Antigravity Support
|
||||
|
||||
Sub2API supports [Antigravity](https://antigravity.so/) accounts. After authorization, dedicated endpoints are available for Claude and Gemini models.
|
||||
@@ -824,6 +486,12 @@ Antigravity accounts support optional **hybrid scheduling**. When enabled, the g
|
||||
|
||||
> **⚠️ Warning**: Anthropic Claude and Antigravity Claude **cannot be mixed within the same conversation context**. Use groups to isolate them properly.
|
||||
|
||||
### Known Issues
|
||||
|
||||
In Claude Code, Plan Mode cannot exit automatically. (Normally when using the native Claude API, after planning is complete, Claude Code will pop up options for users to approve or reject the plan.)
|
||||
|
||||
**Workaround**: Press `Shift + Tab` to manually exit Plan Mode, then type your response to approve or reject the plan.
|
||||
|
||||
---
|
||||
|
||||
## Project Structure
|
||||
@@ -854,6 +522,16 @@ sub2api/
|
||||
└── install.sh # One-click installation script
|
||||
```
|
||||
|
||||
## Disclaimer
|
||||
|
||||
> **Please read carefully before using this project:**
|
||||
>
|
||||
> :rotating_light: **Terms of Service Risk**: Using this project may violate Anthropic's Terms of Service. Please read Anthropic's user agreement carefully before use. All risks arising from the use of this project are borne solely by the user.
|
||||
>
|
||||
> :book: **Disclaimer**: This project is for technical learning and research purposes only. The author assumes no responsibility for account suspension, service interruption, or any other losses caused by the use of this project.
|
||||
|
||||
---
|
||||
|
||||
## Star History
|
||||
|
||||
<a href="https://star-history.com/#Wei-Shaw/sub2api&Date">
|
||||
@@ -868,9 +546,7 @@ sub2api/
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the [GNU Lesser General Public License v3.0](LICENSE) (or later).
|
||||
|
||||
Copyright (c) 2026 Wesley Liddick
|
||||
MIT License
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -1,177 +1,34 @@
|
||||
<div align="center">
|
||||
|
||||
<img src="assets/logo.svg" alt="Sub2API Logo" width="128" />
|
||||
|
||||
# Sub2API
|
||||
|
||||
<div align="center">
|
||||
|
||||
[](https://golang.org/)
|
||||
[](https://vuejs.org/)
|
||||
[](https://www.postgresql.org/)
|
||||
[](https://redis.io/)
|
||||
[](https://www.docker.com/)
|
||||
|
||||
<a href="https://trendshift.io/repositories/21823" target="_blank"><img src="https://trendshift.io/api/badge/repositories/21823" alt="Wei-Shaw%2Fsub2api | Trendshift" width="250" height="55"/></a>
|
||||
|
||||
**AI API 网关平台 - 订阅配额分发管理**
|
||||
|
||||
[English](README.md) | 中文 | [日本語](README_JA.md)
|
||||
[English](README.md) | 中文
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ 重要提醒
|
||||
## 在线体验
|
||||
|
||||
使用本项目前,请务必仔细阅读以下内容:
|
||||
体验地址:**https://v2.pincc.ai/**
|
||||
|
||||
- **🚨 服务条款风险**:使用本项目可能违反 Anthropic 等上游服务商的服务条款。请在使用前仔细阅读相关服务商的用户协议,由此产生的一切风险由用户自行承担。
|
||||
- **⚖️ 合规使用**:请在符合您所在国家或地区法律法规的前提下使用本项目,严禁将其用于任何违法违规用途。
|
||||
- **📖 免责声明**:本项目仅供技术学习与研究使用,作者不对因使用本项目导致的账户封禁、服务中断、数据丢失或其他任何直接或间接损失承担责任。
|
||||
- **🚫 无商业授权**:本项目从未授权任何个人或组织基于本项目开展任何形式的商业化运营。任何以本项目名义或基于本项目从事的商业行为均与本项目及其开发者无关,由此产生的一切纠纷、损失和法律责任由行为主体自行承担。
|
||||
演示账号(共享演示环境;自建部署不会自动创建该账号):
|
||||
|
||||
## ❤️ 赞助商
|
||||
|
||||
> [想出现在这里?](mailto:support@sub2api.org)
|
||||
|
||||
<table>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://cctk.ai/register?aff=SUB2API"><img src="assets/partners/logos/cctk.jpg" alt="CCTK.AI" width="150"></a></td>
|
||||
<td>感谢 CCTK.AI 赞助了本项目!<a href="https://cctk.ai/register?aff=SUB2API">CCTK.AI</a> 是一个专注于稳定与性价比的 AI API 网关平台,提供 Claude、OpenAI、Gemini 等主流模型的高速中转服务,无缝兼容 Claude Code、Codex 等主流编程工具,以远低于官方的成本获得同等的模型能力。点击<a href="https://cctk.ai/register?aff=SUB2API">此链接</a>注册,即刻体验更快、更稳、更省的 AI API 接入。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.openmodel.ai?ref=sub2api"><img src="assets/partners/logos/openmodel.jpg" alt="openmodel" width="150"></a></td>
|
||||
<td>一个API,顶级模型随便用!<a href="https://www.openmodel.ai?ref=sub2api">OpenModel</a> 专注于生产级、高可用的 AI API 网关,让你的应用真正做到高速稳定:自动故障转移、智能选最优渠道、生产级 SLA 保障。远超单一供应商的 SLA,让稳定性成为您的核心竞争力。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://etok.ai"><img src="assets/partners/logos/etok.png" alt="ETok" width="150"></a></td>
|
||||
<td>感谢 ETok.ai 赞助了本项目!ETok.ai 致力于打造一站式 AI 编程工具服务平台。我们提供 Claude Code 专业套餐及技术社群服务,同时支持 Google Gemini 和 OpenAI Codex。通过精心设计的套餐方案和专业的技术社群,为开发者提供稳定的服务保障和持续的技术支持,让 AI 辅助编程真正成为开发者的生产力工具。点击<a href="https://etok.ai">这里</a>注册!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://apikey.fun/register?aff=SUB2API"><img src="assets/partners/logos/apikey-fun.png" alt="APIKEY.FUN" width="150"></a></td>
|
||||
<td>感谢 APIKEY.FUN 赞助了本项目!<a href="https://apikey.fun/register?aff=SUB2API">APIKEY.FUN</a> 是 sub2api 开源项目的核心贡献者之一,致力于提供开放、稳定、高性价比的 AI API 接入服务。平台支持 Claude、OpenAI、Gemini 等热门模型的 API 中转服务,价格低至官方原价的 7%。通过专属链接 <a href="https://apikey.fun/register?aff=SUB2API">APIKEY</a> 注册,可享受充值最高 95 折优惠。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://aigocode.com/invite/SUB2API"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></td>
|
||||
<td>感谢 AIGoCode 赞助了本项目!AIGoCode 是一站式集成 Claude Code、Codex 以及最新 Gemini 模型的综合平台,为您提供稳定、高效、高性价比的 AI 编程服务。平台提供灵活的订阅方案,零封号风险,免 VPN 直连,响应极速。AIGoCode 为 sub2api 用户准备了专属福利:通过<a href="https://aigocode.com/invite/SUB2API">此链接</a>注册,首次充值可额外获得 10% 赠送额度!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://shop.bmoplus.com/?utm_source=github"><img src="assets/partners/logos/bmoplus.jpg" alt="bmoplus" width="150"></a></td>
|
||||
<td>感谢 BmoPlus 赞助了本项目!BmoPlus 是一家专为AI订阅重度用户打造的可靠 AI 账号代充服务商,提供稳定的 ChatGPT Plus / ChatGPT Pro(全程质保) / Claude Pro / Super Grok / Gemini Pro 的官方代充&成品账号。 通过<a href="https://shop.bmoplus.com/?utm_source=github">BmoPlus AI成品号专卖/代充</a>注册下单的用户,可享GPT 官网订阅一折 的震撼价格!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://bestproxy.com/?keyword=a2e8iuol"><img src="assets/partners/logos/bestproxy.png" alt="bestproxy" width="150"></a></td>
|
||||
<td>感谢 Bestproxy 赞助了本项目!<a href="https://bestproxy.com/?keyword=a2e8iuol">Bestproxy</a> 是一家提供高纯度住宅IP,支持一号一IP独享,结合真实家庭网络与指纹隔离,可实现链路环境隔离,降低关联风控概率。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://pateway.ai/?ch=1tsfr51"><img src="assets/partners/logos/pateway.png" alt="pateway" width="150"></a></td>
|
||||
<td>感谢 PatewayAI 赞助了本项目!PatewayAI 是一家面向重度 AI 开发者、专注官方直连的高品质模型 API 中转服务商。提供 Claude 全系列与 Codex 系列模型,100% 官方源直供,不掺假不注水,欢迎检验。计费透明,Token 级账单可逐笔核验。
|
||||
同时支持企业级高并发,并为企业客户提供了专业的管理平台,企业客户可签订正式合同并开具发票,更多详情进入官网获取联系方式。
|
||||
现在通过 <a href="https://pateway.ai/?ch=1tsfr51">此链接</a> 注册即送 $3 试用额度,用户充值低至 6 折,邀请好友双向赠送,邀请奖励可达 $150。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://api.pptoken.cc/register?promo=SUB2API"><img src="assets/partners/logos/pptoken.png" alt="pptoken" width="150"></a></td>
|
||||
<td>感谢 PPToken.cc 赞助本项目! <a href="https://api.pptoken.cc/register?promo=SUB2API">PPToken.cc</a> 主打 GPT 系列模型 API 中转服务,支持 Codex、Claude Code、OpenAI 兼容客户端及 Gemini CLI 等工具接入。充值 1:1,1 元=1 美元额度;GPT 模型最低 0.16 倍倍率,综合成本约为官方价格的 0.22 折,最快首字 Token 约 1 秒,适合开发者低成本、高响应速度接入 GPT 模型能力。技术支持: 7×24 小时真人响应(不是机器人),群内@技术,10 分钟内有回复 。赞助商福利:前 200 名用户通过 <a href="https://api.pptoken.cc/register?promo=SUB2API">[专属注册链接]</a> 注册,输入优惠码 `SUB2API`,可领取 Codex / Claude Code 免费试用额度,无门槛、不绑卡。
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://veilx.io/#/hello/SJRBRVDV"><img src="assets/partners/logos/veilx.png" alt="veilx" width="150"></a></td>
|
||||
<td>感谢 Veilx 赞助本项目! <a href="https://veilx.io/#/hello/SJRBRVDV">Veilx</a> CDN 专为超大规模 API 请求场景打造,针对 AI 中转站业务与 AI API 调用链路进行了深度优化,轻松应对高并发、高频请求与大流量传输,为开发者与企业提供更快、更稳、更低延迟的加速体验。无论是 OpenAI、Claude、Gemini 等 AI 接口中转,还是聊天、绘图、Embedding、流式输出等复杂场景,Veilx 都能显著提升响应速度与连接稳定性,有效降低网络波动带来的超时与失败问题。同时,Veilx 提供中国三网优化回国极速线路,大幅提升中国大陆地区访问海外 AI 服务的速度与稳定性,特别适合全球 AI 中转平台、海外 AI SaaS、跨境业务与高并发 API 系统部署。专为 AI API 而生,让你的 AI 中转服务更快、更稳、更省心。<a href="https://veilx.io/#/hello/SJRBRVDV">购买地址</a>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://roxybrowser.com/invite/bgGKG7"><img src="assets/partners/logos/RoxyBrowser.png" alt="RoxyBrowser" width="150"></a></td>
|
||||
<td>感谢 RoxyBrowser 赞助本项目!<a href="https://roxybrowser.com/invite/bgGKG7">RoxyBrowser</a> 是 Sub2API 的理想搭档:内置原生 Roxy AI Agent 与高质量原生住宅 IP,支持通过简单命令实现批量自动化,显著提升多账号管理的安全性与效率!点击<a href="https://roxybrowser.com/invite/bgGKG7">此链接</a>注册,可领取免费住宅 IP 套餐与终身 9 折优惠。
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://sui-xiang.com/"><img src="assets/partners/logos/sui-xiang.jpg" alt="sui-xiang" width="150"></a></td>
|
||||
<td>感谢 随想AI网关 赞助本项目!<a href="https://sui-xiang.com/">随想AI网关</a> 是一家可靠高效的 API 中继服务提供商,提供 Claude、Codex、Gemini 等的中继服务。注重隐私的中转站·无数据倒卖·无模型掺水,隐私,透明,极速售后。新账户注册每日签到就送 0.5 元测试额度,充值额度 1:1,无需订阅,按量付费。多线路冗余、跨区域容灾、自动故障切换,长链路 SSE 不中断。99.9% 可用性,关键调用从不掉队。
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.proxy4free.com/?keyword=4yjqecpc"><img src="assets/partners/logos/proxy4free.png" alt="proxy4free" width="150"></a></td>
|
||||
<td>感谢 Proxy4Free 赞助本项目!Proxy4Free 是面向开发者和 AI 应用的数据代理服务商,提供住宅代理、静态住宅代理、ISP 代理及数据中心代理等多种代理解决方案,适用于 Web Scraping、Browser Automation、AI Agent 等场景。支持全球 IP 资源、稳定连接与灵活切换,帮助开发者提升数据采集成功率,降低 IP 封禁风险。通过<a href="https://www.proxy4free.com/?keyword=4yjqecpc">此链接注册</a>即可开始体验,轻松构建更稳定、高效的自动化工作流。
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="http://www.fastaitoken.com/register"><img src="assets/partners/logos/fastaitoken.jpg" alt="fastaitoken" width="150"></a></td>
|
||||
<td>🎉 感谢 FastAIToken 对本项目的赞助! <a href="http://www.fastaitoken.com/register">FastAIToken</a> 是面向开发者的 AI API 聚合平台,支持 OpenAI、Claude、Gemini 等主流大模型,充值 1:1,1 元 = 1 美元 API 额度,让开发者以更低成本、更便捷地使用全球领先的大模型服务。<br>
|
||||
|
||||
🚀 平台提供多种渠道自由选择:超级低价的0.02x OpenAI 福利分组(限时)、低至 0.25x OpenAI 分组、0.7x Claude 95%固定缓存、1.2x Claude Max 渠道;同时提供公开状态页,实时展示各分组的可用率、延迟及运行状态,服务透明可靠,并提供 7×24 小时真人技术支持(非机器人),快速响应开发者需求。
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="http://aimzoon.com"><img src="assets/partners/logos/aimzoon.jpg" alt="aimzoon" width="150"></a></td>
|
||||
<td>感谢 Aimzoon 对本项目的赞助! <a href="http://aimzoon.com">Aimzoon</a> 提供稳定、高性价比的 AI API 接入服务,支持开发者将常用 AI 服务快速接入 Codex、Claude Code、Gemini CLI 等编程工具。无需复杂配置,更快接入,更稳调用,更省成本。codex倍率优惠,特价倍率等促销不断,注册即送免费体验额度,让 AI 编程真正进入日常工作流。<a href="http://aimzoon.com">点击这里</a>注册体验!
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://console.claudeapi.com/agent/register/drTKjyn6wGLK061Z"><img src="assets/partners/logos/claudeapi.jpg" alt="claudeapi" width="150"></a></td>
|
||||
<td>感谢 Claude API 对本项目的赞助! <a href="https://console.claudeapi.com/agent/register/drTKjyn6wGLK061Z">Claude API</a> 是专注 Claude 模型的官方渠道 API 服务商,基于 Anthropic 官方 Key 与 AWS Bedrock 官方渠道,提供稳定的 Claude Code 与 Agent 应用接入体验,支持 Claude 全系列模型,保留 Tool Use、长上下文等官方能力。服务非逆向、非降智,适合 Claude Code 深度用户、Agent 工程师与企业技术团队使用。通过<a href="https://console.claudeapi.com/agent/register/drTKjyn6wGLK061Z">[专属链接]</a>注册后联系客服,可领取免费测试额度,并支持开票和团队对接。
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://code0.ai/agent/register/LgpIgl9JHtVG53V1?utm_source=zcf&utm_medium=partner&utm_campaign=zcf_2026&utm_content=default"><img src="assets/partners/logos/code0.jpg" alt="code0" width="150"></a></td>
|
||||
<td>感谢 code0.ai 对本项目的赞助! <a href="https://code0.ai/agent/register/LgpIgl9JHtVG53V1?utm_source=zcf&utm_medium=partner&utm_campaign=zcf_2026&utm_content=default">code0.ai</a> 是面向开发者与技术团队的 AI 编程工作台,聚合 Claude Code、Codex 等主流 Agent 编程能力,支持代码生成、项目理解、调试修复、代码审查与文档生成等常见研发场景。适合独立开发者、Agent 工程师、开源项目维护者和企业研发团队使用,支持开票和团队对接。通过<a href="https://code0.ai/agent/register/LgpIgl9JHtVG53V1?utm_source=zcf&utm_medium=partner&utm_campaign=zcf_2026&utm_content=default">[专属链接]</a>注册后联系客服,可领取免费测试额度,体验更高效的 AI 编程工作流。
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://nagora.ai/"><img src="assets/partners/logos/nagora.png" alt="Nagora" width="150"></a></td>
|
||||
<td><a href="https://nagora.ai/">Nagora</a> 是专为开发者和团队打造的多模型 AI API 网关。通过一个账户和一枚 API Key,即可统一调用 26+ 款主流文本与图像模型,兼容 OpenAI、Anthropic 与 Gemini 协议,并可无缝接入 Claude Code、Codex、Gemini CLI 等开发工具。平台提供智能路由、自动故障转移、透明计费与统一账单,同时支持预算、限速、并发控制,让个人开发、团队协作和生产环境中的 AI 调用更稳定、更可控。无需改造现有应用,只需替换 Base URL 与 API Key,最快 1 分钟即可完成接入。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.novada.com/?sub2api/"><img src="assets/partners/logos/novada.png" alt="Novada" width="150"></a></td>
|
||||
<td>感谢 <a href="https://www.novada.com/?sub2api/">Novada</a> 赞助本项目!Novada 为构建 AI 应用与自动化工作流的开发者提供住宅代理、ISP 代理、数据中心代理与移动代理,以及 Web Unlocker 和 Scraper API。凭借全球 IP 覆盖、灵活的轮换与粘性会话以及精准的地理定位,Novada 帮助团队在 AI Agent 工作流、跨区域测试、网络调研与浏览器自动化等场景中稳定获取网络数据。立即体验 Novada,构建更稳定、更可扩展的 AI 工作流。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://s.qiniu.com/u6rQrq"><img src="assets/partners/logos/qiniu.jpg" alt="七牛云AI" width="150"></a></td>
|
||||
<td>感谢 七牛云AI 赞助本项目!七牛云AI 是七牛云(02567.HK)旗下企业级大模型 MaaS 平台,一站式调用全球 150+ 主流模型,兼容全球主流模型厂商协议,覆盖文本、图像、音频、视频、文件处理等全模态处理能力,服务超过169万企业及开发者用户。七牛云 AI 为 Sub2API 的用户提供了专属福利:通过<a href="https://s.qiniu.com/u6rQrq">此链接</a>注册,企业用户免费领1200万Token,开发者免费领300万Token。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://api.fenno.ai/s/dC4k"><img src="assets/partners/logos/fennoai.jpg" alt="FennoAI" width="150"></a></td>
|
||||
<td>感谢 FennoAI 赞助本项目!FennoAI 是一家面向企业研发团队和开发者的高稳定、高性能 API 中转服务商,兼容 OpenAI 与 Anthropic 协议,可无缝接入 Codex、Claude Code、OpenCode 等主流 AI 编程工具。平台具备企业级稳定性,可支撑千亿 Token/日的调用规模,并支持境内外主体公对公结算及开票,满足企业级研发与采购需求。作为 Sub2API 用户专属福利,通过<a href="https://api.fenno.ai/s/dC4k">专属链接</a>购买订阅,仅需 1.99 美元即可获得价值 50 美元的 Coding Plan 额度。同时支持邀请奖励,邀请好友购买最高可获得 20% 返佣,邀请越多,奖励越高。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://lanox.ai/?c=6"><img src="assets/partners/logos/lanox.jpg" alt="LanoX AI" width="150"></a></td>
|
||||
<td>感谢 LanoX AI 对本项目的赞助!<a href="https://lanox.ai/?c=6">LanoX AI</a> 为开发者、团队与企业提供稳定、高性价比的全球模型接入服务。 🎁 新用户福利 — 免费领取 百万 Token ,更有500+ 免费模型 — 低成本测试、验证、部署更轻松 🧠 全球主流模型 — GPT · Claude · Gemini · Qwen · Grok... 🎬 多模态创作 — Seedance 2.0 · GPT Image · Gemini Nano Banana 🛡️ 企业级稳定服务 — 高可用💎原生能力输出💎不降智💎不混模💎调用与计费透明💎 💰 更低调用成本 — 顶级模型低至官方价 1 折起,文档清晰、接入简单、支持开票与企业批量调用 🏢 企业优选 — 适用于 AI 产品、Agent、内容平台、研发团队批量调用</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.rapidproxy.io/?ref=sub2api"><img src="assets/partners/logos/rapidproxy.jpg" alt="RapidProxy" width="150"></a></td>
|
||||
<td><a href="https://www.rapidproxy.io/?ref=sub2api">RapidProxy</a> 是面向开发者的数据采集代理解决方案,提供稳定可靠的住宅代理服务。通过 9000 万+全球住宅 IP和 200+国家覆盖、智能轮换机制和精准地区定位能力,帮助爬虫、AI 数据训练、SEO 监控、电商数据分析等项目突破访问限制,提高数据采集效率。支持 Playwright、Selenium、Puppeteer 等主流自动化框架,价格低至 $0.65/GB,<a href="https://www.rapidproxy.io/?ref=sub2api">立即免费测试吧</a>。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://hao.ai"><img src="assets/partners/logos/haoai.png" alt="hao.ai" width="150"></a></td>
|
||||
<td><a href="https://hao.ai">hao.ai</a> 是面向开发者与团队的高速、稳定大模型统一 API 网关。通过一个 API Key 和统一接口,即可接入 GPT、Claude、xAI Grok 等主流模型,兼容 OpenAI、Anthropic 等常用协议与 SDK。平台提供模型路由、故障回退、团队管理及完整调用日志,模型价格低至官方参考价的 1.5 折,帮助用户更简单、更稳定、更低成本地构建 AI 应用。</td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
| 邮箱 | 密码 |
|
||||
|------|------|
|
||||
| admin@sub2api.com | admin123 |
|
||||
|
||||
## 项目概述
|
||||
|
||||
Sub2API 是一个 AI API 网关平台,用于分发和管理 AI 产品订阅的 API 配额。用户通过平台生成的 API Key 调用上游 AI 服务,平台负责鉴权、计费、负载均衡和请求转发。
|
||||
Sub2API 是一个 AI API 网关平台,用于分发和管理 AI 产品订阅(如 Claude Code $200/月)的 API 配额。用户通过平台生成的 API Key 调用上游 AI 服务,平台负责鉴权、计费、负载均衡和请求转发。
|
||||
|
||||
## 核心功能
|
||||
|
||||
@@ -181,18 +38,7 @@ Sub2API 是一个 AI API 网关平台,用于分发和管理 AI 产品订阅的
|
||||
- **智能调度** - 智能账号选择,支持粘性会话
|
||||
- **并发控制** - 用户级和账号级并发限制
|
||||
- **速率限制** - 可配置的请求和 Token 速率限制
|
||||
- **内置支付系统** - 支持 EasyPay 易支付、支付宝官方、微信官方、Stripe,用户自助充值,无需独立部署支付服务([配置指南](docs/PAYMENT_CN.md))
|
||||
- **管理后台** - Web 界面进行监控和管理
|
||||
- **外部系统集成** - 支持通过 iframe 嵌入外部系统(如工单等),扩展管理后台功能
|
||||
|
||||
## 生态项目
|
||||
|
||||
围绕 Sub2API 的社区扩展与集成项目:
|
||||
|
||||
| 项目 | 说明 | 功能 |
|
||||
|------|------|------|
|
||||
| ~~[Sub2ApiPay](https://github.com/touwaeriol/sub2apipay)~~ | ~~自助支付系统~~ | **已内置** — 支付功能已集成到 Sub2API 中,无需独立部署。详见 [支付配置指南](docs/PAYMENT_CN.md) |
|
||||
| [sub2api-mobile](https://github.com/ckken/sub2api-mobile) | 移动端管理控制台 | 跨平台应用(iOS/Android/Web),支持用户管理、账号管理、监控看板、多后端切换;基于 Expo + React Native 构建 |
|
||||
|
||||
## 技术栈
|
||||
|
||||
@@ -205,18 +51,17 @@ Sub2API 是一个 AI API 网关平台,用于分发和管理 AI 产品订阅的
|
||||
|
||||
---
|
||||
|
||||
## Nginx 反向代理注意事项
|
||||
## 文档
|
||||
|
||||
通过 Nginx 反向代理 Sub2API(或 CRS 服务)并搭配 Codex CLI 使用时,需要在 Nginx 配置的 `http` 块中添加:
|
||||
|
||||
```nginx
|
||||
underscores_in_headers on;
|
||||
```
|
||||
|
||||
Nginx 默认会丢弃名称中含下划线的请求头(如 `session_id`),这会导致多账号环境下的粘性会话功能失效。
|
||||
- 依赖安全:`docs/dependency-security.md`
|
||||
|
||||
---
|
||||
|
||||
## OpenAI Responses 兼容注意事项
|
||||
|
||||
- 当请求包含 `function_call_output` 时,需要携带 `previous_response_id`,或在 `input` 中包含带 `call_id` 的 `tool_call`/`function_call`,或带非空 `id` 且与 `function_call_output.call_id` 匹配的 `item_reference`。
|
||||
- 若依赖上游历史记录,网关会强制 `store=true` 并需要复用 `previous_response_id`,以避免出现 “No tool call found for function call output” 错误。
|
||||
|
||||
## 部署方式
|
||||
|
||||
### 方式一:脚本安装(推荐)
|
||||
@@ -309,10 +154,10 @@ mkdir -p sub2api-deploy && cd sub2api-deploy
|
||||
curl -sSL https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/deploy/docker-deploy.sh | bash
|
||||
|
||||
# 启动服务
|
||||
docker compose up -d
|
||||
docker-compose up -d
|
||||
|
||||
# 查看日志
|
||||
docker compose logs -f sub2api
|
||||
docker-compose logs -f sub2api
|
||||
```
|
||||
|
||||
**脚本功能:**
|
||||
@@ -333,7 +178,6 @@ cd sub2api/deploy
|
||||
|
||||
# 2. 复制环境配置文件
|
||||
cp .env.example .env
|
||||
chmod 600 .env
|
||||
|
||||
# 3. 编辑配置(生成安全密码)
|
||||
nano .env
|
||||
@@ -377,16 +221,16 @@ mkdir -p data postgres_data redis_data
|
||||
|
||||
# 5. 启动所有服务
|
||||
# 选项 A:本地目录版(推荐 - 易于迁移)
|
||||
docker compose -f docker-compose.local.yml up -d
|
||||
docker-compose -f docker-compose.local.yml up -d
|
||||
|
||||
# 选项 B:命名卷版(简单设置)
|
||||
docker compose up -d
|
||||
docker-compose up -d
|
||||
|
||||
# 6. 查看状态
|
||||
docker compose -f docker-compose.local.yml ps
|
||||
docker-compose -f docker-compose.local.yml ps
|
||||
|
||||
# 7. 查看日志
|
||||
docker compose -f docker-compose.local.yml logs -f sub2api
|
||||
docker-compose -f docker-compose.local.yml logs -f sub2api
|
||||
```
|
||||
|
||||
#### 部署版本对比
|
||||
@@ -416,15 +260,15 @@ docker compose -f docker-compose.local.yml logs -f sub2api
|
||||
|
||||
如果管理员密码是自动生成的,在日志中查找:
|
||||
```bash
|
||||
docker compose -f docker-compose.local.yml logs sub2api | grep "admin password"
|
||||
docker-compose -f docker-compose.local.yml logs sub2api | grep "admin password"
|
||||
```
|
||||
|
||||
#### 升级
|
||||
|
||||
```bash
|
||||
# 拉取最新镜像并重建容器
|
||||
docker compose -f docker-compose.local.yml pull
|
||||
docker compose -f docker-compose.local.yml up -d
|
||||
docker-compose -f docker-compose.local.yml pull
|
||||
docker-compose -f docker-compose.local.yml up -d
|
||||
```
|
||||
|
||||
#### 轻松迁移(本地目录版)
|
||||
@@ -433,7 +277,7 @@ docker compose -f docker-compose.local.yml up -d
|
||||
|
||||
```bash
|
||||
# 源服务器
|
||||
docker compose -f docker-compose.local.yml down
|
||||
docker-compose -f docker-compose.local.yml down
|
||||
cd ..
|
||||
tar czf sub2api-complete.tar.gz sub2api-deploy/
|
||||
|
||||
@@ -443,45 +287,29 @@ scp sub2api-complete.tar.gz user@new-server:/path/
|
||||
# 新服务器
|
||||
tar xzf sub2api-complete.tar.gz
|
||||
cd sub2api-deploy/
|
||||
docker compose -f docker-compose.local.yml up -d
|
||||
docker-compose -f docker-compose.local.yml up -d
|
||||
```
|
||||
|
||||
#### 常用命令
|
||||
|
||||
```bash
|
||||
# 停止所有服务
|
||||
docker compose -f docker-compose.local.yml down
|
||||
docker-compose -f docker-compose.local.yml down
|
||||
|
||||
# 重启
|
||||
docker compose -f docker-compose.local.yml restart
|
||||
docker-compose -f docker-compose.local.yml restart
|
||||
|
||||
# 查看所有日志
|
||||
docker compose -f docker-compose.local.yml logs -f
|
||||
docker-compose -f docker-compose.local.yml logs -f
|
||||
|
||||
# 删除所有数据(谨慎!)
|
||||
docker compose -f docker-compose.local.yml down
|
||||
docker-compose -f docker-compose.local.yml down
|
||||
rm -rf data/ postgres_data/ redis_data/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 方式三:Apple container(macOS)
|
||||
|
||||
Apple 芯片 Mac 在 macOS 26 上可使用 Apple `container` 1.1.0 或更高版本运行完整的 Sub2API、PostgreSQL 和 Redis:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/Wei-Shaw/sub2api.git
|
||||
cd sub2api/deploy
|
||||
./apple-container.sh init
|
||||
./apple-container.sh up
|
||||
./apple-container.sh status
|
||||
```
|
||||
|
||||
该方式面向本地开发和人工运维,不提供持续重启监管;生产部署仍推荐 Docker Compose。生命周期命令、持久化、升级和运行时限制见 [deploy/APPLE_CONTAINER.md](deploy/APPLE_CONTAINER.md)。
|
||||
|
||||
---
|
||||
|
||||
### 方式四:源码编译
|
||||
### 方式三:源码编译
|
||||
|
||||
从源码编译安装,适合开发或定制需求。
|
||||
|
||||
@@ -510,8 +338,7 @@ pnpm run build
|
||||
|
||||
# 4. 编译后端(嵌入前端)
|
||||
cd ../backend
|
||||
VERSION="$(./scripts/resolve-version.sh)"
|
||||
go build -tags embed -ldflags="-X main.Version=${VERSION}" -o sub2api ./cmd/server
|
||||
go build -tags embed -o sub2api ./cmd/server
|
||||
|
||||
# 5. 创建配置文件
|
||||
cp ../deploy/config.example.yaml ./config.yaml
|
||||
@@ -590,18 +417,9 @@ gateway:
|
||||
- `security.response_headers.enabled` 可启用可配置响应头过滤(关闭时使用默认白名单)
|
||||
- `security.csp` 配置 Content-Security-Policy
|
||||
- `billing.circuit_breaker` 计费异常时 fail-closed
|
||||
- `security.trust_forwarded_ip_for_api_key_acl` 控制旧版原始转发头接管(为升级兼容默认开启);关闭后严格使用 `server.trusted_proxies`,其中只应填写直接连接 Sub2API 的精确代理 CIDR
|
||||
- `security.forwarded_client_ip_headers` 最多配置 16 个第三方 CDN 客户端 IP 请求头;仅在旧版接管开启时按顺序优先于内置请求头解析
|
||||
- `server.trusted_proxies` 启用可信代理解析 X-Forwarded-For
|
||||
- `turnstile.required` 在 release 模式强制启用 Turnstile
|
||||
|
||||
自定义客户端 IP 请求头可通过 YAML 配置,也可使用逗号分隔的环境变量:
|
||||
|
||||
```bash
|
||||
SECURITY_FORWARDED_CLIENT_IP_HEADERS=True-Client-IP,X-CDN-Client-IP
|
||||
```
|
||||
|
||||
请求头名称会经过合法性校验、规范化和大小写无关去重。管理员可在安全设置中动态更新列表,无需重启;新安装会持久化 YAML/环境变量默认值,旧安装缺少数据库字段时会自动回填。关闭旧版接管后,自定义头和内置原始转发头均被忽略,只使用 `server.trusted_proxies`。开启接管时必须限制源站仅允许 CDN/代理访问,并确保边缘代理覆盖所有受信客户端 IP 请求头。完整迁移规则和信任边界见 [`deploy/EDGE_SECURITY.md`](deploy/EDGE_SECURITY.md)。
|
||||
|
||||
**网关防御纵深建议(重点)**
|
||||
|
||||
- `gateway.upstream_response_read_max_bytes`:限制非流式上游响应读取大小(默认 `8MB`),用于防止异常响应导致内存放大。
|
||||
@@ -612,20 +430,20 @@ SECURITY_FORWARDED_CLIENT_IP_HEADERS=True-Client-IP,X-CDN-Client-IP
|
||||
|
||||
**⚠️ 安全警告:HTTP URL 配置**
|
||||
|
||||
当 `security.url_allowlist.enabled=false` 时,系统仅执行最小 URL 校验,且**默认允许 HTTP URL**(开发友好模式,Docker Compose 部署的默认值一致)。生产环境建议显式收紧为仅允许 HTTPS:
|
||||
当 `security.url_allowlist.enabled=false` 时,系统默认执行最小 URL 校验,**拒绝 HTTP URL**,仅允许 HTTPS。要允许 HTTP URL(例如用于开发或内网测试),必须显式设置:
|
||||
|
||||
```yaml
|
||||
security:
|
||||
url_allowlist:
|
||||
enabled: false # 禁用白名单检查
|
||||
allow_insecure_http: false # 仅允许 HTTPS(生产环境推荐)
|
||||
allow_insecure_http: true # 允许 HTTP URL(⚠️ 不安全)
|
||||
```
|
||||
|
||||
**或通过环境变量:**
|
||||
|
||||
```bash
|
||||
SECURITY_URL_ALLOWLIST_ENABLED=false
|
||||
SECURITY_URL_ALLOWLIST_ALLOW_INSECURE_HTTP=false
|
||||
SECURITY_URL_ALLOWLIST_ALLOW_INSECURE_HTTP=true
|
||||
```
|
||||
|
||||
**允许 HTTP 的风险:**
|
||||
@@ -639,7 +457,7 @@ SECURITY_URL_ALLOWLIST_ALLOW_INSECURE_HTTP=false
|
||||
- ✅ 获取 HTTPS 前测试账号连通性
|
||||
- ❌ 生产环境(仅使用 HTTPS)
|
||||
|
||||
**设置 `allow_insecure_http: false` 后,HTTP URL 会返回如下错误:**
|
||||
**未设置此项时的错误示例:**
|
||||
```
|
||||
Invalid base URL: invalid url scheme: http
|
||||
```
|
||||
@@ -650,25 +468,6 @@ Invalid base URL: invalid url scheme: http
|
||||
- 强制仅允许 TLS 出站
|
||||
- 在反向代理层移除敏感响应头
|
||||
|
||||
#### ⚠️ 重要:创建管理员账号
|
||||
|
||||
初始管理员账号**只能通过 setup 向导创建**(首次启动时访问 `http://<host>:8080`)。`config.yaml` 中的 `default.admin_email` / `default.admin_password` 字段**不会被用来创建管理员**——它们只是出于历史原因保留在模板里。
|
||||
|
||||
由于上面第 5 步预先创建了 `config.yaml`,**setup 向导在首次启动时会被跳过**:服务检测到 config 已存在,会直接进入正常模式,此时 `users` 表为空,首次登录会返回 `invalid email or password`。
|
||||
|
||||
**创建管理员的两种方式:**
|
||||
|
||||
1. **推荐——让向导自动生成 `config.yaml`:** 跳过上面的第 5 步(不要执行 `cp`)。直接运行 `./sub2api`,访问 `http://localhost:8080`,向导会引导你完成数据库、Redis 和管理员账号配置,并自动写出 `config.yaml`。
|
||||
|
||||
2. **如果你已经创建了 `config.yaml`:** 首次启动前先把它临时移走以触发向导,完成后再恢复:
|
||||
```bash
|
||||
mv config.yaml config.yaml.bak
|
||||
./sub2api # 向导在 http://localhost:8080 启动,并生成新的 config.yaml
|
||||
# 向导完成后 Ctrl+C 停服,再恢复你的配置:
|
||||
mv config.yaml.bak config.yaml
|
||||
./sub2api # 重启进入正常模式,用刚创建的管理员登录
|
||||
```
|
||||
|
||||
```bash
|
||||
# 6. 运行应用
|
||||
./sub2api
|
||||
@@ -755,6 +554,10 @@ Antigravity 账户支持可选的**混合调度**功能。开启后,通用端
|
||||
|
||||
> **⚠️ 注意**:Anthropic Claude 和 Antigravity Claude **不能在同一上下文中混合使用**,请通过分组功能做好隔离。
|
||||
|
||||
|
||||
### 已知问题
|
||||
在 Claude Code 中,无法自动退出Plan Mode。(正常使用原生Claude Api时,Plan 完成后,Claude Code会弹出弹出选项让用户同意或拒绝Plan。)
|
||||
解决办法:shift + Tab,手动退出Plan mode,然后输入内容 告诉 Claude Code 同意或拒绝 Plan
|
||||
---
|
||||
|
||||
## 项目结构
|
||||
@@ -785,6 +588,16 @@ sub2api/
|
||||
└── install.sh # 一键安装脚本
|
||||
```
|
||||
|
||||
## 免责声明
|
||||
|
||||
> **使用本项目前请仔细阅读:**
|
||||
>
|
||||
> :rotating_light: **服务条款风险**: 使用本项目可能违反 Anthropic 的服务条款。请在使用前仔细阅读 Anthropic 的用户协议,使用本项目的一切风险由用户自行承担。
|
||||
>
|
||||
> :book: **免责声明**: 本项目仅供技术学习和研究使用,作者不对因使用本项目导致的账户封禁、服务中断或其他损失承担任何责任。
|
||||
|
||||
---
|
||||
|
||||
## Star History
|
||||
|
||||
<a href="https://star-history.com/#Wei-Shaw/sub2api&Date">
|
||||
@@ -799,9 +612,7 @@ sub2api/
|
||||
|
||||
## 许可证
|
||||
|
||||
本项目基于 [GNU 宽通用公共许可证 v3.0](LICENSE)(或更高版本)授权。
|
||||
|
||||
Copyright (c) 2026 Wesley Liddick
|
||||
MIT License
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -1,747 +0,0 @@
|
||||
<div align="center">
|
||||
|
||||
<img src="assets/logo.svg" alt="Sub2API Logo" width="128" />
|
||||
|
||||
# Sub2API
|
||||
|
||||
[](https://golang.org/)
|
||||
[](https://vuejs.org/)
|
||||
[](https://www.postgresql.org/)
|
||||
[](https://redis.io/)
|
||||
[](https://www.docker.com/)
|
||||
|
||||
<a href="https://trendshift.io/repositories/21823" target="_blank"><img src="https://trendshift.io/api/badge/repositories/21823" alt="Wei-Shaw%2Fsub2api | Trendshift" width="250" height="55"/></a>
|
||||
|
||||
**サブスクリプションクォータ配分のための AI API ゲートウェイプラットフォーム**
|
||||
|
||||
[English](README.md) | [中文](README_CN.md) | 日本語
|
||||
|
||||
</div>
|
||||
|
||||
## ⚠️ 重要なお知らせ
|
||||
|
||||
本プロジェクトをご利用になる前に、以下の内容を必ずよくお読みください:
|
||||
|
||||
- **🚨 利用規約のリスク**:本プロジェクトの使用は、Anthropic をはじめとする上流プロバイダーの利用規約に違反する可能性があります。ご利用前に各プロバイダーのユーザー規約を必ずご確認ください。使用により生じるすべてのリスクはユーザーご自身が負うものとします。
|
||||
- **⚖️ 法令遵守**:お住まいの国または地域の法令を遵守した上で本プロジェクトをご利用ください。いかなる違法な目的での使用も固く禁じます。
|
||||
- **📖 免責事項**:本プロジェクトは技術的な学習および研究の目的でのみ提供されます。本プロジェクトの使用により生じたアカウントの停止、サービスの中断、データの損失、その他一切の直接的または間接的な損害について、作者は一切の責任を負いません。
|
||||
- **🚫 商用利用の非許諾**:本プロジェクトの開発者は、いかなる個人または組織に対しても、本プロジェクトを利用したいかなる形態の商業運営も一切許諾していません。本プロジェクトの名義で、または本プロジェクトに基づいて行われる商業行為はすべて本プロジェクトおよびその開発者とは無関係であり、それにより生じる一切の紛争、損失、法的責任は行為者自身が負うものとします。
|
||||
|
||||
## ❤️ スポンサー
|
||||
|
||||
> [こちらに掲載しませんか?](mailto:support@sub2api.org)
|
||||
|
||||
<table>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://cctk.ai/register?aff=SUB2API"><img src="assets/partners/logos/cctk.jpg" alt="CCTK.AI" width="150"></a></td>
|
||||
<td>CCTK.AI のご支援に感謝します!<a href="https://cctk.ai/register?aff=SUB2API">CCTK.AI</a> は安定性とコストパフォーマンスにこだわった AI API ゲートウェイで、Claude、OpenAI、Gemini など主要モデルの高速中継サービスを提供しています。Claude Code や Codex などの主要なコーディングツールにシームレスに対応し、公式価格を大きく下回るコストで同等のモデル能力を利用できます。<a href="https://cctk.ai/register?aff=SUB2API">こちらのリンク</a>から登録して、より速く、より安定した、よりお得な AI API 接続をお試しください。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.openmodel.ai?ref=sub2api"><img src="assets/partners/logos/openmodel.jpg" alt="openmodel" width="150"></a></td>
|
||||
<td>1つの API で、トップモデルを使い放題!<a href="https://www.openmodel.ai?ref=sub2api">OpenModel</a> は本番環境グレードで高可用性の AI API ゲートウェイに特化し、アプリを真に高速・安定させます:自動フェイルオーバー、最適なチャネルへのスマートルーティング、本番グレードの SLA 保証。単一プロバイダーをはるかに上回る SLA で、安定性をあなたの核心的な競争力にします。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://etok.ai"><img src="assets/partners/logos/etok.png" alt="ETok" width="150"></a></td>
|
||||
<td>ETok.ai のご支援に感謝します!ETok.ai はワンストップ AI プログラミングツールサービスプラットフォームの構築に取り組んでいます。Claude Code の専用プランと技術コミュニティサービスを提供し、Google Gemini や OpenAI Codex もサポートしています。丁寧に設計されたプランと専門的な技術コミュニティを通じて、開発者に安定したサービス保証と継続的な技術サポートを提供し、AI アシスト プログラミングを真の生産性向上ツールにします。<a href="https://etok.ai">こちら</a>から登録!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://apikey.fun/register?aff=SUB2API"><img src="assets/partners/logos/apikey-fun.png" alt="APIKEY.FUN" width="150"></a></td>
|
||||
<td>APIKEY.FUN のご支援に感謝します!<a href="https://apikey.fun/register?aff=SUB2API">APIKEY.FUN</a> は sub2api オープンソースプロジェクトのコアコントリビューターの一つであり、オープンで安定した、コストパフォーマンスに優れた AI API アクセスサービスの提供に取り組んでいます。プラットフォームは Claude、OpenAI、Gemini など人気モデルの API 中継サービスをサポートし、価格は公式料金のわずか 7% から。専用リンク <a href="https://apikey.fun/register?aff=SUB2API">APIKEY</a> から登録すると、すべてのチャージで永久 5% 割引をご利用いただけます。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://aigocode.com/invite/SUB2API"><img src="assets/partners/logos/aigocode.png" alt="AIGoCode" width="150"></a></td>
|
||||
<td>AIGoCode のご支援に感謝します!AIGoCode は Claude Code、Codex、最新の Gemini モデルを統合したオールインワンプラットフォームで、安定的かつ効率的でコストパフォーマンスに優れた AI コーディングサービスを提供します。柔軟なサブスクリプションプラン、アカウント停止リスクゼロ、VPN 不要の直接アクセス、超高速レスポンスが特長です。AIGoCode は sub2api ユーザー向けに特別特典を用意しています:<a href="https://aigocode.com/invite/SUB2API">こちらのリンク</a>から登録すると、初回チャージ時に 10% のボーナスクレジットを追加プレゼント!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://shop.bmoplus.com/?utm_source=github"><img src="assets/partners/logos/bmoplus.jpg" alt="bmoplus" width="150"></a></td>
|
||||
<td>本プロジェクトにご支援いただいた BmoPlus に感謝いたします!BmoPlusは、AIサブスクリプションのヘビーユーザー向けに特化した信頼性の高いAIアカウントサービスプロバイダーであり、安定した ChatGPT Plus / ChatGPT Pro (完全保証) / Claude Pro / Super Grok / Gemini Pro の公式代行チャージおよび即納アカウントを提供しています。こちらの<a href="https://shop.bmoplus.com/?utm_source=github">BmoPlus AIアカウント専門店/代行チャージ</a>経由でご登録・ご注文いただいたユーザー様は、GPTを 公式サイト価格の約1割(90% OFF) という驚異的な価格でご利用いただけます!</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://bestproxy.com/?keyword=a2e8iuol"><img src="assets/partners/logos/bestproxy.png" alt="bestproxy" width="150"></a></td>
|
||||
<td>Bestproxy のご支援に感謝します!<a href="https://bestproxy.com/?keyword=a2e8iuol">Bestproxy</a> は高純度の住宅IPを提供し、1アカウント1IP専有をサポートしています。実際の家庭ネットワークとフィンガープリント分離を組み合わせることで、リンク環境の分離を実現し、関連付けによるリスク管理の確率を低減します。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://pateway.ai/?ch=1tsfr51"><img src="assets/partners/logos/pateway.png" alt="pateway" width="150"></a></td>
|
||||
<td>PatewayAI のご支援に感謝します!PatewayAI は、ヘビーAI開発者向けに公式直結を重視した高品質モデルAPIリレーサービスプロバイダーです。Claude 全シリーズおよび Codex シリーズモデルを提供し、100%公式ソースから直接供給 — 偽りなし、水増しなし、検証歓迎。課金は完全透明で、トークン単位の請求書を1件ずつ監査可能です。
|
||||
エンタープライズ級の高同時接続にも対応し、法人顧客向けに専用管理プラットフォームを提供しています。法人顧客は正式な契約を締結し、請求書の発行が可能です。詳細は公式サイトでお問い合わせください。
|
||||
<a href="https://pateway.ai/?ch=1tsfr51">こちらのリンク</a>から登録すると、$3 のトライアルクレジットがもらえます。チャージは最大40%オフ、友達紹介で双方にボーナス付与 — 紹介報酬は最大 $150。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://api.pptoken.cc/register?promo=SUB2API"><img src="assets/partners/logos/pptoken.png" alt="pptoken" width="150"></a></td>
|
||||
<td>PPToken.cc のご支援に感謝します!<a href="https://api.pptoken.cc/register?promo=SUB2API">PPToken.cc</a> は GPT シリーズモデルの API 中継サービスを専門としており、Codex、Claude Code、OpenAI 互換クライアント、Gemini CLI などのツール接続をサポートしています。チャージは 1:1(1元=1ドル分のクレジット)、GPT モデルは最低 0.16 倍のレート倍率で、総合コストは公式価格の約 2.2% 、最速ファーストトークンは約1秒 — 開発者が低コスト・高速レスポンスで GPT モデル機能にアクセスするのに最適です。テクニカルサポート:24時間365日リアルな人間が対応(ボットではありません)、グループ内で @技術 すれば 10 分以内に返信。スポンサー特典:先着 200 名のユーザーが<a href="https://api.pptoken.cc/register?promo=SUB2API">専用登録リンク</a>から登録し、プロモコード `SUB2API` を入力すると、Codex / Claude Code の無料トライアルクレジットを獲得できます — 最低利用額なし、カード登録不要。
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://veilx.io/#/hello/SJRBRVDV"><img src="assets/partners/logos/veilx.png" alt="veilx" width="150"></a></td>
|
||||
<td>Veilx のご支援に感謝します!<a href="https://veilx.io/#/hello/SJRBRVDV">Veilx</a> CDN は超大規模 API リクエストシナリオ向けに設計されており、AI 中継サービスと AI API 呼び出しチェーンに対して深く最適化されています。高並列・高頻度リクエスト・大容量トラフィックに容易に対応し、開発者と企業により高速で安定した、低レイテンシの加速体験を提供します。OpenAI、Claude、Gemini などの AI インターフェース中継はもちろん、チャット、画像生成、Embedding、ストリーミング出力などの複雑なシナリオでも、Veilx は応答速度と接続安定性を大幅に向上させ、ネットワーク変動によるタイムアウトや失敗を効果的に削減します。さらに、Veilx は中国三大ネットワーク最適化の高速回線を提供しており、中国本土から海外 AI サービスへのアクセス速度と安定性を大幅に向上させます。グローバル AI 中継プラットフォーム、海外 AI SaaS、越境ビジネス、高並列 API システム展開に特に適しています。AI API のために生まれ、あなたの AI 中継サービスをより速く、より安定して、より安心に。<a href="https://veilx.io/#/hello/SJRBRVDV">購入リンク</a>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://roxybrowser.com/invite/bgGKG7"><img src="assets/partners/logos/RoxyBrowser.png" alt="RoxyBrowser" width="150"></a></td>
|
||||
<td>RoxyBrowser のご支援に感謝します!<a href="https://roxybrowser.com/invite/bgGKG7">RoxyBrowser</a> は Sub2API の理想的なパートナーです:ネイティブ統合された Roxy AI Agent と高品質なネイティブ住宅 IP を搭載し、シンプルなコマンドで一括自動化をサポート、マルチアカウント管理のセキュリティと効率を大幅に向上させます!<a href="https://roxybrowser.com/invite/bgGKG7">このリンク</a>から登録すると、無料の住宅 IP パッケージと生涯 10% 割引を獲得できます。
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://sui-xiang.com/"><img src="assets/partners/logos/sui-xiang.jpg" alt="sui-xiang" width="150"></a></td>
|
||||
<td>随想AI ゲートウェイのご支援に感謝します!<a href="https://sui-xiang.com/">随想AI ゲートウェイ</a> は信頼性と効率に優れた API 中継サービスプロバイダーで、Claude、Codex、Gemini などの中継サービスを提供しています。プライバシー重視の中継ステーション・データ転売なし・モデル水増しなし、プライバシー・透明性・超高速アフターサービス。新規アカウント登録後、毎日サインインで 0.5 元のテストクレジットがもらえ、チャージは 1:1、サブスクリプション不要、従量課金。マルチライン冗長、クロスリージョン災害復旧、自動フェイルオーバー、長時間 SSE 接続が途切れません。99.9% の可用性、重要な呼び出しは決して遅れません。
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.proxy4free.com/?keyword=4yjqecpc"><img src="assets/partners/logos/proxy4free.png" alt="proxy4free" width="150"></a></td>
|
||||
<td>Proxy4Free のご支援に感謝します!Proxy4Free は開発者と AI アプリケーション向けのデータプロキシサービスプロバイダーで、住宅プロキシ、静的住宅プロキシ、ISP プロキシ、データセンタープロキシなど多様なプロキシソリューションを提供しており、Web Scraping、Browser Automation、AI Agent などのシナリオに適しています。グローバル IP リソース、安定した接続、柔軟な切り替えをサポートし、開発者のデータ収集成功率の向上と IP ブロックリスクの低減を支援します。<a href="https://www.proxy4free.com/?keyword=4yjqecpc">こちらのリンクから登録</a>して、より安定した効率的な自動化ワークフローを簡単に構築しましょう。
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="http://www.fastaitoken.com/register"><img src="assets/partners/logos/fastaitoken.jpg" alt="fastaitoken" width="150"></a></td>
|
||||
<td>🎉 FastAIToken のご支援に感謝します!<a href="http://www.fastaitoken.com/register">FastAIToken</a> は開発者向けの AI API アグリゲーションプラットフォームで、OpenAI、Claude、Gemini などの主要な大規模モデルに対応しています。チャージは 1:1(1 元 = 1 米ドル分の API クレジット)で、開発者がより低コスト・より手軽に世界トップクラスの大規模モデルサービスを利用できます。<br>
|
||||
|
||||
🚀 プラットフォームでは多彩なチャネルを自由に選択できます:超低価格の 0.02x OpenAI 特典グループ(期間限定)、最低 0.25x の OpenAI グループ、0.7x Claude(95% 固定キャッシュ)、1.2x Claude Max チャネル。さらに、各グループの可用率・レイテンシ・稼働状況をリアルタイムで表示する公開ステータスページを提供し、透明で信頼できるサービスを実現。7×24 時間の有人テクニカルサポート(ボットではありません)により、開発者のニーズに迅速に対応します。
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="http://aimzoon.com"><img src="assets/partners/logos/aimzoon.jpg" alt="aimzoon" width="150"></a></td>
|
||||
<td>Aimzoon のご支援に感謝します!<a href="http://aimzoon.com">Aimzoon</a> は安定してコストパフォーマンスに優れた AI API 接続サービスを提供し、開発者が主要な AI サービスを Codex、Claude Code、Gemini CLI などのコーディングツールへ素早く接続できるようにします。複雑な設定は不要で、より速い接続、より安定した呼び出し、より低いコストを実現。Codex レート割引や特価レートなどのキャンペーンも随時開催中、登録するだけで無料お試しクレジットをプレゼント。AI コーディングを日常のワークフローへ。<a href="http://aimzoon.com">こちら</a>から登録してお試しください!
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://console.claudeapi.com/agent/register/drTKjyn6wGLK061Z"><img src="assets/partners/logos/claudeapi.jpg" alt="claudeapi" width="150"></a></td>
|
||||
<td>Claude API のご支援に感謝します!<a href="https://console.claudeapi.com/agent/register/drTKjyn6wGLK061Z">Claude API</a> は Claude モデルに特化した公式チャネルの API サービスプロバイダーで、Anthropic 公式キーと AWS Bedrock 公式チャネルをベースに、Claude Code や Agent アプリケーションへの安定した接続体験を提供します。Claude 全シリーズのモデルに対応し、Tool Use や長文コンテキストなどの公式機能もそのまま利用可能。リバースエンジニアリングやモデル劣化のないサービスで、Claude Code のヘビーユーザー、Agent エンジニア、企業の技術チームに最適です。<a href="https://console.claudeapi.com/agent/register/drTKjyn6wGLK061Z">専用リンク</a>から登録後カスタマーサポートへご連絡いただくと、無料お試しクレジットを受け取れます。請求書発行やチーム導入にも対応しています。
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://code0.ai/agent/register/LgpIgl9JHtVG53V1?utm_source=zcf&utm_medium=partner&utm_campaign=zcf_2026&utm_content=default"><img src="assets/partners/logos/code0.jpg" alt="code0" width="150"></a></td>
|
||||
<td>code0.ai のご支援に感謝します!<a href="https://code0.ai/agent/register/LgpIgl9JHtVG53V1?utm_source=zcf&utm_medium=partner&utm_campaign=zcf_2026&utm_content=default">code0.ai</a> は開発者と技術チーム向けの AI プログラミングワークベンチで、Claude Code や Codex などの主要な Agent コーディング能力を集約し、コード生成、プロジェクト理解、デバッグと修正、コードレビュー、ドキュメント生成といった一般的な開発シーンをサポートします。個人開発者、Agent エンジニア、OSS メンテナー、企業の開発チームに最適で、請求書発行やチーム導入にも対応。<a href="https://code0.ai/agent/register/LgpIgl9JHtVG53V1?utm_source=zcf&utm_medium=partner&utm_campaign=zcf_2026&utm_content=default">専用リンク</a>から登録後カスタマーサポートへご連絡いただくと、無料お試しクレジットを受け取り、より効率的な AI プログラミングワークフローを体験できます。
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://nagora.ai/"><img src="assets/partners/logos/nagora.png" alt="Nagora" width="150"></a></td>
|
||||
<td><a href="https://nagora.ai/">Nagora</a>は、開発者やチーム向けに設計されたマルチモデルAI APIゲートウェイです。1つのアカウントと1つのAPIキーだけで、26種類以上の主要なテキストモデルおよび画像モデルを一元的に利用できます。OpenAI、Anthropic、Geminiの各プロトコルに対応し、Claude Code、Codex、Gemini CLIなどの開発ツールにもシームレスに接続できます。 プラットフォームには、インテリジェントルーティング、自動フェイルオーバー、透明性の高い料金体系、請求の一元管理に加え、予算管理、レート制限、同時実行数の制御機能が備わっています。これにより、個人開発、チームでの共同作業、本番環境におけるAI APIの利用を、より安定的かつ柔軟に管理できます。 既存のアプリケーションを改修する必要はありません。Base URLとAPIキーを置き換えるだけで、最短1分で導入を完了できます。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.novada.com/?sub2api/"><img src="assets/partners/logos/novada.png" alt="Novada" width="150"></a></td>
|
||||
<td>Novada のご支援に感謝します!<a href="https://www.novada.com/?sub2api/">Novada</a> は、AI アプリケーションや自動化ワークフローを構築する開発者向けに、レジデンシャル、ISP、データセンター、モバイルプロキシに加え、Web Unlocker と Scraper API を提供しています。グローバルな IP カバレッジ、柔軟なローテーション/スティッキーセッション、精密なジオターゲティングにより、AI エージェントワークフロー、クロスリージョンテスト、Web リサーチ、ブラウザ自動化などのシーンで、チームが Web データへ確実にアクセスできるよう支援します。Novada で、より安定しスケーラブルな AI ワークフローを構築しましょう。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://s.qiniu.com/u6rQrq"><img src="assets/partners/logos/qiniu.jpg" alt="Qiniu AI" width="150"></a></td>
|
||||
<td>七牛云AI のご支援に感謝します!七牛云AI は、七牛云(02567.HK)傘下のエンタープライズ向け大規模モデル MaaS プラットフォームです。世界の主要モデル 150+ をワンストップで利用でき、グローバル主要モデルプロバイダーのプロトコルに対応し、テキスト、画像、音声、動画、ファイル処理などのフルモーダル処理能力をカバー。169万を超える企業・開発者ユーザーにサービスを提供しています。Sub2API ユーザー向けの限定特典として、<a href="https://s.qiniu.com/u6rQrq">こちらのリンク</a>から登録すると、企業ユーザーは 1200万 Token、開発者は 300万 Token を無料で獲得できます。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://api.fenno.ai/s/dC4k"><img src="assets/partners/logos/fennoai.jpg" alt="FennoAI" width="150"></a></td>
|
||||
<td>FennoAI のご支援に感謝します!FennoAI は、企業の研究開発チームと開発者向けの高安定・高性能 API 中継サービスプロバイダーです。OpenAI と Anthropic のプロトコルに対応し、Codex、Claude Code、OpenCode などの主要 AI コーディングツールにシームレスに接続できます。エンタープライズ級の安定性を備え、1 日あたり千億規模の Token 呼び出しに対応。国内外法人間の企業間決済と請求書発行もサポートし、企業の研究開発・調達ニーズに応えます。Sub2API ユーザー限定特典として、<a href="https://api.fenno.ai/s/dC4k">専用リンク</a>からサブスクリプションを購入すると、わずか 1.99 ドルで 50 ドル相当の Coding Plan クレジットを獲得できます。さらに招待報酬にも対応しており、友達の購入で最大 20% の還元を獲得可能。招待が多いほど、報酬も増えます。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://lanox.ai/?c=6"><img src="assets/partners/logos/lanox.jpg" alt="LanoX AI" width="150"></a></td>
|
||||
<td>本プロジェクトをご支援いただいている <a href="https://lanox.ai/?c=6">LanoX AI</a> に感謝します!LanoX AI は、開発者、チーム、企業向けに、安定性とコストパフォーマンスに優れたグローバルモデル接続サービスを提供しています。 🎁 新規ユーザー特典 — 数百万 Token を無料で獲得可能。さらに 500+ の無料モデルで、低コストなテスト、検証、デプロイをより簡単に 🧠 世界の主要モデル — GPT · Claude · Gemini · Qwen · Grok... 🎬 マルチモーダル制作 — Seedance 2.0 · GPT Image · Gemini Nano Banana 🛡️ エンタープライズ級の安定性 — 高可用性 💎 ネイティブ能力の出力 💎 性能劣化なし 💎 モデル混在なし 💎 利用量と課金が透明 💎 💰 より低い利用コスト — トップモデルを公式価格の 1 割から利用可能。明確なドキュメント、簡単な接続、請求書発行、企業向け一括利用に対応 🏢 企業に最適 — AI プロダクト、Agent、コンテンツプラットフォーム、大量利用する開発チームに最適</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://www.rapidproxy.io/?ref=sub2api"><img src="assets/partners/logos/rapidproxy.jpg" alt="RapidProxy" width="150"></a></td>
|
||||
<td><a href="https://www.rapidproxy.io/?ref=sub2api">RapidProxy</a> は開発者向けのデータ収集プロキシソリューションであり、安定して信頼できる住宅用プロキシサービスを提供します。9,000 万以上のグローバル住宅 IP と 200 以上の国・地域のカバー、インテリジェントなローテーション機構、精密な地域ターゲティング機能により、クローラー、AI データ学習、SEO モニタリング、EC データ分析などのプロジェクトがアクセス制限を突破し、データ収集の効率を高めます。Playwright、Selenium、Puppeteer などの主要な自動化フレームワークに対応し、料金は $0.65/GB から。<a href="https://www.rapidproxy.io/?ref=sub2api">今すぐ無料でお試しください</a>。</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td width="180"><a href="https://hao.ai"><img src="assets/partners/logos/haoai.png" alt="hao.ai" width="150"></a></td>
|
||||
<td><a href="https://hao.ai">hao.ai</a> は、開発者とチーム向けの高速で安定した大規模モデル統合 API ゲートウェイです。1 つの API Key と統一されたインターフェースで、GPT、Claude、xAI Grok などの主要モデルに接続でき、OpenAI や Anthropic などの一般的なプロトコルと SDK に対応しています。プラットフォームはモデルルーティング、フェイルオーバー、チーム管理、完全な呼び出しログを提供し、モデル価格は公式参考価格の 1.5 割から。よりシンプルに、より安定して、より低コストに AI アプリケーションを構築できます。</td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
|
||||
## 概要
|
||||
|
||||
Sub2API は、AI 製品のサブスクリプションから API クォータを配分・管理するために設計された AI API ゲートウェイプラットフォームです。ユーザーはプラットフォームが生成した API キーを通じて上流の AI サービスにアクセスでき、プラットフォームは認証、課金、負荷分散、リクエスト転送を処理します。
|
||||
|
||||
## 機能
|
||||
|
||||
- **マルチアカウント管理** - 複数の上流アカウントタイプ(OAuth、APIキー)をサポート
|
||||
- **APIキー配布** - ユーザー向けの APIキーの生成と管理
|
||||
- **精密な課金** - トークンレベルの使用量追跡とコスト計算
|
||||
- **スマートスケジューリング** - スティッキーセッション付きのインテリジェントなアカウント選択
|
||||
- **同時実行制御** - ユーザーごと・アカウントごとの同時実行数制限
|
||||
- **レート制限** - 設定可能なリクエスト数およびトークンレート制限
|
||||
- **内蔵決済システム** - EasyPay、Alipay、WeChat Pay、Stripe に対応。ユーザーのセルフサービスチャージが可能で、別途決済サービスのデプロイは不要([設定ガイド](docs/PAYMENT.md))
|
||||
- **管理ダッシュボード** - 監視・管理のための Web インターフェース
|
||||
- **外部システム連携** - 外部システム(チケット管理など)を iframe 経由で管理ダッシュボードに埋め込み可能
|
||||
|
||||
## エコシステム
|
||||
|
||||
Sub2API を拡張・統合するコミュニティプロジェクト:
|
||||
|
||||
| プロジェクト | 説明 | 機能 |
|
||||
|---------|-------------|----------|
|
||||
| ~~[Sub2ApiPay](https://github.com/touwaeriol/sub2apipay)~~ | ~~セルフサービス決済システム~~ | **内蔵済み** — 決済機能は Sub2API に統合されました。別途デプロイは不要です。[決済設定ガイド](docs/PAYMENT.md)をご参照ください |
|
||||
| [sub2api-mobile](https://github.com/ckken/sub2api-mobile) | モバイル管理コンソール | ユーザー管理、アカウント管理、監視ダッシュボード、マルチバックエンド切り替えが可能なクロスプラットフォームアプリ(iOS/Android/Web)。Expo + React Native で構築 |
|
||||
|
||||
## 技術スタック
|
||||
|
||||
| コンポーネント | 技術 |
|
||||
|-----------|------------|
|
||||
| バックエンド | Go 1.25.7, Gin, Ent |
|
||||
| フロントエンド | Vue 3.4+, Vite 5+, TailwindCSS |
|
||||
| データベース | PostgreSQL 15+ |
|
||||
| キャッシュ/キュー | Redis 7+ |
|
||||
|
||||
---
|
||||
|
||||
## Nginx リバースプロキシに関する注意
|
||||
|
||||
Sub2API(または CRS)を Nginx でリバースプロキシし、Codex CLI と組み合わせて使用する場合、Nginx の `http` ブロックに以下の設定を追加してください:
|
||||
|
||||
```nginx
|
||||
underscores_in_headers on;
|
||||
```
|
||||
|
||||
Nginx はデフォルトでアンダースコアを含むヘッダー(例: `session_id`)を破棄するため、マルチアカウント構成でのスティッキーセッションルーティングに支障をきたします。
|
||||
|
||||
---
|
||||
|
||||
## デプロイ
|
||||
|
||||
### 方法1: スクリプトによるインストール(推奨)
|
||||
|
||||
GitHub Releases からビルド済みバイナリをダウンロードするワンクリックインストールスクリプトです。
|
||||
|
||||
#### 前提条件
|
||||
|
||||
- Linux サーバー(amd64 または arm64)
|
||||
- PostgreSQL 15+(インストール済みかつ稼働中)
|
||||
- Redis 7+(インストール済みかつ稼働中)
|
||||
- root 権限
|
||||
|
||||
#### インストール手順
|
||||
|
||||
```bash
|
||||
curl -sSL https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/deploy/install.sh | sudo bash
|
||||
```
|
||||
|
||||
スクリプトは以下を実行します:
|
||||
1. システムアーキテクチャの検出
|
||||
2. 最新リリースのダウンロード
|
||||
3. バイナリを `/opt/sub2api` にインストール
|
||||
4. systemd サービスの作成
|
||||
5. システムユーザーと権限の設定
|
||||
|
||||
#### インストール後の作業
|
||||
|
||||
```bash
|
||||
# 1. サービスを起動
|
||||
sudo systemctl start sub2api
|
||||
|
||||
# 2. 起動時の自動起動を有効化
|
||||
sudo systemctl enable sub2api
|
||||
|
||||
# 3. ブラウザでセットアップウィザードを開く
|
||||
# http://YOUR_SERVER_IP:8080
|
||||
```
|
||||
|
||||
セットアップウィザードでは以下の設定を行います:
|
||||
- データベース設定
|
||||
- Redis 設定
|
||||
- 管理者アカウントの作成
|
||||
|
||||
#### アップグレード
|
||||
|
||||
**管理ダッシュボード**の左上にある**アップデートを確認**ボタンをクリックすることで、ダッシュボードから直接アップグレードできます。
|
||||
|
||||
Web インターフェースでは以下が可能です:
|
||||
- 新しいバージョンの自動確認
|
||||
- ワンクリックでのアップデートのダウンロードと適用
|
||||
- 必要に応じたロールバック
|
||||
|
||||
#### よく使うコマンド
|
||||
|
||||
```bash
|
||||
# ステータスを確認
|
||||
sudo systemctl status sub2api
|
||||
|
||||
# ログを表示
|
||||
sudo journalctl -u sub2api -f
|
||||
|
||||
# サービスを再起動
|
||||
sudo systemctl restart sub2api
|
||||
|
||||
# アンインストール
|
||||
curl -sSL https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/deploy/install.sh | sudo bash -s -- uninstall -y
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 方法2: Docker Compose(推奨)
|
||||
|
||||
PostgreSQL と Redis のコンテナを含む Docker Compose でデプロイします。
|
||||
|
||||
#### 前提条件
|
||||
|
||||
- Docker 20.10+
|
||||
- Docker Compose v2+
|
||||
|
||||
#### クイックスタート(ワンクリックデプロイ)
|
||||
|
||||
自動デプロイスクリプトを使用して簡単にセットアップできます:
|
||||
|
||||
```bash
|
||||
# デプロイ用ディレクトリを作成
|
||||
mkdir -p sub2api-deploy && cd sub2api-deploy
|
||||
|
||||
# デプロイ準備スクリプトをダウンロードして実行
|
||||
curl -sSL https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/deploy/docker-deploy.sh | bash
|
||||
|
||||
# サービスを起動
|
||||
docker compose up -d
|
||||
|
||||
# ログを表示
|
||||
docker compose logs -f sub2api
|
||||
```
|
||||
|
||||
**スクリプトの動作内容:**
|
||||
- `docker-compose.local.yml`(`docker-compose.yml` として保存)と `.env.example` をダウンロード
|
||||
- セキュアな認証情報(JWT_SECRET、TOTP_ENCRYPTION_KEY、POSTGRES_PASSWORD)を自動生成
|
||||
- 自動生成されたシークレットで `.env` ファイルを作成
|
||||
- データディレクトリを作成(バックアップ・移行が容易なローカルディレクトリを使用)
|
||||
- 生成された認証情報を参照用に表示
|
||||
|
||||
#### 手動デプロイ
|
||||
|
||||
手動でセットアップする場合:
|
||||
|
||||
```bash
|
||||
# 1. リポジトリをクローン
|
||||
git clone https://github.com/Wei-Shaw/sub2api.git
|
||||
cd sub2api/deploy
|
||||
|
||||
# 2. 環境設定ファイルをコピー
|
||||
cp .env.example .env
|
||||
chmod 600 .env
|
||||
|
||||
# 3. 設定を編集(セキュアなパスワードを生成)
|
||||
nano .env
|
||||
```
|
||||
|
||||
**`.env` の必須設定:**
|
||||
|
||||
```bash
|
||||
# PostgreSQL パスワード(必須)
|
||||
POSTGRES_PASSWORD=your_secure_password_here
|
||||
|
||||
# JWT シークレット(推奨 - 再起動後もユーザーのログイン状態を保持)
|
||||
JWT_SECRET=your_jwt_secret_here
|
||||
|
||||
# TOTP 暗号化キー(推奨 - 再起動後も二要素認証を維持)
|
||||
TOTP_ENCRYPTION_KEY=your_totp_key_here
|
||||
|
||||
# オプション: 管理者アカウント
|
||||
ADMIN_EMAIL=admin@example.com
|
||||
ADMIN_PASSWORD=your_admin_password
|
||||
|
||||
# オプション: カスタムポート
|
||||
SERVER_PORT=8080
|
||||
```
|
||||
|
||||
**セキュアなシークレットの生成方法:**
|
||||
```bash
|
||||
# JWT_SECRET を生成
|
||||
openssl rand -hex 32
|
||||
|
||||
# TOTP_ENCRYPTION_KEY を生成
|
||||
openssl rand -hex 32
|
||||
|
||||
# POSTGRES_PASSWORD を生成
|
||||
openssl rand -hex 32
|
||||
```
|
||||
|
||||
```bash
|
||||
# 4. データディレクトリを作成(ローカルバージョンの場合)
|
||||
mkdir -p data postgres_data redis_data
|
||||
|
||||
# 5. すべてのサービスを起動
|
||||
# オプション A: ローカルディレクトリバージョン(推奨 - 移行が容易)
|
||||
docker compose -f docker-compose.local.yml up -d
|
||||
|
||||
# オプション B: 名前付きボリュームバージョン(シンプルなセットアップ)
|
||||
docker compose up -d
|
||||
|
||||
# 6. ステータスを確認
|
||||
docker compose -f docker-compose.local.yml ps
|
||||
|
||||
# 7. ログを表示
|
||||
docker compose -f docker-compose.local.yml logs -f sub2api
|
||||
```
|
||||
|
||||
#### デプロイバージョン
|
||||
|
||||
| バージョン | データストレージ | 移行 | 推奨用途 |
|
||||
|---------|-------------|-----------|----------|
|
||||
| **docker-compose.local.yml** | ローカルディレクトリ | ✅ 容易(ディレクトリ全体を tar) | 本番環境、頻繁なバックアップ |
|
||||
| **docker-compose.yml** | 名前付きボリューム | ⚠️ docker コマンドが必要 | シンプルなセットアップ |
|
||||
|
||||
**推奨:** データ管理が容易な `docker-compose.local.yml`(スクリプトによるデプロイ)を使用してください。
|
||||
|
||||
#### アクセス
|
||||
|
||||
ブラウザで `http://YOUR_SERVER_IP:8080` を開いてください。
|
||||
|
||||
管理者パスワードが自動生成された場合は、ログで確認できます:
|
||||
```bash
|
||||
docker compose -f docker-compose.local.yml logs sub2api | grep "admin password"
|
||||
```
|
||||
|
||||
#### アップグレード
|
||||
|
||||
```bash
|
||||
# 最新イメージをプルしてコンテナを再作成
|
||||
docker compose -f docker-compose.local.yml pull
|
||||
docker compose -f docker-compose.local.yml up -d
|
||||
```
|
||||
|
||||
#### 簡単な移行(ローカルディレクトリバージョン)
|
||||
|
||||
`docker-compose.local.yml` を使用している場合、新しいサーバーへの移行が簡単です:
|
||||
|
||||
```bash
|
||||
# 移行元サーバーにて
|
||||
docker compose -f docker-compose.local.yml down
|
||||
cd ..
|
||||
tar czf sub2api-complete.tar.gz sub2api-deploy/
|
||||
|
||||
# 新しいサーバーに転送
|
||||
scp sub2api-complete.tar.gz user@new-server:/path/
|
||||
|
||||
# 移行先サーバーにて
|
||||
tar xzf sub2api-complete.tar.gz
|
||||
cd sub2api-deploy/
|
||||
docker compose -f docker-compose.local.yml up -d
|
||||
```
|
||||
|
||||
#### よく使うコマンド
|
||||
|
||||
```bash
|
||||
# すべてのサービスを停止
|
||||
docker compose -f docker-compose.local.yml down
|
||||
|
||||
# 再起動
|
||||
docker compose -f docker-compose.local.yml restart
|
||||
|
||||
# すべてのログを表示
|
||||
docker compose -f docker-compose.local.yml logs -f
|
||||
|
||||
# すべてのデータを削除(注意!)
|
||||
docker compose -f docker-compose.local.yml down
|
||||
rm -rf data/ postgres_data/ redis_data/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 方法3: Apple container(macOS)
|
||||
|
||||
Apple シリコン搭載 Mac と macOS 26 では、Apple `container` 1.1.0 以降を使用して Sub2API、PostgreSQL、Redis の完全なスタックを実行できます:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/Wei-Shaw/sub2api.git
|
||||
cd sub2api/deploy
|
||||
./apple-container.sh init
|
||||
./apple-container.sh up
|
||||
./apple-container.sh status
|
||||
```
|
||||
|
||||
これはローカル開発および手動運用向けです。本番環境では引き続き Docker Compose を推奨します。ライフサイクル、永続化、アップグレード、制限については [deploy/APPLE_CONTAINER.md](deploy/APPLE_CONTAINER.md) を参照してください。
|
||||
|
||||
---
|
||||
|
||||
### 方法4: ソースからビルド
|
||||
|
||||
開発やカスタマイズのためにソースコードからビルドして実行します。
|
||||
|
||||
#### 前提条件
|
||||
|
||||
- Go 1.21+
|
||||
- Node.js 18+
|
||||
- PostgreSQL 15+
|
||||
- Redis 7+
|
||||
|
||||
#### ビルド手順
|
||||
|
||||
```bash
|
||||
# 1. リポジトリをクローン
|
||||
git clone https://github.com/Wei-Shaw/sub2api.git
|
||||
cd sub2api
|
||||
|
||||
# 2. pnpm をインストール(未インストールの場合)
|
||||
npm install -g pnpm
|
||||
|
||||
# 3. フロントエンドをビルド
|
||||
cd frontend
|
||||
pnpm install
|
||||
pnpm run build
|
||||
# 出力先: ../backend/internal/web/dist/
|
||||
|
||||
# 4. フロントエンドを組み込んだバックエンドをビルド
|
||||
cd ../backend
|
||||
VERSION="$(./scripts/resolve-version.sh)"
|
||||
go build -tags embed -ldflags="-X main.Version=${VERSION}" -o sub2api ./cmd/server
|
||||
|
||||
# 5. 設定ファイルを作成
|
||||
cp ../deploy/config.example.yaml ./config.yaml
|
||||
|
||||
# 6. 設定を編集
|
||||
nano config.yaml
|
||||
```
|
||||
|
||||
> **注意:** `-tags embed` フラグはフロントエンドをバイナリに組み込みます。このフラグがない場合、バイナリはフロントエンド UI を提供しません。
|
||||
|
||||
**`config.yaml` の主要設定:**
|
||||
|
||||
```yaml
|
||||
server:
|
||||
host: "0.0.0.0"
|
||||
port: 8080
|
||||
mode: "release"
|
||||
|
||||
database:
|
||||
host: "localhost"
|
||||
port: 5432
|
||||
user: "postgres"
|
||||
password: "your_password"
|
||||
dbname: "sub2api"
|
||||
|
||||
redis:
|
||||
host: "localhost"
|
||||
port: 6379
|
||||
password: ""
|
||||
|
||||
jwt:
|
||||
secret: "change-this-to-a-secure-random-string"
|
||||
expire_hour: 24
|
||||
|
||||
default:
|
||||
user_concurrency: 5
|
||||
user_balance: 0
|
||||
api_key_prefix: "sk-"
|
||||
rate_multiplier: 1.0
|
||||
```
|
||||
|
||||
### Sora ステータス(一時的に利用不可)
|
||||
|
||||
> ⚠️ Sora 関連の機能は、上流統合およびメディア配信の技術的問題により一時的に利用できません。
|
||||
> 現時点では本番環境で Sora に依存しないでください。
|
||||
> 既存の `gateway.sora_*` 設定キーは予約されていますが、これらの問題が解決されるまで有効にならない場合があります。
|
||||
|
||||
`config.yaml` では追加のセキュリティ関連オプションも利用できます:
|
||||
|
||||
- `cors.allowed_origins` - CORS 許可リスト
|
||||
- `security.url_allowlist` - 上流/価格/CRS ホストの許可リスト
|
||||
- `security.url_allowlist.enabled` - URL バリデーションの無効化(注意して使用)
|
||||
- `security.url_allowlist.allow_insecure_http` - バリデーション無効時に HTTP URL を許可
|
||||
- `security.url_allowlist.allow_private_hosts` - プライベート/ローカル IP アドレスを許可
|
||||
- `security.response_headers.enabled` - 設定可能なレスポンスヘッダーフィルタリングを有効化(無効時はデフォルトの許可リストを使用)
|
||||
- `security.csp` - Content-Security-Policy ヘッダーの制御
|
||||
- `billing.circuit_breaker` - 課金エラー時にフェイルクローズ
|
||||
- `security.trust_forwarded_ip_for_api_key_acl` - 従来の生転送ヘッダーによる上書きを制御(アップグレード互換性のため既定で有効)。無効にすると `server.trusted_proxies` を厳格に使用し、Sub2API に直接接続するプロキシの正確な CIDR のみを指定
|
||||
- `security.forwarded_client_ip_headers` - サードパーティ CDN のクライアント IP ヘッダーを最大 16 個指定。従来モードが有効な場合のみ、設定順で組み込みヘッダーより先に評価
|
||||
- `turnstile.required` - リリースモードでの Turnstile 必須化
|
||||
|
||||
カスタムクライアント IP ヘッダーは YAML またはカンマ区切りの環境変数で設定できます:
|
||||
|
||||
```bash
|
||||
SECURITY_FORWARDED_CLIENT_IP_HEADERS=True-Client-IP,X-CDN-Client-IP
|
||||
```
|
||||
|
||||
ヘッダー名は検証、正規化、大小文字を区別しない重複排除が行われます。管理画面のセキュリティ設定から再起動せずに更新でき、新規インストールでは YAML/環境変数の既定値を保存し、既存環境ではデータベース値がない場合に補完します。従来モードを無効にするとカスタムおよび組み込みの生転送ヘッダーはすべて無視され、`server.trusted_proxies` のみを使用します。有効にする場合はオリジンへの接続元を CDN/プロキシに制限し、エッジで信頼する全クライアント IP ヘッダーを上書きしてください。移行規則と信頼境界の詳細は [`deploy/EDGE_SECURITY.md`](deploy/EDGE_SECURITY.md) を参照してください。
|
||||
|
||||
**⚠️ セキュリティ警告: HTTP URL 設定**
|
||||
|
||||
`security.url_allowlist.enabled=false` の場合、システムは最小限の URL バリデーションのみを行い、**デフォルトで HTTP URL を許可**します(開発フレンドリーモード。Docker Compose デプロイのデフォルトも同じです)。本番環境では、以下のように明示的に HTTPS のみに制限することを推奨します:
|
||||
|
||||
```yaml
|
||||
security:
|
||||
url_allowlist:
|
||||
enabled: false # 許可リストチェックを無効化
|
||||
allow_insecure_http: false # HTTPS のみ許可(本番環境推奨)
|
||||
```
|
||||
|
||||
**または環境変数で設定:**
|
||||
|
||||
```bash
|
||||
SECURITY_URL_ALLOWLIST_ENABLED=false
|
||||
SECURITY_URL_ALLOWLIST_ALLOW_INSECURE_HTTP=false
|
||||
```
|
||||
|
||||
**HTTP を許可するリスク:**
|
||||
- API キーとデータが**平文**で送信される(傍受の危険性)
|
||||
- **中間者攻撃(MITM)**を受けやすい
|
||||
- **本番環境には不適切**
|
||||
|
||||
**HTTP を使用すべき場面:**
|
||||
- ✅ ローカルサーバーでの開発・テスト(http://localhost)
|
||||
- ✅ 信頼できるエンドポイントを持つ内部ネットワーク
|
||||
- ✅ HTTPS 取得前のアカウント接続テスト
|
||||
- ❌ 本番環境(HTTPS のみを使用)
|
||||
|
||||
**`allow_insecure_http: false` 設定時に HTTP URL で表示されるエラー例:**
|
||||
```
|
||||
Invalid base URL: invalid url scheme: http
|
||||
```
|
||||
|
||||
URL バリデーションまたはレスポンスヘッダーフィルタリングを無効にする場合は、ネットワーク層を強化してください:
|
||||
- 上流ドメイン/IP のエグレス許可リストを適用
|
||||
- プライベート/ループバック/リンクローカル範囲をブロック
|
||||
- TLS のみのアウトバウンドトラフィックを強制
|
||||
- プロキシで機密性の高い上流レスポンスヘッダーを除去
|
||||
|
||||
#### ⚠️ 重要:管理者アカウントの作成
|
||||
|
||||
初期管理者アカウントは**セットアップウィザード経由でのみ作成**されます(初回起動時に `http://<host>:8080` にアクセス)。`config.yaml` の `default.admin_email` / `default.admin_password` フィールドは**管理者作成には使われません**。テンプレートに残っているのは歴史的経緯によるものです。
|
||||
|
||||
上記ステップ 5 で事前に `config.yaml` を作成しているため、**初回起動時にセットアップウィザードはスキップされます**。サーバーは既存の config を検出して通常モードで直接起動し、この時点では `users` テーブルが空のため、初回ログインは `invalid email or password` を返します。
|
||||
|
||||
**管理者アカウントを作成する 2 つの方法:**
|
||||
|
||||
1. **推奨 — ウィザードに `config.yaml` を自動生成させる:** 上記ステップ 5 をスキップします(`cp` を実行しない)。`./sub2api` を直接起動し、`http://localhost:8080` にアクセスすると、セットアップウィザードがデータベース・Redis・管理者アカウントの設定を案内し、`config.yaml` を自動生成します。
|
||||
|
||||
2. **すでに `config.yaml` を作成してしまった場合:** 初回起動前に一時的に退避してウィザードを発生させ、完了後に戻します:
|
||||
```bash
|
||||
mv config.yaml config.yaml.bak
|
||||
./sub2api # ウィザードが http://localhost:8080 で起動し、新しい config.yaml を生成します
|
||||
# ウィザード完了後、Ctrl+C でサーバーを停止し、設定を復元します:
|
||||
mv config.yaml.bak config.yaml
|
||||
./sub2api # 通常モードで再起動し、作成した管理者でログインします
|
||||
```
|
||||
|
||||
```bash
|
||||
# 6. アプリケーションを実行
|
||||
./sub2api
|
||||
```
|
||||
|
||||
#### 開発モード
|
||||
|
||||
```bash
|
||||
# バックエンド(ホットリロード付き)
|
||||
cd backend
|
||||
go run ./cmd/server
|
||||
|
||||
# フロントエンド(ホットリロード付き)
|
||||
cd frontend
|
||||
pnpm run dev
|
||||
```
|
||||
|
||||
#### コード生成
|
||||
|
||||
`backend/ent/schema` を編集した場合、Ent + Wire を再生成してください:
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
go generate ./ent
|
||||
go generate ./cmd/server
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## シンプルモード
|
||||
|
||||
シンプルモードは、フル SaaS 機能を必要とせず、素早くアクセスしたい個人開発者や社内チーム向けに設計されています。
|
||||
|
||||
- 有効化: 環境変数 `RUN_MODE=simple` を設定
|
||||
- 違い: SaaS 関連機能を非表示にし、課金プロセスをスキップ
|
||||
- セキュリティに関する注意: 本番環境では `SIMPLE_MODE_CONFIRM=true` も設定する必要があります
|
||||
|
||||
---
|
||||
|
||||
## Antigravity サポート
|
||||
|
||||
Sub2API は [Antigravity](https://antigravity.so/) アカウントをサポートしています。認証後、Claude および Gemini モデル用の専用エンドポイントが利用可能になります。
|
||||
|
||||
### 専用エンドポイント
|
||||
|
||||
| エンドポイント | モデル |
|
||||
|----------|-------|
|
||||
| `/antigravity/v1/messages` | Claude モデル |
|
||||
| `/antigravity/v1beta/` | Gemini モデル |
|
||||
|
||||
### Claude Code の設定
|
||||
|
||||
```bash
|
||||
export ANTHROPIC_BASE_URL="http://localhost:8080/antigravity"
|
||||
export ANTHROPIC_AUTH_TOKEN="sk-xxx"
|
||||
```
|
||||
|
||||
### ハイブリッドスケジューリングモード
|
||||
|
||||
Antigravity アカウントはオプションの**ハイブリッドスケジューリング**をサポートしています。有効にすると、汎用エンドポイント `/v1/messages` および `/v1beta/` も Antigravity アカウントにリクエストをルーティングします。
|
||||
|
||||
> **⚠️ 警告**: Anthropic Claude と Antigravity Claude は**同じ会話コンテキスト内で混在させることはできません**。グループを使用して適切に分離してください。
|
||||
|
||||
---
|
||||
|
||||
## プロジェクト構成
|
||||
|
||||
```
|
||||
sub2api/
|
||||
├── backend/ # Go バックエンドサービス
|
||||
│ ├── cmd/server/ # アプリケーションエントリ
|
||||
│ ├── internal/ # 内部モジュール
|
||||
│ │ ├── config/ # 設定
|
||||
│ │ ├── model/ # データモデル
|
||||
│ │ ├── service/ # ビジネスロジック
|
||||
│ │ ├── handler/ # HTTP ハンドラー
|
||||
│ │ └── gateway/ # API ゲートウェイコア
|
||||
│ └── resources/ # 静的リソース
|
||||
│
|
||||
├── frontend/ # Vue 3 フロントエンド
|
||||
│ └── src/
|
||||
│ ├── api/ # API 呼び出し
|
||||
│ ├── stores/ # 状態管理
|
||||
│ ├── views/ # ページコンポーネント
|
||||
│ └── components/ # 再利用可能なコンポーネント
|
||||
│
|
||||
└── deploy/ # デプロイファイル
|
||||
├── docker-compose.yml # Docker Compose 設定
|
||||
├── .env.example # Docker Compose 用環境変数
|
||||
├── config.example.yaml # バイナリデプロイ用フル設定ファイル
|
||||
└── install.sh # ワンクリックインストールスクリプト
|
||||
```
|
||||
|
||||
## スター履歴
|
||||
|
||||
<a href="https://star-history.com/#Wei-Shaw/sub2api&Date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Wei-Shaw/sub2api&type=Date&theme=dark" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Wei-Shaw/sub2api&type=Date" />
|
||||
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Wei-Shaw/sub2api&type=Date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
---
|
||||
|
||||
## ライセンス
|
||||
|
||||
本プロジェクトは [GNU Lesser General Public License v3.0](LICENSE)(またはそれ以降のバージョン)の下でライセンスされています。
|
||||
|
||||
Copyright (c) 2026 Wesley Liddick
|
||||
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
|
||||
**このプロジェクトが役に立ったら、ぜひスターをお願いします!**
|
||||
|
||||
</div>
|
||||
@@ -1,32 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" role="img" aria-labelledby="title desc">
|
||||
<title id="title">Sub2API</title>
|
||||
<desc id="desc">An interlocking S symbol representing subscription routing into APIs.</desc>
|
||||
<defs>
|
||||
<linearGradient id="s2a-bg" x1="72" y1="44" x2="442" y2="478" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#142B56"/>
|
||||
<stop offset=".52" stop-color="#0A1A39"/>
|
||||
<stop offset="1" stop-color="#061127"/>
|
||||
</linearGradient>
|
||||
<radialGradient id="s2a-ambient" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(168 92) rotate(51) scale(342 382)">
|
||||
<stop stop-color="#3E68B0" stop-opacity=".28"/>
|
||||
<stop offset="1" stop-color="#3E68B0" stop-opacity="0"/>
|
||||
</radialGradient>
|
||||
<linearGradient id="s2a-brand" x1="4" y1="4" x2="20" y2="20" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#79F4BD"/>
|
||||
<stop offset=".48" stop-color="#39D9E7"/>
|
||||
<stop offset="1" stop-color="#3875F6"/>
|
||||
</linearGradient>
|
||||
<filter id="s2a-shadow" x="-25%" y="-25%" width="150%" height="165%" color-interpolation-filters="sRGB">
|
||||
<feDropShadow dx="0" dy=".55" stdDeviation=".65" flood-color="#020817" flood-opacity=".34"/>
|
||||
</filter>
|
||||
</defs>
|
||||
|
||||
<rect x="16" y="16" width="480" height="480" rx="120" fill="url(#s2a-bg)"/>
|
||||
<rect x="16" y="16" width="480" height="480" rx="120" fill="url(#s2a-ambient)"/>
|
||||
<rect x="16.75" y="16.75" width="478.5" height="478.5" rx="119.25" fill="none" stroke="#A5BFFF" stroke-opacity=".16" stroke-width="1.5"/>
|
||||
|
||||
<g transform="translate(52 52) scale(17)" fill="none" stroke="url(#s2a-brand)" stroke-linecap="round" stroke-linejoin="round" stroke-width="2.7" filter="url(#s2a-shadow)">
|
||||
<path d="m19.25 7.65-2.55-3.2a1.33 1.33 0 0 0-1.03-.5H8.58c-.34 0-.67.13-.91.37L4.15 7.65c-.93.88-.6 1.52.65 2.3l9.55 5.97"/>
|
||||
<path d="m4.75 16.35 2.55 3.2c.25.31.63.5 1.03.5h7.09c.34 0 .67-.13.91-.37l3.52-3.33c.93-.88.6-1.52-.65-2.3L9.65 8.08"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 2.0 KiB |
|
Before Width: | Height: | Size: 17 KiB |
|
Before Width: | Height: | Size: 38 KiB |
|
Before Width: | Height: | Size: 25 KiB |
|
Before Width: | Height: | Size: 33 KiB |
|
Before Width: | Height: | Size: 9.5 KiB |
|
Before Width: | Height: | Size: 7.8 KiB |
|
Before Width: | Height: | Size: 69 KiB |
|
Before Width: | Height: | Size: 3.6 KiB |
|
Before Width: | Height: | Size: 3.2 KiB |
|
Before Width: | Height: | Size: 246 KiB |
|
Before Width: | Height: | Size: 1.2 MiB |
|
Before Width: | Height: | Size: 5.2 KiB |
|
Before Width: | Height: | Size: 20 KiB |
|
Before Width: | Height: | Size: 28 KiB |
@@ -1,32 +0,0 @@
|
||||
<svg
|
||||
width="340"
|
||||
height="112"
|
||||
viewBox="0 0 340 112"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
role="img"
|
||||
aria-label="Hao.ai"
|
||||
>
|
||||
<!-- Fill the compact landscape canvas while preserving the homepage lockup proportions. -->
|
||||
<g transform="translate(170 56) scale(1.45) translate(-170 -56)">
|
||||
<!-- Homepage HaoAI mark, rendered in the brand green. -->
|
||||
<g transform="translate(66.55 12) scale(0.55)">
|
||||
<path
|
||||
d="M49 30C42.3726 30 37 35.3726 37 42V118C37 124.627 42.3726 130 49 130C55.6274 130 61 124.627 61 118V42C61 35.3726 55.6274 30 49 30ZM111 30C104.373 30 99 35.3726 99 42V118C99 124.627 104.373 130 111 130C117.627 130 123 124.627 123 118V42C123 35.3726 117.627 30 111 30ZM80 92.5C86.9036 92.5 92.5 86.9036 92.5 80C92.5 73.0964 86.9036 67.5 80 67.5C73.0964 67.5 67.5 73.0964 67.5 80C67.5 86.9036 73.0964 92.5 80 92.5Z"
|
||||
fill="#1DB954"
|
||||
fill-rule="evenodd"
|
||||
clip-rule="evenodd"
|
||||
/>
|
||||
</g>
|
||||
|
||||
<!-- Homepage wordmark converted from Inter SemiBold to vector outlines. -->
|
||||
<g transform="translate(150.35 69) scale(0.0166015625 -0.0166015625)" fill="#111111">
|
||||
<path d="M150 0L150 1490L417 1490L417 874L1110 874L1110 1490L1377 1490L1377 0L1110 0L1110 649L417 649L417 0Z" />
|
||||
<path transform="translate(1527 0)" d="M450 -23Q344 -23 259 15.5Q174 54 125 129Q76 204 76 314Q76 409 111.5 471Q147 533 207.5 570Q268 607 344 626Q420 645 502 653Q599 664 660 672Q721 680 749.5 698Q778 716 778 754L778 759Q778 814 756 852.5Q734 891 690.5 911.5Q647 932 583 932Q518 932 470.5 912Q423 892 393 860Q363 828 349 791L108 840Q141 939 210 1003.5Q279 1068 374.5 1100Q470 1132 582 1132Q661 1132 741.5 1113.5Q822 1095 889 1051Q956 1007 997 933Q1038 859 1038 747L1038 0L789 0L789 154L779 154Q754 107 710.5 66.5Q667 26 602.5 1.5Q538 -23 450 -23ZM517 170Q598 170 656.5 202Q715 234 747.5 286.5Q780 339 780 401L780 533Q767 523 736.5 514Q706 505 668.5 498Q631 491 594.5 486Q558 481 533 478Q475 470 428 452Q381 434 354.5 401.5Q328 369 328 317Q328 269 352.5 236.5Q377 204 419.5 187Q462 170 517 170Z" />
|
||||
<path transform="translate(2703 0)" d="M623 -23Q460 -23 340 49.5Q220 122 154.5 251.5Q89 381 89 553Q89 727 154.5 857.5Q220 988 340 1060Q460 1132 623 1132Q787 1132 907 1060Q1027 988 1092.5 857.5Q1158 727 1158 553Q1158 381 1092.5 251.5Q1027 122 907 49.5Q787 -23 623 -23ZM623 188Q714 188 774.5 237Q835 286 864.5 369Q894 452 894 554Q894 657 864.5 740Q835 823 774.5 872Q714 921 623 921Q532 921 472.5 872Q413 823 383.5 740.5Q354 658 354 554Q354 452 383.5 369Q413 286 472.5 237Q532 188 623 188Z" />
|
||||
<path transform="translate(3950 0)" fill="#1DB954" d="M326 -17Q259 -17 212.5 29Q166 75 166 143Q166 210 212.5 256Q259 302 326 302Q394 302 440.5 256Q487 210 487 143Q487 75 440.5 29Q394 -17 326 -17Z" />
|
||||
<path transform="translate(4603 0)" d="M450 -23Q344 -23 259 15.5Q174 54 125 129Q76 204 76 314Q76 409 111.5 471Q147 533 207.5 570Q268 607 344 626Q420 645 502 653Q599 664 660 672Q721 680 749.5 698Q778 716 778 754L778 759Q778 814 756 852.5Q734 891 690.5 911.5Q647 932 583 932Q518 932 470.5 912Q423 892 393 860Q363 828 349 791L108 840Q141 939 210 1003.5Q279 1068 374.5 1100Q470 1132 582 1132Q661 1132 741.5 1113.5Q822 1095 889 1051Q956 1007 997 933Q1038 859 1038 747L1038 0L789 0L789 154L779 154Q754 107 710.5 66.5Q667 26 602.5 1.5Q538 -23 450 -23ZM517 170Q598 170 656.5 202Q715 234 747.5 286.5Q780 339 780 401L780 533Q767 523 736.5 514Q706 505 668.5 498Q631 491 594.5 486Q558 481 533 478Q475 470 428 452Q381 434 354.5 401.5Q328 369 328 317Q328 269 352.5 236.5Q377 204 419.5 187Q462 170 517 170Z" />
|
||||
<path transform="translate(5779 0)" d="M138 0L138 1118L398 1118L398 0ZM268 1276Q206 1276 161.5 1318Q117 1360 117 1418Q117 1478 161.5 1519.5Q206 1561 268 1561Q331 1561 375.5 1519.5Q420 1478 420 1419Q420 1360 375.5 1318Q331 1276 268 1276Z" />
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 3.7 KiB |
|
Before Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 8.9 KiB |
|
Before Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 89 KiB |
|
Before Width: | Height: | Size: 8.0 KiB |
|
Before Width: | Height: | Size: 171 KiB |
|
Before Width: | Height: | Size: 39 KiB |
|
Before Width: | Height: | Size: 69 KiB |
|
Before Width: | Height: | Size: 7.4 KiB |
|
Before Width: | Height: | Size: 32 KiB |
|
Before Width: | Height: | Size: 16 KiB |
|
Before Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 2.8 KiB |
|
Before Width: | Height: | Size: 42 KiB |
|
Before Width: | Height: | Size: 376 KiB |
@@ -1,4 +1,4 @@
|
||||
FROM golang:1.26.5-alpine
|
||||
FROM golang:1.25.7-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
@@ -15,8 +15,7 @@ RUN go mod download
|
||||
COPY . .
|
||||
|
||||
# 构建应用
|
||||
RUN VERSION_VALUE="$(./scripts/resolve-version.sh)" && \
|
||||
go build -ldflags="-s -w -X main.Version=${VERSION_VALUE}" -o main ./cmd/server/
|
||||
RUN go build -o main ./cmd/server/
|
||||
|
||||
# 暴露端口
|
||||
EXPOSE 8080
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
.PHONY: build generate test test-unit test-integration test-e2e
|
||||
|
||||
VERSION ?= $(shell ./scripts/resolve-version.sh)
|
||||
VERSION ?= $(shell tr -d '\r\n' < ./cmd/server/VERSION)
|
||||
LDFLAGS ?= -s -w -X main.Version=$(VERSION)
|
||||
|
||||
build:
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
# Ingress rejection log cleanup
|
||||
|
||||
This maintenance command removes historical admission rejections from
|
||||
`ops_error_logs` without matching unrelated authentication or upstream errors.
|
||||
It is a dry run unless `--execute` is supplied, and always requires an explicit
|
||||
RFC3339 cutoff.
|
||||
|
||||
```sh
|
||||
go run ./cmd/cleanup-ingress-reject-logs --before 2026-07-17T00:00:00Z
|
||||
go run ./cmd/cleanup-ingress-reject-logs --before 2026-07-17T00:00:00Z --execute
|
||||
```
|
||||
|
||||
Run the execute form only after every application instance has been upgraded so
|
||||
older instances cannot add new ingress rejection rows below the chosen cutoff.
|
||||
The classifier intentionally retains invariant failures such as
|
||||
`USER_NOT_FOUND`, database errors, quota/billing errors, and upstream failures.
|
||||
|
||||
After the rollout and cleanup are verified, run
|
||||
`backend/scripts/finalize-ingress-reject-cleanup.sql` in a maintenance window to
|
||||
remove the deprecated plaintext-key audit table and attribution columns.
|
||||
@@ -1,218 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
_ "github.com/Wei-Shaw/sub2api/ent/runtime"
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/repository"
|
||||
"github.com/lib/pq"
|
||||
)
|
||||
|
||||
const classifierVersion = "ingress-reject-v1"
|
||||
|
||||
type candidate struct {
|
||||
id int64
|
||||
statusCode int
|
||||
message string
|
||||
body string
|
||||
}
|
||||
|
||||
func main() {
|
||||
beforeRaw := flag.String("before", "", "required RFC3339 cutoff; only older rows are considered")
|
||||
execute := flag.Bool("execute", false, "delete matched rows (default is dry-run)")
|
||||
batchSize := flag.Int("batch-size", 5000, "scan/delete batch size (1-5000)")
|
||||
flag.Parse()
|
||||
|
||||
if *beforeRaw == "" {
|
||||
log.Fatal("--before is required")
|
||||
}
|
||||
before, err := time.Parse(time.RFC3339, *beforeRaw)
|
||||
if err != nil {
|
||||
log.Fatalf("invalid --before: %v", err)
|
||||
}
|
||||
if *batchSize < 1 || *batchSize > 5000 {
|
||||
log.Fatal("--batch-size must be between 1 and 5000")
|
||||
}
|
||||
|
||||
cfg, err := config.LoadForBootstrap()
|
||||
if err != nil {
|
||||
log.Fatalf("load config: %v", err)
|
||||
}
|
||||
client, db, err := repository.InitEnt(cfg)
|
||||
if err != nil {
|
||||
log.Fatalf("initialize database: %v", err)
|
||||
}
|
||||
defer func() { _ = client.Close() }()
|
||||
|
||||
ctx := context.Background()
|
||||
counts, scanned, matched, deleted, err := cleanup(ctx, db, before, *batchSize, *execute)
|
||||
if err != nil {
|
||||
log.Fatalf("cleanup failed: %v", err)
|
||||
}
|
||||
|
||||
digest := sha256.Sum256([]byte(classifierVersion))
|
||||
mode := "dry-run"
|
||||
if *execute {
|
||||
mode = "execute"
|
||||
}
|
||||
fmt.Printf("mode=%s before=%s classifier=%s scanned=%d matched=%d deleted=%d\n",
|
||||
mode, before.UTC().Format(time.RFC3339), hex.EncodeToString(digest[:]), scanned, matched, deleted)
|
||||
reasons := make([]string, 0, len(counts))
|
||||
for reason := range counts {
|
||||
reasons = append(reasons, reason)
|
||||
}
|
||||
sort.Strings(reasons)
|
||||
for _, reason := range reasons {
|
||||
fmt.Printf("reason=%s count=%d\n", reason, counts[reason])
|
||||
}
|
||||
if *execute && deleted > 0 {
|
||||
fmt.Println("cleanup complete; schedule VACUUM (ANALYZE) ops_error_logs during normal maintenance")
|
||||
}
|
||||
}
|
||||
|
||||
func cleanup(ctx context.Context, db *sql.DB, before time.Time, batchSize int, execute bool) (map[string]int64, int64, int64, int64, error) {
|
||||
counts := make(map[string]int64)
|
||||
var cursor, scanned, matched, deleted int64
|
||||
for {
|
||||
rows, err := db.QueryContext(ctx, `
|
||||
SELECT id, COALESCE(status_code, 0), COALESCE(error_message, ''), COALESCE(error_body, '')
|
||||
FROM ops_error_logs
|
||||
WHERE id > $1
|
||||
AND created_at < $2
|
||||
AND error_phase = 'auth'
|
||||
AND account_id IS NULL
|
||||
AND upstream_status_code IS NULL
|
||||
AND COALESCE(upstream_error_message, '') = ''
|
||||
AND COALESCE(upstream_error_detail, '') = ''
|
||||
ORDER BY id ASC
|
||||
LIMIT $3`, cursor, before, batchSize)
|
||||
if err != nil {
|
||||
return nil, scanned, matched, deleted, err
|
||||
}
|
||||
|
||||
batch := make([]candidate, 0, batchSize)
|
||||
for rows.Next() {
|
||||
var item candidate
|
||||
if err := rows.Scan(&item.id, &item.statusCode, &item.message, &item.body); err != nil {
|
||||
_ = rows.Close()
|
||||
return nil, scanned, matched, deleted, err
|
||||
}
|
||||
batch = append(batch, item)
|
||||
cursor = item.id
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
_ = rows.Close()
|
||||
return nil, scanned, matched, deleted, err
|
||||
}
|
||||
_ = rows.Close()
|
||||
if len(batch) == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
ids := make([]int64, 0, len(batch))
|
||||
for _, item := range batch {
|
||||
scanned++
|
||||
if reason, ok := historicalIngressRejectReason(item); ok {
|
||||
matched++
|
||||
counts[reason]++
|
||||
ids = append(ids, item.id)
|
||||
}
|
||||
}
|
||||
if execute && len(ids) > 0 {
|
||||
result, err := db.ExecContext(ctx,
|
||||
`DELETE FROM ops_error_logs WHERE id = ANY($1) AND created_at < $2`, pq.Array(ids), before)
|
||||
if err != nil {
|
||||
return nil, scanned, matched, deleted, err
|
||||
}
|
||||
n, err := result.RowsAffected()
|
||||
if err != nil {
|
||||
return nil, scanned, matched, deleted, err
|
||||
}
|
||||
deleted += n
|
||||
}
|
||||
}
|
||||
return counts, scanned, matched, deleted, nil
|
||||
}
|
||||
|
||||
func historicalIngressRejectReason(item candidate) (string, bool) {
|
||||
code, message := parseErrorIdentity(item.body, item.message)
|
||||
switch code {
|
||||
case "API_KEY_REQUIRED":
|
||||
return "missing_key", true
|
||||
case "INVALID_API_KEY":
|
||||
return "invalid_key", true
|
||||
case "API_KEY_DISABLED":
|
||||
return "key_disabled", true
|
||||
case "USER_INACTIVE":
|
||||
return "user_inactive", true
|
||||
case "GROUP_DELETED":
|
||||
return "group_deleted", true
|
||||
case "GROUP_DISABLED":
|
||||
return "group_disabled", true
|
||||
case "GROUP_NOT_ALLOWED":
|
||||
return "group_forbidden", true
|
||||
case "ACCESS_DENIED":
|
||||
return "ip_acl_denied", true
|
||||
case "api_key_in_query_deprecated":
|
||||
return "query_key_deprecated", true
|
||||
}
|
||||
|
||||
normalized := strings.TrimSpace(message)
|
||||
switch {
|
||||
case normalized == "API key is required":
|
||||
return "missing_key", true
|
||||
case normalized == "Invalid API key":
|
||||
return "invalid_key", true
|
||||
case normalized == "API key is disabled":
|
||||
return "key_disabled", true
|
||||
case normalized == "User account is not active":
|
||||
return "user_inactive", true
|
||||
case normalized == "API Key 所属分组已删除":
|
||||
return "group_deleted", true
|
||||
case normalized == "API Key 所属分组已停用":
|
||||
return "group_disabled", true
|
||||
case normalized == "API Key 所属专属分组不再允许当前用户使用":
|
||||
return "group_forbidden", true
|
||||
case normalized == "API Key is not assigned to any group and cannot be used. Please contact the administrator to assign it to a group.":
|
||||
return "group_unassigned", true
|
||||
case strings.HasPrefix(normalized, "Access denied. Your IP is "):
|
||||
return "ip_acl_denied", true
|
||||
case normalized == "Query parameter api_key is deprecated. Use Authorization header or key instead.":
|
||||
return "query_key_deprecated", true
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
|
||||
func parseErrorIdentity(body, fallbackMessage string) (string, string) {
|
||||
var payload struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Error struct {
|
||||
Code json.RawMessage `json:"code"`
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(body), &payload); err != nil {
|
||||
return "", fallbackMessage
|
||||
}
|
||||
message := payload.Message
|
||||
if message == "" {
|
||||
message = payload.Error.Message
|
||||
}
|
||||
if message == "" {
|
||||
message = fallbackMessage
|
||||
}
|
||||
return strings.TrimSpace(payload.Code), message
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestHistoricalIngressRejectReason(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
item candidate
|
||||
reason string
|
||||
match bool
|
||||
}{
|
||||
{name: "standard invalid key", item: candidate{body: `{"code":"INVALID_API_KEY","message":"Invalid API key"}`}, reason: "invalid_key", match: true},
|
||||
{name: "google missing key", item: candidate{body: `{"error":{"code":401,"message":"API key is required","status":"UNAUTHENTICATED"}}`}, reason: "missing_key", match: true},
|
||||
{name: "google group deleted", item: candidate{body: `{"error":{"code":403,"message":"API Key 所属分组已删除","status":"PERMISSION_DENIED"}}`}, reason: "group_deleted", match: true},
|
||||
{name: "ip acl", item: candidate{body: `{"code":"ACCESS_DENIED","message":"Access denied. Your IP is 192.0.2.1"}`}, reason: "ip_acl_denied", match: true},
|
||||
{name: "user not found remains", item: candidate{body: `{"code":"USER_NOT_FOUND","message":"User associated with API key not found"}`}, match: false},
|
||||
{name: "quota remains", item: candidate{body: `{"code":"API_KEY_QUOTA_EXHAUSTED","message":"quota"}`}, match: false},
|
||||
{name: "database failure remains", item: candidate{statusCode: 500, message: "Failed to validate API key", body: `{"code":"INTERNAL_ERROR","message":"Failed to validate API key"}`}, match: false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
reason, ok := historicalIngressRejectReason(tt.item)
|
||||
if ok != tt.match || reason != tt.reason {
|
||||
t.Fatalf("got (%q, %v), want (%q, %v)", reason, ok, tt.reason, tt.match)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -33,7 +33,7 @@ func main() {
|
||||
}()
|
||||
|
||||
userRepo := repository.NewUserRepository(client, sqlDB)
|
||||
authService := service.NewAuthService(client, userRepo, nil, nil, cfg, nil, nil, nil, nil, nil, nil, nil, nil)
|
||||
authService := service.NewAuthService(client, userRepo, nil, nil, cfg, nil, nil, nil, nil, nil, nil)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
@@ -48,7 +48,7 @@ func main() {
|
||||
log.Fatalf("failed to resolve admin user: %v", err)
|
||||
}
|
||||
|
||||
token, err := authService.GenerateToken(ctx, user)
|
||||
token, err := authService.GenerateToken(user)
|
||||
if err != nil {
|
||||
log.Fatalf("failed to generate token: %v", err)
|
||||
}
|
||||
|
||||
@@ -1,237 +0,0 @@
|
||||
// profit-preview 读取生产只读导出的 JSON(分组利润配置、账号倍率与探测状态、
|
||||
// 用户覆盖倍率、主力模型清单),复用线上 U/D/阈值判定做五平台离线预演。
|
||||
//
|
||||
// 用法:
|
||||
//
|
||||
// go run ./cmd/profit-preview -input dump.json [-assume-enabled] [-json]
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
)
|
||||
|
||||
type inputGroup struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Platform string `json:"platform"`
|
||||
RateMultiplier float64 `json:"rate_multiplier"`
|
||||
SubscriptionType string `json:"subscription_type"`
|
||||
ProfitControlEnabled bool `json:"profit_control_enabled"`
|
||||
ProfitMinMargin float64 `json:"profit_min_margin"`
|
||||
ProfitSafetyBuffer float64 `json:"profit_safety_buffer"`
|
||||
PeakRateEnabled bool `json:"peak_rate_enabled"`
|
||||
PeakStart string `json:"peak_start"`
|
||||
PeakEnd string `json:"peak_end"`
|
||||
PeakRateMultiplier float64 `json:"peak_rate_multiplier"`
|
||||
}
|
||||
|
||||
type inputAccount struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Platform string `json:"platform"`
|
||||
Type string `json:"type"`
|
||||
RateMultiplier *float64 `json:"rate_multiplier"`
|
||||
Extra map[string]any `json:"extra"`
|
||||
ModelMapping map[string]string `json:"model_mapping"`
|
||||
}
|
||||
|
||||
type inputEntry struct {
|
||||
Group inputGroup `json:"group"`
|
||||
Accounts []inputAccount `json:"accounts"`
|
||||
UserOverrides map[string]*float64 `json:"user_overrides"`
|
||||
Models []string `json:"models"`
|
||||
}
|
||||
|
||||
type inputDoc struct {
|
||||
Groups []inputEntry `json:"groups"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
inputPath := flag.String("input", "", "生产只读导出 JSON 路径")
|
||||
assumeEnabled := flag.Bool("assume-enabled", false, "把当前关闭的支持平台分组按保存配置视为已启用")
|
||||
jsonOut := flag.Bool("json", false, "以 JSON 输出完整报告(默认输出可读表格)")
|
||||
flag.Parse()
|
||||
if *inputPath == "" {
|
||||
fmt.Fprintln(os.Stderr, "usage: profit-preview -input dump.json [-assume-enabled] [-json]")
|
||||
os.Exit(2)
|
||||
}
|
||||
raw, err := os.ReadFile(*inputPath)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "read input: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
inputs, err := parsePreviewInputs(raw, *assumeEnabled)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "parse input: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
evalAt := time.Now()
|
||||
reports := service.PreviewProfitAdmission(inputs, evalAt)
|
||||
if len(reports) == 0 {
|
||||
fmt.Fprintln(os.Stderr, "input produced no preview reports")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if *jsonOut {
|
||||
enc := json.NewEncoder(os.Stdout)
|
||||
enc.SetIndent("", " ")
|
||||
if err := enc.Encode(map[string]any{"evaluated_at": evalAt, "reports": reports}); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "write output: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Printf("利润门预演 @ %s(U=账号倍率;探测状态仅告警)\n", evalAt.Format(time.RFC3339))
|
||||
for _, report := range reports {
|
||||
fmt.Printf("\n== 分组 %d %s [%s] ==\n", report.GroupID, report.GroupName, report.Platform)
|
||||
fmt.Printf(" 利润门生效=%v 假定启用=%v | 默认 D=%.4f 阈值=%.4f | 最低有效 D=%.4f 阈值=%.4f\n",
|
||||
report.EffectiveGate, report.AssumedEnabled,
|
||||
report.DefaultD, report.ThresholdDefault, report.MinEffectiveD, report.ThresholdMinD)
|
||||
counts := map[string]int{}
|
||||
for _, v := range report.Verdicts {
|
||||
counts[v.Class]++
|
||||
rate := "-"
|
||||
if v.AccountRate != nil {
|
||||
rate = fmt.Sprintf("%.4f", *v.AccountRate)
|
||||
}
|
||||
flags := make([]string, 0, 2)
|
||||
if v.RejectedUnderMinD {
|
||||
flags = append(flags, "最低有效D下拒绝")
|
||||
}
|
||||
if len(v.Warnings) > 0 {
|
||||
flags = append(flags, strings.Join(v.Warnings, ","))
|
||||
}
|
||||
suffix := ""
|
||||
if len(flags) > 0 {
|
||||
suffix = " [" + strings.Join(flags, "; ") + "]"
|
||||
}
|
||||
fmt.Printf(" 账号 %-4d %-24s 平台=%-12s U=%-8s 来源=%-19s %s%s\n",
|
||||
v.AccountID, v.Name, v.Platform, rate, v.RateSource, v.Class, suffix)
|
||||
}
|
||||
fmt.Printf(" 分类合计: 准入=%d 利润不足=%d 倍率非法=%d\n",
|
||||
counts[service.ProfitPreviewClassAdmitted],
|
||||
counts[service.ProfitPreviewClassRejectedThreshold],
|
||||
counts[service.ProfitPreviewClassRejectedInvalidRate])
|
||||
models := make([]string, 0, len(report.RemainingByModel))
|
||||
for model := range report.RemainingByModel {
|
||||
models = append(models, model)
|
||||
}
|
||||
sort.Strings(models)
|
||||
for _, model := range models {
|
||||
fmt.Printf(" 模型 %-20s 利润门准入账号: 默认D=%d 最低有效D=%d\n",
|
||||
model, report.RemainingByModel[model], report.RemainingByModelMinD[model])
|
||||
}
|
||||
for _, model := range modelsWithZeroRemaining(report) {
|
||||
fmt.Printf(" 警告: 模型 %s 启用后利润门准入账号为 0\n", model)
|
||||
}
|
||||
for _, model := range modelsWithZeroRemainingUnderMinD(report) {
|
||||
fmt.Printf(" 警告: 模型 %s 在最低有效D(存在低倍率用户覆盖)下利润门准入账号为 0\n", model)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func parsePreviewInputs(raw []byte, assumeEnabled bool) ([]service.ProfitPreviewGroupInput, error) {
|
||||
var doc inputDoc
|
||||
if err := json.Unmarshal(raw, &doc); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(doc.Groups) == 0 {
|
||||
return nil, fmt.Errorf("input contains no groups; check the export query and target configuration")
|
||||
}
|
||||
|
||||
inputs := make([]service.ProfitPreviewGroupInput, 0, len(doc.Groups))
|
||||
for i, entry := range doc.Groups {
|
||||
if entry.Group.ID <= 0 || strings.TrimSpace(entry.Group.Platform) == "" {
|
||||
return nil, fmt.Errorf("invalid group at index %d: id and platform are required", i)
|
||||
}
|
||||
group := &service.Group{
|
||||
ID: entry.Group.ID,
|
||||
Name: entry.Group.Name,
|
||||
Platform: entry.Group.Platform,
|
||||
Status: service.StatusActive,
|
||||
Hydrated: true,
|
||||
RateMultiplier: entry.Group.RateMultiplier,
|
||||
SubscriptionType: entry.Group.SubscriptionType,
|
||||
ProfitControlEnabled: entry.Group.ProfitControlEnabled,
|
||||
ProfitMinMargin: entry.Group.ProfitMinMargin,
|
||||
ProfitSafetyBuffer: entry.Group.ProfitSafetyBuffer,
|
||||
PeakRateEnabled: entry.Group.PeakRateEnabled,
|
||||
PeakStart: entry.Group.PeakStart,
|
||||
PeakEnd: entry.Group.PeakEnd,
|
||||
PeakRateMultiplier: entry.Group.PeakRateMultiplier,
|
||||
}
|
||||
accounts := make([]*service.Account, 0, len(entry.Accounts))
|
||||
for _, a := range entry.Accounts {
|
||||
account := &service.Account{
|
||||
ID: a.ID,
|
||||
Name: a.Name,
|
||||
Platform: a.Platform,
|
||||
Type: a.Type,
|
||||
RateMultiplier: a.RateMultiplier,
|
||||
Extra: a.Extra,
|
||||
}
|
||||
if len(a.ModelMapping) > 0 {
|
||||
mapping := make(map[string]any, len(a.ModelMapping))
|
||||
for k, v := range a.ModelMapping {
|
||||
mapping[k] = v
|
||||
}
|
||||
account.Credentials = map[string]any{"model_mapping": mapping}
|
||||
}
|
||||
accounts = append(accounts, account)
|
||||
}
|
||||
overrides := make(map[int64]float64, len(entry.UserOverrides))
|
||||
for userID, rate := range entry.UserOverrides {
|
||||
if rate == nil {
|
||||
continue
|
||||
}
|
||||
var id int64
|
||||
if _, err := fmt.Sscan(userID, &id); err == nil && id > 0 {
|
||||
overrides[id] = *rate
|
||||
}
|
||||
}
|
||||
inputs = append(inputs, service.ProfitPreviewGroupInput{
|
||||
Group: group,
|
||||
Accounts: accounts,
|
||||
UserOverrides: overrides,
|
||||
Models: entry.Models,
|
||||
AssumeEnabled: assumeEnabled,
|
||||
})
|
||||
}
|
||||
return inputs, nil
|
||||
}
|
||||
|
||||
func modelsWithZeroRemaining(report service.ProfitPreviewGroupReport) []string {
|
||||
var out []string
|
||||
for model, count := range report.RemainingByModel {
|
||||
if count == 0 {
|
||||
out = append(out, model)
|
||||
}
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// modelsWithZeroRemainingUnderMinD 返回默认 D 下仍有准入账号、但在最低有效 D
|
||||
// 下会归零的模型。最低有效 D 来自分组内最低的用户级倍率覆盖:这些模型对那部分
|
||||
// 用户是全黑的,而只看默认 D 的告警完全看不出来。
|
||||
// 两档都为 0 的模型由 modelsWithZeroRemaining 报告,这里不重复。
|
||||
func modelsWithZeroRemainingUnderMinD(report service.ProfitPreviewGroupReport) []string {
|
||||
var out []string
|
||||
for model, count := range report.RemainingByModelMinD {
|
||||
if count == 0 && report.RemainingByModel[model] > 0 {
|
||||
out = append(out, model)
|
||||
}
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestParsePreviewInputsIgnoresNullUserOverride(t *testing.T) {
|
||||
raw := []byte(`{
|
||||
"groups": [{
|
||||
"group": {
|
||||
"id": 50,
|
||||
"name": "preview",
|
||||
"platform": "openai",
|
||||
"rate_multiplier": 0.5,
|
||||
"subscription_type": "standard",
|
||||
"profit_control_enabled": false,
|
||||
"profit_min_margin": 0.1,
|
||||
"profit_safety_buffer": 0
|
||||
},
|
||||
"accounts": [{
|
||||
"id": 1,
|
||||
"name": "cheap",
|
||||
"platform": "openai",
|
||||
"type": "apikey",
|
||||
"rate_multiplier": 0.2
|
||||
}],
|
||||
"user_overrides": {"40": null, "41": 0.4},
|
||||
"models": ["gpt-test"]
|
||||
}]
|
||||
}`)
|
||||
|
||||
inputs, err := parsePreviewInputs(raw, true)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, inputs, 1)
|
||||
require.Equal(t, map[int64]float64{41: 0.4}, inputs[0].UserOverrides)
|
||||
require.True(t, inputs[0].AssumeEnabled)
|
||||
|
||||
report := service.PreviewProfitAdmission(inputs, time.Date(2026, 1, 15, 8, 30, 0, 0, time.UTC))[0]
|
||||
require.InDelta(t, 0.4, report.MinEffectiveD, 1e-12, "null 覆盖不能被解码成 0 倍率")
|
||||
require.InDelta(t, 0.36, report.ThresholdMinD, 1e-12)
|
||||
}
|
||||
|
||||
func TestParsePreviewInputsRejectsEmptyGroups(t *testing.T) {
|
||||
for _, raw := range [][]byte{
|
||||
[]byte(`{"groups":null}`),
|
||||
[]byte(`{"groups":[]}`),
|
||||
} {
|
||||
inputs, err := parsePreviewInputs(raw, false)
|
||||
require.ErrorContains(t, err, "input contains no groups")
|
||||
require.Nil(t, inputs)
|
||||
}
|
||||
}
|
||||
|
||||
// TestModelsWithZeroRemainingWarnings 钉死两档 D 的归零告警分工:
|
||||
// 默认 D 归零由 modelsWithZeroRemaining 报告;默认 D 仍有账号但最低有效 D
|
||||
// (分组内存在更低的用户级倍率覆盖)归零的模型必须单独告警——那些用户的该
|
||||
// 模型会全黑,只看默认 D 完全看不出来。两档都为 0 时不重复告警。
|
||||
func TestModelsWithZeroRemainingWarnings(t *testing.T) {
|
||||
report := service.ProfitPreviewGroupReport{
|
||||
RemainingByModel: map[string]int{
|
||||
"both-zero": 0,
|
||||
"min-d-zero": 2,
|
||||
"healthy": 3,
|
||||
"min-d-zero-alt": 1,
|
||||
},
|
||||
RemainingByModelMinD: map[string]int{
|
||||
"both-zero": 0,
|
||||
"min-d-zero": 0,
|
||||
"healthy": 3,
|
||||
"min-d-zero-alt": 0,
|
||||
},
|
||||
}
|
||||
|
||||
if got := modelsWithZeroRemaining(report); len(got) != 1 || got[0] != "both-zero" {
|
||||
t.Fatalf("默认D归零告警应只覆盖 both-zero,got %v", got)
|
||||
}
|
||||
|
||||
got := modelsWithZeroRemainingUnderMinD(report)
|
||||
want := []string{"min-d-zero", "min-d-zero-alt"}
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("最低有效D归零告警不符: got %v want %v", got, want)
|
||||
}
|
||||
for i := range want {
|
||||
if got[i] != want[i] {
|
||||
t.Fatalf("最低有效D归零告警不符(应按模型名排序): got %v want %v", got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1 +1 @@
|
||||
0.1.171
|
||||
0.1.96.1
|
||||
|
||||
@@ -24,6 +24,8 @@ import (
|
||||
"github.com/Wei-Shaw/sub2api/internal/web"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"golang.org/x/net/http2"
|
||||
"golang.org/x/net/http2/h2c"
|
||||
)
|
||||
|
||||
//go:embed VERSION
|
||||
@@ -114,16 +116,11 @@ func runSetupServer() {
|
||||
log.Printf("Setup wizard available at http://%s", addr)
|
||||
log.Println("Complete the setup wizard to configure Sub2API")
|
||||
|
||||
protocols := new(http.Protocols)
|
||||
protocols.SetHTTP1(true)
|
||||
protocols.SetUnencryptedHTTP2(true)
|
||||
|
||||
server := &http.Server{
|
||||
Addr: addr,
|
||||
Handler: r,
|
||||
Handler: h2c.NewHandler(r, &http2.Server{}),
|
||||
ReadHeaderTimeout: 30 * time.Second,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
Protocols: protocols,
|
||||
}
|
||||
|
||||
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
@@ -153,15 +150,6 @@ func runMainServer() {
|
||||
log.Fatalf("Failed to initialize application: %v", err)
|
||||
}
|
||||
defer app.Cleanup()
|
||||
if app.PromptAudit != nil {
|
||||
if err := app.PromptAudit.Start(context.Background()); err != nil {
|
||||
// Startup continues so unrelated APIs stay up. Fail-closed (unavailable)
|
||||
// applies only when a persisted blocking policy was observed; without
|
||||
// blocking intent, Prompt Audit stays ModeOff so the gateway remains
|
||||
// usable and administrators can still disable the feature (#4560).
|
||||
log.Printf("Prompt Audit started in degraded state: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 启动服务器
|
||||
go func() {
|
||||
@@ -183,7 +171,7 @@ func runMainServer() {
|
||||
defer cancel()
|
||||
|
||||
if err := app.Server.Shutdown(ctx); err != nil {
|
||||
log.Printf("Server forced to shutdown: %v", err)
|
||||
log.Fatalf("Server forced to shutdown: %v", err)
|
||||
}
|
||||
|
||||
log.Println("Server exited")
|
||||
|
||||
@@ -13,9 +13,7 @@ import (
|
||||
"github.com/Wei-Shaw/sub2api/ent"
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/handler"
|
||||
"github.com/Wei-Shaw/sub2api/internal/payment"
|
||||
"github.com/Wei-Shaw/sub2api/internal/repository"
|
||||
"github.com/Wei-Shaw/sub2api/internal/securityaudit"
|
||||
"github.com/Wei-Shaw/sub2api/internal/server"
|
||||
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
@@ -25,9 +23,8 @@ import (
|
||||
)
|
||||
|
||||
type Application struct {
|
||||
Server *http.Server
|
||||
PromptAudit *securityaudit.PromptService
|
||||
Cleanup func()
|
||||
Server *http.Server
|
||||
Cleanup func()
|
||||
}
|
||||
|
||||
func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
|
||||
@@ -38,17 +35,12 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
|
||||
// Business layer ProviderSets
|
||||
repository.ProviderSet,
|
||||
service.ProviderSet,
|
||||
securityaudit.ProviderSet,
|
||||
payment.ProviderSet,
|
||||
middleware.ProviderSet,
|
||||
handler.ProviderSet,
|
||||
|
||||
// Server layer ProviderSet
|
||||
server.ProviderSet,
|
||||
|
||||
// Privacy client factory for OpenAI training opt-out
|
||||
providePrivacyClientFactory,
|
||||
|
||||
// BuildInfo provider
|
||||
provideServiceBuildInfo,
|
||||
|
||||
@@ -56,15 +48,11 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
|
||||
provideCleanup,
|
||||
|
||||
// Application struct
|
||||
wire.Struct(new(Application), "Server", "PromptAudit", "Cleanup"),
|
||||
wire.Struct(new(Application), "Server", "Cleanup"),
|
||||
)
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func providePrivacyClientFactory() service.PrivacyClientFactory {
|
||||
return repository.CreatePrivacyReqClient
|
||||
}
|
||||
|
||||
func provideServiceBuildInfo(buildInfo handler.BuildInfo) service.BuildInfo {
|
||||
return service.BuildInfo{
|
||||
Version: buildInfo.Version,
|
||||
@@ -81,20 +69,13 @@ func provideCleanup(
|
||||
opsCleanup *service.OpsCleanupService,
|
||||
opsScheduledReport *service.OpsScheduledReportService,
|
||||
opsSystemLogSink *service.OpsSystemLogSink,
|
||||
opsService *service.OpsService,
|
||||
opsIngressReject *service.OpsIngressRejectAggregator,
|
||||
apiKeyService *service.APIKeyService,
|
||||
authCacheInvalidationWorker *service.AuthCacheInvalidationWorker,
|
||||
soraMediaCleanup *service.SoraMediaCleanupService,
|
||||
schedulerSnapshot *service.SchedulerSnapshotService,
|
||||
tokenRefresh *service.TokenRefreshService,
|
||||
accountExpiry *service.AccountExpiryService,
|
||||
codexVersionSync *service.OpenAICodexVersionSyncService,
|
||||
proxyExpiry *service.ProxyExpiryService,
|
||||
subscriptionExpiry *service.SubscriptionExpiryService,
|
||||
usageCleanup *service.UsageCleanupService,
|
||||
idempotencyCleanup *service.IdempotencyCleanupService,
|
||||
batchImageCleanup *service.BatchImageCleanupService,
|
||||
batchImageWorker *service.BatchImageWorkerRuntime,
|
||||
pricing *service.PricingService,
|
||||
emailQueue *service.EmailQueueService,
|
||||
billingCache *service.BillingCacheService,
|
||||
@@ -104,17 +85,8 @@ func provideCleanup(
|
||||
openaiOAuth *service.OpenAIOAuthService,
|
||||
geminiOAuth *service.GeminiOAuthService,
|
||||
antigravityOAuth *service.AntigravityOAuthService,
|
||||
grokOAuth *service.GrokOAuthService,
|
||||
openAIGateway *service.OpenAIGatewayService,
|
||||
scheduledTestRunner *service.ScheduledTestRunnerService,
|
||||
backupSvc *service.BackupService,
|
||||
paymentOrderExpiry *service.PaymentOrderExpiryService,
|
||||
channelMonitorRunner *service.ChannelMonitorRunner,
|
||||
quotaFlusher *service.UserPlatformQuotaUsageFlusher,
|
||||
upstreamBillingProbe *service.UpstreamBillingProbeService,
|
||||
ollamaCloudUsage *service.OllamaCloudUsageService,
|
||||
auditLog *service.AuditLogService,
|
||||
promptAudit *securityaudit.PromptService,
|
||||
) func() {
|
||||
return func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
@@ -127,36 +99,6 @@ func provideCleanup(
|
||||
|
||||
// 应用层清理步骤可并行执行,基础设施资源(Redis/Ent)最后按顺序关闭。
|
||||
parallelSteps := []cleanupStep{
|
||||
{"OpsIngressRejectAggregator", func() error {
|
||||
if opsIngressReject != nil {
|
||||
opsIngressReject.Stop()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"AuthCacheInvalidationWorker", func() error {
|
||||
if authCacheInvalidationWorker != nil {
|
||||
authCacheInvalidationWorker.Stop()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"AuthCacheInvalidationSubscriber", func() error {
|
||||
if apiKeyService != nil {
|
||||
apiKeyService.StopAuthCacheInvalidationSubscriber()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"OpsRuntimeSettingsRefresh", func() error {
|
||||
if opsService != nil {
|
||||
opsService.StopRuntimeSettingsRefresh()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"PromptAuditService", func() error {
|
||||
if promptAudit != nil {
|
||||
return promptAudit.Shutdown(ctx)
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"OpsScheduledReportService", func() error {
|
||||
if opsScheduledReport != nil {
|
||||
opsScheduledReport.Stop()
|
||||
@@ -175,9 +117,9 @@ func provideCleanup(
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"AuditLogService", func() error {
|
||||
if auditLog != nil {
|
||||
auditLog.Stop()
|
||||
{"SoraMediaCleanupService", func() error {
|
||||
if soraMediaCleanup != nil {
|
||||
soraMediaCleanup.Stop()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
@@ -217,18 +159,6 @@ func provideCleanup(
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"BatchImageCleanupService", func() error {
|
||||
if batchImageCleanup != nil {
|
||||
batchImageCleanup.Stop()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"BatchImageWorkerRuntime", func() error {
|
||||
if batchImageWorker != nil {
|
||||
batchImageWorker.Stop()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"TokenRefreshService", func() error {
|
||||
tokenRefresh.Stop()
|
||||
return nil
|
||||
@@ -237,14 +167,6 @@ func provideCleanup(
|
||||
accountExpiry.Stop()
|
||||
return nil
|
||||
}},
|
||||
{"OpenAICodexVersionSyncService", func() error {
|
||||
codexVersionSync.Stop()
|
||||
return nil
|
||||
}},
|
||||
{"ProxyExpiryService", func() error {
|
||||
proxyExpiry.Stop()
|
||||
return nil
|
||||
}},
|
||||
{"SubscriptionExpiryService", func() error {
|
||||
subscriptionExpiry.Stop()
|
||||
return nil
|
||||
@@ -289,12 +211,6 @@ func provideCleanup(
|
||||
antigravityOAuth.Stop()
|
||||
return nil
|
||||
}},
|
||||
{"GrokOAuthService", func() error {
|
||||
if grokOAuth != nil {
|
||||
grokOAuth.Stop()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"OpenAIWSPool", func() error {
|
||||
if openAIGateway != nil {
|
||||
openAIGateway.CloseOpenAIWSPool()
|
||||
@@ -307,42 +223,6 @@ func provideCleanup(
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"BackupService", func() error {
|
||||
if backupSvc != nil {
|
||||
backupSvc.Stop()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"PaymentOrderExpiryService", func() error {
|
||||
if paymentOrderExpiry != nil {
|
||||
paymentOrderExpiry.Stop()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"ChannelMonitorRunner", func() error {
|
||||
if channelMonitorRunner != nil {
|
||||
channelMonitorRunner.Stop()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"UserPlatformQuotaUsageFlusher", func() error {
|
||||
if quotaFlusher != nil {
|
||||
quotaFlusher.Stop()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"UpstreamBillingProbeService", func() error {
|
||||
if upstreamBillingProbe != nil {
|
||||
upstreamBillingProbe.Stop()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"OllamaCloudUsageService", func() error {
|
||||
if ollamaCloudUsage != nil {
|
||||
ollamaCloudUsage.Stop()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
}
|
||||
|
||||
infraSteps := []cleanupStep{
|
||||
|
||||
@@ -12,9 +12,7 @@ import (
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/handler"
|
||||
"github.com/Wei-Shaw/sub2api/internal/handler/admin"
|
||||
"github.com/Wei-Shaw/sub2api/internal/payment"
|
||||
"github.com/Wei-Shaw/sub2api/internal/repository"
|
||||
"github.com/Wei-Shaw/sub2api/internal/securityaudit"
|
||||
"github.com/Wei-Shaw/sub2api/internal/server"
|
||||
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
@@ -51,182 +49,131 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
|
||||
refreshTokenCache := repository.NewRefreshTokenCache(redisClient)
|
||||
settingRepository := repository.NewSettingRepository(client)
|
||||
groupRepository := repository.NewGroupRepository(client, db)
|
||||
proxyRepository := repository.NewProxyRepository(client, db)
|
||||
settingService := service.ProvideSettingService(settingRepository, groupRepository, proxyRepository, configConfig)
|
||||
settingService := service.ProvideSettingService(settingRepository, groupRepository, configConfig)
|
||||
emailCache := repository.NewEmailCache(redisClient)
|
||||
emailService := service.NewEmailService(settingRepository, emailCache)
|
||||
turnstileVerifier := repository.NewTurnstileVerifier()
|
||||
turnstileService := service.NewTurnstileService(settingService, turnstileVerifier)
|
||||
tencentCaptchaVerifier := repository.NewTencentCaptchaVerifier()
|
||||
tencentCaptchaService := service.NewTencentCaptchaService(settingService, tencentCaptchaVerifier)
|
||||
aliyunCaptchaVerifier := repository.NewAliyunCaptchaVerifier()
|
||||
aliyunCaptchaService := service.NewAliyunCaptchaService(settingService, aliyunCaptchaVerifier)
|
||||
emailQueueService := service.ProvideEmailQueueService(emailService)
|
||||
promoCodeRepository := repository.NewPromoCodeRepository(client)
|
||||
billingCache := repository.NewBillingCache(redisClient)
|
||||
userSubscriptionRepository := repository.NewUserSubscriptionRepository(client)
|
||||
apiKeyRepository := repository.NewAPIKeyRepository(client, db)
|
||||
userRPMCache := repository.NewUserRPMCache(redisClient)
|
||||
billingCacheService := service.NewBillingCacheService(billingCache, userRepository, userSubscriptionRepository, apiKeyRepository, configConfig)
|
||||
userGroupRateRepository := repository.NewUserGroupRateRepository(db)
|
||||
userPlatformQuotaRepository := repository.NewUserPlatformQuotaRepository(client)
|
||||
serviceUserPlatformQuotaRepository := repository.NewUserPlatformQuotaServiceAdapter(userPlatformQuotaRepository)
|
||||
billingCacheService := service.ProvideBillingCacheService(billingCache, userRepository, userSubscriptionRepository, apiKeyRepository, userRPMCache, userGroupRateRepository, configConfig, serviceUserPlatformQuotaRepository)
|
||||
apiKeyCache := repository.NewAPIKeyCache(redisClient)
|
||||
concurrencyCache := repository.ProvideConcurrencyCache(redisClient, configConfig)
|
||||
schedulerCache := repository.ProvideSchedulerCache(redisClient, configConfig)
|
||||
accountRepository := repository.NewAccountRepository(client, db, schedulerCache)
|
||||
concurrencyService := service.ProvideConcurrencyService(concurrencyCache, accountRepository, configConfig)
|
||||
apiKeyService := service.ProvideAPIKeyService(apiKeyRepository, userRepository, groupRepository, userSubscriptionRepository, userGroupRateRepository, apiKeyCache, configConfig, billingCacheService, concurrencyService)
|
||||
apiKeyService := service.NewAPIKeyService(apiKeyRepository, userRepository, groupRepository, userSubscriptionRepository, userGroupRateRepository, apiKeyCache, configConfig)
|
||||
apiKeyService.SetRateLimitCacheInvalidator(billingCache)
|
||||
apiKeyAuthCacheInvalidator := service.ProvideAPIKeyAuthCacheInvalidator(apiKeyService)
|
||||
promoService := service.NewPromoService(promoCodeRepository, userRepository, billingCacheService, client, apiKeyAuthCacheInvalidator)
|
||||
subscriptionService := service.NewSubscriptionService(groupRepository, userSubscriptionRepository, billingCacheService, client, configConfig)
|
||||
affiliateRepository := repository.NewAffiliateRepository(client, db)
|
||||
affiliateService := service.NewAffiliateService(affiliateRepository, settingService, apiKeyAuthCacheInvalidator, billingCacheService)
|
||||
authService := service.ProvideAuthService(client, userRepository, redeemCodeRepository, refreshTokenCache, configConfig, settingService, emailService, turnstileService, tencentCaptchaService, aliyunCaptchaService, emailQueueService, promoService, subscriptionService, affiliateService, serviceUserPlatformQuotaRepository)
|
||||
userService := service.NewUserService(userRepository, settingRepository, apiKeyAuthCacheInvalidator, billingCache)
|
||||
authService := service.NewAuthService(client, userRepository, redeemCodeRepository, refreshTokenCache, configConfig, settingService, emailService, turnstileService, emailQueueService, promoService, subscriptionService)
|
||||
userService := service.NewUserService(userRepository, apiKeyAuthCacheInvalidator, billingCache)
|
||||
redeemCache := repository.NewRedeemCache(redisClient)
|
||||
redeemService := service.NewRedeemService(redeemCodeRepository, userRepository, subscriptionService, redeemCache, billingCacheService, client, apiKeyAuthCacheInvalidator, affiliateService)
|
||||
redeemService := service.NewRedeemService(redeemCodeRepository, userRepository, subscriptionService, redeemCache, billingCacheService, client, apiKeyAuthCacheInvalidator)
|
||||
secretEncryptor, err := repository.NewAESEncryptor(configConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
totpCache := repository.NewTotpCache(redisClient)
|
||||
totpService := service.NewTotpService(userRepository, secretEncryptor, totpCache, settingService, emailService, emailQueueService)
|
||||
userAttributeDefinitionRepository := repository.NewUserAttributeDefinitionRepository(client)
|
||||
userAttributeValueRepository := repository.NewUserAttributeValueRepository(client)
|
||||
userAttributeService := service.NewUserAttributeService(userAttributeDefinitionRepository, userAttributeValueRepository)
|
||||
authHandler := handler.NewAuthHandler(configConfig, authService, userService, settingService, promoService, redeemService, totpService, userAttributeService)
|
||||
userHandler := handler.NewUserHandler(userService, authService, emailService, emailCache, affiliateService, serviceUserPlatformQuotaRepository)
|
||||
authHandler := handler.NewAuthHandler(configConfig, authService, userService, settingService, promoService, redeemService, totpService)
|
||||
userHandler := handler.NewUserHandler(userService)
|
||||
apiKeyHandler := handler.NewAPIKeyHandler(apiKeyService)
|
||||
usageLogRepository := repository.NewUsageLogRepository(client, db)
|
||||
usageService := service.NewUsageService(usageLogRepository, userRepository, client, apiKeyAuthCacheInvalidator)
|
||||
opsRepository := repository.NewOpsRepository(db)
|
||||
usageBillingRepository := repository.NewUsageBillingRepository(client, db)
|
||||
gatewayCache := repository.NewGatewayCache(redisClient)
|
||||
schedulerOutboxRepository := repository.NewSchedulerOutboxRepository(db)
|
||||
schedulerSnapshotService := service.ProvideSchedulerSnapshotService(schedulerCache, schedulerOutboxRepository, accountRepository, groupRepository, configConfig)
|
||||
pricingRemoteClient := repository.ProvidePricingRemoteClient(configConfig)
|
||||
pricingService, err := service.ProvidePricingService(configConfig, pricingRemoteClient)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
billingService := service.NewBillingService(configConfig, pricingService)
|
||||
geminiQuotaService := service.NewGeminiQuotaService(configConfig, settingRepository)
|
||||
tempUnschedCache := repository.NewTempUnschedCache(redisClient)
|
||||
timeoutCounterCache := repository.NewTimeoutCounterCache(redisClient)
|
||||
openAI403CounterCache := repository.NewOpenAI403CounterCache(redisClient)
|
||||
geminiTokenCache := repository.NewGeminiTokenCache(redisClient)
|
||||
compositeTokenCacheInvalidator := service.NewCompositeTokenCacheInvalidator(geminiTokenCache)
|
||||
rateLimitService := service.ProvideRateLimitService(accountRepository, usageLogRepository, configConfig, geminiQuotaService, tempUnschedCache, timeoutCounterCache, openAI403CounterCache, settingService, compositeTokenCacheInvalidator)
|
||||
identityCache := repository.NewIdentityCache(redisClient)
|
||||
identityService := service.NewIdentityService(identityCache)
|
||||
httpUpstream := repository.NewHTTPUpstream(configConfig)
|
||||
timingWheelService, err := service.ProvideTimingWheelService()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
deferredService := service.ProvideDeferredService(accountRepository, timingWheelService)
|
||||
claudeOAuthClient := repository.NewClaudeOAuthClient()
|
||||
oAuthService := service.NewOAuthService(proxyRepository, claudeOAuthClient)
|
||||
oAuthRefreshAPI := service.ProvideOAuthRefreshAPI(accountRepository, geminiTokenCache)
|
||||
claudeTokenProvider := service.ProvideClaudeTokenProvider(accountRepository, geminiTokenCache, oAuthService, oAuthRefreshAPI)
|
||||
sessionLimitCache := repository.ProvideSessionLimitCache(redisClient, configConfig)
|
||||
rpmCache := repository.NewRPMCache(redisClient)
|
||||
digestSessionStore := service.NewDigestSessionStore()
|
||||
tlsFingerprintProfileRepository := repository.NewTLSFingerprintProfileRepository(client)
|
||||
tlsFingerprintProfileCache := repository.NewTLSFingerprintProfileCache(redisClient)
|
||||
tlsFingerprintProfileService := service.NewTLSFingerprintProfileService(tlsFingerprintProfileRepository, tlsFingerprintProfileCache)
|
||||
channelRepository := repository.NewChannelRepository(db)
|
||||
channelService := service.NewChannelService(channelRepository, groupRepository, apiKeyAuthCacheInvalidator, pricingService)
|
||||
modelPricingResolver := service.NewModelPricingResolver(channelService, billingService)
|
||||
compositeModelRouteRepository := repository.NewCompositeModelRouteRepository(client)
|
||||
compositeRouteResolver := service.NewCompositeRouteResolver(compositeModelRouteRepository)
|
||||
notificationEmailService := service.NewNotificationEmailService(settingRepository, emailService)
|
||||
balanceNotifyService := service.ProvideBalanceNotifyService(emailService, settingRepository, accountRepository, notificationEmailService)
|
||||
gatewayService := service.NewGatewayService(accountRepository, groupRepository, usageLogRepository, usageBillingRepository, userRepository, userSubscriptionRepository, userGroupRateRepository, gatewayCache, configConfig, schedulerSnapshotService, concurrencyService, billingService, rateLimitService, billingCacheService, identityService, httpUpstream, deferredService, claudeTokenProvider, sessionLimitCache, rpmCache, digestSessionStore, settingService, tlsFingerprintProfileService, channelService, modelPricingResolver, compositeRouteResolver, balanceNotifyService, serviceUserPlatformQuotaRepository)
|
||||
openAIOAuthClient := repository.NewOpenAIOAuthClient()
|
||||
privacyClientFactory := providePrivacyClientFactory()
|
||||
openAIOAuthService := service.ProvideOpenAIOAuthService(proxyRepository, openAIOAuthClient, privacyClientFactory)
|
||||
openAITokenProvider := service.ProvideOpenAITokenProvider(accountRepository, geminiTokenCache, openAIOAuthService, oAuthRefreshAPI)
|
||||
grokOAuthClient := repository.NewGrokOAuthClient()
|
||||
grokOAuthService := service.NewGrokOAuthService(proxyRepository, grokOAuthClient)
|
||||
grokTokenProvider := service.ProvideGrokTokenProvider(accountRepository, geminiTokenCache, grokOAuthService, oAuthRefreshAPI, tempUnschedCache)
|
||||
openAIGatewayService := service.NewOpenAIGatewayService(accountRepository, usageLogRepository, usageBillingRepository, userRepository, userSubscriptionRepository, userGroupRateRepository, gatewayCache, configConfig, schedulerSnapshotService, concurrencyService, billingService, rateLimitService, billingCacheService, httpUpstream, deferredService, openAITokenProvider, grokTokenProvider, modelPricingResolver, channelService, balanceNotifyService, settingService, serviceUserPlatformQuotaRepository)
|
||||
geminiOAuthClient := repository.NewGeminiOAuthClient(configConfig)
|
||||
geminiCliCodeAssistClient := repository.NewGeminiCliCodeAssistClient()
|
||||
driveClient := repository.NewGeminiDriveClient()
|
||||
geminiOAuthService := service.NewGeminiOAuthService(proxyRepository, geminiOAuthClient, geminiCliCodeAssistClient, driveClient, configConfig)
|
||||
geminiTokenProvider := service.ProvideGeminiTokenProvider(accountRepository, geminiTokenCache, geminiOAuthService, oAuthRefreshAPI)
|
||||
antigravityOAuthService := service.NewAntigravityOAuthService(proxyRepository)
|
||||
antigravityTokenProvider := service.ProvideAntigravityTokenProvider(accountRepository, geminiTokenCache, antigravityOAuthService, oAuthRefreshAPI, tempUnschedCache)
|
||||
internal500CounterCache := repository.NewInternal500CounterCache(redisClient)
|
||||
antigravityGatewayService := service.NewAntigravityGatewayService(accountRepository, gatewayCache, schedulerSnapshotService, antigravityTokenProvider, rateLimitService, httpUpstream, settingService, internal500CounterCache)
|
||||
geminiMessagesCompatService := service.NewGeminiMessagesCompatService(accountRepository, groupRepository, gatewayCache, schedulerSnapshotService, geminiTokenProvider, rateLimitService, httpUpstream, antigravityGatewayService, configConfig)
|
||||
opsSystemLogSink := service.ProvideOpsSystemLogSink(opsRepository)
|
||||
authCacheInvalidationOutboxRepository := repository.NewAuthCacheInvalidationOutboxRepository(db)
|
||||
authCacheInvalidationWorker := service.ProvideAuthCacheInvalidationWorker(authCacheInvalidationOutboxRepository, apiKeyCache, apiKeyService)
|
||||
opsService := service.ProvideOpsService(opsRepository, settingRepository, configConfig, accountRepository, userRepository, concurrencyService, gatewayService, openAIGatewayService, geminiMessagesCompatService, antigravityGatewayService, opsSystemLogSink, settingService, authCacheInvalidationWorker, apiKeyService)
|
||||
usageHandler := handler.NewUsageHandler(usageService, apiKeyService, opsService, settingService)
|
||||
usageHandler := handler.NewUsageHandler(usageService, apiKeyService)
|
||||
redeemHandler := handler.NewRedeemHandler(redeemService)
|
||||
subscriptionHandler := handler.NewSubscriptionHandler(subscriptionService)
|
||||
announcementRepository := repository.NewAnnouncementRepository(client)
|
||||
announcementReadRepository := repository.NewAnnouncementReadRepository(client)
|
||||
announcementService := service.NewAnnouncementService(announcementRepository, announcementReadRepository, userRepository, userSubscriptionRepository)
|
||||
announcementHandler := handler.NewAnnouncementHandler(announcementService)
|
||||
channelMonitorRepository := repository.NewChannelMonitorRepository(client, db)
|
||||
channelMonitorService := service.ProvideChannelMonitorService(channelMonitorRepository, secretEncryptor)
|
||||
channelMonitorUserHandler := handler.NewChannelMonitorUserHandler(channelMonitorService, settingService)
|
||||
dashboardAggregationRepository := repository.NewDashboardAggregationRepository(db)
|
||||
dashboardStatsCache := repository.NewDashboardCache(redisClient, configConfig)
|
||||
dashboardService := service.NewDashboardService(usageLogRepository, dashboardAggregationRepository, dashboardStatsCache, configConfig)
|
||||
leaderLockCache := repository.NewLeaderLockCache(redisClient)
|
||||
dashboardAggregationService := service.ProvideDashboardAggregationService(dashboardAggregationRepository, timingWheelService, leaderLockCache, db, configConfig)
|
||||
dashboardHandler := admin.NewDashboardHandler(dashboardService, dashboardAggregationService)
|
||||
adminGroupRepository := repository.NewAdminGroupRepository(client, db)
|
||||
adminAccountRepository := repository.NewAdminAccountRepository(client, db, schedulerCache)
|
||||
proxyExitInfoProber := repository.NewProxyExitInfoProber(configConfig)
|
||||
proxyLatencyCache := repository.NewProxyLatencyCache(redisClient)
|
||||
adminService := service.NewAdminService(userRepository, adminGroupRepository, adminAccountRepository, proxyRepository, apiKeyRepository, redeemCodeRepository, userGroupRateRepository, userRPMCache, billingCacheService, proxyExitInfoProber, proxyLatencyCache, apiKeyAuthCacheInvalidator, client, settingService, subscriptionService, userSubscriptionRepository, privacyClientFactory, openAIGatewayService, affiliateService, compositeModelRouteRepository, compositeRouteResolver)
|
||||
adminUserHandler := admin.NewUserHandler(adminService, concurrencyService, serviceUserPlatformQuotaRepository, billingCache, totpService, userService, settingService)
|
||||
groupCapacityService := service.NewGroupCapacityService(accountRepository, groupRepository, concurrencyService, sessionLimitCache, rpmCache)
|
||||
groupHandler := admin.NewGroupHandler(adminService, dashboardService, groupCapacityService)
|
||||
claudeUsageFetcher := repository.NewClaudeUsageFetcher(httpUpstream)
|
||||
antigravityQuotaFetcher := service.NewAntigravityQuotaFetcher(proxyRepository)
|
||||
grokQuotaFetcher := service.NewGrokQuotaFetcher()
|
||||
grokQuotaService := service.ProvideGrokQuotaService(accountRepository, proxyRepository, grokTokenProvider, httpUpstream, configConfig, usageLogRepository)
|
||||
openAIQuotaService := service.ProvideOpenAIQuotaService(accountRepository, proxyRepository, openAITokenProvider, privacyClientFactory, openAIGatewayService)
|
||||
usageCache := service.NewUsageCache()
|
||||
accountUsageService := service.ProvideAccountUsageService(accountRepository, usageLogRepository, claudeUsageFetcher, geminiQuotaService, antigravityQuotaFetcher, grokQuotaFetcher, grokQuotaService, openAIQuotaService, usageCache, identityCache, tlsFingerprintProfileService, openAIGatewayService)
|
||||
accountTestService := service.ProvideAccountTestService(accountRepository, geminiTokenProvider, claudeTokenProvider, grokTokenProvider, antigravityGatewayService, httpUpstream, configConfig, tlsFingerprintProfileService, openAIGatewayService)
|
||||
crsSyncService := service.NewCRSSyncService(accountRepository, proxyRepository, oAuthService, openAIOAuthService, geminiOAuthService, configConfig)
|
||||
accountHandler := admin.ProvideAccountHandler(adminService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, rateLimitService, accountUsageService, accountTestService, concurrencyService, crsSyncService, sessionLimitCache, rpmCache, compositeTokenCacheInvalidator, grokQuotaService)
|
||||
adminAnnouncementHandler := admin.NewAnnouncementHandler(announcementService)
|
||||
dataManagementService := service.NewDataManagementService()
|
||||
dataManagementHandler := admin.NewDataManagementHandler(dataManagementService)
|
||||
backupObjectStoreFactory := repository.NewS3BackupStoreFactory()
|
||||
dbDumper := repository.NewPgDumper(configConfig)
|
||||
backupService := service.ProvideBackupService(settingRepository, configConfig, secretEncryptor, backupObjectStoreFactory, dbDumper)
|
||||
imageStorageFactory := repository.ProvideImageStorageFactory()
|
||||
imageStorageSettingService := service.ProvideImageStorageSettingService(settingRepository, secretEncryptor, backupService, imageStorageFactory, configConfig)
|
||||
backupHandler := admin.NewBackupHandler(backupService, userService, imageStorageSettingService)
|
||||
oAuthHandler := admin.NewOAuthHandler(oAuthService)
|
||||
openAIOAuthHandler := admin.NewOpenAIOAuthHandler(openAIOAuthService, adminService, openAIQuotaService, rateLimitService)
|
||||
geminiOAuthHandler := admin.NewGeminiOAuthHandler(geminiOAuthService)
|
||||
antigravityOAuthHandler := admin.NewAntigravityOAuthHandler(antigravityOAuthService)
|
||||
tokenRefreshService := service.ProvideTokenRefreshService(accountRepository, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, compositeTokenCacheInvalidator, schedulerCache, configConfig, tempUnschedCache, privacyClientFactory, proxyRepository, oAuthRefreshAPI, openAIGatewayService)
|
||||
grokOAuthHandler := admin.NewGrokOAuthHandler(grokOAuthService, adminService, grokQuotaService, tokenRefreshService)
|
||||
proxyHandler := admin.NewProxyHandler(adminService)
|
||||
adminRedeemHandler := admin.NewRedeemHandler(adminService, redeemService)
|
||||
promoHandler := admin.NewPromoHandler(promoService)
|
||||
encryptionKey, err := payment.ProvideEncryptionKey(configConfig)
|
||||
timingWheelService, err := service.ProvideTimingWheelService()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
paymentConfigService := service.ProvidePaymentConfigService(client, settingRepository, encryptionKey)
|
||||
registry := payment.ProvideRegistry()
|
||||
defaultLoadBalancer := payment.ProvideDefaultLoadBalancer(client, encryptionKey)
|
||||
paymentService := service.ProvidePaymentService(client, registry, defaultLoadBalancer, redeemService, subscriptionService, paymentConfigService, userRepository, groupRepository, affiliateService, notificationEmailService)
|
||||
settingHandler := handler.ProvideAdminSettingHandler(settingService, emailService, turnstileService, aliyunCaptchaService, opsService, paymentConfigService, paymentService, userAttributeService, notificationEmailService, totpService, userService)
|
||||
dashboardAggregationService := service.ProvideDashboardAggregationService(dashboardAggregationRepository, timingWheelService, configConfig)
|
||||
dashboardHandler := admin.NewDashboardHandler(dashboardService, dashboardAggregationService)
|
||||
schedulerCache := repository.NewSchedulerCache(redisClient)
|
||||
accountRepository := repository.NewAccountRepository(client, db, schedulerCache)
|
||||
soraAccountRepository := repository.NewSoraAccountRepository(db)
|
||||
proxyRepository := repository.NewProxyRepository(client, db)
|
||||
proxyExitInfoProber := repository.NewProxyExitInfoProber(configConfig)
|
||||
proxyLatencyCache := repository.NewProxyLatencyCache(redisClient)
|
||||
adminService := service.NewAdminService(userRepository, groupRepository, accountRepository, soraAccountRepository, proxyRepository, apiKeyRepository, redeemCodeRepository, userGroupRateRepository, billingCacheService, proxyExitInfoProber, proxyLatencyCache, apiKeyAuthCacheInvalidator, client, settingService, subscriptionService, userSubscriptionRepository)
|
||||
concurrencyCache := repository.ProvideConcurrencyCache(redisClient, configConfig)
|
||||
concurrencyService := service.ProvideConcurrencyService(concurrencyCache, accountRepository, configConfig)
|
||||
adminUserHandler := admin.NewUserHandler(adminService, concurrencyService)
|
||||
groupHandler := admin.NewGroupHandler(adminService)
|
||||
claudeOAuthClient := repository.NewClaudeOAuthClient()
|
||||
oAuthService := service.NewOAuthService(proxyRepository, claudeOAuthClient)
|
||||
openAIOAuthClient := repository.NewOpenAIOAuthClient()
|
||||
openAIOAuthService := service.NewOpenAIOAuthService(proxyRepository, openAIOAuthClient)
|
||||
geminiOAuthClient := repository.NewGeminiOAuthClient(configConfig)
|
||||
geminiCliCodeAssistClient := repository.NewGeminiCliCodeAssistClient()
|
||||
driveClient := repository.NewGeminiDriveClient()
|
||||
geminiOAuthService := service.NewGeminiOAuthService(proxyRepository, geminiOAuthClient, geminiCliCodeAssistClient, driveClient, configConfig)
|
||||
antigravityOAuthService := service.NewAntigravityOAuthService(proxyRepository)
|
||||
geminiQuotaService := service.NewGeminiQuotaService(configConfig, settingRepository)
|
||||
tempUnschedCache := repository.NewTempUnschedCache(redisClient)
|
||||
timeoutCounterCache := repository.NewTimeoutCounterCache(redisClient)
|
||||
geminiTokenCache := repository.NewGeminiTokenCache(redisClient)
|
||||
compositeTokenCacheInvalidator := service.NewCompositeTokenCacheInvalidator(geminiTokenCache)
|
||||
rateLimitService := service.ProvideRateLimitService(accountRepository, usageLogRepository, configConfig, geminiQuotaService, tempUnschedCache, timeoutCounterCache, settingService, compositeTokenCacheInvalidator)
|
||||
httpUpstream := repository.NewHTTPUpstream(configConfig)
|
||||
claudeUsageFetcher := repository.NewClaudeUsageFetcher(httpUpstream)
|
||||
antigravityQuotaFetcher := service.NewAntigravityQuotaFetcher(proxyRepository)
|
||||
usageCache := service.NewUsageCache()
|
||||
identityCache := repository.NewIdentityCache(redisClient)
|
||||
accountUsageService := service.NewAccountUsageService(accountRepository, usageLogRepository, claudeUsageFetcher, geminiQuotaService, antigravityQuotaFetcher, usageCache, identityCache)
|
||||
geminiTokenProvider := service.NewGeminiTokenProvider(accountRepository, geminiTokenCache, geminiOAuthService)
|
||||
gatewayCache := repository.NewGatewayCache(redisClient)
|
||||
schedulerOutboxRepository := repository.NewSchedulerOutboxRepository(db)
|
||||
schedulerSnapshotService := service.ProvideSchedulerSnapshotService(schedulerCache, schedulerOutboxRepository, accountRepository, groupRepository, configConfig)
|
||||
antigravityTokenProvider := service.NewAntigravityTokenProvider(accountRepository, geminiTokenCache, antigravityOAuthService)
|
||||
antigravityGatewayService := service.NewAntigravityGatewayService(accountRepository, gatewayCache, schedulerSnapshotService, antigravityTokenProvider, rateLimitService, httpUpstream, settingService)
|
||||
accountTestService := service.NewAccountTestService(accountRepository, geminiTokenProvider, antigravityGatewayService, httpUpstream, configConfig)
|
||||
crsSyncService := service.NewCRSSyncService(accountRepository, proxyRepository, oAuthService, openAIOAuthService, geminiOAuthService, configConfig)
|
||||
sessionLimitCache := repository.ProvideSessionLimitCache(redisClient, configConfig)
|
||||
rpmCache := repository.NewRPMCache(redisClient)
|
||||
accountHandler := admin.NewAccountHandler(adminService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, rateLimitService, accountUsageService, accountTestService, concurrencyService, crsSyncService, sessionLimitCache, rpmCache, compositeTokenCacheInvalidator)
|
||||
adminAnnouncementHandler := admin.NewAnnouncementHandler(announcementService)
|
||||
dataManagementService := service.NewDataManagementService()
|
||||
dataManagementHandler := admin.NewDataManagementHandler(dataManagementService)
|
||||
oAuthHandler := admin.NewOAuthHandler(oAuthService)
|
||||
openAIOAuthHandler := admin.NewOpenAIOAuthHandler(openAIOAuthService, adminService)
|
||||
geminiOAuthHandler := admin.NewGeminiOAuthHandler(geminiOAuthService)
|
||||
antigravityOAuthHandler := admin.NewAntigravityOAuthHandler(antigravityOAuthService)
|
||||
proxyHandler := admin.NewProxyHandler(adminService)
|
||||
adminRedeemHandler := admin.NewRedeemHandler(adminService, redeemService)
|
||||
promoHandler := admin.NewPromoHandler(promoService)
|
||||
opsRepository := repository.NewOpsRepository(db)
|
||||
pricingRemoteClient := repository.ProvidePricingRemoteClient(configConfig)
|
||||
pricingService, err := service.ProvidePricingService(configConfig, pricingRemoteClient)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
billingService := service.NewBillingService(configConfig, pricingService)
|
||||
identityService := service.NewIdentityService(identityCache)
|
||||
deferredService := service.ProvideDeferredService(accountRepository, timingWheelService)
|
||||
claudeTokenProvider := service.NewClaudeTokenProvider(accountRepository, geminiTokenCache, oAuthService)
|
||||
digestSessionStore := service.NewDigestSessionStore()
|
||||
gatewayService := service.NewGatewayService(accountRepository, groupRepository, usageLogRepository, userRepository, userSubscriptionRepository, userGroupRateRepository, gatewayCache, configConfig, schedulerSnapshotService, concurrencyService, billingService, rateLimitService, billingCacheService, identityService, httpUpstream, deferredService, claudeTokenProvider, sessionLimitCache, rpmCache, digestSessionStore, settingService)
|
||||
openAITokenProvider := service.NewOpenAITokenProvider(accountRepository, geminiTokenCache, openAIOAuthService)
|
||||
openAIGatewayService := service.NewOpenAIGatewayService(accountRepository, usageLogRepository, userRepository, userSubscriptionRepository, userGroupRateRepository, gatewayCache, configConfig, schedulerSnapshotService, concurrencyService, billingService, rateLimitService, billingCacheService, httpUpstream, deferredService, openAITokenProvider)
|
||||
geminiMessagesCompatService := service.NewGeminiMessagesCompatService(accountRepository, groupRepository, gatewayCache, schedulerSnapshotService, geminiTokenProvider, rateLimitService, httpUpstream, antigravityGatewayService, configConfig)
|
||||
opsSystemLogSink := service.ProvideOpsSystemLogSink(opsRepository)
|
||||
opsService := service.NewOpsService(opsRepository, settingRepository, configConfig, accountRepository, userRepository, concurrencyService, gatewayService, openAIGatewayService, geminiMessagesCompatService, antigravityGatewayService, opsSystemLogSink)
|
||||
soraS3Storage := service.NewSoraS3Storage(settingService)
|
||||
settingService.SetOnS3UpdateCallback(soraS3Storage.RefreshClient)
|
||||
soraGenerationRepository := repository.NewSoraGenerationRepository(db)
|
||||
soraQuotaService := service.NewSoraQuotaService(userRepository, groupRepository, settingService)
|
||||
soraGenerationService := service.NewSoraGenerationService(soraGenerationRepository, soraS3Storage, soraQuotaService)
|
||||
settingHandler := admin.NewSettingHandler(settingService, emailService, turnstileService, opsService, soraS3Storage)
|
||||
opsHandler := admin.NewOpsHandler(opsService)
|
||||
updateCache := repository.NewUpdateCache(redisClient)
|
||||
gitHubReleaseClient := repository.ProvideGitHubReleaseClient(configConfig)
|
||||
@@ -239,104 +186,54 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
|
||||
usageCleanupRepository := repository.NewUsageCleanupRepository(client, db)
|
||||
usageCleanupService := service.ProvideUsageCleanupService(usageCleanupRepository, timingWheelService, dashboardAggregationService, configConfig)
|
||||
adminUsageHandler := admin.NewUsageHandler(usageService, apiKeyService, adminService, usageCleanupService)
|
||||
userAttributeDefinitionRepository := repository.NewUserAttributeDefinitionRepository(client)
|
||||
userAttributeValueRepository := repository.NewUserAttributeValueRepository(client)
|
||||
userAttributeService := service.NewUserAttributeService(userAttributeDefinitionRepository, userAttributeValueRepository)
|
||||
userAttributeHandler := admin.NewUserAttributeHandler(userAttributeService)
|
||||
errorPassthroughRepository := repository.NewErrorPassthroughRepository(client)
|
||||
errorPassthroughCache := repository.NewErrorPassthroughCache(redisClient)
|
||||
errorPassthroughService := service.NewErrorPassthroughService(errorPassthroughRepository, errorPassthroughCache)
|
||||
errorPassthroughHandler := admin.NewErrorPassthroughHandler(errorPassthroughService)
|
||||
tlsFingerprintProfileHandler := admin.NewTLSFingerprintProfileHandler(tlsFingerprintProfileService)
|
||||
adminAPIKeyHandler := admin.NewAdminAPIKeyHandler(adminService)
|
||||
scheduledTestPlanRepository := repository.NewScheduledTestPlanRepository(db)
|
||||
scheduledTestResultRepository := repository.NewScheduledTestResultRepository(db)
|
||||
scheduledTestService := service.ProvideScheduledTestService(scheduledTestPlanRepository, scheduledTestResultRepository)
|
||||
scheduledTestHandler := admin.NewScheduledTestHandler(scheduledTestService)
|
||||
channelHandler := admin.NewChannelHandler(channelService, billingService, pricingService)
|
||||
channelMonitorHandler := admin.NewChannelMonitorHandler(channelMonitorService)
|
||||
channelMonitorRequestTemplateRepository := repository.NewChannelMonitorRequestTemplateRepository(client, db)
|
||||
channelMonitorRequestTemplateService := service.NewChannelMonitorRequestTemplateService(channelMonitorRequestTemplateRepository)
|
||||
channelMonitorRequestTemplateHandler := admin.NewChannelMonitorRequestTemplateHandler(channelMonitorRequestTemplateService)
|
||||
contentModerationRepository := repository.NewContentModerationRepository(db)
|
||||
contentModerationHashCache := repository.NewContentModerationHashCache(redisClient)
|
||||
contentModerationService := service.NewContentModerationService(settingRepository, contentModerationRepository, contentModerationHashCache, groupRepository, userRepository, proxyRepository, apiKeyAuthCacheInvalidator, emailService)
|
||||
contentModerationHandler := admin.NewContentModerationHandler(contentModerationService)
|
||||
configManager := securityaudit.NewConfigManager(db, settingRepository, redisClient, secretEncryptor, configConfig)
|
||||
postgreSQLRepository := securityaudit.NewPostgreSQLRepository(db)
|
||||
redisPayloadStore := securityaudit.NewRedisPayloadStore(redisClient)
|
||||
openAICompatibleScanner := securityaudit.NewOpenAICompatibleScanner()
|
||||
atomicMetrics := securityaudit.NewAtomicMetrics()
|
||||
promptService := securityaudit.NewPromptService(configManager, postgreSQLRepository, redisPayloadStore, openAICompatibleScanner, atomicMetrics)
|
||||
promptAdminHandler := securityaudit.NewPromptAdminHandler(promptService)
|
||||
paymentHandler := admin.NewPaymentHandler(paymentService, paymentConfigService)
|
||||
affiliateHandler := admin.NewAffiliateHandler(affiliateService, adminService)
|
||||
complianceHandler := admin.NewComplianceHandler(settingService)
|
||||
auditLogRepository := repository.NewAuditLogRepository(db)
|
||||
auditLogService := service.ProvideAuditLogService(auditLogRepository, settingService)
|
||||
auditLogHandler := admin.NewAuditLogHandler(auditLogService, totpService)
|
||||
upstreamBillingProbeService := service.ProvideUpstreamBillingProbeService(accountRepository, accountTestService, settingService, leaderLockCache, db)
|
||||
ollamaCloudUsageService := service.ProvideOllamaCloudUsageService(accountRepository, httpUpstream, settingService, secretEncryptor, configConfig, leaderLockCache, db)
|
||||
adminHandlers := handler.ProvideAdminHandlers(dashboardHandler, adminUserHandler, groupHandler, accountHandler, adminAnnouncementHandler, dataManagementHandler, backupHandler, oAuthHandler, openAIOAuthHandler, geminiOAuthHandler, antigravityOAuthHandler, grokOAuthHandler, proxyHandler, adminRedeemHandler, promoHandler, settingHandler, opsHandler, systemHandler, adminSubscriptionHandler, adminUsageHandler, userAttributeHandler, errorPassthroughHandler, tlsFingerprintProfileHandler, adminAPIKeyHandler, scheduledTestHandler, channelHandler, channelMonitorHandler, channelMonitorRequestTemplateHandler, contentModerationHandler, promptAdminHandler, paymentHandler, affiliateHandler, complianceHandler, auditLogHandler, upstreamBillingProbeService, ollamaCloudUsageService)
|
||||
adminHandlers := handler.ProvideAdminHandlers(dashboardHandler, adminUserHandler, groupHandler, accountHandler, adminAnnouncementHandler, dataManagementHandler, oAuthHandler, openAIOAuthHandler, geminiOAuthHandler, antigravityOAuthHandler, proxyHandler, adminRedeemHandler, promoHandler, settingHandler, opsHandler, systemHandler, adminSubscriptionHandler, adminUsageHandler, userAttributeHandler, errorPassthroughHandler, adminAPIKeyHandler, scheduledTestHandler)
|
||||
usageRecordWorkerPool := service.NewUsageRecordWorkerPool(configConfig)
|
||||
userMsgQueueCache := repository.NewUserMsgQueueCache(redisClient)
|
||||
userMessageQueueService := service.ProvideUserMessageQueueService(userMsgQueueCache, rpmCache, configConfig)
|
||||
legacyEngine := securityaudit.NewLegacyModerationAdapter(contentModerationService)
|
||||
coordinator := securityaudit.NewCoordinator(legacyEngine, promptService)
|
||||
gatewayHandler := handler.ProvideGatewayHandler(gatewayService, openAIGatewayService, geminiMessagesCompatService, antigravityGatewayService, userService, concurrencyService, billingCacheService, usageService, apiKeyService, usageRecordWorkerPool, errorPassthroughService, contentModerationService, userMessageQueueService, configConfig, settingService, coordinator)
|
||||
openAIGatewayHandler := handler.ProvideOpenAIGatewayHandler(openAIGatewayService, concurrencyService, billingCacheService, apiKeyService, usageRecordWorkerPool, errorPassthroughService, contentModerationService, opsService, grokQuotaService, configConfig, coordinator)
|
||||
handlerSettingHandler := handler.ProvideSettingHandler(settingService, buildInfo, notificationEmailService)
|
||||
gatewayHandler := handler.NewGatewayHandler(gatewayService, geminiMessagesCompatService, antigravityGatewayService, userService, concurrencyService, billingCacheService, usageService, apiKeyService, usageRecordWorkerPool, errorPassthroughService, userMessageQueueService, configConfig, settingService)
|
||||
openAIGatewayHandler := handler.NewOpenAIGatewayHandler(openAIGatewayService, concurrencyService, billingCacheService, apiKeyService, usageRecordWorkerPool, errorPassthroughService, configConfig)
|
||||
soraSDKClient := service.ProvideSoraSDKClient(configConfig, httpUpstream, openAITokenProvider, accountRepository, soraAccountRepository)
|
||||
soraMediaStorage := service.ProvideSoraMediaStorage(configConfig)
|
||||
soraGatewayService := service.NewSoraGatewayService(soraSDKClient, rateLimitService, httpUpstream, configConfig)
|
||||
soraClientHandler := handler.NewSoraClientHandler(soraGenerationService, soraQuotaService, soraS3Storage, soraGatewayService, gatewayService, soraMediaStorage, apiKeyService)
|
||||
soraGatewayHandler := handler.NewSoraGatewayHandler(gatewayService, soraGatewayService, concurrencyService, billingCacheService, usageRecordWorkerPool, configConfig)
|
||||
handlerSettingHandler := handler.ProvideSettingHandler(settingService, buildInfo)
|
||||
totpHandler := handler.NewTotpHandler(totpService)
|
||||
passkeyRepository := repository.NewPasskeyRepository(db)
|
||||
passkeySessionStore := repository.NewPasskeySessionStore(redisClient)
|
||||
passkeyService, err := service.NewPasskeyService(configConfig, passkeyRepository, passkeySessionStore, userRepository)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
passkeyHandler := handler.NewPasskeyHandler(passkeyService, authService, settingService)
|
||||
handlerPaymentHandler := handler.NewPaymentHandler(paymentService, paymentConfigService)
|
||||
paymentWebhookHandler := handler.NewPaymentWebhookHandler(paymentService, registry)
|
||||
availableChannelHandler := handler.NewAvailableChannelHandler(channelService, apiKeyService, settingService)
|
||||
modelPlazaHandler := handler.NewModelPlazaHandler(channelService, apiKeyService, settingService)
|
||||
imageTaskStore := repository.NewImageTaskStore(redisClient)
|
||||
imageTaskService := service.ProvideImageTaskService(imageTaskStore, imageStorageSettingService)
|
||||
asyncImageHandler := handler.NewAsyncImageHandler(imageTaskService, openAIGatewayHandler)
|
||||
batchImageRepository := repository.NewBatchImageRepository(db)
|
||||
batchImageQueue := repository.NewBatchImageQueue(redisClient, configConfig)
|
||||
batchImageModelPricingResolver := service.ProvideBatchImageModelPricingResolver(modelPricingResolver)
|
||||
batchImagePublicService := service.NewBatchImagePublicService(batchImageRepository, accountRepository, groupRepository, userGroupRateRepository, batchImageQueue, batchImageModelPricingResolver, usageBillingRepository, apiKeyAuthCacheInvalidator, configConfig)
|
||||
batchImageDownloadLimiter := repository.NewBatchImageDownloadLimiter(redisClient, configConfig)
|
||||
batchImageDownloadService := service.NewBatchImageDownloadService(batchImageRepository, accountRepository, batchImageDownloadLimiter, configConfig)
|
||||
batchImageCleanupService := service.ProvideBatchImageCleanupService(batchImageRepository, accountRepository, configConfig)
|
||||
batchImageHandler := handler.ProvideBatchImageHandler(batchImagePublicService, batchImageDownloadService, batchImageCleanupService, openAIGatewayHandler)
|
||||
idempotencyCoordinator := service.ProvideIdempotencyCoordinator(idempotencyRepository, configConfig)
|
||||
idempotencyCleanupService := service.ProvideIdempotencyCleanupService(idempotencyRepository, configConfig)
|
||||
handlers := handler.ProvideHandlers(authHandler, userHandler, apiKeyHandler, usageHandler, redeemHandler, subscriptionHandler, announcementHandler, channelMonitorUserHandler, adminHandlers, gatewayHandler, openAIGatewayHandler, handlerSettingHandler, totpHandler, passkeyHandler, handlerPaymentHandler, paymentWebhookHandler, availableChannelHandler, modelPlazaHandler, asyncImageHandler, batchImageHandler, idempotencyCoordinator, idempotencyCleanupService)
|
||||
jwtAuthMiddleware := middleware.NewJWTAuthMiddleware(authService, userService, settingService, auditLogService)
|
||||
optionalJWTAuthMiddleware := middleware.NewOptionalJWTAuthMiddleware(authService, userService, settingService, auditLogService)
|
||||
adminAuthMiddleware := middleware.NewAdminAuthMiddleware(authService, userService, settingService, auditLogService)
|
||||
handlers := handler.ProvideHandlers(authHandler, userHandler, apiKeyHandler, usageHandler, redeemHandler, subscriptionHandler, announcementHandler, adminHandlers, gatewayHandler, openAIGatewayHandler, soraGatewayHandler, soraClientHandler, handlerSettingHandler, totpHandler, idempotencyCoordinator, idempotencyCleanupService)
|
||||
jwtAuthMiddleware := middleware.NewJWTAuthMiddleware(authService, userService)
|
||||
adminAuthMiddleware := middleware.NewAdminAuthMiddleware(authService, userService, settingService)
|
||||
apiKeyAuthMiddleware := middleware.NewAPIKeyAuthMiddleware(apiKeyService, subscriptionService, configConfig)
|
||||
auditLogMiddleware := middleware.NewAuditLogMiddleware(auditLogService)
|
||||
stepUpAuthMiddleware := middleware.NewStepUpAuthMiddleware(totpService, userService, settingService)
|
||||
engine := server.ProvideRouter(configConfig, handlers, jwtAuthMiddleware, optionalJWTAuthMiddleware, adminAuthMiddleware, apiKeyAuthMiddleware, auditLogMiddleware, stepUpAuthMiddleware, apiKeyService, subscriptionService, opsService, settingService, compositeRouteResolver, redisClient)
|
||||
engine := server.ProvideRouter(configConfig, handlers, jwtAuthMiddleware, adminAuthMiddleware, apiKeyAuthMiddleware, apiKeyService, subscriptionService, opsService, settingService, redisClient)
|
||||
httpServer := server.ProvideHTTPServer(configConfig, engine)
|
||||
opsMetricsCollector := service.ProvideOpsMetricsCollector(opsRepository, settingRepository, accountRepository, concurrencyService, db, redisClient, configConfig)
|
||||
opsAggregationService := service.ProvideOpsAggregationService(opsRepository, settingRepository, db, redisClient, configConfig)
|
||||
opsAlertEvaluatorService := service.ProvideOpsAlertEvaluatorService(opsService, opsRepository, emailService, redisClient, configConfig, proxyRepository)
|
||||
opsCleanupService := service.ProvideOpsCleanupService(opsRepository, db, redisClient, configConfig, channelMonitorService, settingRepository, opsService)
|
||||
opsAlertEvaluatorService := service.ProvideOpsAlertEvaluatorService(opsService, opsRepository, emailService, redisClient, configConfig)
|
||||
opsCleanupService := service.ProvideOpsCleanupService(opsRepository, db, redisClient, configConfig)
|
||||
opsScheduledReportService := service.ProvideOpsScheduledReportService(opsService, userService, emailService, redisClient, configConfig)
|
||||
opsIngressRejectAggregator := service.ProvideOpsIngressRejectAggregator(opsRepository, opsService)
|
||||
soraMediaCleanupService := service.ProvideSoraMediaCleanupService(soraMediaStorage, configConfig)
|
||||
tokenRefreshService := service.ProvideTokenRefreshService(accountRepository, soraAccountRepository, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, compositeTokenCacheInvalidator, schedulerCache, configConfig, tempUnschedCache)
|
||||
accountExpiryService := service.ProvideAccountExpiryService(accountRepository)
|
||||
openAICodexVersionSyncService := service.ProvideOpenAICodexVersionSyncService(settingRepository, settingService, gitHubReleaseClient)
|
||||
proxyExpiryService := service.ProvideProxyExpiryService(proxyRepository)
|
||||
subscriptionExpiryService := service.ProvideSubscriptionExpiryService(userSubscriptionRepository, settingRepository, notificationEmailService, leaderLockCache, db)
|
||||
batchImageWorkerRuntime := service.ProvideBatchImageWorkerRuntime(batchImageRepository, accountRepository, batchImageQueue, usageBillingRepository, usageLogRepository, batchImageModelPricingResolver, apiKeyAuthCacheInvalidator, configConfig)
|
||||
subscriptionExpiryService := service.ProvideSubscriptionExpiryService(userSubscriptionRepository)
|
||||
scheduledTestRunnerService := service.ProvideScheduledTestRunnerService(scheduledTestPlanRepository, scheduledTestService, accountTestService, rateLimitService, configConfig)
|
||||
paymentOrderExpiryService := service.ProvidePaymentOrderExpiryService(paymentService, leaderLockCache, db)
|
||||
channelMonitorRunner := service.ProvideChannelMonitorRunner(channelMonitorService, settingService)
|
||||
userPlatformQuotaUsageFlusher := service.ProvideUserPlatformQuotaUsageFlusher(configConfig, billingCache, serviceUserPlatformQuotaRepository, timingWheelService)
|
||||
v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, opsService, opsIngressRejectAggregator, apiKeyService, authCacheInvalidationWorker, schedulerSnapshotService, tokenRefreshService, accountExpiryService, openAICodexVersionSyncService, proxyExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, batchImageCleanupService, batchImageWorkerRuntime, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, grokOAuthService, openAIGatewayService, scheduledTestRunnerService, backupService, paymentOrderExpiryService, channelMonitorRunner, userPlatformQuotaUsageFlusher, upstreamBillingProbeService, ollamaCloudUsageService, auditLogService, promptService)
|
||||
v := provideCleanup(client, redisClient, opsMetricsCollector, opsAggregationService, opsAlertEvaluatorService, opsCleanupService, opsScheduledReportService, opsSystemLogSink, soraMediaCleanupService, schedulerSnapshotService, tokenRefreshService, accountExpiryService, subscriptionExpiryService, usageCleanupService, idempotencyCleanupService, pricingService, emailQueueService, billingCacheService, usageRecordWorkerPool, subscriptionService, oAuthService, openAIOAuthService, geminiOAuthService, antigravityOAuthService, openAIGatewayService, scheduledTestRunnerService)
|
||||
application := &Application{
|
||||
Server: httpServer,
|
||||
PromptAudit: promptService,
|
||||
Cleanup: v,
|
||||
Server: httpServer,
|
||||
Cleanup: v,
|
||||
}
|
||||
return application, nil
|
||||
}
|
||||
@@ -344,13 +241,8 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
|
||||
// wire.go:
|
||||
|
||||
type Application struct {
|
||||
Server *http.Server
|
||||
PromptAudit *securityaudit.PromptService
|
||||
Cleanup func()
|
||||
}
|
||||
|
||||
func providePrivacyClientFactory() service.PrivacyClientFactory {
|
||||
return repository.CreatePrivacyReqClient
|
||||
Server *http.Server
|
||||
Cleanup func()
|
||||
}
|
||||
|
||||
func provideServiceBuildInfo(buildInfo handler.BuildInfo) service.BuildInfo {
|
||||
@@ -369,20 +261,13 @@ func provideCleanup(
|
||||
opsCleanup *service.OpsCleanupService,
|
||||
opsScheduledReport *service.OpsScheduledReportService,
|
||||
opsSystemLogSink *service.OpsSystemLogSink,
|
||||
opsService *service.OpsService,
|
||||
opsIngressReject *service.OpsIngressRejectAggregator,
|
||||
apiKeyService *service.APIKeyService,
|
||||
authCacheInvalidationWorker *service.AuthCacheInvalidationWorker,
|
||||
soraMediaCleanup *service.SoraMediaCleanupService,
|
||||
schedulerSnapshot *service.SchedulerSnapshotService,
|
||||
tokenRefresh *service.TokenRefreshService,
|
||||
accountExpiry *service.AccountExpiryService,
|
||||
codexVersionSync *service.OpenAICodexVersionSyncService,
|
||||
proxyExpiry *service.ProxyExpiryService,
|
||||
subscriptionExpiry *service.SubscriptionExpiryService,
|
||||
usageCleanup *service.UsageCleanupService,
|
||||
idempotencyCleanup *service.IdempotencyCleanupService,
|
||||
batchImageCleanup *service.BatchImageCleanupService,
|
||||
batchImageWorker *service.BatchImageWorkerRuntime,
|
||||
pricing *service.PricingService,
|
||||
emailQueue *service.EmailQueueService,
|
||||
billingCache *service.BillingCacheService,
|
||||
@@ -392,17 +277,8 @@ func provideCleanup(
|
||||
openaiOAuth *service.OpenAIOAuthService,
|
||||
geminiOAuth *service.GeminiOAuthService,
|
||||
antigravityOAuth *service.AntigravityOAuthService,
|
||||
grokOAuth *service.GrokOAuthService,
|
||||
openAIGateway *service.OpenAIGatewayService,
|
||||
scheduledTestRunner *service.ScheduledTestRunnerService,
|
||||
backupSvc *service.BackupService,
|
||||
paymentOrderExpiry *service.PaymentOrderExpiryService,
|
||||
channelMonitorRunner *service.ChannelMonitorRunner,
|
||||
quotaFlusher *service.UserPlatformQuotaUsageFlusher,
|
||||
upstreamBillingProbe *service.UpstreamBillingProbeService,
|
||||
ollamaCloudUsage *service.OllamaCloudUsageService,
|
||||
auditLog *service.AuditLogService,
|
||||
promptAudit *securityaudit.PromptService,
|
||||
) func() {
|
||||
return func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
@@ -414,36 +290,6 @@ func provideCleanup(
|
||||
}
|
||||
|
||||
parallelSteps := []cleanupStep{
|
||||
{"OpsIngressRejectAggregator", func() error {
|
||||
if opsIngressReject != nil {
|
||||
opsIngressReject.Stop()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"AuthCacheInvalidationWorker", func() error {
|
||||
if authCacheInvalidationWorker != nil {
|
||||
authCacheInvalidationWorker.Stop()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"AuthCacheInvalidationSubscriber", func() error {
|
||||
if apiKeyService != nil {
|
||||
apiKeyService.StopAuthCacheInvalidationSubscriber()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"OpsRuntimeSettingsRefresh", func() error {
|
||||
if opsService != nil {
|
||||
opsService.StopRuntimeSettingsRefresh()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"PromptAuditService", func() error {
|
||||
if promptAudit != nil {
|
||||
return promptAudit.Shutdown(ctx)
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"OpsScheduledReportService", func() error {
|
||||
if opsScheduledReport != nil {
|
||||
opsScheduledReport.Stop()
|
||||
@@ -462,9 +308,9 @@ func provideCleanup(
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"AuditLogService", func() error {
|
||||
if auditLog != nil {
|
||||
auditLog.Stop()
|
||||
{"SoraMediaCleanupService", func() error {
|
||||
if soraMediaCleanup != nil {
|
||||
soraMediaCleanup.Stop()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
@@ -504,18 +350,6 @@ func provideCleanup(
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"BatchImageCleanupService", func() error {
|
||||
if batchImageCleanup != nil {
|
||||
batchImageCleanup.Stop()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"BatchImageWorkerRuntime", func() error {
|
||||
if batchImageWorker != nil {
|
||||
batchImageWorker.Stop()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"TokenRefreshService", func() error {
|
||||
tokenRefresh.Stop()
|
||||
return nil
|
||||
@@ -524,14 +358,6 @@ func provideCleanup(
|
||||
accountExpiry.Stop()
|
||||
return nil
|
||||
}},
|
||||
{"OpenAICodexVersionSyncService", func() error {
|
||||
codexVersionSync.Stop()
|
||||
return nil
|
||||
}},
|
||||
{"ProxyExpiryService", func() error {
|
||||
proxyExpiry.Stop()
|
||||
return nil
|
||||
}},
|
||||
{"SubscriptionExpiryService", func() error {
|
||||
subscriptionExpiry.Stop()
|
||||
return nil
|
||||
@@ -576,12 +402,6 @@ func provideCleanup(
|
||||
antigravityOAuth.Stop()
|
||||
return nil
|
||||
}},
|
||||
{"GrokOAuthService", func() error {
|
||||
if grokOAuth != nil {
|
||||
grokOAuth.Stop()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"OpenAIWSPool", func() error {
|
||||
if openAIGateway != nil {
|
||||
openAIGateway.CloseOpenAIWSPool()
|
||||
@@ -594,42 +414,6 @@ func provideCleanup(
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"BackupService", func() error {
|
||||
if backupSvc != nil {
|
||||
backupSvc.Stop()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"PaymentOrderExpiryService", func() error {
|
||||
if paymentOrderExpiry != nil {
|
||||
paymentOrderExpiry.Stop()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"ChannelMonitorRunner", func() error {
|
||||
if channelMonitorRunner != nil {
|
||||
channelMonitorRunner.Stop()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"UserPlatformQuotaUsageFlusher", func() error {
|
||||
if quotaFlusher != nil {
|
||||
quotaFlusher.Stop()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"UpstreamBillingProbeService", func() error {
|
||||
if upstreamBillingProbe != nil {
|
||||
upstreamBillingProbe.Stop()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
{"OllamaCloudUsageService", func() error {
|
||||
if ollamaCloudUsage != nil {
|
||||
ollamaCloudUsage.Stop()
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
}
|
||||
|
||||
infraSteps := []cleanupStep{
|
||||
|
||||
@@ -40,12 +40,10 @@ func TestProvideCleanup_WithMinimalDependencies_NoPanic(t *testing.T) {
|
||||
nil,
|
||||
)
|
||||
accountExpirySvc := service.NewAccountExpiryService(nil, time.Second)
|
||||
codexVersionSyncSvc := service.NewOpenAICodexVersionSyncService(nil, nil, nil, time.Second)
|
||||
proxyExpirySvc := service.NewProxyExpiryService(nil, time.Second)
|
||||
subscriptionExpirySvc := service.NewSubscriptionExpiryService(nil, time.Second)
|
||||
pricingSvc := service.NewPricingService(cfg, nil)
|
||||
emailQueueSvc := service.NewEmailQueueService(nil, 1)
|
||||
billingCacheSvc := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
|
||||
billingCacheSvc := service.NewBillingCacheService(nil, nil, nil, nil, cfg)
|
||||
idempotencyCleanupSvc := service.NewIdempotencyCleanupService(nil, cfg)
|
||||
schedulerSnapshotSvc := service.NewSchedulerSnapshotService(nil, nil, nil, nil, cfg)
|
||||
opsSystemLogSinkSvc := service.NewOpsSystemLogSink(nil)
|
||||
@@ -59,20 +57,13 @@ func TestProvideCleanup_WithMinimalDependencies_NoPanic(t *testing.T) {
|
||||
&service.OpsCleanupService{},
|
||||
&service.OpsScheduledReportService{},
|
||||
opsSystemLogSinkSvc,
|
||||
nil, // opsService
|
||||
nil, // opsIngressRejectAggregator
|
||||
nil, // apiKeyService
|
||||
nil, // authCacheInvalidationWorker
|
||||
&service.SoraMediaCleanupService{},
|
||||
schedulerSnapshotSvc,
|
||||
tokenRefreshSvc,
|
||||
accountExpirySvc,
|
||||
codexVersionSyncSvc,
|
||||
proxyExpirySvc,
|
||||
subscriptionExpirySvc,
|
||||
&service.UsageCleanupService{},
|
||||
idempotencyCleanupSvc,
|
||||
&service.BatchImageCleanupService{},
|
||||
nil, // batchImageWorker
|
||||
pricingSvc,
|
||||
emailQueueSvc,
|
||||
billingCacheSvc,
|
||||
@@ -82,17 +73,8 @@ func TestProvideCleanup_WithMinimalDependencies_NoPanic(t *testing.T) {
|
||||
openAIOAuthSvc,
|
||||
geminiOAuthSvc,
|
||||
antigravityOAuthSvc,
|
||||
nil, // grokOAuth
|
||||
nil, // openAIGateway
|
||||
nil, // scheduledTestRunner
|
||||
nil, // backupSvc
|
||||
nil, // paymentOrderExpiry
|
||||
nil, // channelMonitorRunner
|
||||
nil, // quotaFlusher
|
||||
nil, // upstreamBillingProbe
|
||||
nil, // ollamaCloudUsage
|
||||
nil, // auditLog
|
||||
nil, // promptAudit
|
||||
)
|
||||
|
||||
require.NotPanics(t, func() {
|
||||
|
||||
@@ -39,8 +39,6 @@ type Account struct {
|
||||
Extra map[string]interface{} `json:"extra,omitempty"`
|
||||
// ProxyID holds the value of the "proxy_id" field.
|
||||
ProxyID *int64 `json:"proxy_id,omitempty"`
|
||||
// Original proxy id replaced by expiry-fallback; for manual revert. NULL = not in fallback.
|
||||
ProxyFallbackOriginID *int64 `json:"proxy_fallback_origin_id,omitempty"`
|
||||
// Concurrency holds the value of the "concurrency" field.
|
||||
Concurrency int `json:"concurrency,omitempty"`
|
||||
// LoadFactor holds the value of the "load_factor" field.
|
||||
@@ -77,10 +75,6 @@ type Account struct {
|
||||
SessionWindowEnd *time.Time `json:"session_window_end,omitempty"`
|
||||
// SessionWindowStatus holds the value of the "session_window_status" field.
|
||||
SessionWindowStatus *string `json:"session_window_status,omitempty"`
|
||||
// Parent account id for a linked spark shadow (NULL = normal).
|
||||
ParentAccountID *int64 `json:"parent_account_id,omitempty"`
|
||||
// 'global' (default) or 'spark' (shadow reads codex_bengalfox).
|
||||
QuotaDimension account.QuotaDimension `json:"quota_dimension,omitempty"`
|
||||
// Edges holds the relations/edges for other nodes in the graph.
|
||||
// The values are being populated by the AccountQuery when eager-loading is set.
|
||||
Edges AccountEdges `json:"edges"`
|
||||
@@ -93,17 +87,13 @@ type AccountEdges struct {
|
||||
Groups []*Group `json:"groups,omitempty"`
|
||||
// Proxy holds the value of the proxy edge.
|
||||
Proxy *Proxy `json:"proxy,omitempty"`
|
||||
// Parent holds the value of the parent edge.
|
||||
Parent *Account `json:"parent,omitempty"`
|
||||
// Children holds the value of the children edge.
|
||||
Children []*Account `json:"children,omitempty"`
|
||||
// UsageLogs holds the value of the usage_logs edge.
|
||||
UsageLogs []*UsageLog `json:"usage_logs,omitempty"`
|
||||
// AccountGroups holds the value of the account_groups edge.
|
||||
AccountGroups []*AccountGroup `json:"account_groups,omitempty"`
|
||||
// loadedTypes holds the information for reporting if a
|
||||
// type was loaded (or requested) in eager-loading or not.
|
||||
loadedTypes [6]bool
|
||||
loadedTypes [4]bool
|
||||
}
|
||||
|
||||
// GroupsOrErr returns the Groups value or an error if the edge
|
||||
@@ -126,30 +116,10 @@ func (e AccountEdges) ProxyOrErr() (*Proxy, error) {
|
||||
return nil, &NotLoadedError{edge: "proxy"}
|
||||
}
|
||||
|
||||
// ParentOrErr returns the Parent value or an error if the edge
|
||||
// was not loaded in eager-loading, or loaded but was not found.
|
||||
func (e AccountEdges) ParentOrErr() (*Account, error) {
|
||||
if e.Parent != nil {
|
||||
return e.Parent, nil
|
||||
} else if e.loadedTypes[2] {
|
||||
return nil, &NotFoundError{label: account.Label}
|
||||
}
|
||||
return nil, &NotLoadedError{edge: "parent"}
|
||||
}
|
||||
|
||||
// ChildrenOrErr returns the Children value or an error if the edge
|
||||
// was not loaded in eager-loading.
|
||||
func (e AccountEdges) ChildrenOrErr() ([]*Account, error) {
|
||||
if e.loadedTypes[3] {
|
||||
return e.Children, nil
|
||||
}
|
||||
return nil, &NotLoadedError{edge: "children"}
|
||||
}
|
||||
|
||||
// UsageLogsOrErr returns the UsageLogs value or an error if the edge
|
||||
// was not loaded in eager-loading.
|
||||
func (e AccountEdges) UsageLogsOrErr() ([]*UsageLog, error) {
|
||||
if e.loadedTypes[4] {
|
||||
if e.loadedTypes[2] {
|
||||
return e.UsageLogs, nil
|
||||
}
|
||||
return nil, &NotLoadedError{edge: "usage_logs"}
|
||||
@@ -158,7 +128,7 @@ func (e AccountEdges) UsageLogsOrErr() ([]*UsageLog, error) {
|
||||
// AccountGroupsOrErr returns the AccountGroups value or an error if the edge
|
||||
// was not loaded in eager-loading.
|
||||
func (e AccountEdges) AccountGroupsOrErr() ([]*AccountGroup, error) {
|
||||
if e.loadedTypes[5] {
|
||||
if e.loadedTypes[3] {
|
||||
return e.AccountGroups, nil
|
||||
}
|
||||
return nil, &NotLoadedError{edge: "account_groups"}
|
||||
@@ -175,9 +145,9 @@ func (*Account) scanValues(columns []string) ([]any, error) {
|
||||
values[i] = new(sql.NullBool)
|
||||
case account.FieldRateMultiplier:
|
||||
values[i] = new(sql.NullFloat64)
|
||||
case account.FieldID, account.FieldProxyID, account.FieldProxyFallbackOriginID, account.FieldConcurrency, account.FieldLoadFactor, account.FieldPriority, account.FieldParentAccountID:
|
||||
case account.FieldID, account.FieldProxyID, account.FieldConcurrency, account.FieldLoadFactor, account.FieldPriority:
|
||||
values[i] = new(sql.NullInt64)
|
||||
case account.FieldName, account.FieldNotes, account.FieldPlatform, account.FieldType, account.FieldStatus, account.FieldErrorMessage, account.FieldTempUnschedulableReason, account.FieldSessionWindowStatus, account.FieldQuotaDimension:
|
||||
case account.FieldName, account.FieldNotes, account.FieldPlatform, account.FieldType, account.FieldStatus, account.FieldErrorMessage, account.FieldTempUnschedulableReason, account.FieldSessionWindowStatus:
|
||||
values[i] = new(sql.NullString)
|
||||
case account.FieldCreatedAt, account.FieldUpdatedAt, account.FieldDeletedAt, account.FieldLastUsedAt, account.FieldExpiresAt, account.FieldRateLimitedAt, account.FieldRateLimitResetAt, account.FieldOverloadUntil, account.FieldTempUnschedulableUntil, account.FieldSessionWindowStart, account.FieldSessionWindowEnd:
|
||||
values[i] = new(sql.NullTime)
|
||||
@@ -269,13 +239,6 @@ func (_m *Account) assignValues(columns []string, values []any) error {
|
||||
_m.ProxyID = new(int64)
|
||||
*_m.ProxyID = value.Int64
|
||||
}
|
||||
case account.FieldProxyFallbackOriginID:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field proxy_fallback_origin_id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ProxyFallbackOriginID = new(int64)
|
||||
*_m.ProxyFallbackOriginID = value.Int64
|
||||
}
|
||||
case account.FieldConcurrency:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field concurrency", values[i])
|
||||
@@ -396,19 +359,6 @@ func (_m *Account) assignValues(columns []string, values []any) error {
|
||||
_m.SessionWindowStatus = new(string)
|
||||
*_m.SessionWindowStatus = value.String
|
||||
}
|
||||
case account.FieldParentAccountID:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field parent_account_id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ParentAccountID = new(int64)
|
||||
*_m.ParentAccountID = value.Int64
|
||||
}
|
||||
case account.FieldQuotaDimension:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field quota_dimension", values[i])
|
||||
} else if value.Valid {
|
||||
_m.QuotaDimension = account.QuotaDimension(value.String)
|
||||
}
|
||||
default:
|
||||
_m.selectValues.Set(columns[i], values[i])
|
||||
}
|
||||
@@ -432,16 +382,6 @@ func (_m *Account) QueryProxy() *ProxyQuery {
|
||||
return NewAccountClient(_m.config).QueryProxy(_m)
|
||||
}
|
||||
|
||||
// QueryParent queries the "parent" edge of the Account entity.
|
||||
func (_m *Account) QueryParent() *AccountQuery {
|
||||
return NewAccountClient(_m.config).QueryParent(_m)
|
||||
}
|
||||
|
||||
// QueryChildren queries the "children" edge of the Account entity.
|
||||
func (_m *Account) QueryChildren() *AccountQuery {
|
||||
return NewAccountClient(_m.config).QueryChildren(_m)
|
||||
}
|
||||
|
||||
// QueryUsageLogs queries the "usage_logs" edge of the Account entity.
|
||||
func (_m *Account) QueryUsageLogs() *UsageLogQuery {
|
||||
return NewAccountClient(_m.config).QueryUsageLogs(_m)
|
||||
@@ -511,11 +451,6 @@ func (_m *Account) String() string {
|
||||
builder.WriteString(fmt.Sprintf("%v", *v))
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.ProxyFallbackOriginID; v != nil {
|
||||
builder.WriteString("proxy_fallback_origin_id=")
|
||||
builder.WriteString(fmt.Sprintf("%v", *v))
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("concurrency=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.Concurrency))
|
||||
builder.WriteString(", ")
|
||||
@@ -593,14 +528,6 @@ func (_m *Account) String() string {
|
||||
builder.WriteString("session_window_status=")
|
||||
builder.WriteString(*v)
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.ParentAccountID; v != nil {
|
||||
builder.WriteString("parent_account_id=")
|
||||
builder.WriteString(fmt.Sprintf("%v", *v))
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("quota_dimension=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.QuotaDimension))
|
||||
builder.WriteByte(')')
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
package account
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent"
|
||||
@@ -36,8 +35,6 @@ const (
|
||||
FieldExtra = "extra"
|
||||
// FieldProxyID holds the string denoting the proxy_id field in the database.
|
||||
FieldProxyID = "proxy_id"
|
||||
// FieldProxyFallbackOriginID holds the string denoting the proxy_fallback_origin_id field in the database.
|
||||
FieldProxyFallbackOriginID = "proxy_fallback_origin_id"
|
||||
// FieldConcurrency holds the string denoting the concurrency field in the database.
|
||||
FieldConcurrency = "concurrency"
|
||||
// FieldLoadFactor holds the string denoting the load_factor field in the database.
|
||||
@@ -74,18 +71,10 @@ const (
|
||||
FieldSessionWindowEnd = "session_window_end"
|
||||
// FieldSessionWindowStatus holds the string denoting the session_window_status field in the database.
|
||||
FieldSessionWindowStatus = "session_window_status"
|
||||
// FieldParentAccountID holds the string denoting the parent_account_id field in the database.
|
||||
FieldParentAccountID = "parent_account_id"
|
||||
// FieldQuotaDimension holds the string denoting the quota_dimension field in the database.
|
||||
FieldQuotaDimension = "quota_dimension"
|
||||
// EdgeGroups holds the string denoting the groups edge name in mutations.
|
||||
EdgeGroups = "groups"
|
||||
// EdgeProxy holds the string denoting the proxy edge name in mutations.
|
||||
EdgeProxy = "proxy"
|
||||
// EdgeParent holds the string denoting the parent edge name in mutations.
|
||||
EdgeParent = "parent"
|
||||
// EdgeChildren holds the string denoting the children edge name in mutations.
|
||||
EdgeChildren = "children"
|
||||
// EdgeUsageLogs holds the string denoting the usage_logs edge name in mutations.
|
||||
EdgeUsageLogs = "usage_logs"
|
||||
// EdgeAccountGroups holds the string denoting the account_groups edge name in mutations.
|
||||
@@ -104,14 +93,6 @@ const (
|
||||
ProxyInverseTable = "proxies"
|
||||
// ProxyColumn is the table column denoting the proxy relation/edge.
|
||||
ProxyColumn = "proxy_id"
|
||||
// ParentTable is the table that holds the parent relation/edge.
|
||||
ParentTable = "accounts"
|
||||
// ParentColumn is the table column denoting the parent relation/edge.
|
||||
ParentColumn = "parent_account_id"
|
||||
// ChildrenTable is the table that holds the children relation/edge.
|
||||
ChildrenTable = "accounts"
|
||||
// ChildrenColumn is the table column denoting the children relation/edge.
|
||||
ChildrenColumn = "parent_account_id"
|
||||
// UsageLogsTable is the table that holds the usage_logs relation/edge.
|
||||
UsageLogsTable = "usage_logs"
|
||||
// UsageLogsInverseTable is the table name for the UsageLog entity.
|
||||
@@ -141,7 +122,6 @@ var Columns = []string{
|
||||
FieldCredentials,
|
||||
FieldExtra,
|
||||
FieldProxyID,
|
||||
FieldProxyFallbackOriginID,
|
||||
FieldConcurrency,
|
||||
FieldLoadFactor,
|
||||
FieldPriority,
|
||||
@@ -160,8 +140,6 @@ var Columns = []string{
|
||||
FieldSessionWindowStart,
|
||||
FieldSessionWindowEnd,
|
||||
FieldSessionWindowStatus,
|
||||
FieldParentAccountID,
|
||||
FieldQuotaDimension,
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -222,32 +200,6 @@ var (
|
||||
SessionWindowStatusValidator func(string) error
|
||||
)
|
||||
|
||||
// QuotaDimension defines the type for the "quota_dimension" enum field.
|
||||
type QuotaDimension string
|
||||
|
||||
// QuotaDimensionGlobal is the default value of the QuotaDimension enum.
|
||||
const DefaultQuotaDimension = QuotaDimensionGlobal
|
||||
|
||||
// QuotaDimension values.
|
||||
const (
|
||||
QuotaDimensionGlobal QuotaDimension = "global"
|
||||
QuotaDimensionSpark QuotaDimension = "spark"
|
||||
)
|
||||
|
||||
func (qd QuotaDimension) String() string {
|
||||
return string(qd)
|
||||
}
|
||||
|
||||
// QuotaDimensionValidator is a validator for the "quota_dimension" field enum values. It is called by the builders before save.
|
||||
func QuotaDimensionValidator(qd QuotaDimension) error {
|
||||
switch qd {
|
||||
case QuotaDimensionGlobal, QuotaDimensionSpark:
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("account: invalid enum value for quota_dimension field: %q", qd)
|
||||
}
|
||||
}
|
||||
|
||||
// OrderOption defines the ordering options for the Account queries.
|
||||
type OrderOption func(*sql.Selector)
|
||||
|
||||
@@ -296,11 +248,6 @@ func ByProxyID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldProxyID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByProxyFallbackOriginID orders the results by the proxy_fallback_origin_id field.
|
||||
func ByProxyFallbackOriginID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldProxyFallbackOriginID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByConcurrency orders the results by the concurrency field.
|
||||
func ByConcurrency(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldConcurrency, opts...).ToFunc()
|
||||
@@ -391,16 +338,6 @@ func BySessionWindowStatus(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldSessionWindowStatus, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByParentAccountID orders the results by the parent_account_id field.
|
||||
func ByParentAccountID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldParentAccountID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByQuotaDimension orders the results by the quota_dimension field.
|
||||
func ByQuotaDimension(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldQuotaDimension, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByGroupsCount orders the results by groups count.
|
||||
func ByGroupsCount(opts ...sql.OrderTermOption) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
@@ -422,27 +359,6 @@ func ByProxyField(field string, opts ...sql.OrderTermOption) OrderOption {
|
||||
}
|
||||
}
|
||||
|
||||
// ByParentField orders the results by parent field.
|
||||
func ByParentField(field string, opts ...sql.OrderTermOption) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborTerms(s, newParentStep(), sql.OrderByField(field, opts...))
|
||||
}
|
||||
}
|
||||
|
||||
// ByChildrenCount orders the results by children count.
|
||||
func ByChildrenCount(opts ...sql.OrderTermOption) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborsCount(s, newChildrenStep(), opts...)
|
||||
}
|
||||
}
|
||||
|
||||
// ByChildren orders the results by children terms.
|
||||
func ByChildren(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborTerms(s, newChildrenStep(), append([]sql.OrderTerm{term}, terms...)...)
|
||||
}
|
||||
}
|
||||
|
||||
// ByUsageLogsCount orders the results by usage_logs count.
|
||||
func ByUsageLogsCount(opts ...sql.OrderTermOption) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
@@ -484,20 +400,6 @@ func newProxyStep() *sqlgraph.Step {
|
||||
sqlgraph.Edge(sqlgraph.M2O, false, ProxyTable, ProxyColumn),
|
||||
)
|
||||
}
|
||||
func newParentStep() *sqlgraph.Step {
|
||||
return sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(Table, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, true, ParentTable, ParentColumn),
|
||||
)
|
||||
}
|
||||
func newChildrenStep() *sqlgraph.Step {
|
||||
return sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(Table, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, ChildrenTable, ChildrenColumn),
|
||||
)
|
||||
}
|
||||
func newUsageLogsStep() *sqlgraph.Step {
|
||||
return sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
|
||||
@@ -95,11 +95,6 @@ func ProxyID(v int64) predicate.Account {
|
||||
return predicate.Account(sql.FieldEQ(FieldProxyID, v))
|
||||
}
|
||||
|
||||
// ProxyFallbackOriginID applies equality check predicate on the "proxy_fallback_origin_id" field. It's identical to ProxyFallbackOriginIDEQ.
|
||||
func ProxyFallbackOriginID(v int64) predicate.Account {
|
||||
return predicate.Account(sql.FieldEQ(FieldProxyFallbackOriginID, v))
|
||||
}
|
||||
|
||||
// Concurrency applies equality check predicate on the "concurrency" field. It's identical to ConcurrencyEQ.
|
||||
func Concurrency(v int) predicate.Account {
|
||||
return predicate.Account(sql.FieldEQ(FieldConcurrency, v))
|
||||
@@ -190,11 +185,6 @@ func SessionWindowStatus(v string) predicate.Account {
|
||||
return predicate.Account(sql.FieldEQ(FieldSessionWindowStatus, v))
|
||||
}
|
||||
|
||||
// ParentAccountID applies equality check predicate on the "parent_account_id" field. It's identical to ParentAccountIDEQ.
|
||||
func ParentAccountID(v int64) predicate.Account {
|
||||
return predicate.Account(sql.FieldEQ(FieldParentAccountID, v))
|
||||
}
|
||||
|
||||
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
|
||||
func CreatedAtEQ(v time.Time) predicate.Account {
|
||||
return predicate.Account(sql.FieldEQ(FieldCreatedAt, v))
|
||||
@@ -625,56 +615,6 @@ func ProxyIDNotNil() predicate.Account {
|
||||
return predicate.Account(sql.FieldNotNull(FieldProxyID))
|
||||
}
|
||||
|
||||
// ProxyFallbackOriginIDEQ applies the EQ predicate on the "proxy_fallback_origin_id" field.
|
||||
func ProxyFallbackOriginIDEQ(v int64) predicate.Account {
|
||||
return predicate.Account(sql.FieldEQ(FieldProxyFallbackOriginID, v))
|
||||
}
|
||||
|
||||
// ProxyFallbackOriginIDNEQ applies the NEQ predicate on the "proxy_fallback_origin_id" field.
|
||||
func ProxyFallbackOriginIDNEQ(v int64) predicate.Account {
|
||||
return predicate.Account(sql.FieldNEQ(FieldProxyFallbackOriginID, v))
|
||||
}
|
||||
|
||||
// ProxyFallbackOriginIDIn applies the In predicate on the "proxy_fallback_origin_id" field.
|
||||
func ProxyFallbackOriginIDIn(vs ...int64) predicate.Account {
|
||||
return predicate.Account(sql.FieldIn(FieldProxyFallbackOriginID, vs...))
|
||||
}
|
||||
|
||||
// ProxyFallbackOriginIDNotIn applies the NotIn predicate on the "proxy_fallback_origin_id" field.
|
||||
func ProxyFallbackOriginIDNotIn(vs ...int64) predicate.Account {
|
||||
return predicate.Account(sql.FieldNotIn(FieldProxyFallbackOriginID, vs...))
|
||||
}
|
||||
|
||||
// ProxyFallbackOriginIDGT applies the GT predicate on the "proxy_fallback_origin_id" field.
|
||||
func ProxyFallbackOriginIDGT(v int64) predicate.Account {
|
||||
return predicate.Account(sql.FieldGT(FieldProxyFallbackOriginID, v))
|
||||
}
|
||||
|
||||
// ProxyFallbackOriginIDGTE applies the GTE predicate on the "proxy_fallback_origin_id" field.
|
||||
func ProxyFallbackOriginIDGTE(v int64) predicate.Account {
|
||||
return predicate.Account(sql.FieldGTE(FieldProxyFallbackOriginID, v))
|
||||
}
|
||||
|
||||
// ProxyFallbackOriginIDLT applies the LT predicate on the "proxy_fallback_origin_id" field.
|
||||
func ProxyFallbackOriginIDLT(v int64) predicate.Account {
|
||||
return predicate.Account(sql.FieldLT(FieldProxyFallbackOriginID, v))
|
||||
}
|
||||
|
||||
// ProxyFallbackOriginIDLTE applies the LTE predicate on the "proxy_fallback_origin_id" field.
|
||||
func ProxyFallbackOriginIDLTE(v int64) predicate.Account {
|
||||
return predicate.Account(sql.FieldLTE(FieldProxyFallbackOriginID, v))
|
||||
}
|
||||
|
||||
// ProxyFallbackOriginIDIsNil applies the IsNil predicate on the "proxy_fallback_origin_id" field.
|
||||
func ProxyFallbackOriginIDIsNil() predicate.Account {
|
||||
return predicate.Account(sql.FieldIsNull(FieldProxyFallbackOriginID))
|
||||
}
|
||||
|
||||
// ProxyFallbackOriginIDNotNil applies the NotNil predicate on the "proxy_fallback_origin_id" field.
|
||||
func ProxyFallbackOriginIDNotNil() predicate.Account {
|
||||
return predicate.Account(sql.FieldNotNull(FieldProxyFallbackOriginID))
|
||||
}
|
||||
|
||||
// ConcurrencyEQ applies the EQ predicate on the "concurrency" field.
|
||||
func ConcurrencyEQ(v int) predicate.Account {
|
||||
return predicate.Account(sql.FieldEQ(FieldConcurrency, v))
|
||||
@@ -1555,56 +1495,6 @@ func SessionWindowStatusContainsFold(v string) predicate.Account {
|
||||
return predicate.Account(sql.FieldContainsFold(FieldSessionWindowStatus, v))
|
||||
}
|
||||
|
||||
// ParentAccountIDEQ applies the EQ predicate on the "parent_account_id" field.
|
||||
func ParentAccountIDEQ(v int64) predicate.Account {
|
||||
return predicate.Account(sql.FieldEQ(FieldParentAccountID, v))
|
||||
}
|
||||
|
||||
// ParentAccountIDNEQ applies the NEQ predicate on the "parent_account_id" field.
|
||||
func ParentAccountIDNEQ(v int64) predicate.Account {
|
||||
return predicate.Account(sql.FieldNEQ(FieldParentAccountID, v))
|
||||
}
|
||||
|
||||
// ParentAccountIDIn applies the In predicate on the "parent_account_id" field.
|
||||
func ParentAccountIDIn(vs ...int64) predicate.Account {
|
||||
return predicate.Account(sql.FieldIn(FieldParentAccountID, vs...))
|
||||
}
|
||||
|
||||
// ParentAccountIDNotIn applies the NotIn predicate on the "parent_account_id" field.
|
||||
func ParentAccountIDNotIn(vs ...int64) predicate.Account {
|
||||
return predicate.Account(sql.FieldNotIn(FieldParentAccountID, vs...))
|
||||
}
|
||||
|
||||
// ParentAccountIDIsNil applies the IsNil predicate on the "parent_account_id" field.
|
||||
func ParentAccountIDIsNil() predicate.Account {
|
||||
return predicate.Account(sql.FieldIsNull(FieldParentAccountID))
|
||||
}
|
||||
|
||||
// ParentAccountIDNotNil applies the NotNil predicate on the "parent_account_id" field.
|
||||
func ParentAccountIDNotNil() predicate.Account {
|
||||
return predicate.Account(sql.FieldNotNull(FieldParentAccountID))
|
||||
}
|
||||
|
||||
// QuotaDimensionEQ applies the EQ predicate on the "quota_dimension" field.
|
||||
func QuotaDimensionEQ(v QuotaDimension) predicate.Account {
|
||||
return predicate.Account(sql.FieldEQ(FieldQuotaDimension, v))
|
||||
}
|
||||
|
||||
// QuotaDimensionNEQ applies the NEQ predicate on the "quota_dimension" field.
|
||||
func QuotaDimensionNEQ(v QuotaDimension) predicate.Account {
|
||||
return predicate.Account(sql.FieldNEQ(FieldQuotaDimension, v))
|
||||
}
|
||||
|
||||
// QuotaDimensionIn applies the In predicate on the "quota_dimension" field.
|
||||
func QuotaDimensionIn(vs ...QuotaDimension) predicate.Account {
|
||||
return predicate.Account(sql.FieldIn(FieldQuotaDimension, vs...))
|
||||
}
|
||||
|
||||
// QuotaDimensionNotIn applies the NotIn predicate on the "quota_dimension" field.
|
||||
func QuotaDimensionNotIn(vs ...QuotaDimension) predicate.Account {
|
||||
return predicate.Account(sql.FieldNotIn(FieldQuotaDimension, vs...))
|
||||
}
|
||||
|
||||
// HasGroups applies the HasEdge predicate on the "groups" edge.
|
||||
func HasGroups() predicate.Account {
|
||||
return predicate.Account(func(s *sql.Selector) {
|
||||
@@ -1651,52 +1541,6 @@ func HasProxyWith(preds ...predicate.Proxy) predicate.Account {
|
||||
})
|
||||
}
|
||||
|
||||
// HasParent applies the HasEdge predicate on the "parent" edge.
|
||||
func HasParent() predicate.Account {
|
||||
return predicate.Account(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, true, ParentTable, ParentColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
})
|
||||
}
|
||||
|
||||
// HasParentWith applies the HasEdge predicate on the "parent" edge with a given conditions (other predicates).
|
||||
func HasParentWith(preds ...predicate.Account) predicate.Account {
|
||||
return predicate.Account(func(s *sql.Selector) {
|
||||
step := newParentStep()
|
||||
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
|
||||
for _, p := range preds {
|
||||
p(s)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// HasChildren applies the HasEdge predicate on the "children" edge.
|
||||
func HasChildren() predicate.Account {
|
||||
return predicate.Account(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, ChildrenTable, ChildrenColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
})
|
||||
}
|
||||
|
||||
// HasChildrenWith applies the HasEdge predicate on the "children" edge with a given conditions (other predicates).
|
||||
func HasChildrenWith(preds ...predicate.Account) predicate.Account {
|
||||
return predicate.Account(func(s *sql.Selector) {
|
||||
step := newChildrenStep()
|
||||
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
|
||||
for _, p := range preds {
|
||||
p(s)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// HasUsageLogs applies the HasEdge predicate on the "usage_logs" edge.
|
||||
func HasUsageLogs() predicate.Account {
|
||||
return predicate.Account(func(s *sql.Selector) {
|
||||
|
||||
@@ -125,20 +125,6 @@ func (_c *AccountCreate) SetNillableProxyID(v *int64) *AccountCreate {
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetProxyFallbackOriginID sets the "proxy_fallback_origin_id" field.
|
||||
func (_c *AccountCreate) SetProxyFallbackOriginID(v int64) *AccountCreate {
|
||||
_c.mutation.SetProxyFallbackOriginID(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableProxyFallbackOriginID sets the "proxy_fallback_origin_id" field if the given value is not nil.
|
||||
func (_c *AccountCreate) SetNillableProxyFallbackOriginID(v *int64) *AccountCreate {
|
||||
if v != nil {
|
||||
_c.SetProxyFallbackOriginID(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetConcurrency sets the "concurrency" field.
|
||||
func (_c *AccountCreate) SetConcurrency(v int) *AccountCreate {
|
||||
_c.mutation.SetConcurrency(v)
|
||||
@@ -391,34 +377,6 @@ func (_c *AccountCreate) SetNillableSessionWindowStatus(v *string) *AccountCreat
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetParentAccountID sets the "parent_account_id" field.
|
||||
func (_c *AccountCreate) SetParentAccountID(v int64) *AccountCreate {
|
||||
_c.mutation.SetParentAccountID(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableParentAccountID sets the "parent_account_id" field if the given value is not nil.
|
||||
func (_c *AccountCreate) SetNillableParentAccountID(v *int64) *AccountCreate {
|
||||
if v != nil {
|
||||
_c.SetParentAccountID(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetQuotaDimension sets the "quota_dimension" field.
|
||||
func (_c *AccountCreate) SetQuotaDimension(v account.QuotaDimension) *AccountCreate {
|
||||
_c.mutation.SetQuotaDimension(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableQuotaDimension sets the "quota_dimension" field if the given value is not nil.
|
||||
func (_c *AccountCreate) SetNillableQuotaDimension(v *account.QuotaDimension) *AccountCreate {
|
||||
if v != nil {
|
||||
_c.SetQuotaDimension(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// AddGroupIDs adds the "groups" edge to the Group entity by IDs.
|
||||
func (_c *AccountCreate) AddGroupIDs(ids ...int64) *AccountCreate {
|
||||
_c.mutation.AddGroupIDs(ids...)
|
||||
@@ -439,40 +397,6 @@ func (_c *AccountCreate) SetProxy(v *Proxy) *AccountCreate {
|
||||
return _c.SetProxyID(v.ID)
|
||||
}
|
||||
|
||||
// SetParentID sets the "parent" edge to the Account entity by ID.
|
||||
func (_c *AccountCreate) SetParentID(id int64) *AccountCreate {
|
||||
_c.mutation.SetParentID(id)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableParentID sets the "parent" edge to the Account entity by ID if the given value is not nil.
|
||||
func (_c *AccountCreate) SetNillableParentID(id *int64) *AccountCreate {
|
||||
if id != nil {
|
||||
_c = _c.SetParentID(*id)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetParent sets the "parent" edge to the Account entity.
|
||||
func (_c *AccountCreate) SetParent(v *Account) *AccountCreate {
|
||||
return _c.SetParentID(v.ID)
|
||||
}
|
||||
|
||||
// AddChildIDs adds the "children" edge to the Account entity by IDs.
|
||||
func (_c *AccountCreate) AddChildIDs(ids ...int64) *AccountCreate {
|
||||
_c.mutation.AddChildIDs(ids...)
|
||||
return _c
|
||||
}
|
||||
|
||||
// AddChildren adds the "children" edges to the Account entity.
|
||||
func (_c *AccountCreate) AddChildren(v ...*Account) *AccountCreate {
|
||||
ids := make([]int64, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _c.AddChildIDs(ids...)
|
||||
}
|
||||
|
||||
// AddUsageLogIDs adds the "usage_logs" edge to the UsageLog entity by IDs.
|
||||
func (_c *AccountCreate) AddUsageLogIDs(ids ...int64) *AccountCreate {
|
||||
_c.mutation.AddUsageLogIDs(ids...)
|
||||
@@ -577,10 +501,6 @@ func (_c *AccountCreate) defaults() error {
|
||||
v := account.DefaultSchedulable
|
||||
_c.mutation.SetSchedulable(v)
|
||||
}
|
||||
if _, ok := _c.mutation.QuotaDimension(); !ok {
|
||||
v := account.DefaultQuotaDimension
|
||||
_c.mutation.SetQuotaDimension(v)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -650,14 +570,6 @@ func (_c *AccountCreate) check() error {
|
||||
return &ValidationError{Name: "session_window_status", err: fmt.Errorf(`ent: validator failed for field "Account.session_window_status": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _, ok := _c.mutation.QuotaDimension(); !ok {
|
||||
return &ValidationError{Name: "quota_dimension", err: errors.New(`ent: missing required field "Account.quota_dimension"`)}
|
||||
}
|
||||
if v, ok := _c.mutation.QuotaDimension(); ok {
|
||||
if err := account.QuotaDimensionValidator(v); err != nil {
|
||||
return &ValidationError{Name: "quota_dimension", err: fmt.Errorf(`ent: validator failed for field "Account.quota_dimension": %w`, err)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -721,10 +633,6 @@ func (_c *AccountCreate) createSpec() (*Account, *sqlgraph.CreateSpec) {
|
||||
_spec.SetField(account.FieldExtra, field.TypeJSON, value)
|
||||
_node.Extra = value
|
||||
}
|
||||
if value, ok := _c.mutation.ProxyFallbackOriginID(); ok {
|
||||
_spec.SetField(account.FieldProxyFallbackOriginID, field.TypeInt64, value)
|
||||
_node.ProxyFallbackOriginID = &value
|
||||
}
|
||||
if value, ok := _c.mutation.Concurrency(); ok {
|
||||
_spec.SetField(account.FieldConcurrency, field.TypeInt, value)
|
||||
_node.Concurrency = value
|
||||
@@ -797,10 +705,6 @@ func (_c *AccountCreate) createSpec() (*Account, *sqlgraph.CreateSpec) {
|
||||
_spec.SetField(account.FieldSessionWindowStatus, field.TypeString, value)
|
||||
_node.SessionWindowStatus = &value
|
||||
}
|
||||
if value, ok := _c.mutation.QuotaDimension(); ok {
|
||||
_spec.SetField(account.FieldQuotaDimension, field.TypeEnum, value)
|
||||
_node.QuotaDimension = value
|
||||
}
|
||||
if nodes := _c.mutation.GroupsIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2M,
|
||||
@@ -838,39 +742,6 @@ func (_c *AccountCreate) createSpec() (*Account, *sqlgraph.CreateSpec) {
|
||||
_node.ProxyID = &nodes[0]
|
||||
_spec.Edges = append(_spec.Edges, edge)
|
||||
}
|
||||
if nodes := _c.mutation.ParentIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: account.ParentTable,
|
||||
Columns: []string{account.ParentColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_node.ParentAccountID = &nodes[0]
|
||||
_spec.Edges = append(_spec.Edges, edge)
|
||||
}
|
||||
if nodes := _c.mutation.ChildrenIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: account.ChildrenTable,
|
||||
Columns: []string{account.ChildrenColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges = append(_spec.Edges, edge)
|
||||
}
|
||||
if nodes := _c.mutation.UsageLogsIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
@@ -1065,30 +936,6 @@ func (u *AccountUpsert) ClearProxyID() *AccountUpsert {
|
||||
return u
|
||||
}
|
||||
|
||||
// SetProxyFallbackOriginID sets the "proxy_fallback_origin_id" field.
|
||||
func (u *AccountUpsert) SetProxyFallbackOriginID(v int64) *AccountUpsert {
|
||||
u.Set(account.FieldProxyFallbackOriginID, v)
|
||||
return u
|
||||
}
|
||||
|
||||
// UpdateProxyFallbackOriginID sets the "proxy_fallback_origin_id" field to the value that was provided on create.
|
||||
func (u *AccountUpsert) UpdateProxyFallbackOriginID() *AccountUpsert {
|
||||
u.SetExcluded(account.FieldProxyFallbackOriginID)
|
||||
return u
|
||||
}
|
||||
|
||||
// AddProxyFallbackOriginID adds v to the "proxy_fallback_origin_id" field.
|
||||
func (u *AccountUpsert) AddProxyFallbackOriginID(v int64) *AccountUpsert {
|
||||
u.Add(account.FieldProxyFallbackOriginID, v)
|
||||
return u
|
||||
}
|
||||
|
||||
// ClearProxyFallbackOriginID clears the value of the "proxy_fallback_origin_id" field.
|
||||
func (u *AccountUpsert) ClearProxyFallbackOriginID() *AccountUpsert {
|
||||
u.SetNull(account.FieldProxyFallbackOriginID)
|
||||
return u
|
||||
}
|
||||
|
||||
// SetConcurrency sets the "concurrency" field.
|
||||
func (u *AccountUpsert) SetConcurrency(v int) *AccountUpsert {
|
||||
u.Set(account.FieldConcurrency, v)
|
||||
@@ -1401,36 +1248,6 @@ func (u *AccountUpsert) ClearSessionWindowStatus() *AccountUpsert {
|
||||
return u
|
||||
}
|
||||
|
||||
// SetParentAccountID sets the "parent_account_id" field.
|
||||
func (u *AccountUpsert) SetParentAccountID(v int64) *AccountUpsert {
|
||||
u.Set(account.FieldParentAccountID, v)
|
||||
return u
|
||||
}
|
||||
|
||||
// UpdateParentAccountID sets the "parent_account_id" field to the value that was provided on create.
|
||||
func (u *AccountUpsert) UpdateParentAccountID() *AccountUpsert {
|
||||
u.SetExcluded(account.FieldParentAccountID)
|
||||
return u
|
||||
}
|
||||
|
||||
// ClearParentAccountID clears the value of the "parent_account_id" field.
|
||||
func (u *AccountUpsert) ClearParentAccountID() *AccountUpsert {
|
||||
u.SetNull(account.FieldParentAccountID)
|
||||
return u
|
||||
}
|
||||
|
||||
// SetQuotaDimension sets the "quota_dimension" field.
|
||||
func (u *AccountUpsert) SetQuotaDimension(v account.QuotaDimension) *AccountUpsert {
|
||||
u.Set(account.FieldQuotaDimension, v)
|
||||
return u
|
||||
}
|
||||
|
||||
// UpdateQuotaDimension sets the "quota_dimension" field to the value that was provided on create.
|
||||
func (u *AccountUpsert) UpdateQuotaDimension() *AccountUpsert {
|
||||
u.SetExcluded(account.FieldQuotaDimension)
|
||||
return u
|
||||
}
|
||||
|
||||
// UpdateNewValues updates the mutable fields using the new values that were set on create.
|
||||
// Using this option is equivalent to using:
|
||||
//
|
||||
@@ -1623,34 +1440,6 @@ func (u *AccountUpsertOne) ClearProxyID() *AccountUpsertOne {
|
||||
})
|
||||
}
|
||||
|
||||
// SetProxyFallbackOriginID sets the "proxy_fallback_origin_id" field.
|
||||
func (u *AccountUpsertOne) SetProxyFallbackOriginID(v int64) *AccountUpsertOne {
|
||||
return u.Update(func(s *AccountUpsert) {
|
||||
s.SetProxyFallbackOriginID(v)
|
||||
})
|
||||
}
|
||||
|
||||
// AddProxyFallbackOriginID adds v to the "proxy_fallback_origin_id" field.
|
||||
func (u *AccountUpsertOne) AddProxyFallbackOriginID(v int64) *AccountUpsertOne {
|
||||
return u.Update(func(s *AccountUpsert) {
|
||||
s.AddProxyFallbackOriginID(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateProxyFallbackOriginID sets the "proxy_fallback_origin_id" field to the value that was provided on create.
|
||||
func (u *AccountUpsertOne) UpdateProxyFallbackOriginID() *AccountUpsertOne {
|
||||
return u.Update(func(s *AccountUpsert) {
|
||||
s.UpdateProxyFallbackOriginID()
|
||||
})
|
||||
}
|
||||
|
||||
// ClearProxyFallbackOriginID clears the value of the "proxy_fallback_origin_id" field.
|
||||
func (u *AccountUpsertOne) ClearProxyFallbackOriginID() *AccountUpsertOne {
|
||||
return u.Update(func(s *AccountUpsert) {
|
||||
s.ClearProxyFallbackOriginID()
|
||||
})
|
||||
}
|
||||
|
||||
// SetConcurrency sets the "concurrency" field.
|
||||
func (u *AccountUpsertOne) SetConcurrency(v int) *AccountUpsertOne {
|
||||
return u.Update(func(s *AccountUpsert) {
|
||||
@@ -2015,41 +1804,6 @@ func (u *AccountUpsertOne) ClearSessionWindowStatus() *AccountUpsertOne {
|
||||
})
|
||||
}
|
||||
|
||||
// SetParentAccountID sets the "parent_account_id" field.
|
||||
func (u *AccountUpsertOne) SetParentAccountID(v int64) *AccountUpsertOne {
|
||||
return u.Update(func(s *AccountUpsert) {
|
||||
s.SetParentAccountID(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateParentAccountID sets the "parent_account_id" field to the value that was provided on create.
|
||||
func (u *AccountUpsertOne) UpdateParentAccountID() *AccountUpsertOne {
|
||||
return u.Update(func(s *AccountUpsert) {
|
||||
s.UpdateParentAccountID()
|
||||
})
|
||||
}
|
||||
|
||||
// ClearParentAccountID clears the value of the "parent_account_id" field.
|
||||
func (u *AccountUpsertOne) ClearParentAccountID() *AccountUpsertOne {
|
||||
return u.Update(func(s *AccountUpsert) {
|
||||
s.ClearParentAccountID()
|
||||
})
|
||||
}
|
||||
|
||||
// SetQuotaDimension sets the "quota_dimension" field.
|
||||
func (u *AccountUpsertOne) SetQuotaDimension(v account.QuotaDimension) *AccountUpsertOne {
|
||||
return u.Update(func(s *AccountUpsert) {
|
||||
s.SetQuotaDimension(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateQuotaDimension sets the "quota_dimension" field to the value that was provided on create.
|
||||
func (u *AccountUpsertOne) UpdateQuotaDimension() *AccountUpsertOne {
|
||||
return u.Update(func(s *AccountUpsert) {
|
||||
s.UpdateQuotaDimension()
|
||||
})
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (u *AccountUpsertOne) Exec(ctx context.Context) error {
|
||||
if len(u.create.conflict) == 0 {
|
||||
@@ -2408,34 +2162,6 @@ func (u *AccountUpsertBulk) ClearProxyID() *AccountUpsertBulk {
|
||||
})
|
||||
}
|
||||
|
||||
// SetProxyFallbackOriginID sets the "proxy_fallback_origin_id" field.
|
||||
func (u *AccountUpsertBulk) SetProxyFallbackOriginID(v int64) *AccountUpsertBulk {
|
||||
return u.Update(func(s *AccountUpsert) {
|
||||
s.SetProxyFallbackOriginID(v)
|
||||
})
|
||||
}
|
||||
|
||||
// AddProxyFallbackOriginID adds v to the "proxy_fallback_origin_id" field.
|
||||
func (u *AccountUpsertBulk) AddProxyFallbackOriginID(v int64) *AccountUpsertBulk {
|
||||
return u.Update(func(s *AccountUpsert) {
|
||||
s.AddProxyFallbackOriginID(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateProxyFallbackOriginID sets the "proxy_fallback_origin_id" field to the value that was provided on create.
|
||||
func (u *AccountUpsertBulk) UpdateProxyFallbackOriginID() *AccountUpsertBulk {
|
||||
return u.Update(func(s *AccountUpsert) {
|
||||
s.UpdateProxyFallbackOriginID()
|
||||
})
|
||||
}
|
||||
|
||||
// ClearProxyFallbackOriginID clears the value of the "proxy_fallback_origin_id" field.
|
||||
func (u *AccountUpsertBulk) ClearProxyFallbackOriginID() *AccountUpsertBulk {
|
||||
return u.Update(func(s *AccountUpsert) {
|
||||
s.ClearProxyFallbackOriginID()
|
||||
})
|
||||
}
|
||||
|
||||
// SetConcurrency sets the "concurrency" field.
|
||||
func (u *AccountUpsertBulk) SetConcurrency(v int) *AccountUpsertBulk {
|
||||
return u.Update(func(s *AccountUpsert) {
|
||||
@@ -2800,41 +2526,6 @@ func (u *AccountUpsertBulk) ClearSessionWindowStatus() *AccountUpsertBulk {
|
||||
})
|
||||
}
|
||||
|
||||
// SetParentAccountID sets the "parent_account_id" field.
|
||||
func (u *AccountUpsertBulk) SetParentAccountID(v int64) *AccountUpsertBulk {
|
||||
return u.Update(func(s *AccountUpsert) {
|
||||
s.SetParentAccountID(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateParentAccountID sets the "parent_account_id" field to the value that was provided on create.
|
||||
func (u *AccountUpsertBulk) UpdateParentAccountID() *AccountUpsertBulk {
|
||||
return u.Update(func(s *AccountUpsert) {
|
||||
s.UpdateParentAccountID()
|
||||
})
|
||||
}
|
||||
|
||||
// ClearParentAccountID clears the value of the "parent_account_id" field.
|
||||
func (u *AccountUpsertBulk) ClearParentAccountID() *AccountUpsertBulk {
|
||||
return u.Update(func(s *AccountUpsert) {
|
||||
s.ClearParentAccountID()
|
||||
})
|
||||
}
|
||||
|
||||
// SetQuotaDimension sets the "quota_dimension" field.
|
||||
func (u *AccountUpsertBulk) SetQuotaDimension(v account.QuotaDimension) *AccountUpsertBulk {
|
||||
return u.Update(func(s *AccountUpsert) {
|
||||
s.SetQuotaDimension(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateQuotaDimension sets the "quota_dimension" field to the value that was provided on create.
|
||||
func (u *AccountUpsertBulk) UpdateQuotaDimension() *AccountUpsertBulk {
|
||||
return u.Update(func(s *AccountUpsert) {
|
||||
s.UpdateQuotaDimension()
|
||||
})
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (u *AccountUpsertBulk) Exec(ctx context.Context) error {
|
||||
if u.create.err != nil {
|
||||
|
||||
@@ -30,8 +30,6 @@ type AccountQuery struct {
|
||||
predicates []predicate.Account
|
||||
withGroups *GroupQuery
|
||||
withProxy *ProxyQuery
|
||||
withParent *AccountQuery
|
||||
withChildren *AccountQuery
|
||||
withUsageLogs *UsageLogQuery
|
||||
withAccountGroups *AccountGroupQuery
|
||||
modifiers []func(*sql.Selector)
|
||||
@@ -115,50 +113,6 @@ func (_q *AccountQuery) QueryProxy() *ProxyQuery {
|
||||
return query
|
||||
}
|
||||
|
||||
// QueryParent chains the current query on the "parent" edge.
|
||||
func (_q *AccountQuery) QueryParent() *AccountQuery {
|
||||
query := (&AccountClient{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(account.Table, account.FieldID, selector),
|
||||
sqlgraph.To(account.Table, account.FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, true, account.ParentTable, account.ParentColumn),
|
||||
)
|
||||
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
|
||||
return fromU, nil
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
// QueryChildren chains the current query on the "children" edge.
|
||||
func (_q *AccountQuery) QueryChildren() *AccountQuery {
|
||||
query := (&AccountClient{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(account.Table, account.FieldID, selector),
|
||||
sqlgraph.To(account.Table, account.FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, account.ChildrenTable, account.ChildrenColumn),
|
||||
)
|
||||
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
|
||||
return fromU, nil
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
// QueryUsageLogs chains the current query on the "usage_logs" edge.
|
||||
func (_q *AccountQuery) QueryUsageLogs() *UsageLogQuery {
|
||||
query := (&UsageLogClient{config: _q.config}).Query()
|
||||
@@ -397,8 +351,6 @@ func (_q *AccountQuery) Clone() *AccountQuery {
|
||||
predicates: append([]predicate.Account{}, _q.predicates...),
|
||||
withGroups: _q.withGroups.Clone(),
|
||||
withProxy: _q.withProxy.Clone(),
|
||||
withParent: _q.withParent.Clone(),
|
||||
withChildren: _q.withChildren.Clone(),
|
||||
withUsageLogs: _q.withUsageLogs.Clone(),
|
||||
withAccountGroups: _q.withAccountGroups.Clone(),
|
||||
// clone intermediate query.
|
||||
@@ -429,28 +381,6 @@ func (_q *AccountQuery) WithProxy(opts ...func(*ProxyQuery)) *AccountQuery {
|
||||
return _q
|
||||
}
|
||||
|
||||
// WithParent tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "parent" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (_q *AccountQuery) WithParent(opts ...func(*AccountQuery)) *AccountQuery {
|
||||
query := (&AccountClient{config: _q.config}).Query()
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
_q.withParent = query
|
||||
return _q
|
||||
}
|
||||
|
||||
// WithChildren tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "children" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (_q *AccountQuery) WithChildren(opts ...func(*AccountQuery)) *AccountQuery {
|
||||
query := (&AccountClient{config: _q.config}).Query()
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
_q.withChildren = query
|
||||
return _q
|
||||
}
|
||||
|
||||
// WithUsageLogs tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "usage_logs" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (_q *AccountQuery) WithUsageLogs(opts ...func(*UsageLogQuery)) *AccountQuery {
|
||||
@@ -551,11 +481,9 @@ func (_q *AccountQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Acco
|
||||
var (
|
||||
nodes = []*Account{}
|
||||
_spec = _q.querySpec()
|
||||
loadedTypes = [6]bool{
|
||||
loadedTypes = [4]bool{
|
||||
_q.withGroups != nil,
|
||||
_q.withProxy != nil,
|
||||
_q.withParent != nil,
|
||||
_q.withChildren != nil,
|
||||
_q.withUsageLogs != nil,
|
||||
_q.withAccountGroups != nil,
|
||||
}
|
||||
@@ -594,19 +522,6 @@ func (_q *AccountQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Acco
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if query := _q.withParent; query != nil {
|
||||
if err := _q.loadParent(ctx, query, nodes, nil,
|
||||
func(n *Account, e *Account) { n.Edges.Parent = e }); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if query := _q.withChildren; query != nil {
|
||||
if err := _q.loadChildren(ctx, query, nodes,
|
||||
func(n *Account) { n.Edges.Children = []*Account{} },
|
||||
func(n *Account, e *Account) { n.Edges.Children = append(n.Edges.Children, e) }); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if query := _q.withUsageLogs; query != nil {
|
||||
if err := _q.loadUsageLogs(ctx, query, nodes,
|
||||
func(n *Account) { n.Edges.UsageLogs = []*UsageLog{} },
|
||||
@@ -717,71 +632,6 @@ func (_q *AccountQuery) loadProxy(ctx context.Context, query *ProxyQuery, nodes
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (_q *AccountQuery) loadParent(ctx context.Context, query *AccountQuery, nodes []*Account, init func(*Account), assign func(*Account, *Account)) error {
|
||||
ids := make([]int64, 0, len(nodes))
|
||||
nodeids := make(map[int64][]*Account)
|
||||
for i := range nodes {
|
||||
if nodes[i].ParentAccountID == nil {
|
||||
continue
|
||||
}
|
||||
fk := *nodes[i].ParentAccountID
|
||||
if _, ok := nodeids[fk]; !ok {
|
||||
ids = append(ids, fk)
|
||||
}
|
||||
nodeids[fk] = append(nodeids[fk], nodes[i])
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
query.Where(account.IDIn(ids...))
|
||||
neighbors, err := query.All(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, n := range neighbors {
|
||||
nodes, ok := nodeids[n.ID]
|
||||
if !ok {
|
||||
return fmt.Errorf(`unexpected foreign-key "parent_account_id" returned %v`, n.ID)
|
||||
}
|
||||
for i := range nodes {
|
||||
assign(nodes[i], n)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (_q *AccountQuery) loadChildren(ctx context.Context, query *AccountQuery, nodes []*Account, init func(*Account), assign func(*Account, *Account)) error {
|
||||
fks := make([]driver.Value, 0, len(nodes))
|
||||
nodeids := make(map[int64]*Account)
|
||||
for i := range nodes {
|
||||
fks = append(fks, nodes[i].ID)
|
||||
nodeids[nodes[i].ID] = nodes[i]
|
||||
if init != nil {
|
||||
init(nodes[i])
|
||||
}
|
||||
}
|
||||
if len(query.ctx.Fields) > 0 {
|
||||
query.ctx.AppendFieldOnce(account.FieldParentAccountID)
|
||||
}
|
||||
query.Where(predicate.Account(func(s *sql.Selector) {
|
||||
s.Where(sql.InValues(s.C(account.ChildrenColumn), fks...))
|
||||
}))
|
||||
neighbors, err := query.All(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, n := range neighbors {
|
||||
fk := n.ParentAccountID
|
||||
if fk == nil {
|
||||
return fmt.Errorf(`foreign-key "parent_account_id" is nil for node %v`, n.ID)
|
||||
}
|
||||
node, ok := nodeids[*fk]
|
||||
if !ok {
|
||||
return fmt.Errorf(`unexpected referenced foreign-key "parent_account_id" returned %v for node %v`, *fk, n.ID)
|
||||
}
|
||||
assign(node, n)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (_q *AccountQuery) loadUsageLogs(ctx context.Context, query *UsageLogQuery, nodes []*Account, init func(*Account), assign func(*Account, *UsageLog)) error {
|
||||
fks := make([]driver.Value, 0, len(nodes))
|
||||
nodeids := make(map[int64]*Account)
|
||||
@@ -874,9 +724,6 @@ func (_q *AccountQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
if _q.withProxy != nil {
|
||||
_spec.Node.AddColumnOnce(account.FieldProxyID)
|
||||
}
|
||||
if _q.withParent != nil {
|
||||
_spec.Node.AddColumnOnce(account.FieldParentAccountID)
|
||||
}
|
||||
}
|
||||
if ps := _q.predicates; len(ps) > 0 {
|
||||
_spec.Predicate = func(selector *sql.Selector) {
|
||||
|
||||
@@ -151,33 +151,6 @@ func (_u *AccountUpdate) ClearProxyID() *AccountUpdate {
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetProxyFallbackOriginID sets the "proxy_fallback_origin_id" field.
|
||||
func (_u *AccountUpdate) SetProxyFallbackOriginID(v int64) *AccountUpdate {
|
||||
_u.mutation.ResetProxyFallbackOriginID()
|
||||
_u.mutation.SetProxyFallbackOriginID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableProxyFallbackOriginID sets the "proxy_fallback_origin_id" field if the given value is not nil.
|
||||
func (_u *AccountUpdate) SetNillableProxyFallbackOriginID(v *int64) *AccountUpdate {
|
||||
if v != nil {
|
||||
_u.SetProxyFallbackOriginID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddProxyFallbackOriginID adds value to the "proxy_fallback_origin_id" field.
|
||||
func (_u *AccountUpdate) AddProxyFallbackOriginID(v int64) *AccountUpdate {
|
||||
_u.mutation.AddProxyFallbackOriginID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearProxyFallbackOriginID clears the value of the "proxy_fallback_origin_id" field.
|
||||
func (_u *AccountUpdate) ClearProxyFallbackOriginID() *AccountUpdate {
|
||||
_u.mutation.ClearProxyFallbackOriginID()
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetConcurrency sets the "concurrency" field.
|
||||
func (_u *AccountUpdate) SetConcurrency(v int) *AccountUpdate {
|
||||
_u.mutation.ResetConcurrency()
|
||||
@@ -530,40 +503,6 @@ func (_u *AccountUpdate) ClearSessionWindowStatus() *AccountUpdate {
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetParentAccountID sets the "parent_account_id" field.
|
||||
func (_u *AccountUpdate) SetParentAccountID(v int64) *AccountUpdate {
|
||||
_u.mutation.SetParentAccountID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableParentAccountID sets the "parent_account_id" field if the given value is not nil.
|
||||
func (_u *AccountUpdate) SetNillableParentAccountID(v *int64) *AccountUpdate {
|
||||
if v != nil {
|
||||
_u.SetParentAccountID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearParentAccountID clears the value of the "parent_account_id" field.
|
||||
func (_u *AccountUpdate) ClearParentAccountID() *AccountUpdate {
|
||||
_u.mutation.ClearParentAccountID()
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetQuotaDimension sets the "quota_dimension" field.
|
||||
func (_u *AccountUpdate) SetQuotaDimension(v account.QuotaDimension) *AccountUpdate {
|
||||
_u.mutation.SetQuotaDimension(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableQuotaDimension sets the "quota_dimension" field if the given value is not nil.
|
||||
func (_u *AccountUpdate) SetNillableQuotaDimension(v *account.QuotaDimension) *AccountUpdate {
|
||||
if v != nil {
|
||||
_u.SetQuotaDimension(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddGroupIDs adds the "groups" edge to the Group entity by IDs.
|
||||
func (_u *AccountUpdate) AddGroupIDs(ids ...int64) *AccountUpdate {
|
||||
_u.mutation.AddGroupIDs(ids...)
|
||||
@@ -584,40 +523,6 @@ func (_u *AccountUpdate) SetProxy(v *Proxy) *AccountUpdate {
|
||||
return _u.SetProxyID(v.ID)
|
||||
}
|
||||
|
||||
// SetParentID sets the "parent" edge to the Account entity by ID.
|
||||
func (_u *AccountUpdate) SetParentID(id int64) *AccountUpdate {
|
||||
_u.mutation.SetParentID(id)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableParentID sets the "parent" edge to the Account entity by ID if the given value is not nil.
|
||||
func (_u *AccountUpdate) SetNillableParentID(id *int64) *AccountUpdate {
|
||||
if id != nil {
|
||||
_u = _u.SetParentID(*id)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetParent sets the "parent" edge to the Account entity.
|
||||
func (_u *AccountUpdate) SetParent(v *Account) *AccountUpdate {
|
||||
return _u.SetParentID(v.ID)
|
||||
}
|
||||
|
||||
// AddChildIDs adds the "children" edge to the Account entity by IDs.
|
||||
func (_u *AccountUpdate) AddChildIDs(ids ...int64) *AccountUpdate {
|
||||
_u.mutation.AddChildIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddChildren adds the "children" edges to the Account entity.
|
||||
func (_u *AccountUpdate) AddChildren(v ...*Account) *AccountUpdate {
|
||||
ids := make([]int64, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.AddChildIDs(ids...)
|
||||
}
|
||||
|
||||
// AddUsageLogIDs adds the "usage_logs" edge to the UsageLog entity by IDs.
|
||||
func (_u *AccountUpdate) AddUsageLogIDs(ids ...int64) *AccountUpdate {
|
||||
_u.mutation.AddUsageLogIDs(ids...)
|
||||
@@ -665,33 +570,6 @@ func (_u *AccountUpdate) ClearProxy() *AccountUpdate {
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearParent clears the "parent" edge to the Account entity.
|
||||
func (_u *AccountUpdate) ClearParent() *AccountUpdate {
|
||||
_u.mutation.ClearParent()
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearChildren clears all "children" edges to the Account entity.
|
||||
func (_u *AccountUpdate) ClearChildren() *AccountUpdate {
|
||||
_u.mutation.ClearChildren()
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveChildIDs removes the "children" edge to Account entities by IDs.
|
||||
func (_u *AccountUpdate) RemoveChildIDs(ids ...int64) *AccountUpdate {
|
||||
_u.mutation.RemoveChildIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveChildren removes "children" edges to Account entities.
|
||||
func (_u *AccountUpdate) RemoveChildren(v ...*Account) *AccountUpdate {
|
||||
ids := make([]int64, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.RemoveChildIDs(ids...)
|
||||
}
|
||||
|
||||
// ClearUsageLogs clears all "usage_logs" edges to the UsageLog entity.
|
||||
func (_u *AccountUpdate) ClearUsageLogs() *AccountUpdate {
|
||||
_u.mutation.ClearUsageLogs()
|
||||
@@ -782,11 +660,6 @@ func (_u *AccountUpdate) check() error {
|
||||
return &ValidationError{Name: "session_window_status", err: fmt.Errorf(`ent: validator failed for field "Account.session_window_status": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.QuotaDimension(); ok {
|
||||
if err := account.QuotaDimensionValidator(v); err != nil {
|
||||
return &ValidationError{Name: "quota_dimension", err: fmt.Errorf(`ent: validator failed for field "Account.quota_dimension": %w`, err)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -832,15 +705,6 @@ func (_u *AccountUpdate) sqlSave(ctx context.Context) (_node int, err error) {
|
||||
if value, ok := _u.mutation.Extra(); ok {
|
||||
_spec.SetField(account.FieldExtra, field.TypeJSON, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ProxyFallbackOriginID(); ok {
|
||||
_spec.SetField(account.FieldProxyFallbackOriginID, field.TypeInt64, value)
|
||||
}
|
||||
if value, ok := _u.mutation.AddedProxyFallbackOriginID(); ok {
|
||||
_spec.AddField(account.FieldProxyFallbackOriginID, field.TypeInt64, value)
|
||||
}
|
||||
if _u.mutation.ProxyFallbackOriginIDCleared() {
|
||||
_spec.ClearField(account.FieldProxyFallbackOriginID, field.TypeInt64)
|
||||
}
|
||||
if value, ok := _u.mutation.Concurrency(); ok {
|
||||
_spec.SetField(account.FieldConcurrency, field.TypeInt, value)
|
||||
}
|
||||
@@ -943,9 +807,6 @@ func (_u *AccountUpdate) sqlSave(ctx context.Context) (_node int, err error) {
|
||||
if _u.mutation.SessionWindowStatusCleared() {
|
||||
_spec.ClearField(account.FieldSessionWindowStatus, field.TypeString)
|
||||
}
|
||||
if value, ok := _u.mutation.QuotaDimension(); ok {
|
||||
_spec.SetField(account.FieldQuotaDimension, field.TypeEnum, value)
|
||||
}
|
||||
if _u.mutation.GroupsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2M,
|
||||
@@ -1032,80 +893,6 @@ func (_u *AccountUpdate) sqlSave(ctx context.Context) (_node int, err error) {
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if _u.mutation.ParentCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: account.ParentTable,
|
||||
Columns: []string{account.ParentColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.ParentIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: account.ParentTable,
|
||||
Columns: []string{account.ParentColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if _u.mutation.ChildrenCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: account.ChildrenTable,
|
||||
Columns: []string{account.ChildrenColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.RemovedChildrenIDs(); len(nodes) > 0 && !_u.mutation.ChildrenCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: account.ChildrenTable,
|
||||
Columns: []string{account.ChildrenColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.ChildrenIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: account.ChildrenTable,
|
||||
Columns: []string{account.ChildrenColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if _u.mutation.UsageLogsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
@@ -1291,33 +1078,6 @@ func (_u *AccountUpdateOne) ClearProxyID() *AccountUpdateOne {
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetProxyFallbackOriginID sets the "proxy_fallback_origin_id" field.
|
||||
func (_u *AccountUpdateOne) SetProxyFallbackOriginID(v int64) *AccountUpdateOne {
|
||||
_u.mutation.ResetProxyFallbackOriginID()
|
||||
_u.mutation.SetProxyFallbackOriginID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableProxyFallbackOriginID sets the "proxy_fallback_origin_id" field if the given value is not nil.
|
||||
func (_u *AccountUpdateOne) SetNillableProxyFallbackOriginID(v *int64) *AccountUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetProxyFallbackOriginID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddProxyFallbackOriginID adds value to the "proxy_fallback_origin_id" field.
|
||||
func (_u *AccountUpdateOne) AddProxyFallbackOriginID(v int64) *AccountUpdateOne {
|
||||
_u.mutation.AddProxyFallbackOriginID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearProxyFallbackOriginID clears the value of the "proxy_fallback_origin_id" field.
|
||||
func (_u *AccountUpdateOne) ClearProxyFallbackOriginID() *AccountUpdateOne {
|
||||
_u.mutation.ClearProxyFallbackOriginID()
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetConcurrency sets the "concurrency" field.
|
||||
func (_u *AccountUpdateOne) SetConcurrency(v int) *AccountUpdateOne {
|
||||
_u.mutation.ResetConcurrency()
|
||||
@@ -1670,40 +1430,6 @@ func (_u *AccountUpdateOne) ClearSessionWindowStatus() *AccountUpdateOne {
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetParentAccountID sets the "parent_account_id" field.
|
||||
func (_u *AccountUpdateOne) SetParentAccountID(v int64) *AccountUpdateOne {
|
||||
_u.mutation.SetParentAccountID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableParentAccountID sets the "parent_account_id" field if the given value is not nil.
|
||||
func (_u *AccountUpdateOne) SetNillableParentAccountID(v *int64) *AccountUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetParentAccountID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearParentAccountID clears the value of the "parent_account_id" field.
|
||||
func (_u *AccountUpdateOne) ClearParentAccountID() *AccountUpdateOne {
|
||||
_u.mutation.ClearParentAccountID()
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetQuotaDimension sets the "quota_dimension" field.
|
||||
func (_u *AccountUpdateOne) SetQuotaDimension(v account.QuotaDimension) *AccountUpdateOne {
|
||||
_u.mutation.SetQuotaDimension(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableQuotaDimension sets the "quota_dimension" field if the given value is not nil.
|
||||
func (_u *AccountUpdateOne) SetNillableQuotaDimension(v *account.QuotaDimension) *AccountUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetQuotaDimension(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddGroupIDs adds the "groups" edge to the Group entity by IDs.
|
||||
func (_u *AccountUpdateOne) AddGroupIDs(ids ...int64) *AccountUpdateOne {
|
||||
_u.mutation.AddGroupIDs(ids...)
|
||||
@@ -1724,40 +1450,6 @@ func (_u *AccountUpdateOne) SetProxy(v *Proxy) *AccountUpdateOne {
|
||||
return _u.SetProxyID(v.ID)
|
||||
}
|
||||
|
||||
// SetParentID sets the "parent" edge to the Account entity by ID.
|
||||
func (_u *AccountUpdateOne) SetParentID(id int64) *AccountUpdateOne {
|
||||
_u.mutation.SetParentID(id)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableParentID sets the "parent" edge to the Account entity by ID if the given value is not nil.
|
||||
func (_u *AccountUpdateOne) SetNillableParentID(id *int64) *AccountUpdateOne {
|
||||
if id != nil {
|
||||
_u = _u.SetParentID(*id)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetParent sets the "parent" edge to the Account entity.
|
||||
func (_u *AccountUpdateOne) SetParent(v *Account) *AccountUpdateOne {
|
||||
return _u.SetParentID(v.ID)
|
||||
}
|
||||
|
||||
// AddChildIDs adds the "children" edge to the Account entity by IDs.
|
||||
func (_u *AccountUpdateOne) AddChildIDs(ids ...int64) *AccountUpdateOne {
|
||||
_u.mutation.AddChildIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddChildren adds the "children" edges to the Account entity.
|
||||
func (_u *AccountUpdateOne) AddChildren(v ...*Account) *AccountUpdateOne {
|
||||
ids := make([]int64, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.AddChildIDs(ids...)
|
||||
}
|
||||
|
||||
// AddUsageLogIDs adds the "usage_logs" edge to the UsageLog entity by IDs.
|
||||
func (_u *AccountUpdateOne) AddUsageLogIDs(ids ...int64) *AccountUpdateOne {
|
||||
_u.mutation.AddUsageLogIDs(ids...)
|
||||
@@ -1805,33 +1497,6 @@ func (_u *AccountUpdateOne) ClearProxy() *AccountUpdateOne {
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearParent clears the "parent" edge to the Account entity.
|
||||
func (_u *AccountUpdateOne) ClearParent() *AccountUpdateOne {
|
||||
_u.mutation.ClearParent()
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearChildren clears all "children" edges to the Account entity.
|
||||
func (_u *AccountUpdateOne) ClearChildren() *AccountUpdateOne {
|
||||
_u.mutation.ClearChildren()
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveChildIDs removes the "children" edge to Account entities by IDs.
|
||||
func (_u *AccountUpdateOne) RemoveChildIDs(ids ...int64) *AccountUpdateOne {
|
||||
_u.mutation.RemoveChildIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveChildren removes "children" edges to Account entities.
|
||||
func (_u *AccountUpdateOne) RemoveChildren(v ...*Account) *AccountUpdateOne {
|
||||
ids := make([]int64, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.RemoveChildIDs(ids...)
|
||||
}
|
||||
|
||||
// ClearUsageLogs clears all "usage_logs" edges to the UsageLog entity.
|
||||
func (_u *AccountUpdateOne) ClearUsageLogs() *AccountUpdateOne {
|
||||
_u.mutation.ClearUsageLogs()
|
||||
@@ -1935,11 +1600,6 @@ func (_u *AccountUpdateOne) check() error {
|
||||
return &ValidationError{Name: "session_window_status", err: fmt.Errorf(`ent: validator failed for field "Account.session_window_status": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.QuotaDimension(); ok {
|
||||
if err := account.QuotaDimensionValidator(v); err != nil {
|
||||
return &ValidationError{Name: "quota_dimension", err: fmt.Errorf(`ent: validator failed for field "Account.quota_dimension": %w`, err)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -2002,15 +1662,6 @@ func (_u *AccountUpdateOne) sqlSave(ctx context.Context) (_node *Account, err er
|
||||
if value, ok := _u.mutation.Extra(); ok {
|
||||
_spec.SetField(account.FieldExtra, field.TypeJSON, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ProxyFallbackOriginID(); ok {
|
||||
_spec.SetField(account.FieldProxyFallbackOriginID, field.TypeInt64, value)
|
||||
}
|
||||
if value, ok := _u.mutation.AddedProxyFallbackOriginID(); ok {
|
||||
_spec.AddField(account.FieldProxyFallbackOriginID, field.TypeInt64, value)
|
||||
}
|
||||
if _u.mutation.ProxyFallbackOriginIDCleared() {
|
||||
_spec.ClearField(account.FieldProxyFallbackOriginID, field.TypeInt64)
|
||||
}
|
||||
if value, ok := _u.mutation.Concurrency(); ok {
|
||||
_spec.SetField(account.FieldConcurrency, field.TypeInt, value)
|
||||
}
|
||||
@@ -2113,9 +1764,6 @@ func (_u *AccountUpdateOne) sqlSave(ctx context.Context) (_node *Account, err er
|
||||
if _u.mutation.SessionWindowStatusCleared() {
|
||||
_spec.ClearField(account.FieldSessionWindowStatus, field.TypeString)
|
||||
}
|
||||
if value, ok := _u.mutation.QuotaDimension(); ok {
|
||||
_spec.SetField(account.FieldQuotaDimension, field.TypeEnum, value)
|
||||
}
|
||||
if _u.mutation.GroupsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2M,
|
||||
@@ -2202,80 +1850,6 @@ func (_u *AccountUpdateOne) sqlSave(ctx context.Context) (_node *Account, err er
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if _u.mutation.ParentCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: account.ParentTable,
|
||||
Columns: []string{account.ParentColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.ParentIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: account.ParentTable,
|
||||
Columns: []string{account.ParentColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if _u.mutation.ChildrenCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: account.ChildrenTable,
|
||||
Columns: []string{account.ChildrenColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.RemovedChildrenIDs(); len(nodes) > 0 && !_u.mutation.ChildrenCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: account.ChildrenTable,
|
||||
Columns: []string{account.ChildrenColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.ChildrenIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: account.ChildrenTable,
|
||||
Columns: []string{account.ChildrenColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(account.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if _u.mutation.UsageLogsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
|
||||
@@ -1,266 +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"
|
||||
"github.com/Wei-Shaw/sub2api/ent/authidentity"
|
||||
"github.com/Wei-Shaw/sub2api/ent/user"
|
||||
)
|
||||
|
||||
// AuthIdentity is the model entity for the AuthIdentity schema.
|
||||
type AuthIdentity struct {
|
||||
config `json:"-"`
|
||||
// ID of the ent.
|
||||
ID int64 `json:"id,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"`
|
||||
// UserID holds the value of the "user_id" field.
|
||||
UserID int64 `json:"user_id,omitempty"`
|
||||
// ProviderType holds the value of the "provider_type" field.
|
||||
ProviderType string `json:"provider_type,omitempty"`
|
||||
// ProviderKey holds the value of the "provider_key" field.
|
||||
ProviderKey string `json:"provider_key,omitempty"`
|
||||
// ProviderSubject holds the value of the "provider_subject" field.
|
||||
ProviderSubject string `json:"provider_subject,omitempty"`
|
||||
// VerifiedAt holds the value of the "verified_at" field.
|
||||
VerifiedAt *time.Time `json:"verified_at,omitempty"`
|
||||
// Issuer holds the value of the "issuer" field.
|
||||
Issuer *string `json:"issuer,omitempty"`
|
||||
// Metadata holds the value of the "metadata" field.
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
// Edges holds the relations/edges for other nodes in the graph.
|
||||
// The values are being populated by the AuthIdentityQuery when eager-loading is set.
|
||||
Edges AuthIdentityEdges `json:"edges"`
|
||||
selectValues sql.SelectValues
|
||||
}
|
||||
|
||||
// AuthIdentityEdges holds the relations/edges for other nodes in the graph.
|
||||
type AuthIdentityEdges struct {
|
||||
// User holds the value of the user edge.
|
||||
User *User `json:"user,omitempty"`
|
||||
// Channels holds the value of the channels edge.
|
||||
Channels []*AuthIdentityChannel `json:"channels,omitempty"`
|
||||
// AdoptionDecisions holds the value of the adoption_decisions edge.
|
||||
AdoptionDecisions []*IdentityAdoptionDecision `json:"adoption_decisions,omitempty"`
|
||||
// loadedTypes holds the information for reporting if a
|
||||
// type was loaded (or requested) in eager-loading or not.
|
||||
loadedTypes [3]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 AuthIdentityEdges) 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"}
|
||||
}
|
||||
|
||||
// ChannelsOrErr returns the Channels value or an error if the edge
|
||||
// was not loaded in eager-loading.
|
||||
func (e AuthIdentityEdges) ChannelsOrErr() ([]*AuthIdentityChannel, error) {
|
||||
if e.loadedTypes[1] {
|
||||
return e.Channels, nil
|
||||
}
|
||||
return nil, &NotLoadedError{edge: "channels"}
|
||||
}
|
||||
|
||||
// AdoptionDecisionsOrErr returns the AdoptionDecisions value or an error if the edge
|
||||
// was not loaded in eager-loading.
|
||||
func (e AuthIdentityEdges) AdoptionDecisionsOrErr() ([]*IdentityAdoptionDecision, error) {
|
||||
if e.loadedTypes[2] {
|
||||
return e.AdoptionDecisions, nil
|
||||
}
|
||||
return nil, &NotLoadedError{edge: "adoption_decisions"}
|
||||
}
|
||||
|
||||
// scanValues returns the types for scanning values from sql.Rows.
|
||||
func (*AuthIdentity) scanValues(columns []string) ([]any, error) {
|
||||
values := make([]any, len(columns))
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case authidentity.FieldMetadata:
|
||||
values[i] = new([]byte)
|
||||
case authidentity.FieldID, authidentity.FieldUserID:
|
||||
values[i] = new(sql.NullInt64)
|
||||
case authidentity.FieldProviderType, authidentity.FieldProviderKey, authidentity.FieldProviderSubject, authidentity.FieldIssuer:
|
||||
values[i] = new(sql.NullString)
|
||||
case authidentity.FieldCreatedAt, authidentity.FieldUpdatedAt, authidentity.FieldVerifiedAt:
|
||||
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 AuthIdentity fields.
|
||||
func (_m *AuthIdentity) 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 authidentity.FieldID:
|
||||
value, ok := values[i].(*sql.NullInt64)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field id", value)
|
||||
}
|
||||
_m.ID = int64(value.Int64)
|
||||
case authidentity.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 authidentity.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
|
||||
}
|
||||
case authidentity.FieldUserID:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field user_id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.UserID = value.Int64
|
||||
}
|
||||
case authidentity.FieldProviderType:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field provider_type", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ProviderType = value.String
|
||||
}
|
||||
case authidentity.FieldProviderKey:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field provider_key", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ProviderKey = value.String
|
||||
}
|
||||
case authidentity.FieldProviderSubject:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field provider_subject", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ProviderSubject = value.String
|
||||
}
|
||||
case authidentity.FieldVerifiedAt:
|
||||
if value, ok := values[i].(*sql.NullTime); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field verified_at", values[i])
|
||||
} else if value.Valid {
|
||||
_m.VerifiedAt = new(time.Time)
|
||||
*_m.VerifiedAt = value.Time
|
||||
}
|
||||
case authidentity.FieldIssuer:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field issuer", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Issuer = new(string)
|
||||
*_m.Issuer = value.String
|
||||
}
|
||||
case authidentity.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)
|
||||
}
|
||||
}
|
||||
default:
|
||||
_m.selectValues.Set(columns[i], values[i])
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Value returns the ent.Value that was dynamically selected and assigned to the AuthIdentity.
|
||||
// This includes values selected through modifiers, order, etc.
|
||||
func (_m *AuthIdentity) Value(name string) (ent.Value, error) {
|
||||
return _m.selectValues.Get(name)
|
||||
}
|
||||
|
||||
// QueryUser queries the "user" edge of the AuthIdentity entity.
|
||||
func (_m *AuthIdentity) QueryUser() *UserQuery {
|
||||
return NewAuthIdentityClient(_m.config).QueryUser(_m)
|
||||
}
|
||||
|
||||
// QueryChannels queries the "channels" edge of the AuthIdentity entity.
|
||||
func (_m *AuthIdentity) QueryChannels() *AuthIdentityChannelQuery {
|
||||
return NewAuthIdentityClient(_m.config).QueryChannels(_m)
|
||||
}
|
||||
|
||||
// QueryAdoptionDecisions queries the "adoption_decisions" edge of the AuthIdentity entity.
|
||||
func (_m *AuthIdentity) QueryAdoptionDecisions() *IdentityAdoptionDecisionQuery {
|
||||
return NewAuthIdentityClient(_m.config).QueryAdoptionDecisions(_m)
|
||||
}
|
||||
|
||||
// Update returns a builder for updating this AuthIdentity.
|
||||
// Note that you need to call AuthIdentity.Unwrap() before calling this method if this AuthIdentity
|
||||
// was returned from a transaction, and the transaction was committed or rolled back.
|
||||
func (_m *AuthIdentity) Update() *AuthIdentityUpdateOne {
|
||||
return NewAuthIdentityClient(_m.config).UpdateOne(_m)
|
||||
}
|
||||
|
||||
// Unwrap unwraps the AuthIdentity 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 *AuthIdentity) Unwrap() *AuthIdentity {
|
||||
_tx, ok := _m.config.driver.(*txDriver)
|
||||
if !ok {
|
||||
panic("ent: AuthIdentity is not a transactional entity")
|
||||
}
|
||||
_m.config.driver = _tx.drv
|
||||
return _m
|
||||
}
|
||||
|
||||
// String implements the fmt.Stringer.
|
||||
func (_m *AuthIdentity) String() string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString("AuthIdentity(")
|
||||
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
|
||||
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.WriteString(", ")
|
||||
builder.WriteString("user_id=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.UserID))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("provider_type=")
|
||||
builder.WriteString(_m.ProviderType)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("provider_key=")
|
||||
builder.WriteString(_m.ProviderKey)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("provider_subject=")
|
||||
builder.WriteString(_m.ProviderSubject)
|
||||
builder.WriteString(", ")
|
||||
if v := _m.VerifiedAt; v != nil {
|
||||
builder.WriteString("verified_at=")
|
||||
builder.WriteString(v.Format(time.ANSIC))
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.Issuer; v != nil {
|
||||
builder.WriteString("issuer=")
|
||||
builder.WriteString(*v)
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("metadata=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.Metadata))
|
||||
builder.WriteByte(')')
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// AuthIdentities is a parsable slice of AuthIdentity.
|
||||
type AuthIdentities []*AuthIdentity
|
||||
@@ -1,209 +0,0 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package authidentity
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
)
|
||||
|
||||
const (
|
||||
// Label holds the string label denoting the authidentity type in the database.
|
||||
Label = "auth_identity"
|
||||
// FieldID holds the string denoting the id field in the database.
|
||||
FieldID = "id"
|
||||
// FieldCreatedAt holds the string denoting the created_at field in the database.
|
||||
FieldCreatedAt = "created_at"
|
||||
// FieldUpdatedAt holds the string denoting the updated_at field in the database.
|
||||
FieldUpdatedAt = "updated_at"
|
||||
// FieldUserID holds the string denoting the user_id field in the database.
|
||||
FieldUserID = "user_id"
|
||||
// FieldProviderType holds the string denoting the provider_type field in the database.
|
||||
FieldProviderType = "provider_type"
|
||||
// FieldProviderKey holds the string denoting the provider_key field in the database.
|
||||
FieldProviderKey = "provider_key"
|
||||
// FieldProviderSubject holds the string denoting the provider_subject field in the database.
|
||||
FieldProviderSubject = "provider_subject"
|
||||
// FieldVerifiedAt holds the string denoting the verified_at field in the database.
|
||||
FieldVerifiedAt = "verified_at"
|
||||
// FieldIssuer holds the string denoting the issuer field in the database.
|
||||
FieldIssuer = "issuer"
|
||||
// FieldMetadata holds the string denoting the metadata field in the database.
|
||||
FieldMetadata = "metadata"
|
||||
// EdgeUser holds the string denoting the user edge name in mutations.
|
||||
EdgeUser = "user"
|
||||
// EdgeChannels holds the string denoting the channels edge name in mutations.
|
||||
EdgeChannels = "channels"
|
||||
// EdgeAdoptionDecisions holds the string denoting the adoption_decisions edge name in mutations.
|
||||
EdgeAdoptionDecisions = "adoption_decisions"
|
||||
// Table holds the table name of the authidentity in the database.
|
||||
Table = "auth_identities"
|
||||
// UserTable is the table that holds the user relation/edge.
|
||||
UserTable = "auth_identities"
|
||||
// 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"
|
||||
// ChannelsTable is the table that holds the channels relation/edge.
|
||||
ChannelsTable = "auth_identity_channels"
|
||||
// ChannelsInverseTable is the table name for the AuthIdentityChannel entity.
|
||||
// It exists in this package in order to avoid circular dependency with the "authidentitychannel" package.
|
||||
ChannelsInverseTable = "auth_identity_channels"
|
||||
// ChannelsColumn is the table column denoting the channels relation/edge.
|
||||
ChannelsColumn = "identity_id"
|
||||
// AdoptionDecisionsTable is the table that holds the adoption_decisions relation/edge.
|
||||
AdoptionDecisionsTable = "identity_adoption_decisions"
|
||||
// AdoptionDecisionsInverseTable is the table name for the IdentityAdoptionDecision entity.
|
||||
// It exists in this package in order to avoid circular dependency with the "identityadoptiondecision" package.
|
||||
AdoptionDecisionsInverseTable = "identity_adoption_decisions"
|
||||
// AdoptionDecisionsColumn is the table column denoting the adoption_decisions relation/edge.
|
||||
AdoptionDecisionsColumn = "identity_id"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns for authidentity fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldCreatedAt,
|
||||
FieldUpdatedAt,
|
||||
FieldUserID,
|
||||
FieldProviderType,
|
||||
FieldProviderKey,
|
||||
FieldProviderSubject,
|
||||
FieldVerifiedAt,
|
||||
FieldIssuer,
|
||||
FieldMetadata,
|
||||
}
|
||||
|
||||
// ValidColumn reports if the column name is valid (part of the table columns).
|
||||
func ValidColumn(column string) bool {
|
||||
for i := range Columns {
|
||||
if column == Columns[i] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var (
|
||||
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
|
||||
DefaultCreatedAt func() time.Time
|
||||
// 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
|
||||
// ProviderTypeValidator is a validator for the "provider_type" field. It is called by the builders before save.
|
||||
ProviderTypeValidator func(string) error
|
||||
// ProviderKeyValidator is a validator for the "provider_key" field. It is called by the builders before save.
|
||||
ProviderKeyValidator func(string) error
|
||||
// ProviderSubjectValidator is a validator for the "provider_subject" field. It is called by the builders before save.
|
||||
ProviderSubjectValidator func(string) error
|
||||
// DefaultMetadata holds the default value on creation for the "metadata" field.
|
||||
DefaultMetadata func() map[string]interface{}
|
||||
)
|
||||
|
||||
// OrderOption defines the ordering options for the AuthIdentity queries.
|
||||
type OrderOption func(*sql.Selector)
|
||||
|
||||
// ByID orders the results by the id field.
|
||||
func ByID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByCreatedAt orders the results by the created_at field.
|
||||
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByUpdatedAt orders the results by the updated_at field.
|
||||
func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByUserID orders the results by the user_id field.
|
||||
func ByUserID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldUserID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByProviderType orders the results by the provider_type field.
|
||||
func ByProviderType(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldProviderType, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByProviderKey orders the results by the provider_key field.
|
||||
func ByProviderKey(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldProviderKey, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByProviderSubject orders the results by the provider_subject field.
|
||||
func ByProviderSubject(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldProviderSubject, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByVerifiedAt orders the results by the verified_at field.
|
||||
func ByVerifiedAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldVerifiedAt, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByIssuer orders the results by the issuer field.
|
||||
func ByIssuer(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldIssuer, 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...))
|
||||
}
|
||||
}
|
||||
|
||||
// ByChannelsCount orders the results by channels count.
|
||||
func ByChannelsCount(opts ...sql.OrderTermOption) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborsCount(s, newChannelsStep(), opts...)
|
||||
}
|
||||
}
|
||||
|
||||
// ByChannels orders the results by channels terms.
|
||||
func ByChannels(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborTerms(s, newChannelsStep(), append([]sql.OrderTerm{term}, terms...)...)
|
||||
}
|
||||
}
|
||||
|
||||
// ByAdoptionDecisionsCount orders the results by adoption_decisions count.
|
||||
func ByAdoptionDecisionsCount(opts ...sql.OrderTermOption) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborsCount(s, newAdoptionDecisionsStep(), opts...)
|
||||
}
|
||||
}
|
||||
|
||||
// ByAdoptionDecisions orders the results by adoption_decisions terms.
|
||||
func ByAdoptionDecisions(term sql.OrderTerm, terms ...sql.OrderTerm) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborTerms(s, newAdoptionDecisionsStep(), append([]sql.OrderTerm{term}, terms...)...)
|
||||
}
|
||||
}
|
||||
func newUserStep() *sqlgraph.Step {
|
||||
return sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(UserInverseTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, true, UserTable, UserColumn),
|
||||
)
|
||||
}
|
||||
func newChannelsStep() *sqlgraph.Step {
|
||||
return sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(ChannelsInverseTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, ChannelsTable, ChannelsColumn),
|
||||
)
|
||||
}
|
||||
func newAdoptionDecisionsStep() *sqlgraph.Step {
|
||||
return sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(AdoptionDecisionsInverseTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, AdoptionDecisionsTable, AdoptionDecisionsColumn),
|
||||
)
|
||||
}
|
||||
@@ -1,600 +0,0 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package authidentity
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"github.com/Wei-Shaw/sub2api/ent/predicate"
|
||||
)
|
||||
|
||||
// ID filters vertices based on their ID field.
|
||||
func ID(id int64) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDEQ applies the EQ predicate on the ID field.
|
||||
func IDEQ(id int64) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDNEQ applies the NEQ predicate on the ID field.
|
||||
func IDNEQ(id int64) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldNEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDIn applies the In predicate on the ID field.
|
||||
func IDIn(ids ...int64) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDNotIn applies the NotIn predicate on the ID field.
|
||||
func IDNotIn(ids ...int64) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldNotIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDGT applies the GT predicate on the ID field.
|
||||
func IDGT(id int64) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldGT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDGTE applies the GTE predicate on the ID field.
|
||||
func IDGTE(id int64) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldGTE(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLT applies the LT predicate on the ID field.
|
||||
func IDLT(id int64) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldLT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLTE applies the LTE predicate on the ID field.
|
||||
func IDLTE(id int64) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldLTE(FieldID, id))
|
||||
}
|
||||
|
||||
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
|
||||
func CreatedAt(v time.Time) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(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.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldEQ(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ.
|
||||
func UserID(v int64) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldEQ(FieldUserID, v))
|
||||
}
|
||||
|
||||
// ProviderType applies equality check predicate on the "provider_type" field. It's identical to ProviderTypeEQ.
|
||||
func ProviderType(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldEQ(FieldProviderType, v))
|
||||
}
|
||||
|
||||
// ProviderKey applies equality check predicate on the "provider_key" field. It's identical to ProviderKeyEQ.
|
||||
func ProviderKey(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldEQ(FieldProviderKey, v))
|
||||
}
|
||||
|
||||
// ProviderSubject applies equality check predicate on the "provider_subject" field. It's identical to ProviderSubjectEQ.
|
||||
func ProviderSubject(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldEQ(FieldProviderSubject, v))
|
||||
}
|
||||
|
||||
// VerifiedAt applies equality check predicate on the "verified_at" field. It's identical to VerifiedAtEQ.
|
||||
func VerifiedAt(v time.Time) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldEQ(FieldVerifiedAt, v))
|
||||
}
|
||||
|
||||
// Issuer applies equality check predicate on the "issuer" field. It's identical to IssuerEQ.
|
||||
func Issuer(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldEQ(FieldIssuer, v))
|
||||
}
|
||||
|
||||
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
|
||||
func CreatedAtEQ(v time.Time) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldEQ(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
|
||||
func CreatedAtNEQ(v time.Time) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldNEQ(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtIn applies the In predicate on the "created_at" field.
|
||||
func CreatedAtIn(vs ...time.Time) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldIn(FieldCreatedAt, vs...))
|
||||
}
|
||||
|
||||
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
|
||||
func CreatedAtNotIn(vs ...time.Time) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldNotIn(FieldCreatedAt, vs...))
|
||||
}
|
||||
|
||||
// CreatedAtGT applies the GT predicate on the "created_at" field.
|
||||
func CreatedAtGT(v time.Time) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldGT(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
|
||||
func CreatedAtGTE(v time.Time) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldGTE(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtLT applies the LT predicate on the "created_at" field.
|
||||
func CreatedAtLT(v time.Time) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldLT(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
|
||||
func CreatedAtLTE(v time.Time) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldLTE(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
|
||||
func UpdatedAtEQ(v time.Time) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldEQ(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
|
||||
func UpdatedAtNEQ(v time.Time) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldNEQ(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtIn applies the In predicate on the "updated_at" field.
|
||||
func UpdatedAtIn(vs ...time.Time) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldIn(FieldUpdatedAt, vs...))
|
||||
}
|
||||
|
||||
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
|
||||
func UpdatedAtNotIn(vs ...time.Time) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldNotIn(FieldUpdatedAt, vs...))
|
||||
}
|
||||
|
||||
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
|
||||
func UpdatedAtGT(v time.Time) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldGT(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
|
||||
func UpdatedAtGTE(v time.Time) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldGTE(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
|
||||
func UpdatedAtLT(v time.Time) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldLT(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
|
||||
func UpdatedAtLTE(v time.Time) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldLTE(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UserIDEQ applies the EQ predicate on the "user_id" field.
|
||||
func UserIDEQ(v int64) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldEQ(FieldUserID, v))
|
||||
}
|
||||
|
||||
// UserIDNEQ applies the NEQ predicate on the "user_id" field.
|
||||
func UserIDNEQ(v int64) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldNEQ(FieldUserID, v))
|
||||
}
|
||||
|
||||
// UserIDIn applies the In predicate on the "user_id" field.
|
||||
func UserIDIn(vs ...int64) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldIn(FieldUserID, vs...))
|
||||
}
|
||||
|
||||
// UserIDNotIn applies the NotIn predicate on the "user_id" field.
|
||||
func UserIDNotIn(vs ...int64) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldNotIn(FieldUserID, vs...))
|
||||
}
|
||||
|
||||
// ProviderTypeEQ applies the EQ predicate on the "provider_type" field.
|
||||
func ProviderTypeEQ(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldEQ(FieldProviderType, v))
|
||||
}
|
||||
|
||||
// ProviderTypeNEQ applies the NEQ predicate on the "provider_type" field.
|
||||
func ProviderTypeNEQ(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldNEQ(FieldProviderType, v))
|
||||
}
|
||||
|
||||
// ProviderTypeIn applies the In predicate on the "provider_type" field.
|
||||
func ProviderTypeIn(vs ...string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldIn(FieldProviderType, vs...))
|
||||
}
|
||||
|
||||
// ProviderTypeNotIn applies the NotIn predicate on the "provider_type" field.
|
||||
func ProviderTypeNotIn(vs ...string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldNotIn(FieldProviderType, vs...))
|
||||
}
|
||||
|
||||
// ProviderTypeGT applies the GT predicate on the "provider_type" field.
|
||||
func ProviderTypeGT(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldGT(FieldProviderType, v))
|
||||
}
|
||||
|
||||
// ProviderTypeGTE applies the GTE predicate on the "provider_type" field.
|
||||
func ProviderTypeGTE(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldGTE(FieldProviderType, v))
|
||||
}
|
||||
|
||||
// ProviderTypeLT applies the LT predicate on the "provider_type" field.
|
||||
func ProviderTypeLT(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldLT(FieldProviderType, v))
|
||||
}
|
||||
|
||||
// ProviderTypeLTE applies the LTE predicate on the "provider_type" field.
|
||||
func ProviderTypeLTE(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldLTE(FieldProviderType, v))
|
||||
}
|
||||
|
||||
// ProviderTypeContains applies the Contains predicate on the "provider_type" field.
|
||||
func ProviderTypeContains(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldContains(FieldProviderType, v))
|
||||
}
|
||||
|
||||
// ProviderTypeHasPrefix applies the HasPrefix predicate on the "provider_type" field.
|
||||
func ProviderTypeHasPrefix(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldHasPrefix(FieldProviderType, v))
|
||||
}
|
||||
|
||||
// ProviderTypeHasSuffix applies the HasSuffix predicate on the "provider_type" field.
|
||||
func ProviderTypeHasSuffix(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldHasSuffix(FieldProviderType, v))
|
||||
}
|
||||
|
||||
// ProviderTypeEqualFold applies the EqualFold predicate on the "provider_type" field.
|
||||
func ProviderTypeEqualFold(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldEqualFold(FieldProviderType, v))
|
||||
}
|
||||
|
||||
// ProviderTypeContainsFold applies the ContainsFold predicate on the "provider_type" field.
|
||||
func ProviderTypeContainsFold(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldContainsFold(FieldProviderType, v))
|
||||
}
|
||||
|
||||
// ProviderKeyEQ applies the EQ predicate on the "provider_key" field.
|
||||
func ProviderKeyEQ(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldEQ(FieldProviderKey, v))
|
||||
}
|
||||
|
||||
// ProviderKeyNEQ applies the NEQ predicate on the "provider_key" field.
|
||||
func ProviderKeyNEQ(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldNEQ(FieldProviderKey, v))
|
||||
}
|
||||
|
||||
// ProviderKeyIn applies the In predicate on the "provider_key" field.
|
||||
func ProviderKeyIn(vs ...string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldIn(FieldProviderKey, vs...))
|
||||
}
|
||||
|
||||
// ProviderKeyNotIn applies the NotIn predicate on the "provider_key" field.
|
||||
func ProviderKeyNotIn(vs ...string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldNotIn(FieldProviderKey, vs...))
|
||||
}
|
||||
|
||||
// ProviderKeyGT applies the GT predicate on the "provider_key" field.
|
||||
func ProviderKeyGT(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldGT(FieldProviderKey, v))
|
||||
}
|
||||
|
||||
// ProviderKeyGTE applies the GTE predicate on the "provider_key" field.
|
||||
func ProviderKeyGTE(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldGTE(FieldProviderKey, v))
|
||||
}
|
||||
|
||||
// ProviderKeyLT applies the LT predicate on the "provider_key" field.
|
||||
func ProviderKeyLT(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldLT(FieldProviderKey, v))
|
||||
}
|
||||
|
||||
// ProviderKeyLTE applies the LTE predicate on the "provider_key" field.
|
||||
func ProviderKeyLTE(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldLTE(FieldProviderKey, v))
|
||||
}
|
||||
|
||||
// ProviderKeyContains applies the Contains predicate on the "provider_key" field.
|
||||
func ProviderKeyContains(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldContains(FieldProviderKey, v))
|
||||
}
|
||||
|
||||
// ProviderKeyHasPrefix applies the HasPrefix predicate on the "provider_key" field.
|
||||
func ProviderKeyHasPrefix(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldHasPrefix(FieldProviderKey, v))
|
||||
}
|
||||
|
||||
// ProviderKeyHasSuffix applies the HasSuffix predicate on the "provider_key" field.
|
||||
func ProviderKeyHasSuffix(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldHasSuffix(FieldProviderKey, v))
|
||||
}
|
||||
|
||||
// ProviderKeyEqualFold applies the EqualFold predicate on the "provider_key" field.
|
||||
func ProviderKeyEqualFold(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldEqualFold(FieldProviderKey, v))
|
||||
}
|
||||
|
||||
// ProviderKeyContainsFold applies the ContainsFold predicate on the "provider_key" field.
|
||||
func ProviderKeyContainsFold(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldContainsFold(FieldProviderKey, v))
|
||||
}
|
||||
|
||||
// ProviderSubjectEQ applies the EQ predicate on the "provider_subject" field.
|
||||
func ProviderSubjectEQ(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldEQ(FieldProviderSubject, v))
|
||||
}
|
||||
|
||||
// ProviderSubjectNEQ applies the NEQ predicate on the "provider_subject" field.
|
||||
func ProviderSubjectNEQ(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldNEQ(FieldProviderSubject, v))
|
||||
}
|
||||
|
||||
// ProviderSubjectIn applies the In predicate on the "provider_subject" field.
|
||||
func ProviderSubjectIn(vs ...string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldIn(FieldProviderSubject, vs...))
|
||||
}
|
||||
|
||||
// ProviderSubjectNotIn applies the NotIn predicate on the "provider_subject" field.
|
||||
func ProviderSubjectNotIn(vs ...string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldNotIn(FieldProviderSubject, vs...))
|
||||
}
|
||||
|
||||
// ProviderSubjectGT applies the GT predicate on the "provider_subject" field.
|
||||
func ProviderSubjectGT(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldGT(FieldProviderSubject, v))
|
||||
}
|
||||
|
||||
// ProviderSubjectGTE applies the GTE predicate on the "provider_subject" field.
|
||||
func ProviderSubjectGTE(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldGTE(FieldProviderSubject, v))
|
||||
}
|
||||
|
||||
// ProviderSubjectLT applies the LT predicate on the "provider_subject" field.
|
||||
func ProviderSubjectLT(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldLT(FieldProviderSubject, v))
|
||||
}
|
||||
|
||||
// ProviderSubjectLTE applies the LTE predicate on the "provider_subject" field.
|
||||
func ProviderSubjectLTE(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldLTE(FieldProviderSubject, v))
|
||||
}
|
||||
|
||||
// ProviderSubjectContains applies the Contains predicate on the "provider_subject" field.
|
||||
func ProviderSubjectContains(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldContains(FieldProviderSubject, v))
|
||||
}
|
||||
|
||||
// ProviderSubjectHasPrefix applies the HasPrefix predicate on the "provider_subject" field.
|
||||
func ProviderSubjectHasPrefix(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldHasPrefix(FieldProviderSubject, v))
|
||||
}
|
||||
|
||||
// ProviderSubjectHasSuffix applies the HasSuffix predicate on the "provider_subject" field.
|
||||
func ProviderSubjectHasSuffix(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldHasSuffix(FieldProviderSubject, v))
|
||||
}
|
||||
|
||||
// ProviderSubjectEqualFold applies the EqualFold predicate on the "provider_subject" field.
|
||||
func ProviderSubjectEqualFold(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldEqualFold(FieldProviderSubject, v))
|
||||
}
|
||||
|
||||
// ProviderSubjectContainsFold applies the ContainsFold predicate on the "provider_subject" field.
|
||||
func ProviderSubjectContainsFold(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldContainsFold(FieldProviderSubject, v))
|
||||
}
|
||||
|
||||
// VerifiedAtEQ applies the EQ predicate on the "verified_at" field.
|
||||
func VerifiedAtEQ(v time.Time) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldEQ(FieldVerifiedAt, v))
|
||||
}
|
||||
|
||||
// VerifiedAtNEQ applies the NEQ predicate on the "verified_at" field.
|
||||
func VerifiedAtNEQ(v time.Time) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldNEQ(FieldVerifiedAt, v))
|
||||
}
|
||||
|
||||
// VerifiedAtIn applies the In predicate on the "verified_at" field.
|
||||
func VerifiedAtIn(vs ...time.Time) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldIn(FieldVerifiedAt, vs...))
|
||||
}
|
||||
|
||||
// VerifiedAtNotIn applies the NotIn predicate on the "verified_at" field.
|
||||
func VerifiedAtNotIn(vs ...time.Time) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldNotIn(FieldVerifiedAt, vs...))
|
||||
}
|
||||
|
||||
// VerifiedAtGT applies the GT predicate on the "verified_at" field.
|
||||
func VerifiedAtGT(v time.Time) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldGT(FieldVerifiedAt, v))
|
||||
}
|
||||
|
||||
// VerifiedAtGTE applies the GTE predicate on the "verified_at" field.
|
||||
func VerifiedAtGTE(v time.Time) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldGTE(FieldVerifiedAt, v))
|
||||
}
|
||||
|
||||
// VerifiedAtLT applies the LT predicate on the "verified_at" field.
|
||||
func VerifiedAtLT(v time.Time) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldLT(FieldVerifiedAt, v))
|
||||
}
|
||||
|
||||
// VerifiedAtLTE applies the LTE predicate on the "verified_at" field.
|
||||
func VerifiedAtLTE(v time.Time) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldLTE(FieldVerifiedAt, v))
|
||||
}
|
||||
|
||||
// VerifiedAtIsNil applies the IsNil predicate on the "verified_at" field.
|
||||
func VerifiedAtIsNil() predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldIsNull(FieldVerifiedAt))
|
||||
}
|
||||
|
||||
// VerifiedAtNotNil applies the NotNil predicate on the "verified_at" field.
|
||||
func VerifiedAtNotNil() predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldNotNull(FieldVerifiedAt))
|
||||
}
|
||||
|
||||
// IssuerEQ applies the EQ predicate on the "issuer" field.
|
||||
func IssuerEQ(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldEQ(FieldIssuer, v))
|
||||
}
|
||||
|
||||
// IssuerNEQ applies the NEQ predicate on the "issuer" field.
|
||||
func IssuerNEQ(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldNEQ(FieldIssuer, v))
|
||||
}
|
||||
|
||||
// IssuerIn applies the In predicate on the "issuer" field.
|
||||
func IssuerIn(vs ...string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldIn(FieldIssuer, vs...))
|
||||
}
|
||||
|
||||
// IssuerNotIn applies the NotIn predicate on the "issuer" field.
|
||||
func IssuerNotIn(vs ...string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldNotIn(FieldIssuer, vs...))
|
||||
}
|
||||
|
||||
// IssuerGT applies the GT predicate on the "issuer" field.
|
||||
func IssuerGT(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldGT(FieldIssuer, v))
|
||||
}
|
||||
|
||||
// IssuerGTE applies the GTE predicate on the "issuer" field.
|
||||
func IssuerGTE(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldGTE(FieldIssuer, v))
|
||||
}
|
||||
|
||||
// IssuerLT applies the LT predicate on the "issuer" field.
|
||||
func IssuerLT(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldLT(FieldIssuer, v))
|
||||
}
|
||||
|
||||
// IssuerLTE applies the LTE predicate on the "issuer" field.
|
||||
func IssuerLTE(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldLTE(FieldIssuer, v))
|
||||
}
|
||||
|
||||
// IssuerContains applies the Contains predicate on the "issuer" field.
|
||||
func IssuerContains(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldContains(FieldIssuer, v))
|
||||
}
|
||||
|
||||
// IssuerHasPrefix applies the HasPrefix predicate on the "issuer" field.
|
||||
func IssuerHasPrefix(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldHasPrefix(FieldIssuer, v))
|
||||
}
|
||||
|
||||
// IssuerHasSuffix applies the HasSuffix predicate on the "issuer" field.
|
||||
func IssuerHasSuffix(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldHasSuffix(FieldIssuer, v))
|
||||
}
|
||||
|
||||
// IssuerIsNil applies the IsNil predicate on the "issuer" field.
|
||||
func IssuerIsNil() predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldIsNull(FieldIssuer))
|
||||
}
|
||||
|
||||
// IssuerNotNil applies the NotNil predicate on the "issuer" field.
|
||||
func IssuerNotNil() predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldNotNull(FieldIssuer))
|
||||
}
|
||||
|
||||
// IssuerEqualFold applies the EqualFold predicate on the "issuer" field.
|
||||
func IssuerEqualFold(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldEqualFold(FieldIssuer, v))
|
||||
}
|
||||
|
||||
// IssuerContainsFold applies the ContainsFold predicate on the "issuer" field.
|
||||
func IssuerContainsFold(v string) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.FieldContainsFold(FieldIssuer, v))
|
||||
}
|
||||
|
||||
// HasUser applies the HasEdge predicate on the "user" edge.
|
||||
func HasUser() predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, true, 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.AuthIdentity {
|
||||
return predicate.AuthIdentity(func(s *sql.Selector) {
|
||||
step := newUserStep()
|
||||
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
|
||||
for _, p := range preds {
|
||||
p(s)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// HasChannels applies the HasEdge predicate on the "channels" edge.
|
||||
func HasChannels() predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, ChannelsTable, ChannelsColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
})
|
||||
}
|
||||
|
||||
// HasChannelsWith applies the HasEdge predicate on the "channels" edge with a given conditions (other predicates).
|
||||
func HasChannelsWith(preds ...predicate.AuthIdentityChannel) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(func(s *sql.Selector) {
|
||||
step := newChannelsStep()
|
||||
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
|
||||
for _, p := range preds {
|
||||
p(s)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// HasAdoptionDecisions applies the HasEdge predicate on the "adoption_decisions" edge.
|
||||
func HasAdoptionDecisions() predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, AdoptionDecisionsTable, AdoptionDecisionsColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
})
|
||||
}
|
||||
|
||||
// HasAdoptionDecisionsWith applies the HasEdge predicate on the "adoption_decisions" edge with a given conditions (other predicates).
|
||||
func HasAdoptionDecisionsWith(preds ...predicate.IdentityAdoptionDecision) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(func(s *sql.Selector) {
|
||||
step := newAdoptionDecisionsStep()
|
||||
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.AuthIdentity) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.AndPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Or groups predicates with the OR operator between them.
|
||||
func Or(predicates ...predicate.AuthIdentity) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.OrPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Not applies the not operator on the given predicate.
|
||||
func Not(p predicate.AuthIdentity) predicate.AuthIdentity {
|
||||
return predicate.AuthIdentity(sql.NotPredicates(p))
|
||||
}
|
||||
@@ -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"
|
||||
"github.com/Wei-Shaw/sub2api/ent/authidentity"
|
||||
"github.com/Wei-Shaw/sub2api/ent/predicate"
|
||||
)
|
||||
|
||||
// AuthIdentityDelete is the builder for deleting a AuthIdentity entity.
|
||||
type AuthIdentityDelete struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *AuthIdentityMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the AuthIdentityDelete builder.
|
||||
func (_d *AuthIdentityDelete) Where(ps ...predicate.AuthIdentity) *AuthIdentityDelete {
|
||||
_d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query and returns how many vertices were deleted.
|
||||
func (_d *AuthIdentityDelete) 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 *AuthIdentityDelete) ExecX(ctx context.Context) int {
|
||||
n, err := _d.Exec(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (_d *AuthIdentityDelete) sqlExec(ctx context.Context) (int, error) {
|
||||
_spec := sqlgraph.NewDeleteSpec(authidentity.Table, sqlgraph.NewFieldSpec(authidentity.FieldID, field.TypeInt64))
|
||||
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
|
||||
}
|
||||
|
||||
// AuthIdentityDeleteOne is the builder for deleting a single AuthIdentity entity.
|
||||
type AuthIdentityDeleteOne struct {
|
||||
_d *AuthIdentityDelete
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the AuthIdentityDelete builder.
|
||||
func (_d *AuthIdentityDeleteOne) Where(ps ...predicate.AuthIdentity) *AuthIdentityDeleteOne {
|
||||
_d._d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query.
|
||||
func (_d *AuthIdentityDeleteOne) Exec(ctx context.Context) error {
|
||||
n, err := _d._d.Exec(ctx)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case n == 0:
|
||||
return &NotFoundError{authidentity.Label}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_d *AuthIdentityDeleteOne) ExecX(ctx context.Context) {
|
||||
if err := _d.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
@@ -1,797 +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"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/Wei-Shaw/sub2api/ent/authidentity"
|
||||
"github.com/Wei-Shaw/sub2api/ent/authidentitychannel"
|
||||
"github.com/Wei-Shaw/sub2api/ent/identityadoptiondecision"
|
||||
"github.com/Wei-Shaw/sub2api/ent/predicate"
|
||||
"github.com/Wei-Shaw/sub2api/ent/user"
|
||||
)
|
||||
|
||||
// AuthIdentityQuery is the builder for querying AuthIdentity entities.
|
||||
type AuthIdentityQuery struct {
|
||||
config
|
||||
ctx *QueryContext
|
||||
order []authidentity.OrderOption
|
||||
inters []Interceptor
|
||||
predicates []predicate.AuthIdentity
|
||||
withUser *UserQuery
|
||||
withChannels *AuthIdentityChannelQuery
|
||||
withAdoptionDecisions *IdentityAdoptionDecisionQuery
|
||||
modifiers []func(*sql.Selector)
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
path func(context.Context) (*sql.Selector, error)
|
||||
}
|
||||
|
||||
// Where adds a new predicate for the AuthIdentityQuery builder.
|
||||
func (_q *AuthIdentityQuery) Where(ps ...predicate.AuthIdentity) *AuthIdentityQuery {
|
||||
_q.predicates = append(_q.predicates, ps...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// Limit the number of records to be returned by this query.
|
||||
func (_q *AuthIdentityQuery) Limit(limit int) *AuthIdentityQuery {
|
||||
_q.ctx.Limit = &limit
|
||||
return _q
|
||||
}
|
||||
|
||||
// Offset to start from.
|
||||
func (_q *AuthIdentityQuery) Offset(offset int) *AuthIdentityQuery {
|
||||
_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 *AuthIdentityQuery) Unique(unique bool) *AuthIdentityQuery {
|
||||
_q.ctx.Unique = &unique
|
||||
return _q
|
||||
}
|
||||
|
||||
// Order specifies how the records should be ordered.
|
||||
func (_q *AuthIdentityQuery) Order(o ...authidentity.OrderOption) *AuthIdentityQuery {
|
||||
_q.order = append(_q.order, o...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// QueryUser chains the current query on the "user" edge.
|
||||
func (_q *AuthIdentityQuery) 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(authidentity.Table, authidentity.FieldID, selector),
|
||||
sqlgraph.To(user.Table, user.FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, true, authidentity.UserTable, authidentity.UserColumn),
|
||||
)
|
||||
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
|
||||
return fromU, nil
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
// QueryChannels chains the current query on the "channels" edge.
|
||||
func (_q *AuthIdentityQuery) QueryChannels() *AuthIdentityChannelQuery {
|
||||
query := (&AuthIdentityChannelClient{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(authidentity.Table, authidentity.FieldID, selector),
|
||||
sqlgraph.To(authidentitychannel.Table, authidentitychannel.FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, authidentity.ChannelsTable, authidentity.ChannelsColumn),
|
||||
)
|
||||
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
|
||||
return fromU, nil
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
// QueryAdoptionDecisions chains the current query on the "adoption_decisions" edge.
|
||||
func (_q *AuthIdentityQuery) QueryAdoptionDecisions() *IdentityAdoptionDecisionQuery {
|
||||
query := (&IdentityAdoptionDecisionClient{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(authidentity.Table, authidentity.FieldID, selector),
|
||||
sqlgraph.To(identityadoptiondecision.Table, identityadoptiondecision.FieldID),
|
||||
sqlgraph.Edge(sqlgraph.O2M, false, authidentity.AdoptionDecisionsTable, authidentity.AdoptionDecisionsColumn),
|
||||
)
|
||||
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
|
||||
return fromU, nil
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
// First returns the first AuthIdentity entity from the query.
|
||||
// Returns a *NotFoundError when no AuthIdentity was found.
|
||||
func (_q *AuthIdentityQuery) First(ctx context.Context) (*AuthIdentity, 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{authidentity.Label}
|
||||
}
|
||||
return nodes[0], nil
|
||||
}
|
||||
|
||||
// FirstX is like First, but panics if an error occurs.
|
||||
func (_q *AuthIdentityQuery) FirstX(ctx context.Context) *AuthIdentity {
|
||||
node, err := _q.First(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// FirstID returns the first AuthIdentity ID from the query.
|
||||
// Returns a *NotFoundError when no AuthIdentity ID was found.
|
||||
func (_q *AuthIdentityQuery) FirstID(ctx context.Context) (id int64, err error) {
|
||||
var ids []int64
|
||||
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
|
||||
return
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
err = &NotFoundError{authidentity.Label}
|
||||
return
|
||||
}
|
||||
return ids[0], nil
|
||||
}
|
||||
|
||||
// FirstIDX is like FirstID, but panics if an error occurs.
|
||||
func (_q *AuthIdentityQuery) FirstIDX(ctx context.Context) int64 {
|
||||
id, err := _q.FirstID(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// Only returns a single AuthIdentity entity found by the query, ensuring it only returns one.
|
||||
// Returns a *NotSingularError when more than one AuthIdentity entity is found.
|
||||
// Returns a *NotFoundError when no AuthIdentity entities are found.
|
||||
func (_q *AuthIdentityQuery) Only(ctx context.Context) (*AuthIdentity, 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{authidentity.Label}
|
||||
default:
|
||||
return nil, &NotSingularError{authidentity.Label}
|
||||
}
|
||||
}
|
||||
|
||||
// OnlyX is like Only, but panics if an error occurs.
|
||||
func (_q *AuthIdentityQuery) OnlyX(ctx context.Context) *AuthIdentity {
|
||||
node, err := _q.Only(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// OnlyID is like Only, but returns the only AuthIdentity ID in the query.
|
||||
// Returns a *NotSingularError when more than one AuthIdentity ID is found.
|
||||
// Returns a *NotFoundError when no entities are found.
|
||||
func (_q *AuthIdentityQuery) OnlyID(ctx context.Context) (id int64, err error) {
|
||||
var ids []int64
|
||||
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{authidentity.Label}
|
||||
default:
|
||||
err = &NotSingularError{authidentity.Label}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// OnlyIDX is like OnlyID, but panics if an error occurs.
|
||||
func (_q *AuthIdentityQuery) OnlyIDX(ctx context.Context) int64 {
|
||||
id, err := _q.OnlyID(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// All executes the query and returns a list of AuthIdentities.
|
||||
func (_q *AuthIdentityQuery) All(ctx context.Context) ([]*AuthIdentity, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
|
||||
if err := _q.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qr := querierAll[[]*AuthIdentity, *AuthIdentityQuery]()
|
||||
return withInterceptors[[]*AuthIdentity](ctx, _q, qr, _q.inters)
|
||||
}
|
||||
|
||||
// AllX is like All, but panics if an error occurs.
|
||||
func (_q *AuthIdentityQuery) AllX(ctx context.Context) []*AuthIdentity {
|
||||
nodes, err := _q.All(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
||||
// IDs executes the query and returns a list of AuthIdentity IDs.
|
||||
func (_q *AuthIdentityQuery) IDs(ctx context.Context) (ids []int64, err error) {
|
||||
if _q.ctx.Unique == nil && _q.path != nil {
|
||||
_q.Unique(true)
|
||||
}
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
|
||||
if err = _q.Select(authidentity.FieldID).Scan(ctx, &ids); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// IDsX is like IDs, but panics if an error occurs.
|
||||
func (_q *AuthIdentityQuery) IDsX(ctx context.Context) []int64 {
|
||||
ids, err := _q.IDs(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// Count returns the count of the given query.
|
||||
func (_q *AuthIdentityQuery) 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[*AuthIdentityQuery](), _q.inters)
|
||||
}
|
||||
|
||||
// CountX is like Count, but panics if an error occurs.
|
||||
func (_q *AuthIdentityQuery) 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 *AuthIdentityQuery) 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 *AuthIdentityQuery) ExistX(ctx context.Context) bool {
|
||||
exist, err := _q.Exist(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return exist
|
||||
}
|
||||
|
||||
// Clone returns a duplicate of the AuthIdentityQuery 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 *AuthIdentityQuery) Clone() *AuthIdentityQuery {
|
||||
if _q == nil {
|
||||
return nil
|
||||
}
|
||||
return &AuthIdentityQuery{
|
||||
config: _q.config,
|
||||
ctx: _q.ctx.Clone(),
|
||||
order: append([]authidentity.OrderOption{}, _q.order...),
|
||||
inters: append([]Interceptor{}, _q.inters...),
|
||||
predicates: append([]predicate.AuthIdentity{}, _q.predicates...),
|
||||
withUser: _q.withUser.Clone(),
|
||||
withChannels: _q.withChannels.Clone(),
|
||||
withAdoptionDecisions: _q.withAdoptionDecisions.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 *AuthIdentityQuery) WithUser(opts ...func(*UserQuery)) *AuthIdentityQuery {
|
||||
query := (&UserClient{config: _q.config}).Query()
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
_q.withUser = query
|
||||
return _q
|
||||
}
|
||||
|
||||
// WithChannels tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "channels" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (_q *AuthIdentityQuery) WithChannels(opts ...func(*AuthIdentityChannelQuery)) *AuthIdentityQuery {
|
||||
query := (&AuthIdentityChannelClient{config: _q.config}).Query()
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
_q.withChannels = query
|
||||
return _q
|
||||
}
|
||||
|
||||
// WithAdoptionDecisions tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "adoption_decisions" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (_q *AuthIdentityQuery) WithAdoptionDecisions(opts ...func(*IdentityAdoptionDecisionQuery)) *AuthIdentityQuery {
|
||||
query := (&IdentityAdoptionDecisionClient{config: _q.config}).Query()
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
_q.withAdoptionDecisions = 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 {
|
||||
// CreatedAt time.Time `json:"created_at,omitempty"`
|
||||
// Count int `json:"count,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.AuthIdentity.Query().
|
||||
// GroupBy(authidentity.FieldCreatedAt).
|
||||
// Aggregate(ent.Count()).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *AuthIdentityQuery) GroupBy(field string, fields ...string) *AuthIdentityGroupBy {
|
||||
_q.ctx.Fields = append([]string{field}, fields...)
|
||||
grbuild := &AuthIdentityGroupBy{build: _q}
|
||||
grbuild.flds = &_q.ctx.Fields
|
||||
grbuild.label = authidentity.Label
|
||||
grbuild.scan = grbuild.Scan
|
||||
return grbuild
|
||||
}
|
||||
|
||||
// Select allows the selection one or more fields/columns for the given query,
|
||||
// instead of selecting all fields in the entity.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// var v []struct {
|
||||
// CreatedAt time.Time `json:"created_at,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.AuthIdentity.Query().
|
||||
// Select(authidentity.FieldCreatedAt).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *AuthIdentityQuery) Select(fields ...string) *AuthIdentitySelect {
|
||||
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
|
||||
sbuild := &AuthIdentitySelect{AuthIdentityQuery: _q}
|
||||
sbuild.label = authidentity.Label
|
||||
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
|
||||
return sbuild
|
||||
}
|
||||
|
||||
// Aggregate returns a AuthIdentitySelect configured with the given aggregations.
|
||||
func (_q *AuthIdentityQuery) Aggregate(fns ...AggregateFunc) *AuthIdentitySelect {
|
||||
return _q.Select().Aggregate(fns...)
|
||||
}
|
||||
|
||||
func (_q *AuthIdentityQuery) 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 !authidentity.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 *AuthIdentityQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AuthIdentity, error) {
|
||||
var (
|
||||
nodes = []*AuthIdentity{}
|
||||
_spec = _q.querySpec()
|
||||
loadedTypes = [3]bool{
|
||||
_q.withUser != nil,
|
||||
_q.withChannels != nil,
|
||||
_q.withAdoptionDecisions != nil,
|
||||
}
|
||||
)
|
||||
_spec.ScanValues = func(columns []string) ([]any, error) {
|
||||
return (*AuthIdentity).scanValues(nil, columns)
|
||||
}
|
||||
_spec.Assign = func(columns []string, values []any) error {
|
||||
node := &AuthIdentity{config: _q.config}
|
||||
nodes = append(nodes, node)
|
||||
node.Edges.loadedTypes = loadedTypes
|
||||
return node.assignValues(columns, values)
|
||||
}
|
||||
if len(_q.modifiers) > 0 {
|
||||
_spec.Modifiers = _q.modifiers
|
||||
}
|
||||
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 *AuthIdentity, e *User) { n.Edges.User = e }); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if query := _q.withChannels; query != nil {
|
||||
if err := _q.loadChannels(ctx, query, nodes,
|
||||
func(n *AuthIdentity) { n.Edges.Channels = []*AuthIdentityChannel{} },
|
||||
func(n *AuthIdentity, e *AuthIdentityChannel) { n.Edges.Channels = append(n.Edges.Channels, e) }); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if query := _q.withAdoptionDecisions; query != nil {
|
||||
if err := _q.loadAdoptionDecisions(ctx, query, nodes,
|
||||
func(n *AuthIdentity) { n.Edges.AdoptionDecisions = []*IdentityAdoptionDecision{} },
|
||||
func(n *AuthIdentity, e *IdentityAdoptionDecision) {
|
||||
n.Edges.AdoptionDecisions = append(n.Edges.AdoptionDecisions, e)
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
func (_q *AuthIdentityQuery) loadUser(ctx context.Context, query *UserQuery, nodes []*AuthIdentity, init func(*AuthIdentity), assign func(*AuthIdentity, *User)) error {
|
||||
ids := make([]int64, 0, len(nodes))
|
||||
nodeids := make(map[int64][]*AuthIdentity)
|
||||
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 *AuthIdentityQuery) loadChannels(ctx context.Context, query *AuthIdentityChannelQuery, nodes []*AuthIdentity, init func(*AuthIdentity), assign func(*AuthIdentity, *AuthIdentityChannel)) error {
|
||||
fks := make([]driver.Value, 0, len(nodes))
|
||||
nodeids := make(map[int64]*AuthIdentity)
|
||||
for i := range nodes {
|
||||
fks = append(fks, nodes[i].ID)
|
||||
nodeids[nodes[i].ID] = nodes[i]
|
||||
if init != nil {
|
||||
init(nodes[i])
|
||||
}
|
||||
}
|
||||
if len(query.ctx.Fields) > 0 {
|
||||
query.ctx.AppendFieldOnce(authidentitychannel.FieldIdentityID)
|
||||
}
|
||||
query.Where(predicate.AuthIdentityChannel(func(s *sql.Selector) {
|
||||
s.Where(sql.InValues(s.C(authidentity.ChannelsColumn), fks...))
|
||||
}))
|
||||
neighbors, err := query.All(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, n := range neighbors {
|
||||
fk := n.IdentityID
|
||||
node, ok := nodeids[fk]
|
||||
if !ok {
|
||||
return fmt.Errorf(`unexpected referenced foreign-key "identity_id" returned %v for node %v`, fk, n.ID)
|
||||
}
|
||||
assign(node, n)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (_q *AuthIdentityQuery) loadAdoptionDecisions(ctx context.Context, query *IdentityAdoptionDecisionQuery, nodes []*AuthIdentity, init func(*AuthIdentity), assign func(*AuthIdentity, *IdentityAdoptionDecision)) error {
|
||||
fks := make([]driver.Value, 0, len(nodes))
|
||||
nodeids := make(map[int64]*AuthIdentity)
|
||||
for i := range nodes {
|
||||
fks = append(fks, nodes[i].ID)
|
||||
nodeids[nodes[i].ID] = nodes[i]
|
||||
if init != nil {
|
||||
init(nodes[i])
|
||||
}
|
||||
}
|
||||
if len(query.ctx.Fields) > 0 {
|
||||
query.ctx.AppendFieldOnce(identityadoptiondecision.FieldIdentityID)
|
||||
}
|
||||
query.Where(predicate.IdentityAdoptionDecision(func(s *sql.Selector) {
|
||||
s.Where(sql.InValues(s.C(authidentity.AdoptionDecisionsColumn), fks...))
|
||||
}))
|
||||
neighbors, err := query.All(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, n := range neighbors {
|
||||
fk := n.IdentityID
|
||||
if fk == nil {
|
||||
return fmt.Errorf(`foreign-key "identity_id" is nil for node %v`, n.ID)
|
||||
}
|
||||
node, ok := nodeids[*fk]
|
||||
if !ok {
|
||||
return fmt.Errorf(`unexpected referenced foreign-key "identity_id" returned %v for node %v`, *fk, n.ID)
|
||||
}
|
||||
assign(node, n)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_q *AuthIdentityQuery) sqlCount(ctx context.Context) (int, error) {
|
||||
_spec := _q.querySpec()
|
||||
if len(_q.modifiers) > 0 {
|
||||
_spec.Modifiers = _q.modifiers
|
||||
}
|
||||
_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 *AuthIdentityQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
_spec := sqlgraph.NewQuerySpec(authidentity.Table, authidentity.Columns, sqlgraph.NewFieldSpec(authidentity.FieldID, field.TypeInt64))
|
||||
_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, authidentity.FieldID)
|
||||
for i := range fields {
|
||||
if fields[i] != authidentity.FieldID {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
|
||||
}
|
||||
}
|
||||
if _q.withUser != nil {
|
||||
_spec.Node.AddColumnOnce(authidentity.FieldUserID)
|
||||
}
|
||||
}
|
||||
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 *AuthIdentityQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
builder := sql.Dialect(_q.driver.Dialect())
|
||||
t1 := builder.Table(authidentity.Table)
|
||||
columns := _q.ctx.Fields
|
||||
if len(columns) == 0 {
|
||||
columns = authidentity.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 _, m := range _q.modifiers {
|
||||
m(selector)
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
|
||||
// updated, deleted or "selected ... for update" by other sessions, until the transaction is
|
||||
// either committed or rolled-back.
|
||||
func (_q *AuthIdentityQuery) ForUpdate(opts ...sql.LockOption) *AuthIdentityQuery {
|
||||
if _q.driver.Dialect() == dialect.Postgres {
|
||||
_q.Unique(false)
|
||||
}
|
||||
_q.modifiers = append(_q.modifiers, func(s *sql.Selector) {
|
||||
s.ForUpdate(opts...)
|
||||
})
|
||||
return _q
|
||||
}
|
||||
|
||||
// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
|
||||
// on any rows that are read. Other sessions can read the rows, but cannot modify them
|
||||
// until your transaction commits.
|
||||
func (_q *AuthIdentityQuery) ForShare(opts ...sql.LockOption) *AuthIdentityQuery {
|
||||
if _q.driver.Dialect() == dialect.Postgres {
|
||||
_q.Unique(false)
|
||||
}
|
||||
_q.modifiers = append(_q.modifiers, func(s *sql.Selector) {
|
||||
s.ForShare(opts...)
|
||||
})
|
||||
return _q
|
||||
}
|
||||
|
||||
// AuthIdentityGroupBy is the group-by builder for AuthIdentity entities.
|
||||
type AuthIdentityGroupBy struct {
|
||||
selector
|
||||
build *AuthIdentityQuery
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the group-by query.
|
||||
func (_g *AuthIdentityGroupBy) Aggregate(fns ...AggregateFunc) *AuthIdentityGroupBy {
|
||||
_g.fns = append(_g.fns, fns...)
|
||||
return _g
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_g *AuthIdentityGroupBy) 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[*AuthIdentityQuery, *AuthIdentityGroupBy](ctx, _g.build, _g, _g.build.inters, v)
|
||||
}
|
||||
|
||||
func (_g *AuthIdentityGroupBy) sqlScan(ctx context.Context, root *AuthIdentityQuery, 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)
|
||||
}
|
||||
|
||||
// AuthIdentitySelect is the builder for selecting fields of AuthIdentity entities.
|
||||
type AuthIdentitySelect struct {
|
||||
*AuthIdentityQuery
|
||||
selector
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the selector query.
|
||||
func (_s *AuthIdentitySelect) Aggregate(fns ...AggregateFunc) *AuthIdentitySelect {
|
||||
_s.fns = append(_s.fns, fns...)
|
||||
return _s
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_s *AuthIdentitySelect) 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[*AuthIdentityQuery, *AuthIdentitySelect](ctx, _s.AuthIdentityQuery, _s, _s.inters, v)
|
||||
}
|
||||
|
||||
func (_s *AuthIdentitySelect) sqlScan(ctx context.Context, root *AuthIdentityQuery, 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)
|
||||
}
|
||||
@@ -1,923 +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"
|
||||
"github.com/Wei-Shaw/sub2api/ent/authidentity"
|
||||
"github.com/Wei-Shaw/sub2api/ent/authidentitychannel"
|
||||
"github.com/Wei-Shaw/sub2api/ent/identityadoptiondecision"
|
||||
"github.com/Wei-Shaw/sub2api/ent/predicate"
|
||||
"github.com/Wei-Shaw/sub2api/ent/user"
|
||||
)
|
||||
|
||||
// AuthIdentityUpdate is the builder for updating AuthIdentity entities.
|
||||
type AuthIdentityUpdate struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *AuthIdentityMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the AuthIdentityUpdate builder.
|
||||
func (_u *AuthIdentityUpdate) Where(ps ...predicate.AuthIdentity) *AuthIdentityUpdate {
|
||||
_u.mutation.Where(ps...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetUpdatedAt sets the "updated_at" field.
|
||||
func (_u *AuthIdentityUpdate) SetUpdatedAt(v time.Time) *AuthIdentityUpdate {
|
||||
_u.mutation.SetUpdatedAt(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetUserID sets the "user_id" field.
|
||||
func (_u *AuthIdentityUpdate) SetUserID(v int64) *AuthIdentityUpdate {
|
||||
_u.mutation.SetUserID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableUserID sets the "user_id" field if the given value is not nil.
|
||||
func (_u *AuthIdentityUpdate) SetNillableUserID(v *int64) *AuthIdentityUpdate {
|
||||
if v != nil {
|
||||
_u.SetUserID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetProviderType sets the "provider_type" field.
|
||||
func (_u *AuthIdentityUpdate) SetProviderType(v string) *AuthIdentityUpdate {
|
||||
_u.mutation.SetProviderType(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableProviderType sets the "provider_type" field if the given value is not nil.
|
||||
func (_u *AuthIdentityUpdate) SetNillableProviderType(v *string) *AuthIdentityUpdate {
|
||||
if v != nil {
|
||||
_u.SetProviderType(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetProviderKey sets the "provider_key" field.
|
||||
func (_u *AuthIdentityUpdate) SetProviderKey(v string) *AuthIdentityUpdate {
|
||||
_u.mutation.SetProviderKey(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableProviderKey sets the "provider_key" field if the given value is not nil.
|
||||
func (_u *AuthIdentityUpdate) SetNillableProviderKey(v *string) *AuthIdentityUpdate {
|
||||
if v != nil {
|
||||
_u.SetProviderKey(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetProviderSubject sets the "provider_subject" field.
|
||||
func (_u *AuthIdentityUpdate) SetProviderSubject(v string) *AuthIdentityUpdate {
|
||||
_u.mutation.SetProviderSubject(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableProviderSubject sets the "provider_subject" field if the given value is not nil.
|
||||
func (_u *AuthIdentityUpdate) SetNillableProviderSubject(v *string) *AuthIdentityUpdate {
|
||||
if v != nil {
|
||||
_u.SetProviderSubject(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetVerifiedAt sets the "verified_at" field.
|
||||
func (_u *AuthIdentityUpdate) SetVerifiedAt(v time.Time) *AuthIdentityUpdate {
|
||||
_u.mutation.SetVerifiedAt(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableVerifiedAt sets the "verified_at" field if the given value is not nil.
|
||||
func (_u *AuthIdentityUpdate) SetNillableVerifiedAt(v *time.Time) *AuthIdentityUpdate {
|
||||
if v != nil {
|
||||
_u.SetVerifiedAt(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearVerifiedAt clears the value of the "verified_at" field.
|
||||
func (_u *AuthIdentityUpdate) ClearVerifiedAt() *AuthIdentityUpdate {
|
||||
_u.mutation.ClearVerifiedAt()
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetIssuer sets the "issuer" field.
|
||||
func (_u *AuthIdentityUpdate) SetIssuer(v string) *AuthIdentityUpdate {
|
||||
_u.mutation.SetIssuer(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableIssuer sets the "issuer" field if the given value is not nil.
|
||||
func (_u *AuthIdentityUpdate) SetNillableIssuer(v *string) *AuthIdentityUpdate {
|
||||
if v != nil {
|
||||
_u.SetIssuer(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearIssuer clears the value of the "issuer" field.
|
||||
func (_u *AuthIdentityUpdate) ClearIssuer() *AuthIdentityUpdate {
|
||||
_u.mutation.ClearIssuer()
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetMetadata sets the "metadata" field.
|
||||
func (_u *AuthIdentityUpdate) SetMetadata(v map[string]interface{}) *AuthIdentityUpdate {
|
||||
_u.mutation.SetMetadata(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetUser sets the "user" edge to the User entity.
|
||||
func (_u *AuthIdentityUpdate) SetUser(v *User) *AuthIdentityUpdate {
|
||||
return _u.SetUserID(v.ID)
|
||||
}
|
||||
|
||||
// AddChannelIDs adds the "channels" edge to the AuthIdentityChannel entity by IDs.
|
||||
func (_u *AuthIdentityUpdate) AddChannelIDs(ids ...int64) *AuthIdentityUpdate {
|
||||
_u.mutation.AddChannelIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddChannels adds the "channels" edges to the AuthIdentityChannel entity.
|
||||
func (_u *AuthIdentityUpdate) AddChannels(v ...*AuthIdentityChannel) *AuthIdentityUpdate {
|
||||
ids := make([]int64, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.AddChannelIDs(ids...)
|
||||
}
|
||||
|
||||
// AddAdoptionDecisionIDs adds the "adoption_decisions" edge to the IdentityAdoptionDecision entity by IDs.
|
||||
func (_u *AuthIdentityUpdate) AddAdoptionDecisionIDs(ids ...int64) *AuthIdentityUpdate {
|
||||
_u.mutation.AddAdoptionDecisionIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddAdoptionDecisions adds the "adoption_decisions" edges to the IdentityAdoptionDecision entity.
|
||||
func (_u *AuthIdentityUpdate) AddAdoptionDecisions(v ...*IdentityAdoptionDecision) *AuthIdentityUpdate {
|
||||
ids := make([]int64, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.AddAdoptionDecisionIDs(ids...)
|
||||
}
|
||||
|
||||
// Mutation returns the AuthIdentityMutation object of the builder.
|
||||
func (_u *AuthIdentityUpdate) Mutation() *AuthIdentityMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// ClearUser clears the "user" edge to the User entity.
|
||||
func (_u *AuthIdentityUpdate) ClearUser() *AuthIdentityUpdate {
|
||||
_u.mutation.ClearUser()
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearChannels clears all "channels" edges to the AuthIdentityChannel entity.
|
||||
func (_u *AuthIdentityUpdate) ClearChannels() *AuthIdentityUpdate {
|
||||
_u.mutation.ClearChannels()
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveChannelIDs removes the "channels" edge to AuthIdentityChannel entities by IDs.
|
||||
func (_u *AuthIdentityUpdate) RemoveChannelIDs(ids ...int64) *AuthIdentityUpdate {
|
||||
_u.mutation.RemoveChannelIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveChannels removes "channels" edges to AuthIdentityChannel entities.
|
||||
func (_u *AuthIdentityUpdate) RemoveChannels(v ...*AuthIdentityChannel) *AuthIdentityUpdate {
|
||||
ids := make([]int64, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.RemoveChannelIDs(ids...)
|
||||
}
|
||||
|
||||
// ClearAdoptionDecisions clears all "adoption_decisions" edges to the IdentityAdoptionDecision entity.
|
||||
func (_u *AuthIdentityUpdate) ClearAdoptionDecisions() *AuthIdentityUpdate {
|
||||
_u.mutation.ClearAdoptionDecisions()
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveAdoptionDecisionIDs removes the "adoption_decisions" edge to IdentityAdoptionDecision entities by IDs.
|
||||
func (_u *AuthIdentityUpdate) RemoveAdoptionDecisionIDs(ids ...int64) *AuthIdentityUpdate {
|
||||
_u.mutation.RemoveAdoptionDecisionIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveAdoptionDecisions removes "adoption_decisions" edges to IdentityAdoptionDecision entities.
|
||||
func (_u *AuthIdentityUpdate) RemoveAdoptionDecisions(v ...*IdentityAdoptionDecision) *AuthIdentityUpdate {
|
||||
ids := make([]int64, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.RemoveAdoptionDecisionIDs(ids...)
|
||||
}
|
||||
|
||||
// Save executes the query and returns the number of nodes affected by the update operation.
|
||||
func (_u *AuthIdentityUpdate) 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 *AuthIdentityUpdate) SaveX(ctx context.Context) int {
|
||||
affected, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return affected
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_u *AuthIdentityUpdate) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *AuthIdentityUpdate) 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 *AuthIdentityUpdate) defaults() {
|
||||
if _, ok := _u.mutation.UpdatedAt(); !ok {
|
||||
v := authidentity.UpdateDefaultUpdatedAt()
|
||||
_u.mutation.SetUpdatedAt(v)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_u *AuthIdentityUpdate) check() error {
|
||||
if v, ok := _u.mutation.ProviderType(); ok {
|
||||
if err := authidentity.ProviderTypeValidator(v); err != nil {
|
||||
return &ValidationError{Name: "provider_type", err: fmt.Errorf(`ent: validator failed for field "AuthIdentity.provider_type": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.ProviderKey(); ok {
|
||||
if err := authidentity.ProviderKeyValidator(v); err != nil {
|
||||
return &ValidationError{Name: "provider_key", err: fmt.Errorf(`ent: validator failed for field "AuthIdentity.provider_key": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.ProviderSubject(); ok {
|
||||
if err := authidentity.ProviderSubjectValidator(v); err != nil {
|
||||
return &ValidationError{Name: "provider_subject", err: fmt.Errorf(`ent: validator failed for field "AuthIdentity.provider_subject": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _u.mutation.UserCleared() && len(_u.mutation.UserIDs()) > 0 {
|
||||
return errors.New(`ent: clearing a required unique edge "AuthIdentity.user"`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_u *AuthIdentityUpdate) sqlSave(ctx context.Context) (_node int, err error) {
|
||||
if err := _u.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := sqlgraph.NewUpdateSpec(authidentity.Table, authidentity.Columns, sqlgraph.NewFieldSpec(authidentity.FieldID, field.TypeInt64))
|
||||
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.UpdatedAt(); ok {
|
||||
_spec.SetField(authidentity.FieldUpdatedAt, field.TypeTime, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ProviderType(); ok {
|
||||
_spec.SetField(authidentity.FieldProviderType, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ProviderKey(); ok {
|
||||
_spec.SetField(authidentity.FieldProviderKey, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ProviderSubject(); ok {
|
||||
_spec.SetField(authidentity.FieldProviderSubject, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.VerifiedAt(); ok {
|
||||
_spec.SetField(authidentity.FieldVerifiedAt, field.TypeTime, value)
|
||||
}
|
||||
if _u.mutation.VerifiedAtCleared() {
|
||||
_spec.ClearField(authidentity.FieldVerifiedAt, field.TypeTime)
|
||||
}
|
||||
if value, ok := _u.mutation.Issuer(); ok {
|
||||
_spec.SetField(authidentity.FieldIssuer, field.TypeString, value)
|
||||
}
|
||||
if _u.mutation.IssuerCleared() {
|
||||
_spec.ClearField(authidentity.FieldIssuer, field.TypeString)
|
||||
}
|
||||
if value, ok := _u.mutation.Metadata(); ok {
|
||||
_spec.SetField(authidentity.FieldMetadata, field.TypeJSON, value)
|
||||
}
|
||||
if _u.mutation.UserCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: authidentity.UserTable,
|
||||
Columns: []string{authidentity.UserColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.UserIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: authidentity.UserTable,
|
||||
Columns: []string{authidentity.UserColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if _u.mutation.ChannelsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: authidentity.ChannelsTable,
|
||||
Columns: []string{authidentity.ChannelsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(authidentitychannel.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.RemovedChannelsIDs(); len(nodes) > 0 && !_u.mutation.ChannelsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: authidentity.ChannelsTable,
|
||||
Columns: []string{authidentity.ChannelsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(authidentitychannel.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.ChannelsIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: authidentity.ChannelsTable,
|
||||
Columns: []string{authidentity.ChannelsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(authidentitychannel.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if _u.mutation.AdoptionDecisionsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: authidentity.AdoptionDecisionsTable,
|
||||
Columns: []string{authidentity.AdoptionDecisionsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(identityadoptiondecision.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.RemovedAdoptionDecisionsIDs(); len(nodes) > 0 && !_u.mutation.AdoptionDecisionsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: authidentity.AdoptionDecisionsTable,
|
||||
Columns: []string{authidentity.AdoptionDecisionsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(identityadoptiondecision.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.AdoptionDecisionsIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: authidentity.AdoptionDecisionsTable,
|
||||
Columns: []string{authidentity.AdoptionDecisionsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(identityadoptiondecision.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
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{authidentity.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
// AuthIdentityUpdateOne is the builder for updating a single AuthIdentity entity.
|
||||
type AuthIdentityUpdateOne struct {
|
||||
config
|
||||
fields []string
|
||||
hooks []Hook
|
||||
mutation *AuthIdentityMutation
|
||||
}
|
||||
|
||||
// SetUpdatedAt sets the "updated_at" field.
|
||||
func (_u *AuthIdentityUpdateOne) SetUpdatedAt(v time.Time) *AuthIdentityUpdateOne {
|
||||
_u.mutation.SetUpdatedAt(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetUserID sets the "user_id" field.
|
||||
func (_u *AuthIdentityUpdateOne) SetUserID(v int64) *AuthIdentityUpdateOne {
|
||||
_u.mutation.SetUserID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableUserID sets the "user_id" field if the given value is not nil.
|
||||
func (_u *AuthIdentityUpdateOne) SetNillableUserID(v *int64) *AuthIdentityUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetUserID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetProviderType sets the "provider_type" field.
|
||||
func (_u *AuthIdentityUpdateOne) SetProviderType(v string) *AuthIdentityUpdateOne {
|
||||
_u.mutation.SetProviderType(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableProviderType sets the "provider_type" field if the given value is not nil.
|
||||
func (_u *AuthIdentityUpdateOne) SetNillableProviderType(v *string) *AuthIdentityUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetProviderType(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetProviderKey sets the "provider_key" field.
|
||||
func (_u *AuthIdentityUpdateOne) SetProviderKey(v string) *AuthIdentityUpdateOne {
|
||||
_u.mutation.SetProviderKey(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableProviderKey sets the "provider_key" field if the given value is not nil.
|
||||
func (_u *AuthIdentityUpdateOne) SetNillableProviderKey(v *string) *AuthIdentityUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetProviderKey(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetProviderSubject sets the "provider_subject" field.
|
||||
func (_u *AuthIdentityUpdateOne) SetProviderSubject(v string) *AuthIdentityUpdateOne {
|
||||
_u.mutation.SetProviderSubject(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableProviderSubject sets the "provider_subject" field if the given value is not nil.
|
||||
func (_u *AuthIdentityUpdateOne) SetNillableProviderSubject(v *string) *AuthIdentityUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetProviderSubject(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetVerifiedAt sets the "verified_at" field.
|
||||
func (_u *AuthIdentityUpdateOne) SetVerifiedAt(v time.Time) *AuthIdentityUpdateOne {
|
||||
_u.mutation.SetVerifiedAt(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableVerifiedAt sets the "verified_at" field if the given value is not nil.
|
||||
func (_u *AuthIdentityUpdateOne) SetNillableVerifiedAt(v *time.Time) *AuthIdentityUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetVerifiedAt(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearVerifiedAt clears the value of the "verified_at" field.
|
||||
func (_u *AuthIdentityUpdateOne) ClearVerifiedAt() *AuthIdentityUpdateOne {
|
||||
_u.mutation.ClearVerifiedAt()
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetIssuer sets the "issuer" field.
|
||||
func (_u *AuthIdentityUpdateOne) SetIssuer(v string) *AuthIdentityUpdateOne {
|
||||
_u.mutation.SetIssuer(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableIssuer sets the "issuer" field if the given value is not nil.
|
||||
func (_u *AuthIdentityUpdateOne) SetNillableIssuer(v *string) *AuthIdentityUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetIssuer(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearIssuer clears the value of the "issuer" field.
|
||||
func (_u *AuthIdentityUpdateOne) ClearIssuer() *AuthIdentityUpdateOne {
|
||||
_u.mutation.ClearIssuer()
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetMetadata sets the "metadata" field.
|
||||
func (_u *AuthIdentityUpdateOne) SetMetadata(v map[string]interface{}) *AuthIdentityUpdateOne {
|
||||
_u.mutation.SetMetadata(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetUser sets the "user" edge to the User entity.
|
||||
func (_u *AuthIdentityUpdateOne) SetUser(v *User) *AuthIdentityUpdateOne {
|
||||
return _u.SetUserID(v.ID)
|
||||
}
|
||||
|
||||
// AddChannelIDs adds the "channels" edge to the AuthIdentityChannel entity by IDs.
|
||||
func (_u *AuthIdentityUpdateOne) AddChannelIDs(ids ...int64) *AuthIdentityUpdateOne {
|
||||
_u.mutation.AddChannelIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddChannels adds the "channels" edges to the AuthIdentityChannel entity.
|
||||
func (_u *AuthIdentityUpdateOne) AddChannels(v ...*AuthIdentityChannel) *AuthIdentityUpdateOne {
|
||||
ids := make([]int64, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.AddChannelIDs(ids...)
|
||||
}
|
||||
|
||||
// AddAdoptionDecisionIDs adds the "adoption_decisions" edge to the IdentityAdoptionDecision entity by IDs.
|
||||
func (_u *AuthIdentityUpdateOne) AddAdoptionDecisionIDs(ids ...int64) *AuthIdentityUpdateOne {
|
||||
_u.mutation.AddAdoptionDecisionIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// AddAdoptionDecisions adds the "adoption_decisions" edges to the IdentityAdoptionDecision entity.
|
||||
func (_u *AuthIdentityUpdateOne) AddAdoptionDecisions(v ...*IdentityAdoptionDecision) *AuthIdentityUpdateOne {
|
||||
ids := make([]int64, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.AddAdoptionDecisionIDs(ids...)
|
||||
}
|
||||
|
||||
// Mutation returns the AuthIdentityMutation object of the builder.
|
||||
func (_u *AuthIdentityUpdateOne) Mutation() *AuthIdentityMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// ClearUser clears the "user" edge to the User entity.
|
||||
func (_u *AuthIdentityUpdateOne) ClearUser() *AuthIdentityUpdateOne {
|
||||
_u.mutation.ClearUser()
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearChannels clears all "channels" edges to the AuthIdentityChannel entity.
|
||||
func (_u *AuthIdentityUpdateOne) ClearChannels() *AuthIdentityUpdateOne {
|
||||
_u.mutation.ClearChannels()
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveChannelIDs removes the "channels" edge to AuthIdentityChannel entities by IDs.
|
||||
func (_u *AuthIdentityUpdateOne) RemoveChannelIDs(ids ...int64) *AuthIdentityUpdateOne {
|
||||
_u.mutation.RemoveChannelIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveChannels removes "channels" edges to AuthIdentityChannel entities.
|
||||
func (_u *AuthIdentityUpdateOne) RemoveChannels(v ...*AuthIdentityChannel) *AuthIdentityUpdateOne {
|
||||
ids := make([]int64, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.RemoveChannelIDs(ids...)
|
||||
}
|
||||
|
||||
// ClearAdoptionDecisions clears all "adoption_decisions" edges to the IdentityAdoptionDecision entity.
|
||||
func (_u *AuthIdentityUpdateOne) ClearAdoptionDecisions() *AuthIdentityUpdateOne {
|
||||
_u.mutation.ClearAdoptionDecisions()
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveAdoptionDecisionIDs removes the "adoption_decisions" edge to IdentityAdoptionDecision entities by IDs.
|
||||
func (_u *AuthIdentityUpdateOne) RemoveAdoptionDecisionIDs(ids ...int64) *AuthIdentityUpdateOne {
|
||||
_u.mutation.RemoveAdoptionDecisionIDs(ids...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// RemoveAdoptionDecisions removes "adoption_decisions" edges to IdentityAdoptionDecision entities.
|
||||
func (_u *AuthIdentityUpdateOne) RemoveAdoptionDecisions(v ...*IdentityAdoptionDecision) *AuthIdentityUpdateOne {
|
||||
ids := make([]int64, len(v))
|
||||
for i := range v {
|
||||
ids[i] = v[i].ID
|
||||
}
|
||||
return _u.RemoveAdoptionDecisionIDs(ids...)
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the AuthIdentityUpdate builder.
|
||||
func (_u *AuthIdentityUpdateOne) Where(ps ...predicate.AuthIdentity) *AuthIdentityUpdateOne {
|
||||
_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 *AuthIdentityUpdateOne) Select(field string, fields ...string) *AuthIdentityUpdateOne {
|
||||
_u.fields = append([]string{field}, fields...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// Save executes the query and returns the updated AuthIdentity entity.
|
||||
func (_u *AuthIdentityUpdateOne) Save(ctx context.Context) (*AuthIdentity, error) {
|
||||
_u.defaults()
|
||||
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_u *AuthIdentityUpdateOne) SaveX(ctx context.Context) *AuthIdentity {
|
||||
node, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// Exec executes the query on the entity.
|
||||
func (_u *AuthIdentityUpdateOne) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *AuthIdentityUpdateOne) 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 *AuthIdentityUpdateOne) defaults() {
|
||||
if _, ok := _u.mutation.UpdatedAt(); !ok {
|
||||
v := authidentity.UpdateDefaultUpdatedAt()
|
||||
_u.mutation.SetUpdatedAt(v)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_u *AuthIdentityUpdateOne) check() error {
|
||||
if v, ok := _u.mutation.ProviderType(); ok {
|
||||
if err := authidentity.ProviderTypeValidator(v); err != nil {
|
||||
return &ValidationError{Name: "provider_type", err: fmt.Errorf(`ent: validator failed for field "AuthIdentity.provider_type": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.ProviderKey(); ok {
|
||||
if err := authidentity.ProviderKeyValidator(v); err != nil {
|
||||
return &ValidationError{Name: "provider_key", err: fmt.Errorf(`ent: validator failed for field "AuthIdentity.provider_key": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.ProviderSubject(); ok {
|
||||
if err := authidentity.ProviderSubjectValidator(v); err != nil {
|
||||
return &ValidationError{Name: "provider_subject", err: fmt.Errorf(`ent: validator failed for field "AuthIdentity.provider_subject": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _u.mutation.UserCleared() && len(_u.mutation.UserIDs()) > 0 {
|
||||
return errors.New(`ent: clearing a required unique edge "AuthIdentity.user"`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_u *AuthIdentityUpdateOne) sqlSave(ctx context.Context) (_node *AuthIdentity, err error) {
|
||||
if err := _u.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := sqlgraph.NewUpdateSpec(authidentity.Table, authidentity.Columns, sqlgraph.NewFieldSpec(authidentity.FieldID, field.TypeInt64))
|
||||
id, ok := _u.mutation.ID()
|
||||
if !ok {
|
||||
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "AuthIdentity.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, authidentity.FieldID)
|
||||
for _, f := range fields {
|
||||
if !authidentity.ValidColumn(f) {
|
||||
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
if f != authidentity.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.UpdatedAt(); ok {
|
||||
_spec.SetField(authidentity.FieldUpdatedAt, field.TypeTime, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ProviderType(); ok {
|
||||
_spec.SetField(authidentity.FieldProviderType, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ProviderKey(); ok {
|
||||
_spec.SetField(authidentity.FieldProviderKey, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ProviderSubject(); ok {
|
||||
_spec.SetField(authidentity.FieldProviderSubject, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.VerifiedAt(); ok {
|
||||
_spec.SetField(authidentity.FieldVerifiedAt, field.TypeTime, value)
|
||||
}
|
||||
if _u.mutation.VerifiedAtCleared() {
|
||||
_spec.ClearField(authidentity.FieldVerifiedAt, field.TypeTime)
|
||||
}
|
||||
if value, ok := _u.mutation.Issuer(); ok {
|
||||
_spec.SetField(authidentity.FieldIssuer, field.TypeString, value)
|
||||
}
|
||||
if _u.mutation.IssuerCleared() {
|
||||
_spec.ClearField(authidentity.FieldIssuer, field.TypeString)
|
||||
}
|
||||
if value, ok := _u.mutation.Metadata(); ok {
|
||||
_spec.SetField(authidentity.FieldMetadata, field.TypeJSON, value)
|
||||
}
|
||||
if _u.mutation.UserCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: authidentity.UserTable,
|
||||
Columns: []string{authidentity.UserColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.UserIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: authidentity.UserTable,
|
||||
Columns: []string{authidentity.UserColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if _u.mutation.ChannelsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: authidentity.ChannelsTable,
|
||||
Columns: []string{authidentity.ChannelsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(authidentitychannel.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.RemovedChannelsIDs(); len(nodes) > 0 && !_u.mutation.ChannelsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: authidentity.ChannelsTable,
|
||||
Columns: []string{authidentity.ChannelsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(authidentitychannel.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.ChannelsIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: authidentity.ChannelsTable,
|
||||
Columns: []string{authidentity.ChannelsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(authidentitychannel.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
if _u.mutation.AdoptionDecisionsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: authidentity.AdoptionDecisionsTable,
|
||||
Columns: []string{authidentity.AdoptionDecisionsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(identityadoptiondecision.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.RemovedAdoptionDecisionsIDs(); len(nodes) > 0 && !_u.mutation.AdoptionDecisionsCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: authidentity.AdoptionDecisionsTable,
|
||||
Columns: []string{authidentity.AdoptionDecisionsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(identityadoptiondecision.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.AdoptionDecisionsIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.O2M,
|
||||
Inverse: false,
|
||||
Table: authidentity.AdoptionDecisionsTable,
|
||||
Columns: []string{authidentity.AdoptionDecisionsColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(identityadoptiondecision.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
_node = &AuthIdentity{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{authidentity.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
@@ -1,228 +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"
|
||||
"github.com/Wei-Shaw/sub2api/ent/authidentity"
|
||||
"github.com/Wei-Shaw/sub2api/ent/authidentitychannel"
|
||||
)
|
||||
|
||||
// AuthIdentityChannel is the model entity for the AuthIdentityChannel schema.
|
||||
type AuthIdentityChannel struct {
|
||||
config `json:"-"`
|
||||
// ID of the ent.
|
||||
ID int64 `json:"id,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"`
|
||||
// IdentityID holds the value of the "identity_id" field.
|
||||
IdentityID int64 `json:"identity_id,omitempty"`
|
||||
// ProviderType holds the value of the "provider_type" field.
|
||||
ProviderType string `json:"provider_type,omitempty"`
|
||||
// ProviderKey holds the value of the "provider_key" field.
|
||||
ProviderKey string `json:"provider_key,omitempty"`
|
||||
// Channel holds the value of the "channel" field.
|
||||
Channel string `json:"channel,omitempty"`
|
||||
// ChannelAppID holds the value of the "channel_app_id" field.
|
||||
ChannelAppID string `json:"channel_app_id,omitempty"`
|
||||
// ChannelSubject holds the value of the "channel_subject" field.
|
||||
ChannelSubject string `json:"channel_subject,omitempty"`
|
||||
// Metadata holds the value of the "metadata" field.
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
// Edges holds the relations/edges for other nodes in the graph.
|
||||
// The values are being populated by the AuthIdentityChannelQuery when eager-loading is set.
|
||||
Edges AuthIdentityChannelEdges `json:"edges"`
|
||||
selectValues sql.SelectValues
|
||||
}
|
||||
|
||||
// AuthIdentityChannelEdges holds the relations/edges for other nodes in the graph.
|
||||
type AuthIdentityChannelEdges struct {
|
||||
// Identity holds the value of the identity edge.
|
||||
Identity *AuthIdentity `json:"identity,omitempty"`
|
||||
// loadedTypes holds the information for reporting if a
|
||||
// type was loaded (or requested) in eager-loading or not.
|
||||
loadedTypes [1]bool
|
||||
}
|
||||
|
||||
// IdentityOrErr returns the Identity value or an error if the edge
|
||||
// was not loaded in eager-loading, or loaded but was not found.
|
||||
func (e AuthIdentityChannelEdges) IdentityOrErr() (*AuthIdentity, error) {
|
||||
if e.Identity != nil {
|
||||
return e.Identity, nil
|
||||
} else if e.loadedTypes[0] {
|
||||
return nil, &NotFoundError{label: authidentity.Label}
|
||||
}
|
||||
return nil, &NotLoadedError{edge: "identity"}
|
||||
}
|
||||
|
||||
// scanValues returns the types for scanning values from sql.Rows.
|
||||
func (*AuthIdentityChannel) scanValues(columns []string) ([]any, error) {
|
||||
values := make([]any, len(columns))
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case authidentitychannel.FieldMetadata:
|
||||
values[i] = new([]byte)
|
||||
case authidentitychannel.FieldID, authidentitychannel.FieldIdentityID:
|
||||
values[i] = new(sql.NullInt64)
|
||||
case authidentitychannel.FieldProviderType, authidentitychannel.FieldProviderKey, authidentitychannel.FieldChannel, authidentitychannel.FieldChannelAppID, authidentitychannel.FieldChannelSubject:
|
||||
values[i] = new(sql.NullString)
|
||||
case authidentitychannel.FieldCreatedAt, authidentitychannel.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 AuthIdentityChannel fields.
|
||||
func (_m *AuthIdentityChannel) 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 authidentitychannel.FieldID:
|
||||
value, ok := values[i].(*sql.NullInt64)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field id", value)
|
||||
}
|
||||
_m.ID = int64(value.Int64)
|
||||
case authidentitychannel.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 authidentitychannel.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
|
||||
}
|
||||
case authidentitychannel.FieldIdentityID:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field identity_id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.IdentityID = value.Int64
|
||||
}
|
||||
case authidentitychannel.FieldProviderType:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field provider_type", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ProviderType = value.String
|
||||
}
|
||||
case authidentitychannel.FieldProviderKey:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field provider_key", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ProviderKey = value.String
|
||||
}
|
||||
case authidentitychannel.FieldChannel:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field channel", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Channel = value.String
|
||||
}
|
||||
case authidentitychannel.FieldChannelAppID:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field channel_app_id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ChannelAppID = value.String
|
||||
}
|
||||
case authidentitychannel.FieldChannelSubject:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field channel_subject", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ChannelSubject = value.String
|
||||
}
|
||||
case authidentitychannel.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)
|
||||
}
|
||||
}
|
||||
default:
|
||||
_m.selectValues.Set(columns[i], values[i])
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Value returns the ent.Value that was dynamically selected and assigned to the AuthIdentityChannel.
|
||||
// This includes values selected through modifiers, order, etc.
|
||||
func (_m *AuthIdentityChannel) Value(name string) (ent.Value, error) {
|
||||
return _m.selectValues.Get(name)
|
||||
}
|
||||
|
||||
// QueryIdentity queries the "identity" edge of the AuthIdentityChannel entity.
|
||||
func (_m *AuthIdentityChannel) QueryIdentity() *AuthIdentityQuery {
|
||||
return NewAuthIdentityChannelClient(_m.config).QueryIdentity(_m)
|
||||
}
|
||||
|
||||
// Update returns a builder for updating this AuthIdentityChannel.
|
||||
// Note that you need to call AuthIdentityChannel.Unwrap() before calling this method if this AuthIdentityChannel
|
||||
// was returned from a transaction, and the transaction was committed or rolled back.
|
||||
func (_m *AuthIdentityChannel) Update() *AuthIdentityChannelUpdateOne {
|
||||
return NewAuthIdentityChannelClient(_m.config).UpdateOne(_m)
|
||||
}
|
||||
|
||||
// Unwrap unwraps the AuthIdentityChannel 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 *AuthIdentityChannel) Unwrap() *AuthIdentityChannel {
|
||||
_tx, ok := _m.config.driver.(*txDriver)
|
||||
if !ok {
|
||||
panic("ent: AuthIdentityChannel is not a transactional entity")
|
||||
}
|
||||
_m.config.driver = _tx.drv
|
||||
return _m
|
||||
}
|
||||
|
||||
// String implements the fmt.Stringer.
|
||||
func (_m *AuthIdentityChannel) String() string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString("AuthIdentityChannel(")
|
||||
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
|
||||
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.WriteString(", ")
|
||||
builder.WriteString("identity_id=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.IdentityID))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("provider_type=")
|
||||
builder.WriteString(_m.ProviderType)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("provider_key=")
|
||||
builder.WriteString(_m.ProviderKey)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("channel=")
|
||||
builder.WriteString(_m.Channel)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("channel_app_id=")
|
||||
builder.WriteString(_m.ChannelAppID)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("channel_subject=")
|
||||
builder.WriteString(_m.ChannelSubject)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("metadata=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.Metadata))
|
||||
builder.WriteByte(')')
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// AuthIdentityChannels is a parsable slice of AuthIdentityChannel.
|
||||
type AuthIdentityChannels []*AuthIdentityChannel
|
||||
@@ -1,153 +0,0 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package authidentitychannel
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
)
|
||||
|
||||
const (
|
||||
// Label holds the string label denoting the authidentitychannel type in the database.
|
||||
Label = "auth_identity_channel"
|
||||
// FieldID holds the string denoting the id field in the database.
|
||||
FieldID = "id"
|
||||
// FieldCreatedAt holds the string denoting the created_at field in the database.
|
||||
FieldCreatedAt = "created_at"
|
||||
// FieldUpdatedAt holds the string denoting the updated_at field in the database.
|
||||
FieldUpdatedAt = "updated_at"
|
||||
// FieldIdentityID holds the string denoting the identity_id field in the database.
|
||||
FieldIdentityID = "identity_id"
|
||||
// FieldProviderType holds the string denoting the provider_type field in the database.
|
||||
FieldProviderType = "provider_type"
|
||||
// FieldProviderKey holds the string denoting the provider_key field in the database.
|
||||
FieldProviderKey = "provider_key"
|
||||
// FieldChannel holds the string denoting the channel field in the database.
|
||||
FieldChannel = "channel"
|
||||
// FieldChannelAppID holds the string denoting the channel_app_id field in the database.
|
||||
FieldChannelAppID = "channel_app_id"
|
||||
// FieldChannelSubject holds the string denoting the channel_subject field in the database.
|
||||
FieldChannelSubject = "channel_subject"
|
||||
// FieldMetadata holds the string denoting the metadata field in the database.
|
||||
FieldMetadata = "metadata"
|
||||
// EdgeIdentity holds the string denoting the identity edge name in mutations.
|
||||
EdgeIdentity = "identity"
|
||||
// Table holds the table name of the authidentitychannel in the database.
|
||||
Table = "auth_identity_channels"
|
||||
// IdentityTable is the table that holds the identity relation/edge.
|
||||
IdentityTable = "auth_identity_channels"
|
||||
// IdentityInverseTable is the table name for the AuthIdentity entity.
|
||||
// It exists in this package in order to avoid circular dependency with the "authidentity" package.
|
||||
IdentityInverseTable = "auth_identities"
|
||||
// IdentityColumn is the table column denoting the identity relation/edge.
|
||||
IdentityColumn = "identity_id"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns for authidentitychannel fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldCreatedAt,
|
||||
FieldUpdatedAt,
|
||||
FieldIdentityID,
|
||||
FieldProviderType,
|
||||
FieldProviderKey,
|
||||
FieldChannel,
|
||||
FieldChannelAppID,
|
||||
FieldChannelSubject,
|
||||
FieldMetadata,
|
||||
}
|
||||
|
||||
// ValidColumn reports if the column name is valid (part of the table columns).
|
||||
func ValidColumn(column string) bool {
|
||||
for i := range Columns {
|
||||
if column == Columns[i] {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
var (
|
||||
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
|
||||
DefaultCreatedAt func() time.Time
|
||||
// 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
|
||||
// ProviderTypeValidator is a validator for the "provider_type" field. It is called by the builders before save.
|
||||
ProviderTypeValidator func(string) error
|
||||
// ProviderKeyValidator is a validator for the "provider_key" field. It is called by the builders before save.
|
||||
ProviderKeyValidator func(string) error
|
||||
// ChannelValidator is a validator for the "channel" field. It is called by the builders before save.
|
||||
ChannelValidator func(string) error
|
||||
// ChannelAppIDValidator is a validator for the "channel_app_id" field. It is called by the builders before save.
|
||||
ChannelAppIDValidator func(string) error
|
||||
// ChannelSubjectValidator is a validator for the "channel_subject" field. It is called by the builders before save.
|
||||
ChannelSubjectValidator func(string) error
|
||||
// DefaultMetadata holds the default value on creation for the "metadata" field.
|
||||
DefaultMetadata func() map[string]interface{}
|
||||
)
|
||||
|
||||
// OrderOption defines the ordering options for the AuthIdentityChannel queries.
|
||||
type OrderOption func(*sql.Selector)
|
||||
|
||||
// ByID orders the results by the id field.
|
||||
func ByID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByCreatedAt orders the results by the created_at field.
|
||||
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByUpdatedAt orders the results by the updated_at field.
|
||||
func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByIdentityID orders the results by the identity_id field.
|
||||
func ByIdentityID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldIdentityID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByProviderType orders the results by the provider_type field.
|
||||
func ByProviderType(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldProviderType, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByProviderKey orders the results by the provider_key field.
|
||||
func ByProviderKey(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldProviderKey, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByChannel orders the results by the channel field.
|
||||
func ByChannel(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldChannel, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByChannelAppID orders the results by the channel_app_id field.
|
||||
func ByChannelAppID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldChannelAppID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByChannelSubject orders the results by the channel_subject field.
|
||||
func ByChannelSubject(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldChannelSubject, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByIdentityField orders the results by identity field.
|
||||
func ByIdentityField(field string, opts ...sql.OrderTermOption) OrderOption {
|
||||
return func(s *sql.Selector) {
|
||||
sqlgraph.OrderByNeighborTerms(s, newIdentityStep(), sql.OrderByField(field, opts...))
|
||||
}
|
||||
}
|
||||
func newIdentityStep() *sqlgraph.Step {
|
||||
return sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.To(IdentityInverseTable, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, true, IdentityTable, IdentityColumn),
|
||||
)
|
||||
}
|
||||
@@ -1,559 +0,0 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package authidentitychannel
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"github.com/Wei-Shaw/sub2api/ent/predicate"
|
||||
)
|
||||
|
||||
// ID filters vertices based on their ID field.
|
||||
func ID(id int64) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDEQ applies the EQ predicate on the ID field.
|
||||
func IDEQ(id int64) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDNEQ applies the NEQ predicate on the ID field.
|
||||
func IDNEQ(id int64) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldNEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDIn applies the In predicate on the ID field.
|
||||
func IDIn(ids ...int64) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDNotIn applies the NotIn predicate on the ID field.
|
||||
func IDNotIn(ids ...int64) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldNotIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDGT applies the GT predicate on the ID field.
|
||||
func IDGT(id int64) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldGT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDGTE applies the GTE predicate on the ID field.
|
||||
func IDGTE(id int64) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldGTE(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLT applies the LT predicate on the ID field.
|
||||
func IDLT(id int64) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldLT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLTE applies the LTE predicate on the ID field.
|
||||
func IDLTE(id int64) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldLTE(FieldID, id))
|
||||
}
|
||||
|
||||
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
|
||||
func CreatedAt(v time.Time) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(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.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldEQ(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// IdentityID applies equality check predicate on the "identity_id" field. It's identical to IdentityIDEQ.
|
||||
func IdentityID(v int64) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldEQ(FieldIdentityID, v))
|
||||
}
|
||||
|
||||
// ProviderType applies equality check predicate on the "provider_type" field. It's identical to ProviderTypeEQ.
|
||||
func ProviderType(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldEQ(FieldProviderType, v))
|
||||
}
|
||||
|
||||
// ProviderKey applies equality check predicate on the "provider_key" field. It's identical to ProviderKeyEQ.
|
||||
func ProviderKey(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldEQ(FieldProviderKey, v))
|
||||
}
|
||||
|
||||
// Channel applies equality check predicate on the "channel" field. It's identical to ChannelEQ.
|
||||
func Channel(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldEQ(FieldChannel, v))
|
||||
}
|
||||
|
||||
// ChannelAppID applies equality check predicate on the "channel_app_id" field. It's identical to ChannelAppIDEQ.
|
||||
func ChannelAppID(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldEQ(FieldChannelAppID, v))
|
||||
}
|
||||
|
||||
// ChannelSubject applies equality check predicate on the "channel_subject" field. It's identical to ChannelSubjectEQ.
|
||||
func ChannelSubject(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldEQ(FieldChannelSubject, v))
|
||||
}
|
||||
|
||||
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
|
||||
func CreatedAtEQ(v time.Time) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldEQ(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
|
||||
func CreatedAtNEQ(v time.Time) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldNEQ(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtIn applies the In predicate on the "created_at" field.
|
||||
func CreatedAtIn(vs ...time.Time) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldIn(FieldCreatedAt, vs...))
|
||||
}
|
||||
|
||||
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
|
||||
func CreatedAtNotIn(vs ...time.Time) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldNotIn(FieldCreatedAt, vs...))
|
||||
}
|
||||
|
||||
// CreatedAtGT applies the GT predicate on the "created_at" field.
|
||||
func CreatedAtGT(v time.Time) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldGT(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
|
||||
func CreatedAtGTE(v time.Time) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldGTE(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtLT applies the LT predicate on the "created_at" field.
|
||||
func CreatedAtLT(v time.Time) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldLT(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
|
||||
func CreatedAtLTE(v time.Time) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldLTE(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
|
||||
func UpdatedAtEQ(v time.Time) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldEQ(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
|
||||
func UpdatedAtNEQ(v time.Time) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldNEQ(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtIn applies the In predicate on the "updated_at" field.
|
||||
func UpdatedAtIn(vs ...time.Time) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldIn(FieldUpdatedAt, vs...))
|
||||
}
|
||||
|
||||
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
|
||||
func UpdatedAtNotIn(vs ...time.Time) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldNotIn(FieldUpdatedAt, vs...))
|
||||
}
|
||||
|
||||
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
|
||||
func UpdatedAtGT(v time.Time) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldGT(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
|
||||
func UpdatedAtGTE(v time.Time) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldGTE(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
|
||||
func UpdatedAtLT(v time.Time) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldLT(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
|
||||
func UpdatedAtLTE(v time.Time) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldLTE(FieldUpdatedAt, v))
|
||||
}
|
||||
|
||||
// IdentityIDEQ applies the EQ predicate on the "identity_id" field.
|
||||
func IdentityIDEQ(v int64) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldEQ(FieldIdentityID, v))
|
||||
}
|
||||
|
||||
// IdentityIDNEQ applies the NEQ predicate on the "identity_id" field.
|
||||
func IdentityIDNEQ(v int64) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldNEQ(FieldIdentityID, v))
|
||||
}
|
||||
|
||||
// IdentityIDIn applies the In predicate on the "identity_id" field.
|
||||
func IdentityIDIn(vs ...int64) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldIn(FieldIdentityID, vs...))
|
||||
}
|
||||
|
||||
// IdentityIDNotIn applies the NotIn predicate on the "identity_id" field.
|
||||
func IdentityIDNotIn(vs ...int64) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldNotIn(FieldIdentityID, vs...))
|
||||
}
|
||||
|
||||
// ProviderTypeEQ applies the EQ predicate on the "provider_type" field.
|
||||
func ProviderTypeEQ(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldEQ(FieldProviderType, v))
|
||||
}
|
||||
|
||||
// ProviderTypeNEQ applies the NEQ predicate on the "provider_type" field.
|
||||
func ProviderTypeNEQ(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldNEQ(FieldProviderType, v))
|
||||
}
|
||||
|
||||
// ProviderTypeIn applies the In predicate on the "provider_type" field.
|
||||
func ProviderTypeIn(vs ...string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldIn(FieldProviderType, vs...))
|
||||
}
|
||||
|
||||
// ProviderTypeNotIn applies the NotIn predicate on the "provider_type" field.
|
||||
func ProviderTypeNotIn(vs ...string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldNotIn(FieldProviderType, vs...))
|
||||
}
|
||||
|
||||
// ProviderTypeGT applies the GT predicate on the "provider_type" field.
|
||||
func ProviderTypeGT(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldGT(FieldProviderType, v))
|
||||
}
|
||||
|
||||
// ProviderTypeGTE applies the GTE predicate on the "provider_type" field.
|
||||
func ProviderTypeGTE(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldGTE(FieldProviderType, v))
|
||||
}
|
||||
|
||||
// ProviderTypeLT applies the LT predicate on the "provider_type" field.
|
||||
func ProviderTypeLT(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldLT(FieldProviderType, v))
|
||||
}
|
||||
|
||||
// ProviderTypeLTE applies the LTE predicate on the "provider_type" field.
|
||||
func ProviderTypeLTE(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldLTE(FieldProviderType, v))
|
||||
}
|
||||
|
||||
// ProviderTypeContains applies the Contains predicate on the "provider_type" field.
|
||||
func ProviderTypeContains(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldContains(FieldProviderType, v))
|
||||
}
|
||||
|
||||
// ProviderTypeHasPrefix applies the HasPrefix predicate on the "provider_type" field.
|
||||
func ProviderTypeHasPrefix(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldHasPrefix(FieldProviderType, v))
|
||||
}
|
||||
|
||||
// ProviderTypeHasSuffix applies the HasSuffix predicate on the "provider_type" field.
|
||||
func ProviderTypeHasSuffix(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldHasSuffix(FieldProviderType, v))
|
||||
}
|
||||
|
||||
// ProviderTypeEqualFold applies the EqualFold predicate on the "provider_type" field.
|
||||
func ProviderTypeEqualFold(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldEqualFold(FieldProviderType, v))
|
||||
}
|
||||
|
||||
// ProviderTypeContainsFold applies the ContainsFold predicate on the "provider_type" field.
|
||||
func ProviderTypeContainsFold(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldContainsFold(FieldProviderType, v))
|
||||
}
|
||||
|
||||
// ProviderKeyEQ applies the EQ predicate on the "provider_key" field.
|
||||
func ProviderKeyEQ(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldEQ(FieldProviderKey, v))
|
||||
}
|
||||
|
||||
// ProviderKeyNEQ applies the NEQ predicate on the "provider_key" field.
|
||||
func ProviderKeyNEQ(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldNEQ(FieldProviderKey, v))
|
||||
}
|
||||
|
||||
// ProviderKeyIn applies the In predicate on the "provider_key" field.
|
||||
func ProviderKeyIn(vs ...string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldIn(FieldProviderKey, vs...))
|
||||
}
|
||||
|
||||
// ProviderKeyNotIn applies the NotIn predicate on the "provider_key" field.
|
||||
func ProviderKeyNotIn(vs ...string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldNotIn(FieldProviderKey, vs...))
|
||||
}
|
||||
|
||||
// ProviderKeyGT applies the GT predicate on the "provider_key" field.
|
||||
func ProviderKeyGT(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldGT(FieldProviderKey, v))
|
||||
}
|
||||
|
||||
// ProviderKeyGTE applies the GTE predicate on the "provider_key" field.
|
||||
func ProviderKeyGTE(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldGTE(FieldProviderKey, v))
|
||||
}
|
||||
|
||||
// ProviderKeyLT applies the LT predicate on the "provider_key" field.
|
||||
func ProviderKeyLT(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldLT(FieldProviderKey, v))
|
||||
}
|
||||
|
||||
// ProviderKeyLTE applies the LTE predicate on the "provider_key" field.
|
||||
func ProviderKeyLTE(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldLTE(FieldProviderKey, v))
|
||||
}
|
||||
|
||||
// ProviderKeyContains applies the Contains predicate on the "provider_key" field.
|
||||
func ProviderKeyContains(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldContains(FieldProviderKey, v))
|
||||
}
|
||||
|
||||
// ProviderKeyHasPrefix applies the HasPrefix predicate on the "provider_key" field.
|
||||
func ProviderKeyHasPrefix(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldHasPrefix(FieldProviderKey, v))
|
||||
}
|
||||
|
||||
// ProviderKeyHasSuffix applies the HasSuffix predicate on the "provider_key" field.
|
||||
func ProviderKeyHasSuffix(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldHasSuffix(FieldProviderKey, v))
|
||||
}
|
||||
|
||||
// ProviderKeyEqualFold applies the EqualFold predicate on the "provider_key" field.
|
||||
func ProviderKeyEqualFold(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldEqualFold(FieldProviderKey, v))
|
||||
}
|
||||
|
||||
// ProviderKeyContainsFold applies the ContainsFold predicate on the "provider_key" field.
|
||||
func ProviderKeyContainsFold(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldContainsFold(FieldProviderKey, v))
|
||||
}
|
||||
|
||||
// ChannelEQ applies the EQ predicate on the "channel" field.
|
||||
func ChannelEQ(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldEQ(FieldChannel, v))
|
||||
}
|
||||
|
||||
// ChannelNEQ applies the NEQ predicate on the "channel" field.
|
||||
func ChannelNEQ(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldNEQ(FieldChannel, v))
|
||||
}
|
||||
|
||||
// ChannelIn applies the In predicate on the "channel" field.
|
||||
func ChannelIn(vs ...string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldIn(FieldChannel, vs...))
|
||||
}
|
||||
|
||||
// ChannelNotIn applies the NotIn predicate on the "channel" field.
|
||||
func ChannelNotIn(vs ...string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldNotIn(FieldChannel, vs...))
|
||||
}
|
||||
|
||||
// ChannelGT applies the GT predicate on the "channel" field.
|
||||
func ChannelGT(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldGT(FieldChannel, v))
|
||||
}
|
||||
|
||||
// ChannelGTE applies the GTE predicate on the "channel" field.
|
||||
func ChannelGTE(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldGTE(FieldChannel, v))
|
||||
}
|
||||
|
||||
// ChannelLT applies the LT predicate on the "channel" field.
|
||||
func ChannelLT(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldLT(FieldChannel, v))
|
||||
}
|
||||
|
||||
// ChannelLTE applies the LTE predicate on the "channel" field.
|
||||
func ChannelLTE(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldLTE(FieldChannel, v))
|
||||
}
|
||||
|
||||
// ChannelContains applies the Contains predicate on the "channel" field.
|
||||
func ChannelContains(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldContains(FieldChannel, v))
|
||||
}
|
||||
|
||||
// ChannelHasPrefix applies the HasPrefix predicate on the "channel" field.
|
||||
func ChannelHasPrefix(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldHasPrefix(FieldChannel, v))
|
||||
}
|
||||
|
||||
// ChannelHasSuffix applies the HasSuffix predicate on the "channel" field.
|
||||
func ChannelHasSuffix(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldHasSuffix(FieldChannel, v))
|
||||
}
|
||||
|
||||
// ChannelEqualFold applies the EqualFold predicate on the "channel" field.
|
||||
func ChannelEqualFold(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldEqualFold(FieldChannel, v))
|
||||
}
|
||||
|
||||
// ChannelContainsFold applies the ContainsFold predicate on the "channel" field.
|
||||
func ChannelContainsFold(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldContainsFold(FieldChannel, v))
|
||||
}
|
||||
|
||||
// ChannelAppIDEQ applies the EQ predicate on the "channel_app_id" field.
|
||||
func ChannelAppIDEQ(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldEQ(FieldChannelAppID, v))
|
||||
}
|
||||
|
||||
// ChannelAppIDNEQ applies the NEQ predicate on the "channel_app_id" field.
|
||||
func ChannelAppIDNEQ(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldNEQ(FieldChannelAppID, v))
|
||||
}
|
||||
|
||||
// ChannelAppIDIn applies the In predicate on the "channel_app_id" field.
|
||||
func ChannelAppIDIn(vs ...string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldIn(FieldChannelAppID, vs...))
|
||||
}
|
||||
|
||||
// ChannelAppIDNotIn applies the NotIn predicate on the "channel_app_id" field.
|
||||
func ChannelAppIDNotIn(vs ...string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldNotIn(FieldChannelAppID, vs...))
|
||||
}
|
||||
|
||||
// ChannelAppIDGT applies the GT predicate on the "channel_app_id" field.
|
||||
func ChannelAppIDGT(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldGT(FieldChannelAppID, v))
|
||||
}
|
||||
|
||||
// ChannelAppIDGTE applies the GTE predicate on the "channel_app_id" field.
|
||||
func ChannelAppIDGTE(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldGTE(FieldChannelAppID, v))
|
||||
}
|
||||
|
||||
// ChannelAppIDLT applies the LT predicate on the "channel_app_id" field.
|
||||
func ChannelAppIDLT(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldLT(FieldChannelAppID, v))
|
||||
}
|
||||
|
||||
// ChannelAppIDLTE applies the LTE predicate on the "channel_app_id" field.
|
||||
func ChannelAppIDLTE(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldLTE(FieldChannelAppID, v))
|
||||
}
|
||||
|
||||
// ChannelAppIDContains applies the Contains predicate on the "channel_app_id" field.
|
||||
func ChannelAppIDContains(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldContains(FieldChannelAppID, v))
|
||||
}
|
||||
|
||||
// ChannelAppIDHasPrefix applies the HasPrefix predicate on the "channel_app_id" field.
|
||||
func ChannelAppIDHasPrefix(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldHasPrefix(FieldChannelAppID, v))
|
||||
}
|
||||
|
||||
// ChannelAppIDHasSuffix applies the HasSuffix predicate on the "channel_app_id" field.
|
||||
func ChannelAppIDHasSuffix(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldHasSuffix(FieldChannelAppID, v))
|
||||
}
|
||||
|
||||
// ChannelAppIDEqualFold applies the EqualFold predicate on the "channel_app_id" field.
|
||||
func ChannelAppIDEqualFold(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldEqualFold(FieldChannelAppID, v))
|
||||
}
|
||||
|
||||
// ChannelAppIDContainsFold applies the ContainsFold predicate on the "channel_app_id" field.
|
||||
func ChannelAppIDContainsFold(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldContainsFold(FieldChannelAppID, v))
|
||||
}
|
||||
|
||||
// ChannelSubjectEQ applies the EQ predicate on the "channel_subject" field.
|
||||
func ChannelSubjectEQ(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldEQ(FieldChannelSubject, v))
|
||||
}
|
||||
|
||||
// ChannelSubjectNEQ applies the NEQ predicate on the "channel_subject" field.
|
||||
func ChannelSubjectNEQ(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldNEQ(FieldChannelSubject, v))
|
||||
}
|
||||
|
||||
// ChannelSubjectIn applies the In predicate on the "channel_subject" field.
|
||||
func ChannelSubjectIn(vs ...string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldIn(FieldChannelSubject, vs...))
|
||||
}
|
||||
|
||||
// ChannelSubjectNotIn applies the NotIn predicate on the "channel_subject" field.
|
||||
func ChannelSubjectNotIn(vs ...string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldNotIn(FieldChannelSubject, vs...))
|
||||
}
|
||||
|
||||
// ChannelSubjectGT applies the GT predicate on the "channel_subject" field.
|
||||
func ChannelSubjectGT(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldGT(FieldChannelSubject, v))
|
||||
}
|
||||
|
||||
// ChannelSubjectGTE applies the GTE predicate on the "channel_subject" field.
|
||||
func ChannelSubjectGTE(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldGTE(FieldChannelSubject, v))
|
||||
}
|
||||
|
||||
// ChannelSubjectLT applies the LT predicate on the "channel_subject" field.
|
||||
func ChannelSubjectLT(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldLT(FieldChannelSubject, v))
|
||||
}
|
||||
|
||||
// ChannelSubjectLTE applies the LTE predicate on the "channel_subject" field.
|
||||
func ChannelSubjectLTE(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldLTE(FieldChannelSubject, v))
|
||||
}
|
||||
|
||||
// ChannelSubjectContains applies the Contains predicate on the "channel_subject" field.
|
||||
func ChannelSubjectContains(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldContains(FieldChannelSubject, v))
|
||||
}
|
||||
|
||||
// ChannelSubjectHasPrefix applies the HasPrefix predicate on the "channel_subject" field.
|
||||
func ChannelSubjectHasPrefix(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldHasPrefix(FieldChannelSubject, v))
|
||||
}
|
||||
|
||||
// ChannelSubjectHasSuffix applies the HasSuffix predicate on the "channel_subject" field.
|
||||
func ChannelSubjectHasSuffix(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldHasSuffix(FieldChannelSubject, v))
|
||||
}
|
||||
|
||||
// ChannelSubjectEqualFold applies the EqualFold predicate on the "channel_subject" field.
|
||||
func ChannelSubjectEqualFold(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldEqualFold(FieldChannelSubject, v))
|
||||
}
|
||||
|
||||
// ChannelSubjectContainsFold applies the ContainsFold predicate on the "channel_subject" field.
|
||||
func ChannelSubjectContainsFold(v string) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.FieldContainsFold(FieldChannelSubject, v))
|
||||
}
|
||||
|
||||
// HasIdentity applies the HasEdge predicate on the "identity" edge.
|
||||
func HasIdentity() predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(func(s *sql.Selector) {
|
||||
step := sqlgraph.NewStep(
|
||||
sqlgraph.From(Table, FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, true, IdentityTable, IdentityColumn),
|
||||
)
|
||||
sqlgraph.HasNeighbors(s, step)
|
||||
})
|
||||
}
|
||||
|
||||
// HasIdentityWith applies the HasEdge predicate on the "identity" edge with a given conditions (other predicates).
|
||||
func HasIdentityWith(preds ...predicate.AuthIdentity) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(func(s *sql.Selector) {
|
||||
step := newIdentityStep()
|
||||
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.AuthIdentityChannel) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.AndPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Or groups predicates with the OR operator between them.
|
||||
func Or(predicates ...predicate.AuthIdentityChannel) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.OrPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Not applies the not operator on the given predicate.
|
||||
func Not(p predicate.AuthIdentityChannel) predicate.AuthIdentityChannel {
|
||||
return predicate.AuthIdentityChannel(sql.NotPredicates(p))
|
||||
}
|
||||
@@ -1,932 +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"
|
||||
"github.com/Wei-Shaw/sub2api/ent/authidentity"
|
||||
"github.com/Wei-Shaw/sub2api/ent/authidentitychannel"
|
||||
)
|
||||
|
||||
// AuthIdentityChannelCreate is the builder for creating a AuthIdentityChannel entity.
|
||||
type AuthIdentityChannelCreate struct {
|
||||
config
|
||||
mutation *AuthIdentityChannelMutation
|
||||
hooks []Hook
|
||||
conflict []sql.ConflictOption
|
||||
}
|
||||
|
||||
// SetCreatedAt sets the "created_at" field.
|
||||
func (_c *AuthIdentityChannelCreate) SetCreatedAt(v time.Time) *AuthIdentityChannelCreate {
|
||||
_c.mutation.SetCreatedAt(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
|
||||
func (_c *AuthIdentityChannelCreate) SetNillableCreatedAt(v *time.Time) *AuthIdentityChannelCreate {
|
||||
if v != nil {
|
||||
_c.SetCreatedAt(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetUpdatedAt sets the "updated_at" field.
|
||||
func (_c *AuthIdentityChannelCreate) SetUpdatedAt(v time.Time) *AuthIdentityChannelCreate {
|
||||
_c.mutation.SetUpdatedAt(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
|
||||
func (_c *AuthIdentityChannelCreate) SetNillableUpdatedAt(v *time.Time) *AuthIdentityChannelCreate {
|
||||
if v != nil {
|
||||
_c.SetUpdatedAt(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetIdentityID sets the "identity_id" field.
|
||||
func (_c *AuthIdentityChannelCreate) SetIdentityID(v int64) *AuthIdentityChannelCreate {
|
||||
_c.mutation.SetIdentityID(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetProviderType sets the "provider_type" field.
|
||||
func (_c *AuthIdentityChannelCreate) SetProviderType(v string) *AuthIdentityChannelCreate {
|
||||
_c.mutation.SetProviderType(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetProviderKey sets the "provider_key" field.
|
||||
func (_c *AuthIdentityChannelCreate) SetProviderKey(v string) *AuthIdentityChannelCreate {
|
||||
_c.mutation.SetProviderKey(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetChannel sets the "channel" field.
|
||||
func (_c *AuthIdentityChannelCreate) SetChannel(v string) *AuthIdentityChannelCreate {
|
||||
_c.mutation.SetChannel(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetChannelAppID sets the "channel_app_id" field.
|
||||
func (_c *AuthIdentityChannelCreate) SetChannelAppID(v string) *AuthIdentityChannelCreate {
|
||||
_c.mutation.SetChannelAppID(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetChannelSubject sets the "channel_subject" field.
|
||||
func (_c *AuthIdentityChannelCreate) SetChannelSubject(v string) *AuthIdentityChannelCreate {
|
||||
_c.mutation.SetChannelSubject(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetMetadata sets the "metadata" field.
|
||||
func (_c *AuthIdentityChannelCreate) SetMetadata(v map[string]interface{}) *AuthIdentityChannelCreate {
|
||||
_c.mutation.SetMetadata(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetIdentity sets the "identity" edge to the AuthIdentity entity.
|
||||
func (_c *AuthIdentityChannelCreate) SetIdentity(v *AuthIdentity) *AuthIdentityChannelCreate {
|
||||
return _c.SetIdentityID(v.ID)
|
||||
}
|
||||
|
||||
// Mutation returns the AuthIdentityChannelMutation object of the builder.
|
||||
func (_c *AuthIdentityChannelCreate) Mutation() *AuthIdentityChannelMutation {
|
||||
return _c.mutation
|
||||
}
|
||||
|
||||
// Save creates the AuthIdentityChannel in the database.
|
||||
func (_c *AuthIdentityChannelCreate) Save(ctx context.Context) (*AuthIdentityChannel, error) {
|
||||
_c.defaults()
|
||||
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
|
||||
}
|
||||
|
||||
// SaveX calls Save and panics if Save returns an error.
|
||||
func (_c *AuthIdentityChannelCreate) SaveX(ctx context.Context) *AuthIdentityChannel {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *AuthIdentityChannelCreate) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *AuthIdentityChannelCreate) 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 *AuthIdentityChannelCreate) defaults() {
|
||||
if _, ok := _c.mutation.CreatedAt(); !ok {
|
||||
v := authidentitychannel.DefaultCreatedAt()
|
||||
_c.mutation.SetCreatedAt(v)
|
||||
}
|
||||
if _, ok := _c.mutation.UpdatedAt(); !ok {
|
||||
v := authidentitychannel.DefaultUpdatedAt()
|
||||
_c.mutation.SetUpdatedAt(v)
|
||||
}
|
||||
if _, ok := _c.mutation.Metadata(); !ok {
|
||||
v := authidentitychannel.DefaultMetadata()
|
||||
_c.mutation.SetMetadata(v)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_c *AuthIdentityChannelCreate) check() error {
|
||||
if _, ok := _c.mutation.CreatedAt(); !ok {
|
||||
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "AuthIdentityChannel.created_at"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.UpdatedAt(); !ok {
|
||||
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "AuthIdentityChannel.updated_at"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.IdentityID(); !ok {
|
||||
return &ValidationError{Name: "identity_id", err: errors.New(`ent: missing required field "AuthIdentityChannel.identity_id"`)}
|
||||
}
|
||||
if _, ok := _c.mutation.ProviderType(); !ok {
|
||||
return &ValidationError{Name: "provider_type", err: errors.New(`ent: missing required field "AuthIdentityChannel.provider_type"`)}
|
||||
}
|
||||
if v, ok := _c.mutation.ProviderType(); ok {
|
||||
if err := authidentitychannel.ProviderTypeValidator(v); err != nil {
|
||||
return &ValidationError{Name: "provider_type", err: fmt.Errorf(`ent: validator failed for field "AuthIdentityChannel.provider_type": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _, ok := _c.mutation.ProviderKey(); !ok {
|
||||
return &ValidationError{Name: "provider_key", err: errors.New(`ent: missing required field "AuthIdentityChannel.provider_key"`)}
|
||||
}
|
||||
if v, ok := _c.mutation.ProviderKey(); ok {
|
||||
if err := authidentitychannel.ProviderKeyValidator(v); err != nil {
|
||||
return &ValidationError{Name: "provider_key", err: fmt.Errorf(`ent: validator failed for field "AuthIdentityChannel.provider_key": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _, ok := _c.mutation.Channel(); !ok {
|
||||
return &ValidationError{Name: "channel", err: errors.New(`ent: missing required field "AuthIdentityChannel.channel"`)}
|
||||
}
|
||||
if v, ok := _c.mutation.Channel(); ok {
|
||||
if err := authidentitychannel.ChannelValidator(v); err != nil {
|
||||
return &ValidationError{Name: "channel", err: fmt.Errorf(`ent: validator failed for field "AuthIdentityChannel.channel": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _, ok := _c.mutation.ChannelAppID(); !ok {
|
||||
return &ValidationError{Name: "channel_app_id", err: errors.New(`ent: missing required field "AuthIdentityChannel.channel_app_id"`)}
|
||||
}
|
||||
if v, ok := _c.mutation.ChannelAppID(); ok {
|
||||
if err := authidentitychannel.ChannelAppIDValidator(v); err != nil {
|
||||
return &ValidationError{Name: "channel_app_id", err: fmt.Errorf(`ent: validator failed for field "AuthIdentityChannel.channel_app_id": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _, ok := _c.mutation.ChannelSubject(); !ok {
|
||||
return &ValidationError{Name: "channel_subject", err: errors.New(`ent: missing required field "AuthIdentityChannel.channel_subject"`)}
|
||||
}
|
||||
if v, ok := _c.mutation.ChannelSubject(); ok {
|
||||
if err := authidentitychannel.ChannelSubjectValidator(v); err != nil {
|
||||
return &ValidationError{Name: "channel_subject", err: fmt.Errorf(`ent: validator failed for field "AuthIdentityChannel.channel_subject": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _, ok := _c.mutation.Metadata(); !ok {
|
||||
return &ValidationError{Name: "metadata", err: errors.New(`ent: missing required field "AuthIdentityChannel.metadata"`)}
|
||||
}
|
||||
if len(_c.mutation.IdentityIDs()) == 0 {
|
||||
return &ValidationError{Name: "identity", err: errors.New(`ent: missing required edge "AuthIdentityChannel.identity"`)}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_c *AuthIdentityChannelCreate) sqlSave(ctx context.Context) (*AuthIdentityChannel, 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 = int64(id)
|
||||
_c.mutation.id = &_node.ID
|
||||
_c.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
func (_c *AuthIdentityChannelCreate) createSpec() (*AuthIdentityChannel, *sqlgraph.CreateSpec) {
|
||||
var (
|
||||
_node = &AuthIdentityChannel{config: _c.config}
|
||||
_spec = sqlgraph.NewCreateSpec(authidentitychannel.Table, sqlgraph.NewFieldSpec(authidentitychannel.FieldID, field.TypeInt64))
|
||||
)
|
||||
_spec.OnConflict = _c.conflict
|
||||
if value, ok := _c.mutation.CreatedAt(); ok {
|
||||
_spec.SetField(authidentitychannel.FieldCreatedAt, field.TypeTime, value)
|
||||
_node.CreatedAt = value
|
||||
}
|
||||
if value, ok := _c.mutation.UpdatedAt(); ok {
|
||||
_spec.SetField(authidentitychannel.FieldUpdatedAt, field.TypeTime, value)
|
||||
_node.UpdatedAt = value
|
||||
}
|
||||
if value, ok := _c.mutation.ProviderType(); ok {
|
||||
_spec.SetField(authidentitychannel.FieldProviderType, field.TypeString, value)
|
||||
_node.ProviderType = value
|
||||
}
|
||||
if value, ok := _c.mutation.ProviderKey(); ok {
|
||||
_spec.SetField(authidentitychannel.FieldProviderKey, field.TypeString, value)
|
||||
_node.ProviderKey = value
|
||||
}
|
||||
if value, ok := _c.mutation.Channel(); ok {
|
||||
_spec.SetField(authidentitychannel.FieldChannel, field.TypeString, value)
|
||||
_node.Channel = value
|
||||
}
|
||||
if value, ok := _c.mutation.ChannelAppID(); ok {
|
||||
_spec.SetField(authidentitychannel.FieldChannelAppID, field.TypeString, value)
|
||||
_node.ChannelAppID = value
|
||||
}
|
||||
if value, ok := _c.mutation.ChannelSubject(); ok {
|
||||
_spec.SetField(authidentitychannel.FieldChannelSubject, field.TypeString, value)
|
||||
_node.ChannelSubject = value
|
||||
}
|
||||
if value, ok := _c.mutation.Metadata(); ok {
|
||||
_spec.SetField(authidentitychannel.FieldMetadata, field.TypeJSON, value)
|
||||
_node.Metadata = value
|
||||
}
|
||||
if nodes := _c.mutation.IdentityIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: authidentitychannel.IdentityTable,
|
||||
Columns: []string{authidentitychannel.IdentityColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(authidentity.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_node.IdentityID = nodes[0]
|
||||
_spec.Edges = append(_spec.Edges, edge)
|
||||
}
|
||||
return _node, _spec
|
||||
}
|
||||
|
||||
// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
|
||||
// of the `INSERT` statement. For example:
|
||||
//
|
||||
// client.AuthIdentityChannel.Create().
|
||||
// SetCreatedAt(v).
|
||||
// OnConflict(
|
||||
// // Update the row with the new values
|
||||
// // the was proposed for insertion.
|
||||
// sql.ResolveWithNewValues(),
|
||||
// ).
|
||||
// // Override some of the fields with custom
|
||||
// // update values.
|
||||
// Update(func(u *ent.AuthIdentityChannelUpsert) {
|
||||
// SetCreatedAt(v+v).
|
||||
// }).
|
||||
// Exec(ctx)
|
||||
func (_c *AuthIdentityChannelCreate) OnConflict(opts ...sql.ConflictOption) *AuthIdentityChannelUpsertOne {
|
||||
_c.conflict = opts
|
||||
return &AuthIdentityChannelUpsertOne{
|
||||
create: _c,
|
||||
}
|
||||
}
|
||||
|
||||
// OnConflictColumns calls `OnConflict` and configures the columns
|
||||
// as conflict target. Using this option is equivalent to using:
|
||||
//
|
||||
// client.AuthIdentityChannel.Create().
|
||||
// OnConflict(sql.ConflictColumns(columns...)).
|
||||
// Exec(ctx)
|
||||
func (_c *AuthIdentityChannelCreate) OnConflictColumns(columns ...string) *AuthIdentityChannelUpsertOne {
|
||||
_c.conflict = append(_c.conflict, sql.ConflictColumns(columns...))
|
||||
return &AuthIdentityChannelUpsertOne{
|
||||
create: _c,
|
||||
}
|
||||
}
|
||||
|
||||
type (
|
||||
// AuthIdentityChannelUpsertOne is the builder for "upsert"-ing
|
||||
// one AuthIdentityChannel node.
|
||||
AuthIdentityChannelUpsertOne struct {
|
||||
create *AuthIdentityChannelCreate
|
||||
}
|
||||
|
||||
// AuthIdentityChannelUpsert is the "OnConflict" setter.
|
||||
AuthIdentityChannelUpsert struct {
|
||||
*sql.UpdateSet
|
||||
}
|
||||
)
|
||||
|
||||
// SetUpdatedAt sets the "updated_at" field.
|
||||
func (u *AuthIdentityChannelUpsert) SetUpdatedAt(v time.Time) *AuthIdentityChannelUpsert {
|
||||
u.Set(authidentitychannel.FieldUpdatedAt, v)
|
||||
return u
|
||||
}
|
||||
|
||||
// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
|
||||
func (u *AuthIdentityChannelUpsert) UpdateUpdatedAt() *AuthIdentityChannelUpsert {
|
||||
u.SetExcluded(authidentitychannel.FieldUpdatedAt)
|
||||
return u
|
||||
}
|
||||
|
||||
// SetIdentityID sets the "identity_id" field.
|
||||
func (u *AuthIdentityChannelUpsert) SetIdentityID(v int64) *AuthIdentityChannelUpsert {
|
||||
u.Set(authidentitychannel.FieldIdentityID, v)
|
||||
return u
|
||||
}
|
||||
|
||||
// UpdateIdentityID sets the "identity_id" field to the value that was provided on create.
|
||||
func (u *AuthIdentityChannelUpsert) UpdateIdentityID() *AuthIdentityChannelUpsert {
|
||||
u.SetExcluded(authidentitychannel.FieldIdentityID)
|
||||
return u
|
||||
}
|
||||
|
||||
// SetProviderType sets the "provider_type" field.
|
||||
func (u *AuthIdentityChannelUpsert) SetProviderType(v string) *AuthIdentityChannelUpsert {
|
||||
u.Set(authidentitychannel.FieldProviderType, v)
|
||||
return u
|
||||
}
|
||||
|
||||
// UpdateProviderType sets the "provider_type" field to the value that was provided on create.
|
||||
func (u *AuthIdentityChannelUpsert) UpdateProviderType() *AuthIdentityChannelUpsert {
|
||||
u.SetExcluded(authidentitychannel.FieldProviderType)
|
||||
return u
|
||||
}
|
||||
|
||||
// SetProviderKey sets the "provider_key" field.
|
||||
func (u *AuthIdentityChannelUpsert) SetProviderKey(v string) *AuthIdentityChannelUpsert {
|
||||
u.Set(authidentitychannel.FieldProviderKey, v)
|
||||
return u
|
||||
}
|
||||
|
||||
// UpdateProviderKey sets the "provider_key" field to the value that was provided on create.
|
||||
func (u *AuthIdentityChannelUpsert) UpdateProviderKey() *AuthIdentityChannelUpsert {
|
||||
u.SetExcluded(authidentitychannel.FieldProviderKey)
|
||||
return u
|
||||
}
|
||||
|
||||
// SetChannel sets the "channel" field.
|
||||
func (u *AuthIdentityChannelUpsert) SetChannel(v string) *AuthIdentityChannelUpsert {
|
||||
u.Set(authidentitychannel.FieldChannel, v)
|
||||
return u
|
||||
}
|
||||
|
||||
// UpdateChannel sets the "channel" field to the value that was provided on create.
|
||||
func (u *AuthIdentityChannelUpsert) UpdateChannel() *AuthIdentityChannelUpsert {
|
||||
u.SetExcluded(authidentitychannel.FieldChannel)
|
||||
return u
|
||||
}
|
||||
|
||||
// SetChannelAppID sets the "channel_app_id" field.
|
||||
func (u *AuthIdentityChannelUpsert) SetChannelAppID(v string) *AuthIdentityChannelUpsert {
|
||||
u.Set(authidentitychannel.FieldChannelAppID, v)
|
||||
return u
|
||||
}
|
||||
|
||||
// UpdateChannelAppID sets the "channel_app_id" field to the value that was provided on create.
|
||||
func (u *AuthIdentityChannelUpsert) UpdateChannelAppID() *AuthIdentityChannelUpsert {
|
||||
u.SetExcluded(authidentitychannel.FieldChannelAppID)
|
||||
return u
|
||||
}
|
||||
|
||||
// SetChannelSubject sets the "channel_subject" field.
|
||||
func (u *AuthIdentityChannelUpsert) SetChannelSubject(v string) *AuthIdentityChannelUpsert {
|
||||
u.Set(authidentitychannel.FieldChannelSubject, v)
|
||||
return u
|
||||
}
|
||||
|
||||
// UpdateChannelSubject sets the "channel_subject" field to the value that was provided on create.
|
||||
func (u *AuthIdentityChannelUpsert) UpdateChannelSubject() *AuthIdentityChannelUpsert {
|
||||
u.SetExcluded(authidentitychannel.FieldChannelSubject)
|
||||
return u
|
||||
}
|
||||
|
||||
// SetMetadata sets the "metadata" field.
|
||||
func (u *AuthIdentityChannelUpsert) SetMetadata(v map[string]interface{}) *AuthIdentityChannelUpsert {
|
||||
u.Set(authidentitychannel.FieldMetadata, v)
|
||||
return u
|
||||
}
|
||||
|
||||
// UpdateMetadata sets the "metadata" field to the value that was provided on create.
|
||||
func (u *AuthIdentityChannelUpsert) UpdateMetadata() *AuthIdentityChannelUpsert {
|
||||
u.SetExcluded(authidentitychannel.FieldMetadata)
|
||||
return u
|
||||
}
|
||||
|
||||
// UpdateNewValues updates the mutable fields using the new values that were set on create.
|
||||
// Using this option is equivalent to using:
|
||||
//
|
||||
// client.AuthIdentityChannel.Create().
|
||||
// OnConflict(
|
||||
// sql.ResolveWithNewValues(),
|
||||
// ).
|
||||
// Exec(ctx)
|
||||
func (u *AuthIdentityChannelUpsertOne) UpdateNewValues() *AuthIdentityChannelUpsertOne {
|
||||
u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
|
||||
u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
|
||||
if _, exists := u.create.mutation.CreatedAt(); exists {
|
||||
s.SetIgnore(authidentitychannel.FieldCreatedAt)
|
||||
}
|
||||
}))
|
||||
return u
|
||||
}
|
||||
|
||||
// Ignore sets each column to itself in case of conflict.
|
||||
// Using this option is equivalent to using:
|
||||
//
|
||||
// client.AuthIdentityChannel.Create().
|
||||
// OnConflict(sql.ResolveWithIgnore()).
|
||||
// Exec(ctx)
|
||||
func (u *AuthIdentityChannelUpsertOne) Ignore() *AuthIdentityChannelUpsertOne {
|
||||
u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
|
||||
return u
|
||||
}
|
||||
|
||||
// DoNothing configures the conflict_action to `DO NOTHING`.
|
||||
// Supported only by SQLite and PostgreSQL.
|
||||
func (u *AuthIdentityChannelUpsertOne) DoNothing() *AuthIdentityChannelUpsertOne {
|
||||
u.create.conflict = append(u.create.conflict, sql.DoNothing())
|
||||
return u
|
||||
}
|
||||
|
||||
// Update allows overriding fields `UPDATE` values. See the AuthIdentityChannelCreate.OnConflict
|
||||
// documentation for more info.
|
||||
func (u *AuthIdentityChannelUpsertOne) Update(set func(*AuthIdentityChannelUpsert)) *AuthIdentityChannelUpsertOne {
|
||||
u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
|
||||
set(&AuthIdentityChannelUpsert{UpdateSet: update})
|
||||
}))
|
||||
return u
|
||||
}
|
||||
|
||||
// SetUpdatedAt sets the "updated_at" field.
|
||||
func (u *AuthIdentityChannelUpsertOne) SetUpdatedAt(v time.Time) *AuthIdentityChannelUpsertOne {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.SetUpdatedAt(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
|
||||
func (u *AuthIdentityChannelUpsertOne) UpdateUpdatedAt() *AuthIdentityChannelUpsertOne {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.UpdateUpdatedAt()
|
||||
})
|
||||
}
|
||||
|
||||
// SetIdentityID sets the "identity_id" field.
|
||||
func (u *AuthIdentityChannelUpsertOne) SetIdentityID(v int64) *AuthIdentityChannelUpsertOne {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.SetIdentityID(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateIdentityID sets the "identity_id" field to the value that was provided on create.
|
||||
func (u *AuthIdentityChannelUpsertOne) UpdateIdentityID() *AuthIdentityChannelUpsertOne {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.UpdateIdentityID()
|
||||
})
|
||||
}
|
||||
|
||||
// SetProviderType sets the "provider_type" field.
|
||||
func (u *AuthIdentityChannelUpsertOne) SetProviderType(v string) *AuthIdentityChannelUpsertOne {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.SetProviderType(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateProviderType sets the "provider_type" field to the value that was provided on create.
|
||||
func (u *AuthIdentityChannelUpsertOne) UpdateProviderType() *AuthIdentityChannelUpsertOne {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.UpdateProviderType()
|
||||
})
|
||||
}
|
||||
|
||||
// SetProviderKey sets the "provider_key" field.
|
||||
func (u *AuthIdentityChannelUpsertOne) SetProviderKey(v string) *AuthIdentityChannelUpsertOne {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.SetProviderKey(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateProviderKey sets the "provider_key" field to the value that was provided on create.
|
||||
func (u *AuthIdentityChannelUpsertOne) UpdateProviderKey() *AuthIdentityChannelUpsertOne {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.UpdateProviderKey()
|
||||
})
|
||||
}
|
||||
|
||||
// SetChannel sets the "channel" field.
|
||||
func (u *AuthIdentityChannelUpsertOne) SetChannel(v string) *AuthIdentityChannelUpsertOne {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.SetChannel(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateChannel sets the "channel" field to the value that was provided on create.
|
||||
func (u *AuthIdentityChannelUpsertOne) UpdateChannel() *AuthIdentityChannelUpsertOne {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.UpdateChannel()
|
||||
})
|
||||
}
|
||||
|
||||
// SetChannelAppID sets the "channel_app_id" field.
|
||||
func (u *AuthIdentityChannelUpsertOne) SetChannelAppID(v string) *AuthIdentityChannelUpsertOne {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.SetChannelAppID(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateChannelAppID sets the "channel_app_id" field to the value that was provided on create.
|
||||
func (u *AuthIdentityChannelUpsertOne) UpdateChannelAppID() *AuthIdentityChannelUpsertOne {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.UpdateChannelAppID()
|
||||
})
|
||||
}
|
||||
|
||||
// SetChannelSubject sets the "channel_subject" field.
|
||||
func (u *AuthIdentityChannelUpsertOne) SetChannelSubject(v string) *AuthIdentityChannelUpsertOne {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.SetChannelSubject(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateChannelSubject sets the "channel_subject" field to the value that was provided on create.
|
||||
func (u *AuthIdentityChannelUpsertOne) UpdateChannelSubject() *AuthIdentityChannelUpsertOne {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.UpdateChannelSubject()
|
||||
})
|
||||
}
|
||||
|
||||
// SetMetadata sets the "metadata" field.
|
||||
func (u *AuthIdentityChannelUpsertOne) SetMetadata(v map[string]interface{}) *AuthIdentityChannelUpsertOne {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.SetMetadata(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateMetadata sets the "metadata" field to the value that was provided on create.
|
||||
func (u *AuthIdentityChannelUpsertOne) UpdateMetadata() *AuthIdentityChannelUpsertOne {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.UpdateMetadata()
|
||||
})
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (u *AuthIdentityChannelUpsertOne) Exec(ctx context.Context) error {
|
||||
if len(u.create.conflict) == 0 {
|
||||
return errors.New("ent: missing options for AuthIdentityChannelCreate.OnConflict")
|
||||
}
|
||||
return u.create.Exec(ctx)
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (u *AuthIdentityChannelUpsertOne) ExecX(ctx context.Context) {
|
||||
if err := u.create.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Exec executes the UPSERT query and returns the inserted/updated ID.
|
||||
func (u *AuthIdentityChannelUpsertOne) ID(ctx context.Context) (id int64, err error) {
|
||||
node, err := u.create.Save(ctx)
|
||||
if err != nil {
|
||||
return id, err
|
||||
}
|
||||
return node.ID, nil
|
||||
}
|
||||
|
||||
// IDX is like ID, but panics if an error occurs.
|
||||
func (u *AuthIdentityChannelUpsertOne) IDX(ctx context.Context) int64 {
|
||||
id, err := u.ID(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// AuthIdentityChannelCreateBulk is the builder for creating many AuthIdentityChannel entities in bulk.
|
||||
type AuthIdentityChannelCreateBulk struct {
|
||||
config
|
||||
err error
|
||||
builders []*AuthIdentityChannelCreate
|
||||
conflict []sql.ConflictOption
|
||||
}
|
||||
|
||||
// Save creates the AuthIdentityChannel entities in the database.
|
||||
func (_c *AuthIdentityChannelCreateBulk) Save(ctx context.Context) ([]*AuthIdentityChannel, error) {
|
||||
if _c.err != nil {
|
||||
return nil, _c.err
|
||||
}
|
||||
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
|
||||
nodes := make([]*AuthIdentityChannel, 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.(*AuthIdentityChannelMutation)
|
||||
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}
|
||||
spec.OnConflict = _c.conflict
|
||||
// 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 = int64(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 *AuthIdentityChannelCreateBulk) SaveX(ctx context.Context) []*AuthIdentityChannel {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *AuthIdentityChannelCreateBulk) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *AuthIdentityChannelCreateBulk) ExecX(ctx context.Context) {
|
||||
if err := _c.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
|
||||
// of the `INSERT` statement. For example:
|
||||
//
|
||||
// client.AuthIdentityChannel.CreateBulk(builders...).
|
||||
// OnConflict(
|
||||
// // Update the row with the new values
|
||||
// // the was proposed for insertion.
|
||||
// sql.ResolveWithNewValues(),
|
||||
// ).
|
||||
// // Override some of the fields with custom
|
||||
// // update values.
|
||||
// Update(func(u *ent.AuthIdentityChannelUpsert) {
|
||||
// SetCreatedAt(v+v).
|
||||
// }).
|
||||
// Exec(ctx)
|
||||
func (_c *AuthIdentityChannelCreateBulk) OnConflict(opts ...sql.ConflictOption) *AuthIdentityChannelUpsertBulk {
|
||||
_c.conflict = opts
|
||||
return &AuthIdentityChannelUpsertBulk{
|
||||
create: _c,
|
||||
}
|
||||
}
|
||||
|
||||
// OnConflictColumns calls `OnConflict` and configures the columns
|
||||
// as conflict target. Using this option is equivalent to using:
|
||||
//
|
||||
// client.AuthIdentityChannel.Create().
|
||||
// OnConflict(sql.ConflictColumns(columns...)).
|
||||
// Exec(ctx)
|
||||
func (_c *AuthIdentityChannelCreateBulk) OnConflictColumns(columns ...string) *AuthIdentityChannelUpsertBulk {
|
||||
_c.conflict = append(_c.conflict, sql.ConflictColumns(columns...))
|
||||
return &AuthIdentityChannelUpsertBulk{
|
||||
create: _c,
|
||||
}
|
||||
}
|
||||
|
||||
// AuthIdentityChannelUpsertBulk is the builder for "upsert"-ing
|
||||
// a bulk of AuthIdentityChannel nodes.
|
||||
type AuthIdentityChannelUpsertBulk struct {
|
||||
create *AuthIdentityChannelCreateBulk
|
||||
}
|
||||
|
||||
// UpdateNewValues updates the mutable fields using the new values that
|
||||
// were set on create. Using this option is equivalent to using:
|
||||
//
|
||||
// client.AuthIdentityChannel.Create().
|
||||
// OnConflict(
|
||||
// sql.ResolveWithNewValues(),
|
||||
// ).
|
||||
// Exec(ctx)
|
||||
func (u *AuthIdentityChannelUpsertBulk) UpdateNewValues() *AuthIdentityChannelUpsertBulk {
|
||||
u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
|
||||
u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
|
||||
for _, b := range u.create.builders {
|
||||
if _, exists := b.mutation.CreatedAt(); exists {
|
||||
s.SetIgnore(authidentitychannel.FieldCreatedAt)
|
||||
}
|
||||
}
|
||||
}))
|
||||
return u
|
||||
}
|
||||
|
||||
// Ignore sets each column to itself in case of conflict.
|
||||
// Using this option is equivalent to using:
|
||||
//
|
||||
// client.AuthIdentityChannel.Create().
|
||||
// OnConflict(sql.ResolveWithIgnore()).
|
||||
// Exec(ctx)
|
||||
func (u *AuthIdentityChannelUpsertBulk) Ignore() *AuthIdentityChannelUpsertBulk {
|
||||
u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
|
||||
return u
|
||||
}
|
||||
|
||||
// DoNothing configures the conflict_action to `DO NOTHING`.
|
||||
// Supported only by SQLite and PostgreSQL.
|
||||
func (u *AuthIdentityChannelUpsertBulk) DoNothing() *AuthIdentityChannelUpsertBulk {
|
||||
u.create.conflict = append(u.create.conflict, sql.DoNothing())
|
||||
return u
|
||||
}
|
||||
|
||||
// Update allows overriding fields `UPDATE` values. See the AuthIdentityChannelCreateBulk.OnConflict
|
||||
// documentation for more info.
|
||||
func (u *AuthIdentityChannelUpsertBulk) Update(set func(*AuthIdentityChannelUpsert)) *AuthIdentityChannelUpsertBulk {
|
||||
u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
|
||||
set(&AuthIdentityChannelUpsert{UpdateSet: update})
|
||||
}))
|
||||
return u
|
||||
}
|
||||
|
||||
// SetUpdatedAt sets the "updated_at" field.
|
||||
func (u *AuthIdentityChannelUpsertBulk) SetUpdatedAt(v time.Time) *AuthIdentityChannelUpsertBulk {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.SetUpdatedAt(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateUpdatedAt sets the "updated_at" field to the value that was provided on create.
|
||||
func (u *AuthIdentityChannelUpsertBulk) UpdateUpdatedAt() *AuthIdentityChannelUpsertBulk {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.UpdateUpdatedAt()
|
||||
})
|
||||
}
|
||||
|
||||
// SetIdentityID sets the "identity_id" field.
|
||||
func (u *AuthIdentityChannelUpsertBulk) SetIdentityID(v int64) *AuthIdentityChannelUpsertBulk {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.SetIdentityID(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateIdentityID sets the "identity_id" field to the value that was provided on create.
|
||||
func (u *AuthIdentityChannelUpsertBulk) UpdateIdentityID() *AuthIdentityChannelUpsertBulk {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.UpdateIdentityID()
|
||||
})
|
||||
}
|
||||
|
||||
// SetProviderType sets the "provider_type" field.
|
||||
func (u *AuthIdentityChannelUpsertBulk) SetProviderType(v string) *AuthIdentityChannelUpsertBulk {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.SetProviderType(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateProviderType sets the "provider_type" field to the value that was provided on create.
|
||||
func (u *AuthIdentityChannelUpsertBulk) UpdateProviderType() *AuthIdentityChannelUpsertBulk {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.UpdateProviderType()
|
||||
})
|
||||
}
|
||||
|
||||
// SetProviderKey sets the "provider_key" field.
|
||||
func (u *AuthIdentityChannelUpsertBulk) SetProviderKey(v string) *AuthIdentityChannelUpsertBulk {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.SetProviderKey(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateProviderKey sets the "provider_key" field to the value that was provided on create.
|
||||
func (u *AuthIdentityChannelUpsertBulk) UpdateProviderKey() *AuthIdentityChannelUpsertBulk {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.UpdateProviderKey()
|
||||
})
|
||||
}
|
||||
|
||||
// SetChannel sets the "channel" field.
|
||||
func (u *AuthIdentityChannelUpsertBulk) SetChannel(v string) *AuthIdentityChannelUpsertBulk {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.SetChannel(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateChannel sets the "channel" field to the value that was provided on create.
|
||||
func (u *AuthIdentityChannelUpsertBulk) UpdateChannel() *AuthIdentityChannelUpsertBulk {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.UpdateChannel()
|
||||
})
|
||||
}
|
||||
|
||||
// SetChannelAppID sets the "channel_app_id" field.
|
||||
func (u *AuthIdentityChannelUpsertBulk) SetChannelAppID(v string) *AuthIdentityChannelUpsertBulk {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.SetChannelAppID(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateChannelAppID sets the "channel_app_id" field to the value that was provided on create.
|
||||
func (u *AuthIdentityChannelUpsertBulk) UpdateChannelAppID() *AuthIdentityChannelUpsertBulk {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.UpdateChannelAppID()
|
||||
})
|
||||
}
|
||||
|
||||
// SetChannelSubject sets the "channel_subject" field.
|
||||
func (u *AuthIdentityChannelUpsertBulk) SetChannelSubject(v string) *AuthIdentityChannelUpsertBulk {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.SetChannelSubject(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateChannelSubject sets the "channel_subject" field to the value that was provided on create.
|
||||
func (u *AuthIdentityChannelUpsertBulk) UpdateChannelSubject() *AuthIdentityChannelUpsertBulk {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.UpdateChannelSubject()
|
||||
})
|
||||
}
|
||||
|
||||
// SetMetadata sets the "metadata" field.
|
||||
func (u *AuthIdentityChannelUpsertBulk) SetMetadata(v map[string]interface{}) *AuthIdentityChannelUpsertBulk {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.SetMetadata(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateMetadata sets the "metadata" field to the value that was provided on create.
|
||||
func (u *AuthIdentityChannelUpsertBulk) UpdateMetadata() *AuthIdentityChannelUpsertBulk {
|
||||
return u.Update(func(s *AuthIdentityChannelUpsert) {
|
||||
s.UpdateMetadata()
|
||||
})
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (u *AuthIdentityChannelUpsertBulk) Exec(ctx context.Context) error {
|
||||
if u.create.err != nil {
|
||||
return u.create.err
|
||||
}
|
||||
for i, b := range u.create.builders {
|
||||
if len(b.conflict) != 0 {
|
||||
return fmt.Errorf("ent: OnConflict was set for builder %d. Set it on the AuthIdentityChannelCreateBulk instead", i)
|
||||
}
|
||||
}
|
||||
if len(u.create.conflict) == 0 {
|
||||
return errors.New("ent: missing options for AuthIdentityChannelCreateBulk.OnConflict")
|
||||
}
|
||||
return u.create.Exec(ctx)
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (u *AuthIdentityChannelUpsertBulk) ExecX(ctx context.Context) {
|
||||
if err := u.create.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
"github.com/Wei-Shaw/sub2api/ent/authidentitychannel"
|
||||
"github.com/Wei-Shaw/sub2api/ent/predicate"
|
||||
)
|
||||
|
||||
// AuthIdentityChannelDelete is the builder for deleting a AuthIdentityChannel entity.
|
||||
type AuthIdentityChannelDelete struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *AuthIdentityChannelMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the AuthIdentityChannelDelete builder.
|
||||
func (_d *AuthIdentityChannelDelete) Where(ps ...predicate.AuthIdentityChannel) *AuthIdentityChannelDelete {
|
||||
_d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query and returns how many vertices were deleted.
|
||||
func (_d *AuthIdentityChannelDelete) 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 *AuthIdentityChannelDelete) ExecX(ctx context.Context) int {
|
||||
n, err := _d.Exec(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (_d *AuthIdentityChannelDelete) sqlExec(ctx context.Context) (int, error) {
|
||||
_spec := sqlgraph.NewDeleteSpec(authidentitychannel.Table, sqlgraph.NewFieldSpec(authidentitychannel.FieldID, field.TypeInt64))
|
||||
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
|
||||
}
|
||||
|
||||
// AuthIdentityChannelDeleteOne is the builder for deleting a single AuthIdentityChannel entity.
|
||||
type AuthIdentityChannelDeleteOne struct {
|
||||
_d *AuthIdentityChannelDelete
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the AuthIdentityChannelDelete builder.
|
||||
func (_d *AuthIdentityChannelDeleteOne) Where(ps ...predicate.AuthIdentityChannel) *AuthIdentityChannelDeleteOne {
|
||||
_d._d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query.
|
||||
func (_d *AuthIdentityChannelDeleteOne) Exec(ctx context.Context) error {
|
||||
n, err := _d._d.Exec(ctx)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case n == 0:
|
||||
return &NotFoundError{authidentitychannel.Label}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_d *AuthIdentityChannelDeleteOne) ExecX(ctx context.Context) {
|
||||
if err := _d.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
@@ -1,643 +0,0 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/Wei-Shaw/sub2api/ent/authidentity"
|
||||
"github.com/Wei-Shaw/sub2api/ent/authidentitychannel"
|
||||
"github.com/Wei-Shaw/sub2api/ent/predicate"
|
||||
)
|
||||
|
||||
// AuthIdentityChannelQuery is the builder for querying AuthIdentityChannel entities.
|
||||
type AuthIdentityChannelQuery struct {
|
||||
config
|
||||
ctx *QueryContext
|
||||
order []authidentitychannel.OrderOption
|
||||
inters []Interceptor
|
||||
predicates []predicate.AuthIdentityChannel
|
||||
withIdentity *AuthIdentityQuery
|
||||
modifiers []func(*sql.Selector)
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
path func(context.Context) (*sql.Selector, error)
|
||||
}
|
||||
|
||||
// Where adds a new predicate for the AuthIdentityChannelQuery builder.
|
||||
func (_q *AuthIdentityChannelQuery) Where(ps ...predicate.AuthIdentityChannel) *AuthIdentityChannelQuery {
|
||||
_q.predicates = append(_q.predicates, ps...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// Limit the number of records to be returned by this query.
|
||||
func (_q *AuthIdentityChannelQuery) Limit(limit int) *AuthIdentityChannelQuery {
|
||||
_q.ctx.Limit = &limit
|
||||
return _q
|
||||
}
|
||||
|
||||
// Offset to start from.
|
||||
func (_q *AuthIdentityChannelQuery) Offset(offset int) *AuthIdentityChannelQuery {
|
||||
_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 *AuthIdentityChannelQuery) Unique(unique bool) *AuthIdentityChannelQuery {
|
||||
_q.ctx.Unique = &unique
|
||||
return _q
|
||||
}
|
||||
|
||||
// Order specifies how the records should be ordered.
|
||||
func (_q *AuthIdentityChannelQuery) Order(o ...authidentitychannel.OrderOption) *AuthIdentityChannelQuery {
|
||||
_q.order = append(_q.order, o...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// QueryIdentity chains the current query on the "identity" edge.
|
||||
func (_q *AuthIdentityChannelQuery) QueryIdentity() *AuthIdentityQuery {
|
||||
query := (&AuthIdentityClient{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(authidentitychannel.Table, authidentitychannel.FieldID, selector),
|
||||
sqlgraph.To(authidentity.Table, authidentity.FieldID),
|
||||
sqlgraph.Edge(sqlgraph.M2O, true, authidentitychannel.IdentityTable, authidentitychannel.IdentityColumn),
|
||||
)
|
||||
fromU = sqlgraph.SetNeighbors(_q.driver.Dialect(), step)
|
||||
return fromU, nil
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
// First returns the first AuthIdentityChannel entity from the query.
|
||||
// Returns a *NotFoundError when no AuthIdentityChannel was found.
|
||||
func (_q *AuthIdentityChannelQuery) First(ctx context.Context) (*AuthIdentityChannel, 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{authidentitychannel.Label}
|
||||
}
|
||||
return nodes[0], nil
|
||||
}
|
||||
|
||||
// FirstX is like First, but panics if an error occurs.
|
||||
func (_q *AuthIdentityChannelQuery) FirstX(ctx context.Context) *AuthIdentityChannel {
|
||||
node, err := _q.First(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// FirstID returns the first AuthIdentityChannel ID from the query.
|
||||
// Returns a *NotFoundError when no AuthIdentityChannel ID was found.
|
||||
func (_q *AuthIdentityChannelQuery) FirstID(ctx context.Context) (id int64, err error) {
|
||||
var ids []int64
|
||||
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
|
||||
return
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
err = &NotFoundError{authidentitychannel.Label}
|
||||
return
|
||||
}
|
||||
return ids[0], nil
|
||||
}
|
||||
|
||||
// FirstIDX is like FirstID, but panics if an error occurs.
|
||||
func (_q *AuthIdentityChannelQuery) FirstIDX(ctx context.Context) int64 {
|
||||
id, err := _q.FirstID(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// Only returns a single AuthIdentityChannel entity found by the query, ensuring it only returns one.
|
||||
// Returns a *NotSingularError when more than one AuthIdentityChannel entity is found.
|
||||
// Returns a *NotFoundError when no AuthIdentityChannel entities are found.
|
||||
func (_q *AuthIdentityChannelQuery) Only(ctx context.Context) (*AuthIdentityChannel, 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{authidentitychannel.Label}
|
||||
default:
|
||||
return nil, &NotSingularError{authidentitychannel.Label}
|
||||
}
|
||||
}
|
||||
|
||||
// OnlyX is like Only, but panics if an error occurs.
|
||||
func (_q *AuthIdentityChannelQuery) OnlyX(ctx context.Context) *AuthIdentityChannel {
|
||||
node, err := _q.Only(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// OnlyID is like Only, but returns the only AuthIdentityChannel ID in the query.
|
||||
// Returns a *NotSingularError when more than one AuthIdentityChannel ID is found.
|
||||
// Returns a *NotFoundError when no entities are found.
|
||||
func (_q *AuthIdentityChannelQuery) OnlyID(ctx context.Context) (id int64, err error) {
|
||||
var ids []int64
|
||||
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{authidentitychannel.Label}
|
||||
default:
|
||||
err = &NotSingularError{authidentitychannel.Label}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// OnlyIDX is like OnlyID, but panics if an error occurs.
|
||||
func (_q *AuthIdentityChannelQuery) OnlyIDX(ctx context.Context) int64 {
|
||||
id, err := _q.OnlyID(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// All executes the query and returns a list of AuthIdentityChannels.
|
||||
func (_q *AuthIdentityChannelQuery) All(ctx context.Context) ([]*AuthIdentityChannel, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
|
||||
if err := _q.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qr := querierAll[[]*AuthIdentityChannel, *AuthIdentityChannelQuery]()
|
||||
return withInterceptors[[]*AuthIdentityChannel](ctx, _q, qr, _q.inters)
|
||||
}
|
||||
|
||||
// AllX is like All, but panics if an error occurs.
|
||||
func (_q *AuthIdentityChannelQuery) AllX(ctx context.Context) []*AuthIdentityChannel {
|
||||
nodes, err := _q.All(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
||||
// IDs executes the query and returns a list of AuthIdentityChannel IDs.
|
||||
func (_q *AuthIdentityChannelQuery) IDs(ctx context.Context) (ids []int64, err error) {
|
||||
if _q.ctx.Unique == nil && _q.path != nil {
|
||||
_q.Unique(true)
|
||||
}
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
|
||||
if err = _q.Select(authidentitychannel.FieldID).Scan(ctx, &ids); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// IDsX is like IDs, but panics if an error occurs.
|
||||
func (_q *AuthIdentityChannelQuery) IDsX(ctx context.Context) []int64 {
|
||||
ids, err := _q.IDs(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// Count returns the count of the given query.
|
||||
func (_q *AuthIdentityChannelQuery) 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[*AuthIdentityChannelQuery](), _q.inters)
|
||||
}
|
||||
|
||||
// CountX is like Count, but panics if an error occurs.
|
||||
func (_q *AuthIdentityChannelQuery) 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 *AuthIdentityChannelQuery) 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 *AuthIdentityChannelQuery) ExistX(ctx context.Context) bool {
|
||||
exist, err := _q.Exist(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return exist
|
||||
}
|
||||
|
||||
// Clone returns a duplicate of the AuthIdentityChannelQuery 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 *AuthIdentityChannelQuery) Clone() *AuthIdentityChannelQuery {
|
||||
if _q == nil {
|
||||
return nil
|
||||
}
|
||||
return &AuthIdentityChannelQuery{
|
||||
config: _q.config,
|
||||
ctx: _q.ctx.Clone(),
|
||||
order: append([]authidentitychannel.OrderOption{}, _q.order...),
|
||||
inters: append([]Interceptor{}, _q.inters...),
|
||||
predicates: append([]predicate.AuthIdentityChannel{}, _q.predicates...),
|
||||
withIdentity: _q.withIdentity.Clone(),
|
||||
// clone intermediate query.
|
||||
sql: _q.sql.Clone(),
|
||||
path: _q.path,
|
||||
}
|
||||
}
|
||||
|
||||
// WithIdentity tells the query-builder to eager-load the nodes that are connected to
|
||||
// the "identity" edge. The optional arguments are used to configure the query builder of the edge.
|
||||
func (_q *AuthIdentityChannelQuery) WithIdentity(opts ...func(*AuthIdentityQuery)) *AuthIdentityChannelQuery {
|
||||
query := (&AuthIdentityClient{config: _q.config}).Query()
|
||||
for _, opt := range opts {
|
||||
opt(query)
|
||||
}
|
||||
_q.withIdentity = 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 {
|
||||
// CreatedAt time.Time `json:"created_at,omitempty"`
|
||||
// Count int `json:"count,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.AuthIdentityChannel.Query().
|
||||
// GroupBy(authidentitychannel.FieldCreatedAt).
|
||||
// Aggregate(ent.Count()).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *AuthIdentityChannelQuery) GroupBy(field string, fields ...string) *AuthIdentityChannelGroupBy {
|
||||
_q.ctx.Fields = append([]string{field}, fields...)
|
||||
grbuild := &AuthIdentityChannelGroupBy{build: _q}
|
||||
grbuild.flds = &_q.ctx.Fields
|
||||
grbuild.label = authidentitychannel.Label
|
||||
grbuild.scan = grbuild.Scan
|
||||
return grbuild
|
||||
}
|
||||
|
||||
// Select allows the selection one or more fields/columns for the given query,
|
||||
// instead of selecting all fields in the entity.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// var v []struct {
|
||||
// CreatedAt time.Time `json:"created_at,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.AuthIdentityChannel.Query().
|
||||
// Select(authidentitychannel.FieldCreatedAt).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *AuthIdentityChannelQuery) Select(fields ...string) *AuthIdentityChannelSelect {
|
||||
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
|
||||
sbuild := &AuthIdentityChannelSelect{AuthIdentityChannelQuery: _q}
|
||||
sbuild.label = authidentitychannel.Label
|
||||
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
|
||||
return sbuild
|
||||
}
|
||||
|
||||
// Aggregate returns a AuthIdentityChannelSelect configured with the given aggregations.
|
||||
func (_q *AuthIdentityChannelQuery) Aggregate(fns ...AggregateFunc) *AuthIdentityChannelSelect {
|
||||
return _q.Select().Aggregate(fns...)
|
||||
}
|
||||
|
||||
func (_q *AuthIdentityChannelQuery) 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 !authidentitychannel.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 *AuthIdentityChannelQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*AuthIdentityChannel, error) {
|
||||
var (
|
||||
nodes = []*AuthIdentityChannel{}
|
||||
_spec = _q.querySpec()
|
||||
loadedTypes = [1]bool{
|
||||
_q.withIdentity != nil,
|
||||
}
|
||||
)
|
||||
_spec.ScanValues = func(columns []string) ([]any, error) {
|
||||
return (*AuthIdentityChannel).scanValues(nil, columns)
|
||||
}
|
||||
_spec.Assign = func(columns []string, values []any) error {
|
||||
node := &AuthIdentityChannel{config: _q.config}
|
||||
nodes = append(nodes, node)
|
||||
node.Edges.loadedTypes = loadedTypes
|
||||
return node.assignValues(columns, values)
|
||||
}
|
||||
if len(_q.modifiers) > 0 {
|
||||
_spec.Modifiers = _q.modifiers
|
||||
}
|
||||
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.withIdentity; query != nil {
|
||||
if err := _q.loadIdentity(ctx, query, nodes, nil,
|
||||
func(n *AuthIdentityChannel, e *AuthIdentity) { n.Edges.Identity = e }); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
func (_q *AuthIdentityChannelQuery) loadIdentity(ctx context.Context, query *AuthIdentityQuery, nodes []*AuthIdentityChannel, init func(*AuthIdentityChannel), assign func(*AuthIdentityChannel, *AuthIdentity)) error {
|
||||
ids := make([]int64, 0, len(nodes))
|
||||
nodeids := make(map[int64][]*AuthIdentityChannel)
|
||||
for i := range nodes {
|
||||
fk := nodes[i].IdentityID
|
||||
if _, ok := nodeids[fk]; !ok {
|
||||
ids = append(ids, fk)
|
||||
}
|
||||
nodeids[fk] = append(nodeids[fk], nodes[i])
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
query.Where(authidentity.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 "identity_id" returned %v`, n.ID)
|
||||
}
|
||||
for i := range nodes {
|
||||
assign(nodes[i], n)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_q *AuthIdentityChannelQuery) sqlCount(ctx context.Context) (int, error) {
|
||||
_spec := _q.querySpec()
|
||||
if len(_q.modifiers) > 0 {
|
||||
_spec.Modifiers = _q.modifiers
|
||||
}
|
||||
_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 *AuthIdentityChannelQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
_spec := sqlgraph.NewQuerySpec(authidentitychannel.Table, authidentitychannel.Columns, sqlgraph.NewFieldSpec(authidentitychannel.FieldID, field.TypeInt64))
|
||||
_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, authidentitychannel.FieldID)
|
||||
for i := range fields {
|
||||
if fields[i] != authidentitychannel.FieldID {
|
||||
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
|
||||
}
|
||||
}
|
||||
if _q.withIdentity != nil {
|
||||
_spec.Node.AddColumnOnce(authidentitychannel.FieldIdentityID)
|
||||
}
|
||||
}
|
||||
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 *AuthIdentityChannelQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
builder := sql.Dialect(_q.driver.Dialect())
|
||||
t1 := builder.Table(authidentitychannel.Table)
|
||||
columns := _q.ctx.Fields
|
||||
if len(columns) == 0 {
|
||||
columns = authidentitychannel.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 _, m := range _q.modifiers {
|
||||
m(selector)
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
|
||||
// updated, deleted or "selected ... for update" by other sessions, until the transaction is
|
||||
// either committed or rolled-back.
|
||||
func (_q *AuthIdentityChannelQuery) ForUpdate(opts ...sql.LockOption) *AuthIdentityChannelQuery {
|
||||
if _q.driver.Dialect() == dialect.Postgres {
|
||||
_q.Unique(false)
|
||||
}
|
||||
_q.modifiers = append(_q.modifiers, func(s *sql.Selector) {
|
||||
s.ForUpdate(opts...)
|
||||
})
|
||||
return _q
|
||||
}
|
||||
|
||||
// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
|
||||
// on any rows that are read. Other sessions can read the rows, but cannot modify them
|
||||
// until your transaction commits.
|
||||
func (_q *AuthIdentityChannelQuery) ForShare(opts ...sql.LockOption) *AuthIdentityChannelQuery {
|
||||
if _q.driver.Dialect() == dialect.Postgres {
|
||||
_q.Unique(false)
|
||||
}
|
||||
_q.modifiers = append(_q.modifiers, func(s *sql.Selector) {
|
||||
s.ForShare(opts...)
|
||||
})
|
||||
return _q
|
||||
}
|
||||
|
||||
// AuthIdentityChannelGroupBy is the group-by builder for AuthIdentityChannel entities.
|
||||
type AuthIdentityChannelGroupBy struct {
|
||||
selector
|
||||
build *AuthIdentityChannelQuery
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the group-by query.
|
||||
func (_g *AuthIdentityChannelGroupBy) Aggregate(fns ...AggregateFunc) *AuthIdentityChannelGroupBy {
|
||||
_g.fns = append(_g.fns, fns...)
|
||||
return _g
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_g *AuthIdentityChannelGroupBy) 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[*AuthIdentityChannelQuery, *AuthIdentityChannelGroupBy](ctx, _g.build, _g, _g.build.inters, v)
|
||||
}
|
||||
|
||||
func (_g *AuthIdentityChannelGroupBy) sqlScan(ctx context.Context, root *AuthIdentityChannelQuery, 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)
|
||||
}
|
||||
|
||||
// AuthIdentityChannelSelect is the builder for selecting fields of AuthIdentityChannel entities.
|
||||
type AuthIdentityChannelSelect struct {
|
||||
*AuthIdentityChannelQuery
|
||||
selector
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the selector query.
|
||||
func (_s *AuthIdentityChannelSelect) Aggregate(fns ...AggregateFunc) *AuthIdentityChannelSelect {
|
||||
_s.fns = append(_s.fns, fns...)
|
||||
return _s
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_s *AuthIdentityChannelSelect) 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[*AuthIdentityChannelQuery, *AuthIdentityChannelSelect](ctx, _s.AuthIdentityChannelQuery, _s, _s.inters, v)
|
||||
}
|
||||
|
||||
func (_s *AuthIdentityChannelSelect) sqlScan(ctx context.Context, root *AuthIdentityChannelQuery, 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)
|
||||
}
|
||||
@@ -1,581 +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"
|
||||
"github.com/Wei-Shaw/sub2api/ent/authidentity"
|
||||
"github.com/Wei-Shaw/sub2api/ent/authidentitychannel"
|
||||
"github.com/Wei-Shaw/sub2api/ent/predicate"
|
||||
)
|
||||
|
||||
// AuthIdentityChannelUpdate is the builder for updating AuthIdentityChannel entities.
|
||||
type AuthIdentityChannelUpdate struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *AuthIdentityChannelMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the AuthIdentityChannelUpdate builder.
|
||||
func (_u *AuthIdentityChannelUpdate) Where(ps ...predicate.AuthIdentityChannel) *AuthIdentityChannelUpdate {
|
||||
_u.mutation.Where(ps...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetUpdatedAt sets the "updated_at" field.
|
||||
func (_u *AuthIdentityChannelUpdate) SetUpdatedAt(v time.Time) *AuthIdentityChannelUpdate {
|
||||
_u.mutation.SetUpdatedAt(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetIdentityID sets the "identity_id" field.
|
||||
func (_u *AuthIdentityChannelUpdate) SetIdentityID(v int64) *AuthIdentityChannelUpdate {
|
||||
_u.mutation.SetIdentityID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableIdentityID sets the "identity_id" field if the given value is not nil.
|
||||
func (_u *AuthIdentityChannelUpdate) SetNillableIdentityID(v *int64) *AuthIdentityChannelUpdate {
|
||||
if v != nil {
|
||||
_u.SetIdentityID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetProviderType sets the "provider_type" field.
|
||||
func (_u *AuthIdentityChannelUpdate) SetProviderType(v string) *AuthIdentityChannelUpdate {
|
||||
_u.mutation.SetProviderType(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableProviderType sets the "provider_type" field if the given value is not nil.
|
||||
func (_u *AuthIdentityChannelUpdate) SetNillableProviderType(v *string) *AuthIdentityChannelUpdate {
|
||||
if v != nil {
|
||||
_u.SetProviderType(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetProviderKey sets the "provider_key" field.
|
||||
func (_u *AuthIdentityChannelUpdate) SetProviderKey(v string) *AuthIdentityChannelUpdate {
|
||||
_u.mutation.SetProviderKey(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableProviderKey sets the "provider_key" field if the given value is not nil.
|
||||
func (_u *AuthIdentityChannelUpdate) SetNillableProviderKey(v *string) *AuthIdentityChannelUpdate {
|
||||
if v != nil {
|
||||
_u.SetProviderKey(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetChannel sets the "channel" field.
|
||||
func (_u *AuthIdentityChannelUpdate) SetChannel(v string) *AuthIdentityChannelUpdate {
|
||||
_u.mutation.SetChannel(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableChannel sets the "channel" field if the given value is not nil.
|
||||
func (_u *AuthIdentityChannelUpdate) SetNillableChannel(v *string) *AuthIdentityChannelUpdate {
|
||||
if v != nil {
|
||||
_u.SetChannel(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetChannelAppID sets the "channel_app_id" field.
|
||||
func (_u *AuthIdentityChannelUpdate) SetChannelAppID(v string) *AuthIdentityChannelUpdate {
|
||||
_u.mutation.SetChannelAppID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableChannelAppID sets the "channel_app_id" field if the given value is not nil.
|
||||
func (_u *AuthIdentityChannelUpdate) SetNillableChannelAppID(v *string) *AuthIdentityChannelUpdate {
|
||||
if v != nil {
|
||||
_u.SetChannelAppID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetChannelSubject sets the "channel_subject" field.
|
||||
func (_u *AuthIdentityChannelUpdate) SetChannelSubject(v string) *AuthIdentityChannelUpdate {
|
||||
_u.mutation.SetChannelSubject(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableChannelSubject sets the "channel_subject" field if the given value is not nil.
|
||||
func (_u *AuthIdentityChannelUpdate) SetNillableChannelSubject(v *string) *AuthIdentityChannelUpdate {
|
||||
if v != nil {
|
||||
_u.SetChannelSubject(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetMetadata sets the "metadata" field.
|
||||
func (_u *AuthIdentityChannelUpdate) SetMetadata(v map[string]interface{}) *AuthIdentityChannelUpdate {
|
||||
_u.mutation.SetMetadata(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetIdentity sets the "identity" edge to the AuthIdentity entity.
|
||||
func (_u *AuthIdentityChannelUpdate) SetIdentity(v *AuthIdentity) *AuthIdentityChannelUpdate {
|
||||
return _u.SetIdentityID(v.ID)
|
||||
}
|
||||
|
||||
// Mutation returns the AuthIdentityChannelMutation object of the builder.
|
||||
func (_u *AuthIdentityChannelUpdate) Mutation() *AuthIdentityChannelMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// ClearIdentity clears the "identity" edge to the AuthIdentity entity.
|
||||
func (_u *AuthIdentityChannelUpdate) ClearIdentity() *AuthIdentityChannelUpdate {
|
||||
_u.mutation.ClearIdentity()
|
||||
return _u
|
||||
}
|
||||
|
||||
// Save executes the query and returns the number of nodes affected by the update operation.
|
||||
func (_u *AuthIdentityChannelUpdate) 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 *AuthIdentityChannelUpdate) SaveX(ctx context.Context) int {
|
||||
affected, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return affected
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_u *AuthIdentityChannelUpdate) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *AuthIdentityChannelUpdate) 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 *AuthIdentityChannelUpdate) defaults() {
|
||||
if _, ok := _u.mutation.UpdatedAt(); !ok {
|
||||
v := authidentitychannel.UpdateDefaultUpdatedAt()
|
||||
_u.mutation.SetUpdatedAt(v)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_u *AuthIdentityChannelUpdate) check() error {
|
||||
if v, ok := _u.mutation.ProviderType(); ok {
|
||||
if err := authidentitychannel.ProviderTypeValidator(v); err != nil {
|
||||
return &ValidationError{Name: "provider_type", err: fmt.Errorf(`ent: validator failed for field "AuthIdentityChannel.provider_type": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.ProviderKey(); ok {
|
||||
if err := authidentitychannel.ProviderKeyValidator(v); err != nil {
|
||||
return &ValidationError{Name: "provider_key", err: fmt.Errorf(`ent: validator failed for field "AuthIdentityChannel.provider_key": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.Channel(); ok {
|
||||
if err := authidentitychannel.ChannelValidator(v); err != nil {
|
||||
return &ValidationError{Name: "channel", err: fmt.Errorf(`ent: validator failed for field "AuthIdentityChannel.channel": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.ChannelAppID(); ok {
|
||||
if err := authidentitychannel.ChannelAppIDValidator(v); err != nil {
|
||||
return &ValidationError{Name: "channel_app_id", err: fmt.Errorf(`ent: validator failed for field "AuthIdentityChannel.channel_app_id": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.ChannelSubject(); ok {
|
||||
if err := authidentitychannel.ChannelSubjectValidator(v); err != nil {
|
||||
return &ValidationError{Name: "channel_subject", err: fmt.Errorf(`ent: validator failed for field "AuthIdentityChannel.channel_subject": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _u.mutation.IdentityCleared() && len(_u.mutation.IdentityIDs()) > 0 {
|
||||
return errors.New(`ent: clearing a required unique edge "AuthIdentityChannel.identity"`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_u *AuthIdentityChannelUpdate) sqlSave(ctx context.Context) (_node int, err error) {
|
||||
if err := _u.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := sqlgraph.NewUpdateSpec(authidentitychannel.Table, authidentitychannel.Columns, sqlgraph.NewFieldSpec(authidentitychannel.FieldID, field.TypeInt64))
|
||||
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.UpdatedAt(); ok {
|
||||
_spec.SetField(authidentitychannel.FieldUpdatedAt, field.TypeTime, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ProviderType(); ok {
|
||||
_spec.SetField(authidentitychannel.FieldProviderType, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ProviderKey(); ok {
|
||||
_spec.SetField(authidentitychannel.FieldProviderKey, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.Channel(); ok {
|
||||
_spec.SetField(authidentitychannel.FieldChannel, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ChannelAppID(); ok {
|
||||
_spec.SetField(authidentitychannel.FieldChannelAppID, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ChannelSubject(); ok {
|
||||
_spec.SetField(authidentitychannel.FieldChannelSubject, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.Metadata(); ok {
|
||||
_spec.SetField(authidentitychannel.FieldMetadata, field.TypeJSON, value)
|
||||
}
|
||||
if _u.mutation.IdentityCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: authidentitychannel.IdentityTable,
|
||||
Columns: []string{authidentitychannel.IdentityColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(authidentity.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.IdentityIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: authidentitychannel.IdentityTable,
|
||||
Columns: []string{authidentitychannel.IdentityColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(authidentity.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
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{authidentitychannel.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
// AuthIdentityChannelUpdateOne is the builder for updating a single AuthIdentityChannel entity.
|
||||
type AuthIdentityChannelUpdateOne struct {
|
||||
config
|
||||
fields []string
|
||||
hooks []Hook
|
||||
mutation *AuthIdentityChannelMutation
|
||||
}
|
||||
|
||||
// SetUpdatedAt sets the "updated_at" field.
|
||||
func (_u *AuthIdentityChannelUpdateOne) SetUpdatedAt(v time.Time) *AuthIdentityChannelUpdateOne {
|
||||
_u.mutation.SetUpdatedAt(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetIdentityID sets the "identity_id" field.
|
||||
func (_u *AuthIdentityChannelUpdateOne) SetIdentityID(v int64) *AuthIdentityChannelUpdateOne {
|
||||
_u.mutation.SetIdentityID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableIdentityID sets the "identity_id" field if the given value is not nil.
|
||||
func (_u *AuthIdentityChannelUpdateOne) SetNillableIdentityID(v *int64) *AuthIdentityChannelUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetIdentityID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetProviderType sets the "provider_type" field.
|
||||
func (_u *AuthIdentityChannelUpdateOne) SetProviderType(v string) *AuthIdentityChannelUpdateOne {
|
||||
_u.mutation.SetProviderType(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableProviderType sets the "provider_type" field if the given value is not nil.
|
||||
func (_u *AuthIdentityChannelUpdateOne) SetNillableProviderType(v *string) *AuthIdentityChannelUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetProviderType(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetProviderKey sets the "provider_key" field.
|
||||
func (_u *AuthIdentityChannelUpdateOne) SetProviderKey(v string) *AuthIdentityChannelUpdateOne {
|
||||
_u.mutation.SetProviderKey(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableProviderKey sets the "provider_key" field if the given value is not nil.
|
||||
func (_u *AuthIdentityChannelUpdateOne) SetNillableProviderKey(v *string) *AuthIdentityChannelUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetProviderKey(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetChannel sets the "channel" field.
|
||||
func (_u *AuthIdentityChannelUpdateOne) SetChannel(v string) *AuthIdentityChannelUpdateOne {
|
||||
_u.mutation.SetChannel(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableChannel sets the "channel" field if the given value is not nil.
|
||||
func (_u *AuthIdentityChannelUpdateOne) SetNillableChannel(v *string) *AuthIdentityChannelUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetChannel(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetChannelAppID sets the "channel_app_id" field.
|
||||
func (_u *AuthIdentityChannelUpdateOne) SetChannelAppID(v string) *AuthIdentityChannelUpdateOne {
|
||||
_u.mutation.SetChannelAppID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableChannelAppID sets the "channel_app_id" field if the given value is not nil.
|
||||
func (_u *AuthIdentityChannelUpdateOne) SetNillableChannelAppID(v *string) *AuthIdentityChannelUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetChannelAppID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetChannelSubject sets the "channel_subject" field.
|
||||
func (_u *AuthIdentityChannelUpdateOne) SetChannelSubject(v string) *AuthIdentityChannelUpdateOne {
|
||||
_u.mutation.SetChannelSubject(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableChannelSubject sets the "channel_subject" field if the given value is not nil.
|
||||
func (_u *AuthIdentityChannelUpdateOne) SetNillableChannelSubject(v *string) *AuthIdentityChannelUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetChannelSubject(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetMetadata sets the "metadata" field.
|
||||
func (_u *AuthIdentityChannelUpdateOne) SetMetadata(v map[string]interface{}) *AuthIdentityChannelUpdateOne {
|
||||
_u.mutation.SetMetadata(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetIdentity sets the "identity" edge to the AuthIdentity entity.
|
||||
func (_u *AuthIdentityChannelUpdateOne) SetIdentity(v *AuthIdentity) *AuthIdentityChannelUpdateOne {
|
||||
return _u.SetIdentityID(v.ID)
|
||||
}
|
||||
|
||||
// Mutation returns the AuthIdentityChannelMutation object of the builder.
|
||||
func (_u *AuthIdentityChannelUpdateOne) Mutation() *AuthIdentityChannelMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// ClearIdentity clears the "identity" edge to the AuthIdentity entity.
|
||||
func (_u *AuthIdentityChannelUpdateOne) ClearIdentity() *AuthIdentityChannelUpdateOne {
|
||||
_u.mutation.ClearIdentity()
|
||||
return _u
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the AuthIdentityChannelUpdate builder.
|
||||
func (_u *AuthIdentityChannelUpdateOne) Where(ps ...predicate.AuthIdentityChannel) *AuthIdentityChannelUpdateOne {
|
||||
_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 *AuthIdentityChannelUpdateOne) Select(field string, fields ...string) *AuthIdentityChannelUpdateOne {
|
||||
_u.fields = append([]string{field}, fields...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// Save executes the query and returns the updated AuthIdentityChannel entity.
|
||||
func (_u *AuthIdentityChannelUpdateOne) Save(ctx context.Context) (*AuthIdentityChannel, error) {
|
||||
_u.defaults()
|
||||
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_u *AuthIdentityChannelUpdateOne) SaveX(ctx context.Context) *AuthIdentityChannel {
|
||||
node, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// Exec executes the query on the entity.
|
||||
func (_u *AuthIdentityChannelUpdateOne) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *AuthIdentityChannelUpdateOne) 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 *AuthIdentityChannelUpdateOne) defaults() {
|
||||
if _, ok := _u.mutation.UpdatedAt(); !ok {
|
||||
v := authidentitychannel.UpdateDefaultUpdatedAt()
|
||||
_u.mutation.SetUpdatedAt(v)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_u *AuthIdentityChannelUpdateOne) check() error {
|
||||
if v, ok := _u.mutation.ProviderType(); ok {
|
||||
if err := authidentitychannel.ProviderTypeValidator(v); err != nil {
|
||||
return &ValidationError{Name: "provider_type", err: fmt.Errorf(`ent: validator failed for field "AuthIdentityChannel.provider_type": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.ProviderKey(); ok {
|
||||
if err := authidentitychannel.ProviderKeyValidator(v); err != nil {
|
||||
return &ValidationError{Name: "provider_key", err: fmt.Errorf(`ent: validator failed for field "AuthIdentityChannel.provider_key": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.Channel(); ok {
|
||||
if err := authidentitychannel.ChannelValidator(v); err != nil {
|
||||
return &ValidationError{Name: "channel", err: fmt.Errorf(`ent: validator failed for field "AuthIdentityChannel.channel": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.ChannelAppID(); ok {
|
||||
if err := authidentitychannel.ChannelAppIDValidator(v); err != nil {
|
||||
return &ValidationError{Name: "channel_app_id", err: fmt.Errorf(`ent: validator failed for field "AuthIdentityChannel.channel_app_id": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.ChannelSubject(); ok {
|
||||
if err := authidentitychannel.ChannelSubjectValidator(v); err != nil {
|
||||
return &ValidationError{Name: "channel_subject", err: fmt.Errorf(`ent: validator failed for field "AuthIdentityChannel.channel_subject": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _u.mutation.IdentityCleared() && len(_u.mutation.IdentityIDs()) > 0 {
|
||||
return errors.New(`ent: clearing a required unique edge "AuthIdentityChannel.identity"`)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_u *AuthIdentityChannelUpdateOne) sqlSave(ctx context.Context) (_node *AuthIdentityChannel, err error) {
|
||||
if err := _u.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := sqlgraph.NewUpdateSpec(authidentitychannel.Table, authidentitychannel.Columns, sqlgraph.NewFieldSpec(authidentitychannel.FieldID, field.TypeInt64))
|
||||
id, ok := _u.mutation.ID()
|
||||
if !ok {
|
||||
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "AuthIdentityChannel.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, authidentitychannel.FieldID)
|
||||
for _, f := range fields {
|
||||
if !authidentitychannel.ValidColumn(f) {
|
||||
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
if f != authidentitychannel.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.UpdatedAt(); ok {
|
||||
_spec.SetField(authidentitychannel.FieldUpdatedAt, field.TypeTime, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ProviderType(); ok {
|
||||
_spec.SetField(authidentitychannel.FieldProviderType, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ProviderKey(); ok {
|
||||
_spec.SetField(authidentitychannel.FieldProviderKey, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.Channel(); ok {
|
||||
_spec.SetField(authidentitychannel.FieldChannel, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ChannelAppID(); ok {
|
||||
_spec.SetField(authidentitychannel.FieldChannelAppID, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.ChannelSubject(); ok {
|
||||
_spec.SetField(authidentitychannel.FieldChannelSubject, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.Metadata(); ok {
|
||||
_spec.SetField(authidentitychannel.FieldMetadata, field.TypeJSON, value)
|
||||
}
|
||||
if _u.mutation.IdentityCleared() {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: authidentitychannel.IdentityTable,
|
||||
Columns: []string{authidentitychannel.IdentityColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(authidentity.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
|
||||
}
|
||||
if nodes := _u.mutation.IdentityIDs(); len(nodes) > 0 {
|
||||
edge := &sqlgraph.EdgeSpec{
|
||||
Rel: sqlgraph.M2O,
|
||||
Inverse: true,
|
||||
Table: authidentitychannel.IdentityTable,
|
||||
Columns: []string{authidentitychannel.IdentityColumn},
|
||||
Bidi: false,
|
||||
Target: &sqlgraph.EdgeTarget{
|
||||
IDSpec: sqlgraph.NewFieldSpec(authidentity.FieldID, field.TypeInt64),
|
||||
},
|
||||
}
|
||||
for _, k := range nodes {
|
||||
edge.Target.Nodes = append(edge.Target.Nodes, k)
|
||||
}
|
||||
_spec.Edges.Add = append(_spec.Edges.Add, edge)
|
||||
}
|
||||
_node = &AuthIdentityChannel{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{authidentitychannel.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
@@ -1,158 +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"
|
||||
"github.com/Wei-Shaw/sub2api/ent/batchimageevent"
|
||||
)
|
||||
|
||||
// BatchImageEvent is the model entity for the BatchImageEvent schema.
|
||||
type BatchImageEvent struct {
|
||||
config `json:"-"`
|
||||
// ID of the ent.
|
||||
ID int64 `json:"id,omitempty"`
|
||||
// JobID holds the value of the "job_id" field.
|
||||
JobID string `json:"job_id,omitempty"`
|
||||
// EventType holds the value of the "event_type" field.
|
||||
EventType string `json:"event_type,omitempty"`
|
||||
// Payload holds the value of the "payload" field.
|
||||
Payload map[string]interface{} `json:"payload,omitempty"`
|
||||
// EventHash holds the value of the "event_hash" field.
|
||||
EventHash *string `json:"event_hash,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 (*BatchImageEvent) scanValues(columns []string) ([]any, error) {
|
||||
values := make([]any, len(columns))
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case batchimageevent.FieldPayload:
|
||||
values[i] = new([]byte)
|
||||
case batchimageevent.FieldID:
|
||||
values[i] = new(sql.NullInt64)
|
||||
case batchimageevent.FieldJobID, batchimageevent.FieldEventType, batchimageevent.FieldEventHash:
|
||||
values[i] = new(sql.NullString)
|
||||
case batchimageevent.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 BatchImageEvent fields.
|
||||
func (_m *BatchImageEvent) 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 batchimageevent.FieldID:
|
||||
value, ok := values[i].(*sql.NullInt64)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field id", value)
|
||||
}
|
||||
_m.ID = int64(value.Int64)
|
||||
case batchimageevent.FieldJobID:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field job_id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.JobID = value.String
|
||||
}
|
||||
case batchimageevent.FieldEventType:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field event_type", values[i])
|
||||
} else if value.Valid {
|
||||
_m.EventType = value.String
|
||||
}
|
||||
case batchimageevent.FieldPayload:
|
||||
if value, ok := values[i].(*[]byte); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field payload", values[i])
|
||||
} else if value != nil && len(*value) > 0 {
|
||||
if err := json.Unmarshal(*value, &_m.Payload); err != nil {
|
||||
return fmt.Errorf("unmarshal field payload: %w", err)
|
||||
}
|
||||
}
|
||||
case batchimageevent.FieldEventHash:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field event_hash", values[i])
|
||||
} else if value.Valid {
|
||||
_m.EventHash = new(string)
|
||||
*_m.EventHash = value.String
|
||||
}
|
||||
case batchimageevent.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 BatchImageEvent.
|
||||
// This includes values selected through modifiers, order, etc.
|
||||
func (_m *BatchImageEvent) Value(name string) (ent.Value, error) {
|
||||
return _m.selectValues.Get(name)
|
||||
}
|
||||
|
||||
// Update returns a builder for updating this BatchImageEvent.
|
||||
// Note that you need to call BatchImageEvent.Unwrap() before calling this method if this BatchImageEvent
|
||||
// was returned from a transaction, and the transaction was committed or rolled back.
|
||||
func (_m *BatchImageEvent) Update() *BatchImageEventUpdateOne {
|
||||
return NewBatchImageEventClient(_m.config).UpdateOne(_m)
|
||||
}
|
||||
|
||||
// Unwrap unwraps the BatchImageEvent 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 *BatchImageEvent) Unwrap() *BatchImageEvent {
|
||||
_tx, ok := _m.config.driver.(*txDriver)
|
||||
if !ok {
|
||||
panic("ent: BatchImageEvent is not a transactional entity")
|
||||
}
|
||||
_m.config.driver = _tx.drv
|
||||
return _m
|
||||
}
|
||||
|
||||
// String implements the fmt.Stringer.
|
||||
func (_m *BatchImageEvent) String() string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString("BatchImageEvent(")
|
||||
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
|
||||
builder.WriteString("job_id=")
|
||||
builder.WriteString(_m.JobID)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("event_type=")
|
||||
builder.WriteString(_m.EventType)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("payload=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.Payload))
|
||||
builder.WriteString(", ")
|
||||
if v := _m.EventHash; v != nil {
|
||||
builder.WriteString("event_hash=")
|
||||
builder.WriteString(*v)
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("created_at=")
|
||||
builder.WriteString(_m.CreatedAt.Format(time.ANSIC))
|
||||
builder.WriteByte(')')
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// BatchImageEvents is a parsable slice of BatchImageEvent.
|
||||
type BatchImageEvents []*BatchImageEvent
|
||||
@@ -1,87 +0,0 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package batchimageevent
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
)
|
||||
|
||||
const (
|
||||
// Label holds the string label denoting the batchimageevent type in the database.
|
||||
Label = "batch_image_event"
|
||||
// FieldID holds the string denoting the id field in the database.
|
||||
FieldID = "id"
|
||||
// FieldJobID holds the string denoting the job_id field in the database.
|
||||
FieldJobID = "job_id"
|
||||
// FieldEventType holds the string denoting the event_type field in the database.
|
||||
FieldEventType = "event_type"
|
||||
// FieldPayload holds the string denoting the payload field in the database.
|
||||
FieldPayload = "payload"
|
||||
// FieldEventHash holds the string denoting the event_hash field in the database.
|
||||
FieldEventHash = "event_hash"
|
||||
// FieldCreatedAt holds the string denoting the created_at field in the database.
|
||||
FieldCreatedAt = "created_at"
|
||||
// Table holds the table name of the batchimageevent in the database.
|
||||
Table = "batch_image_events"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns for batchimageevent fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldJobID,
|
||||
FieldEventType,
|
||||
FieldPayload,
|
||||
FieldEventHash,
|
||||
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 (
|
||||
// JobIDValidator is a validator for the "job_id" field. It is called by the builders before save.
|
||||
JobIDValidator func(string) error
|
||||
// EventTypeValidator is a validator for the "event_type" field. It is called by the builders before save.
|
||||
EventTypeValidator func(string) error
|
||||
// EventHashValidator is a validator for the "event_hash" field. It is called by the builders before save.
|
||||
EventHashValidator 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 BatchImageEvent 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()
|
||||
}
|
||||
|
||||
// ByJobID orders the results by the job_id field.
|
||||
func ByJobID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldJobID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByEventType orders the results by the event_type field.
|
||||
func ByEventType(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldEventType, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByEventHash orders the results by the event_hash field.
|
||||
func ByEventHash(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldEventHash, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByCreatedAt orders the results by the created_at field.
|
||||
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
|
||||
}
|
||||
@@ -1,345 +0,0 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package batchimageevent
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"github.com/Wei-Shaw/sub2api/ent/predicate"
|
||||
)
|
||||
|
||||
// ID filters vertices based on their ID field.
|
||||
func ID(id int64) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDEQ applies the EQ predicate on the ID field.
|
||||
func IDEQ(id int64) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDNEQ applies the NEQ predicate on the ID field.
|
||||
func IDNEQ(id int64) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldNEQ(FieldID, id))
|
||||
}
|
||||
|
||||
// IDIn applies the In predicate on the ID field.
|
||||
func IDIn(ids ...int64) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDNotIn applies the NotIn predicate on the ID field.
|
||||
func IDNotIn(ids ...int64) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldNotIn(FieldID, ids...))
|
||||
}
|
||||
|
||||
// IDGT applies the GT predicate on the ID field.
|
||||
func IDGT(id int64) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldGT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDGTE applies the GTE predicate on the ID field.
|
||||
func IDGTE(id int64) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldGTE(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLT applies the LT predicate on the ID field.
|
||||
func IDLT(id int64) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldLT(FieldID, id))
|
||||
}
|
||||
|
||||
// IDLTE applies the LTE predicate on the ID field.
|
||||
func IDLTE(id int64) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldLTE(FieldID, id))
|
||||
}
|
||||
|
||||
// JobID applies equality check predicate on the "job_id" field. It's identical to JobIDEQ.
|
||||
func JobID(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldEQ(FieldJobID, v))
|
||||
}
|
||||
|
||||
// EventType applies equality check predicate on the "event_type" field. It's identical to EventTypeEQ.
|
||||
func EventType(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldEQ(FieldEventType, v))
|
||||
}
|
||||
|
||||
// EventHash applies equality check predicate on the "event_hash" field. It's identical to EventHashEQ.
|
||||
func EventHash(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldEQ(FieldEventHash, v))
|
||||
}
|
||||
|
||||
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
|
||||
func CreatedAt(v time.Time) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldEQ(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// JobIDEQ applies the EQ predicate on the "job_id" field.
|
||||
func JobIDEQ(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldEQ(FieldJobID, v))
|
||||
}
|
||||
|
||||
// JobIDNEQ applies the NEQ predicate on the "job_id" field.
|
||||
func JobIDNEQ(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldNEQ(FieldJobID, v))
|
||||
}
|
||||
|
||||
// JobIDIn applies the In predicate on the "job_id" field.
|
||||
func JobIDIn(vs ...string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldIn(FieldJobID, vs...))
|
||||
}
|
||||
|
||||
// JobIDNotIn applies the NotIn predicate on the "job_id" field.
|
||||
func JobIDNotIn(vs ...string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldNotIn(FieldJobID, vs...))
|
||||
}
|
||||
|
||||
// JobIDGT applies the GT predicate on the "job_id" field.
|
||||
func JobIDGT(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldGT(FieldJobID, v))
|
||||
}
|
||||
|
||||
// JobIDGTE applies the GTE predicate on the "job_id" field.
|
||||
func JobIDGTE(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldGTE(FieldJobID, v))
|
||||
}
|
||||
|
||||
// JobIDLT applies the LT predicate on the "job_id" field.
|
||||
func JobIDLT(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldLT(FieldJobID, v))
|
||||
}
|
||||
|
||||
// JobIDLTE applies the LTE predicate on the "job_id" field.
|
||||
func JobIDLTE(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldLTE(FieldJobID, v))
|
||||
}
|
||||
|
||||
// JobIDContains applies the Contains predicate on the "job_id" field.
|
||||
func JobIDContains(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldContains(FieldJobID, v))
|
||||
}
|
||||
|
||||
// JobIDHasPrefix applies the HasPrefix predicate on the "job_id" field.
|
||||
func JobIDHasPrefix(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldHasPrefix(FieldJobID, v))
|
||||
}
|
||||
|
||||
// JobIDHasSuffix applies the HasSuffix predicate on the "job_id" field.
|
||||
func JobIDHasSuffix(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldHasSuffix(FieldJobID, v))
|
||||
}
|
||||
|
||||
// JobIDEqualFold applies the EqualFold predicate on the "job_id" field.
|
||||
func JobIDEqualFold(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldEqualFold(FieldJobID, v))
|
||||
}
|
||||
|
||||
// JobIDContainsFold applies the ContainsFold predicate on the "job_id" field.
|
||||
func JobIDContainsFold(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldContainsFold(FieldJobID, v))
|
||||
}
|
||||
|
||||
// EventTypeEQ applies the EQ predicate on the "event_type" field.
|
||||
func EventTypeEQ(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldEQ(FieldEventType, v))
|
||||
}
|
||||
|
||||
// EventTypeNEQ applies the NEQ predicate on the "event_type" field.
|
||||
func EventTypeNEQ(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldNEQ(FieldEventType, v))
|
||||
}
|
||||
|
||||
// EventTypeIn applies the In predicate on the "event_type" field.
|
||||
func EventTypeIn(vs ...string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldIn(FieldEventType, vs...))
|
||||
}
|
||||
|
||||
// EventTypeNotIn applies the NotIn predicate on the "event_type" field.
|
||||
func EventTypeNotIn(vs ...string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldNotIn(FieldEventType, vs...))
|
||||
}
|
||||
|
||||
// EventTypeGT applies the GT predicate on the "event_type" field.
|
||||
func EventTypeGT(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldGT(FieldEventType, v))
|
||||
}
|
||||
|
||||
// EventTypeGTE applies the GTE predicate on the "event_type" field.
|
||||
func EventTypeGTE(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldGTE(FieldEventType, v))
|
||||
}
|
||||
|
||||
// EventTypeLT applies the LT predicate on the "event_type" field.
|
||||
func EventTypeLT(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldLT(FieldEventType, v))
|
||||
}
|
||||
|
||||
// EventTypeLTE applies the LTE predicate on the "event_type" field.
|
||||
func EventTypeLTE(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldLTE(FieldEventType, v))
|
||||
}
|
||||
|
||||
// EventTypeContains applies the Contains predicate on the "event_type" field.
|
||||
func EventTypeContains(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldContains(FieldEventType, v))
|
||||
}
|
||||
|
||||
// EventTypeHasPrefix applies the HasPrefix predicate on the "event_type" field.
|
||||
func EventTypeHasPrefix(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldHasPrefix(FieldEventType, v))
|
||||
}
|
||||
|
||||
// EventTypeHasSuffix applies the HasSuffix predicate on the "event_type" field.
|
||||
func EventTypeHasSuffix(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldHasSuffix(FieldEventType, v))
|
||||
}
|
||||
|
||||
// EventTypeEqualFold applies the EqualFold predicate on the "event_type" field.
|
||||
func EventTypeEqualFold(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldEqualFold(FieldEventType, v))
|
||||
}
|
||||
|
||||
// EventTypeContainsFold applies the ContainsFold predicate on the "event_type" field.
|
||||
func EventTypeContainsFold(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldContainsFold(FieldEventType, v))
|
||||
}
|
||||
|
||||
// PayloadIsNil applies the IsNil predicate on the "payload" field.
|
||||
func PayloadIsNil() predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldIsNull(FieldPayload))
|
||||
}
|
||||
|
||||
// PayloadNotNil applies the NotNil predicate on the "payload" field.
|
||||
func PayloadNotNil() predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldNotNull(FieldPayload))
|
||||
}
|
||||
|
||||
// EventHashEQ applies the EQ predicate on the "event_hash" field.
|
||||
func EventHashEQ(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldEQ(FieldEventHash, v))
|
||||
}
|
||||
|
||||
// EventHashNEQ applies the NEQ predicate on the "event_hash" field.
|
||||
func EventHashNEQ(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldNEQ(FieldEventHash, v))
|
||||
}
|
||||
|
||||
// EventHashIn applies the In predicate on the "event_hash" field.
|
||||
func EventHashIn(vs ...string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldIn(FieldEventHash, vs...))
|
||||
}
|
||||
|
||||
// EventHashNotIn applies the NotIn predicate on the "event_hash" field.
|
||||
func EventHashNotIn(vs ...string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldNotIn(FieldEventHash, vs...))
|
||||
}
|
||||
|
||||
// EventHashGT applies the GT predicate on the "event_hash" field.
|
||||
func EventHashGT(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldGT(FieldEventHash, v))
|
||||
}
|
||||
|
||||
// EventHashGTE applies the GTE predicate on the "event_hash" field.
|
||||
func EventHashGTE(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldGTE(FieldEventHash, v))
|
||||
}
|
||||
|
||||
// EventHashLT applies the LT predicate on the "event_hash" field.
|
||||
func EventHashLT(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldLT(FieldEventHash, v))
|
||||
}
|
||||
|
||||
// EventHashLTE applies the LTE predicate on the "event_hash" field.
|
||||
func EventHashLTE(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldLTE(FieldEventHash, v))
|
||||
}
|
||||
|
||||
// EventHashContains applies the Contains predicate on the "event_hash" field.
|
||||
func EventHashContains(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldContains(FieldEventHash, v))
|
||||
}
|
||||
|
||||
// EventHashHasPrefix applies the HasPrefix predicate on the "event_hash" field.
|
||||
func EventHashHasPrefix(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldHasPrefix(FieldEventHash, v))
|
||||
}
|
||||
|
||||
// EventHashHasSuffix applies the HasSuffix predicate on the "event_hash" field.
|
||||
func EventHashHasSuffix(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldHasSuffix(FieldEventHash, v))
|
||||
}
|
||||
|
||||
// EventHashIsNil applies the IsNil predicate on the "event_hash" field.
|
||||
func EventHashIsNil() predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldIsNull(FieldEventHash))
|
||||
}
|
||||
|
||||
// EventHashNotNil applies the NotNil predicate on the "event_hash" field.
|
||||
func EventHashNotNil() predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldNotNull(FieldEventHash))
|
||||
}
|
||||
|
||||
// EventHashEqualFold applies the EqualFold predicate on the "event_hash" field.
|
||||
func EventHashEqualFold(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldEqualFold(FieldEventHash, v))
|
||||
}
|
||||
|
||||
// EventHashContainsFold applies the ContainsFold predicate on the "event_hash" field.
|
||||
func EventHashContainsFold(v string) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldContainsFold(FieldEventHash, v))
|
||||
}
|
||||
|
||||
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
|
||||
func CreatedAtEQ(v time.Time) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldEQ(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
|
||||
func CreatedAtNEQ(v time.Time) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldNEQ(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtIn applies the In predicate on the "created_at" field.
|
||||
func CreatedAtIn(vs ...time.Time) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldIn(FieldCreatedAt, vs...))
|
||||
}
|
||||
|
||||
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
|
||||
func CreatedAtNotIn(vs ...time.Time) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldNotIn(FieldCreatedAt, vs...))
|
||||
}
|
||||
|
||||
// CreatedAtGT applies the GT predicate on the "created_at" field.
|
||||
func CreatedAtGT(v time.Time) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldGT(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
|
||||
func CreatedAtGTE(v time.Time) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldGTE(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtLT applies the LT predicate on the "created_at" field.
|
||||
func CreatedAtLT(v time.Time) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldLT(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
|
||||
func CreatedAtLTE(v time.Time) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.FieldLTE(FieldCreatedAt, v))
|
||||
}
|
||||
|
||||
// And groups predicates with the AND operator between them.
|
||||
func And(predicates ...predicate.BatchImageEvent) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.AndPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Or groups predicates with the OR operator between them.
|
||||
func Or(predicates ...predicate.BatchImageEvent) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.OrPredicates(predicates...))
|
||||
}
|
||||
|
||||
// Not applies the not operator on the given predicate.
|
||||
func Not(p predicate.BatchImageEvent) predicate.BatchImageEvent {
|
||||
return predicate.BatchImageEvent(sql.NotPredicates(p))
|
||||
}
|
||||
@@ -1,714 +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"
|
||||
"github.com/Wei-Shaw/sub2api/ent/batchimageevent"
|
||||
)
|
||||
|
||||
// BatchImageEventCreate is the builder for creating a BatchImageEvent entity.
|
||||
type BatchImageEventCreate struct {
|
||||
config
|
||||
mutation *BatchImageEventMutation
|
||||
hooks []Hook
|
||||
conflict []sql.ConflictOption
|
||||
}
|
||||
|
||||
// SetJobID sets the "job_id" field.
|
||||
func (_c *BatchImageEventCreate) SetJobID(v string) *BatchImageEventCreate {
|
||||
_c.mutation.SetJobID(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetEventType sets the "event_type" field.
|
||||
func (_c *BatchImageEventCreate) SetEventType(v string) *BatchImageEventCreate {
|
||||
_c.mutation.SetEventType(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetPayload sets the "payload" field.
|
||||
func (_c *BatchImageEventCreate) SetPayload(v map[string]interface{}) *BatchImageEventCreate {
|
||||
_c.mutation.SetPayload(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetEventHash sets the "event_hash" field.
|
||||
func (_c *BatchImageEventCreate) SetEventHash(v string) *BatchImageEventCreate {
|
||||
_c.mutation.SetEventHash(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableEventHash sets the "event_hash" field if the given value is not nil.
|
||||
func (_c *BatchImageEventCreate) SetNillableEventHash(v *string) *BatchImageEventCreate {
|
||||
if v != nil {
|
||||
_c.SetEventHash(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetCreatedAt sets the "created_at" field.
|
||||
func (_c *BatchImageEventCreate) SetCreatedAt(v time.Time) *BatchImageEventCreate {
|
||||
_c.mutation.SetCreatedAt(v)
|
||||
return _c
|
||||
}
|
||||
|
||||
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
|
||||
func (_c *BatchImageEventCreate) SetNillableCreatedAt(v *time.Time) *BatchImageEventCreate {
|
||||
if v != nil {
|
||||
_c.SetCreatedAt(*v)
|
||||
}
|
||||
return _c
|
||||
}
|
||||
|
||||
// Mutation returns the BatchImageEventMutation object of the builder.
|
||||
func (_c *BatchImageEventCreate) Mutation() *BatchImageEventMutation {
|
||||
return _c.mutation
|
||||
}
|
||||
|
||||
// Save creates the BatchImageEvent in the database.
|
||||
func (_c *BatchImageEventCreate) Save(ctx context.Context) (*BatchImageEvent, error) {
|
||||
_c.defaults()
|
||||
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
|
||||
}
|
||||
|
||||
// SaveX calls Save and panics if Save returns an error.
|
||||
func (_c *BatchImageEventCreate) SaveX(ctx context.Context) *BatchImageEvent {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *BatchImageEventCreate) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *BatchImageEventCreate) 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 *BatchImageEventCreate) defaults() {
|
||||
if _, ok := _c.mutation.CreatedAt(); !ok {
|
||||
v := batchimageevent.DefaultCreatedAt()
|
||||
_c.mutation.SetCreatedAt(v)
|
||||
}
|
||||
}
|
||||
|
||||
// check runs all checks and user-defined validators on the builder.
|
||||
func (_c *BatchImageEventCreate) check() error {
|
||||
if _, ok := _c.mutation.JobID(); !ok {
|
||||
return &ValidationError{Name: "job_id", err: errors.New(`ent: missing required field "BatchImageEvent.job_id"`)}
|
||||
}
|
||||
if v, ok := _c.mutation.JobID(); ok {
|
||||
if err := batchimageevent.JobIDValidator(v); err != nil {
|
||||
return &ValidationError{Name: "job_id", err: fmt.Errorf(`ent: validator failed for field "BatchImageEvent.job_id": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _, ok := _c.mutation.EventType(); !ok {
|
||||
return &ValidationError{Name: "event_type", err: errors.New(`ent: missing required field "BatchImageEvent.event_type"`)}
|
||||
}
|
||||
if v, ok := _c.mutation.EventType(); ok {
|
||||
if err := batchimageevent.EventTypeValidator(v); err != nil {
|
||||
return &ValidationError{Name: "event_type", err: fmt.Errorf(`ent: validator failed for field "BatchImageEvent.event_type": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _c.mutation.EventHash(); ok {
|
||||
if err := batchimageevent.EventHashValidator(v); err != nil {
|
||||
return &ValidationError{Name: "event_hash", err: fmt.Errorf(`ent: validator failed for field "BatchImageEvent.event_hash": %w`, err)}
|
||||
}
|
||||
}
|
||||
if _, ok := _c.mutation.CreatedAt(); !ok {
|
||||
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "BatchImageEvent.created_at"`)}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_c *BatchImageEventCreate) sqlSave(ctx context.Context) (*BatchImageEvent, 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 = int64(id)
|
||||
_c.mutation.id = &_node.ID
|
||||
_c.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
func (_c *BatchImageEventCreate) createSpec() (*BatchImageEvent, *sqlgraph.CreateSpec) {
|
||||
var (
|
||||
_node = &BatchImageEvent{config: _c.config}
|
||||
_spec = sqlgraph.NewCreateSpec(batchimageevent.Table, sqlgraph.NewFieldSpec(batchimageevent.FieldID, field.TypeInt64))
|
||||
)
|
||||
_spec.OnConflict = _c.conflict
|
||||
if value, ok := _c.mutation.JobID(); ok {
|
||||
_spec.SetField(batchimageevent.FieldJobID, field.TypeString, value)
|
||||
_node.JobID = value
|
||||
}
|
||||
if value, ok := _c.mutation.EventType(); ok {
|
||||
_spec.SetField(batchimageevent.FieldEventType, field.TypeString, value)
|
||||
_node.EventType = value
|
||||
}
|
||||
if value, ok := _c.mutation.Payload(); ok {
|
||||
_spec.SetField(batchimageevent.FieldPayload, field.TypeJSON, value)
|
||||
_node.Payload = value
|
||||
}
|
||||
if value, ok := _c.mutation.EventHash(); ok {
|
||||
_spec.SetField(batchimageevent.FieldEventHash, field.TypeString, value)
|
||||
_node.EventHash = &value
|
||||
}
|
||||
if value, ok := _c.mutation.CreatedAt(); ok {
|
||||
_spec.SetField(batchimageevent.FieldCreatedAt, field.TypeTime, value)
|
||||
_node.CreatedAt = value
|
||||
}
|
||||
return _node, _spec
|
||||
}
|
||||
|
||||
// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
|
||||
// of the `INSERT` statement. For example:
|
||||
//
|
||||
// client.BatchImageEvent.Create().
|
||||
// SetJobID(v).
|
||||
// OnConflict(
|
||||
// // Update the row with the new values
|
||||
// // the was proposed for insertion.
|
||||
// sql.ResolveWithNewValues(),
|
||||
// ).
|
||||
// // Override some of the fields with custom
|
||||
// // update values.
|
||||
// Update(func(u *ent.BatchImageEventUpsert) {
|
||||
// SetJobID(v+v).
|
||||
// }).
|
||||
// Exec(ctx)
|
||||
func (_c *BatchImageEventCreate) OnConflict(opts ...sql.ConflictOption) *BatchImageEventUpsertOne {
|
||||
_c.conflict = opts
|
||||
return &BatchImageEventUpsertOne{
|
||||
create: _c,
|
||||
}
|
||||
}
|
||||
|
||||
// OnConflictColumns calls `OnConflict` and configures the columns
|
||||
// as conflict target. Using this option is equivalent to using:
|
||||
//
|
||||
// client.BatchImageEvent.Create().
|
||||
// OnConflict(sql.ConflictColumns(columns...)).
|
||||
// Exec(ctx)
|
||||
func (_c *BatchImageEventCreate) OnConflictColumns(columns ...string) *BatchImageEventUpsertOne {
|
||||
_c.conflict = append(_c.conflict, sql.ConflictColumns(columns...))
|
||||
return &BatchImageEventUpsertOne{
|
||||
create: _c,
|
||||
}
|
||||
}
|
||||
|
||||
type (
|
||||
// BatchImageEventUpsertOne is the builder for "upsert"-ing
|
||||
// one BatchImageEvent node.
|
||||
BatchImageEventUpsertOne struct {
|
||||
create *BatchImageEventCreate
|
||||
}
|
||||
|
||||
// BatchImageEventUpsert is the "OnConflict" setter.
|
||||
BatchImageEventUpsert struct {
|
||||
*sql.UpdateSet
|
||||
}
|
||||
)
|
||||
|
||||
// SetJobID sets the "job_id" field.
|
||||
func (u *BatchImageEventUpsert) SetJobID(v string) *BatchImageEventUpsert {
|
||||
u.Set(batchimageevent.FieldJobID, v)
|
||||
return u
|
||||
}
|
||||
|
||||
// UpdateJobID sets the "job_id" field to the value that was provided on create.
|
||||
func (u *BatchImageEventUpsert) UpdateJobID() *BatchImageEventUpsert {
|
||||
u.SetExcluded(batchimageevent.FieldJobID)
|
||||
return u
|
||||
}
|
||||
|
||||
// SetEventType sets the "event_type" field.
|
||||
func (u *BatchImageEventUpsert) SetEventType(v string) *BatchImageEventUpsert {
|
||||
u.Set(batchimageevent.FieldEventType, v)
|
||||
return u
|
||||
}
|
||||
|
||||
// UpdateEventType sets the "event_type" field to the value that was provided on create.
|
||||
func (u *BatchImageEventUpsert) UpdateEventType() *BatchImageEventUpsert {
|
||||
u.SetExcluded(batchimageevent.FieldEventType)
|
||||
return u
|
||||
}
|
||||
|
||||
// SetPayload sets the "payload" field.
|
||||
func (u *BatchImageEventUpsert) SetPayload(v map[string]interface{}) *BatchImageEventUpsert {
|
||||
u.Set(batchimageevent.FieldPayload, v)
|
||||
return u
|
||||
}
|
||||
|
||||
// UpdatePayload sets the "payload" field to the value that was provided on create.
|
||||
func (u *BatchImageEventUpsert) UpdatePayload() *BatchImageEventUpsert {
|
||||
u.SetExcluded(batchimageevent.FieldPayload)
|
||||
return u
|
||||
}
|
||||
|
||||
// ClearPayload clears the value of the "payload" field.
|
||||
func (u *BatchImageEventUpsert) ClearPayload() *BatchImageEventUpsert {
|
||||
u.SetNull(batchimageevent.FieldPayload)
|
||||
return u
|
||||
}
|
||||
|
||||
// SetEventHash sets the "event_hash" field.
|
||||
func (u *BatchImageEventUpsert) SetEventHash(v string) *BatchImageEventUpsert {
|
||||
u.Set(batchimageevent.FieldEventHash, v)
|
||||
return u
|
||||
}
|
||||
|
||||
// UpdateEventHash sets the "event_hash" field to the value that was provided on create.
|
||||
func (u *BatchImageEventUpsert) UpdateEventHash() *BatchImageEventUpsert {
|
||||
u.SetExcluded(batchimageevent.FieldEventHash)
|
||||
return u
|
||||
}
|
||||
|
||||
// ClearEventHash clears the value of the "event_hash" field.
|
||||
func (u *BatchImageEventUpsert) ClearEventHash() *BatchImageEventUpsert {
|
||||
u.SetNull(batchimageevent.FieldEventHash)
|
||||
return u
|
||||
}
|
||||
|
||||
// UpdateNewValues updates the mutable fields using the new values that were set on create.
|
||||
// Using this option is equivalent to using:
|
||||
//
|
||||
// client.BatchImageEvent.Create().
|
||||
// OnConflict(
|
||||
// sql.ResolveWithNewValues(),
|
||||
// ).
|
||||
// Exec(ctx)
|
||||
func (u *BatchImageEventUpsertOne) UpdateNewValues() *BatchImageEventUpsertOne {
|
||||
u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
|
||||
u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
|
||||
if _, exists := u.create.mutation.CreatedAt(); exists {
|
||||
s.SetIgnore(batchimageevent.FieldCreatedAt)
|
||||
}
|
||||
}))
|
||||
return u
|
||||
}
|
||||
|
||||
// Ignore sets each column to itself in case of conflict.
|
||||
// Using this option is equivalent to using:
|
||||
//
|
||||
// client.BatchImageEvent.Create().
|
||||
// OnConflict(sql.ResolveWithIgnore()).
|
||||
// Exec(ctx)
|
||||
func (u *BatchImageEventUpsertOne) Ignore() *BatchImageEventUpsertOne {
|
||||
u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
|
||||
return u
|
||||
}
|
||||
|
||||
// DoNothing configures the conflict_action to `DO NOTHING`.
|
||||
// Supported only by SQLite and PostgreSQL.
|
||||
func (u *BatchImageEventUpsertOne) DoNothing() *BatchImageEventUpsertOne {
|
||||
u.create.conflict = append(u.create.conflict, sql.DoNothing())
|
||||
return u
|
||||
}
|
||||
|
||||
// Update allows overriding fields `UPDATE` values. See the BatchImageEventCreate.OnConflict
|
||||
// documentation for more info.
|
||||
func (u *BatchImageEventUpsertOne) Update(set func(*BatchImageEventUpsert)) *BatchImageEventUpsertOne {
|
||||
u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
|
||||
set(&BatchImageEventUpsert{UpdateSet: update})
|
||||
}))
|
||||
return u
|
||||
}
|
||||
|
||||
// SetJobID sets the "job_id" field.
|
||||
func (u *BatchImageEventUpsertOne) SetJobID(v string) *BatchImageEventUpsertOne {
|
||||
return u.Update(func(s *BatchImageEventUpsert) {
|
||||
s.SetJobID(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateJobID sets the "job_id" field to the value that was provided on create.
|
||||
func (u *BatchImageEventUpsertOne) UpdateJobID() *BatchImageEventUpsertOne {
|
||||
return u.Update(func(s *BatchImageEventUpsert) {
|
||||
s.UpdateJobID()
|
||||
})
|
||||
}
|
||||
|
||||
// SetEventType sets the "event_type" field.
|
||||
func (u *BatchImageEventUpsertOne) SetEventType(v string) *BatchImageEventUpsertOne {
|
||||
return u.Update(func(s *BatchImageEventUpsert) {
|
||||
s.SetEventType(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateEventType sets the "event_type" field to the value that was provided on create.
|
||||
func (u *BatchImageEventUpsertOne) UpdateEventType() *BatchImageEventUpsertOne {
|
||||
return u.Update(func(s *BatchImageEventUpsert) {
|
||||
s.UpdateEventType()
|
||||
})
|
||||
}
|
||||
|
||||
// SetPayload sets the "payload" field.
|
||||
func (u *BatchImageEventUpsertOne) SetPayload(v map[string]interface{}) *BatchImageEventUpsertOne {
|
||||
return u.Update(func(s *BatchImageEventUpsert) {
|
||||
s.SetPayload(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatePayload sets the "payload" field to the value that was provided on create.
|
||||
func (u *BatchImageEventUpsertOne) UpdatePayload() *BatchImageEventUpsertOne {
|
||||
return u.Update(func(s *BatchImageEventUpsert) {
|
||||
s.UpdatePayload()
|
||||
})
|
||||
}
|
||||
|
||||
// ClearPayload clears the value of the "payload" field.
|
||||
func (u *BatchImageEventUpsertOne) ClearPayload() *BatchImageEventUpsertOne {
|
||||
return u.Update(func(s *BatchImageEventUpsert) {
|
||||
s.ClearPayload()
|
||||
})
|
||||
}
|
||||
|
||||
// SetEventHash sets the "event_hash" field.
|
||||
func (u *BatchImageEventUpsertOne) SetEventHash(v string) *BatchImageEventUpsertOne {
|
||||
return u.Update(func(s *BatchImageEventUpsert) {
|
||||
s.SetEventHash(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateEventHash sets the "event_hash" field to the value that was provided on create.
|
||||
func (u *BatchImageEventUpsertOne) UpdateEventHash() *BatchImageEventUpsertOne {
|
||||
return u.Update(func(s *BatchImageEventUpsert) {
|
||||
s.UpdateEventHash()
|
||||
})
|
||||
}
|
||||
|
||||
// ClearEventHash clears the value of the "event_hash" field.
|
||||
func (u *BatchImageEventUpsertOne) ClearEventHash() *BatchImageEventUpsertOne {
|
||||
return u.Update(func(s *BatchImageEventUpsert) {
|
||||
s.ClearEventHash()
|
||||
})
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (u *BatchImageEventUpsertOne) Exec(ctx context.Context) error {
|
||||
if len(u.create.conflict) == 0 {
|
||||
return errors.New("ent: missing options for BatchImageEventCreate.OnConflict")
|
||||
}
|
||||
return u.create.Exec(ctx)
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (u *BatchImageEventUpsertOne) ExecX(ctx context.Context) {
|
||||
if err := u.create.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Exec executes the UPSERT query and returns the inserted/updated ID.
|
||||
func (u *BatchImageEventUpsertOne) ID(ctx context.Context) (id int64, err error) {
|
||||
node, err := u.create.Save(ctx)
|
||||
if err != nil {
|
||||
return id, err
|
||||
}
|
||||
return node.ID, nil
|
||||
}
|
||||
|
||||
// IDX is like ID, but panics if an error occurs.
|
||||
func (u *BatchImageEventUpsertOne) IDX(ctx context.Context) int64 {
|
||||
id, err := u.ID(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// BatchImageEventCreateBulk is the builder for creating many BatchImageEvent entities in bulk.
|
||||
type BatchImageEventCreateBulk struct {
|
||||
config
|
||||
err error
|
||||
builders []*BatchImageEventCreate
|
||||
conflict []sql.ConflictOption
|
||||
}
|
||||
|
||||
// Save creates the BatchImageEvent entities in the database.
|
||||
func (_c *BatchImageEventCreateBulk) Save(ctx context.Context) ([]*BatchImageEvent, error) {
|
||||
if _c.err != nil {
|
||||
return nil, _c.err
|
||||
}
|
||||
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
|
||||
nodes := make([]*BatchImageEvent, 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.(*BatchImageEventMutation)
|
||||
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}
|
||||
spec.OnConflict = _c.conflict
|
||||
// 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 = int64(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 *BatchImageEventCreateBulk) SaveX(ctx context.Context) []*BatchImageEvent {
|
||||
v, err := _c.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_c *BatchImageEventCreateBulk) Exec(ctx context.Context) error {
|
||||
_, err := _c.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_c *BatchImageEventCreateBulk) ExecX(ctx context.Context) {
|
||||
if err := _c.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// OnConflict allows configuring the `ON CONFLICT` / `ON DUPLICATE KEY` clause
|
||||
// of the `INSERT` statement. For example:
|
||||
//
|
||||
// client.BatchImageEvent.CreateBulk(builders...).
|
||||
// OnConflict(
|
||||
// // Update the row with the new values
|
||||
// // the was proposed for insertion.
|
||||
// sql.ResolveWithNewValues(),
|
||||
// ).
|
||||
// // Override some of the fields with custom
|
||||
// // update values.
|
||||
// Update(func(u *ent.BatchImageEventUpsert) {
|
||||
// SetJobID(v+v).
|
||||
// }).
|
||||
// Exec(ctx)
|
||||
func (_c *BatchImageEventCreateBulk) OnConflict(opts ...sql.ConflictOption) *BatchImageEventUpsertBulk {
|
||||
_c.conflict = opts
|
||||
return &BatchImageEventUpsertBulk{
|
||||
create: _c,
|
||||
}
|
||||
}
|
||||
|
||||
// OnConflictColumns calls `OnConflict` and configures the columns
|
||||
// as conflict target. Using this option is equivalent to using:
|
||||
//
|
||||
// client.BatchImageEvent.Create().
|
||||
// OnConflict(sql.ConflictColumns(columns...)).
|
||||
// Exec(ctx)
|
||||
func (_c *BatchImageEventCreateBulk) OnConflictColumns(columns ...string) *BatchImageEventUpsertBulk {
|
||||
_c.conflict = append(_c.conflict, sql.ConflictColumns(columns...))
|
||||
return &BatchImageEventUpsertBulk{
|
||||
create: _c,
|
||||
}
|
||||
}
|
||||
|
||||
// BatchImageEventUpsertBulk is the builder for "upsert"-ing
|
||||
// a bulk of BatchImageEvent nodes.
|
||||
type BatchImageEventUpsertBulk struct {
|
||||
create *BatchImageEventCreateBulk
|
||||
}
|
||||
|
||||
// UpdateNewValues updates the mutable fields using the new values that
|
||||
// were set on create. Using this option is equivalent to using:
|
||||
//
|
||||
// client.BatchImageEvent.Create().
|
||||
// OnConflict(
|
||||
// sql.ResolveWithNewValues(),
|
||||
// ).
|
||||
// Exec(ctx)
|
||||
func (u *BatchImageEventUpsertBulk) UpdateNewValues() *BatchImageEventUpsertBulk {
|
||||
u.create.conflict = append(u.create.conflict, sql.ResolveWithNewValues())
|
||||
u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(s *sql.UpdateSet) {
|
||||
for _, b := range u.create.builders {
|
||||
if _, exists := b.mutation.CreatedAt(); exists {
|
||||
s.SetIgnore(batchimageevent.FieldCreatedAt)
|
||||
}
|
||||
}
|
||||
}))
|
||||
return u
|
||||
}
|
||||
|
||||
// Ignore sets each column to itself in case of conflict.
|
||||
// Using this option is equivalent to using:
|
||||
//
|
||||
// client.BatchImageEvent.Create().
|
||||
// OnConflict(sql.ResolveWithIgnore()).
|
||||
// Exec(ctx)
|
||||
func (u *BatchImageEventUpsertBulk) Ignore() *BatchImageEventUpsertBulk {
|
||||
u.create.conflict = append(u.create.conflict, sql.ResolveWithIgnore())
|
||||
return u
|
||||
}
|
||||
|
||||
// DoNothing configures the conflict_action to `DO NOTHING`.
|
||||
// Supported only by SQLite and PostgreSQL.
|
||||
func (u *BatchImageEventUpsertBulk) DoNothing() *BatchImageEventUpsertBulk {
|
||||
u.create.conflict = append(u.create.conflict, sql.DoNothing())
|
||||
return u
|
||||
}
|
||||
|
||||
// Update allows overriding fields `UPDATE` values. See the BatchImageEventCreateBulk.OnConflict
|
||||
// documentation for more info.
|
||||
func (u *BatchImageEventUpsertBulk) Update(set func(*BatchImageEventUpsert)) *BatchImageEventUpsertBulk {
|
||||
u.create.conflict = append(u.create.conflict, sql.ResolveWith(func(update *sql.UpdateSet) {
|
||||
set(&BatchImageEventUpsert{UpdateSet: update})
|
||||
}))
|
||||
return u
|
||||
}
|
||||
|
||||
// SetJobID sets the "job_id" field.
|
||||
func (u *BatchImageEventUpsertBulk) SetJobID(v string) *BatchImageEventUpsertBulk {
|
||||
return u.Update(func(s *BatchImageEventUpsert) {
|
||||
s.SetJobID(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateJobID sets the "job_id" field to the value that was provided on create.
|
||||
func (u *BatchImageEventUpsertBulk) UpdateJobID() *BatchImageEventUpsertBulk {
|
||||
return u.Update(func(s *BatchImageEventUpsert) {
|
||||
s.UpdateJobID()
|
||||
})
|
||||
}
|
||||
|
||||
// SetEventType sets the "event_type" field.
|
||||
func (u *BatchImageEventUpsertBulk) SetEventType(v string) *BatchImageEventUpsertBulk {
|
||||
return u.Update(func(s *BatchImageEventUpsert) {
|
||||
s.SetEventType(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateEventType sets the "event_type" field to the value that was provided on create.
|
||||
func (u *BatchImageEventUpsertBulk) UpdateEventType() *BatchImageEventUpsertBulk {
|
||||
return u.Update(func(s *BatchImageEventUpsert) {
|
||||
s.UpdateEventType()
|
||||
})
|
||||
}
|
||||
|
||||
// SetPayload sets the "payload" field.
|
||||
func (u *BatchImageEventUpsertBulk) SetPayload(v map[string]interface{}) *BatchImageEventUpsertBulk {
|
||||
return u.Update(func(s *BatchImageEventUpsert) {
|
||||
s.SetPayload(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdatePayload sets the "payload" field to the value that was provided on create.
|
||||
func (u *BatchImageEventUpsertBulk) UpdatePayload() *BatchImageEventUpsertBulk {
|
||||
return u.Update(func(s *BatchImageEventUpsert) {
|
||||
s.UpdatePayload()
|
||||
})
|
||||
}
|
||||
|
||||
// ClearPayload clears the value of the "payload" field.
|
||||
func (u *BatchImageEventUpsertBulk) ClearPayload() *BatchImageEventUpsertBulk {
|
||||
return u.Update(func(s *BatchImageEventUpsert) {
|
||||
s.ClearPayload()
|
||||
})
|
||||
}
|
||||
|
||||
// SetEventHash sets the "event_hash" field.
|
||||
func (u *BatchImageEventUpsertBulk) SetEventHash(v string) *BatchImageEventUpsertBulk {
|
||||
return u.Update(func(s *BatchImageEventUpsert) {
|
||||
s.SetEventHash(v)
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateEventHash sets the "event_hash" field to the value that was provided on create.
|
||||
func (u *BatchImageEventUpsertBulk) UpdateEventHash() *BatchImageEventUpsertBulk {
|
||||
return u.Update(func(s *BatchImageEventUpsert) {
|
||||
s.UpdateEventHash()
|
||||
})
|
||||
}
|
||||
|
||||
// ClearEventHash clears the value of the "event_hash" field.
|
||||
func (u *BatchImageEventUpsertBulk) ClearEventHash() *BatchImageEventUpsertBulk {
|
||||
return u.Update(func(s *BatchImageEventUpsert) {
|
||||
s.ClearEventHash()
|
||||
})
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (u *BatchImageEventUpsertBulk) Exec(ctx context.Context) error {
|
||||
if u.create.err != nil {
|
||||
return u.create.err
|
||||
}
|
||||
for i, b := range u.create.builders {
|
||||
if len(b.conflict) != 0 {
|
||||
return fmt.Errorf("ent: OnConflict was set for builder %d. Set it on the BatchImageEventCreateBulk instead", i)
|
||||
}
|
||||
}
|
||||
if len(u.create.conflict) == 0 {
|
||||
return errors.New("ent: missing options for BatchImageEventCreateBulk.OnConflict")
|
||||
}
|
||||
return u.create.Exec(ctx)
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (u *BatchImageEventUpsertBulk) ExecX(ctx context.Context) {
|
||||
if err := u.create.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
"github.com/Wei-Shaw/sub2api/ent/batchimageevent"
|
||||
"github.com/Wei-Shaw/sub2api/ent/predicate"
|
||||
)
|
||||
|
||||
// BatchImageEventDelete is the builder for deleting a BatchImageEvent entity.
|
||||
type BatchImageEventDelete struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *BatchImageEventMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the BatchImageEventDelete builder.
|
||||
func (_d *BatchImageEventDelete) Where(ps ...predicate.BatchImageEvent) *BatchImageEventDelete {
|
||||
_d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query and returns how many vertices were deleted.
|
||||
func (_d *BatchImageEventDelete) 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 *BatchImageEventDelete) ExecX(ctx context.Context) int {
|
||||
n, err := _d.Exec(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (_d *BatchImageEventDelete) sqlExec(ctx context.Context) (int, error) {
|
||||
_spec := sqlgraph.NewDeleteSpec(batchimageevent.Table, sqlgraph.NewFieldSpec(batchimageevent.FieldID, field.TypeInt64))
|
||||
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
|
||||
}
|
||||
|
||||
// BatchImageEventDeleteOne is the builder for deleting a single BatchImageEvent entity.
|
||||
type BatchImageEventDeleteOne struct {
|
||||
_d *BatchImageEventDelete
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the BatchImageEventDelete builder.
|
||||
func (_d *BatchImageEventDeleteOne) Where(ps ...predicate.BatchImageEvent) *BatchImageEventDeleteOne {
|
||||
_d._d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query.
|
||||
func (_d *BatchImageEventDeleteOne) Exec(ctx context.Context) error {
|
||||
n, err := _d._d.Exec(ctx)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case n == 0:
|
||||
return &NotFoundError{batchimageevent.Label}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_d *BatchImageEventDeleteOne) ExecX(ctx context.Context) {
|
||||
if err := _d.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
@@ -1,564 +0,0 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/Wei-Shaw/sub2api/ent/batchimageevent"
|
||||
"github.com/Wei-Shaw/sub2api/ent/predicate"
|
||||
)
|
||||
|
||||
// BatchImageEventQuery is the builder for querying BatchImageEvent entities.
|
||||
type BatchImageEventQuery struct {
|
||||
config
|
||||
ctx *QueryContext
|
||||
order []batchimageevent.OrderOption
|
||||
inters []Interceptor
|
||||
predicates []predicate.BatchImageEvent
|
||||
modifiers []func(*sql.Selector)
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
path func(context.Context) (*sql.Selector, error)
|
||||
}
|
||||
|
||||
// Where adds a new predicate for the BatchImageEventQuery builder.
|
||||
func (_q *BatchImageEventQuery) Where(ps ...predicate.BatchImageEvent) *BatchImageEventQuery {
|
||||
_q.predicates = append(_q.predicates, ps...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// Limit the number of records to be returned by this query.
|
||||
func (_q *BatchImageEventQuery) Limit(limit int) *BatchImageEventQuery {
|
||||
_q.ctx.Limit = &limit
|
||||
return _q
|
||||
}
|
||||
|
||||
// Offset to start from.
|
||||
func (_q *BatchImageEventQuery) Offset(offset int) *BatchImageEventQuery {
|
||||
_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 *BatchImageEventQuery) Unique(unique bool) *BatchImageEventQuery {
|
||||
_q.ctx.Unique = &unique
|
||||
return _q
|
||||
}
|
||||
|
||||
// Order specifies how the records should be ordered.
|
||||
func (_q *BatchImageEventQuery) Order(o ...batchimageevent.OrderOption) *BatchImageEventQuery {
|
||||
_q.order = append(_q.order, o...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// First returns the first BatchImageEvent entity from the query.
|
||||
// Returns a *NotFoundError when no BatchImageEvent was found.
|
||||
func (_q *BatchImageEventQuery) First(ctx context.Context) (*BatchImageEvent, 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{batchimageevent.Label}
|
||||
}
|
||||
return nodes[0], nil
|
||||
}
|
||||
|
||||
// FirstX is like First, but panics if an error occurs.
|
||||
func (_q *BatchImageEventQuery) FirstX(ctx context.Context) *BatchImageEvent {
|
||||
node, err := _q.First(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// FirstID returns the first BatchImageEvent ID from the query.
|
||||
// Returns a *NotFoundError when no BatchImageEvent ID was found.
|
||||
func (_q *BatchImageEventQuery) FirstID(ctx context.Context) (id int64, err error) {
|
||||
var ids []int64
|
||||
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
|
||||
return
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
err = &NotFoundError{batchimageevent.Label}
|
||||
return
|
||||
}
|
||||
return ids[0], nil
|
||||
}
|
||||
|
||||
// FirstIDX is like FirstID, but panics if an error occurs.
|
||||
func (_q *BatchImageEventQuery) FirstIDX(ctx context.Context) int64 {
|
||||
id, err := _q.FirstID(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// Only returns a single BatchImageEvent entity found by the query, ensuring it only returns one.
|
||||
// Returns a *NotSingularError when more than one BatchImageEvent entity is found.
|
||||
// Returns a *NotFoundError when no BatchImageEvent entities are found.
|
||||
func (_q *BatchImageEventQuery) Only(ctx context.Context) (*BatchImageEvent, 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{batchimageevent.Label}
|
||||
default:
|
||||
return nil, &NotSingularError{batchimageevent.Label}
|
||||
}
|
||||
}
|
||||
|
||||
// OnlyX is like Only, but panics if an error occurs.
|
||||
func (_q *BatchImageEventQuery) OnlyX(ctx context.Context) *BatchImageEvent {
|
||||
node, err := _q.Only(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// OnlyID is like Only, but returns the only BatchImageEvent ID in the query.
|
||||
// Returns a *NotSingularError when more than one BatchImageEvent ID is found.
|
||||
// Returns a *NotFoundError when no entities are found.
|
||||
func (_q *BatchImageEventQuery) OnlyID(ctx context.Context) (id int64, err error) {
|
||||
var ids []int64
|
||||
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{batchimageevent.Label}
|
||||
default:
|
||||
err = &NotSingularError{batchimageevent.Label}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// OnlyIDX is like OnlyID, but panics if an error occurs.
|
||||
func (_q *BatchImageEventQuery) OnlyIDX(ctx context.Context) int64 {
|
||||
id, err := _q.OnlyID(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// All executes the query and returns a list of BatchImageEvents.
|
||||
func (_q *BatchImageEventQuery) All(ctx context.Context) ([]*BatchImageEvent, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
|
||||
if err := _q.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qr := querierAll[[]*BatchImageEvent, *BatchImageEventQuery]()
|
||||
return withInterceptors[[]*BatchImageEvent](ctx, _q, qr, _q.inters)
|
||||
}
|
||||
|
||||
// AllX is like All, but panics if an error occurs.
|
||||
func (_q *BatchImageEventQuery) AllX(ctx context.Context) []*BatchImageEvent {
|
||||
nodes, err := _q.All(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
||||
// IDs executes the query and returns a list of BatchImageEvent IDs.
|
||||
func (_q *BatchImageEventQuery) IDs(ctx context.Context) (ids []int64, err error) {
|
||||
if _q.ctx.Unique == nil && _q.path != nil {
|
||||
_q.Unique(true)
|
||||
}
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
|
||||
if err = _q.Select(batchimageevent.FieldID).Scan(ctx, &ids); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// IDsX is like IDs, but panics if an error occurs.
|
||||
func (_q *BatchImageEventQuery) IDsX(ctx context.Context) []int64 {
|
||||
ids, err := _q.IDs(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// Count returns the count of the given query.
|
||||
func (_q *BatchImageEventQuery) 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[*BatchImageEventQuery](), _q.inters)
|
||||
}
|
||||
|
||||
// CountX is like Count, but panics if an error occurs.
|
||||
func (_q *BatchImageEventQuery) 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 *BatchImageEventQuery) 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 *BatchImageEventQuery) ExistX(ctx context.Context) bool {
|
||||
exist, err := _q.Exist(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return exist
|
||||
}
|
||||
|
||||
// Clone returns a duplicate of the BatchImageEventQuery 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 *BatchImageEventQuery) Clone() *BatchImageEventQuery {
|
||||
if _q == nil {
|
||||
return nil
|
||||
}
|
||||
return &BatchImageEventQuery{
|
||||
config: _q.config,
|
||||
ctx: _q.ctx.Clone(),
|
||||
order: append([]batchimageevent.OrderOption{}, _q.order...),
|
||||
inters: append([]Interceptor{}, _q.inters...),
|
||||
predicates: append([]predicate.BatchImageEvent{}, _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 {
|
||||
// JobID string `json:"job_id,omitempty"`
|
||||
// Count int `json:"count,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.BatchImageEvent.Query().
|
||||
// GroupBy(batchimageevent.FieldJobID).
|
||||
// Aggregate(ent.Count()).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *BatchImageEventQuery) GroupBy(field string, fields ...string) *BatchImageEventGroupBy {
|
||||
_q.ctx.Fields = append([]string{field}, fields...)
|
||||
grbuild := &BatchImageEventGroupBy{build: _q}
|
||||
grbuild.flds = &_q.ctx.Fields
|
||||
grbuild.label = batchimageevent.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 {
|
||||
// JobID string `json:"job_id,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.BatchImageEvent.Query().
|
||||
// Select(batchimageevent.FieldJobID).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *BatchImageEventQuery) Select(fields ...string) *BatchImageEventSelect {
|
||||
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
|
||||
sbuild := &BatchImageEventSelect{BatchImageEventQuery: _q}
|
||||
sbuild.label = batchimageevent.Label
|
||||
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
|
||||
return sbuild
|
||||
}
|
||||
|
||||
// Aggregate returns a BatchImageEventSelect configured with the given aggregations.
|
||||
func (_q *BatchImageEventQuery) Aggregate(fns ...AggregateFunc) *BatchImageEventSelect {
|
||||
return _q.Select().Aggregate(fns...)
|
||||
}
|
||||
|
||||
func (_q *BatchImageEventQuery) 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 !batchimageevent.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 *BatchImageEventQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*BatchImageEvent, error) {
|
||||
var (
|
||||
nodes = []*BatchImageEvent{}
|
||||
_spec = _q.querySpec()
|
||||
)
|
||||
_spec.ScanValues = func(columns []string) ([]any, error) {
|
||||
return (*BatchImageEvent).scanValues(nil, columns)
|
||||
}
|
||||
_spec.Assign = func(columns []string, values []any) error {
|
||||
node := &BatchImageEvent{config: _q.config}
|
||||
nodes = append(nodes, node)
|
||||
return node.assignValues(columns, values)
|
||||
}
|
||||
if len(_q.modifiers) > 0 {
|
||||
_spec.Modifiers = _q.modifiers
|
||||
}
|
||||
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 *BatchImageEventQuery) sqlCount(ctx context.Context) (int, error) {
|
||||
_spec := _q.querySpec()
|
||||
if len(_q.modifiers) > 0 {
|
||||
_spec.Modifiers = _q.modifiers
|
||||
}
|
||||
_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 *BatchImageEventQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
_spec := sqlgraph.NewQuerySpec(batchimageevent.Table, batchimageevent.Columns, sqlgraph.NewFieldSpec(batchimageevent.FieldID, field.TypeInt64))
|
||||
_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, batchimageevent.FieldID)
|
||||
for i := range fields {
|
||||
if fields[i] != batchimageevent.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 *BatchImageEventQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
builder := sql.Dialect(_q.driver.Dialect())
|
||||
t1 := builder.Table(batchimageevent.Table)
|
||||
columns := _q.ctx.Fields
|
||||
if len(columns) == 0 {
|
||||
columns = batchimageevent.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 _, m := range _q.modifiers {
|
||||
m(selector)
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
|
||||
// updated, deleted or "selected ... for update" by other sessions, until the transaction is
|
||||
// either committed or rolled-back.
|
||||
func (_q *BatchImageEventQuery) ForUpdate(opts ...sql.LockOption) *BatchImageEventQuery {
|
||||
if _q.driver.Dialect() == dialect.Postgres {
|
||||
_q.Unique(false)
|
||||
}
|
||||
_q.modifiers = append(_q.modifiers, func(s *sql.Selector) {
|
||||
s.ForUpdate(opts...)
|
||||
})
|
||||
return _q
|
||||
}
|
||||
|
||||
// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
|
||||
// on any rows that are read. Other sessions can read the rows, but cannot modify them
|
||||
// until your transaction commits.
|
||||
func (_q *BatchImageEventQuery) ForShare(opts ...sql.LockOption) *BatchImageEventQuery {
|
||||
if _q.driver.Dialect() == dialect.Postgres {
|
||||
_q.Unique(false)
|
||||
}
|
||||
_q.modifiers = append(_q.modifiers, func(s *sql.Selector) {
|
||||
s.ForShare(opts...)
|
||||
})
|
||||
return _q
|
||||
}
|
||||
|
||||
// BatchImageEventGroupBy is the group-by builder for BatchImageEvent entities.
|
||||
type BatchImageEventGroupBy struct {
|
||||
selector
|
||||
build *BatchImageEventQuery
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the group-by query.
|
||||
func (_g *BatchImageEventGroupBy) Aggregate(fns ...AggregateFunc) *BatchImageEventGroupBy {
|
||||
_g.fns = append(_g.fns, fns...)
|
||||
return _g
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_g *BatchImageEventGroupBy) 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[*BatchImageEventQuery, *BatchImageEventGroupBy](ctx, _g.build, _g, _g.build.inters, v)
|
||||
}
|
||||
|
||||
func (_g *BatchImageEventGroupBy) sqlScan(ctx context.Context, root *BatchImageEventQuery, 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)
|
||||
}
|
||||
|
||||
// BatchImageEventSelect is the builder for selecting fields of BatchImageEvent entities.
|
||||
type BatchImageEventSelect struct {
|
||||
*BatchImageEventQuery
|
||||
selector
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the selector query.
|
||||
func (_s *BatchImageEventSelect) Aggregate(fns ...AggregateFunc) *BatchImageEventSelect {
|
||||
_s.fns = append(_s.fns, fns...)
|
||||
return _s
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_s *BatchImageEventSelect) 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[*BatchImageEventQuery, *BatchImageEventSelect](ctx, _s.BatchImageEventQuery, _s, _s.inters, v)
|
||||
}
|
||||
|
||||
func (_s *BatchImageEventSelect) sqlScan(ctx context.Context, root *BatchImageEventQuery, 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)
|
||||
}
|
||||
@@ -1,377 +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"
|
||||
"github.com/Wei-Shaw/sub2api/ent/batchimageevent"
|
||||
"github.com/Wei-Shaw/sub2api/ent/predicate"
|
||||
)
|
||||
|
||||
// BatchImageEventUpdate is the builder for updating BatchImageEvent entities.
|
||||
type BatchImageEventUpdate struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *BatchImageEventMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the BatchImageEventUpdate builder.
|
||||
func (_u *BatchImageEventUpdate) Where(ps ...predicate.BatchImageEvent) *BatchImageEventUpdate {
|
||||
_u.mutation.Where(ps...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetJobID sets the "job_id" field.
|
||||
func (_u *BatchImageEventUpdate) SetJobID(v string) *BatchImageEventUpdate {
|
||||
_u.mutation.SetJobID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableJobID sets the "job_id" field if the given value is not nil.
|
||||
func (_u *BatchImageEventUpdate) SetNillableJobID(v *string) *BatchImageEventUpdate {
|
||||
if v != nil {
|
||||
_u.SetJobID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetEventType sets the "event_type" field.
|
||||
func (_u *BatchImageEventUpdate) SetEventType(v string) *BatchImageEventUpdate {
|
||||
_u.mutation.SetEventType(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableEventType sets the "event_type" field if the given value is not nil.
|
||||
func (_u *BatchImageEventUpdate) SetNillableEventType(v *string) *BatchImageEventUpdate {
|
||||
if v != nil {
|
||||
_u.SetEventType(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetPayload sets the "payload" field.
|
||||
func (_u *BatchImageEventUpdate) SetPayload(v map[string]interface{}) *BatchImageEventUpdate {
|
||||
_u.mutation.SetPayload(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearPayload clears the value of the "payload" field.
|
||||
func (_u *BatchImageEventUpdate) ClearPayload() *BatchImageEventUpdate {
|
||||
_u.mutation.ClearPayload()
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetEventHash sets the "event_hash" field.
|
||||
func (_u *BatchImageEventUpdate) SetEventHash(v string) *BatchImageEventUpdate {
|
||||
_u.mutation.SetEventHash(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableEventHash sets the "event_hash" field if the given value is not nil.
|
||||
func (_u *BatchImageEventUpdate) SetNillableEventHash(v *string) *BatchImageEventUpdate {
|
||||
if v != nil {
|
||||
_u.SetEventHash(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearEventHash clears the value of the "event_hash" field.
|
||||
func (_u *BatchImageEventUpdate) ClearEventHash() *BatchImageEventUpdate {
|
||||
_u.mutation.ClearEventHash()
|
||||
return _u
|
||||
}
|
||||
|
||||
// Mutation returns the BatchImageEventMutation object of the builder.
|
||||
func (_u *BatchImageEventUpdate) Mutation() *BatchImageEventMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// Save executes the query and returns the number of nodes affected by the update operation.
|
||||
func (_u *BatchImageEventUpdate) 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 *BatchImageEventUpdate) SaveX(ctx context.Context) int {
|
||||
affected, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return affected
|
||||
}
|
||||
|
||||
// Exec executes the query.
|
||||
func (_u *BatchImageEventUpdate) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *BatchImageEventUpdate) 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 *BatchImageEventUpdate) check() error {
|
||||
if v, ok := _u.mutation.JobID(); ok {
|
||||
if err := batchimageevent.JobIDValidator(v); err != nil {
|
||||
return &ValidationError{Name: "job_id", err: fmt.Errorf(`ent: validator failed for field "BatchImageEvent.job_id": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.EventType(); ok {
|
||||
if err := batchimageevent.EventTypeValidator(v); err != nil {
|
||||
return &ValidationError{Name: "event_type", err: fmt.Errorf(`ent: validator failed for field "BatchImageEvent.event_type": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.EventHash(); ok {
|
||||
if err := batchimageevent.EventHashValidator(v); err != nil {
|
||||
return &ValidationError{Name: "event_hash", err: fmt.Errorf(`ent: validator failed for field "BatchImageEvent.event_hash": %w`, err)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_u *BatchImageEventUpdate) sqlSave(ctx context.Context) (_node int, err error) {
|
||||
if err := _u.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := sqlgraph.NewUpdateSpec(batchimageevent.Table, batchimageevent.Columns, sqlgraph.NewFieldSpec(batchimageevent.FieldID, field.TypeInt64))
|
||||
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.JobID(); ok {
|
||||
_spec.SetField(batchimageevent.FieldJobID, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.EventType(); ok {
|
||||
_spec.SetField(batchimageevent.FieldEventType, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.Payload(); ok {
|
||||
_spec.SetField(batchimageevent.FieldPayload, field.TypeJSON, value)
|
||||
}
|
||||
if _u.mutation.PayloadCleared() {
|
||||
_spec.ClearField(batchimageevent.FieldPayload, field.TypeJSON)
|
||||
}
|
||||
if value, ok := _u.mutation.EventHash(); ok {
|
||||
_spec.SetField(batchimageevent.FieldEventHash, field.TypeString, value)
|
||||
}
|
||||
if _u.mutation.EventHashCleared() {
|
||||
_spec.ClearField(batchimageevent.FieldEventHash, field.TypeString)
|
||||
}
|
||||
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
|
||||
if _, ok := err.(*sqlgraph.NotFoundError); ok {
|
||||
err = &NotFoundError{batchimageevent.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
|
||||
// BatchImageEventUpdateOne is the builder for updating a single BatchImageEvent entity.
|
||||
type BatchImageEventUpdateOne struct {
|
||||
config
|
||||
fields []string
|
||||
hooks []Hook
|
||||
mutation *BatchImageEventMutation
|
||||
}
|
||||
|
||||
// SetJobID sets the "job_id" field.
|
||||
func (_u *BatchImageEventUpdateOne) SetJobID(v string) *BatchImageEventUpdateOne {
|
||||
_u.mutation.SetJobID(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableJobID sets the "job_id" field if the given value is not nil.
|
||||
func (_u *BatchImageEventUpdateOne) SetNillableJobID(v *string) *BatchImageEventUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetJobID(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetEventType sets the "event_type" field.
|
||||
func (_u *BatchImageEventUpdateOne) SetEventType(v string) *BatchImageEventUpdateOne {
|
||||
_u.mutation.SetEventType(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableEventType sets the "event_type" field if the given value is not nil.
|
||||
func (_u *BatchImageEventUpdateOne) SetNillableEventType(v *string) *BatchImageEventUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetEventType(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetPayload sets the "payload" field.
|
||||
func (_u *BatchImageEventUpdateOne) SetPayload(v map[string]interface{}) *BatchImageEventUpdateOne {
|
||||
_u.mutation.SetPayload(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearPayload clears the value of the "payload" field.
|
||||
func (_u *BatchImageEventUpdateOne) ClearPayload() *BatchImageEventUpdateOne {
|
||||
_u.mutation.ClearPayload()
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetEventHash sets the "event_hash" field.
|
||||
func (_u *BatchImageEventUpdateOne) SetEventHash(v string) *BatchImageEventUpdateOne {
|
||||
_u.mutation.SetEventHash(v)
|
||||
return _u
|
||||
}
|
||||
|
||||
// SetNillableEventHash sets the "event_hash" field if the given value is not nil.
|
||||
func (_u *BatchImageEventUpdateOne) SetNillableEventHash(v *string) *BatchImageEventUpdateOne {
|
||||
if v != nil {
|
||||
_u.SetEventHash(*v)
|
||||
}
|
||||
return _u
|
||||
}
|
||||
|
||||
// ClearEventHash clears the value of the "event_hash" field.
|
||||
func (_u *BatchImageEventUpdateOne) ClearEventHash() *BatchImageEventUpdateOne {
|
||||
_u.mutation.ClearEventHash()
|
||||
return _u
|
||||
}
|
||||
|
||||
// Mutation returns the BatchImageEventMutation object of the builder.
|
||||
func (_u *BatchImageEventUpdateOne) Mutation() *BatchImageEventMutation {
|
||||
return _u.mutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the BatchImageEventUpdate builder.
|
||||
func (_u *BatchImageEventUpdateOne) Where(ps ...predicate.BatchImageEvent) *BatchImageEventUpdateOne {
|
||||
_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 *BatchImageEventUpdateOne) Select(field string, fields ...string) *BatchImageEventUpdateOne {
|
||||
_u.fields = append([]string{field}, fields...)
|
||||
return _u
|
||||
}
|
||||
|
||||
// Save executes the query and returns the updated BatchImageEvent entity.
|
||||
func (_u *BatchImageEventUpdateOne) Save(ctx context.Context) (*BatchImageEvent, error) {
|
||||
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
|
||||
}
|
||||
|
||||
// SaveX is like Save, but panics if an error occurs.
|
||||
func (_u *BatchImageEventUpdateOne) SaveX(ctx context.Context) *BatchImageEvent {
|
||||
node, err := _u.Save(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// Exec executes the query on the entity.
|
||||
func (_u *BatchImageEventUpdateOne) Exec(ctx context.Context) error {
|
||||
_, err := _u.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_u *BatchImageEventUpdateOne) 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 *BatchImageEventUpdateOne) check() error {
|
||||
if v, ok := _u.mutation.JobID(); ok {
|
||||
if err := batchimageevent.JobIDValidator(v); err != nil {
|
||||
return &ValidationError{Name: "job_id", err: fmt.Errorf(`ent: validator failed for field "BatchImageEvent.job_id": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.EventType(); ok {
|
||||
if err := batchimageevent.EventTypeValidator(v); err != nil {
|
||||
return &ValidationError{Name: "event_type", err: fmt.Errorf(`ent: validator failed for field "BatchImageEvent.event_type": %w`, err)}
|
||||
}
|
||||
}
|
||||
if v, ok := _u.mutation.EventHash(); ok {
|
||||
if err := batchimageevent.EventHashValidator(v); err != nil {
|
||||
return &ValidationError{Name: "event_hash", err: fmt.Errorf(`ent: validator failed for field "BatchImageEvent.event_hash": %w`, err)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (_u *BatchImageEventUpdateOne) sqlSave(ctx context.Context) (_node *BatchImageEvent, err error) {
|
||||
if err := _u.check(); err != nil {
|
||||
return _node, err
|
||||
}
|
||||
_spec := sqlgraph.NewUpdateSpec(batchimageevent.Table, batchimageevent.Columns, sqlgraph.NewFieldSpec(batchimageevent.FieldID, field.TypeInt64))
|
||||
id, ok := _u.mutation.ID()
|
||||
if !ok {
|
||||
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "BatchImageEvent.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, batchimageevent.FieldID)
|
||||
for _, f := range fields {
|
||||
if !batchimageevent.ValidColumn(f) {
|
||||
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
|
||||
}
|
||||
if f != batchimageevent.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.JobID(); ok {
|
||||
_spec.SetField(batchimageevent.FieldJobID, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.EventType(); ok {
|
||||
_spec.SetField(batchimageevent.FieldEventType, field.TypeString, value)
|
||||
}
|
||||
if value, ok := _u.mutation.Payload(); ok {
|
||||
_spec.SetField(batchimageevent.FieldPayload, field.TypeJSON, value)
|
||||
}
|
||||
if _u.mutation.PayloadCleared() {
|
||||
_spec.ClearField(batchimageevent.FieldPayload, field.TypeJSON)
|
||||
}
|
||||
if value, ok := _u.mutation.EventHash(); ok {
|
||||
_spec.SetField(batchimageevent.FieldEventHash, field.TypeString, value)
|
||||
}
|
||||
if _u.mutation.EventHashCleared() {
|
||||
_spec.ClearField(batchimageevent.FieldEventHash, field.TypeString)
|
||||
}
|
||||
_node = &BatchImageEvent{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{batchimageevent.Label}
|
||||
} else if sqlgraph.IsConstraintError(err) {
|
||||
err = &ConstraintError{msg: err.Error(), wrap: err}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
_u.mutation.done = true
|
||||
return _node, nil
|
||||
}
|
||||
@@ -1,320 +0,0 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"github.com/Wei-Shaw/sub2api/ent/batchimageitem"
|
||||
)
|
||||
|
||||
// BatchImageItem is the model entity for the BatchImageItem schema.
|
||||
type BatchImageItem struct {
|
||||
config `json:"-"`
|
||||
// ID of the ent.
|
||||
ID int64 `json:"id,omitempty"`
|
||||
// JobID holds the value of the "job_id" field.
|
||||
JobID string `json:"job_id,omitempty"`
|
||||
// CustomID holds the value of the "custom_id" field.
|
||||
CustomID string `json:"custom_id,omitempty"`
|
||||
// Status holds the value of the "status" field.
|
||||
Status string `json:"status,omitempty"`
|
||||
// RequestHash holds the value of the "request_hash" field.
|
||||
RequestHash *string `json:"request_hash,omitempty"`
|
||||
// PromptPreview holds the value of the "prompt_preview" field.
|
||||
PromptPreview *string `json:"prompt_preview,omitempty"`
|
||||
// ProviderSourceObject holds the value of the "provider_source_object" field.
|
||||
ProviderSourceObject *string `json:"provider_source_object,omitempty"`
|
||||
// SourceLineNumber holds the value of the "source_line_number" field.
|
||||
SourceLineNumber *int `json:"source_line_number,omitempty"`
|
||||
// SourceByteOffset holds the value of the "source_byte_offset" field.
|
||||
SourceByteOffset *int64 `json:"source_byte_offset,omitempty"`
|
||||
// SourceByteLength holds the value of the "source_byte_length" field.
|
||||
SourceByteLength *int64 `json:"source_byte_length,omitempty"`
|
||||
// MimeType holds the value of the "mime_type" field.
|
||||
MimeType *string `json:"mime_type,omitempty"`
|
||||
// FileExtension holds the value of the "file_extension" field.
|
||||
FileExtension *string `json:"file_extension,omitempty"`
|
||||
// ImageCount holds the value of the "image_count" field.
|
||||
ImageCount int `json:"image_count,omitempty"`
|
||||
// ErrorCode holds the value of the "error_code" field.
|
||||
ErrorCode *string `json:"error_code,omitempty"`
|
||||
// ErrorMessage holds the value of the "error_message" field.
|
||||
ErrorMessage *string `json:"error_message,omitempty"`
|
||||
// BilledAmount holds the value of the "billed_amount" field.
|
||||
BilledAmount *float64 `json:"billed_amount,omitempty"`
|
||||
// CreatedAt holds the value of the "created_at" field.
|
||||
CreatedAt time.Time `json:"created_at,omitempty"`
|
||||
// IndexedAt holds the value of the "indexed_at" field.
|
||||
IndexedAt *time.Time `json:"indexed_at,omitempty"`
|
||||
selectValues sql.SelectValues
|
||||
}
|
||||
|
||||
// scanValues returns the types for scanning values from sql.Rows.
|
||||
func (*BatchImageItem) scanValues(columns []string) ([]any, error) {
|
||||
values := make([]any, len(columns))
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case batchimageitem.FieldBilledAmount:
|
||||
values[i] = new(sql.NullFloat64)
|
||||
case batchimageitem.FieldID, batchimageitem.FieldSourceLineNumber, batchimageitem.FieldSourceByteOffset, batchimageitem.FieldSourceByteLength, batchimageitem.FieldImageCount:
|
||||
values[i] = new(sql.NullInt64)
|
||||
case batchimageitem.FieldJobID, batchimageitem.FieldCustomID, batchimageitem.FieldStatus, batchimageitem.FieldRequestHash, batchimageitem.FieldPromptPreview, batchimageitem.FieldProviderSourceObject, batchimageitem.FieldMimeType, batchimageitem.FieldFileExtension, batchimageitem.FieldErrorCode, batchimageitem.FieldErrorMessage:
|
||||
values[i] = new(sql.NullString)
|
||||
case batchimageitem.FieldCreatedAt, batchimageitem.FieldIndexedAt:
|
||||
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 BatchImageItem fields.
|
||||
func (_m *BatchImageItem) 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 batchimageitem.FieldID:
|
||||
value, ok := values[i].(*sql.NullInt64)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field id", value)
|
||||
}
|
||||
_m.ID = int64(value.Int64)
|
||||
case batchimageitem.FieldJobID:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field job_id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.JobID = value.String
|
||||
}
|
||||
case batchimageitem.FieldCustomID:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field custom_id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.CustomID = value.String
|
||||
}
|
||||
case batchimageitem.FieldStatus:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field status", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Status = value.String
|
||||
}
|
||||
case batchimageitem.FieldRequestHash:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field request_hash", values[i])
|
||||
} else if value.Valid {
|
||||
_m.RequestHash = new(string)
|
||||
*_m.RequestHash = value.String
|
||||
}
|
||||
case batchimageitem.FieldPromptPreview:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field prompt_preview", values[i])
|
||||
} else if value.Valid {
|
||||
_m.PromptPreview = new(string)
|
||||
*_m.PromptPreview = value.String
|
||||
}
|
||||
case batchimageitem.FieldProviderSourceObject:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field provider_source_object", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ProviderSourceObject = new(string)
|
||||
*_m.ProviderSourceObject = value.String
|
||||
}
|
||||
case batchimageitem.FieldSourceLineNumber:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field source_line_number", values[i])
|
||||
} else if value.Valid {
|
||||
_m.SourceLineNumber = new(int)
|
||||
*_m.SourceLineNumber = int(value.Int64)
|
||||
}
|
||||
case batchimageitem.FieldSourceByteOffset:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field source_byte_offset", values[i])
|
||||
} else if value.Valid {
|
||||
_m.SourceByteOffset = new(int64)
|
||||
*_m.SourceByteOffset = value.Int64
|
||||
}
|
||||
case batchimageitem.FieldSourceByteLength:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field source_byte_length", values[i])
|
||||
} else if value.Valid {
|
||||
_m.SourceByteLength = new(int64)
|
||||
*_m.SourceByteLength = value.Int64
|
||||
}
|
||||
case batchimageitem.FieldMimeType:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field mime_type", values[i])
|
||||
} else if value.Valid {
|
||||
_m.MimeType = new(string)
|
||||
*_m.MimeType = value.String
|
||||
}
|
||||
case batchimageitem.FieldFileExtension:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field file_extension", values[i])
|
||||
} else if value.Valid {
|
||||
_m.FileExtension = new(string)
|
||||
*_m.FileExtension = value.String
|
||||
}
|
||||
case batchimageitem.FieldImageCount:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field image_count", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ImageCount = int(value.Int64)
|
||||
}
|
||||
case batchimageitem.FieldErrorCode:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field error_code", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ErrorCode = new(string)
|
||||
*_m.ErrorCode = value.String
|
||||
}
|
||||
case batchimageitem.FieldErrorMessage:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field error_message", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ErrorMessage = new(string)
|
||||
*_m.ErrorMessage = value.String
|
||||
}
|
||||
case batchimageitem.FieldBilledAmount:
|
||||
if value, ok := values[i].(*sql.NullFloat64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field billed_amount", values[i])
|
||||
} else if value.Valid {
|
||||
_m.BilledAmount = new(float64)
|
||||
*_m.BilledAmount = value.Float64
|
||||
}
|
||||
case batchimageitem.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 batchimageitem.FieldIndexedAt:
|
||||
if value, ok := values[i].(*sql.NullTime); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field indexed_at", values[i])
|
||||
} else if value.Valid {
|
||||
_m.IndexedAt = new(time.Time)
|
||||
*_m.IndexedAt = 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 BatchImageItem.
|
||||
// This includes values selected through modifiers, order, etc.
|
||||
func (_m *BatchImageItem) Value(name string) (ent.Value, error) {
|
||||
return _m.selectValues.Get(name)
|
||||
}
|
||||
|
||||
// Update returns a builder for updating this BatchImageItem.
|
||||
// Note that you need to call BatchImageItem.Unwrap() before calling this method if this BatchImageItem
|
||||
// was returned from a transaction, and the transaction was committed or rolled back.
|
||||
func (_m *BatchImageItem) Update() *BatchImageItemUpdateOne {
|
||||
return NewBatchImageItemClient(_m.config).UpdateOne(_m)
|
||||
}
|
||||
|
||||
// Unwrap unwraps the BatchImageItem 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 *BatchImageItem) Unwrap() *BatchImageItem {
|
||||
_tx, ok := _m.config.driver.(*txDriver)
|
||||
if !ok {
|
||||
panic("ent: BatchImageItem is not a transactional entity")
|
||||
}
|
||||
_m.config.driver = _tx.drv
|
||||
return _m
|
||||
}
|
||||
|
||||
// String implements the fmt.Stringer.
|
||||
func (_m *BatchImageItem) String() string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString("BatchImageItem(")
|
||||
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
|
||||
builder.WriteString("job_id=")
|
||||
builder.WriteString(_m.JobID)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("custom_id=")
|
||||
builder.WriteString(_m.CustomID)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("status=")
|
||||
builder.WriteString(_m.Status)
|
||||
builder.WriteString(", ")
|
||||
if v := _m.RequestHash; v != nil {
|
||||
builder.WriteString("request_hash=")
|
||||
builder.WriteString(*v)
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.PromptPreview; v != nil {
|
||||
builder.WriteString("prompt_preview=")
|
||||
builder.WriteString(*v)
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.ProviderSourceObject; v != nil {
|
||||
builder.WriteString("provider_source_object=")
|
||||
builder.WriteString(*v)
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.SourceLineNumber; v != nil {
|
||||
builder.WriteString("source_line_number=")
|
||||
builder.WriteString(fmt.Sprintf("%v", *v))
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.SourceByteOffset; v != nil {
|
||||
builder.WriteString("source_byte_offset=")
|
||||
builder.WriteString(fmt.Sprintf("%v", *v))
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.SourceByteLength; v != nil {
|
||||
builder.WriteString("source_byte_length=")
|
||||
builder.WriteString(fmt.Sprintf("%v", *v))
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.MimeType; v != nil {
|
||||
builder.WriteString("mime_type=")
|
||||
builder.WriteString(*v)
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.FileExtension; v != nil {
|
||||
builder.WriteString("file_extension=")
|
||||
builder.WriteString(*v)
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("image_count=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.ImageCount))
|
||||
builder.WriteString(", ")
|
||||
if v := _m.ErrorCode; v != nil {
|
||||
builder.WriteString("error_code=")
|
||||
builder.WriteString(*v)
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.ErrorMessage; v != nil {
|
||||
builder.WriteString("error_message=")
|
||||
builder.WriteString(*v)
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.BilledAmount; v != nil {
|
||||
builder.WriteString("billed_amount=")
|
||||
builder.WriteString(fmt.Sprintf("%v", *v))
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("created_at=")
|
||||
builder.WriteString(_m.CreatedAt.Format(time.ANSIC))
|
||||
builder.WriteString(", ")
|
||||
if v := _m.IndexedAt; v != nil {
|
||||
builder.WriteString("indexed_at=")
|
||||
builder.WriteString(v.Format(time.ANSIC))
|
||||
}
|
||||
builder.WriteByte(')')
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// BatchImageItems is a parsable slice of BatchImageItem.
|
||||
type BatchImageItems []*BatchImageItem
|
||||
@@ -1,200 +0,0 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package batchimageitem
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
)
|
||||
|
||||
const (
|
||||
// Label holds the string label denoting the batchimageitem type in the database.
|
||||
Label = "batch_image_item"
|
||||
// FieldID holds the string denoting the id field in the database.
|
||||
FieldID = "id"
|
||||
// FieldJobID holds the string denoting the job_id field in the database.
|
||||
FieldJobID = "job_id"
|
||||
// FieldCustomID holds the string denoting the custom_id field in the database.
|
||||
FieldCustomID = "custom_id"
|
||||
// FieldStatus holds the string denoting the status field in the database.
|
||||
FieldStatus = "status"
|
||||
// FieldRequestHash holds the string denoting the request_hash field in the database.
|
||||
FieldRequestHash = "request_hash"
|
||||
// FieldPromptPreview holds the string denoting the prompt_preview field in the database.
|
||||
FieldPromptPreview = "prompt_preview"
|
||||
// FieldProviderSourceObject holds the string denoting the provider_source_object field in the database.
|
||||
FieldProviderSourceObject = "provider_source_object"
|
||||
// FieldSourceLineNumber holds the string denoting the source_line_number field in the database.
|
||||
FieldSourceLineNumber = "source_line_number"
|
||||
// FieldSourceByteOffset holds the string denoting the source_byte_offset field in the database.
|
||||
FieldSourceByteOffset = "source_byte_offset"
|
||||
// FieldSourceByteLength holds the string denoting the source_byte_length field in the database.
|
||||
FieldSourceByteLength = "source_byte_length"
|
||||
// FieldMimeType holds the string denoting the mime_type field in the database.
|
||||
FieldMimeType = "mime_type"
|
||||
// FieldFileExtension holds the string denoting the file_extension field in the database.
|
||||
FieldFileExtension = "file_extension"
|
||||
// FieldImageCount holds the string denoting the image_count field in the database.
|
||||
FieldImageCount = "image_count"
|
||||
// FieldErrorCode holds the string denoting the error_code field in the database.
|
||||
FieldErrorCode = "error_code"
|
||||
// FieldErrorMessage holds the string denoting the error_message field in the database.
|
||||
FieldErrorMessage = "error_message"
|
||||
// FieldBilledAmount holds the string denoting the billed_amount field in the database.
|
||||
FieldBilledAmount = "billed_amount"
|
||||
// FieldCreatedAt holds the string denoting the created_at field in the database.
|
||||
FieldCreatedAt = "created_at"
|
||||
// FieldIndexedAt holds the string denoting the indexed_at field in the database.
|
||||
FieldIndexedAt = "indexed_at"
|
||||
// Table holds the table name of the batchimageitem in the database.
|
||||
Table = "batch_image_items"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns for batchimageitem fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldJobID,
|
||||
FieldCustomID,
|
||||
FieldStatus,
|
||||
FieldRequestHash,
|
||||
FieldPromptPreview,
|
||||
FieldProviderSourceObject,
|
||||
FieldSourceLineNumber,
|
||||
FieldSourceByteOffset,
|
||||
FieldSourceByteLength,
|
||||
FieldMimeType,
|
||||
FieldFileExtension,
|
||||
FieldImageCount,
|
||||
FieldErrorCode,
|
||||
FieldErrorMessage,
|
||||
FieldBilledAmount,
|
||||
FieldCreatedAt,
|
||||
FieldIndexedAt,
|
||||
}
|
||||
|
||||
// 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 (
|
||||
// JobIDValidator is a validator for the "job_id" field. It is called by the builders before save.
|
||||
JobIDValidator func(string) error
|
||||
// CustomIDValidator is a validator for the "custom_id" field. It is called by the builders before save.
|
||||
CustomIDValidator func(string) error
|
||||
// StatusValidator is a validator for the "status" field. It is called by the builders before save.
|
||||
StatusValidator func(string) error
|
||||
// RequestHashValidator is a validator for the "request_hash" field. It is called by the builders before save.
|
||||
RequestHashValidator func(string) error
|
||||
// ProviderSourceObjectValidator is a validator for the "provider_source_object" field. It is called by the builders before save.
|
||||
ProviderSourceObjectValidator func(string) error
|
||||
// MimeTypeValidator is a validator for the "mime_type" field. It is called by the builders before save.
|
||||
MimeTypeValidator func(string) error
|
||||
// FileExtensionValidator is a validator for the "file_extension" field. It is called by the builders before save.
|
||||
FileExtensionValidator func(string) error
|
||||
// DefaultImageCount holds the default value on creation for the "image_count" field.
|
||||
DefaultImageCount int
|
||||
// ErrorCodeValidator is a validator for the "error_code" field. It is called by the builders before save.
|
||||
ErrorCodeValidator 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 BatchImageItem 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()
|
||||
}
|
||||
|
||||
// ByJobID orders the results by the job_id field.
|
||||
func ByJobID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldJobID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByCustomID orders the results by the custom_id field.
|
||||
func ByCustomID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldCustomID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByStatus orders the results by the status field.
|
||||
func ByStatus(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldStatus, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByRequestHash orders the results by the request_hash field.
|
||||
func ByRequestHash(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldRequestHash, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByPromptPreview orders the results by the prompt_preview field.
|
||||
func ByPromptPreview(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldPromptPreview, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByProviderSourceObject orders the results by the provider_source_object field.
|
||||
func ByProviderSourceObject(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldProviderSourceObject, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// BySourceLineNumber orders the results by the source_line_number field.
|
||||
func BySourceLineNumber(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldSourceLineNumber, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// BySourceByteOffset orders the results by the source_byte_offset field.
|
||||
func BySourceByteOffset(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldSourceByteOffset, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// BySourceByteLength orders the results by the source_byte_length field.
|
||||
func BySourceByteLength(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldSourceByteLength, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByMimeType orders the results by the mime_type field.
|
||||
func ByMimeType(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldMimeType, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByFileExtension orders the results by the file_extension field.
|
||||
func ByFileExtension(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldFileExtension, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByImageCount orders the results by the image_count field.
|
||||
func ByImageCount(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldImageCount, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByErrorCode orders the results by the error_code field.
|
||||
func ByErrorCode(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldErrorCode, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByErrorMessage orders the results by the error_message field.
|
||||
func ByErrorMessage(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldErrorMessage, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByBilledAmount orders the results by the billed_amount field.
|
||||
func ByBilledAmount(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldBilledAmount, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByCreatedAt orders the results by the created_at field.
|
||||
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByIndexedAt orders the results by the indexed_at field.
|
||||
func ByIndexedAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldIndexedAt, opts...).ToFunc()
|
||||
}
|
||||
@@ -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"
|
||||
"github.com/Wei-Shaw/sub2api/ent/batchimageitem"
|
||||
"github.com/Wei-Shaw/sub2api/ent/predicate"
|
||||
)
|
||||
|
||||
// BatchImageItemDelete is the builder for deleting a BatchImageItem entity.
|
||||
type BatchImageItemDelete struct {
|
||||
config
|
||||
hooks []Hook
|
||||
mutation *BatchImageItemMutation
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the BatchImageItemDelete builder.
|
||||
func (_d *BatchImageItemDelete) Where(ps ...predicate.BatchImageItem) *BatchImageItemDelete {
|
||||
_d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query and returns how many vertices were deleted.
|
||||
func (_d *BatchImageItemDelete) 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 *BatchImageItemDelete) ExecX(ctx context.Context) int {
|
||||
n, err := _d.Exec(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func (_d *BatchImageItemDelete) sqlExec(ctx context.Context) (int, error) {
|
||||
_spec := sqlgraph.NewDeleteSpec(batchimageitem.Table, sqlgraph.NewFieldSpec(batchimageitem.FieldID, field.TypeInt64))
|
||||
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
|
||||
}
|
||||
|
||||
// BatchImageItemDeleteOne is the builder for deleting a single BatchImageItem entity.
|
||||
type BatchImageItemDeleteOne struct {
|
||||
_d *BatchImageItemDelete
|
||||
}
|
||||
|
||||
// Where appends a list predicates to the BatchImageItemDelete builder.
|
||||
func (_d *BatchImageItemDeleteOne) Where(ps ...predicate.BatchImageItem) *BatchImageItemDeleteOne {
|
||||
_d._d.mutation.Where(ps...)
|
||||
return _d
|
||||
}
|
||||
|
||||
// Exec executes the deletion query.
|
||||
func (_d *BatchImageItemDeleteOne) Exec(ctx context.Context) error {
|
||||
n, err := _d._d.Exec(ctx)
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case n == 0:
|
||||
return &NotFoundError{batchimageitem.Label}
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExecX is like Exec, but panics if an error occurs.
|
||||
func (_d *BatchImageItemDeleteOne) ExecX(ctx context.Context) {
|
||||
if err := _d.Exec(ctx); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
@@ -1,564 +0,0 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"entgo.io/ent/dialect/sql/sqlgraph"
|
||||
"entgo.io/ent/schema/field"
|
||||
"github.com/Wei-Shaw/sub2api/ent/batchimageitem"
|
||||
"github.com/Wei-Shaw/sub2api/ent/predicate"
|
||||
)
|
||||
|
||||
// BatchImageItemQuery is the builder for querying BatchImageItem entities.
|
||||
type BatchImageItemQuery struct {
|
||||
config
|
||||
ctx *QueryContext
|
||||
order []batchimageitem.OrderOption
|
||||
inters []Interceptor
|
||||
predicates []predicate.BatchImageItem
|
||||
modifiers []func(*sql.Selector)
|
||||
// intermediate query (i.e. traversal path).
|
||||
sql *sql.Selector
|
||||
path func(context.Context) (*sql.Selector, error)
|
||||
}
|
||||
|
||||
// Where adds a new predicate for the BatchImageItemQuery builder.
|
||||
func (_q *BatchImageItemQuery) Where(ps ...predicate.BatchImageItem) *BatchImageItemQuery {
|
||||
_q.predicates = append(_q.predicates, ps...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// Limit the number of records to be returned by this query.
|
||||
func (_q *BatchImageItemQuery) Limit(limit int) *BatchImageItemQuery {
|
||||
_q.ctx.Limit = &limit
|
||||
return _q
|
||||
}
|
||||
|
||||
// Offset to start from.
|
||||
func (_q *BatchImageItemQuery) Offset(offset int) *BatchImageItemQuery {
|
||||
_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 *BatchImageItemQuery) Unique(unique bool) *BatchImageItemQuery {
|
||||
_q.ctx.Unique = &unique
|
||||
return _q
|
||||
}
|
||||
|
||||
// Order specifies how the records should be ordered.
|
||||
func (_q *BatchImageItemQuery) Order(o ...batchimageitem.OrderOption) *BatchImageItemQuery {
|
||||
_q.order = append(_q.order, o...)
|
||||
return _q
|
||||
}
|
||||
|
||||
// First returns the first BatchImageItem entity from the query.
|
||||
// Returns a *NotFoundError when no BatchImageItem was found.
|
||||
func (_q *BatchImageItemQuery) First(ctx context.Context) (*BatchImageItem, 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{batchimageitem.Label}
|
||||
}
|
||||
return nodes[0], nil
|
||||
}
|
||||
|
||||
// FirstX is like First, but panics if an error occurs.
|
||||
func (_q *BatchImageItemQuery) FirstX(ctx context.Context) *BatchImageItem {
|
||||
node, err := _q.First(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// FirstID returns the first BatchImageItem ID from the query.
|
||||
// Returns a *NotFoundError when no BatchImageItem ID was found.
|
||||
func (_q *BatchImageItemQuery) FirstID(ctx context.Context) (id int64, err error) {
|
||||
var ids []int64
|
||||
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
|
||||
return
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
err = &NotFoundError{batchimageitem.Label}
|
||||
return
|
||||
}
|
||||
return ids[0], nil
|
||||
}
|
||||
|
||||
// FirstIDX is like FirstID, but panics if an error occurs.
|
||||
func (_q *BatchImageItemQuery) FirstIDX(ctx context.Context) int64 {
|
||||
id, err := _q.FirstID(ctx)
|
||||
if err != nil && !IsNotFound(err) {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// Only returns a single BatchImageItem entity found by the query, ensuring it only returns one.
|
||||
// Returns a *NotSingularError when more than one BatchImageItem entity is found.
|
||||
// Returns a *NotFoundError when no BatchImageItem entities are found.
|
||||
func (_q *BatchImageItemQuery) Only(ctx context.Context) (*BatchImageItem, 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{batchimageitem.Label}
|
||||
default:
|
||||
return nil, &NotSingularError{batchimageitem.Label}
|
||||
}
|
||||
}
|
||||
|
||||
// OnlyX is like Only, but panics if an error occurs.
|
||||
func (_q *BatchImageItemQuery) OnlyX(ctx context.Context) *BatchImageItem {
|
||||
node, err := _q.Only(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
// OnlyID is like Only, but returns the only BatchImageItem ID in the query.
|
||||
// Returns a *NotSingularError when more than one BatchImageItem ID is found.
|
||||
// Returns a *NotFoundError when no entities are found.
|
||||
func (_q *BatchImageItemQuery) OnlyID(ctx context.Context) (id int64, err error) {
|
||||
var ids []int64
|
||||
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{batchimageitem.Label}
|
||||
default:
|
||||
err = &NotSingularError{batchimageitem.Label}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// OnlyIDX is like OnlyID, but panics if an error occurs.
|
||||
func (_q *BatchImageItemQuery) OnlyIDX(ctx context.Context) int64 {
|
||||
id, err := _q.OnlyID(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// All executes the query and returns a list of BatchImageItems.
|
||||
func (_q *BatchImageItemQuery) All(ctx context.Context) ([]*BatchImageItem, error) {
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
|
||||
if err := _q.prepareQuery(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
qr := querierAll[[]*BatchImageItem, *BatchImageItemQuery]()
|
||||
return withInterceptors[[]*BatchImageItem](ctx, _q, qr, _q.inters)
|
||||
}
|
||||
|
||||
// AllX is like All, but panics if an error occurs.
|
||||
func (_q *BatchImageItemQuery) AllX(ctx context.Context) []*BatchImageItem {
|
||||
nodes, err := _q.All(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
||||
// IDs executes the query and returns a list of BatchImageItem IDs.
|
||||
func (_q *BatchImageItemQuery) IDs(ctx context.Context) (ids []int64, err error) {
|
||||
if _q.ctx.Unique == nil && _q.path != nil {
|
||||
_q.Unique(true)
|
||||
}
|
||||
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
|
||||
if err = _q.Select(batchimageitem.FieldID).Scan(ctx, &ids); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
// IDsX is like IDs, but panics if an error occurs.
|
||||
func (_q *BatchImageItemQuery) IDsX(ctx context.Context) []int64 {
|
||||
ids, err := _q.IDs(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// Count returns the count of the given query.
|
||||
func (_q *BatchImageItemQuery) 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[*BatchImageItemQuery](), _q.inters)
|
||||
}
|
||||
|
||||
// CountX is like Count, but panics if an error occurs.
|
||||
func (_q *BatchImageItemQuery) 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 *BatchImageItemQuery) 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 *BatchImageItemQuery) ExistX(ctx context.Context) bool {
|
||||
exist, err := _q.Exist(ctx)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return exist
|
||||
}
|
||||
|
||||
// Clone returns a duplicate of the BatchImageItemQuery 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 *BatchImageItemQuery) Clone() *BatchImageItemQuery {
|
||||
if _q == nil {
|
||||
return nil
|
||||
}
|
||||
return &BatchImageItemQuery{
|
||||
config: _q.config,
|
||||
ctx: _q.ctx.Clone(),
|
||||
order: append([]batchimageitem.OrderOption{}, _q.order...),
|
||||
inters: append([]Interceptor{}, _q.inters...),
|
||||
predicates: append([]predicate.BatchImageItem{}, _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 {
|
||||
// JobID string `json:"job_id,omitempty"`
|
||||
// Count int `json:"count,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.BatchImageItem.Query().
|
||||
// GroupBy(batchimageitem.FieldJobID).
|
||||
// Aggregate(ent.Count()).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *BatchImageItemQuery) GroupBy(field string, fields ...string) *BatchImageItemGroupBy {
|
||||
_q.ctx.Fields = append([]string{field}, fields...)
|
||||
grbuild := &BatchImageItemGroupBy{build: _q}
|
||||
grbuild.flds = &_q.ctx.Fields
|
||||
grbuild.label = batchimageitem.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 {
|
||||
// JobID string `json:"job_id,omitempty"`
|
||||
// }
|
||||
//
|
||||
// client.BatchImageItem.Query().
|
||||
// Select(batchimageitem.FieldJobID).
|
||||
// Scan(ctx, &v)
|
||||
func (_q *BatchImageItemQuery) Select(fields ...string) *BatchImageItemSelect {
|
||||
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
|
||||
sbuild := &BatchImageItemSelect{BatchImageItemQuery: _q}
|
||||
sbuild.label = batchimageitem.Label
|
||||
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
|
||||
return sbuild
|
||||
}
|
||||
|
||||
// Aggregate returns a BatchImageItemSelect configured with the given aggregations.
|
||||
func (_q *BatchImageItemQuery) Aggregate(fns ...AggregateFunc) *BatchImageItemSelect {
|
||||
return _q.Select().Aggregate(fns...)
|
||||
}
|
||||
|
||||
func (_q *BatchImageItemQuery) 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 !batchimageitem.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 *BatchImageItemQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*BatchImageItem, error) {
|
||||
var (
|
||||
nodes = []*BatchImageItem{}
|
||||
_spec = _q.querySpec()
|
||||
)
|
||||
_spec.ScanValues = func(columns []string) ([]any, error) {
|
||||
return (*BatchImageItem).scanValues(nil, columns)
|
||||
}
|
||||
_spec.Assign = func(columns []string, values []any) error {
|
||||
node := &BatchImageItem{config: _q.config}
|
||||
nodes = append(nodes, node)
|
||||
return node.assignValues(columns, values)
|
||||
}
|
||||
if len(_q.modifiers) > 0 {
|
||||
_spec.Modifiers = _q.modifiers
|
||||
}
|
||||
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 *BatchImageItemQuery) sqlCount(ctx context.Context) (int, error) {
|
||||
_spec := _q.querySpec()
|
||||
if len(_q.modifiers) > 0 {
|
||||
_spec.Modifiers = _q.modifiers
|
||||
}
|
||||
_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 *BatchImageItemQuery) querySpec() *sqlgraph.QuerySpec {
|
||||
_spec := sqlgraph.NewQuerySpec(batchimageitem.Table, batchimageitem.Columns, sqlgraph.NewFieldSpec(batchimageitem.FieldID, field.TypeInt64))
|
||||
_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, batchimageitem.FieldID)
|
||||
for i := range fields {
|
||||
if fields[i] != batchimageitem.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 *BatchImageItemQuery) sqlQuery(ctx context.Context) *sql.Selector {
|
||||
builder := sql.Dialect(_q.driver.Dialect())
|
||||
t1 := builder.Table(batchimageitem.Table)
|
||||
columns := _q.ctx.Fields
|
||||
if len(columns) == 0 {
|
||||
columns = batchimageitem.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 _, m := range _q.modifiers {
|
||||
m(selector)
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
// ForUpdate locks the selected rows against concurrent updates, and prevent them from being
|
||||
// updated, deleted or "selected ... for update" by other sessions, until the transaction is
|
||||
// either committed or rolled-back.
|
||||
func (_q *BatchImageItemQuery) ForUpdate(opts ...sql.LockOption) *BatchImageItemQuery {
|
||||
if _q.driver.Dialect() == dialect.Postgres {
|
||||
_q.Unique(false)
|
||||
}
|
||||
_q.modifiers = append(_q.modifiers, func(s *sql.Selector) {
|
||||
s.ForUpdate(opts...)
|
||||
})
|
||||
return _q
|
||||
}
|
||||
|
||||
// ForShare behaves similarly to ForUpdate, except that it acquires a shared mode lock
|
||||
// on any rows that are read. Other sessions can read the rows, but cannot modify them
|
||||
// until your transaction commits.
|
||||
func (_q *BatchImageItemQuery) ForShare(opts ...sql.LockOption) *BatchImageItemQuery {
|
||||
if _q.driver.Dialect() == dialect.Postgres {
|
||||
_q.Unique(false)
|
||||
}
|
||||
_q.modifiers = append(_q.modifiers, func(s *sql.Selector) {
|
||||
s.ForShare(opts...)
|
||||
})
|
||||
return _q
|
||||
}
|
||||
|
||||
// BatchImageItemGroupBy is the group-by builder for BatchImageItem entities.
|
||||
type BatchImageItemGroupBy struct {
|
||||
selector
|
||||
build *BatchImageItemQuery
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the group-by query.
|
||||
func (_g *BatchImageItemGroupBy) Aggregate(fns ...AggregateFunc) *BatchImageItemGroupBy {
|
||||
_g.fns = append(_g.fns, fns...)
|
||||
return _g
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_g *BatchImageItemGroupBy) 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[*BatchImageItemQuery, *BatchImageItemGroupBy](ctx, _g.build, _g, _g.build.inters, v)
|
||||
}
|
||||
|
||||
func (_g *BatchImageItemGroupBy) sqlScan(ctx context.Context, root *BatchImageItemQuery, 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)
|
||||
}
|
||||
|
||||
// BatchImageItemSelect is the builder for selecting fields of BatchImageItem entities.
|
||||
type BatchImageItemSelect struct {
|
||||
*BatchImageItemQuery
|
||||
selector
|
||||
}
|
||||
|
||||
// Aggregate adds the given aggregation functions to the selector query.
|
||||
func (_s *BatchImageItemSelect) Aggregate(fns ...AggregateFunc) *BatchImageItemSelect {
|
||||
_s.fns = append(_s.fns, fns...)
|
||||
return _s
|
||||
}
|
||||
|
||||
// Scan applies the selector query and scans the result into the given value.
|
||||
func (_s *BatchImageItemSelect) 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[*BatchImageItemQuery, *BatchImageItemSelect](ctx, _s.BatchImageItemQuery, _s, _s.inters, v)
|
||||
}
|
||||
|
||||
func (_s *BatchImageItemSelect) sqlScan(ctx context.Context, root *BatchImageItemQuery, 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)
|
||||
}
|
||||
@@ -1,609 +0,0 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package ent
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"entgo.io/ent"
|
||||
"entgo.io/ent/dialect/sql"
|
||||
"github.com/Wei-Shaw/sub2api/ent/batchimagejob"
|
||||
)
|
||||
|
||||
// BatchImageJob is the model entity for the BatchImageJob schema.
|
||||
type BatchImageJob struct {
|
||||
config `json:"-"`
|
||||
// ID of the ent.
|
||||
ID int64 `json:"id,omitempty"`
|
||||
// BatchID holds the value of the "batch_id" field.
|
||||
BatchID string `json:"batch_id,omitempty"`
|
||||
// UserID holds the value of the "user_id" field.
|
||||
UserID int64 `json:"user_id,omitempty"`
|
||||
// APIKeyID holds the value of the "api_key_id" field.
|
||||
APIKeyID *int64 `json:"api_key_id,omitempty"`
|
||||
// AccountID holds the value of the "account_id" field.
|
||||
AccountID *int64 `json:"account_id,omitempty"`
|
||||
// Provider holds the value of the "provider" field.
|
||||
Provider string `json:"provider,omitempty"`
|
||||
// Model holds the value of the "model" field.
|
||||
Model string `json:"model,omitempty"`
|
||||
// TaskName holds the value of the "task_name" field.
|
||||
TaskName string `json:"task_name,omitempty"`
|
||||
// Status holds the value of the "status" field.
|
||||
Status string `json:"status,omitempty"`
|
||||
// ProviderJobName holds the value of the "provider_job_name" field.
|
||||
ProviderJobName *string `json:"provider_job_name,omitempty"`
|
||||
// ProviderInputRef holds the value of the "provider_input_ref" field.
|
||||
ProviderInputRef *string `json:"provider_input_ref,omitempty"`
|
||||
// ProviderOutputRef holds the value of the "provider_output_ref" field.
|
||||
ProviderOutputRef *string `json:"provider_output_ref,omitempty"`
|
||||
// GcsInputURI holds the value of the "gcs_input_uri" field.
|
||||
GcsInputURI *string `json:"gcs_input_uri,omitempty"`
|
||||
// GcsOutputURI holds the value of the "gcs_output_uri" field.
|
||||
GcsOutputURI *string `json:"gcs_output_uri,omitempty"`
|
||||
// ItemCount holds the value of the "item_count" field.
|
||||
ItemCount int `json:"item_count,omitempty"`
|
||||
// SuccessCount holds the value of the "success_count" field.
|
||||
SuccessCount int `json:"success_count,omitempty"`
|
||||
// FailCount holds the value of the "fail_count" field.
|
||||
FailCount int `json:"fail_count,omitempty"`
|
||||
// CancelledCount holds the value of the "cancelled_count" field.
|
||||
CancelledCount int `json:"cancelled_count,omitempty"`
|
||||
// EstimatedCost holds the value of the "estimated_cost" field.
|
||||
EstimatedCost float64 `json:"estimated_cost,omitempty"`
|
||||
// HoldAmount holds the value of the "hold_amount" field.
|
||||
HoldAmount *float64 `json:"hold_amount,omitempty"`
|
||||
// ActualCost holds the value of the "actual_cost" field.
|
||||
ActualCost *float64 `json:"actual_cost,omitempty"`
|
||||
// Currency holds the value of the "currency" field.
|
||||
Currency string `json:"currency,omitempty"`
|
||||
// HoldID holds the value of the "hold_id" field.
|
||||
HoldID *string `json:"hold_id,omitempty"`
|
||||
// IdempotencyKey holds the value of the "idempotency_key" field.
|
||||
IdempotencyKey *string `json:"idempotency_key,omitempty"`
|
||||
// RequestHash holds the value of the "request_hash" field.
|
||||
RequestHash *string `json:"request_hash,omitempty"`
|
||||
// ManifestHash holds the value of the "manifest_hash" field.
|
||||
ManifestHash *string `json:"manifest_hash,omitempty"`
|
||||
// RetryCount holds the value of the "retry_count" field.
|
||||
RetryCount int `json:"retry_count,omitempty"`
|
||||
// Version holds the value of the "version" field.
|
||||
Version int `json:"version,omitempty"`
|
||||
// OutputExpiresAt holds the value of the "output_expires_at" field.
|
||||
OutputExpiresAt *time.Time `json:"output_expires_at,omitempty"`
|
||||
// InputDeletedAt holds the value of the "input_deleted_at" field.
|
||||
InputDeletedAt *time.Time `json:"input_deleted_at,omitempty"`
|
||||
// OutputDeletedAt holds the value of the "output_deleted_at" field.
|
||||
OutputDeletedAt *time.Time `json:"output_deleted_at,omitempty"`
|
||||
// DownloadedAt holds the value of the "downloaded_at" field.
|
||||
DownloadedAt *time.Time `json:"downloaded_at,omitempty"`
|
||||
// UserDeletedAt holds the value of the "user_deleted_at" field.
|
||||
UserDeletedAt *time.Time `json:"user_deleted_at,omitempty"`
|
||||
// LastErrorCode holds the value of the "last_error_code" field.
|
||||
LastErrorCode *string `json:"last_error_code,omitempty"`
|
||||
// LastErrorMessage holds the value of the "last_error_message" field.
|
||||
LastErrorMessage *string `json:"last_error_message,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"`
|
||||
// SubmittedAt holds the value of the "submitted_at" field.
|
||||
SubmittedAt *time.Time `json:"submitted_at,omitempty"`
|
||||
// StartedAt holds the value of the "started_at" field.
|
||||
StartedAt *time.Time `json:"started_at,omitempty"`
|
||||
// FinishedAt holds the value of the "finished_at" field.
|
||||
FinishedAt *time.Time `json:"finished_at,omitempty"`
|
||||
// SettledAt holds the value of the "settled_at" field.
|
||||
SettledAt *time.Time `json:"settled_at,omitempty"`
|
||||
selectValues sql.SelectValues
|
||||
}
|
||||
|
||||
// scanValues returns the types for scanning values from sql.Rows.
|
||||
func (*BatchImageJob) scanValues(columns []string) ([]any, error) {
|
||||
values := make([]any, len(columns))
|
||||
for i := range columns {
|
||||
switch columns[i] {
|
||||
case batchimagejob.FieldEstimatedCost, batchimagejob.FieldHoldAmount, batchimagejob.FieldActualCost:
|
||||
values[i] = new(sql.NullFloat64)
|
||||
case batchimagejob.FieldID, batchimagejob.FieldUserID, batchimagejob.FieldAPIKeyID, batchimagejob.FieldAccountID, batchimagejob.FieldItemCount, batchimagejob.FieldSuccessCount, batchimagejob.FieldFailCount, batchimagejob.FieldCancelledCount, batchimagejob.FieldRetryCount, batchimagejob.FieldVersion:
|
||||
values[i] = new(sql.NullInt64)
|
||||
case batchimagejob.FieldBatchID, batchimagejob.FieldProvider, batchimagejob.FieldModel, batchimagejob.FieldTaskName, batchimagejob.FieldStatus, batchimagejob.FieldProviderJobName, batchimagejob.FieldProviderInputRef, batchimagejob.FieldProviderOutputRef, batchimagejob.FieldGcsInputURI, batchimagejob.FieldGcsOutputURI, batchimagejob.FieldCurrency, batchimagejob.FieldHoldID, batchimagejob.FieldIdempotencyKey, batchimagejob.FieldRequestHash, batchimagejob.FieldManifestHash, batchimagejob.FieldLastErrorCode, batchimagejob.FieldLastErrorMessage:
|
||||
values[i] = new(sql.NullString)
|
||||
case batchimagejob.FieldOutputExpiresAt, batchimagejob.FieldInputDeletedAt, batchimagejob.FieldOutputDeletedAt, batchimagejob.FieldDownloadedAt, batchimagejob.FieldUserDeletedAt, batchimagejob.FieldCreatedAt, batchimagejob.FieldUpdatedAt, batchimagejob.FieldSubmittedAt, batchimagejob.FieldStartedAt, batchimagejob.FieldFinishedAt, batchimagejob.FieldSettledAt:
|
||||
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 BatchImageJob fields.
|
||||
func (_m *BatchImageJob) 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 batchimagejob.FieldID:
|
||||
value, ok := values[i].(*sql.NullInt64)
|
||||
if !ok {
|
||||
return fmt.Errorf("unexpected type %T for field id", value)
|
||||
}
|
||||
_m.ID = int64(value.Int64)
|
||||
case batchimagejob.FieldBatchID:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field batch_id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.BatchID = value.String
|
||||
}
|
||||
case batchimagejob.FieldUserID:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field user_id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.UserID = value.Int64
|
||||
}
|
||||
case batchimagejob.FieldAPIKeyID:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field api_key_id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.APIKeyID = new(int64)
|
||||
*_m.APIKeyID = value.Int64
|
||||
}
|
||||
case batchimagejob.FieldAccountID:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field account_id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.AccountID = new(int64)
|
||||
*_m.AccountID = value.Int64
|
||||
}
|
||||
case batchimagejob.FieldProvider:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field provider", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Provider = value.String
|
||||
}
|
||||
case batchimagejob.FieldModel:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field model", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Model = value.String
|
||||
}
|
||||
case batchimagejob.FieldTaskName:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field task_name", values[i])
|
||||
} else if value.Valid {
|
||||
_m.TaskName = value.String
|
||||
}
|
||||
case batchimagejob.FieldStatus:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field status", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Status = value.String
|
||||
}
|
||||
case batchimagejob.FieldProviderJobName:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field provider_job_name", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ProviderJobName = new(string)
|
||||
*_m.ProviderJobName = value.String
|
||||
}
|
||||
case batchimagejob.FieldProviderInputRef:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field provider_input_ref", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ProviderInputRef = new(string)
|
||||
*_m.ProviderInputRef = value.String
|
||||
}
|
||||
case batchimagejob.FieldProviderOutputRef:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field provider_output_ref", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ProviderOutputRef = new(string)
|
||||
*_m.ProviderOutputRef = value.String
|
||||
}
|
||||
case batchimagejob.FieldGcsInputURI:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field gcs_input_uri", values[i])
|
||||
} else if value.Valid {
|
||||
_m.GcsInputURI = new(string)
|
||||
*_m.GcsInputURI = value.String
|
||||
}
|
||||
case batchimagejob.FieldGcsOutputURI:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field gcs_output_uri", values[i])
|
||||
} else if value.Valid {
|
||||
_m.GcsOutputURI = new(string)
|
||||
*_m.GcsOutputURI = value.String
|
||||
}
|
||||
case batchimagejob.FieldItemCount:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field item_count", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ItemCount = int(value.Int64)
|
||||
}
|
||||
case batchimagejob.FieldSuccessCount:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field success_count", values[i])
|
||||
} else if value.Valid {
|
||||
_m.SuccessCount = int(value.Int64)
|
||||
}
|
||||
case batchimagejob.FieldFailCount:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field fail_count", values[i])
|
||||
} else if value.Valid {
|
||||
_m.FailCount = int(value.Int64)
|
||||
}
|
||||
case batchimagejob.FieldCancelledCount:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field cancelled_count", values[i])
|
||||
} else if value.Valid {
|
||||
_m.CancelledCount = int(value.Int64)
|
||||
}
|
||||
case batchimagejob.FieldEstimatedCost:
|
||||
if value, ok := values[i].(*sql.NullFloat64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field estimated_cost", values[i])
|
||||
} else if value.Valid {
|
||||
_m.EstimatedCost = value.Float64
|
||||
}
|
||||
case batchimagejob.FieldHoldAmount:
|
||||
if value, ok := values[i].(*sql.NullFloat64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field hold_amount", values[i])
|
||||
} else if value.Valid {
|
||||
_m.HoldAmount = new(float64)
|
||||
*_m.HoldAmount = value.Float64
|
||||
}
|
||||
case batchimagejob.FieldActualCost:
|
||||
if value, ok := values[i].(*sql.NullFloat64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field actual_cost", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ActualCost = new(float64)
|
||||
*_m.ActualCost = value.Float64
|
||||
}
|
||||
case batchimagejob.FieldCurrency:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field currency", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Currency = value.String
|
||||
}
|
||||
case batchimagejob.FieldHoldID:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field hold_id", values[i])
|
||||
} else if value.Valid {
|
||||
_m.HoldID = new(string)
|
||||
*_m.HoldID = value.String
|
||||
}
|
||||
case batchimagejob.FieldIdempotencyKey:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field idempotency_key", values[i])
|
||||
} else if value.Valid {
|
||||
_m.IdempotencyKey = new(string)
|
||||
*_m.IdempotencyKey = value.String
|
||||
}
|
||||
case batchimagejob.FieldRequestHash:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field request_hash", values[i])
|
||||
} else if value.Valid {
|
||||
_m.RequestHash = new(string)
|
||||
*_m.RequestHash = value.String
|
||||
}
|
||||
case batchimagejob.FieldManifestHash:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field manifest_hash", values[i])
|
||||
} else if value.Valid {
|
||||
_m.ManifestHash = new(string)
|
||||
*_m.ManifestHash = value.String
|
||||
}
|
||||
case batchimagejob.FieldRetryCount:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field retry_count", values[i])
|
||||
} else if value.Valid {
|
||||
_m.RetryCount = int(value.Int64)
|
||||
}
|
||||
case batchimagejob.FieldVersion:
|
||||
if value, ok := values[i].(*sql.NullInt64); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field version", values[i])
|
||||
} else if value.Valid {
|
||||
_m.Version = int(value.Int64)
|
||||
}
|
||||
case batchimagejob.FieldOutputExpiresAt:
|
||||
if value, ok := values[i].(*sql.NullTime); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field output_expires_at", values[i])
|
||||
} else if value.Valid {
|
||||
_m.OutputExpiresAt = new(time.Time)
|
||||
*_m.OutputExpiresAt = value.Time
|
||||
}
|
||||
case batchimagejob.FieldInputDeletedAt:
|
||||
if value, ok := values[i].(*sql.NullTime); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field input_deleted_at", values[i])
|
||||
} else if value.Valid {
|
||||
_m.InputDeletedAt = new(time.Time)
|
||||
*_m.InputDeletedAt = value.Time
|
||||
}
|
||||
case batchimagejob.FieldOutputDeletedAt:
|
||||
if value, ok := values[i].(*sql.NullTime); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field output_deleted_at", values[i])
|
||||
} else if value.Valid {
|
||||
_m.OutputDeletedAt = new(time.Time)
|
||||
*_m.OutputDeletedAt = value.Time
|
||||
}
|
||||
case batchimagejob.FieldDownloadedAt:
|
||||
if value, ok := values[i].(*sql.NullTime); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field downloaded_at", values[i])
|
||||
} else if value.Valid {
|
||||
_m.DownloadedAt = new(time.Time)
|
||||
*_m.DownloadedAt = value.Time
|
||||
}
|
||||
case batchimagejob.FieldUserDeletedAt:
|
||||
if value, ok := values[i].(*sql.NullTime); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field user_deleted_at", values[i])
|
||||
} else if value.Valid {
|
||||
_m.UserDeletedAt = new(time.Time)
|
||||
*_m.UserDeletedAt = value.Time
|
||||
}
|
||||
case batchimagejob.FieldLastErrorCode:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field last_error_code", values[i])
|
||||
} else if value.Valid {
|
||||
_m.LastErrorCode = new(string)
|
||||
*_m.LastErrorCode = value.String
|
||||
}
|
||||
case batchimagejob.FieldLastErrorMessage:
|
||||
if value, ok := values[i].(*sql.NullString); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field last_error_message", values[i])
|
||||
} else if value.Valid {
|
||||
_m.LastErrorMessage = new(string)
|
||||
*_m.LastErrorMessage = value.String
|
||||
}
|
||||
case batchimagejob.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 batchimagejob.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
|
||||
}
|
||||
case batchimagejob.FieldSubmittedAt:
|
||||
if value, ok := values[i].(*sql.NullTime); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field submitted_at", values[i])
|
||||
} else if value.Valid {
|
||||
_m.SubmittedAt = new(time.Time)
|
||||
*_m.SubmittedAt = value.Time
|
||||
}
|
||||
case batchimagejob.FieldStartedAt:
|
||||
if value, ok := values[i].(*sql.NullTime); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field started_at", values[i])
|
||||
} else if value.Valid {
|
||||
_m.StartedAt = new(time.Time)
|
||||
*_m.StartedAt = value.Time
|
||||
}
|
||||
case batchimagejob.FieldFinishedAt:
|
||||
if value, ok := values[i].(*sql.NullTime); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field finished_at", values[i])
|
||||
} else if value.Valid {
|
||||
_m.FinishedAt = new(time.Time)
|
||||
*_m.FinishedAt = value.Time
|
||||
}
|
||||
case batchimagejob.FieldSettledAt:
|
||||
if value, ok := values[i].(*sql.NullTime); !ok {
|
||||
return fmt.Errorf("unexpected type %T for field settled_at", values[i])
|
||||
} else if value.Valid {
|
||||
_m.SettledAt = new(time.Time)
|
||||
*_m.SettledAt = 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 BatchImageJob.
|
||||
// This includes values selected through modifiers, order, etc.
|
||||
func (_m *BatchImageJob) Value(name string) (ent.Value, error) {
|
||||
return _m.selectValues.Get(name)
|
||||
}
|
||||
|
||||
// Update returns a builder for updating this BatchImageJob.
|
||||
// Note that you need to call BatchImageJob.Unwrap() before calling this method if this BatchImageJob
|
||||
// was returned from a transaction, and the transaction was committed or rolled back.
|
||||
func (_m *BatchImageJob) Update() *BatchImageJobUpdateOne {
|
||||
return NewBatchImageJobClient(_m.config).UpdateOne(_m)
|
||||
}
|
||||
|
||||
// Unwrap unwraps the BatchImageJob 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 *BatchImageJob) Unwrap() *BatchImageJob {
|
||||
_tx, ok := _m.config.driver.(*txDriver)
|
||||
if !ok {
|
||||
panic("ent: BatchImageJob is not a transactional entity")
|
||||
}
|
||||
_m.config.driver = _tx.drv
|
||||
return _m
|
||||
}
|
||||
|
||||
// String implements the fmt.Stringer.
|
||||
func (_m *BatchImageJob) String() string {
|
||||
var builder strings.Builder
|
||||
builder.WriteString("BatchImageJob(")
|
||||
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
|
||||
builder.WriteString("batch_id=")
|
||||
builder.WriteString(_m.BatchID)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("user_id=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.UserID))
|
||||
builder.WriteString(", ")
|
||||
if v := _m.APIKeyID; v != nil {
|
||||
builder.WriteString("api_key_id=")
|
||||
builder.WriteString(fmt.Sprintf("%v", *v))
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.AccountID; v != nil {
|
||||
builder.WriteString("account_id=")
|
||||
builder.WriteString(fmt.Sprintf("%v", *v))
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("provider=")
|
||||
builder.WriteString(_m.Provider)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("model=")
|
||||
builder.WriteString(_m.Model)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("task_name=")
|
||||
builder.WriteString(_m.TaskName)
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("status=")
|
||||
builder.WriteString(_m.Status)
|
||||
builder.WriteString(", ")
|
||||
if v := _m.ProviderJobName; v != nil {
|
||||
builder.WriteString("provider_job_name=")
|
||||
builder.WriteString(*v)
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.ProviderInputRef; v != nil {
|
||||
builder.WriteString("provider_input_ref=")
|
||||
builder.WriteString(*v)
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.ProviderOutputRef; v != nil {
|
||||
builder.WriteString("provider_output_ref=")
|
||||
builder.WriteString(*v)
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.GcsInputURI; v != nil {
|
||||
builder.WriteString("gcs_input_uri=")
|
||||
builder.WriteString(*v)
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.GcsOutputURI; v != nil {
|
||||
builder.WriteString("gcs_output_uri=")
|
||||
builder.WriteString(*v)
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("item_count=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.ItemCount))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("success_count=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.SuccessCount))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("fail_count=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.FailCount))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("cancelled_count=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.CancelledCount))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("estimated_cost=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.EstimatedCost))
|
||||
builder.WriteString(", ")
|
||||
if v := _m.HoldAmount; v != nil {
|
||||
builder.WriteString("hold_amount=")
|
||||
builder.WriteString(fmt.Sprintf("%v", *v))
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.ActualCost; v != nil {
|
||||
builder.WriteString("actual_cost=")
|
||||
builder.WriteString(fmt.Sprintf("%v", *v))
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("currency=")
|
||||
builder.WriteString(_m.Currency)
|
||||
builder.WriteString(", ")
|
||||
if v := _m.HoldID; v != nil {
|
||||
builder.WriteString("hold_id=")
|
||||
builder.WriteString(*v)
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.IdempotencyKey; v != nil {
|
||||
builder.WriteString("idempotency_key=")
|
||||
builder.WriteString(*v)
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.RequestHash; v != nil {
|
||||
builder.WriteString("request_hash=")
|
||||
builder.WriteString(*v)
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.ManifestHash; v != nil {
|
||||
builder.WriteString("manifest_hash=")
|
||||
builder.WriteString(*v)
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("retry_count=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.RetryCount))
|
||||
builder.WriteString(", ")
|
||||
builder.WriteString("version=")
|
||||
builder.WriteString(fmt.Sprintf("%v", _m.Version))
|
||||
builder.WriteString(", ")
|
||||
if v := _m.OutputExpiresAt; v != nil {
|
||||
builder.WriteString("output_expires_at=")
|
||||
builder.WriteString(v.Format(time.ANSIC))
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.InputDeletedAt; v != nil {
|
||||
builder.WriteString("input_deleted_at=")
|
||||
builder.WriteString(v.Format(time.ANSIC))
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.OutputDeletedAt; v != nil {
|
||||
builder.WriteString("output_deleted_at=")
|
||||
builder.WriteString(v.Format(time.ANSIC))
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.DownloadedAt; v != nil {
|
||||
builder.WriteString("downloaded_at=")
|
||||
builder.WriteString(v.Format(time.ANSIC))
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.UserDeletedAt; v != nil {
|
||||
builder.WriteString("user_deleted_at=")
|
||||
builder.WriteString(v.Format(time.ANSIC))
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.LastErrorCode; v != nil {
|
||||
builder.WriteString("last_error_code=")
|
||||
builder.WriteString(*v)
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.LastErrorMessage; v != nil {
|
||||
builder.WriteString("last_error_message=")
|
||||
builder.WriteString(*v)
|
||||
}
|
||||
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.WriteString(", ")
|
||||
if v := _m.SubmittedAt; v != nil {
|
||||
builder.WriteString("submitted_at=")
|
||||
builder.WriteString(v.Format(time.ANSIC))
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.StartedAt; v != nil {
|
||||
builder.WriteString("started_at=")
|
||||
builder.WriteString(v.Format(time.ANSIC))
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.FinishedAt; v != nil {
|
||||
builder.WriteString("finished_at=")
|
||||
builder.WriteString(v.Format(time.ANSIC))
|
||||
}
|
||||
builder.WriteString(", ")
|
||||
if v := _m.SettledAt; v != nil {
|
||||
builder.WriteString("settled_at=")
|
||||
builder.WriteString(v.Format(time.ANSIC))
|
||||
}
|
||||
builder.WriteByte(')')
|
||||
return builder.String()
|
||||
}
|
||||
|
||||
// BatchImageJobs is a parsable slice of BatchImageJob.
|
||||
type BatchImageJobs []*BatchImageJob
|
||||
@@ -1,420 +0,0 @@
|
||||
// Code generated by ent, DO NOT EDIT.
|
||||
|
||||
package batchimagejob
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"entgo.io/ent/dialect/sql"
|
||||
)
|
||||
|
||||
const (
|
||||
// Label holds the string label denoting the batchimagejob type in the database.
|
||||
Label = "batch_image_job"
|
||||
// FieldID holds the string denoting the id field in the database.
|
||||
FieldID = "id"
|
||||
// FieldBatchID holds the string denoting the batch_id field in the database.
|
||||
FieldBatchID = "batch_id"
|
||||
// FieldUserID holds the string denoting the user_id field in the database.
|
||||
FieldUserID = "user_id"
|
||||
// FieldAPIKeyID holds the string denoting the api_key_id field in the database.
|
||||
FieldAPIKeyID = "api_key_id"
|
||||
// FieldAccountID holds the string denoting the account_id field in the database.
|
||||
FieldAccountID = "account_id"
|
||||
// FieldProvider holds the string denoting the provider field in the database.
|
||||
FieldProvider = "provider"
|
||||
// FieldModel holds the string denoting the model field in the database.
|
||||
FieldModel = "model"
|
||||
// FieldTaskName holds the string denoting the task_name field in the database.
|
||||
FieldTaskName = "task_name"
|
||||
// FieldStatus holds the string denoting the status field in the database.
|
||||
FieldStatus = "status"
|
||||
// FieldProviderJobName holds the string denoting the provider_job_name field in the database.
|
||||
FieldProviderJobName = "provider_job_name"
|
||||
// FieldProviderInputRef holds the string denoting the provider_input_ref field in the database.
|
||||
FieldProviderInputRef = "provider_input_ref"
|
||||
// FieldProviderOutputRef holds the string denoting the provider_output_ref field in the database.
|
||||
FieldProviderOutputRef = "provider_output_ref"
|
||||
// FieldGcsInputURI holds the string denoting the gcs_input_uri field in the database.
|
||||
FieldGcsInputURI = "gcs_input_uri"
|
||||
// FieldGcsOutputURI holds the string denoting the gcs_output_uri field in the database.
|
||||
FieldGcsOutputURI = "gcs_output_uri"
|
||||
// FieldItemCount holds the string denoting the item_count field in the database.
|
||||
FieldItemCount = "item_count"
|
||||
// FieldSuccessCount holds the string denoting the success_count field in the database.
|
||||
FieldSuccessCount = "success_count"
|
||||
// FieldFailCount holds the string denoting the fail_count field in the database.
|
||||
FieldFailCount = "fail_count"
|
||||
// FieldCancelledCount holds the string denoting the cancelled_count field in the database.
|
||||
FieldCancelledCount = "cancelled_count"
|
||||
// FieldEstimatedCost holds the string denoting the estimated_cost field in the database.
|
||||
FieldEstimatedCost = "estimated_cost"
|
||||
// FieldHoldAmount holds the string denoting the hold_amount field in the database.
|
||||
FieldHoldAmount = "hold_amount"
|
||||
// FieldActualCost holds the string denoting the actual_cost field in the database.
|
||||
FieldActualCost = "actual_cost"
|
||||
// FieldCurrency holds the string denoting the currency field in the database.
|
||||
FieldCurrency = "currency"
|
||||
// FieldHoldID holds the string denoting the hold_id field in the database.
|
||||
FieldHoldID = "hold_id"
|
||||
// FieldIdempotencyKey holds the string denoting the idempotency_key field in the database.
|
||||
FieldIdempotencyKey = "idempotency_key"
|
||||
// FieldRequestHash holds the string denoting the request_hash field in the database.
|
||||
FieldRequestHash = "request_hash"
|
||||
// FieldManifestHash holds the string denoting the manifest_hash field in the database.
|
||||
FieldManifestHash = "manifest_hash"
|
||||
// FieldRetryCount holds the string denoting the retry_count field in the database.
|
||||
FieldRetryCount = "retry_count"
|
||||
// FieldVersion holds the string denoting the version field in the database.
|
||||
FieldVersion = "version"
|
||||
// FieldOutputExpiresAt holds the string denoting the output_expires_at field in the database.
|
||||
FieldOutputExpiresAt = "output_expires_at"
|
||||
// FieldInputDeletedAt holds the string denoting the input_deleted_at field in the database.
|
||||
FieldInputDeletedAt = "input_deleted_at"
|
||||
// FieldOutputDeletedAt holds the string denoting the output_deleted_at field in the database.
|
||||
FieldOutputDeletedAt = "output_deleted_at"
|
||||
// FieldDownloadedAt holds the string denoting the downloaded_at field in the database.
|
||||
FieldDownloadedAt = "downloaded_at"
|
||||
// FieldUserDeletedAt holds the string denoting the user_deleted_at field in the database.
|
||||
FieldUserDeletedAt = "user_deleted_at"
|
||||
// FieldLastErrorCode holds the string denoting the last_error_code field in the database.
|
||||
FieldLastErrorCode = "last_error_code"
|
||||
// FieldLastErrorMessage holds the string denoting the last_error_message field in the database.
|
||||
FieldLastErrorMessage = "last_error_message"
|
||||
// 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"
|
||||
// FieldSubmittedAt holds the string denoting the submitted_at field in the database.
|
||||
FieldSubmittedAt = "submitted_at"
|
||||
// FieldStartedAt holds the string denoting the started_at field in the database.
|
||||
FieldStartedAt = "started_at"
|
||||
// FieldFinishedAt holds the string denoting the finished_at field in the database.
|
||||
FieldFinishedAt = "finished_at"
|
||||
// FieldSettledAt holds the string denoting the settled_at field in the database.
|
||||
FieldSettledAt = "settled_at"
|
||||
// Table holds the table name of the batchimagejob in the database.
|
||||
Table = "batch_image_jobs"
|
||||
)
|
||||
|
||||
// Columns holds all SQL columns for batchimagejob fields.
|
||||
var Columns = []string{
|
||||
FieldID,
|
||||
FieldBatchID,
|
||||
FieldUserID,
|
||||
FieldAPIKeyID,
|
||||
FieldAccountID,
|
||||
FieldProvider,
|
||||
FieldModel,
|
||||
FieldTaskName,
|
||||
FieldStatus,
|
||||
FieldProviderJobName,
|
||||
FieldProviderInputRef,
|
||||
FieldProviderOutputRef,
|
||||
FieldGcsInputURI,
|
||||
FieldGcsOutputURI,
|
||||
FieldItemCount,
|
||||
FieldSuccessCount,
|
||||
FieldFailCount,
|
||||
FieldCancelledCount,
|
||||
FieldEstimatedCost,
|
||||
FieldHoldAmount,
|
||||
FieldActualCost,
|
||||
FieldCurrency,
|
||||
FieldHoldID,
|
||||
FieldIdempotencyKey,
|
||||
FieldRequestHash,
|
||||
FieldManifestHash,
|
||||
FieldRetryCount,
|
||||
FieldVersion,
|
||||
FieldOutputExpiresAt,
|
||||
FieldInputDeletedAt,
|
||||
FieldOutputDeletedAt,
|
||||
FieldDownloadedAt,
|
||||
FieldUserDeletedAt,
|
||||
FieldLastErrorCode,
|
||||
FieldLastErrorMessage,
|
||||
FieldCreatedAt,
|
||||
FieldUpdatedAt,
|
||||
FieldSubmittedAt,
|
||||
FieldStartedAt,
|
||||
FieldFinishedAt,
|
||||
FieldSettledAt,
|
||||
}
|
||||
|
||||
// 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 (
|
||||
// BatchIDValidator is a validator for the "batch_id" field. It is called by the builders before save.
|
||||
BatchIDValidator func(string) error
|
||||
// ProviderValidator is a validator for the "provider" field. It is called by the builders before save.
|
||||
ProviderValidator func(string) error
|
||||
// ModelValidator is a validator for the "model" field. It is called by the builders before save.
|
||||
ModelValidator func(string) error
|
||||
// DefaultTaskName holds the default value on creation for the "task_name" field.
|
||||
DefaultTaskName string
|
||||
// TaskNameValidator is a validator for the "task_name" field. It is called by the builders before save.
|
||||
TaskNameValidator func(string) error
|
||||
// DefaultStatus holds the default value on creation for the "status" field.
|
||||
DefaultStatus string
|
||||
// StatusValidator is a validator for the "status" field. It is called by the builders before save.
|
||||
StatusValidator func(string) error
|
||||
// ProviderJobNameValidator is a validator for the "provider_job_name" field. It is called by the builders before save.
|
||||
ProviderJobNameValidator func(string) error
|
||||
// ProviderInputRefValidator is a validator for the "provider_input_ref" field. It is called by the builders before save.
|
||||
ProviderInputRefValidator func(string) error
|
||||
// ProviderOutputRefValidator is a validator for the "provider_output_ref" field. It is called by the builders before save.
|
||||
ProviderOutputRefValidator func(string) error
|
||||
// GcsInputURIValidator is a validator for the "gcs_input_uri" field. It is called by the builders before save.
|
||||
GcsInputURIValidator func(string) error
|
||||
// GcsOutputURIValidator is a validator for the "gcs_output_uri" field. It is called by the builders before save.
|
||||
GcsOutputURIValidator func(string) error
|
||||
// DefaultSuccessCount holds the default value on creation for the "success_count" field.
|
||||
DefaultSuccessCount int
|
||||
// DefaultFailCount holds the default value on creation for the "fail_count" field.
|
||||
DefaultFailCount int
|
||||
// DefaultCancelledCount holds the default value on creation for the "cancelled_count" field.
|
||||
DefaultCancelledCount int
|
||||
// DefaultEstimatedCost holds the default value on creation for the "estimated_cost" field.
|
||||
DefaultEstimatedCost float64
|
||||
// DefaultCurrency holds the default value on creation for the "currency" field.
|
||||
DefaultCurrency string
|
||||
// CurrencyValidator is a validator for the "currency" field. It is called by the builders before save.
|
||||
CurrencyValidator func(string) error
|
||||
// HoldIDValidator is a validator for the "hold_id" field. It is called by the builders before save.
|
||||
HoldIDValidator func(string) error
|
||||
// IdempotencyKeyValidator is a validator for the "idempotency_key" field. It is called by the builders before save.
|
||||
IdempotencyKeyValidator func(string) error
|
||||
// RequestHashValidator is a validator for the "request_hash" field. It is called by the builders before save.
|
||||
RequestHashValidator func(string) error
|
||||
// ManifestHashValidator is a validator for the "manifest_hash" field. It is called by the builders before save.
|
||||
ManifestHashValidator func(string) error
|
||||
// DefaultRetryCount holds the default value on creation for the "retry_count" field.
|
||||
DefaultRetryCount int
|
||||
// DefaultVersion holds the default value on creation for the "version" field.
|
||||
DefaultVersion int
|
||||
// LastErrorCodeValidator is a validator for the "last_error_code" field. It is called by the builders before save.
|
||||
LastErrorCodeValidator func(string) error
|
||||
// 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 BatchImageJob 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()
|
||||
}
|
||||
|
||||
// ByBatchID orders the results by the batch_id field.
|
||||
func ByBatchID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldBatchID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByUserID orders the results by the user_id field.
|
||||
func ByUserID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldUserID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByAPIKeyID orders the results by the api_key_id field.
|
||||
func ByAPIKeyID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldAPIKeyID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByAccountID orders the results by the account_id field.
|
||||
func ByAccountID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldAccountID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByProvider orders the results by the provider field.
|
||||
func ByProvider(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldProvider, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByModel orders the results by the model field.
|
||||
func ByModel(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldModel, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByTaskName orders the results by the task_name field.
|
||||
func ByTaskName(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldTaskName, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByStatus orders the results by the status field.
|
||||
func ByStatus(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldStatus, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByProviderJobName orders the results by the provider_job_name field.
|
||||
func ByProviderJobName(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldProviderJobName, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByProviderInputRef orders the results by the provider_input_ref field.
|
||||
func ByProviderInputRef(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldProviderInputRef, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByProviderOutputRef orders the results by the provider_output_ref field.
|
||||
func ByProviderOutputRef(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldProviderOutputRef, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByGcsInputURI orders the results by the gcs_input_uri field.
|
||||
func ByGcsInputURI(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldGcsInputURI, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByGcsOutputURI orders the results by the gcs_output_uri field.
|
||||
func ByGcsOutputURI(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldGcsOutputURI, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByItemCount orders the results by the item_count field.
|
||||
func ByItemCount(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldItemCount, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// BySuccessCount orders the results by the success_count field.
|
||||
func BySuccessCount(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldSuccessCount, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByFailCount orders the results by the fail_count field.
|
||||
func ByFailCount(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldFailCount, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByCancelledCount orders the results by the cancelled_count field.
|
||||
func ByCancelledCount(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldCancelledCount, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByEstimatedCost orders the results by the estimated_cost field.
|
||||
func ByEstimatedCost(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldEstimatedCost, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByHoldAmount orders the results by the hold_amount field.
|
||||
func ByHoldAmount(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldHoldAmount, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByActualCost orders the results by the actual_cost field.
|
||||
func ByActualCost(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldActualCost, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByCurrency orders the results by the currency field.
|
||||
func ByCurrency(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldCurrency, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByHoldID orders the results by the hold_id field.
|
||||
func ByHoldID(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldHoldID, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByIdempotencyKey orders the results by the idempotency_key field.
|
||||
func ByIdempotencyKey(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldIdempotencyKey, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByRequestHash orders the results by the request_hash field.
|
||||
func ByRequestHash(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldRequestHash, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByManifestHash orders the results by the manifest_hash field.
|
||||
func ByManifestHash(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldManifestHash, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByRetryCount orders the results by the retry_count field.
|
||||
func ByRetryCount(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldRetryCount, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByVersion orders the results by the version field.
|
||||
func ByVersion(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldVersion, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByOutputExpiresAt orders the results by the output_expires_at field.
|
||||
func ByOutputExpiresAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldOutputExpiresAt, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByInputDeletedAt orders the results by the input_deleted_at field.
|
||||
func ByInputDeletedAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldInputDeletedAt, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByOutputDeletedAt orders the results by the output_deleted_at field.
|
||||
func ByOutputDeletedAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldOutputDeletedAt, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByDownloadedAt orders the results by the downloaded_at field.
|
||||
func ByDownloadedAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldDownloadedAt, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByUserDeletedAt orders the results by the user_deleted_at field.
|
||||
func ByUserDeletedAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldUserDeletedAt, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByLastErrorCode orders the results by the last_error_code field.
|
||||
func ByLastErrorCode(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldLastErrorCode, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByLastErrorMessage orders the results by the last_error_message field.
|
||||
func ByLastErrorMessage(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldLastErrorMessage, 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()
|
||||
}
|
||||
|
||||
// BySubmittedAt orders the results by the submitted_at field.
|
||||
func BySubmittedAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldSubmittedAt, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByStartedAt orders the results by the started_at field.
|
||||
func ByStartedAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldStartedAt, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// ByFinishedAt orders the results by the finished_at field.
|
||||
func ByFinishedAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldFinishedAt, opts...).ToFunc()
|
||||
}
|
||||
|
||||
// BySettledAt orders the results by the settled_at field.
|
||||
func BySettledAt(opts ...sql.OrderTermOption) OrderOption {
|
||||
return sql.OrderByField(FieldSettledAt, opts...).ToFunc()
|
||||
}
|
||||